diff --git "a/5425.jsonl" "b/5425.jsonl" new file mode 100644--- /dev/null +++ "b/5425.jsonl" @@ -0,0 +1,620 @@ +{"seq_id":"455127954","text":"import pytz\nfrom django.utils.translation import ugettext as _\nfrom corehq.apps.reports.filters.base import BaseSingleOptionFilter\nfrom custom.fri.models import PROFILE_A, PROFILE_B, PROFILE_C, PROFILE_D, PROFILE_E, PROFILE_F, PROFILE_G, PROFILE_H, PROFILE_DESC\nfrom custom.fri.api import get_interactive_participants\nfrom datetime import datetime, date, timedelta\nfrom dimagi.utils.parsing import json_format_date\n\n\nclass InteractiveParticipantFilter(BaseSingleOptionFilter):\n slug = \"participant\"\n label = _(\"Participant\")\n\n @property\n def options(self):\n cases = get_interactive_participants(self.domain)\n return [(case.get_id, case.name) for case in cases]\n\n\nclass RiskProfileFilter(BaseSingleOptionFilter):\n slug = \"risk_profile\"\n label = _(\"Risk Profile\")\n default_text = _(\"All\")\n\n @property\n def options(self):\n return [\n (PROFILE_A, PROFILE_DESC[PROFILE_A]),\n (PROFILE_B, PROFILE_DESC[PROFILE_B]),\n (PROFILE_C, PROFILE_DESC[PROFILE_C]),\n (PROFILE_D, PROFILE_DESC[PROFILE_D]),\n (PROFILE_E, PROFILE_DESC[PROFILE_E]),\n (PROFILE_F, PROFILE_DESC[PROFILE_F]),\n (PROFILE_G, PROFILE_DESC[PROFILE_G]),\n (PROFILE_H, PROFILE_DESC[PROFILE_H]),\n ]\n\n\nclass SurveyDateSelector(BaseSingleOptionFilter):\n \"\"\"\n Single option filter for selecting the dates on which surveys were\n sent out.\n \"\"\"\n slug = \"survey_report_date\"\n label = _(\"Show participants who where sent a survey on\")\n default_text = _(\"Choose...\")\n\n @classmethod\n def get_value(cls, *args, **kwargs):\n default = json_format_date(cls.get_date_choices()[-1])\n return super(SurveyDateSelector, cls).get_value(*args, **kwargs) or default\n\n @classmethod\n def get_date_choices(cls):\n next_date = date(2014, 3, 18)\n last_date = pytz.utc.localize(datetime.utcnow())\n last_date = last_date.astimezone(pytz.timezone(\"US/Pacific\"))\n last_date = last_date.date()\n dates = []\n while next_date <= last_date:\n dates.append(next_date)\n next_date += timedelta(days=7)\n return dates\n\n def __init__(self, *args, **kwargs):\n super(SurveyDateSelector, self).__init__(*args, **kwargs)\n self._date_choices = SurveyDateSelector.get_date_choices()\n\n @property\n def options(self):\n result = []\n for date in sorted(self._date_choices, reverse=True):\n result.append((json_format_date(date), date.strftime(\"%m/%d/%y\")))\n return result\n\n","sub_path":"custom/fri/reports/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"342357318","text":"\ndef cursorALista(pCursor, pClase):\n filas = pCursor.fetchall()\n descripcion = pCursor.description\n lista = list()\n\n for fila in filas:\n instancia = pClase()\n for indice in range(0,len(descripcion)): \n setattr(instancia, descripcion[indice].name, fila[indice])\n\n lista.append(instancia)\n\n return lista\n","sub_path":"python/ejemplos/acceso_postgres2/db_util.py","file_name":"db_util.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"188938118","text":"import numpy as np\nimport itertools as it\n\n\nclass Permutation:\n \"\"\"\n класс будет выдавать все возможные комбинации последовательностей чисел,\n для которых сумма не будет превышать заданного числа\n \"\"\"\n\n def __init__(self,size, Sum):\n self.sum_condition = Sum\n parameter = list(range(Sum+1))\n self.lst = list(it.product(parameter, repeat=size))\n\n def getNext(self):\n while len(self.lst) > 0:\n last = np.array(self.lst.pop())\n if last.sum() <= self.sum_condition:\n return last\n return None\n\n def getAll(self):\n ret = []\n while True:\n arr = self.getNext()\n ret.append(arr);\n if not arr.any():\n break\n return ret\n\n @staticmethod\n def permute(prmts_ln):\n \"\"\"\n permute возвращает все возможные комбинации каждого элемента c каждым эелементом из всех групп L\n prmts_ln - содержит массивы возможных распределений для каждого типа l\n\n \"\"\"\n\n ret = []\n x = [0] * len(prmts_ln)\n\n l = 0\n nl_indexes = np.ones(len(prmts_ln), dtype=np.int)*-1\n groups_cnt = len(prmts_ln)\n while True:\n if l == groups_cnt - 1:\n for nl_indexes[l] in range(len(prmts_ln[l])):\n x[l] = prmts_ln[l][nl_indexes[l]]\n ret.append(np.array(x))\n if nl_indexes[0] == 70:\n l=l\n l -= 1\n else:\n if nl_indexes[l] < len(prmts_ln[l])-1:\n nl_indexes[l] += 1\n x[l] = prmts_ln[l][nl_indexes[l]]\n l += 1\n else:\n nl_indexes[l] = -1\n l -= 1\n\n # условие выхода\n if nl_indexes[0] == -1:\n break\n return ret\n","sub_path":"app/solver/brute_force/permutations.py","file_name":"permutations.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"433861831","text":"#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 2 (SVM) mini-project.\n\n Use a SVM to identify emails from the Enron corpus by their authors: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nfrom time import time\nfrom email_preprocess import preprocess\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.svm import SVC\nimport collections\n\n\n# features_train and features_test are the features for the training and testing datasets, respectively\n# labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n# Reduce the size of the training/label set to 1%\n# features_train = features_train[:int(len(features_train) / 100)]\n# labels_train = labels_train[:int(len(labels_train) / 100)]\n\n# set the kernel type\nk_type1 = 'linear'\nk_type2 = 'rbf'\n\n# c_param = [1.0, 10.0, 100.0, 1000.0, 10000.0]\nc_param = [10000.0]\n\npred_element = [10, 26, 50]\n\nfor c in c_param:\n print(f'Testing penalty parameter C = {c}')\n clf = SVC(C=c, kernel=k_type2)\n t0 = time()\n\n # Train the dataset\n clf.fit(features_train, labels_train)\n print(\"Training time:\", round(time()-t0, 3), \"s\")\n\n t1 = time()\n pred = clf.predict(features_test)\n\n print(\"Testing time:\", round(time()-t1, 3), \"s\")\n for elem in pred_element:\n print(f'Element {elem} Prediction: {pred[elem]}')\n\n acc = accuracy_score(pred, labels_test)\n\n\n def submitAccuracy():\n return acc\n\n author_count = collections.Counter(pred)\n print(f'Number of emails predicted to be written by Sara(0) & Chris(1): {author_count}')\n\n\nif __name__ == \"__main__\":\n\n print(f'Accuracy: {submitAccuracy()}\\n')\n\n\n\n\n","sub_path":"svm/svm_author_id.py","file_name":"svm_author_id.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"401539936","text":"# -*- coding: UTF-8 -*-\nimport matplotlib.pyplot as plt\n# plt.switch_backend(u'Qt5Agg')\n# print plt.get_backend()\n# 函数式编程\ndef fun():\n\t# 1D data\n\tx = [1,2,3,4,5]\n\ty = [2.3,3.4,1.2,6.6,7.0]\n\n\tplt.figure(figsize=(12,6))\n\n\tplt.subplot(231)\n\tplt.plot(x,y)\n\tplt.title(\"plot\")\n\n\tplt.subplot(232)\n\tplt.scatter(x, y)\n\tplt.title(\"scatter\")\n\n\tplt.subplot(233)\n\tplt.pie(y)\n\tplt.title(\"pie\")\n\n\tplt.subplot(234)\n\tplt.bar(x, y)\n\tplt.title(\"bar\")\n\n\t# 2D data\n\timport numpy as np\n\tdelta = 0.025\n\tx = y = np.arange(-3.0, 3.0, delta)\n\tX, Y = np.meshgrid(x, y)\n\tZ = Y**2 + X**2\n\n\tplt.subplot(235)\n\tplt.contour(X,Y,Z)\n\tplt.colorbar()\n\tplt.title(\"contour\")\n\n\t# read image\n\timport matplotlib.image as mpimg\n\timg=mpimg.imread('D:\\\\workspace\\\\Sublime_python\\\\basicpython\\\\marvin.jpg')\n\n\tplt.subplot(236)\n\tplt.imshow(img)\n\tplt.title(\"imshow\")\n\n\tplt.savefig(\"matplot_sample.jpg\")\n\n\tplt.show()\n\n\n# object-oriented plot\n\n\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n\nfig = Figure()\ncanvas = FigureCanvas(fig)\nax = fig.add_axes([0.1, 0.1, 0.8, 0.8])\n\nline, = ax.plot([0,1], [0,1])\nax.set_title(\"a straight line (OO)\")\nax.set_xlabel(\"x value\")\nax.set_ylabel(\"y value\")\ncanvas.print_figure('demo.jpg')\n# canvas.draw()\n# plt.savefig('save.png')","sub_path":"scripts/basic_test/OOPlot.py","file_name":"OOPlot.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"473422351","text":"from matplotlib import colors \nimport numpy as np\n\n\ndef label_image_to_RGB(image):\n # we assume that the image is width x heigh x colormaps (one hot)\n dim = image.shape[2]\n\n\n\n newimage = np.zeros((image.shape[0], image.shape[1], 3))\n\n\n \n colorlist = get_spaced_colors(dim)\n \n\n\n for w in range(0,image.shape[0]):\n for h in range(0,image.shape[1]):\n for d in range(0,dim):\n if(image[w,h,d] == 1): \n newimage[w,h,:] = colorlist[d] \n\n return newimage\n\n\n\n\n# stoleeeen from https://www.quora.com/How-do-I-generate-n-visually-distinct-RGB-colours-in-Python\n\ndef get_spaced_colors(n):\n max_value = 16581375 #255**3\n interval = int(max_value / n)\n colors = [hex(I)[2:].zfill(6) for I in range(0, max_value, interval)]\n \n return [(int(i[:2], 16), int(i[2:4], 16), int(i[4:], 16)) for i in colors]\n","sub_path":"label2image.py","file_name":"label2image.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"603488759","text":"import requests\nimport unittest\n\n\n# 扫码下载pdf\nclass TesePrintRecord(unittest.TestCase) :\n # 准备工作\n def setUp(self) :\n self.url110 = 'https://zhihuotech.com/devj/question_composing/get/print_record'\n\n # 扫描下载pdf\n def test_getcode(self) :\n header = {'Accept' : '*/*',\n 'Accept-Encoding' : 'gzip, deflate, br',\n 'Accept-Language' : 'zh-CN,zh;q=0.9',\n 'Authorization' : 'null',\n 'Connection' : 'keep-alive',\n 'Host' : 'zhihuotech.com',\n 'Referer' : 'https://zhihuotech.com/customization/school/downloadpdf/download?unionid=oyu3N0dB39pHO9a3RqpNwVFRtg_g&type=xcx',\n 'Sec-Fetch-Mode' : 'cors',\n 'Sec-Fetch-Site' : 'same-origin',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}\n param = {'union_id' : 'oyu3N0dB39pHO9a3RqpNwVFRtg_g'}\n r = requests.get(self.url110, headers=header, params=param)\n result = r.json()\n\n self.assertEqual(result['code'], 0)\n self.assertTrue('2020011419390796652' in r.text)\n print(r.json())\n\n\nif __name__ == '__main__' :\n unittest.main()\n","sub_path":"test_case/test_print_record.py","file_name":"test_print_record.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"508051015","text":"from opengever.testing import IntegrationTestCase\n\n\nclass TestSubmittedProposal(IntegrationTestCase):\n\n features = ('meeting', 'word-meeting')\n\n def test_sql_index_proposal_title_is_updated(self):\n # an agenda item is needed for this test\n self.login(self.committee_responsible)\n self.meeting.model.schedule_proposal(self.proposal.load_model())\n agenda_item = self.meeting.model.agenda_items[0]\n self.assertEquals(agenda_item.get_title(), agenda_item.proposal.submitted_title)\n\n agenda_item.set_title('New agenda item title')\n\n self.assertEquals('New agenda item title', agenda_item.get_title())\n self.assertEquals('New agenda item title', agenda_item.proposal.submitted_title)\n","sub_path":"opengever/meeting/tests/test_sql_index.py","file_name":"test_sql_index.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"263356815","text":"#!/usr/bin/pythonX\n# -*- coding: UTF-8 -*-\n\nimport requests\nimport time\nimport re\nimport json\nimport logging\nimport os\n\nfrom pathlib import Path\nfrom urllib import parse\n\nfrom xtask import *\n\n_FAKE_APPLY = False\n\nlogger = logging.getLogger(__name__)\n\nclass DianPingGetBaWangCanListTask(XTask):\n __base_url = 'http://m.dianping.com/activity/static/pc'\n\n def __init__(self, cookie, city_id, type, mode, page, callback=None):\n super(DianPingGetBaWangCanListTask, self).__init__(callback)\n self.city_id = city_id\n self.type = type\n self.mode = mode\n self.page = page\n self.cookie = cookie\n\n def __get_parameters(self):\n timestamp = int(time.time() * 1000)\n ret = {}\n ret['callback'] = 'jsonp_' + str(timestamp)\n ret['cityId'] = self.city_id\n ret['type'] = self.type\n ret['mode'] = self.mode\n ret['page'] = self.page\n ret['_'] = str(timestamp)\n return ret\n\n def __get_headers(self):\n headers = {\n 'Host' : 'm.dianping.com',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',\n 'Accept': '*/*',\n 'Refer': 'http://s.dianping.com/event/hangzhou',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',\n 'Connection': 'keep-alive',\n }\n\n if self.cookie:\n headers['Cookie'] = self.cookie\n\n return headers\n\n def __deal_with_response(self, response):\n if not response:\n return\n\n objects = re.match('jsonp_\\d+\\((.*)\\)', response)\n if objects:\n return objects.group(1)\n\n def run(self):\n \n params = parse.urlencode(self.__get_parameters())\n url = self.__base_url + \"/list?\" + params\n\n try:\n logger.info('GET: %s', url)\n html = requests.get(url, headers = self.__get_headers())\n html.encoding = 'utf-8'\n text = html.text\n logger.info('Response: %s', text)\n json_str = self.__deal_with_response(text)\n\n if json_str:\n obj = json.loads(json_str)\n if self._completion_callback:\n self._completion_callback(obj)\n else:\n if self._completion_callback:\n self._completion_callback(None)\n except Exception as e:\n logger.error('Error %s', str(e))\n if self._completion_callback:\n self._completion_callback(None)\n finally:\n return True \n\nclass DianPingBaWangCanApplyTask(XTask):\n __load_apply_item_url = 'http://s.dianping.com/ajax/json/activity/offline/loadApplyItem'\n __save_apply_item_url = 'http://s.dianping.com/ajax/json/activity/offline/saveApplyInfo'\n\n def __init__(self, cookie, offline_activity_id, phone_number, callback=None):\n super(DianPingBaWangCanApplyTask, self).__init__(callback)\n self.offline_activity_id = offline_activity_id\n self.cookie = cookie\n self.phone_number = phone_number\n\n def __get_headers(self):\n headers = {\n 'Host' : 's.dianping.com',\n 'Connection' : 'keep-alive',\n 'Origin' : 'http://s.dianping.com',\n 'X-Request' : 'JSON',\n 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',\n 'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8;',\n 'Accept' : 'application/json, text/javascript',\n 'X-Requested-With' : 'XMLHttpRequest',\n 'Refer' : 'http://s.dianping.com/event/' + str(self.offline_activity_id or \"\"),\n 'Accept-Encoding' : 'gzip, deflate',\n 'Accept-Language' : 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',\n }\n\n if self.cookie:\n headers['Cookie'] = self.cookie\n\n return headers\n\n def __get_save_apply_item_params(self):\n return {\n 'offlineActivityId' : self.offline_activity_id or 0,\n 'phoneNo' : self.phone_number,\n }\n\n def run(self):\n if _FAKE_APPLY:\n return True\n\n logger.info('Begin applying offline activity id: %s', str(self.offline_activity_id))\n\n if not self.offline_activity_id or not self.cookie:\n logger.info('No offline_activity_id or cookie, exit')\n return True\n\n headers = self.__get_headers()\n data = { 'offlineActivityId' : self.offline_activity_id }\n logger.info('POST: %s', self.__load_apply_item_url)\n logger.info('Data: %s', str(data))\n logger.info('Headers: %s', str(headers))\n response = requests.post(self.__load_apply_item_url, data = data, headers = headers)\n response.encoding = 'utf-8'\n html = response.text\n logger.info('Response: %s', html)\n json_obj = json.loads(html)\n if json_obj['code'] != 200:\n logger.info('Error: Status code (%d)', json_obj['code'])\n if self._completion_callback:\n self._completion_callback(self.offline_activity_id, False)\n return True\n\n if '黄金替补' in html:\n logger.info('Don\\'t apply because of not single')\n if self._completion_callback:\n self._completion_callback(self.offline_activity_id, False)\n return True\n\n params = self.__get_save_apply_item_params()\n time.sleep(1)\n logger.info('GET: %s', self.__save_apply_item_url)\n logger.info('Params: %s', str(params))\n logger.info('Headers: %s', str(headers))\n response = requests.get(self.__save_apply_item_url, params = params, headers = headers)\n response.encoding = 'utf-8'\n html = response.text\n logger.info('Response: %s', html)\n json_obj = json.loads(html)\n\n if json_obj['code'] == 500 and '重复报名' in html:\n logger.info('Have already applied for activity: %s', str(self.offline_activity_id))\n if self._completion_callback:\n self._completion_callback(self.offline_activity_id, False)\n elif json_obj['code'] == 200:\n logger.info('Apply for activity %s success!!!', str(self.offline_activity_id))\n if self._completion_callback:\n self._completion_callback(self.offline_activity_id, True)\n else:\n logger.info('Apply for activity %s failed!!!', str(self.offline_activity_id))\n if self._completion_callback:\n self._completion_callback(self.offline_activity_id, False)\n\n return True\n\nclass DianPingBaWangCanTask(XTask):\n\n __region_file_name = 'dian_ping_config/regions.txt'\n __new_region_file_name = 'dian_ping_config/new_regions.txt'\n __new_regions = []\n def __init__(self, cookie, phone_number, city_id, type, mode='', callback=None):\n super(DianPingBaWangCanTask, self).__init__(callback)\n self.cookie = cookie\n self.city_id = city_id\n self.type = type\n self.mode = mode\n self.phone_number = phone_number\n self.__activities = {}\n self.__load_region_config()\n\n # 加载商圈配置\n def __load_region_config(self):\n self.__region_config = {}\n self.__new_regions.clear()\n region_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.__region_file_name)\n with open(region_file_path) as f:\n lines = f.readlines()\n for line in lines:\n region_name, flag = line.split()\n if int(flag) != 0:\n self.__region_config[region_name] = True\n else:\n self.__region_config[region_name] = False\n\n # 如果有新的未收录商圈,写到文件里\n def __update_regions(self):\n if not self.__new_regions:\n return\n\n file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.__new_region_file_name)\n file = Path(file_path)\n region_name_dict = {}\n if file.is_file():\n with open(file_path) as f:\n lines = f.readlines()\n for line in lines:\n region_name_dict[line.strip()] = True\n\n new = []\n for region_name in self.__new_regions:\n if not region_name in region_name_dict:\n new.append(region_name)\n\n if not new:\n return\n\n with open(file_path, 'a+') as f:\n for region_name in new:\n f.write(region_name + '\\n')\n\n\n # 处理返回的申请结果\n def __apply_activity_callback(self, offline_activity_id, result):\n if not result or not offline_activity_id in self.__activities:\n return\n\n activity_title = self.__activities[offline_activity_id]['activity_title']\n if not activity_title:\n return\n region = self.__activities[offline_activity_id]['region']\n self.message = self.message + activity_title + ' ' + region + ' (' + self.__activities[offline_activity_id]['detail_url'] + ') 申请成功\\n'\n\n def __should_apply(self, activity):\n if not activity:\n return False\n region_name = activity['regionName']\n\n if not region_name in self.__region_config:\n self.__new_regions.append(region_name)\n\n if region_name in self.__region_config and self.__region_config[region_name]:\n return True\n return False\n\n # 处理返回的一页activities\n def __get_list_callback(self, response):\n if not response:\n logger.info('No response from DianPingGetBaWangCanListTask')\n return\n\n if response['code'] != 200:\n logger.info('Response status code is %d, error: %s', response['code'], response['errorMsg'])\n return\n\n data = response['data']\n if not data:\n logger.info('No data in response')\n return\n\n activities = data['detail']\n\n # 取出所有的activities\n if activities:\n for activity in activities:\n offline_activity_id = activity['offlineActivityId']\n self.__activities[offline_activity_id] = {\n 'activity_title' : activity['activityTitle'],\n 'detail_url' : activity['detailUrl'],\n 'region' : activity['regionName'],\n }\n # 看是否需要申请\n region_name = activity['regionName']\n if self.__should_apply(activity):\n task = DianPingBaWangCanApplyTask(self.cookie, offline_activity_id, self.phone_number, self.__apply_activity_callback)\n self.task_actor.add(task)\n time.sleep(1)\n else:\n logger.info('No activities in current response')\n\n if data['hasNext']:\n time.sleep(2)\n self.page = self.page + 1\n self.__perform_list_task()\n else:\n logger.info('No more pages')\n\n # 获取一页的activities\n def __perform_list_task(self):\n self.list_task = DianPingGetBaWangCanListTask(self.cookie, self.city_id, self.type, self.mode, self.page, self.__get_list_callback)\n self.task_actor.add(self.list_task)\n\n def run(self):\n self.page = 1\n self.message = ''\n self.__activities.clear()\n self.__perform_list_task()\n\n self.__update_regions()\n if self._completion_callback:\n self._completion_callback(self.message)\n return True\n\nclass DianPingBaWangCanBatchApplyTask(XTask):\n\n def __init__(self, callback=None):\n super(DianPingBaWangCanBatchApplyTask, self).__init__(callback)\n self.__config_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dian_ping_config')\n self.__users_file_path = os.path.join(self.__config_dir_path, 'apply_ba_wang_can_users.cfg')\n\n def run(self):\n with open(self.__users_file_path) as f:\n user_configs = f.readlines()\n for cfg in user_configs:\n if cfg.startswith('#'):\n continue\n username, phone_number, city_id, mode = [x.strip() for x in cfg.split(',')]\n cookie_file_path = os.path.join(self.__config_dir_path, username + '.cookie')\n with open(cookie_file_path) as ff:\n cookie = ff.read()\n task = DianPingBaWangCanTask(cookie.strip(), phone_number, city_id, mode, callback=self._completion_callback)\n task.concurrent = True\n self.task_actor.add(task)\n\n return True\n\nif __name__ == '__main__':\n\n from xlog import XLog\n from xtask import *\n from xnotifier import *\n\n def notifiy(message):\n logging.info(message)\n notifier = SimpleMailNotifier('XCapricornMail@163.com', 'Capricorn2018', 'smtp.163.com', title='提示', message=message)\n notifier.notify()\n\n XLog.config(__file__)\n\n actor = XTaskActor.start_task_actor()\n task = DianPingBaWangCanBatchApplyTask(callback=notifiy)\n task.repeat_count = -1\n task.delay = 24 * 30 * 60\n task.concurrent = True\n actor.add(task)\n actor.join()\n\n\n","sub_path":"dian_ping.py","file_name":"dian_ping.py","file_ext":"py","file_size_in_byte":13405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"97412303","text":"import json\nfrom datetime import datetime\nfrom sys import exc_info\n\nfrom django.shortcuts import render\nfrom django.template import Template, RequestContext\nfrom django.template.response import TemplateResponse\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core import serializers\nfrom django.views.generic import ListView, CreateView, UpdateView, View, DetailView\nfrom django.db.models import Q\nfrom django.template.loader import render_to_string\n\nfrom common.mixins import LoginRequiredMixin\n\nfrom usermgmt.models import Messages, Conversation, GolfUser\n\nclass ConversationsView(LoginRequiredMixin,View):\n\ttemplate_name = 'usermgmt/messages/message_list.html'\n\n\tdef get(self, request):\n\t\tdata = {}\n\t\tconversations = Conversation.objects.filter(participants = request.user).order_by('-modified_on')\n\t\tdata['conversations'] = conversations\n\t\tdata['user'] = request.user\n\t\treturn render(request, self.template_name,data)\n\nconversations = ConversationsView.as_view()\n\nclass NewConversationView(View):\n\ttemplate_name = 'usermgmt/messages/new_conversation.html'\n\t\n\tdef get(self,request, format=None):\n\n\t\tusers = GolfUser.objects.filter(is_private=False).exclude(id = request.user.id)\n\t\tdata = {'users':users}\n\n\t\treturn render(request, self.template_name,data)\n\n\tdef post(self,request, format=None):\n\n\t\tconversation = Conversation()\n\n\t\tconversation.save()\n\n\t\tparticipants = request.POST.getlist('participants')\n\t\tm = request.POST.get('message')\n\n\t\tfor id in participants:\n\t\t\tparticipant = GolfUser.objects.get(id = str(id))\n\t\t\tconversation.participants.add(participant)\n\n\t\tconversation.participants.add(request.user)\n\n\t\tif conversation.participants.all().count() > 2:\n\t\t\tconversation.ctype = 'G'\n\t\t\tconversation.name = 'Group Message'\n\t\t\tconversation.save()\n\t\t\t\n\t\tmessage = Messages()\n\t\tmessage.message = m\n\t\tmessage.created_by = request.user\n\t\tmessage.save()\n\n\t\tconversation.messages.add(message)\n\n\t\treturn HttpResponseRedirect(reverse('ajax_conversations'))\n\nnew_conversation = NewConversationView.as_view()\n\nclass ConversationDetails(View):\n\ttemplate_name = 'usermgmt/messages/conversation_details.html'\n\n\tdef get_object(self, pk):\n\t\ttry:\n\t\t\treturn Conversation.objects.get(pk=pk)\n\t\texcept Conversation.DoesNotExist:\n\t\t\traise Http404\n\n\tdef get(self, request, pk, format=None):\n\t\tconversation = self.get_object(pk)\n\t\tdata= {}\n\t\tdata['user'] = request.user\n\t\tdata['conversation'] = conversation\n\t\treturn render(request, self.template_name,data)\n\n\tdef delete(self, request, pk, format=None):\n\t\tconversation = self.get_object(pk)\n\t\tconversation.delete()\n\t\treturn Response(status=status.HTTP_200_OK)\n\nconversation_details = ConversationDetails.as_view()\n\nclass NewMessageView(View):\n\n\tdef get_object(self, pk):\n\t\ttry:\n\t\t\treturn Conversation.objects.get(pk=pk)\n\t\texcept Conversation.DoesNotExist:\n\t\t\traise Http404\n\n\tdef post(self, request, pk, format=None):\n\t\tdata = {}\n\t\tconversation = self.get_object(pk)\n\n\t\tmessage = request.POST.get('message_body')\n\n\t\tm_obj = Messages(\n\t\t\t\tmessage = message,\n\t\t\t\tcreated_by = request.user\n\t\t\t)\n\t\tm_obj.save()\n\n\t\tconversation.messages.add(m_obj)\n\n\t\ttoday = datetime.today()\n\t\tconversation.modified_on = today\n\t\tconversation.save()\n\t\tsdata = {'message':m_obj}\n\n\t\tdata['html']=render_to_string('usermgmt/messages/include_new_message.html',sdata,context_instance=RequestContext(request))\n\t\tdata['status'] = 1\n\n\t\treturn HttpResponse(json.dumps(data), content_type='application/x-json')\n\nnew_message = NewMessageView.as_view()\n\nclass DeleteConversationView(View):\n\n\tdef get_object(self, pk):\n\t\ttry:\n\t\t\treturn Conversation.objects.get(pk=pk)\n\t\texcept Conversation.DoesNotExist:\n\t\t\traise Http404\n\n\tdef get(self,request, pk, format=None):\n\t\tdata = {}\n\t\tconversation = self.get_object(pk)\n\t\tconversation.delete()\n\n\t\treturn HttpResponseRedirect(reverse('ajax_conversations'))\n\nconversation_delete = DeleteConversationView.as_view()","sub_path":"golfconnectx/usermgmt/messageviews.py","file_name":"messageviews.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"17407145","text":"Import('env')\nImport('libs')\n\nenv['LIBPATH'] = ['#/platform_library', '#/lib/libtommath', '#/lib/libtomcrypt', '#/lib']\nenv['CPPPATH'] = ['#/platform_library']\n\nserver_files = Glob('server_*.cpp')\nenv.Build('Program', 'server', server_files, LIBS_CFG=libs[1])\n\nclient_files = Glob('client_*.cpp')\nenv.Build('Program', 'client', client_files, LIBS='socket_client_DEBUG')\n","sub_path":"products/test/test3/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"249706801","text":"# This module contains a couple of Python functions serving as a link between\n# the R interface of slendr and the underlying tskit tree sequence machinery.\n# It is distributed under the same conditions and license as the rest of the\n# slendr R package codebase.\n\nimport numpy as np\nimport pandas as pd\nimport tskit\n\ndef mult_roots(ts):\n \"\"\"Check how many trees in the tree sequence have multiple roots (i.e. how\n many are not fully coalesced.\n \"\"\"\n return [not tree.has_multiple_roots for tree in ts.trees()]\n\ndef get_pedigree_ids(ts):\n \"\"\"Extract pedigree IDs of all individuals in a SLiM tree sequence.\n \"\"\"\n # float conversion is an unfortunate hack around Python long int -> R int\n # overflow (fix appears to be a work in progress in reticulate, see here:\n # https://github.com/rstudio/reticulate/issues/323)\n return [float(ind.metadata[\"pedigree_id\"]) for ind in ts.individuals()]\n\ndef collect_ibd(ts, coordinates = False, within=None, between=None,\n min_span=None, max_time=None):\n \"\"\"Extract IBD fragments (or the summary of pairwise IBD sharing) from\n a tree sequence.\n \"\"\"\n ibd_segments = ts.ibd_segments(\n within=within,\n between=between,\n store_pairs=True,\n store_segments=coordinates,\n min_span=min_span,\n max_time=max_time\n )\n\n result = []\n for pair, ibd in ibd_segments.items():\n if coordinates:\n for segment in ibd:\n mrca = segment.node\n tmrca = ts.node(mrca).time\n result.append((pair[0], pair[1], segment.right - segment.left,\n mrca, tmrca, segment.left, segment.right))\n # node1 = np.repeat(pair[0], len(ibd))\n # node2 = np.repeat(pair[1], len(ibd))\n # left = np.fromiter((i.left for i in ibd), dtype=int)\n # right = np.fromiter((i.right for i in ibd), dtype=int)\n # pair_result = np.column_stack((left, right, right - left, node1, node2)).astype(int)\n else:\n # pair_result = np.asarray([len(ibd), ibd.total_span, pair[0], pair[1]], dtype=int)\n result.append((pair[0], pair[1], len(ibd), ibd.total_span))\n # result.append(pair_result)\n # result = np.vstack(result)\n\n if coordinates:\n columns = [\"node1\", \"node2\", \"length\", \"mrca\", \"tmrca\", \"left\", \"right\"]\n else:\n columns = [\"node1\", \"node2\", \"count\", \"total\"]\n\n return pd.DataFrame(result, columns=columns)\n","sub_path":"inst/pylib/pylib.py","file_name":"pylib.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"525786239","text":"from toee import *\nfrom utilities import *\nfrom scripts import *\nfrom InventoryRespawn import *\nfrom combat_standard_routines import *\n\n\ndef san_dialog( attachee, triggerer ):\n\tattachee.turn_towards(triggerer)\n\ttriggerer.begin_dialog( attachee, 1 )\n\treturn SKIP_DEFAULT\n\n\ndef san_first_heartbeat( attachee, triggerer ):\n\tif (game.global_flags[921] == 0):\n\t\tgame.timevent_add(respawn, (attachee), 3600000 ) #3600000ms is 1 hour\n\t\tgame.global_flags[921] = 1\n\treturn RUN_DEFAULT\n\n\ndef san_dying( attachee, triggerer ):\n\tif should_modify_CR( attachee ):\n\t\tmodify_CR( attachee, get_av_level() )\n\tfor pc in game.party:\n\t\tpc.condition_add('fallen_paladin')\n\tgame.global_flags[972] = 1\n\treturn RUN_DEFAULT\n\n\ndef san_resurrect( attachee, triggerer ):\n\tgame.global_flags[972] = 0\n\treturn RUN_DEFAULT\n\n\ndef san_heartbeat( attachee, triggerer ):\n\tif (game.global_flags[993] == 0 ):\n\t\tattachee.object_flag_set(OF_OFF)\n\tif (game.global_flags[993] == 1 ):\n\t\tattachee.object_flag_unset(OF_OFF)\n\treturn RUN_DEFAULT\n\n\ndef run_off( attachee, triggerer ):\n\tfor pc in game.party:\n\t\tattachee.ai_shitlist_remove( pc )\n\tattachee.runoff(attachee.location-3)\n\treturn RUN_DEFAULT\n\n\ndef respawn(attachee):\n\tbox = find_container_near(attachee,1001)\n\tRespawnInventory(box)\n\tgame.timevent_add(respawn, (attachee), 3600000 ) #3600000ms is 1 hour\n\treturn","sub_path":"scr/py00373Jenna.py","file_name":"py00373Jenna.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"438393528","text":"import numpy as np\n# from keras.models import Sequential\nfrom tensorflow.keras.models import Sequential\nfrom keras.layers.core import Activation, Dense\nfrom keras.optimizers import SGD\n\n# Trains a neural net that recognizes the digit displayed by a 7-segment LED:\n# \"Lit segments\" are indexed as:\n# -- 0 --\n# | |\n# 1 2\n# | |\n# -- 3 --\n# | |\n# 4 5\n# | |\n# -- 6 --\n#\n# For instance \"2\" = [1, 0, 1, 1, 1, 0, 1]\n\n# The testing data is a 10 x 7 array. A single row are the segments on the LED (e.g., 1,1,1,0,1,1,1 => \"0\") and there are 10 rows\nx = np.zeros((10, 7), dtype='uint8')\n# The output is a array of length 10. A single row is the one-hot encoded value of the equivalent 7-segment source\ny = np.zeros((10, 10), dtype='uint8')\n\n# This is the 7-segment map. x = input, y = output\n\nx[0] = [1, 1, 1, 0, 1, 1, 1]\nx[1] = [0, 0, 1, 0, 0, 1, 0]\nx[2] = [1, 0, 1, 1, 1, 0, 1]\nx[3] = [1, 0, 1, 1, 0, 1, 1]\nx[4] = [0, 1, 1, 1, 0, 1, 0]\nx[5] = [1, 1, 0, 1, 0, 1, 1]\nx[6] = [1, 1, 0, 1, 1, 1, 1]\nx[7] = [1, 0, 1, 0, 0, 1, 0]\nx[8] = [1, 1, 1, 1, 1, 1, 1]\nx[9] = [1, 1, 1, 1, 0, 1, 1]\n# Here's the desired output, in \"1-hot encoding\"\ny[0] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]\ny[1] = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]\ny[2] = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]\ny[3] = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]\ny[4] = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]\ny[5] = [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]\ny[6] = [0, 0, 0, 0, 0, 0, 1, 0, 0, 0]\ny[7] = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]\ny[8] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]\ny[9] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n\n# A \"sequential\" neural net is one where the data flows straight from inputs through the layers towards the output\nmodel = Sequential()\n# Densely interconnect an input layer consisting of 7 nodes (input_dim = 7) with a middle layer consisting of 4 nodes\n# (Experiment with fewer middle layer nodes, possibly with different activation / training times?\n# N.B. This also adds bias nodes\nmodel.add(Dense(4, input_dim=7))\n# Use the sigmoid activation function between the input layer and the middle layer\nmodel.add(Activation('sigmoid'))\n\n# Densely interconnect the middle layer with the 10 nodes in the output layer\nmodel.add(Dense(10))\n# Use the sigmoid activation function between the middle layer and this output layer\nmodel.add(Activation('sigmoid'))\n\n'''\nThe model is now ready!\n7 nodes in the input layer\n4 nodes in the middle layer\n10 node in the output layer\n'''\n\n# Train using \"Stochastic Gradient Descent\"\nsgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\n# Compile this to the underlying NN library.\nmodel.compile(loss='mean_squared_error', optimizer=sgd, class_mode=\"binary\")\n\nweight_formatter = lambda x: \"%.1f\" % x\nnp.set_printoptions(formatter={'float_kind':weight_formatter})\n\nprint (\"Prior to training weights are:\")\nfor layer in model.layers:\n g=layer.get_config()\n h=layer.get_weights()\n print (g)\n print (h)\n\n\n# Train. Take 10,000 spins through the training data!\nprint (\"Training...\")\nhistory = model.fit(x, y, nb_epoch=10000, batch_size=5, show_accuracy=True, verbose=0)\n\n# Take the input data and predict the outcomes.\nprint (\"Predictions:\")\nfloat_formatter = lambda x: \"%.0f\" % round(x)\nnp.set_printoptions(formatter={'float_kind':float_formatter})\nprint (np.matrix(model.predict(x)))\npredictArray = model.predict(x)\n\n\nprint (\"Subsequent to training weights are:\")\nnp.set_printoptions(formatter={'float_kind':weight_formatter})\n\nfor layer in model.layers:\n g=layer.get_config()\n h=layer.get_weights()\n print (g)\n print (h)\n","sub_path":"ramli/led_segs.py","file_name":"led_segs.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"370018814","text":"'''def greatest_division(a,b):\n if a == b:\n return a\n elif a>b:\n a = a-b\n return greatest_division(a,b)\n else:\n b = b - a\n return greatest_division(a,b)\nprint(greatest_division(8,6))\n'''\nimport math\n# NOTE : MERGE SORT\n\n\ndef merge_sort(lst):\n if len(lst) == 1:\n return lst\n else:\n\n mid = len(lst)//2\n left = lst[:mid]\n right = lst[mid:]\n m_left = merge_sort(left)\n m_right = merge_sort(right)\n loop = True\n i = 0\n j = 0\n new_lst = []\n while loop:\n if m_left[i] > m_right[j]:\n new_lst.append(m_right[j])\n j += 1\n if j == len(m_right):\n loop = False\n new_lst += m_left[i:]\n else:\n new_lst.append(m_left[i])\n i += 1\n if i == len(m_left):\n loop = False\n new_lst += m_right[j:]\n return new_lst\n\n\nh = [3, 7, 4, 2, 34324, 44, 433, 3434, 5]\nprint(merge_sort(h))\n\n\ndef quick_sort(lst):\n if len(lst) == 1 or len(lst) == 0:\n return lst\n else:\n a = 0\n b = len(lst)\n i = -1\n for _ in range(len(lst)-1):\n pivot = lst[a]\n b += i\n if (lst[b] < pivot and a < b) or (lst[b] > pivot and a > b):\n lst[a], lst[b] = lst[b], lst[a]\n a, b = b, a\n i = i * -1\n left = lst[:a]\n mid = [lst[a]]\n right = lst[(a+1):]\n q_left = quick_sort(left)\n q_right = quick_sort(right)\n lst = q_left + mid + q_right\n return lst\n\n\nprint(quick_sort(h))\n","sub_path":"session_4/session_4.py","file_name":"session_4.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"74883657","text":"# -*- coding:utf-8 -*-\nimport itchat\nitchat.login()\n#爬取自己好友相关信息, 返回一个json文件\nfriends = itchat.get_friends(update=True)[0:]\n\n#初始化计数器\nmale = female = other = 0\n#friends[0]是自己的信息,所以要从friends[1]开始\nfor i in friends[1:]:\n sex = i[\"Sex\"]\n if sex == 1:\n male += 1\n elif sex == 2:\n female += 1\n else:\n other +=1\n#计算朋友总数\ntotal = len(friends[1:])\n#打印出自己的好友性别比例\nprint(\"渔火总共好友人数为:%d\" % total + \"\\n\" +\n\"男性好友比例: %.2f%%\" % (float(male)/total*100) + \"\\n\" +\n\"女性好友比例: %.2f%%\" % (float(female) / total * 100) + \"\\n\" +\n\"不明性别好友比例: %.2f%%\" % (float(other) / total * 100))\n\n","sub_path":"apply/wechat.py","file_name":"wechat.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"590440021","text":"__author__ = 'winxos'\nimport random\nimport time\nsize=100#the queens number\nmaxstep=100\nseq=[0 for x in range(size)]#the queen sequence\nseqc=[0 for x in range(size)]\nam=[[0 for x in range(size)] for y in range(size)]#queen map\nbm=[[0 for x in range(size)] for y in range(size)]#queen conflicts value\n\ndef init():\n for x in range(size):\n seq[x]=random.randint(0,size-1)\ndef isConflict(ix,iy,jx,jy): #judge the conflict of queen a, and b\n detx=ix-jx\n dety=iy-jy\n if detx*dety==0:\n return 1\n if detx==dety or detx+dety==0:\n return 1\n return 0\ndef singleVar(x,y):#fill a queen,calc the conflicts\n for i in range(size):\n bm[x][i]+=1\n bm[i][y]+=1\n bm[x][y]-=1\n det=1\n while x-det>0 and y-det>0:\n bm[x-det][y-det]+=1\n det+=1\n det=1\n while x+det0 and y+det0:\n bm[x+det][y-det]+=1\n det+=1\ndef conflicts():\n for i in range(size):\n for j in range(size):\n bm[i][j]=0\n for x in range(size):\n singleVar(x,seq[x])\n ret=[]\n for i in range(size):\n if bm[i][seq[i]]>1:ret.append(i)\n return ret\ndef replace(n):\n mi=min(bm[n])\n t=[]\n for i in range(size):\n if bm[n][i]==mi:t.append(i)\n seq[n]=t[random.randint(0,len(t)-1)]\ndef search():\n for step in range(maxstep):\n c=conflicts()\n if len(c)==0:return\n replace(c[random.randint(0,len(c)-1)])\ndef prt(n):#print the array\n for x in range(size):\n print(n[x])\n print(\"----end----\")\ndef fillQ():#create the queen map am though seq\n for i in range(size):\n am[i][seq[i]]=1\n#main loop\nt1=time.time()*1000\ninit()\nprint(seq,\"ok\")\nwhile len(conflicts())>0:\n search()\n print(len(conflicts()),seq)\nprint(seq)\nt2=time.time()*1000\nprint(t2-t1)\n","sub_path":"nqueen_v2.py","file_name":"nqueen_v2.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616381929","text":"import requests\r\nfrom bs4 import BeautifulSoup as bs\r\n\r\nurl = r'https://www.rogerebert.com/reviews/blade-of-the-immortal-2017'\r\n\r\ndata = requests.get(url).text\r\nsoup = bs(data,'html.parser')\r\n#print(soup)\r\nf = open('BladeOfImmortal.txt','w+')\r\nfor x in soup.find_all('div',attrs={'itemprop':'reviewBody'}):\r\n # print x.get_text()\r\n for y in x.find_all('p'):\r\n #print(y.get_text())')\r\n f.write(y.get_text().strip().encode('utf-8'))\r\nf.close()\r\nprint(\"Done!\")\r\n","sub_path":"Natural Language Processing/Basics of NLP/GetMovieReviewpy2.py","file_name":"GetMovieReviewpy2.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"572569806","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport scipy.constants as sc\n\nv = np.linspace(0,1000,50)\nXi = 25\nE0 = 130\n\n\"\"\" Physical & Atomic Constants \"\"\"\nkb=sc.Boltzmann\nmu0 = sc.mu_0\nmuB = 9.2740099*10**-24\nu=sc.proton_mass\nhbar=sc.hbar\nc=sc.c\npi=np.pi \ne=sc.e\nM=87*u\nwab=2*pi*384.23e12\nG=38.11e6\nZ =337\ndip= 3.485e-29\n##d = G*Xi\n''' Variable Orgy '''\nRabi = dip*E0/hbar\nIoIs = 2*Rabi**2/G**2\nIrE = c*8.85e-12/2*E0**2/10000 # This is W/cm^2\nFplot = [2.41418817e15, 2.41418821e15, 2.41418809e15]\nd = np.subtract(wab, Fplot)\nw = wab - d\n\n\ni=0\nzs=[]\nvs=[]\nts=[]\na=0\nprint(Fplot[0])\nprint(v)\n#print(mu0)\n#print()\n#Ir=power/(a**2*pi)\nv = np.linspace(0,1000,100)\ndef dv(v,F,D):\n Lambda=2*pi*c/F\n k = 2*pi/Lambda\n 'Incremental Acceleration'\n O = F/(2*pi*c)\n c1 =1+IoIs+4*D**2/G**2\n c2 = O*8/G**2*D\n c3 = 4*O**2/G**2 \n rhoaa = -IoIs**2/(c1+c2*v+c3*v**2) + IoIs**2/(c1-c2*v+c3*v**2) \n return rhoaa*hbar*k*G/M\nprint(dv(100,20,2))\n\nL = len(Fplot)\nfor i in range(L):\n plt.plot(v, dv(v,Fplot[i],d[i]))\nS = []\nfor i in range(L):\n S.append(dv(v,Fplot[i],d[i]))\nS = np.reshape(S,(len(Fplot),len(v)))\n#print(S)\nSs = []\nfor i in range(L):\n Sim = np.argmax(S[i])\n Ss = np.append(Ss,Sim)\nprint(Ss)\nVv = []\nfor i in range(L):\n Vv.append(v[int(Ss[i])])\nprint(Vv)\n \nfor i in range(L):\n plt.axvline(Vv[i])\n\nplt.title('Force on Rb Atom v Velocity for different detunings', fontsize=20)\nplt.ylabel('∝ Force', fontsize=20)\nplt.xlabel('Velocity m/s', fontsize=20)\nplt.show()","sub_path":"Simulation/VisualS/EOM/throww.py","file_name":"throww.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"235849385","text":"from embit.liquid.pset import PSET\n\n\ndef to_canonical_pset(pset):\n \"\"\"\n Removes unblinded information from the transaction\n so Elements Core can decode it\n \"\"\"\n # if we got psbt, not pset - just return\n if not pset.startswith(\"cHNl\"):\n return pset\n tx = PSET.from_string(pset)\n\n for inp in tx.inputs:\n inp.value = None\n inp.asset = None\n inp.value_blinding_factor = None\n inp.asset_blinding_factor = None\n\n for out in tx.outputs:\n if out.is_blinded:\n out.asset = None\n out.asset_blinding_factor = None\n out.value = None\n out.value_blinding_factor = None\n return str(tx)\n","sub_path":"src/cryptoadvance/specter/liquid/util/pset.py","file_name":"pset.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"461307534","text":"import os\nimport torch\nimport torchvision.transforms as transforms\nimport numbers\nfrom PIL import Image\n\n# configurations\nimagenet_path = '/export/scratch/b/libigpu2/datasets/ImageNet2012/'\noutput_path = '/export/scratch/a/han424/imagenet_central_cropped/'\ncompressed_path = '/export/scratch/a/han424/imagenet_central_cropped.tar.gz'\n\n# define the train_path and the val_path\ninput_train_path = imagenet_path + 'train/'\ninput_val_path = imagenet_path + 'val/'\n\noutput_train_path = output_path + 'train/'\noutput_val_path = output_path + 'val/'\n\n# define the utilities\ntry:\n import accimage\nexcept ImportError:\n accimage = None\n\ndef _is_pil_image(img):\n if accimage is not None:\n return isinstance(img, (Image.Image, accimage.Image))\n else:\n return isinstance(img, Image.Image)\n\ndef crop(img, i, j, h, w):\n \"\"\"Crop the given PIL Image.\n Args:\n img (PIL Image): Image to be cropped.\n i (int): i in (i,j) i.e coordinates of the upper left corner.\n j (int): j in (i,j) i.e coordinates of the upper left corner.\n h (int): Height of the cropped image.\n w (int): Width of the cropped image.\n Returns:\n PIL Image: Cropped image.\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n return img.crop((j, i, j + w, i + h))\n\ndef center_crop(img):\n w, h = img.size\n output_size = w if (w < h) else h\n if isinstance(output_size, numbers.Number):\n output_size = (int(output_size), int(output_size))\n th, tw = output_size\n i = int(round((h - th) / 2.))\n j = int(round((w - tw) / 2.))\n return crop(img, i, j, th, tw)\n\ndef transform_save_image(image_path, save_path):\n # load the image\n img = Image.open(image_path)\n img_crop = center_crop(img) \n try:\n img_crop.save(save_path) \n except:\n print(' ' + image_path + ' needs to be transformed from RGBA to RGB before saving to ' + save_path)\n img = img.convert(\"RGB\")\n img.save(save_path)\n\n return 0\n\n# processing training data\ndef transform_data_set(input_set_path, output_set_path):\n os.system('mkdir ' + output_set_path)\n for sub_folder in os.listdir(input_set_path):\n sub_folder_path = input_set_path + sub_folder + '/'\n if os.path.isdir(sub_folder_path) is True:\n print('Transforming images from ' + sub_folder_path)\n output_folder_path = output_set_path + sub_folder + '/'\n os.system('mkdir ' + output_folder_path)\n for image_name in os.listdir(sub_folder_path):\n image_path = sub_folder_path + image_name\n image_save_path = output_folder_path + image_name\n transform_save_image(image_path, image_save_path)\n\n# run the transform_data_set function\nos.system('mkdir ' + output_path)\ntransform_data_set(input_train_path, output_train_path)\ntransform_data_set(input_val_path, output_val_path)\n\n# compress the files\nos.system('tar -czvf ' + compressed_path + ' ' + output_path)\n\n \n \n \n","sub_path":"dataset_generate_central-cropped_imagenet.py","file_name":"dataset_generate_central-cropped_imagenet.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"547071647","text":"\"\"\"\ncomputer select random word,\ngive user a tips: number of letter in word;\nuser tryin' to guess that word,\nuser has a 5 tries to guess is there a letter in the word,\nthen he must have to guess the word\n\"\"\"\nimport random\n\n# parameterized main params\nWORDS = (\"one\", \"two\", \"three\", \"four\", \"five\")\ntries = 0\t\t# hints\nuser_lett = None\t# user input\nword = \"empty\"\t# user input\n\n# initialize quiz-word\ncorrect = random.choice (WORDS)\nnum = len (correct)\nprint (correct)\n\nprint (\"\"\"\n\t\t\t\tHELLO, MY LITTLE DUMB FRIEND!\n\n\t\t\t\t\twelcome to quiz-game,\n\t \t\t\t try to guess hidden word\nyou have 5 attempts to find out whether there is such letter in the word\n if you don't want use a hint -- press \"Enter\" without your version,\n\n\t\t\tin your hidden word \"\"\", num, \"\"\" letters\n\t\t\t\t\t\tgood luck (:\n\n\t\"\"\")\n\n#letter validate\nwhile tries < 5:\n\tuser_lett = input (\"\\nplease input the estimated letter : \")\n\tif user_lett:\n\t\tif user_lett.lower() in correct:\n\t\t\tprint (\"\\nYEP\")\n\t\t\ttries += 1\n\t\telse:\n\t\t\tprint (\"\\nNOPE\")\n\t\t\ttries += 1\n\telse:\n\t\tbreak\n\nword = input (\"\\nplease input your version of estimated word : \")\n\n#word validate\nif word:\n if word.lower() == correct:\n print (\"\"\"\n GRATZ!\n YOU'RE RIGHT!\n \"\"\")\n elif word.lower() != correct:\n print (\"\"\"\n SORRY,\n but you're typicaly dumbass!\n \"\"\")\nelse:\n print(\"\"\"\n GOODBYE!\n \"\"\")\n\ninput(\"\\npress any key to exit\")\n","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"340527346","text":"import json\nimport logging\nimport requests\nfrom infiweather import settings\nfrom .models import CityWeatherDetails\nlogging = logging.getLogger(__name__)\n\n\ndef fetch_weather_info():\n endpoint = settings.WEATHER_API_ENDPOINT\n data = open('weatherinfo/city_name.json')\n json_data = json.load(data)\n city_names = json_data[\"city_names\"]\n logging.info(\"city names {}\".format(json_data[\"city_names\"]))\n\n for city in city_names:\n url = endpoint + \"/data/2.5/weather?q={}&appid={}\".format(city, settings.WEATHER_API_KEY)\n logging.info(\"calling Weather api, url {} \".format(url))\n try:\n r = requests.get(url)\n logging.info(\"status code {}\".format(r.status_code))\n if r.status_code != requests.codes.ok:\n logging.error(\n \"Unsuccessful response from Weather api ERROR = {}\".format(r.json()[\"message\"]))\n else:\n data = r.json()\n logging.info(\"successful response from weather api data - {}\".format(data))\n cityWeatherDetails = {\n \"city_name\": data[\"name\"],\n \"weather_details\": data[\"weather\"],\n \"wind_details\": data[\"wind\"],\n \"temperature_details\": data[\"main\"],\n \"visibility\": data[\"visibility\"],\n \"lat\": data[\"coord\"][\"lat\"],\n \"long\": data[\"coord\"][\"lon\"],\n \"openweather_id\": data[\"id\"]\n }\n city_details = CityWeatherDetails.objects.filter(city_name=data[\"name\"])\n if city_details.exists():\n city_details.update(**cityWeatherDetails)\n else:\n city_details = CityWeatherDetails(**cityWeatherDetails)\n city_details.save()\n except requests.exceptions.RequestException as e:\n logging.error(\n \"Error while calling WEATHER API, City {}, ERROR = {}\".format(city, e))\n","sub_path":"weatherinfo/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"241531392","text":"import sys\nimport copy\nimport json\nimport asyncio\nimport collections\nfrom unittest import mock\n\nimport furl\nimport aiohttp\nimport aiohttp.streams\n\n\nclass ImmutableFurl:\n\n def __init__(self, url, params=None):\n self._url = url\n self._furl = furl.furl(url)\n self._params = furl.furl(url).args\n self._furl.set(args={})\n\n params = params or {}\n for (k, v) in params.items():\n self._params.add(k, v)\n\n def with_out_params(self):\n return ImmutableFurl(self.url)\n\n @property\n def url(self):\n return self._furl.url\n\n @property\n def params(self):\n return self._params\n\n def __eq__(self, other):\n return hash(self) == hash(other)\n\n def __hash__(self):\n return hash(self.url + ''.join([\n self.params[x] or ''\n for x in sorted(self.params)\n ]))\n\nclass _MockStream(aiohttp.streams.StreamReader):\n def __init__(self, data):\n super().__init__()\n if isinstance(data, str):\n data = data.encode('UTF-8')\n elif not isinstance(data, bytes):\n raise TypeError('Data must be either str or bytes, found {!r}'.format(type(data)))\n\n self.size = len(data)\n self.feed_data(data)\n self.feed_eof()\n\n\ndef _wrap_content_stream(content):\n if isinstance(content, str):\n content = content.encode('utf-8')\n\n if isinstance(content, bytes):\n return _MockStream(content)\n\n if hasattr(content, 'read') and asyncio.iscoroutinefunction(content.read):\n return content\n\n raise TypeError('Content must be of type bytes or str, or implement the stream interface.')\n\n\nclass _AioHttPretty:\n def __init__(self):\n self.calls = []\n self.registry = {}\n self.request = None\n\n def make_call(self, **kwargs):\n return kwargs\n\n @asyncio.coroutine\n def process_request(self, **kwargs):\n \"\"\"Process request options as if the request was actually executed.\"\"\"\n data = kwargs.get('data')\n if isinstance(data, asyncio.StreamReader):\n yield from data.read()\n\n @asyncio.coroutine\n def fake_request(self, method, uri, **kwargs):\n params = kwargs.get('params', None)\n url = ImmutableFurl(uri, params=params)\n\n try:\n response = self.registry[(method, url)]\n except KeyError:\n raise Exception(\n 'No URLs matching {method} {uri} with params {url.params}. Not making request. '\n 'Go fix your test.'.format(**locals())\n )\n\n if isinstance(response, collections.Sequence):\n try:\n response = response.pop(0)\n except IndexError:\n raise Exception('No responses left.')\n\n yield from self.process_request(**kwargs)\n self.calls.append(\n self.make_call(method=method, uri=ImmutableFurl(uri, params=kwargs.pop('params', None)),\n **kwargs)\n )\n mock_response = aiohttp.client.ClientResponse(method, uri)\n mock_response.content = _wrap_content_stream(response.get('body', 'aiohttpretty'))\n mock_response._loop = mock.Mock()\n\n if response.get('auto_length'):\n defaults = {\n 'Content-Length': str(mock_response.content.size)\n }\n else:\n defaults = {}\n\n mock_response.headers = aiohttp.multidict.CIMultiDict(response.get('headers', defaults))\n mock_response.status = response.get('status', 200)\n return mock_response\n\n def register_uri(self, method, uri, **options):\n if any(x.get('params') for x in options.get('responses', [])):\n raise ValueError('Cannot specify params in responses, call register multiple times.')\n\n params = options.pop('params', {})\n url = ImmutableFurl(uri, params=params)\n\n self.registry[(method, url)] = options.get('responses', options)\n\n def register_json_uri(self, method, uri, **options):\n body = json.dumps(options.pop('body', None)).encode('utf-8')\n headers = {'Content-Type': 'application/json'}\n headers.update(options.pop('headers', {}))\n self.register_uri(method, uri, body=body, headers=headers, **options)\n\n def activate(self):\n aiohttp.ClientSession._request, self.request = self.fake_request, aiohttp.ClientSession._request\n\n def deactivate(self):\n aiohttp.ClientSession._request, self.request = self.request, None\n\n def clear(self):\n self.calls = []\n self.registry = {}\n\n def compare_call(self, first, second):\n for key, value in first.items():\n if second.get(key) != value:\n return False\n return True\n\n def has_call(self, uri, check_params=True, **kwargs):\n kwargs['uri'] = ImmutableFurl(uri, params=kwargs.pop('params', None))\n\n for call in self.calls:\n if not check_params:\n call = copy.deepcopy(call)\n call['uri'] = call['uri'].with_out_params()\n if self.compare_call(kwargs, call):\n return True\n return False\n\n\nsys.modules[__name__] = _AioHttPretty()\n","sub_path":"aiohttpretty.py","file_name":"aiohttpretty.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"126968208","text":"from collections import Counter\n\n\ndef sort_chars_freq(string):\n ans = \"\"\n count = Counter(string)\n pairs = []\n for key in count:\n pairs.append((key, count[key]))\n pairs.sort(key=lambda x: x[1], reverse=True)\n print(pairs)\n for pair in pairs:\n ans += pair[0]*pair[1]\n print(ans)\n \n\nprint(sort_chars_freq('tree'))","sub_path":"sort_chars_freq.py","file_name":"sort_chars_freq.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"46790626","text":"\"\"\" Faça uma função que receba 3 números inteiros como parâmetro, representando horas, minutos e segundos, e os converta\nem segundos.\"\"\"\n\n\ndef conversor_de_tempo(hours, minutes, seconds):\n \"\"\"\n -> Função que converte horas e minutos em segundos.\n :param hours: Horas informadas pelo usuário.\n :param minutes: Minutos informados pelo usuário.\n :param seconds: Segundos informados pelo usuário.\n :return: Retorna os valores convertidos para segundos.\n \"\"\"\n return f'{hours} h {minutes} mins e {seconds} segs, convertidos ficam com {(hours*3600) + (minutes*60) + seconds} segs'\n\n\nprint(conversor_de_tempo(int(input('Informe quantas horas deseja converter: ')),\n int(input('Informe quantos minutos deseja converter: ')),\n int(input('Informe quantos segundos deseja converter: '))))\n","sub_path":"Seção 8 - Funções/ex006.py","file_name":"ex006.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"34226158","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tuskar.storage.exceptions import UnknownName\nfrom tuskar.storage.stores import TemplateStore\n\n\ndef load_file(role_path):\n with open(role_path) as role_file:\n return role_file.read()\n\n\ndef create_or_update(name, contents, store=None, relative_path='',\n registry_path=''):\n if store is None:\n store = TemplateStore()\n try:\n role = store.retrieve_by_name(name)\n if role.contents != contents:\n role = store.update(role.uuid, contents, relative_path,\n registry_path)\n\n return False, role\n except UnknownName:\n return True, store.create(name, contents, relative_path, registry_path)\n\n\ndef process_role(role_path, role_name, store, all_roles, created, updated,\n relative_path=''):\n contents = load_file(role_path)\n # if bigger than 255 chars, truncate to the last 255\n registry_path = role_path[-255:]\n role_created, _ = create_or_update(role_name, contents, store,\n relative_path, registry_path)\n\n if all_roles is not None:\n all_roles.append(role_name)\n\n if role_created:\n created.append(role_name)\n else:\n updated.append(role_name)\n","sub_path":"tuskar/storage/load_utils.py","file_name":"load_utils.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"216412642","text":"import os\nimport urllib\nfrom threading import Thread\n\n\"\"\"\nCopy from http://fayaa.com/code/view/58/\n\"\"\"\n\nclass paxel(Thread, urllib.FancyURLopener):\n BLOCK_SIZE = 8192\n baidu_headers = {\n \"User-Agent\": \"netdisk;4.4.0.6;PC;PC-Windows;6.2.9200;WindowsBaiduYunGuaJia\",\n \"referer\": \"http://pan.baidu.com/disk/home\"\n }\n\n def __init__(self, threadname, url, filename, ranges):\n Thread.__init__(self, name = threadname)\n urllib.FancyURLopener.__init__(self)\n self.name = threadname\n self.url = url\n self.filename = filename\n self.beg, self.end = ranges\n self.cur = 0\n\n def run(self):\n try:\n dl = os.path.getsize(self.filename)\n except:\n dl = 0\n\n self.cur = self.beg + dl\n if self.cur >= self.end:\n return\n for key in self.baidu_headers:\n self.addheader(key, self.baidu_headers[key])\n self.addheader(\"Range\", \"bytes=%d-%d\" % (self.cur, self.end))\n\n out = open(self.filename, \"ab+\")\n handle = self.open(self.url)\n while self.cur < self.end:\n buf = handle.read(self.BLOCK_SIZE)\n out.write(buf)\n self.cur += len(buf)\n out.close()\n\n","sub_path":"paxel.py","file_name":"paxel.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"412502043","text":"# -*- coding: utf-8 -*-\nfrom light_qiwi import Qiwi, Provider\n\napi = Qiwi('00000000000000000000000000000000', '71234567890')\n\n\"\"\" Перевод на Qiwi кошелёк \"\"\"\n\naccount = \"77123456780\"\namount = 1050.55\ncomment = \"Спасибо за помощь!\"\n\nresponse = api.pay(account, amount, comment)\n\nprint(response)\n\n# -------------------------------------------\n\n\"\"\" Перевод на карту Visa по России \"\"\"\n\naccount = \"4276640999999999\"\namount = 1050.55\nprovider = Provider.RU_VISA\n\nresponse = api.pay(account, amount, provider=provider) # Отправлять комментарии нельзя\n\nprint(response)\n","sub_path":"examples/sample_pay.py","file_name":"sample_pay.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"248471915","text":"from __future__ import unicode_literals, print_function\nfrom abc import ABCMeta, abstractmethod\nimport json\nfrom exceptions import EnvironmentError\n\n\nclass Handler(object):\n __metaclass__ = ABCMeta\n\n def handle(self, event, context):\n \"\"\"\n :param dict event:\n :param context:\n :return dict:\n \"\"\"\n print(\"EVENT:\")\n print(json.dumps(event))\n try:\n return self._handle(event, context)\n except Exception as e:\n raise EnvironmentError('Bad Request: {}'.format(e.message))\n\n @abstractmethod\n def _handle(self, event, context):\n \"\"\"\n Dummy function for handlers.\n\n Override this so handle() will catch the exception and make it a \"Bad Request: \"\n\n :param dict event:\n :param context:\n :return dict:\n \"\"\"\n raise NotImplementedError()\n\n @staticmethod\n def retrieve(dictionary, key, dict_name=None):\n \"\"\"\n Retrieves a value from a dictionary.\n\n raises an error message if the specified key is not valid\n\n :param dict dictionary:\n :param any key:\n :param str|unicode dict_name: name of dictionary, for error message\n :return: value corresponding to key\n \"\"\"\n if key in dictionary:\n return dictionary[key]\n dict_name = \"dictionary\" if dict_name is None else dict_name\n raise Exception('{k} not found in {d}'.format(k=repr(key), d=dict_name))\n","sub_path":"lambda_handlers/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"154036008","text":"# Import Packages\nimport time\nimport os\n\nlocation='Bhinjpur'\n\n# Go to CLOVER directory\n#cd('/Users/Shez/Google Drive/Grantham/CLOVER/CLOVER-master/')\n\n# Import scripts\nprint('Importing Scripts...')\nexec(open(\"Scripts/Conversion_scripts/Conversion.py\").read())\nexec(open(\"Scripts/Generation_scripts/Diesel.py\").read())\nexec(open(\"Scripts/Generation_scripts/Grid.py\").read())\nexec(open(\"Scripts/Generation_scripts/Solar.py\").read())\nexec(open(\"Scripts/Load_scripts/Load.py\").read())\nexec(open(\"Scripts/Simulation_scripts/Energy_System.py\").read())\nexec(open(\"Scripts/Optimisation_scripts/Optimisation.py\").read())\n\n# Run optimisation - multiplicative factors in estimated ranges based on previous runs for 2000 households (+-25% of PV&stor per household from values in these runs - but CLOVER will explore outside of this range if it doesn't find an optimal solution here.)\nopt=Optimisation(location='Bhinjpur',\nstorage_type='LiB',\noptimisation_inputs=[\n['Scenario length',10],\n['Iteration length',2],\n['Threshold value',0.05],\n['Threshold criterion','Blackouts'],\n['PV size (min)',0.0],['PV size (max)',2*18],['PV size (step)',18/3],['PV size (increase)',18/2],\n['Storage size (min)',0.0],['Storage size (max)',2*73],['Storage size (step)',73/5],['Storage size (increase)',73/2]\n],\nfinance_inputs=[\n['Storage cost',350],\n['Storage cost decrease',5]\n],\nGHG_inputs=[\n['Storage GHGs',272]\n],\nenergy_system_inputs=[\n['Battery cycle lifetime',1000],\n['Battery minimum charge',0.2]\n]\n).multiple_optimisation_step()\n\n\n\nOptimisation(location='Bhinjpur').save_optimisation(opt,filename='Bhinjpur_LiB_cyc1000_cost350_It2yrs_Opt')\n\n\nprint('Done!')\n","sub_path":"Bhinjpur_MidBattCost/Bhinjpur_MidBattCost.py","file_name":"Bhinjpur_MidBattCost.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"612010062","text":"from django.shortcuts import render, redirect, get_object_or_404\n\nfrom license.forms import LicenseForm\nfrom license.models import License\nfrom openplane import settings as stgs\n\n\ndef license(request):\n licenses = License.objects.all()\n warning_months = stgs.MONTHS_BEFORE_WARNING\n alert_months = stgs.MONTHS_BEFORE_ALERT\n return render(request, 'license/show_licenses.html', locals())\n\n\ndef add(request):\n if request.method == 'POST':\n print('coucou')\n form = LicenseForm(request.POST)\n if form.is_valid():\n print('hey')\n form.save()\n return redirect('license')\n else:\n form = LicenseForm()\n\n return render(request, 'license/license_form.html', locals())\n\n\ndef edit(request, pk=None):\n if pk is None:\n return redirect('add_license')\n elif request.method == 'POST':\n license = get_object_or_404(License, id=pk)\n form = LicenseForm(request.POST, instance=license)\n if form.is_valid():\n form.save()\n return redirect('license')\n else:\n edit = True # The template know if we want to edit or to add a new license\n license = get_object_or_404(License, id=pk)\n form = LicenseForm(request.POST or None, instance=license)\n return render(request, 'license/license_form.html', locals())\n\n\ndef delete(request, pk):\n license = get_object_or_404(License, id=pk)\n license.delete()\n return redirect('license')\n","sub_path":"openplane/license/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"577100990","text":"#!/usr/bin /env python3\nfrom mat import *\n\nA = readm('A.csv')\nb = readm('b.csv')\n\ndef solve(A, b):\n # YOUR CODE HERE\n import numpy as np\n a,b = np.array(A), np.array(b)\n n= len(A[0])\n x = np.array([0]*n)\n #1.elimination\n \"\"\"n = len(A[0])\n print(f'n={n}')\n \"\"\"\n for k in range(0,n-1): # pivot equation #k\n #print(f'เลือกสมการที่ {k}')\n for j in range(k+1, n): #eliminate eq #j\n if a[j,k] !=0.0:\n #print(f'\\tกำจัดตัวแปรที่ {k},ออกจากสมการที่ {j}')\n lam = a[j][k]/a[k][k]\n #update A[j][k เป็นต้นไป]\n a[j,k:n] = a[j,k:n] - lam*a[k,k:n]\n #A[j][k+2] = A[j][k+2] - lam*A[k][k+2]\n #A[j][k+3] = A[j][k+3] - lam*A[k][k+3]\n #print(f'\\t\\tlambda={lam}')\n #update b[j]\n b[j] = b[j] - lam* b[k]\n\n \"\"\"printm(A)\n print(b)\n \"\"\"\n #2 back substitution\n for k in range(n-1, -1, -1): #2,1,0\n x[k] = (b[k] - np.dot(a[k,k+1:n], x[k+1:n]))/a[k,k]\n #print(f' k={k}')\n #A[k,0:n]*x[k:] = b[k:]\n #x = []\n return x.flatten()\nprint( solve (A,b))\n","sub_path":"la.py","file_name":"la.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"188262046","text":"from pydmfet import locints, sdmfet, oep, tools, dfet_ao, proj_ao\nfrom pydmfet.dfet_ao import dfet\nfrom pydmfet.qcwrap.pyscf_rks_ao import rks_ao\nfrom pyscf import gto, scf,dft, ao2mo,cc\nimport numpy as np\nfrom pyscf.tools import molden, cubegen\nimport copy\nfrom pydmfet.tools.sym import h_lattice_sym_tab\n\nt0 = tools.time0()\n\n\nbas = '6-31G*'\ntemp = 0.005\n\n\nmol = gto.Mole()\nmol.atom = open('trans_retinal_90_150.xyz').read()\nmol.basis = bas\nmol.charge = 1\nmol.build(max_memory = 16000, verbose=4)\n\n_, _, mo_coeff, mo_occ, _, _ = molden.load(\"MO.molden\")\ndm_guess = np.dot(mo_coeff*mo_occ, mo_coeff.T)\n\nmf = rks_ao(mol,smear_sigma = temp)\nmf.xc = 'hf'\nmf.max_cycle = 50\nmf.scf(dm0=dm_guess)\n\nwith open( 'MO.molden', 'w' ) as thefile:\n molden.header(mf.mol, thefile)\n molden.orbital_coeff(mf.mol, thefile, mf.mo_coeff,occ = mf.mo_occ)\n\nmyInts = locints.LocalIntegrals( mf, range( mol.nao_nr() ), 'meta_lowdin' )\nmyInts.TI_OK = False\n\nnatoms = mol.natm\nimpAtom = np.zeros([natoms], dtype=int)\nfor i in range(4):\n impAtom[i] = 1\n\n\nghost_frag = 1-impAtom\nghost_env = 1-ghost_frag\n\nmol_frag = gto.Mole()\nmol_frag.atom = tools.add_ghost(mol.atom, ghost_frag)\nmol_frag.basis = bas\nmol_frag.charge = -2 \nmol_frag.build(max_memory = 16000,verbose = 4)\n\nmol_env = gto.Mole()\nmol_env.atom = tools.add_ghost(mol.atom, ghost_env)\nmol_env.basis = bas\nmol_env.charge = 3\nmol_env.build(max_memory = 16000,verbose = 4)\n\nboundary_atoms = np.zeros([natoms])\nboundary_atoms2 = np.zeros([natoms])\nboundary_atoms[5-1] = 1\nboundary_atoms[6-1] = 1\nboundary_atoms2[1-1] = -1\nboundary_atoms2[2-1] = -1\n\nNe_frag = 16 \naoslice = mol.aoslice_by_atom()\nimpurities = np.zeros([mol.nao_nr()], dtype = int)\nfor i in range(natoms):\n if(impAtom[i] == 1):\n impurities[aoslice[i,2]:aoslice[i,3]] = 1\n\n\nparams = oep.OEPparams(algorithm = 'split', opt_method = 'L-BFGS-B', diffP_tol=1e-4, outer_maxit = 50)\nparams.options['ftol'] = 1e-10\nparams.options['gtol'] = 1e-4\nparams.options['maxiter'] = 100\nparams.options['svd_thresh'] = 1e-2\n\numat = None\n#umat = np.load(\"umat.npy\")\n\ntheDMFET = sdmfet.DMFET( mf, mol_frag, mol_env,myInts,impurities, impAtom, Ne_frag, \\\n boundary_atoms=boundary_atoms, boundary_atoms2=boundary_atoms2,\\\n umat = umat, dim_imp =None, dim_bath=32, dim_big =None, smear_sigma = temp, \\\n oep_params=params,ecw_method='ccsd', mf_method = mf.xc,\\\n use_umat_ao=False, scf_max_cycle = 100)\n\n#umat = theDMFET.embedding_potential()\n#energy = theDMFET.correction_energy()\nt1 = tools.timer(\"total calc time\",t0) \n","sub_path":"examples/research/retinal/dmfet/embed.py","file_name":"embed.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"373175300","text":"#-*- coding : gbk -*-\n# coding:unicode_escape\n#coding=utf-8\n#coding=gbk\n#r = r.decode('utf-8', 'ignore')\nimport datetime\nimport json\nimport os\nimport pickle\nimport sys\nimport warnings\nfrom multiprocessing import Manager, Pool\n\nimport numpy as np\nimport pandas as pd\nimport tushare as ts\n\nwarnings.filterwarnings('ignore')\n# 请根据自己的情况填写ts的token\nsetting = json.load(open('C://config//config.json'))\n# pro = foundation_tushare.TuShare(setting['token'], max_retry=60)\nts.set_token(setting['token'])\npro = ts.pro_api()\n\nglobal dataBase\ncurPath = os.path.abspath(os.path.dirname('c://temp//fund_data//'))\n# rootPath = curPath[:curPath.find(\"多因子框架\\\\\")+len(\"多因子框架\\\\\")]\nrootPath = curPath\ndataBase = rootPath + '//base_data//'\n\n\ndef read_pickle(path):\n with open(path, 'rb') as handle:\n return pickle.load(handle)\n\n\ndef update_pickle(text, path):\n with open(path, 'wb') as handle:\n pickle.dump(text, handle)\n\n\nclass DataDownloader:\n def __init__(self, start_date='20050101', end_date=None):\n self.start_date = start_date\n self.end_date = end_date\n self.trade_dates = self.get_trade_dates()\n #self.stk_codes = self.get_stks()\n #获取场内基金代码\n self.fund_codes = self.get_stks_fund()\n # self.template_df = pd.DataFrame(index=self.trade_dates,columns=self.stk_codes)\n\n def get_trade_dates(self, start_date=None, end_date=None):\n if start_date == None:\n start_date = self.start_date\n end_date = datetime.datetime.now().strftime('%Y%m%d') if end_date == None else self.end_date\n df = pro.trade_cal(exchange='SSE', start_date=start_date, end_date=end_date)\n df[df['is_open'] == 1]['cal_date'].drop_duplicates()\n return df[df['is_open'] == 1]['cal_date'].to_list()\n\n def get_stks(self):\n stk_set = set()\n for list_status in ['L', 'D', 'P']:\n stk_set |= set(pro.stock_basic(list_status=list_status, fileds='ts_code')['ts_code'].to_list())\n\n return sorted(list(stk_set))\n\n#########################################################################################\n def get_stks_fund(self):\n #stk_set = DataReader.read_E_fund()\n #筛选特定几个数据\n #list_sh 上证380 上证180 上证50 沪深300 科创50\n list_sh =('000009.SH','000010.SH','000016.SH','000300.SH','000688.SH',\n # 中证1000 中证100 中证500\t 中证800\n '000852.SH','000903.SH','000905.SH','000906.SH')\n #深圳指数 深证成指 中小板指\t 创业板指 深证100\n list_sz =('399001.SZ','399005.SZ','399006.SZ','399330.SZ')\n list_1 = list_sh+list_sz\n list_1 = list(list_1)\n #stk_set = stk_set[stk_set[['ts_code']].apply(lambda x : x.str.contains('|'.join(list_1))).any(1)]\n ###########\n #stk_set = stk_set['ts_code'].to_list()\n stk_set = list_1\n return sorted(list(stk_set))\n\n\n##########################################################################################\n\n def get_IdxWeight(self, idx_code):\n \"\"\"\n 指数成分股\n \"\"\"\n start_date = pd.to_datetime(self.trade_dates[0]) - datetime.timedelta(days=32)\n start_date = start_date.strftime('%Y%m%d')\n trade_dates = self.get_trade_dates(start_date)\n df_ls = []\n while start_date < trade_dates[-1]:\n end_date = pd.to_datetime(start_date) + datetime.timedelta(days=32)\n end_date = end_date.strftime('%Y%m%d')\n raw_df = pro.index_weight(index_code=idx_code, start_date=start_date, end_date=end_date)\n df_ls.append(raw_df.pivot(index='trade_date', columns='con_code', values='weight'))\n start_date = end_date\n\n res_df = pd.concat(df_ls)\n res_df = res_df[~res_df.index.duplicated(keep='first')]\n res_df = res_df.reindex(trade_dates)\n res_df = res_df.ffill().reindex(self.trade_dates)\n return res_df.sort_index()\n\n def get_ST_valid(self):\n \"\"\"\n ST股\n \"\"\"\n res_df = pd.DataFrame(index=self.trade_dates, columns=self.stk_codes).fillna(1)\n df = pro.namechange(fields='ts_code,name,start_date,end_date')\n df = df[df.name.str.contains('ST')]\n for i in range(df.shape[0]):\n ts_code = df.iloc[i, 0]\n if ts_code not in self.stk_codes:\n continue\n s_date = df.iloc[i, 2]\n e_date = df.iloc[i, 3]\n if e_date == None:\n res_df[ts_code].loc[s_date:] = np.nan\n else:\n res_df[ts_code].loc[s_date:e_date] = np.nan\n return res_df.sort_index()\n\n def get_suspend_oneDate(self, trade_date, m_ls):\n '''\n tushare的接口一次最多返回5000条数据,所以按天调取。用并行加速。\n '''\n try:\n df = pro.suspend_d(suspend_type='S', trade_date=trade_date)\n m_ls.append([trade_date, df])\n except:\n df = pro.suspend_d(suspend_type='S', trade_date=trade_date)\n m_ls.append([trade_date, df])\n\n def get_suspend_valid(self):\n '''\n 停牌股\n '''\n res_df = pd.DataFrame(index=self.trade_dates, columns=self.stk_codes).fillna(1)\n\n m_ls = Manager().list()\n pools = Pool(4)\n for date in self.trade_dates:\n pools.apply_async(self.get_suspend_oneDate,\n args=(date, m_ls)\n )\n pools.close()\n pools.join()\n m_ls = list(m_ls)\n for date, df in m_ls:\n print(date, df)\n res_df.loc[date, df['ts_code'].to_list()] = np.nan\n return res_df.sort_index()\n\n def get_limit_oneDate(self, trade_date, m_ls):\n '''\n tushare的接口一次最多返回5000条数据,所以按天调取。用并行加速。\n '''\n try:\n df = pro.limit_list(trade_date=trade_date)\n m_ls.append([trade_date, df])\n except:\n df = pro.suspend_d(trade_date=trade_date)\n m_ls.append([trade_date, df])\n\n def get_limit_valid(self):\n '''\n 停牌股\n '''\n res_df = pd.DataFrame(index=self.trade_dates, columns=self.stk_codes).fillna(1)\n m_ls = Manager().list()\n pools = Pool(3)\n for date in self.trade_dates:\n pools.apply_async(self.get_limit_oneDate,\n args=(date, m_ls)\n )\n pools.close()\n pools.join()\n m_ls = list(m_ls)\n for date, df in m_ls:\n res_df.loc[date, df['ts_code'].to_list()] = np.nan\n return res_df.sort_index()\n\n def get_dailyMkt_oneStock(self, ts_code, m_ls):\n '''\n 前复权的行情数据\n\n 因为tushare下载复权行情接口一次只能获取一只股票\n 所以使用多进行并行\n '''\n\n try:\n # 偶尔会因为网络问题请求失败,报错重新请求\n df = ts.pro_bar(ts_code=ts_code, adj='qfq', start_date=self.start_date, end_date=self.end_date)\n m_ls.append(df)\n except:\n df = ts.pro_bar(ts_code=ts_code, adj='qfq', start_date=self.start_date, end_date=self.end_date)\n m_ls.append(df)\n\n def get_dailyMkt_mulP(self):\n m_ls = Manager().list()\n pools = Pool(3) # 开太多会有访问频率限制\n for ts_code in self.stk_codes:\n pools.apply_async(self.get_dailyMkt_oneStock,\n args=(ts_code, m_ls))\n pools.close()\n pools.join()\n m_ls = list(m_ls)\n raw_df = pd.concat(m_ls)\n res_dict = {}\n for data_name in ['open', 'close', 'high', 'low', 'vol', 'amount']:\n res_df = raw_df.pivot(index='trade_date', columns='ts_code', values=data_name)\n res_dict[data_name] = res_df.sort_index()\n return res_dict\n######################场内基金更新######################################################\n def get_E_fund(self):\n '''\n 场内基金数据\n '''\n res_df=pro.index_basic()\n return res_df\n\n def get_dailyMkt_mulP_fund(self):\n m_ls = Manager().list()\n pools = Pool(3) # 开太多会有访问频率限制\n for ts_code in self.fund_codes:\n pools.apply_async(self.get_dailyMkt_oneFund,\n args=(ts_code, m_ls))\n pools.close()\n pools.join()\n m_ls = list(m_ls)\n raw_df = pd.concat(m_ls)\n ##############################################\n #raw_df.drop_duplicates(subset=['ts_code', 'nav_date'], keep='last', inplace=True)\n res_dict = {}\n for data_name in ['open', 'close', 'high', 'low','pre_close', 'vol', 'amount']:\n res_df = raw_df.pivot(index='trade_date', columns='ts_code', values=data_name)\n res_dict[data_name] = res_df.sort_index()\n return res_dict\n\n def get_dailyMkt_oneFund(self, ts_code, m_ls):\n '''\n 前复权的行情数据\n\n 因为tushare下载复权行情接口一次只能获取一只股票\n 所以使用多进行并行\n '''\n\n try:\n # 偶尔会因为网络问题请求失败,报错重新请求\n df = pro.index_daily(ts_code=ts_code, start_date=self.start_date, end_date=self.end_date)\n m_ls.append(df)\n except:\n df = pro.index_daily(ts_code=ts_code, start_date=self.start_date, end_date=self.end_date)\n m_ls.append(df)\nclass DataWriter:\n @staticmethod\n def commonFunc(data_path, getFunc, cover, *args, **kwds):\n if not os.path.exists(data_path) or cover:\n t1 = datetime.datetime.now()\n print(f'--------{data_path},第一次下载该数据,可能耗时较长')\n newData_df = eval(f'DataDownloader().{getFunc}(*args,**kwds)')\n newData_df.to_pickle(data_path)\n t2 = datetime.datetime.now()\n print(f'--------下载完成,耗时{t2 - t1}')\n else:\n savedData_df = pd.read_pickle(data_path)\n savedLastDate = savedData_df.index[-1]\n print(f'---------{data_path}上次更新至{savedLastDate},正在更新至最新交易日')\n\n lastData_df = eval(f'DataDownloader(savedLastDate).{getFunc}(*args,**kwds)')\n newData_df = pd.concat([savedData_df, lastData_df]).sort_index()\n newData_df = newData_df[~newData_df.index.duplicated(keep='first')]\n newData_df.to_pickle(data_path)\n print(f'---------已更新至最新日期{newData_df.index[-1]}')\n newData_df.index = pd.to_datetime(newData_df.index)\n return newData_df\n\n @staticmethod\n def update_IdxWeight(stk_code, cover=False):\n data_path = dataBase + f'daily/idx_cons/{stk_code}.pkl'\n return DataWriter.commonFunc(data_path, 'get_IdxWeight', cover, stk_code)\n\n @staticmethod\n def update_ST_valid(cover=False):\n data_path = dataBase + f'daily/valid/ST_valid.pkl'\n return DataWriter.commonFunc(data_path, 'get_ST_valid', cover)\n\n @staticmethod\n def update_suspend_valid(cover=False):\n data_path = dataBase + 'daily/valid/suspend_valid.pkl'\n return DataWriter.commonFunc(data_path, 'get_suspend_valid', cover)\n\n @staticmethod\n def update_limit_valid(cover=False):\n data_path = dataBase + 'daily/valid/limit_valid.pkl'\n return DataWriter.commonFunc(data_path, 'get_limit_valid', cover)\n\n @staticmethod\n def update_dailyMkt(cover=False):\n '''\n 需要保证已存储的ochlv数据的日期一致\n '''\n if not os.path.exists(dataBase + f'daily/mkt/open.pkl') or cover:\n print(f'--------Mkt,第一次下载该数据,可能耗时较长')\n res_dict = DataDownloader().get_dailyMkt_mulP()\n for data_name, df in res_dict.items():\n data_path = dataBase + f'daily/mkt//{data_name}.pkl'\n df.to_pickle(data_path)\n else:\n savedData_df = pd.read_pickle(dataBase + f'daily/mkt/{data_name}.pkl')\n savedLastDate = savedData_df.index[-1]\n print(f'---------Mkt,上次更新至{savedLastDate},正在更新至最新交易日')\n\n res_dict = DataDownloader(savedLastDate).get_dailyMkt_mulP()\n new_df = pd.DataFrame()\n for data_name, last_df in res_dict.items():\n data_path = dataBase + f'daily/mkt//{data_name}.pkl'\n new_df = pd.concat([savedData_df, last_df]).sort_index()\n new_df = new_df[~new_df.index.duplicated(keep='first')]\n new_df.to_pickle(data_path)\n print(f'---------已更新至最新日期{new_df.index[-1]}')\n\n###########################更新场内基金#################################################\n @staticmethod\n def update_E_fund(cover=False):\n data_path = dataBase + 'all_e_funds.pkl'\n return DataWriter.commonFunc(data_path, 'get_E_fund', cover)\n\n @staticmethod\n def update_dailyMkt_fund(cover=False):\n '''\n 需要保证已存储的ochlv数据的日期一致\n '''\n if not os.path.exists(dataBase + 'mkt//open.pkl') or cover:\n print(f'--------Mkt,第一次下载该数据,可能耗时较长')\n res_dict = DataDownloader().get_dailyMkt_mulP_fund()\n for data_name, df in res_dict.items():\n data_path = dataBase + f'mkt//{data_name}.pkl'\n df.to_pickle(data_path)\n else:\n savedData_df = pd.read_pickle(dataBase + f'mkt//open.pkl')\n savedLastDate = savedData_df.index[-1]\n print(f'---------Mkt,上次更新至{savedLastDate},正在更新至最新交易日')\n\n res_dict = DataDownloader(savedLastDate).get_dailyMkt_mulP_fund()\n new_df = pd.DataFrame()\n for data_name, last_df in res_dict.items():\n data_path = dataBase + f'mkt//{data_name}.pkl'\n savedData_df1 = pd.read_pickle(dataBase + f'mkt//{data_name}.pkl')\n new_df = pd.concat([savedData_df1, last_df]).sort_index()\n new_df = new_df[~new_df.index.duplicated(keep='first')]\n new_df.to_pickle(data_path)\n print(f'---------已更新至最新日期{new_df.index[-1]}')\n\nclass DataReader:\n @staticmethod\n def commonFunc(data_path):\n if not os.path.exists(data_path):\n print(f'{data_path}不存在,请先调用DataWriter().update_xx')\n return\n df = pd.read_pickle(data_path)\n df.index = pd.to_datetime(df.index)\n return df\n\n @staticmethod\n def read_IdxWeight(stk_code):\n data_path = dataBase + f'daily/idx_cons/{stk_code}.pkl'\n return DataReader.commonFunc(data_path)\n\n @staticmethod\n def read_ST_valid():\n data_path = dataBase + f'daily/valid/ST_valid.pkl'\n return DataReader.commonFunc(data_path)\n\n @staticmethod\n def read_suspend_valid():\n data_path = dataBase + 'daily/valid/suspend_valid.pkl'\n return DataReader.commonFunc(data_path)\n\n @staticmethod\n def read_limit_valid():\n data_path = dataBase + 'daily/valid/limit_valid.pkl'\n return DataReader.commonFunc(data_path)\n\n @staticmethod\n def read_dailyMkt(data_name):\n data_path = dataBase + f'mkt//{data_name}.pkl'\n return DataReader.commonFunc(data_path)\n\n @staticmethod\n def read_index_dailyRtn(index_code, start_date='20100101'):\n df = pro.index_daily(ts_code=index_code, start_date=start_date).set_index('trade_date').sort_index()\n df.index = pd.to_datetime(df.index)\n return df['pct_chg'] / 100\n\n @staticmethod\n def read_dailyRtn():\n df = DataReader.read_dailyMkt('close')\n return df.pct_change()\n\n##########################读取场内基金数据#################################################\n @staticmethod\n def read_E_fund():\n data_path = dataBase + 'all_e_funds.pkl'\n return DataReader.commonFunc(data_path)\n\nif __name__ == '__main__':\n #DataWriter.update_E_fund(cover=False)\n DataWriter.update_dailyMkt_fund(cover=False)\n\n\n\n\n###########################################################################\n #DataWriter.update_ST_valid(cover=True)\n #DataWriter.update_suspend_valid(cover=True)\n #DataWriter.update_IdxWeight('399300.SZ', cover=True)\n #DataWriter.update_dailyMkt(cover=True)\n #DataWriter.update_limit_valid(cover=True)\n\n\n\n'''\ntest_close = pd.read_pickle('C://temp//fund_data//base_data//mkt//close.pkl')\ntest_pre_close = pd.read_pickle('C://temp//fund_data//base_data//mkt//pre_close.pkl')\ntest_high = pd.read_pickle('C://temp//fund_data//base_data//mkt//high.pkl')\ntest_low = pd.read_pickle('C://temp//fund_data//base_data//mkt//low.pkl')\ntest_amount = pd.read_pickle('C://temp//fund_data//base_data//mkt//amount.pkl')\n\n\nindex_code = '000300.SH'\n#'close,pre_close,high,low,amount'\ndfs = [test_close[index_code],test_pre_close[index_code],test_high[index_code],test_low[index_code],test_amount[index_code]]\nresult = pd.concat(dfs,axis=1)\nresult.columns = ['close','pre_close','high','low','amount']\n\n\nresult = result.dropna(inplace=False) \n\n#result.to_csv('c://temp//000300SH.csv')\n#import datetime as datetime\n#close_df=pd.read_csv('c://temp//000300SH.csv')\n#close_df['trade_date']=pd.to_datetime(close_df['trade_date'].astype(str))\n#close_df.set_index('trade_date', inplace=True)\nresult.index=pd.to_datetime(result.index)\nresult.sort_index(inplace=True) \n\n\nclose_df=result\n\nprice_df=close_df[['close']]\n# 指标计算\nLR = cala_LR(price_df['close'])\n\n\nrsrs = RSRS_improve2() # 调用RSRS计算类\nsignal_df = rsrs.get_RSRS(close_df, (1 - LR), 10, 60, 'ols') # 获取各RSRS信号\n\nsignal_df.tail()\n\n'''\n","sub_path":"fund_strategy/技术分析算法框架与实战/data_preparation.py","file_name":"data_preparation.py","file_ext":"py","file_size_in_byte":17930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"76603929","text":"name = \"John,Doe,is,good\"\n\nres = name.lower()\nres = name.upper()\nres = name.split(',',1)\nfirst_name = res[0]\nlast_name = res[1]\n\nprint(name)\nprint(res)\nprint(first_name)\nprint(last_name)\n\narr = ('a','e','i','o','u')\narr = ['a','e','i','o','u']\narr = {'a','e','i','o','u'}\n\nhell= \"\".join(arr)\nprint(hell)","sub_path":"strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"582556461","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 13 18:34:53 2016\n\n@author: tianhao\n\"\"\"\nfrom influxdb import InfluxDBClient\nimport pandas.io.sql as sql \nimport pymysql\nimport pandas as pd\n\ncon = pymysql.connect(host = '10.0.0.10', user = 'hmc_dev', \n passwd = '12345678', db = 'haomaiche_qa', charset=\"utf8\")\n \nsqlstr = \"select count_time as time, count_num as num, count_type as type from web_record_count\"\n\nrawdata = sql.read_sql(sqlstr, con, parse_dates = True)\n\ncon.close()\n\nrawdata.time = pd.to_datetime(rawdata.time)\n\n#print (rawdata.head(10))\n\nclient = InfluxDBClient(host = '192.168.196.128', database = 'source_price')\n\n#client.delete_series(database = 'source_price', measurement = 'record_count')\n\njson_body = []\n\nfor index in range(len(rawdata)):\n point = {\n \"measurement\": \"record\",\n \"tags\": {\n \"record_type\": rawdata.ix[index, 'type']\n }, \n \"time\": rawdata.ix[index, 'time'],\n \"fields\": {\"record_num\": rawdata.ix[index, 'num']}\n }\n json_body.append(point)\n \"\"\"\n try:\n client.write_points(point, database = 'source_price')\n except Exception as e:\n print(e)\n \"\"\"\n#print (json_body)\n \ntry:\n client.write_points(json_body, database = 'source_price', batch_size = 3000)\nexcept Exception as e:\n print(e)\n# print(\"row: \", index, point)\n ","sub_path":"import influxdb/import_web_record.py","file_name":"import_web_record.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"243297634","text":"import sys, json\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport itertools\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport time\n\nimport sys, os\nsys.path.append( os.path.dirname(os.path.dirname( os.path.dirname( os.path.dirname( os.path.abspath(__file__))))))\nfrom src.tf_module.models.conv1d import conv1d_classifier\n\nseq_len = 128 \nn_classes = 4\nn_channels = 1\nscopes = [\"conv1d\", \"conv1d_rms\", \"conv1d_rms_mod1\"]\n# config = json.load(open(\"configs.json\",'r'))['conv1d']\nconfig = {'batch_size': 600, 'seq_len': 128, 'n_classes': 4, 'n_channels': 1, 'learning_rate': 1.25e-05, 'n_epochs': 1000000.0, 're_train': False}\nmodel = conv1d_classifier(config, scope=\"conv1d_rms\")\n\n\ndef split_data(data, seq_len):\n len_d = len(data)\n indx = (len_d//seq_len)*seq_len\n nSplits = len_d//seq_len\n print(\"Data loss: \", (len_d-indx))\n x_split = np.split(data[:indx,:],nSplits,axis=0)\n return x_split\n\n\nraw_data = pd.read_csv(\"Z:\\\\Ongoing_projects\\\\Husqvarna\\\\2018_10_18_Recordings\\\\cleaned_recordings\\\\sess1_oct_18.csv\")\n# raw_data = pd.read_csv(\"C:\\\\Users\\\\siddhartha\\\\Desktop\\\\clean&label\\\\cleaned_recordings\\\\session2.csv\")\n\n#'x','y','z',\ncols = ['rms']\ndata = np.array(split_data(np.array(raw_data[cols].values),seq_len))\n# data = np.array(split_data(np.random.rand(128*1000,2),seq_len))\nprint(np.shape(data))\n\n\nt1 = time.time()\ny = model.predict(data)\n\nprint(np.shape(y))\n\n\nlabels = [ np.random.choice(np.arange(n_classes),p = y[i,:]) for i in range(len(y))]\n\nprint(\"time taken: \", time.time()-t1)\n\nsplit_labels = np.array_split(labels,(len(labels)//25)+1)\nprint(np.shape(split_labels))\navg_data = [max(list(s),key=list(s).count)*100 for s in list(split_labels)]\n# avg_data = [int(np.mean(list(s)))*200 for s in list(split_labels)]\n\n\nprint(np.shape(labels))\nplt.figure(1)\nplt.plot(labels,'.')\nplt.figure(2)\navg_exp = [x for x in list(avg_data) for _ in range(seq_len*25)]\nplt.plot(avg_exp) \n# plt.figure(3)\nplt.plot(raw_data['tof'].values)\nplt.show()\n","sub_path":"src/tf_module/train/mt_detect_app.py","file_name":"mt_detect_app.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"585203886","text":"import os\nimport cPickle as pkl\n\nfrom gensim.models import word2vec\n\nimport config\nfrom simulation import VectorScoringSimulation\nfrom models.lstm import LSTMNet\nfrom utils.textPrep import LSTMPrepper\nfrom utils import get_module_logger\n\nlogger = get_module_logger(__name__)\n\n\nclass Word2VecSimulation(VectorScoringSimulation):\n\n experiment_name = 'word2vec_simulation'\n\n def constraints(self):\n pass\n\n def cleanParameters(self):\n self.size = int(self.size) * 10\n self.window = int(self.window) * 2\n self.min_count = int(self.min_count) * 5\n self.dm = int(self.dm)\n self.hs = int(self.hs)\n self.negative = int(self.negative) * 2\n self.sample = 10 ** -float(self.sample)\n self.sg = int(self.sg)\n self.cbow_mean = int(self.cbow_mean)\n self.iter_ = int(self.iter_)\n self.lstm_size = int(self.lstm_size) * 10\n\n def run(self, dataset, **kwargs):\n docs = dataset.docs\n scores = dataset.scores\n workers = kwargs.get('workers', config.word2vec_workers)\n maxlen = kwargs.get('maxlen', config.word2vec_maxlen)\n dropout_rate = kwargs.get('dropout_rate',\n config.word2vec_dropout_rate)\n patience = kwargs.get('patience', config.word2vec_patience)\n logger.info('maxlen: %d' % maxlen)\n logger.info('dropout_rate: %f' % dropout_rate)\n logger.info('patience: %d' % patience)\n\n logger.info('Starting word2vec training')\n texts = self.processTexts(docs)\n word2vec_model = word2vec.Word2Vec(texts,\n size=self.size, window=self.window,\n min_count=self.min_count,\n sample=self.sample, workers=workers,\n sg=self.sg, hs=self.hs,\n negative=self.negative,\n cbow_mean=self.cbow_mean,\n iter=self.iter_)\n logger.info('Fixing documents')\n texts = LSTMPrepper(docs, word2vec_model.vocab, word2vec_model.syn0)\n\n # save vocab\n with file(os.path.join(config.models_path,\n \"vocabulary\"), \"wb\") as fout:\n pkl.dump(texts.vocab, fout, -1)\n\n logger.info('Starting training the lstm')\n\n lstm = LSTMNet(texts.docs,\n scores,\n vocab_size=texts.vocab_size,\n embedding_size=self.size,\n maxlen=maxlen,\n lstm_size=self.lstm_size,\n dropout_rate=dropout_rate,\n patience=patience,\n weights=texts.embeddings,\n trainable=self.trainable)\n return lstm.docvecs\n\n def processTexts(self, docs):\n logger.info('Processing texts for word2vec')\n return [[unicode(x) for x in sent.split()] for sent in docs]\n","sub_path":"models/word2vec/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"635812643","text":"import os\nimport re\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\ndef mean(a):\n return sum(a) / len(a)\ninput_path = \"title_abstract_data\"\nexpr = re.compile(\"[a-zA-Z]+\")\ntokenize = lambda doc: expr.findall(doc)\nfiles = next(os.walk(input_path))[2]\nreviwer_title_dic = {}\nreviwer_abstract_dic = {}\nreviwer_keyword_dic = {}\nfor i in range(len(files)):\n\tl = []\n\tm = []\n\tf = open(\"title_abstract_data/\" + files[i],\"r\", encoding='utf8', errors='ignore')\n\tfor line in f:\n\t\ts = line.split(\"|\")\n\t\tl.append(s[0])\n\t\tif(len(s[1]) > 1):\n\t\t\tm.append(s[1])\n\treviwer_title_dic[files[i][:-4]] = l\n\treviwer_abstract_dic[files[i][:-4]] = m\n\twhile(\"\" in m):\n\t\tm.remove(\"\")\n\tif len(m) > 0:\n\t\tsklearn_tfidf = TfidfVectorizer(norm='l2',min_df=0, use_idf=True, smooth_idf=True, sublinear_tf=False, tokenizer=tokenize)\n\t\tsklearn_representation = sklearn_tfidf.fit_transform(m)\n\treviwer_Score_dic = {}\n\tvect = np.mean(sklearn_representation.todense(), axis=0).tolist()\n\tfor key in sklearn_tfidf.vocabulary_:\n\t\treviwer_Score_dic[key] = vect[0][sklearn_tfidf.vocabulary_[key]]\n\treviwer_Score_dic = sorted(reviwer_Score_dic.items(), key=lambda x: x[1])\n\t#print(reviwer_Score_dic)\t\n\tg = []\n\tn = int(len(reviwer_Score_dic) * 0.2)\n\tfor f in range(n):\n\t\titem = reviwer_Score_dic.pop()\n\t\tkey,value = item\n\t\tg.append(key)\n\treviwer_keyword_dic[files[i][:-4]] = g \n\t#print(reviwer_keyword_dic)\n\ninput_title = open(\"Expert_Finding_Data/titles.txt\",\"r\", encoding='utf8', errors='ignore')\ninput_abstract = open(\"Expert_Finding_Data/abstracts.txt\",\"r\", encoding='utf8', errors='ignore')\n\nl = []\nm = []\nv = 1\t\t# for indexing in input_dic\nwriters_name = []\nwriters_name_list = []\ninput_dic = {}\nfor line in input_title:\n\ts = line.split(\"/\")\n\tl.append(s[0])\n\twriters_name = \"\".join(s[1]).split(\"and\")\n\tfor i in range(len(writers_name)):\n\t\tif(\"\\n\" in writers_name[i]):\n\t\t\twriters_name[i] = writers_name[i][:-1]\n\t\twriters_name[i] = writers_name[i].strip(\" \")\n\twhile(\"\" in writers_name):\n\t\twriters_name.remove(\"\")\n\twriters_name_list.append(set(writers_name))\n\tprint(writers_name_list)\n\nfor line in input_abstract:\n\ts = l[v - 1] + line \n\tinput_dic[v] = tokenize(s) \n\tv += 1\n\ndef jaccard_similarity(query, document):\n intersection = set(query).intersection(set(document))\n union = set(query).union(set(document))\n return len(intersection)/len(union)\n\n\nindex = 1\nfinal_dic = {}\nfor name in writers_name_list:\n\tjaccard_dic = {}\n\tfor reviewer in reviwer_keyword_dic:\n\t\tif(len(name.intersection(set(reviewer))) > 0):\n\t\t\tcontinue;\n\t\telse:\n\t\t\t#print(type(input_dic[index]))\n\t\t\t#print(type(reviwer_keyword_dic[reviewer]))\n\t\t\tjaccard_dic[reviewer] = jaccard_similarity(input_dic[index],reviwer_keyword_dic[reviewer])\n\t#print(jaccard_dic)\n\tjaccard_dic = sorted(jaccard_dic.items(), key=lambda x: x[1])\n\t#print(jaccard_dic)\n\tg = []\n\tn = 10\n\tfor f in range(n):\n\t\titem = jaccard_dic.pop()\n\t\tkey,value = item\n\t\tg.append(key)\n\tfinal_dic[index] = g\n\tindex += 1\nprint(final_dic)\n\n\n\n\n\t\n\n\n","sub_path":"Recommender_v1.0.py","file_name":"Recommender_v1.0.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"267839476","text":"from baseClasses.DatabaseProcessingUtility import *\nfrom helper.functions import outputObj,loadOBJ,minmax\nfrom IIITDTemplate import *\nfrom FixWithAveragedModel import *\nfrom RotateFace import *\nimport os, glob, copy, numpy as np\n\nclass IIITDKinectDataset(DatabaseProcessingUtility):\n\n def loadTemplateImage(self):\n for t in self.templates:\n t.loadImage()\n\n def loadRotatedFaces(self,angles,axis):\n addTemplates = []\n for t in self.templates:\n print(\"Gerando copia de \"+t.rawRepr)\n for ax in axis:\n for a in angles:\n print(\"Angulo = \"+ str(a))\n nobj = copy.deepcopy(t)\n if os.path.exists(nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+ax+'_newdepth.bmp'):\n pathImages = nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+ax+'_newdepth.bmp'\n with im.open(pathImages) as currImg:\n nobj.image = np.asarray(currImg)\n nobj.rawRepr = pathImages\n addTemplates.append(nobj)\n\n self.templates = self.templates + addTemplates\n\n def __init__(self,path,type='Range'):\n self.imageType = type\n super().__init__(path)\n\n def loadRotatedFaces(self,angles,axis):\n addTemplates = []\n for t in self.templates:\n print(\"Gerando copia de \"+t.rawRepr)\n for ax in axis:\n if ax == 'xy':\n for a in angles:\n for b in angles:\n if a == 0 or b == 0:\n continue\n print(\"Cross Angulo \"+ str(a) + ' '+str(b))\n nobj = copy.deepcopy(t)\n if os.path.exists(nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+str(b)+'_'+ax+'_newdepth.bmp'):\n pathImages = nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+str(b)+'_'+ax+'_newdepth.bmp'\n with im.open(pathImages) as currImg:\n nobj.image = np.asarray(currImg)\n nobj.rawRepr = pathImages\n addTemplates.append(nobj)\n else:\n for a in angles:\n print(\"Angulo = \"+ str(a))\n nobj = copy.deepcopy(t)\n if os.path.exists(nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+ax+'_newdepth.bmp'):\n pathImages = nobj.rawRepr[0:-4] +'_rotate_'+str(a)+'_'+ax+'_newdepth.bmp'\n try:\n with im.open(pathImages) as currImg:\n nobj.image = np.asarray(currImg)\n nobj.rawRepr = pathImages\n addTemplates.append(nobj)\n except:\n continue\n\n self.templates = self.templates + addTemplates\n\n\n def loadNewDepthImage(self):\n for t in self.templates:\n t.loadNewDepthImage()\n\n def getFilesFromDirectory(self,path):\n return glob.glob(path + '/*.'+self.extensionFile[self.imageType])\n\n def getDirecotiresInPath(self,path):\n return [f for f in os.listdir(path) if not os.path.isfile(os.path.join(path, f))]\n\n def getTemplateType(self,fileName):\n explodedFile = fileName.split('.')\n explodedFile = explodedFile[0].split('_')\n return explodedFile.pop()\n\n def feedTemplates(self):\n for subject in self.getDirecotiresInPath(self.databasePath):\n if self.imageType in ['Depth','Range']:\n directories = self.getFilesFromDirectory(os.path.join(self.databasePath,subject,'Depth','depthnocolor'))\n else:\n directories = self.getFilesFromDirectory(os.path.join(self.databasePath,subject,'Depth'))\n for d in directories:\n statinfo = os.stat(os.path.join(self.databasePath,subject,d))\n if statinfo.st_size > 15 and 'rotate' not in d and 'matlab' not in d and 'symfilled' not in d:\n euTemp = IIITDTemplate(os.path.join(self.databasePath,subject,d),subject)\n self.templates.append(euTemp)\n\n def getDatabaseRepresentation(self):\n returnRepr = [[],[]]\n for template in self.templates:\n returnRepr[0].append(template.features)\n returnRepr[1].append(template.itemClass)\n return returnRepr\n\n def getTemplateFromSubject(self,subject):\n returnTemplates = []\n for template in self.templates:\n if (template.itemClass == subject):\n returnTemplates.append(template)\n return returnTemplates\n\n def fixingProbe(self):\n fwa = FixWithAveragedModel()\n for template in self.templates:\n template = fwa.doPreProcessing(template)\n\n def generateDatabaseFile(self,path,otherBases=None,outputDesired='SVMTorchFormat',excludeFiles=[]):\n currSearch = self.templates\n if otherBases:\n for o in otherBases:\n currSearch = currSearch + o.templates\n currFiles = []\n filesPath = []\n for f in currSearch:\n currFiles.append(f)\n filesPath.append(f.rawRepr)\n\n pathFaces = path[:-4]\n pathFaces = pathFaces + '_faces.txt'\n f = open(pathFaces,'w')\n for t in filesPath:\n print(\"Imprimindo linha arquivos\")\n f.write(t + '\\n')\n f.close()\n return getattr(self,outputDesired)(currFiles,path)\n\n def SVMTorchFormat(self,data,path):\n f = open(path,'w')\n f.write(str(len(data))+' '+str(len(data[0].features) + 1) + '\\n')\n for t in data:\n print(\"Imprimindo linha\")\n if not (t.features is None):\n f.write(' '.join([str(e) for e in t.features]) + ' ' + str(t.itemClass - 1) + '\\n')\n f.close()\n return []\n\n def caffeFormat(self,data,path):\n f = open(path,'w')\n for t in data:\n f.write(' '.join([str(e) for e in t.features]) + '\\n')\n f.close()\n return []\n\n def h5Format(self,data,path):\n import h5py\n X = np.zeros((len(data),len(data[0].features)))\n Y = np.zeros((len(data),1))\n for t in range(len(data)):\n X[t] = data[t].features\n Y[t] = data[t].itemClass\n\n with h5py.File(path,'w') as H:\n H.create_dataset( 'X', data=X )\n H.create_dataset( 'Y', data=Y )\n with open(path[:-3]+'_list.txt','w') as L:\n L.write( path )\n\n def imageForCaffe(self,data,path):\n dataNum = 0\n for t in data:\n dataNum = dataNum + 1\n fixedFeature = np.array(t.features).reshape(int(len(t.features)/14),14)\n f = open(os.path.join(path,str(t.itemClass)+'_'+t.typeTemplate+'_'+str(dataNum)+'.txt'),'w')\n for i in fixedFeature:\n finalPrint = ''\n for j in i:\n finalPrint = finalPrint + str(j) + \" \"\n f.write(finalPrint + '\\n')\n f.close()\n\n return []\n\n def generateCharsClasses(self,data,path):\n returnArray = [[],[]]\n for t in data:\n returnArray[0].append(t.features)\n returnArray[1].append(t.itemClass)\n\n return returnArray\n\n def normalizeData(self):\n for t in self.templates:\n print(t.features)\n t.features = minmax(t.features)\n print(t.features)","sub_path":"IIITDKinectDataset.py","file_name":"IIITDKinectDataset.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"217632895","text":"import numpy as np\nfrom numpy import dot\n\nimport random\n\nclass Perceptron:\n def fit(self, X_pos, X_neg):\n N1, n = X_pos.shape\n N2, n = X_neg.shape\n\n X_pos = np.c_[[1] * N1, X_pos]\n X_neg = np.c_[[1] * N2, X_neg]\n\n data = zip(X_pos, [1] * N1) + zip(X_neg, [-1] * N2)\n\n uncorrectly_classified = data\n\n self.weights = np.array([0.] * (n + 1))\n\n while len(uncorrectly_classified) > 0:\n amount = min(len(uncorrectly_classified), 10)\n\n for x, y in random.sample(uncorrectly_classified, amount):\n if not self._predicts_correctly(x, y):\n self.weights += x * y\n\n uncorrectly_classified = self._find_wrongly_classified(data)\n\n def _predict_single(self, x):\n score = x.dot(self.weights)\n\n if score >= 0:\n return 1\n else:\n return -1\n\n def _predicts_correctly(self, x, y):\n return self._predict_single(x) == y\n\n def _find_wrongly_classified(self, data):\n X, y = zip(*data)\n X = np.array(X)\n\n predictions = self.predict(X, add_ones=False)\n results = zip(X, predictions, y)\n\n return [(x, y) for x, prediction, y in results if prediction != y]\n\n def predict(self, X, add_ones=True):\n if add_ones:\n X = np.c_[[1] * len(X), X]\n\n scores = X.dot(self.weights)\n\n return [1 if score >= 0 else -1 for score in scores]\n\n def score(self, X, y):\n predictions = self.predict(X)\n\n n = len(X)\n correct = 0.\n\n for i in range(n):\n if predictions[i] == y[i]:\n correct += 1\n\n return correct / n\n","sub_path":"flearn/linear_model/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"307941612","text":"from mpl_toolkits.basemap import Basemap\nfrom matplotlib import pyplot as plt\n\ndef CreateMapBackground(edges=(-180,180,-90,90),buffer=0):\n '''Edges = (Minimum Longitude, Maximum Longitude, Minimum Latitude, Maximum Latitude)\n Buffer is the number of degrees between Min/Max Lon/Lat around the map'''\n m = Basemap(llcrnrlon=edges[0]-buffer, llcrnrlat=edges[2]-buffer,urcrnrlon=edges[1]+buffer,urcrnrlat=edges[3]+buffer,lon_0=0,lat_0=0)\n m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)\n m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')\n m.drawcoastlines(linewidth=0.1, color=\"white\")\n return m\n","sub_path":"Scripts/BetterMap.py","file_name":"BetterMap.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"416074173","text":"import os\nimport django\nimport random\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intTechProject.settings')\n\ndjango.setup()\n\nfrom django.contrib.auth.models import User\nfrom mainapp.models import City, Hobby, UserProfile, Language, UserRating\n\n\n# Create an array of City objects to be assigned to users\ndef get_cities():\n # Details for currently available cities. If the project were to go on this list would be expanded\n city_names = ['Glasgow', 'Madrid', 'Stockholm', 'Sao Paulo', 'Shanghai', 'Paris', 'Munich', 'Budapest']\n countries = ['Scotland', 'Spain', 'Sweden', 'Brazil', 'China', 'France', 'Germany', 'Hungary']\n\n cities = []\n\n # Load the description of each city (obtained from WikiTravel) from a file\n city_descriptions_file = open(\"static/populationScriptFiles/cityDescriptions.txt\", 'r')\n city_descriptions = city_descriptions_file.readlines()\n\n # Loop through the city list and create a new City object for each\n for i in range(len(city_names)):\n # Create a new city object with the relevant name, country and description\n created_city = City.objects.get_or_create(name=city_names[i], country=countries[i],\n information=city_descriptions[i])[0]\n\n # Load the city's profile image (obtained from WikiTravel) from the relevant file\n new_city_image = \"%s/\" + city_names[i] + \".jpg\"\n\n # Add the new city image to the newly created City object\n created_city.image = new_city_image % 'city_images'\n\n # Save the object and append it to the array of City objects\n created_city.save()\n cities.append(created_city)\n\n # Return the array of City objects\n return cities\n\n\n# Create a new user with a random first name (either male of female), a random surname and a random city\ndef create_user_details(male_names, female_names, last_names, created_city):\n # Create a male profile if random number is 1 (50% chance), female profile otherwise\n if random.randint(0, 1) == 1:\n first_name = male_names[random.randint(0, len(male_names) - 1)].strip().title()\n else:\n first_name = female_names[random.randint(0, len(female_names) - 1)].strip().title()\n\n # Assign user a random surname\n last_name = last_names[random.randint(0, len(last_names) - 1)].strip().title()\n\n # Create an email address in the form .@\n email_suffixes = ['live.com', 'live.co.uk', 'hotmail.com', 'gmail.com', 'yahoo.com', 'apple.com', 'aol.com']\n email_suffix = email_suffixes[random.randint(0, len(email_suffixes) - 1)].strip()\n email = first_name.lower() + '.' + last_name.lower() + '@' + email_suffix\n\n # Create a username\n username = first_name.lower() + last_name.lower()\n\n # Create a new User object\n new_user = User.objects.get_or_create(username=username, email=email)[0]\n\n # Set all passwords to be passwords for testing\n new_user.password = 'password'\n\n # Set the new User object's first and last names\n new_user.first_name = first_name\n new_user.last_name = last_name\n\n # Save the new User object\n new_user.save()\n\n # Create a new User Profile object which is an extension of the User object\n # Two separate objects have to be used as the User object is a native Django one and cannot host the required fields\n new_user_profile = UserProfile.objects.get_or_create(user=new_user, city=created_city, )[0]\n new_user_profile.slug = username\n\n # Assign the user a random profile picture (each picture is the same but with a different coloured background)\n profile_picture = \"%s/profile_picture\" + str(random.randint(0, 4)) + \".jpg\"\n new_user_profile.profilepic = profile_picture % 'profile_pictures'\n\n # Save the new User Profile object\n new_user_profile.save()\n\n # Return the User object\n return new_user\n\n\n# Assign user a random number of hobbies between 0 and 6 (up to a total of seven hobbies)\ndef create_hobbies(user_details, hobby_names):\n # Create an empty array to hold the user's hobbies\n user_hobbies = []\n\n # Loop through hobby assign process a random number (between 0 and 6 times)\n for new_hobby in range(random.randint(0, 6)):\n\n # Choose a random hobby from the given hobby list\n hob = hobby_names[random.randint(0, len(hobby_names) - 1)].strip().title()\n\n # Check if the hobby has already been assigned to the user\n if hob not in user_hobbies:\n # If it has not then add it to the hobby array\n user_hobbies.append(hob)\n\n # Create a new Hobby object and save it\n new_hobby = Hobby.objects.get_or_create(hobby=hob)[0]\n new_hobby.save()\n\n # Assign the new hobby to the given user\n user_details.profile.hobbies.add(new_hobby)\n\n\n# Assign the user a number of languages\ndef create_languages(user_details, random_city):\n # The list of languages a user can speak\n languages = ['English', 'Spanish', 'Swedish', 'Portuguese', 'Chinese', 'French', 'German', 'Hungarian', 'Latin',\n 'Japanese', 'Thai']\n\n # Assign user the language native to that city (e.g. Glasgow would be English)\n # The arrays are in the correct order so the city at index 0 will correspond to the language at index 0\n new_language = Language.objects.get_or_create(language=languages[random_city])[0]\n new_language.save()\n\n # Assign the native language to the user\n user_details.profile.languages.add(new_language)\n user_languages = [languages[random_city]]\n\n # Assign user a random number of other languages between 0 and 3 (up to a total of four languages)\n for new_language in range(random.randint(0, 3)):\n\n # Choose a random language in the list\n lang = languages[random.randint(0, len(languages) - 1)]\n\n # Ensure the language has not already been assigned to the user\n if lang not in user_languages:\n # Create the new language object and save it\n new_language = Language.objects.get_or_create(language=lang)[0]\n new_language.save()\n\n # Assign the new language to the user\n user_details.profile.languages.add(new_language)\n user_languages.append(lang)\n\n\n# Create a database of 100 fake users (plus three real) with random names, home cities, hobbies and languages\ndef create_users():\n # Create the list of City objects to assign to users\n cities = get_cities()\n\n # Read in first names from file\n names_file = open(\"static/populationScriptFiles/newNamesMale.txt\", 'r')\n male_names = names_file.readlines()\n\n names_file = open(\"static/populationScriptFiles/namesFemale.txt\", 'r')\n female_names = names_file.readlines()\n\n # Read in last names from file\n names_file = open(\"static/populationScriptFiles/namesLast.txt\", 'r')\n last_names = names_file.readlines()\n\n # Read in popular hobbies from file\n hobbies_file = open(\"static/populationScriptFiles/hobbies.txt\", 'r')\n hobby_names = hobbies_file.readlines()\n\n # Loop through to obtain a database of 100 users\n for new_person in range(0, 100):\n # Assign the user a random city\n random_city = random.randint(0, len(cities) - 1)\n\n # Create a new User and User profile object with a random name\n user_details = create_user_details(male_names, female_names, last_names, cities[random_city])\n\n # Assign the user random hobbies and languages\n create_hobbies(user_details, hobby_names)\n create_languages(user_details, random_city)\n\n # Save the new user\n user_details.profile.save()\n\n # Create user accounts for the markers to enable them to log in\n user_list = ['leifos', 'laura', 'david']\n created_city = City.objects.get(name=\"Glasgow\")\n\n # Loop through each of the three users\n for new_person in user_list:\n # Create a User object with their password set as their name\n new_user = User.objects.get_or_create(username=new_person, email=new_person + \"@hotmail.com\")[0]\n new_user.set_password(new_person)\n new_user.save()\n\n # Create a new User Profile object with Glasgow as the city\n new_user_profile = UserProfile.objects.get_or_create(user=new_user, city=created_city, )[0]\n new_user_profile.slug = new_person\n\n # Assign a random profile picture\n profile_picture = \"%s/profile_picture\" + str(random.randint(0, 4)) + \".jpg\"\n new_user_profile.profilepic = profile_picture % 'profile_pictures'\n\n # Save the new user profile\n new_user_profile.save()\n\n\n# Each user will leave a random amount of random reviews for other users to populate the rating tables\ndef leave_reviews():\n # Read in random reviews from file\n reviews_file = open(\"static/populationScriptFiles/reviews.txt\", 'r')\n reviews = reviews_file.readlines()\n\n # Get the list of all users from the database\n users = UserProfile.objects.all()\n\n # Loop through the list of all users\n for new_reviewer in users:\n\n # Put new_reviewer in users_reviewed so they never review themselves\n users_reviewed = [new_reviewer]\n\n # Each user will review random users between one and five times\n # This ensures that there is variation in the amount of reviews sent and received\n for new_review in range(random.randint(1, 5)):\n\n # Retrieved a random review (consisting of a comment and a star rating between 1 and 5) from the list\n new_rev = reviews[random.randint(0, len(reviews) - 1)].strip()\n\n # Split the review into a comment and a star rating (these are separated by a comma)\n new_rev = new_rev.split(', ', 2)\n rev = new_rev[0]\n rating = new_rev[1]\n\n # Obtain a random user from the list\n reviewee = users[random.randint(0, len(users) - 1)]\n\n # Ensure the random user has not already been reviewed by this user\n if reviewee not in users_reviewed:\n rev = UserRating.objects.get_or_create(user=reviewee, rating_user=new_reviewer, comment=rev,\n rating=int(rating))[0]\n\n # Add the reviewed users to the reviewed users list\n users_reviewed.append(reviewee)\n\n\nif __name__ == '__main__':\n create_users()\n leave_reviews()\n","sub_path":"populationScript.py","file_name":"populationScript.py","file_ext":"py","file_size_in_byte":10385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"602498834","text":"import pytest\n\nfrom users.fields import EmailSettingsField\n\n\n@pytest.mark.parametrize(\n 'arg, return_value', [\n (None, None),\n (str(), None),\n (dict(), None),\n (dict(notification_type='invalid'), None),\n ]\n)\ndef test_email_settings_field(arg, return_value):\n field = EmailSettingsField()\n\n assert field.process_setting(arg) is return_value\n","sub_path":"apps/users/tests/test_fields.py","file_name":"test_fields.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"128686947","text":"#!/usr/bin/env python\r\n# -- coding: utf-8 --\r\nimport sys\r\n\r\nfrom company_industry.config import *\r\nimport math\r\nimport operator\r\n\r\n\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf-8\")\r\n\r\nclass Namestat():\r\n def __init__(self):\r\n self.length_mean=13.2714529307\r\n self.length_std=3.12689307689\r\n self.three_std_upper=round(self.length_mean+self.length_std*3)\r\n self.three_std_lower = round(self.length_mean - self.length_std * 3)\r\n self.two_std_upper=round(self.length_mean+self.length_std*2)\r\n self.two_std_lower = round(self.length_mean - self.length_std * 2)\r\n\r\n\r\n def get_name_length(self):\r\n with open(target_name_path+'stat/name_length','w') as fw:\r\n input=open(target_data_path+'not_exist/not_exist_company_indid_industry_14','r')\r\n line=str(input.readline())\r\n counter=0\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n if counter%1000==0:\r\n print(counter)\r\n company_name=line.strip().split('\\x01')[0]\r\n u_company_name=company_name.decode('utf-8')\r\n length=len(u_company_name)\r\n fw.write(company_name+'\\x01'+str(length)+'\\n')\r\n line=str(input.readline())\r\n\r\n def statistic(self):\r\n input=open(target_name_path+'stat/name_length','r')\r\n line=str(input.readline())\r\n counter=0\r\n sum1=0\r\n sum2=0\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n print(counter)\r\n length=int(line.strip().split('\\x01')[1])\r\n sum1+=length\r\n sum2+=length**2\r\n line = str(input.readline())\r\n length_mean=sum1/counter\r\n length_var=sum2/counter-length_mean**2\r\n length_std=length_var**0.5\r\n return length_mean,length_std\r\n\r\n def get_three_std_length(self):\r\n '''\r\n 获取公司名称长度大于均值加3个标准差或小于均值减三个标准差的名称\r\n :return:\r\n '''\r\n with open(target_name_path+'stat/three_std_lenth','w') as fw:\r\n input=open(target_name_path+'stat/name_length','r')\r\n line=str(input.readline())\r\n counter=0\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n print(counter)\r\n if int(line.strip().split('\\x01')[1])>=self.three_std_upper or int(line.strip().split('\\x01')[1])<=self.three_std_lower:\r\n fw.write(str(counter)+'\\x01'+line)\r\n line=str(input.readline())\r\n\r\n def get_name_last_three(self):\r\n '''\r\n 获取公司名称中最后三个字组成的字典\r\n :return:\r\n '''\r\n with open(target_name_path+'stat/last_three_kw_dict_all','w') as fw:\r\n input = open(target_name_path + 'stat/name_length', 'r')\r\n line = str(input.readline())\r\n counter = 0\r\n last_three_dict={}\r\n while line != None and len(line) > 1:\r\n counter += 1\r\n print(counter)\r\n company_name=line.strip().split('\\x01')[0]\r\n last_three=company_name.decode('utf-8')[-3:]\r\n if last_three in last_three_dict:\r\n last_three_dict[last_three]+=1\r\n else:\r\n last_three_dict[last_three]=1\r\n line=str(input.readline())\r\n sort_last_three_dict=sorted(last_three_dict.iteritems(),key=operator.itemgetter(1),reverse=True)\r\n for k,v in sort_last_three_dict:\r\n fw.write(k+'\\x01'+str(v)+'\\n')\r\n\r\n\r\n def get_two_std_length(self):\r\n '''\r\n 获取公司名称长度大于均值加2个标准差或小于均值减2个标准差的名称\r\n :return:\r\n '''\r\n with open(target_name_path+'stat/two_std_lenth_all','w') as fw:\r\n input=open(target_name_path+'stat/name_length','r')\r\n line=str(input.readline())\r\n counter=0\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n print(counter)\r\n if int(line.strip().split('\\x01')[1])>=self.two_std_upper or int(line.strip().split('\\x01')[1])<=self.two_std_lower:\r\n fw.write(str(counter)+'\\x01'+line)\r\n line=str(input.readline())\r\n\r\n def get_last_specify(self):\r\n with open(target_name_path+'target/she_ends','w') as fw:\r\n input=open(target_name_path+'stat/last_three_kw_dict_two_std_all')\r\n line=str(input.readline())\r\n counter=0\r\n kw_dict={}\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n print(counter)\r\n kw=line.strip().split('\\x01')[0]\r\n if kw.endswith('社'):\r\n kw_dict[kw]=int(line.strip().split('\\x01')[1])\r\n line = str(input.readline())\r\n sort_kw_dict=sorted(kw_dict.iteritems(),key=operator.itemgetter(1),reverse=True)\r\n for k,v in sort_kw_dict:\r\n fw.write(k+'\\x01'+str(v)+'\\n')\r\n\r\n def get_last_three_target(self):\r\n with open(target_name_path+'target/last_three_kw_target_all','w') as fw:\r\n input=open(target_name_path+'stat/last_three_kw_dict_all')\r\n line=str(input.readline())\r\n counter=0\r\n while line!=None and len(line)>1:\r\n counter+=1\r\n print(counter)\r\n kw=line.strip().split('\\x01')[0]\r\n flag=0\r\n for k in ends:\r\n if kw.endswith(k):\r\n flag=1\r\n break\r\n if flag==1:\r\n line = str(input.readline())\r\n continue\r\n if kw in last_three_available_kw:\r\n line = str(input.readline())\r\n continue\r\n fw.write(line)\r\n line = str(input.readline())\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n model=Namestat()\r\n # model.get_name_length()\r\n # print(model.length_mean)\r\n # print(model.length_std)\r\n # print(model.three_std_upper)\r\n # print(model.three_std_lower)\r\n # model.get_three_std_length()\r\n # model.get_name_last_three()\r\n # model.get_two_std_length()\r\n # model.get_last_specify()\r\n model.get_last_three_target()\r\n","sub_path":"company_info_0/company_industry/data_name/name_statistic.py","file_name":"name_statistic.py","file_ext":"py","file_size_in_byte":6419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"333672585","text":"from django.db import models\n\n# user cloth number finished\nclass ZhongChou(models.Model):\n user = models.ManyToManyField('user.User', through = 'ZhongChouDetail')\n cloth = models.ForeignKey('cloth.Cloth', on_delete = models.CASCADE, )\n total_number = models.IntegerField()\n paid_number = models.IntegerField()\n finished = models.BooleanField()\n all_paid = models.BooleanField()\n start_time = models.DateTimeField(auto_now = False, auto_now_add = True)\n last_time = models.DateTimeField(auto_now = True, auto_now_add = False)\n\nclass ZhongChouDetail(models.Model):\n user = models.ForeignKey('user.User', on_delete = models.CASCADE, )\n zhongchou = models.ForeignKey('ZhongChou', on_delete = models.CASCADE, )\n number = models.IntegerField()\n paid = models.BooleanField()\n","sub_path":"zhongchou/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"1157043","text":"from iqBot.indicators.ichimoku import ichimokuHandle\nfrom iqBot.bots.botOperations import BotOperations\n\nclass Strats:\n def stratReport(self, botOps = BotOperations()):\n print('\\nStrat report:')\n print('Account initial balance: %s' % botOps.botInstance.initialBalance)\n print('Account current balance: %s' % botOps.botInstance.account.get_balance())\n print('---------------------------------------------')\n print('Account profit: $%s\\n' % botOps.__getProfit__())\n\n def baseLEDStrat(self, botOps = BotOperations(), iterations = 1):\n\n print('Executing baseLEDStrat...\\n')\n\n for _iteration in range(0, iterations):\n for currentVal in botOps.botInstance.values:\n botOps.createOrder(currentVal)\n botOps.reportOrder()\n \n if botOps.lastOrder['orderResult'] == 'win':\n break\n\n botOps.reportExecutionStats()\n self.stratReport(botOps=botOps)\n\n\n print('Execution completed')\n\n def holdLEDStrat(self, botOps = BotOperations(), iterations = 1):\n\n print('Executing holdLEDStrat...\\n')\n\n for _iteration in range(0, iterations):\n for currentVal in botOps.botInstance.values:\n botOps.createOrder(currentVal)\n botOps.reportOrder()\n botOps.holdOrder()\n \n if botOps.lastOrder['orderResult'] == 'win':\n break\n\n botOps.reportExecutionStats()\n self.stratReport(botOps=botOps)\n\n def reverseLEDStrat(self, botOps = BotOperations(), iterations = 1):\n\n print('Executing reverserLEDStrat...\\n')\n\n for _iteration in range(0, iterations):\n for currentVal in botOps.botInstance.values:\n botOps.createOrder(currentVal)\n botOps.reportOrder()\n botOps.reverseOperation()\n\n if botOps.lastOrder['orderResult'] == 'win':\n break\n \n botOps.reportExecutionStats()\n self.stratReport(botOps=botOps)\n\n def holdReverseLEDStrat(self, botOps = BotOperations(), iterations = 1):\n\n print('Executing holdReverseLEDStrat...\\n')\n\n for _iteration in range(0, iterations):\n for currentVal in botOps.botInstance.values:\n botOps.createOrder(currentVal)\n botOps.reportOrder()\n botOps.holdOrder()\n botOps.reverseOperation()\n\n if botOps.lastOrder['orderResult'] == 'win':\n break\n \n botOps.reportExecutionStats()\n self.stratReport(botOps=botOps)\n\n def askLEDStrat(self, botOps = BotOperations(), iterations = 1):\n \n print('Executing askLEDStrat...')\n\n originalOperation = botOps.botInstance.operation\n\n for _iteration in range(0, iterations):\n for currentVal in botOps.botInstance.values:\n botOps.createOrder(currentVal)\n botOps.reportOrder()\n response = botOps.askForOrder()\n\n if response:\n break\n \n if botOps.lastOrder['orderResult'] == 'win':\n \n break\n\n botOps.reportExecutionStats()\n self.stratReport(botOps=botOps)\n\n # def tenkanLEDStrat(self, botInstance = BotFunc(), ichimokuInstance = ichimokuHandle(), iterations = 1):\n\n # print('Executing tenkanLEDStrat...\\n')\n\n # for iteration in range(0, iterations):\n # botInstance.createOrderV2(botInstance.values, ichimokuInstance.tenkanOperation())\n # print('')\n # botInstance.reportOrderV2()\n # print('')\n # self.stratReport(botInstance)\n\n # print('Stats:')\n # print(dumps(botInstance.stats, indent=4))\n\n # def tenkanListLEDStrat(self, botInstance = BotFunc(), ichimokuInstance = ichimokuHandle(), iterations = 1):\n\n # print('Executing tenkanListLEDStrat...\\n')\n\n # for iteration in range(0, iterations):\n # for currentVal in botInstance.values:\n # botInstance.createOrderV2(currentVal, ichimokuInstance.tenkanOperation())\n # print('')\n # botInstance.reportOrder()\n # print('')\n\n # if botInstance.lastOrder['orderResult'] == 'win':\n # break\n\n # self.stratReport(botInstance)\n\n # print('Stats:')\n # print(dumps(botInstance.stats, indent=4))","sub_path":"iqBot/strats/strats.py","file_name":"strats.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"247413787","text":"\"\"\" This module processes the dataset Massachusetts obained from https://www.cs.toronto.edu/~vmnih/data/.\n\nThe original dataset contains sattelite images of Massachusetts and its surroundings. The images are\nofsize 1500x1500, 3 channels, TIFF format. The dataset also contains separate labels for roads and\nbuildings. This mdule only processes the road dataset.\n\nProcessing: Adjusted for the needs of Project 2, Machine Learning course, EPFL (fall 2016). Since\nthe original sattelite images are of different zoom level and size than the dataset provided for the project,\nit needs to be rescaled and cropped (both the sattelite image and its corresponding mask). From each original\nimage the non-overlaping patches are taken and only those that contain at least `maskWhitePxRatioTh` * 100\npercent of roads are kept. The resulting patches are stored in `outputPath` directory.\n\n\"\"\"\n\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport os\nimport numpy as np\n\n########################################################################################################################\n# INPUT PARAMETERS\n########################################################################################################################\n\n# Input dataset path.\ninputPath = '../../../ext_data/massachusetts/original/'\noutputPath = '../../../ext_data/massachusetts/patches/'\nmapDir = 'map'\nsatDir = 'sat'\n\n# Threshold for all-white parts of the sattelite images - ratio of white pixels (intensity == 255). If the white/other\n# ratio is higher than this threshold, the image is dropped.\nwhitePxRatioTh = 0.001\n# Threshold of roads vs. background within mask patch - if the roads/background ratio is lower then this threshold,\n# the patch is dropped.\nmaskWhitePxRatioTh = 0.005\n\n# Upscale image and mask ratio.\nupscale = (2.0, 2.0)\npatchSize = (400, 400)\n\n########################################################################################################################\n# MAIN SCRIPT\n########################################################################################################################\n\nimagesFiles = [im for im in os.listdir(inputPath + satDir) if im.endswith('.tiff')]\n\nnumFiles = len(imagesFiles)\n\nfor idx, imgFile in enumerate(imagesFiles):\n print('Processing image {im} / {tot}'.format(im=idx + 1, tot=numFiles))\n\n # Load satelite image.\n img = Image.open(inputPath + satDir + '/' + imgFile)\n assert(img.mode == 'RGB')\n\n # Get image size.\n imgSize = img.size\n\n # Convert image to grayscale.\n gsImg = img.convert(mode='L')\n hist = gsImg.histogram()\n\n whitePxRatio = float(hist[255]) / (imgSize[0] * imgSize[1])\n\n # If the image contains no or insignificant white parts, process it further.\n if whitePxRatio < whitePxRatioTh:\n # Load ground truth road binary mask\n try:\n gtMask = Image.open(inputPath + mapDir + '/' + imgFile)\n except:\n print('Error: cannot open ground truth binary mask file {f}'.format(f=inputPath + mapDir + '/' + imgFile))\n continue\n\n # Check that mask's size matches the corresponding image.\n assert(gtMask.size == imgSize)\n\n # Upscale the image and the mask. For upsampling, nearest neighbour (NEAREST) is used.\n # Another possible option is BICUBIC (only for sattelite img), which, however, blurs the image. We need to experiment\n # to find out which one is better.\n newSize = (int(imgSize[0] * upscale[0]), int(imgSize[1] * upscale[1]))\n imgSize = newSize\n\n # Check that at least one patch can fit in the original image.\n assert(newSize[0] // patchSize[0] > 0)\n assert(newSize[1] // patchSize[1] > 0)\n\n img = img.resize(newSize, resample=Image.NEAREST)\n gtMask = gtMask.resize(newSize, resample=Image.NEAREST)\n\n # Generate x,y coordinates of centers of patches.\n left = 0\n right = imgSize[0] - patchSize[0]\n top = 0\n bottom = imgSize[1] - patchSize[1]\n\n numPatchesInRow = imgSize[0] // patchSize[0]\n numPatchesInCol = imgSize[1] // patchSize[1]\n\n centersInRow = np.linspace(left, right, numPatchesInRow, dtype=np.int32)\n centersInCol = np.linspace(top, bottom, numPatchesInCol, dtype=np.int32)\n\n # Coordinates of patches (left, top, right, bottom)\n patchesCoords = [(l, t, l + patchSize[0], t + patchSize[1]) for t in centersInCol for l in centersInRow]\n\n # Process each patch\n for pc in patchesCoords:\n # Get a patch of img and mask.\n patchMask = gtMask.crop(pc)\n patchImg = img.crop(pc)\n\n # Check correct size of a patch.\n assert(patchMask.size == patchSize)\n\n # Find the ratio of white pixels (roads) to black pixels (background).\n patchMaskHist = patchMask.histogram()\n maskWhitePxRatio = float(patchMaskHist[255]) / (patchSize[0] * patchSize[1])\n\n # Check whether there is sufficient amount of roads in this patch and if so, save the patch (img and mask).\n if maskWhitePxRatio > maskWhitePxRatioTh:\n nameSuffix = '_(' + str(pc[1] + patchSize[1] // 2) + ', ' + str(pc[0] + patchSize[0] // 2) + ')'\n name = imgFile[:-5] + nameSuffix + '.tiff'\n\n patchImg.save(outputPath + satDir + '/' + name)\n patchMask.save(outputPath + mapDir + '/' + name)\n","sub_path":"project2/utils/images2patches.py","file_name":"images2patches.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"482253199","text":"import formatos\nformatos.entrada(36)\nformatos.azul()\nvlr_casa = float(input('Valor total do ímovel (R$): '))\nsalario = float(input('Salário do comprador: '))\nanos = int(input('Quantos anos deseja pagar: '))\nqtd_p = anos * 12\nif vlr_casa / qtd_p > 0.30 * salario:\n formatos.vermelho()\n print(f'De acordo com o valor do ímovel R${vlr_casa:.2f} em {qtd_p} parcelas, o financiamento foi negado!')\n formatos.amarelo()\n print('\\nVocê pode tentar com mais parcelas...')\nelse:\n formatos.verde()\n print(f'Parábens, seu empréstimo foi aprovado!')\n formatos.amarelo()\n print('\\nSegue relação:\\n')\n formatos.azul()\n print(f'Valor total do ímovel: R$ {vlr_casa:.2f}\\nQuantidades de parcelas {qtd_p}\\nFinaciamento previsto em {anos} anos\\nValor da parcela R$ {vlr_casa / qtd_p:.2f}')\nformatos.saida(36)","sub_path":"meus_exercicios_py/ex036.py","file_name":"ex036.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"424677332","text":"# vim:fileencoding=utf-8:ts=2:sw=2:expandtab\n\nfrom AppStruct.Security import SHA1\n\n'''\n\nin Init():\n yield\n\n App.AuthStack = Project.ACRM.Auth.AuthStack(self.UserSession.AuthStack)\n\n\n# For the checkbox at the top of the UI:\nApp.AuthStack.HasAdmin\n\n# For the checkiness of the checkbox at the top of the UI\nApp.AuthStack.AdminMode\n\n# For setting / unsetting the checkbox at the top of the UI\nApp.AuthStack.AdminMode = True/False\n\n# For the checkbox at the top of the UI:\nApp.AuthStack.HasContent\n\n# For the checkiness of the checkbox at the top of the UI\nApp.AuthStack.ContentMode\n\n# For setting / unsetting the checkbox at the top of the UI\nApp.AuthStack.ContentMode = True/False\n\n# For access to the current user\nApp.AuthStack.Account_Contact\n\n\n'''\n \nclass AuthStack():\n '''\n Object information is stored in a redis list. \n Each list item is a JSON encoded object (str)\n {\n 'Account_Contact_MNID' : integer ID\n 'AdminMode' : bool\n 'LastURI' : string\n }\n\n '''\n\n def __init__(self, RedisKey):\n self.RedisKey = RedisKey\n\n # Get the auth stack from redis hash\n try:\n App.Log(App.Redis.lrange_str(self.RedisKey, 0, -1))\n RedisAuthStack = [JD(v) for v in App.Redis.lrange_str(self.RedisKey, 0, -1)]\n ids = [o['Account_Contact_MNID'] for o in RedisAuthStack]\n except Exception as e:\n App.Redis.delete(self.RedisKey)\n raise\n \n\n # Lookup all the users in the stack\n if len(RedisAuthStack) > 0:\n usermap = App.DB.RowDict('''\n SELECT\n \"Account_Contact_MNID\",\n \"Account_MNID\",\n \"FirstName\" || ' ' || \"LastName\" AS \"Name\",\n \"SuperUser\"\n FROM \n \"ACRM\".\"Account_Contact\"\n WHERE True\n AND \"Account_Contact_MNID\" = ANY ($ids::int4[])\n ''',\n ids=ids\n )\n\n \n # Build our object list\n # The object list is composed of what comes from redis and what comes from the query above\n # Information like Name and SuperUser are NOT cached in Redis.\n self._Stack = []\n\n try:\n for i,stackitem in enumerate(RedisAuthStack):\n user = usermap[stackitem['Account_Contact_MNID']]\n \n self._Stack.append(aadict(\n Account_Contact_MNID = user.Account_Contact_MNID,\n Account_MNID = user.Account_MNID,\n Name = user.Name,\n SuperUser = user.SuperUser,\n AdminMode = stackitem['AdminMode'],\n ContentMode = stackitem['ContentMode'],\n LastURI = stackitem['LastURI'],\n ))\n\n except Exception:\n # This is in the case that a logged in ID was not found or something bizarre\n # Best case is to log them out and let them log in again.\n App.Redis.delete(self.RedisKey)\n raise\n \n\n def _SaveTipToRedis(self):\n '''\n This will save the tip of the AuthStack to redis.\n '''\n\n index = len(self._Stack) - 1\n\n if index < 0:\n raise InvalidOperation('The stack is empty')\n\n stackitem = JE(dict(\n Account_Contact_MNID = self._Stack[index].Account_Contact_MNID,\n AdminMode = self._Stack[index].AdminMode,\n ContentMode = self._Stack[index].ContentMode,\n LastURI = self._Stack[index].LastURI,\n ))\n\n App.Redis.lset_str(self.RedisKey, index, stackitem)\n\n\n def Hit(self, MinExpire=3600):\n '''\n Call this function every time a user visits the site.\n It updates the TTL to a minimum of 1 hour\n '''\n ttl = App.Redis.ttl(self.RedisKey) or 0\n if ttl < MinExpire:\n App.Redis.expire(self.RedisKey, MinExpire+300)\n\n \n def SetLastURI(self, URI):\n if len(self._Stack):\n self._Stack[-1].LastURI = URI\n self._SaveTipToRedis()\n \n \n def Clear(self):\n '''\n Call this function to zap the auth stack and log out unconditionally\n '''\n self._Stack = []\n App.Redis.delete(self.RedisKey)\n\n def Push(self, Account_Contact_MNID, *, RememberMe=False):\n \n stackitem = JE(dict(\n Account_Contact_MNID = Account_Contact_MNID,\n AdminMode = False,\n ContentMode = False,\n LastURI = None,\n ))\n\n # Add to (or create the) stack in redis\n App.Redis.rpush_str(self.RedisKey, stackitem)\n \n # Very important to set the TTL on this redis key\n self.Hit(MinExpire = 86400*30 if RememberMe else 3600)\n\n # Reload this object\n self.__init__(self.RedisKey)\n \n def Pop(self):\n App.Redis.rpop(self.RedisKey)\n \n # Reload this object\n self.__init__(self.RedisKey)\n\n @property\n def HasAdmin(self):\n '''\n Returns true if any user in this auth stack has SuperUser permissions\n '''\n for stackitem in self._Stack:\n if stackitem.SuperUser:\n return True\n else:\n return False\n \n def AdminMode_get(self):\n '''\n Fast inquiry as to if this set of users can enable AdminMode\n '''\n if len(self._Stack):\n return self._Stack[-1].AdminMode\n else:\n return False\n\n\n def AdminMode_set(self, value):\n '''\n Call this to enable or disable admin mode\n '''\n if len(self._Stack):\n self._Stack[-1].AdminMode = (bool(value) if self.HasAdmin else False)\n self._SaveTipToRedis()\n\n\n # Create the read/write property\n AdminMode = property(AdminMode_get, AdminMode_set)\n \n @property\n def HasContent(self):\n '''\n Returns true if any user in this auth stack has SuperUser permissions\n '''\n for stackitem in self._Stack:\n if stackitem.SuperUser:\n return True\n else:\n return False\n \n def ContentMode_get(self):\n '''\n Fast inquiry as to if this set of users can enable ContentMode\n '''\n if len(self._Stack):\n return self._Stack[-1].ContentMode\n else:\n return False\n\n\n def ContentMode_set(self, value):\n '''\n Call this to enable or disable admin mode\n '''\n if len(self._Stack):\n self._Stack[-1].ContentMode = (bool(value) if self.HasContent else False)\n self._SaveTipToRedis()\n\n\n # Create the read/write property\n ContentMode = property(ContentMode_get, ContentMode_set)\n \n \n @property\n def Account_Contact_MNID(self):\n if self.IsAuthenticated:\n return self._Stack[-1].Account_Contact_MNID\n else:\n return None\n \n @property\n def Account_MNID(self):\n if self.IsAuthenticated:\n return self._Stack[-1].Account_MNID\n else:\n return None\n\n @property\n def NameList(self):\n return [row.Name for row in self._Stack]\n \n @property\n def Name(self):\n return None if len(self._Stack) == 0 else self._Stack[-1].Name\n\n @property\n def Stack(self):\n return list(self._Stack)\n\n @property\n def IsAuthenticated(self):\n return len(self._Stack) > 0\n \n @property\n def IsImpersonating(self):\n return len(self._Stack) > 1\n \n @property\n def LastURI(self):\n return self._Stack[-1].LastURI if len(self._Stack) else None\n\n @property\n def JSON(self):\n return JE([{'Account_Contact_MNID': row.Account_Contact_MNID} for row in self._Stack])\n\n\n\n###############################################################################\ndef SaltAndHashPassword(Username, Password):\n Salt = App.DB.Value('''\n SELECT \n \"Login_Password_Salt\"\n FROM \n \"ACRM\".\"Account_Contact\" \n WHERE true\n AND \"Login_Username\" = $A\n ''',\n A = Username,\n )\n return SHA1(Password + Salt)\n\n\n###############################################################################\ndef AuthenticateByUsernameAndPassword(Username, Password):\n '''\n Returns a Account_Contact_MNID in the event that the authentication was successful\n '''\n try:\n Password_Hash = SaltAndHashPassword(Username, Password)\n Account_Contact_MNID = App.DB.Value('''\n SELECT \n \"Account_Contact_MNID\"\n FROM \n \"ACRM\".\"Account_Contact\" \n WHERE true\n AND \"Login_Username\" = $A\n AND \"Login_Password_Hash\"= $B\n ''',\n A = Username,\n B = Password_Hash\n )\n except App.DB.NotOneFound:\n raise AuthenticationError('Oops, we didn\\'t recognize that username or password, please try again')\n\n return Account_Contact_MNID\n\n\n","sub_path":"Python/ACRM/Auth.py","file_name":"Auth.py","file_ext":"py","file_size_in_byte":8175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"48122429","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\n\nfrom pecan.testing import load_test_app\n\nfrom tuskar.tests import base\n\n\nURL_PLANS = '/v2/plans'\n\n\nclass PlansTests(base.TestCase):\n\n def setUp(self):\n super(PlansTests, self).setUp()\n\n config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n '..', '..', '..', '..', 'api', 'config.py')\n self.app = load_test_app(config_file)\n\n def test_get_all(self):\n # Setup\n\n # Test\n response = self.app.get(URL_PLANS)\n result = response.json\n\n # Verify\n self.assertEqual(response.status_int, 200)\n self.assertTrue(isinstance(result, list))\n self.assertEqual(1, len(result))\n self.assertEqual(result[0]['name'], 'foo')\n\n def test_get_one(self):\n # Setup\n\n # Test\n url = URL_PLANS + '/' + 'qwerty12345'\n response = self.app.get(url)\n result = response.json\n\n # Verify\n self.assertEqual(response.status_int, 200)\n self.assertEqual(result['name'], 'foo')\n\n def test_delete(self):\n # Test\n url = URL_PLANS + '/' + 'qwerty12345'\n response = self.app.delete(url)\n\n # Verify\n self.assertEqual(response.status_int, 204)\n\n def test_post(self):\n # Setup\n plan_data = {'name': 'new'}\n\n # Test\n response = self.app.post_json(URL_PLANS, params=plan_data)\n result = response.json\n\n # Verify\n self.assertEqual(response.status_int, 201)\n self.assertEqual(result['name'], plan_data['name'])\n\n def test_templates(self):\n # Setup\n\n # Test\n url = URL_PLANS + '/' + 'foo' + '/' + 'templates'\n response = self.app.get(url)\n result = response.body\n\n # Verify\n self.assertEqual(response.status_int, 200)\n self.assertEqual(result, 'foo')\n\n def test_patch(self):\n # Setup\n plan_data = {'name': 'new'}\n\n # Test\n url = URL_PLANS + '/' + 'qwert12345'\n response = self.app.patch_json(url, plan_data)\n result = response.json\n\n # Verify\n self.assertEqual(response.status_int, 201)\n self.assertEqual(result['name'], plan_data['name'])\n","sub_path":"tuskar/tests/api/controllers/v2/test_plans.py","file_name":"test_plans.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"176076869","text":"'''\nGiven an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.\n\nFor example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].\n\nFollow-up: what if you can't use division?\n\n'''\n\nimport math\n\ndef solve(arr):\n new_arr = []\n res = 0\n\n for i in arr:\n res += math.log(i, 10)\n \n for i in arr:\n new_arr.append(res-math.log(i, 10))\n\n\n\n for i in range(len(arr)):\n new_arr[i] = round(10**(new_arr[i]))\n\n return new_arr\n\n\nprint(*solve(list(map(int, input().split()))))\n\n\n","sub_path":"Problem#2.py","file_name":"Problem#2.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"30025644","text":"import os\nfrom itertools import product\nfrom collections import defaultdict\nfrom subprocess import call, STDOUT, DEVNULL\n\nFONT = 'Helvetica'\nFONTSIZE = 48\nINKSCAPE_PATH = '/opt/local/bin/inkscape'\n\ntemplate = '''\n\t{label}\n'''\n\ndef make_image(out_dir, english_words, thai_words):\n\tfilename = ''.join(english_words)\n\tfilepath = os.path.join(out_dir, filename)\n\tthai_string = ''.join(thai_words)\n\tsvg = template.format(label=thai_string, font=FONT, fontsize=FONTSIZE)\n\twith open(filepath + '.svg', mode='w', encoding='utf-8') as file:\n\t\tfile.write(svg)\n\tcall([INKSCAPE_PATH, filepath + '.svg', '-e', filepath + '.png'], stdout=DEVNULL, stderr=STDOUT)\n\tcall(['rm', filepath + '.svg'])\n\ndef load_words(csv_file):\n\twords_by_category = defaultdict(list)\n\twith open(csv_file, encoding='utf-8') as file:\n\t\tfor i, line in enumerate(file):\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\teng, thai, trans, category = line.strip().split(',')\n\t\t\twords_by_category[category].append((eng, thai))\n\t\t\tif category in ['adj', 'dem', 'num']:\n\t\t\t\twords_by_category['mod'].append((eng, thai))\n\treturn words_by_category\n\ndef iter_words_orders(words_by_category, word_order):\n\tword_sets = [words_by_category[category] for category in word_order]\n\tfor label_combination in product(*word_sets):\n\t\tenglish_words = [word_pair[0] for word_pair in label_combination]\n\t\tthai_words = [word_pair[1] for word_pair in label_combination]\n\t\tyield english_words, thai_words\n\ndef make_images_in_whatever_fucking_word_orders_you_want(csv_file, out_dir, word_orders):\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n words_by_category = load_words(csv_file)\n for word_order in word_orders:\n for english_words, thai_words in iter_words_orders(words_by_category, word_order):\n fileName = out_dir+''.join(english_words)+'.png'\n # print(fileName)\n if not os.path.isfile(fileName):\n make_image(out_dir, english_words, thai_words)\n\n\nwordOrders = [\n ('mod','noun'),\n ('noun','mod'),\n ('dem','adj','noun'),\n ('adj','dem','noun'),\n ('dem','num','noun'),\n ('num','dem','noun'),\n ('num','adj','noun'),\n ('adj','num','noun'),\n ('noun','adj','num'),\n ('noun','num','adj'),\n ('noun','dem','num'),\n ('noun','num','dem'),\n ('noun','dem','adj'),\n ('noun','adj','dem')\n]\n\nwordOrders = [\n ('noun','mod'),\n ('noun','adj','dem'),\n ('noun','adj','num'),\n ('noun','num','dem')\n]\n \n\n \nmake_images_in_whatever_fucking_word_orders_you_want('../stimuli/tha/vocab.csv', out_dir='../stimuli/tha/images/BIG', word_orders=wordOrders)\n\n","sub_path":"POS/Thai/lab/scripts/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"208320964","text":"from flask import Flask,jsonify\nfrom flask_restful import Api\nfrom flask_jwt_extended import JWTManager\nfrom resources.user import Register,UserLogin\nfrom resources.registration import Vech_Reg,Reg_Status,DismissVech,DeleteVech,Stats,UserRegs\nfrom resources.payments import FinePayments,PaymentStats\n\napp=Flask(__name__)\napp.config['PROPAGATE_EXCEPTIONS']=True\napp.config['JWT_SECRET_KEY']='coscskillup'\napi=Api(app)\njwt=JWTManager(app)\n\n\n\n@jwt.unauthorized_loader\ndef missing_token_callback(error):\n return jsonify({\n 'error': 'authorization_required',\n \"description\": \"Request does not contain an access token.\"\n }), 401\n\n\n@jwt.invalid_token_loader\ndef invalid_token_callback(error):\n return jsonify({\n 'error': 'invalid_token',\n 'message': 'Signature verification failed.'\n }), 401\n\n\napi.add_resource(Register,'/register')\napi.add_resource(UserLogin,'/login')\napi.add_resource(Vech_Reg,'/vechreg')\napi.add_resource(Reg_Status,'/pending')\napi.add_resource(DismissVech,'/dismiss')\napi.add_resource(Stats,'/regstats')\napi.add_resource(FinePayments,'/fine')\napi.add_resource(DeleteVech,'/delete')\napi.add_resource(PaymentStats,'/paymentstats')\napi.add_resource(UserRegs,'/regsuser')\n\nif __name__=='__main__':\n app.run()\n","sub_path":"API/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"356475916","text":"import json\n\nfrom django.test import TestCase\nfrom freezegun import freeze_time\nfrom rest_framework.reverse import reverse\nfrom rest_framework.test import APIClient\n\nfrom .factories import NoteFactory, PatientFactory, UserFactory\n\n\nclass NoteViewsTestCase(TestCase):\n\n def setUp(self, *args, **kwargs):\n super().setUp(*args, **kwargs)\n self.client = APIClient()\n self.user = UserFactory()\n self.client.force_authenticate(user=self.user)\n self.note_list_url = reverse('core:note-list')\n\n def test_notes_list(self):\n NoteFactory.create_batch(10)\n NoteFactory.create_batch(3, nutritionist=self.user)\n response = self.client.get(self.note_list_url)\n data = json.loads(response.content)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data), 3)\n\n @freeze_time('2021-05-04 13:08:03')\n def test_notes_create(self):\n patient = PatientFactory()\n self.user.patients.add(patient)\n response = self.client.post(self.note_list_url,\n data={'description': 'This patient is very sick', 'patient': patient.id},\n format='json')\n self.user.refresh_from_db()\n note = patient.notes.first()\n self.assertEqual(response.status_code, 201)\n self.assertEqual(self.user.patients.count(), 1)\n self.assertEqual(json.loads(response.content),\n {'id': note.id,\n 'description': note.description,\n 'patient': patient.id,\n 'nutritionist': self.user.id,\n 'date': '2021-05-04T13:08:03Z'})\n","sub_path":"core/tests/test_notes.py","file_name":"test_notes.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"59186809","text":"import Rhino\nimport scriptcontext\nimport System.Guid\n\ndef OrientOnSrf():\n # Select objects to orient\n go = Rhino.Input.Custom.GetObject()\n go.SetCommandPrompt(\"Select objects to orient\")\n go.SubObjectSelect = False\n go.GroupSelect = True\n go.GetMultiple(1, 0)\n if go.CommandResult()!=Rhino.Commands.Result.Success:\n return go.CommandResult()\n\n # Point to orient from\n gp = Rhino.Input.Custom.GetPoint()\n gp.SetCommandPrompt(\"Point to orient from\")\n gp.Get()\n if gp.CommandResult()!=Rhino.Commands.Result.Success:\n return gp.CommandResult()\n\n # Define source plane\n view = gp.View()\n if not view:\n view = doc.Views.ActiveView\n if not view: return Rhino.Commands.Result.Failure\n\n source_plane = view.ActiveViewport.ConstructionPlane()\n source_plane.Origin = gp.Point()\n\n # Surface to orient on\n gs = Rhino.Input.Custom.GetObject()\n gs.SetCommandPrompt(\"Surface to orient on\")\n gs.GeometryFilter = Rhino.DocObjects.ObjectType.Surface\n gs.SubObjectSelect = True\n gs.DeselectAllBeforePostSelect = False\n gs.OneByOnePostSelect = True\n gs.Get()\n if gs.CommandResult()!=Rhino.Commands.Result.Success:\n return gs.CommandResult()\n\n objref = gs.Object(0)\n # get selected surface object\n obj = objref.Object()\n if not obj: return Rhino.Commands.Result.Failure\n # get selected surface (face)\n surface = objref.Surface()\n if not surface: return Rhino.Commands.Result.Failure\n # Unselect surface\n obj.Select(False)\n\n # Point on surface to orient to\n gp.SetCommandPrompt(\"Point on surface to orient to\")\n gp.Constrain(surface, False)\n gp.Get()\n if gp.CommandResult()!=Rhino.Commands.Result.Success:\n return gp.CommandResult()\n\n # Do transformation\n rc = Rhino.Commands.Result.Failure\n getrc, u, v = surface.ClosestPoint(gp.Point())\n if getrc:\n getrc, target_plane = surface.FrameAt(u,v)\n if getrc:\n # Build transformation\n xform = Rhino.Geometry.Transform.PlaneToPlane(source_plane, target_plane)\n # Do the transformation. In this example, we will copy the original objects\n delete_original = False\n for i in range(go.ObjectCount):\n rhobj = go.Object(i)\n scriptcontext.doc.Objects.Transform(rhobj, xform, delete_original)\n scriptcontext.doc.Views.Redraw()\n rc = Rhino.Commands.Result.Success\n return rc\n\n\nif __name__==\"__main__\":\n OrientOnSrf()\n","sub_path":"rhinocommon/snippets/py/orient-on-surface.py","file_name":"orient-on-surface.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"98188307","text":"from django.conf.urls import url\r\nfrom . import views\r\n\r\napp_name = 'AuT'\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n\r\n url(r'^register/$', views.UserFormView.as_view(), name='register'),\r\n\r\n url(r'^(?P[0-9]+)/$', views.DetailView, name='detail'), \r\n\r\n url(r'^atividade/add/$', views.AtividadeCreate.as_view(), name='atividade-add'),\r\n\r\n url(r'^sobre/$', views.about, name='sobre'),\r\n\r\n url(r'^contato/$', views.contato, name='contato'),\r\n\r\n url(r'^login/$', views.login_user, name='login_user'),\r\n\r\n url(r'^home/$', views.home, name='home'),\r\n\r\n url(r'^logout_user/$', views.logout_user, name='logout_user'),\r\n\r\n url(r'^dados/$', views.dados, name='dados'),\r\n\r\n url(r'^atividade/$', views.atividade, name='atividade'),\r\n\r\n url(r'^(?P[0-9]+)/atividade/$', views.detail_atividade, name='detail_atividade'),\r\n\r\n url(r'^create_atividade/$', views.create_atividade, name='create_atividade'),\r\n\r\n url(r'^test/$', views.create_test, name='test'),\r\n\r\n url(r'^reconfiguracao/$', views.reconfiguracao, name='reconfiguracao'),\r\n\r\n url(r'^reconfiguracao_paciente/(?P.*)$', views.reconfiguracao_paciente, name='reconfiguracao_paciente'),\r\n\r\n url(r'^(?P[0-9]+)/reconfiguracao/$', views.detail_reconfiguracao, name='detail_reconfiguracao'),\r\n\r\n url(r'^create_reconfig/$', views.create_reconfig.as_view(), name='create_reconfig'),\r\n\r\n url(r'^reconfig/$', views.reconfig, name='reconfig'),\r\n\r\n #url(r'^addpaciente/$', views.create_paciente, name='addpaciente'),\r\n\r\n #url(r'^atividade/add/$', views.AtividadeUpdate.as_view(), name='atividade-update'),\r\n\r\n #url(r'^atividade/delete/$', views.AtividadeDelete.as_view(), name='atividade-delete'),\r\n] ","sub_path":"AuT/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"268974641","text":"## Script (Python) \"sendThisMail\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=ObjectId, sender=''\n##title=Low level sending email management\n##\n\"\"\"\nGestione centralizzata di invio mail\n\nN.B.:\n 1. Se necessario creare lo script mail_args nella cartella resources del\nPlominoDatabase per customizzare le mail. Lo script deve prendere in\ningresso, nell'ordine, il PlominoDocument in contesto e l'id del messaggio.\nLo script deve restituire un dizionario, sulla falsa riga di custom_args\nqui sotto, degli argomenti dello script sendMail.\n 2. ObjectId: se possibile usare l'id detta transizione\n\"\"\"\n\nfrom gisweb.utils import sendMail\n\nmsg_info = dict(\n numero_pratica = context.getItem('numero_pratica'),\n titolo = context.Title(),\n now = DateTime().strftime('%d/%m/%Y')\n )\n\nargs = dict(\n To = context.getItem('fisica_email'),\n From = sender\n)\n\ncustom_args = dict()\ndb = context.getParentDatabase()\n\nif 'mail_args' in db.resources.keys():\n custom_args = db.resources.mail_args(context, ObjectId)\n\nif not custom_args:\n\n if ObjectId==\"assegna\":\n\n msg_info.update(dict(\n attach = 'domanda_inviata.pdf',\n ))\n\n custom_args = dict(\n Object = 'Avvio del Procedimento pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = '''\nSi comunica che in data %(now)s è stato avviato il procedimento n. %(numero_pratica)s.\n''' % msg_info,\n Attachment = '' if not msg_info['attach'] in context.getFilenames() else context[msg_info['attach']],\n Attachment_name = msg_info['attach'],\n )\n\n elif ObjectId == \"integra\":\n\n msg_info.update(dict(\n attach = 'integrazione.pdf',\n ))\n\n custom_args = dict(\n Object = 'Integrazione pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = \"\"\"\nSi comunica che in data %(now)s il procedimento n. %(numero_pratica)s è stato integrato.\n\"\"\" % msg_info,\n Attachment = '' if not msg_info['attach'] in context.getFilenames() else context[msg_info['attach']],\n Attachment_name = msg_info['attach'],\n )\n\n elif ObjectId == 'autorizza':\n\n custom_args = dict(\n Object = 'Autorizzazione pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = \"\"\"Si comunica che in data %(now)s il procedimento n. %(numero_pratica)s è stato autorizzato.\n\"\"\" % msg_info\n )\n\n elif ObjectId == 'rigetta':\n\n custom_args = dict(\n Object = 'Diniego pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = \"\"\"\nSi comunica che in data %(now)s il procedimento n. %(numero_pratica)s è stato rigettato\n\"\"\" % msg_info\n )\n\n elif ObjectId == 'preavviso_rigetto':\n\n msg_info.update(dict(\n motivazione = context.getItem('motivazione_rigetto',''),\n ))\n\n custom_args = dict(\n Object = 'Preavviso Rigetto pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = \"\"\"\nSi comunica che in data %(now)s il procedimento n. %(numero_pratica)s è\nin preavviso di rigetto con le seguenti motivazioni:\n\n%(motivazione)s\n\n\"\"\" % msg_info\n )\n\n elif ObjectId == 'sospendi':\n\n msg_info.update(dict(\n motivazione = context.getItem('motivazione_sospensione',''),\n ))\n\n custom_args = dict(\n Object = 'Sospensione pratica. n. %(numero_pratica)s - %(titolo)s' % msg_info,\n Text = \"\"\"\nSi comunica che in data %(now)s il procedimento n. %(numero_pratica)s è\nstato sospeso con le seguenti motivazioni:\n\n%(motivazione)s\n\n\"\"\" % msg_info\n )\n\n\nif custom_args:\n args.update(custom_args)\n sendMail(**args)\n","sub_path":"src/gisweb/iol/skins/iol_scripts/sendThisMail.py","file_name":"sendThisMail.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"352334187","text":"#5.\tВ массиве найти максимальный отрицательный элемент.\n# Вывести на экран его значение и позицию (индекс) в массиве.\n\nfrom random import randint\n\nLST = []\nfor i in range(10):\n LST.append(randint(-5, 2))\nprint(LST, '\\n')\n\n# v1\nprint(f\"Максимальный отрицательный элемент: {max([i for i in LST if i < 0])}, \"\n f\"его позиция {LST.index(max([i for i in LST if i < 0]))}.\")\n\n# v2\nMIN = 0\nfor i in LST:\n if i < MIN:\n MIN = i\nGR = MIN\nfor i, el in enumerate(LST):\n if GR < el < 0:\n GR = el\n GRI = i\nprint(f\"Максимальный отрицательный элемент: {GR}, \"\n f\"его позиция {GRI}.\")\n","sub_path":"Lesson_3/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"590712773","text":"# coding=utf-8\n# n! means n × (n − 1) × ... × 3 × 2 × 1\n# \n# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\n# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n# \n# Find the sum of the digits in the number 100!\n\n\ni = 100\nprod = 1\n\nwhile i > 0:\n prod = prod * i\n i = i - 1\n \nnum = str(prod)\nsum = 0\n\nfor letter in num:\n sum = sum + int(letter)\n\nprint(sum)\n","sub_path":"020.py","file_name":"020.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"432048488","text":"import json\nfrom shutil import copyfile\n\nimport aiofiles\nimport aiohttp\nimport discord\nfrom discord.ext import commands\nfrom discord_slash import cog_ext\n\nimport my.sql as mysql\nfrom image.img import Generator\n\n\nclass Top(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @staticmethod\n async def global_top(ctx):\n levels = json.loads((await mysql.Connexion().get(ctx.guild.id))[1])\n\n if len(levels) >= 5:\n\n users = []\n for x in levels:\n users.append([x, levels[x][\"level\"], levels[x][\"xp\"]])\n\n def _cshort(e):\n return e[1], e[2]\n\n users.sort(key=_cshort, reverse=True)\n\n data = []\n\n for x in range(5):\n try:\n user = await ctx.guild.fetch_member(int(users[x][0]))\n\n db_user = users[x]\n\n reqxp = round((((db_user[1] ** 2) + 50 + (db_user[1] * 10)) * 2.5))\n\n data.append(\n {\"pseudo\": user.name,\n \"couleur\": user.color.to_rgb(),\n \"percent\": db_user[2] * 100 / reqxp,\n \"level\": db_user[1]})\n\n async with aiohttp.ClientSession() as session:\n url = str(user.avatar_url_as(format=\"png\", static_format=\"png\", size=512))\n async with session.get(url) as resp:\n f = await aiofiles.open('image/{}avatar.png'.format(x), mode='wb')\n await f.write(await resp.read())\n await f.close()\n except discord.errors.NotFound:\n db_user = users[x]\n\n reqxp = round((((db_user[1] ** 2) + 50 + (db_user[1] * 10)) * 2.5))\n data.append({\"pseudo\": \"Utilisateur\",\n \"couleur\": (255, 255, 255),\n \"percent\": db_user[2] * 100 / reqxp,\n \"level\": db_user[1]})\n\n copyfile(\"image/frank.png\", \"image/{}avatar.png\".format(x))\n\n Generator.top(data)\n return True\n\n @cog_ext.cog_slash(name=\"top\",\n description=\"Affiche les 5 meilleurs membres du serveur\")\n async def s_top(self, ctx):\n await ctx.defer()\n resp = await self.global_top(ctx)\n if resp:\n await ctx.send(file=discord.File(\"image/top.png\"))\n else:\n await ctx.send(\"Désolé, il faut au moins 5 membres classés pour afficher le classement.\")\n\n @commands.command(name=\"top\")\n async def c_top(self, ctx):\n resp = await self.global_top(ctx)\n if resp:\n await ctx.send(file=discord.File(\"image/top.png\"))\n else:\n await ctx.send(\"Désolé, il faut au moins 5 membres classés pour afficher le classement.\")\n\n\ndef setup(bot):\n bot.add_cog(Top(bot))\n","sub_path":"FRank/cogs/top.py","file_name":"top.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"73775534","text":"# -*- coding: utf-8 -*-\n\nimport ask_sdk_core.utils as ask_utils\nimport requests\nimport json\n\n#from ask_sdk_s3.adapter import S3Adapter\nfrom ask_sdk_core.skill_builder import SkillBuilder\nfrom ask_sdk_core.dispatch_components import AbstractRequestHandler\nfrom ask_sdk_core.handler_input import HandlerInput\nfrom ask_sdk_model import Response\n\n\nclass LaunchRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for Skill Launch.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n\n return ask_utils.is_request_type(\"LaunchRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n speak_output = \"Hi what do you want to know\"\n reprompt_text = \"anything else you wanna know?\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .ask(reprompt_text)\n .response\n )\n\nclass CallAPIIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for CallAPIIntent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_intent_name(\"CallAPIIntent\")(handler_input)\n\n def handle(self, handler_input):\n \n slots = handler_input.request_envelope.request.intent.slots\n query = slots[\"sth\"].value\n order = slots[\"good_bad\"].value\n if (order==\"good\"):\n ord = 1\n else:\n ord = 0\n # search top 3 related articles with the query\n IPv4_adress = \"3.125.19.179\" # glove.6B.50d\n # IPv4_adress = \"3.122.223.164\" # sized-down w2v model\n url = f\"http://{IPv4_adress}:8000/predict\"\n data = {\"query\":query}\n \n r = requests.post(url, data = json.dumps(data))\n response = r.json()\n\n query = str(data[\"query\"])\n headlines1 = str(response[\"Headlines\"][0])\n headlines2 = str(response[\"Headlines\"][1])\n headlines3 = str(response[\"Headlines\"][2])\n \n # semantic analysis for each headline. order==1: positive-->negative; otherwise: negative-->positive\n IPv4_adress = \"3.123.254.31\" \n url = f\"http://{IPv4_adress}:8000/predict\"\n data = {\"headlines\":[headlines1, headlines2, headlines3], \"order\":ord}\n r = requests.post(url, data = json.dumps(data))\n response = r.json()\n\n headlines1 = str(response[\"ordered_articles\"][0])\n headlines2 = str(response[\"ordered_articles\"][1])\n headlines3 = str(response[\"ordered_articles\"][2])\n \n # hear the good one first\n if (order==\"good\"):\n speak_output = f\"For news related to: {query}, the better one is {headlines1}.\\n The worse one is {headlines3}\"\n # hear the bad one first\n else:\n speak_output = f\"For news related to: {query}, the worse one is {headlines1}.\\n The better one is {headlines3}\"\n\n # speak_output = \"That model predicted 0 \"\n return (\n handler_input.response_builder\n .speak(speak_output)\n .response\n )\n\nclass HelpIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for Help Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_intent_name(\"AMAZON.HelpIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n speak_output = \"You can say hello to me! How can I help?\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .ask(speak_output)\n .response\n )\n\nclass CancelOrStopIntentHandler(AbstractRequestHandler):\n \"\"\"Single handler for Cancel and Stop Intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return (ask_utils.is_intent_name(\"AMAZON.CancelIntent\")(handler_input) or\n ask_utils.is_intent_name(\"AMAZON.StopIntent\")(handler_input))\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n speak_output = \"Goodbye!\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n .response\n )\n\nclass SessionEndedRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for Session End.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_request_type(\"SessionEndedRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n\n # Any cleanup logic goes here.\n\n return handler_input.response_builder.response\n\nclass IntentReflectorHandler(AbstractRequestHandler):\n \"\"\"The intent reflector is used for interaction model testing and debugging.\n It will simply repeat the intent the user said. You can create custom handlers\n for your intents by defining them above, then also adding them to the request\n handler chain below.\n \"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return ask_utils.is_request_type(\"IntentRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n intent_name = ask_utils.get_intent_name(handler_input)\n speak_output = \"You just triggered \" + intent_name + \".\"\n\n return (\n handler_input.response_builder\n .speak(speak_output)\n # .ask(\"add a reprompt if you want to keep the session open for the user to respond\")\n .response\n )\n\n\nsb = SkillBuilder()\nsb.add_request_handler(LaunchRequestHandler())\nsb.add_request_handler(CallAPIIntentHandler())\nsb.add_request_handler(HelpIntentHandler())\nsb.add_request_handler(CancelOrStopIntentHandler())\nsb.add_request_handler(SessionEndedRequestHandler())\nsb.add_request_handler(IntentReflectorHandler()) \n\nlambda_handler = sb.lambda_handler()","sub_path":"Alexa_lambda/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"256691460","text":"import json\nimport os\nfrom base.field import *\nfrom jsonparser.documents import BaseJsonDocument\nfrom jsonparser.encoder import EnumEncoder\n\n\nclass LE(BaseJsonDocument):\n L = ListField(ListField(PyIntegerField()))\n\n\ndef run_example():\n dir_name = os.path.dirname(os.path.realpath(__file__))\n file_path = \"{0}/json/list_example\".format(dir_name)\n with open('{0}.json'.format(file_path), 'r') as test_data_file:\n a = LE()\n a.load(test_data_file.read().replace('\\n', ''))\n if a.is_valid():\n with open(\"{0}_result.json\".format(file_path), \"w\") as f:\n print(a.dump(), file=f)\n else:\n with open(\"{0}_errors.json\".format(file_path), \"w\") as f:\n json.dump(a.errors, f, cls=EnumEncoder)\n","sub_path":"jsonparser/examples/list_example.py","file_name":"list_example.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"501775266","text":"from sqlalchemy import create_engine, orm\nfrom sqlalchemy.orm.interfaces import MapperExtension\nfrom sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, Text, Float, Table\nfrom datetime import datetime\nfrom auth import hash_password\nimport uuid\n\nengine = create_engine('mysql+mysqldb://u:p@localhost/baseball', echo = True)\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n#region cross tables\nusers_x_sports = Table(\n 'users_x_sports',\n Base.metadata,\n Column('iduser', Integer, ForeignKey('users.id')),\n Column('idsport', Integer, ForeignKey('sports.id'))\n)\n\nusers_x_leagues = Table(\n 'users_x_leagues',\n Base.metadata,\n Column('iduser', Integer, ForeignKey('users.id')),\n Column('idleagues', Integer, ForeignKey('leagues.id'))\n)\n\nsports_x_leagues = Table(\n 'sports_x_leagues',\n Base.metadata,\n Column('idsport', Integer, ForeignKey('sports.id')),\n Column('idleagues', Integer, ForeignKey('leagues.id'))\n)\n\nteams_x_leagues = Table(\n 'teams_x_leagues',\n Base.metadata,\n Column('idteams', Integer, ForeignKey('teams.id')),\n Column('idleagues', Integer, ForeignKey('leagues.id'))\n)\n\nteams_x_seasons = Table(\n 'teams_x_seasons',\n Base.metadata,\n Column('idteams', Integer, ForeignKey('teams.id')),\n Column('idseasons', Integer, ForeignKey('seasons.id'))\n)\n\nusers_x_teams = Table(\n 'users_x_teams',\n Base.metadata,\n Column('iduser', Integer, ForeignKey('users.id')),\n Column('idteam', Integer, ForeignKey('teams.id'))\n)\n\n#end region\n\n#region framework tables\nclass BaseExtension(MapperExtension):\n def before_insert(self, mapper, connection, instance):\n if instance.active:\n instance.active = 1\n else:\n instance.active = 0\n instance.datecreated = datetime.now()\n instance.datemodified = datetime.now()\n instance.rowstamp = uuid.uuid4()\n def before_update(self, mapper, connection, instance):\n instance.datemodified = datetime.now()\n\nclass BaseUserExtension(MapperExtension):\n def before_insert(self, mapper, connection, instance):\n if instance.active:\n instance.active = 1\n else:\n instance.active = 0\n instance.datecreated = datetime.now()\n instance.datemodified = datetime.now()\n instance.rowstamp = uuid.uuid4()\n hashed = hash_password(instance.password)\n instance.password = hashed.split('$')[0]\n instance.salt = hashed.split('$')[1]\n def before_update(self, mapper, connection, instance):\n instance.datemodified = datetime.now()\n\nclass Users(Base):\n __tablename__ = 'users'\n __mapper_args__ = { 'extension' : BaseUserExtension() }\n id = Column(Integer, primary_key = True)\n active = Column(Boolean, default = 1)\n firstname = Column(String(50))\n lastname = Column(String(50))\n username = Column(String(100))\n email = Column(String(100))\n password = Column(String(255))\n salt = Column(String(255))\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n profiles = orm.relationship('Profiles', backref = 'user')\n #leagues_owned = orm.relationship('Leagues', backref = 'user')\n sports = orm.relationship('Sports', secondary = users_x_sports, backref='users')\n leagues = orm.relationship('Leagues', secondary = users_x_leagues, backref='users')\n teams = orm.relationship('Teams', secondary = users_x_teams, backref='users')\n\n def __init__(self, active, firstname, lastname, username, email, password):\n self.active = active\n self.firstname = firstname\n self.lastname = lastname\n self.username = username\n self.email = email\n self.password = password\n\n def __repr__(self):\n return \"\" % (self.firstname, self.lastname, self.rowstamp)\n#end region\n\n#region person tables\nclass Profiles(Base):\n __tablename__ = 'profiles'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n iduser = Column(Integer, ForeignKey('users.id'))\n idprofiletype = Column(Integer, ForeignKey('profiletypes.id'))\n active = Column(Boolean, default = 1)\n description = Column(Text)\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n \n images = orm.relationship('Images', backref = 'profile')\n\n def __init__(self, active, description):\n self.active = active\n self.description = description\n\n def __repr__(self):\n return \"\" % (self.description, self.rowstamp)\n\nclass ProfileTypes(Base):\n __tablename__ = 'profiletypes'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n active = Column(Boolean, default = 1)\n name = Column(String(50)) #player, coach, commissioner, spectator\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n profiles = orm.relationship('Profiles', backref = 'profiletype')\n\n def __init__(self, active, name):\n self.active = active\n self.name = name\n\n def __repr__(self):\n return \"\" % (self.name, self.rowstamp)\n\nclass Images(Base):\n __tablename__ = 'images'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n idprofile = Column(Integer, ForeignKey('profiles.id'))\n active = Column(Boolean, default = 1)\n name = Column(String(100))\n imageurl = Column(String(255))\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n\n def __init__(self, active, name, imageurl):\n self.active = active\n self.name = name\n self.imageurl = imageurl\n\n def __repr__(self):\n return \"\" % (self.name, self.rowstamp)\n#end region\n\n#region organization tables\nclass Sports(Base):\n __tablename__ = 'sports'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n active = Column(Boolean, default = 1)\n name = Column(String(50))\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n leagues = orm.relationship('Leagues', secondary = sports_x_leagues, backref='sports')\n\n def __init__(self, active, name):\n self.active = active\n self.name = name\n\n def __repr__(self):\n return \"\" % (self.name, self.rowstamp)\n\nclass Leagues(Base):\n __tablename__ = 'leagues'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n commissioner = Column(Integer, ForeignKey('users.id'))\n active = Column(Boolean, default = 1)\n name = Column(String(50))\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n seasons = orm.relationship('Seasons', backref = 'league')\n teams = orm.relationship('Teams', secondary = teams_x_leagues, backref='leagues')\n\n def __init__(self, active, name):\n self.active = active\n self.name = name\n\n def __repr__(self):\n return \"\" % (self.name, self.rowstamp)\n\nclass Seasons(Base):\n __tablename__ = 'seasons'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n idleague = Column(Integer, ForeignKey('leagues.id'))\n idseasontype = Column(Integer, ForeignKey('seasontypes.id'))\n active = Column(Boolean, default = 1)\n datestart = Column(DateTime)\n dateend = Column(DateTime)\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n teams = orm.relationship('Teams', secondary = teams_x_seasons, backref='seasons')\n\n def __init__(self, active, datestart, dateend):\n self.active = active\n self.datestart = datestart\n self.dateend = dateend\n\n def __repr__(self):\n return \"\" % (self.datestart, self.dateend, self.rowstamp)\n\nclass SeasonTypes(Base):\n __tablename__ = 'seasontypes'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n idprofile = Column(Integer, ForeignKey('profiles.id'))\n active = Column(Boolean, default = 1)\n name = Column(String(50)) #player, coach, commissioner, spectator\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n seasons = orm.relationship('Seasons', backref = 'seasontype')\n\n def __init__(self, active, name):\n self.active = active\n self.name = name\n\n def __repr__(self):\n return \"\" % (self.name, self.rowstamp)\n\nclass Teams(Base):\n __tablename__ = 'teams'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n active = Column(Boolean, default = 1)\n name = Column(String(100))\n description = Column(Text)\n rank = Column(Integer)\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n\n def __init__(self, active, name, description, rank):\n self.active = active\n self.name = name\n self.description = description\n self.rank = rank\n\n def __repr__(self):\n return \"\" % (self.name, self.rank, self.rowstamp)\n#end region\n\n#region game tables\nclass Games(Base):\n __tablename__ = 'games'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n idhometeam = Column(Integer, ForeignKey('teams.id'))\n idawayteam = Column(Integer, ForeignKey('teams.id'))\n idseason = Column(Integer, ForeignKey('seasons.id'))\n idleague = Column(Integer, ForeignKey('leagues.id'))\n idwinner = Column(Integer, ForeignKey('teams.id'))\n innings = orm.relationship('Innings', backref = 'game')\n active = Column(Boolean, default = 1)\n dateplayed = Column(DateTime)\n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n\n def __init__(self, active):\n self.active = active\n\n def __repr__(self):\n return \"\" % (self.idhometeam, self.idawayteam, self.dateplayed, self.rowstamp)\n\nclass Innings(Base):\n __tablename__ = 'innings'\n __mapper_args__ = { 'extension' : BaseExtension() }\n id = Column(Integer, primary_key = True)\n idgame = Column(Integer, ForeignKey('games.id'))\n inning = Column(Integer)\n half = Column(String(10))\n hits = Column(Integer)\n runs = Column(Integer)\n errors = Column(Integer)\n \n datecreated = Column(DateTime)\n datemodified = Column(DateTime)\n rowstamp = Column(String(50))\n\n def __init__(self, active, inning, half, hits, runs, errors):\n self.active = active\n self.inning = inning\n self.half = half\n self.hits = hits\n self.runs = runs\n self.errors = errors\n\n def __repr__(self):\n return \"\" % (self.inning, self.hits, self.runs, self.errors)\n#end region\n\nusers_table = Users.__table__\nprofiletypes_table = ProfileTypes.__table__\nprofiles_table = Profiles.__table__\nimages_table = Images.__table__\nsports_table = Sports.__table__\nleagues_table = Leagues.__table__\nseasons_table = Seasons.__table__\nseasontypes_table = SeasonTypes.__table__\nteams_table = Teams.__table__\ngames_table = Games.__table__\ninnings_table = Innings.__table__\n\nmetadata = Base.metadata\n\nif __name__ == \"__main__\":\n metadata.create_all(engine)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"110876419","text":"from django import template\n\nregister = template.Library()\n\n@register.simple_tag\ndef get_user_fullname(id, users):\n\t#import pdb; pdb.set_trace()\n\tuser = users.get(int(id))\n\tif(user):\n\t\treturn \"{0} {1}\" .format(user['first_name'], user['last_name'])","sub_path":"invoice/templatetags/user_tags.py","file_name":"user_tags.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"96778609","text":"# Combine the two lists `A' and `B' into a third list, without changing either\n# `A' or `B'.\n\nA = [0, 1, 2, 3, 4]\nB = [5, 6, 7, 8, 9]\n\n# Simple Solution: Not So Good\n\nresult = []\nfor a in A:\n result.append(a)\nfor b in B:\n result.append(b)\n\n# Advanced Solution: Kinda Ok\n\nresult = []\nresult.extend(A)\nresult.extend(B)\n\n# Simple Solution: Idiomatic\n\nresult = A + B\n\n","sub_path":"solutions/merge-lists.py","file_name":"merge-lists.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"409945207","text":"from TrEnvHandler import TrEnvHandler\nimport logging\nimport os\nimport platform\n\nclass nukehandler(TrEnvHandler):\n def __init__(self, name, envkeydict, envkeys):\n self.logger = logging.getLogger('tractor-blade')\n self.logger.debug(\"initializing nukehandler: %s\" % (name))\n TrEnvHandler.__init__(self, name, envkeydict, envkeys)\n\n def updateEnvironment(self, cmd, env, envkeys):\n self.logger.debug(\"nukehandler.updateEnvironment: %s\" % self.name)\n for key in envkeys:\n val = key[4:] #9.0v7\n self.environmentdict['TR_ENV_NUKEVER'] = val\n\n return TrEnvHandler.updateEnvironment(self, cmd, env, envkeys)\n\n def remapCmdArgs(self, cmdinfo, launchenv, thisHost):\n self.logger.debug(\"nukehandler.remapCmdArgs: %s\" % self.name)\n argv = TrEnvHandler.remapCmdArgs(self, cmdinfo, launchenv, thisHost)\n\n nuke_ver = launchenv['TR_ENV_NUKEVER']\n\n p = platform.system()\n if p == 'Linux' or p == 'Window':\n v = nuke_ver.split('v')\n argv[0] = 'Nuke' + v[0] #Nuke9.0\n\n ## Mac OSX\n else:\n argv[0] = 'Nuke' + nuke_ver #Nuke9.0v7\n\n return argv\n","sub_path":"studio_configurations/dabrenderCentralFiles/usr/custom/tractor/nukehandler.py","file_name":"nukehandler.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"57560912","text":"### Prepare wikidata entitity classes lists:\n### human Q5 1 class\n\n### organization Q43229 + indirect subclasses (3 level deep)\n### facility Q13226383\n### university Q3918\n### exclude: state (Q7275)\n### org: exclude city Q515, country Q6256, ...? political territorial entity (Q1048835), administrative territorial entity (Q56061)\n\n### geographical object Q618123 + indirect subclasses (2 level deep)\n### geographic location Q2221906 + indirect subclasses (2 level deep)\n### geographic region Q82794 + indirect subclasses (2 level deep)\n### city Q515\n### country Q6256\n### exclude facility (Q13226383), organization Q43229\n### geo: exclude university Q3918, organization Q43229, ...?\n\n\nfrom pyspark import SparkContext, SparkConf, SparkFiles\nimport time\nimport pprint\nimport sys\nimport json\n\nconf = SparkConf().setAppName(\"cmv\")\nsc = SparkContext(conf=conf)\npp = pprint.PrettyPrinter(width=100)\n\ndef json_loads(x):\n if x[-1] == ',':\n return json.loads(x[:-1])\n else:\n return json.loads(x)\n\ndef subclass_of(x, classes, exclude = []):\n if x is None:\n return False\n \n p31 = x.get('claims', {}).get('P279', {})\n \n for snak in p31:\n valueId = snak.get('mainsnak', {}).get('datavalue', {}).get('value', {}).get('id', '')\n if valueId in classes and valueId not in exclude:\n return True\n\n return False\n\nstart = time.time()\n\n# wikiFile = sc.textFile('/user/lusername/data/input/latest-all.json.bz2')\nwikiFile = sc.textFile('/user/lusername/data/input/wikidata_repartitioned')\nwikiData = wikiFile.filter(lambda x: '{' in x).map(lambda x : json_loads(x))\n\nprint('working ... \\n')\n\n###\n### org\n###\nsubclasses = []\nsubclasses.append(['Q43229'])\nsubclasses_bc = sc.broadcast(subclasses)\nfor i in range(1,4):\n subclasses_obj = wikiData.filter(lambda x : subclass_of(x, subclasses_bc.value[i-1], ['Q515','Q6256', 'Q7275', 'Q1048835', 'Q56061']))\n subclasses_list = subclasses_obj.map(lambda x: x['id'] ).collect()\n print(\"Level #\" + str(i) + \":\" + str(len(subclasses_list)))\n subclasses.append(subclasses_list)\n subclasses_bc = sc.broadcast(subclasses)\n\nsubclasses_flat = [item for sublist in subclasses for item in sublist]\nsubclasses_flat.extend(['Q13226383', 'Q3918'])\n\nprint(\"Org subclasses total:\" + str(len(subclasses_flat)))\nwith open('subclasses_org3.json', 'w') as fp:\n json.dump(subclasses_flat, fp)\n\n###\n### geo\n###\nsubclasses = []\nsubclasses.append(['Q618123', 'Q2221906', 'Q82794'])\nsubclasses_bc = sc.broadcast(subclasses)\nfor i in range(1,3):\n subclasses_obj = wikiData.filter(lambda x : subclass_of(x, subclasses_bc.value[i-1], ['Q13226383', 'Q43229', 'Q3918']))\n subclasses_list = subclasses_obj.map(lambda x: x['id'] ).collect()\n print(\"Level #\" + str(i) + \":\" + str(len(subclasses_list)))\n subclasses.append(subclasses_list)\n subclasses_bc = sc.broadcast(subclasses)\n\nsubclasses_flat = [item for sublist in subclasses for item in sublist]\nsubclasses_flat.extend(['Q515','Q6256'])\n\nprint(\"Geo subclasses total:\" + str(len(subclasses_flat)))\nwith open('subclasses_geo3.json', 'w') as fp:\n json.dump(subclasses_flat, fp)\n\n# 86\n# 556\n# 6079\n\nend = time.time()\nprint(end - start, 'seconds')\n\n\n","sub_path":"tools/wikidata/wikidata_prepare_classes.py","file_name":"wikidata_prepare_classes.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"121840297","text":"import enum\nimport time\nimport random\nfrom agagla import menu\nfrom agagla import player_ship\nfrom agagla import shared_objects\nfrom agagla import enemy\nfrom agagla import death_screen as ds\nfrom agagla import stage_screen\nfrom pygame.math import Vector2\n\nimport pygame\n\nPLAYER_SPAWN = Vector2(shared_objects.get_window_width() / 2, shared_objects.get_window_height() - 50)\nMAX_ENEMIES = 15\n\nENEMY_IDLE_BOUNDS = 75\n\nINTERSTAGE_TIME = 5\n\n\nclass GameState(enum.Enum):\n menu = 1\n running = 2\n interstage = 3\n game_over = 4\n exit = 5\n\n\nclass GameStateManager:\n\n def __init__(self):\n\n self.tick_rate = 60\n self._last_game_state = None\n self._current_game_state = GameState.menu\n self.game_score = 0\n self.stage = 0\n self.interstage_end = 0\n self.lives = 3\n self.lives_added = 0\n self.enemy_idle_left = False\n self._entities = []\n self._last_tick_time = time.time()\n self.states_switch = {GameState.menu: self._menu_fn,\n GameState.running: self._running_fn,\n GameState.game_over: self._game_over_fn,\n GameState.interstage: self._interstage_fn}\n\n self._menu = None\n self._death_screen = None\n self._stage_screen = None\n\n def _set_state(self, state):\n self._current_game_state = state\n\n def get_state(self):\n return self._current_game_state\n\n def get_enemies(self):\n enemies = []\n\n for i in self._entities:\n if type(i).__name__ == 'Enemy':\n enemies.append(i)\n\n return enemies\n\n def get_projectiles(self):\n projectiles = []\n\n for i in self._entities:\n if type(i).__name__ == 'Projectile':\n projectiles.append(i)\n\n return projectiles\n\n def get_player_ship(self):\n for i in self._entities:\n if type(i).__name__ == 'PlayerShip':\n return i\n\n def get_ships(self):\n enemies = self.get_enemies()\n if self.get_player_ship() is not None:\n ships = [self.get_player_ship()]\n else:\n ships = []\n\n ships += enemies\n return ships\n\n def get_entities(self):\n return self._entities\n\n def add_entity(self, e):\n self._entities.append(e)\n\n def remove_entity(self, e):\n self._entities.remove(e)\n\n def get_score(self):\n return self.game_score\n\n def start_game(self):\n self.add_entity(player_ship.PlayerShip(PLAYER_SPAWN))\n\n self._set_state(GameState.running)\n\n def spawn_wave(self, wave):\n new_enemies = []\n\n def add_enemies(enemy_type, number):\n for i in range(0, int(number)):\n new_enemies.append(enemy_type)\n\n if self.stage % 5 == 0:\n stage_num = int(self.stage / 5) - 1\n num_elite = int(stage_num % 20) + 1\n num_standard = stage_num - num_elite\n if num_standard < 0: num_standard = 0\n\n add_enemies(enemy.EnemyType.ELITE, num_elite)\n add_enemies(enemy.EnemyType.STANDARD, num_standard)\n elif self.stage % 4 == 0:\n stage_num = int(self.stage / 4) - 1\n if stage_num <= 0:\n stage_num = 2\n num_reinforced = stage_num / 2\n num_standard = stage_num - num_reinforced\n\n add_enemies(enemy.EnemyType.REINFORCED, num_reinforced)\n add_enemies(enemy.EnemyType.STANDARD, num_standard)\n elif self.stage % 3 == 0:\n stage_num = int(self.stage / 4) - 1\n if stage_num <= 0:\n stage_num = 2\n num_assault = stage_num / 2\n num_standard = stage_num - num_assault\n\n add_enemies(enemy.EnemyType.ASSAULT, num_assault)\n add_enemies(enemy.EnemyType.STANDARD, num_standard)\n else:\n add_enemies(enemy.EnemyType.STANDARD, self.stage)\n\n if len(new_enemies) == 0:\n add_enemies(enemy.EnemyType.STANDARD, self.stage)\n\n num_new_enemies = min(self.stage, MAX_ENEMIES)\n\n num_per_row = 5\n\n for i in range(0, min(len(new_enemies), num_new_enemies)):\n row_index = int(i / num_per_row)\n spawn_y = (row_index * 75) + 100\n spawn_x = ((i % num_per_row) * 100) + 200\n self.add_entity(enemy.Enemy(Vector2(spawn_x, spawn_y), new_enemies[i]))\n\n def submitted_hs(self):\n self.__init__()\n\n def _menu_fn(self, initial_run):\n if initial_run:\n self._menu = menu.Menu()\n\n self._menu.render()\n\n def _running_fn(self, initial_run):\n self._tick()\n self._render_game()\n\n def _interstage_fn(self, initial_run):\n if initial_run:\n self.interstage_end = time.time()+INTERSTAGE_TIME\n self._stage_screen = stage_screen.StageScreen()\n\n self._tick()\n self._render_game()\n self._stage_screen.render()\n\n if time.time() > self.interstage_end:\n self._set_state(GameState.running)\n if self.get_player_ship() is None:\n self.add_entity(player_ship.PlayerShip(Vector2(PLAYER_SPAWN.x, PLAYER_SPAWN.y)))\n else:\n self.spawn_wave(self.stage)\n\n def _game_over_fn(self, initial_run):\n if initial_run:\n self._death_screen = ds.DeathScreen()\n # self._set_state(GameState.menu)\n self._death_screen.render()\n\n def game_loop(self):\n if self._last_game_state == self._current_game_state:\n self.states_switch[self._current_game_state](False)\n else:\n self._last_game_state = self._current_game_state\n self.states_switch[self._current_game_state](True)\n\n def _force_tick(self):\n while not self._tick():\n continue\n\n def _tick(self):\n if time.time() >= self._last_tick_time + (1 / self.tick_rate):\n\n self.manage_game()\n\n for i in self._entities:\n i.tick()\n\n time_off = (self._last_tick_time + (1 / self.tick_rate)) - time.time()\n\n if time_off < 0:\n time_off = 0\n\n self._last_tick_time = time.time() - time_off\n\n return True\n\n return False\n\n def render_game_ui(self):\n screen = pygame.display.get_surface()\n font_small = shared_objects.get_tiny_font()\n score_surface = font_small.render(\"Score \" + str(self.game_score), False, (255, 255, 255))\n screen.blit(score_surface, (30, 10))\n\n round_surface = font_small.render(\"Stage \" + str(self.stage), False, (255, 255, 255))\n screen.blit(round_surface, ((shared_objects.get_window_width() / 2) - (round_surface.get_width() / 2), 10))\n\n life_surface = font_small.render(\"Lives \" + str(self.lives), False, (255, 255, 255))\n screen.blit(life_surface, (shared_objects.get_window_width() - life_surface.get_width() - 30, 10))\n\n return None\n\n def _render_game(self):\n pygame.display.get_surface().fill((0, 0, 0))\n shared_objects.get_bg().render()\n\n for i in self._entities:\n i.render()\n\n self.render_game_ui()\n\n def are_enemy_idle_left(self):\n return self.enemy_idle_left\n\n def manage_game(self):\n\n num_dropping = 0\n\n for i in self.get_enemies():\n if i.is_idle():\n # print(i.get_pos().x)\n if i.get_pos().x < ENEMY_IDLE_BOUNDS: self.enemy_idle_left = False\n\n elif i.get_pos().x > shared_objects.get_window_width() - ENEMY_IDLE_BOUNDS: self.enemy_idle_left = True\n\n if i.is_dropping():\n num_dropping += 1\n\n if i.get_health() <= 0:\n self.game_score += i.get_score()\n\n if num_dropping < 2:\n if len(self.get_enemies()) > 0:\n self.get_enemies()[random.randint(0, len(self.get_enemies())-1)].drop()\n\n for i in self.get_ships():\n if i.get_health() <= 0:\n self._entities.remove(i)\n\n if self.game_score >= 500 and self.lives_added == 0:\n self.lives += 1\n self.lives_added += 1\n\n if self.lives_added != 0 and self.game_score >= (self.lives_added * 1000) and \\\n self.lives_added <= (self.game_score / 1000):\n self.lives += 1\n self.lives_added += 1\n\n ps = self.get_player_ship()\n\n if ps is None and self._current_game_state == GameState.running:\n self.lives -= 1\n self._set_state(GameState.interstage)\n\n if self.lives <= 0:\n self._set_state(GameState.game_over)\n elif len(self.get_enemies()) <= 0 and self._current_game_state == GameState.running:\n self.stage += 1\n self._set_state(GameState.interstage)\n\n","sub_path":"agagla/game_state_manager.py","file_name":"game_state_manager.py","file_ext":"py","file_size_in_byte":8851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"325462490","text":"\"\"\"\nwget?linux???????????\n????:\nwindriver@PEK-QCAO1-D2:~/get_resutl_html_send_email$ python3 test_wget.py\ncmd %s wget -O test.html https://www.centos.bz/2016/10/download-compile-install-nginx/\nstd_out : b\"--2019-08-21 16:13:08-- https://www.centos.bz/2016/10/download-compile-install-nginx/\\nResolving www.centos.bz (www.c entos.bz)... 112.74.125.108\\nConnecting to www.centos.bz (www.centos.bz)|112.74.125.108|:443... connected.\\nHTTP request sent, awa iting response... 200 OK\\nLength: unspecified [text/html]\\nSaving to: `test.html'\\n\\n 0K .......... .......... ...... 140M=0s\\n\\n2019-08-21 16:13:09 (140 MB/s) - `test.html' saved [27123]\\n\\n\"\n\n\"\"\"\n\nimport os\nimport subprocess\n\ndef run_shell_cmd(cmd):\n print('cmd %s', cmd)\n p = subprocess.Popen(cmd, bufsize=1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n std_out, std_err = p.communicate()\n print('std_out : %s' % std_out)\n return p.returncode, std_out\n\ndef get_test_result_from_html(saved_result_html_link, result_html_link):\n cmd = 'wget -O %s %s' % (saved_result_html_link, result_html_link)\n run_shell_cmd(cmd)\n f = open(saved_result_html_link, 'r')\n content = f.readlines()\n for line in content:\n print(line)\n f.close()\n\nif __name__ == '__main__':\n index = 'download-compile-install-nginx'\n result_html_link = 'https://www.centos.bz/2016/10/%s/' % index\n saved_result_html_link = 'test.html'\n get_test_result_from_html(saved_result_html_link, result_html_link)\n","sub_path":"get_result_html_send_email/test_wget.py","file_name":"test_wget.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"3135076","text":"# agent based computational economic model\n# this is the generalized simulation\nfrom src.market import Market\nfrom src.pop import Pop\nfrom src.region import Region\nfrom src.updater import Updater\n\nclass ABCEM(Updater):\n def __init__(self, initSize):\n super().__init__(initSize)\n self.market = Market()\n self.log = {}\n self.time = 0\n\n def update(self, updater):\n self.tick()\n\n def tick(self):\n self.market.update(self)\n for i in range(0,len(self.updatables)):\n if self.updatables[i] == None:\n break\n self.updatables[i].update(self)\n\n self.time += 1\n\n # console visualization of sim state\n def visualInfo(self):\n pop = 0\n cash = 0\n for i in range(0,len(self.updatables)):\n if self.updatables[i] == None:\n break\n else:\n pop += self.updatables[i].popSize\n cash += self.updatables[i].state[\"money\"]\n tendies = str(self.market.getProduct(\"tendies\")[\"supply\"])\n pop = str(pop)\n cash = str(round(cash,2))\n\n string = \"POPULATION: \" + pop + \" (P,S/D)\"\n for key in self.market.products:\n string += \" \" + key + \":(\" + str(round(self.market.getProduct(key)[\"price\"],2)) + \",\" + str(round(self.market.getProduct(key)[\"supply\"],2)) + \"/\" + str(round(self.market.getProduct(key)[\"demand\"],2))+ \")\"\n string += \"CASH: \" + cash\n return string","sub_path":"src/abcem.py","file_name":"abcem.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"312870868","text":"# -*- coding: utf-8 -*-\nfrom iscclib.simhash import simhash\nfrom iscclib.base import Component\nfrom iscclib.utils import normalize_text\n\ntry:\n from datasketch import MinHash\nexcept ImportError:\n from iscclib.minhash import MinHash\n\n\nclass TextID(Component):\n \"\"\"\n The ContentTextID is a similarity preserving hash over normalized plain\n text data.\n\n We first use a MinHash algorithm to create a feature vector from\n 4-character sized n-grams. We then binarize the feature vector to a 64-bit\n hash with simhash.\n \"\"\"\n\n #: Min `code` value at 64 bits\n CODE_MIN = u'H'\n #: Max `code` value at 64 bits\n CODE_MAX = u'PPUYUNKI4DIAK'\n\n def __init__(self, *args, **kwargs):\n self._minhash = kwargs.pop('minhash')\n super(TextID, self).__init__(*args, **kwargs)\n\n @classmethod\n def from_text(cls, text, bits=64):\n norm_text = normalize_text(text)\n mhash = MinHash()\n for shingle in cls.shingles(norm_text):\n mhash.update(shingle.encode('utf-8'))\n try:\n shash = simhash(mhash.hashvalues, hashbits=bits)\n except TypeError:\n shash = simhash(mhash.hashvalues.tolist(), hashbits=bits)\n return cls(ident=shash, minhash=mhash, bits=bits)\n\n @staticmethod\n def shingles(text, width=4):\n idx = range(max(len(text) - width + 1, 1))\n return [text[i:i + width] for i in idx]\n","sub_path":"src/iscclib/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"63233937","text":"'''Input arr is 2D. Make sure output is a slice of original array.\n'''\nfrom __future__ import division\nimport numpy as np\nfrom functools import partial\nfrom utils.array_handling import extend_true, skip_outside_frame_start_to_end\nimport pandas as pd\nfrom collections import OrderedDict\n\n\ndef iterate_sites(func):\n def wrapper(arr, **args):\n if isinstance(arr, OrderedDict):\n for key, value in arr.iteritems():\n func(value, **args)\n else:\n func(arr, **args)\n return wrapper\n\n\ndef normalize_data(arr):\n '''Scale array from 0 to 1.\n\n Examples:\n >>> arr = np.array([50, 100, 0], np.float32)\n >>> normalize_data(arr)\n array([ 0.5, 1. , 0. ], dtype=float32)\n '''\n arr -= arr.min()\n arr /= arr.max()\n return arr\n\n\ndef filter_from_last_frames(arr, FRAME_START=0, FRAME_END=None, LEFT=0):\n \"\"\"Find NaNs and propagate NaNs to previous frames.\n LEFT is how many frames you want to go back.\n\n Examples:\n >>> arr = np.array([[0, np.nan, np.nan], [0, 0, np.nan]], np.float32)\n >>> filter_from_last_frames(arr, LEFT=1)\n array([[ nan, nan, nan],\n [ 0., nan, nan]], dtype=float32)\n \"\"\"\n df = pd.DataFrame(arr)\n nan_appeared = df.isnull().diff(axis=1).values\n nan_appeared = skip_outside_frame_start_to_end(nan_appeared, FRAME_START, FRAME_END) == 1\n fn = partial(extend_true, LEFT=LEFT, RIGHT=0)\n nan_appeared = np.apply_along_axis(fn, axis=1, arr=nan_appeared)\n arr[nan_appeared] = np.nan\n return arr\n\n\ndef interpolate_single_prop(arr, LIMIT=5, METHOD='linear'):\n \"\"\"\n Args:\n arr: 2D data_array\n LIMIT: Maximum number of consecutive NaNs to fill.\n METHOD: see pd.DataFrame.interpolate.\n Returns:\n arr: 2D data_array\n Examples:\n\n >>> interpolate_single_prop(np.array([[0, np.nan, 2]]))\n array([[ 0., 1., 2.]])\n >>> interpolate_single_prop(np.array([[0, np.nan, np.nan]]), LIMIT=1)\n array([[ 0., nan, nan]])\n \"\"\"\n arr1 = pd.DataFrame(arr).interpolate(method=METHOD, axis=1, limit=LIMIT, limit_direction='forward')\n arr1 = filter_from_last_frames(arr1.values, LEFT=LIMIT)\n arr[:] = arr1\n return arr\n","sub_path":"covertrace/ops_filter.py","file_name":"ops_filter.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"313242684","text":"import dateutil.parser\n\nclass Channel:\n\n def __init__(self, service, channel_id):\n self.service = service\n self.id = channel_id\n\n def get_info(self):\n kwargs = {\n 'part': 'snippet,statistics',\n 'id' : self.id\n }\n results = self.service.channels().list(**kwargs).execute()\n if results['items'] == []:\n print('Channel not found. Check the channel id')\n return False\n else:\n self.name = results['items'][0]['snippet']['title']\n publishedAt = dateutil.parser.parse(\n results['items'][0]['snippet']['publishedAt']\n )\n self.publishedAt_year = publishedAt.year\n self.publishedAt_month = publishedAt.month\n self.video_count = results['items'][0]['statistics']['videoCount']\n print('Channel Name : %s \\nVideo Count : %s' % (self.name, self.video_count))\n return True\n","sub_path":"channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"136728737","text":"#!/usr/bin/python3\n\nimport os\nimport sys\nimport filecmp\nimport signal\n\nclass GracefulKiller:\n kill_now = False\n def __init__(self):\n signal.signal(signal.SIGINT, self.exit_gracefully)\n signal.signal(signal.SIGTERM, self.exit_gracefully)\n\n def exit_gracefully(self,signum, frame):\n print(\"Term signal received.\")\n self.kill_now = True\n\nkiller = GracefulKiller()\n \nif len(sys.argv) != 3 and len(sys.argv) != 4:\n print(\"Needs 3 arguments: nosim\")\n print(\"If run without nosim argument, it just verbosely simulates the procedure...\")\n print(\"\\nThis utility checks recursively like diff if files(with full paths) found in first dir exist also in the second.\")\n print(\"If yes, then if they are the same file (content), they are deleted from the first dir. In case they differ, the\")\n print(\"modification times are checked: If file in the first dir is older then it is deleted.\")\n sys.exit(0);\n\ndir1 = sys.argv[1]\ndir2 = sys.argv[2]\nif len(sys.argv) == 4 and sys.argv[3] == \"nosim\":\n sim = False\nelse:\n sim = True\n \n\nif sim:\n print(' -> ' + str(dir1) + \"\\n\" + ' -> ' + str(dir2) + \"\\n\")\n\nif not (os.path.isdir(dir1) and os.path.isdir(dir2)):\n print('First dir or second dir (or both) are not directories.')\n sys.exit(0);\n\nfor dirpath, dirnames, files in os.walk(dir1):\n if killer.kill_now:\n break\n \n for name in files:\n if killer.kill_now:\n break\n \n f1 = os.path.join(dirpath, name)\n f2 = os.path.normpath(os.path.join(dir2, os.path.relpath(dirpath, dir1), name)) # this is constructed, so it may not exist\n\n if os.path.isfile(f2):\n if os.path.getsize(f1) == os.path.getsize(f2) and filecmp.cmp(f1, f2):\n if sim:\n print(\"Would remove \" + f1)\n else:\n os.remove(f1)\n \n else:\n \n if os.stat(f1).st_mtime < os.stat(f2).st_mtime:\n f1age = \" (older -- ok)\"\n f2age = \" (newer)\"\n \n if sim:\n print(\"Files \"+f1+f1age+\" and \"+f2+f2age+\" differ. Would remove left file.\")\n else:\n os.remove(f1)\n\n else:\n f1age = \" (newer (or equal) -- oops)\"\n f2age = \" (older (or equal))\"\n \n if sim:\n print(\"Files \"+f1+f1age+\" and \"+f2+f2age+\" differ. Would NOT remove left file.\") \n\n else:\n if sim:\n print(\"Only in \"+dir1+\" : \"+f1)\n","sub_path":"hyper-diff.py","file_name":"hyper-diff.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"520485717","text":"# 导入词云制作库wordcloud\nimport wordcloud\nimport matplotlib.pyplot as plt\n# 构建并配置词云对象w\nw = wordcloud.WordCloud(width=700,\n height=424,\n background_color='white',\n scale=20,\n font_path='/home/ross/.fonts/思源黑体/SourceHanSansSC-Medium.otf')\nplt.figure()\nw.generate('从明天起,做一个幸福的人。喂马、劈柴,周游世界。从明天起,关心粮食和蔬菜。我有一所房子,面朝大海,春暖花开')\nplt.imshow(w)\nplt.axis(\"off\")\nplt.show()\nplt.savefig('images/haizi.png', dpi=300, bbox_inches='tight')\n\n# 导入中文分词库jieba\nimport jieba\n# 构建并配置词云对象w\nw = wordcloud.WordCloud(width=1200,\n height=742,\n scale=20,\n background_color='white',\n font_path='/home/ross/.fonts/思源黑体/SourceHanSansSC-Medium.otf')\n\n# 调用jieba的lcut()方法对原始文本进行中文分词,得到string\ntxt = '华中科技大学(\"华中大\", Huazhong University of Science and Technology, HUST), 是中华人民共和国教育部直属的综合性研究型全国重点大学、中央直管副部级高校, 是国家首批“双一流”、“985工程”、“211工程”重点建设高校, 入选《Nature》评出的“中国十大科研机构”,被称作“新中国高等教育发展的缩影”'\ntxtlist = jieba.lcut(txt)\nstring = \" \".join(txtlist)\n\n# 将string变量传入w的generate()方法,给词云输入文字\nw.generate(string)\n\nplt.figure()\nplt.imshow(w)\nplt.axis(\"off\")\nplt.show()\nplt.savefig('images/hust.png', dpi=300, bbox_inches='tight')\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"175315675","text":"\nimport pico2d\n\nimport CEffect\nimport math\nimport random\nimport main_state\n\nclass ListManager:\n def __init__(self):\n self.UI_Lst = []\n self.Player_Lst = []\n self.Monster_BulletList = []\n self.Hyperion_Lst=[]\n self.Monster_List = []\n self.Boss_List = []\n self.Player_BulletLst=[]\n self.Item_Lst=[]\n self.Effect_Lst=[]\n self.Player_Lager_Lst = []\n self.Event=0\n self.ListManager=[ self.Player_Lst ,self.Boss_List,self.Player_BulletLst,self.Monster_BulletList,self.Monster_List,self.Item_Lst,self.Hyperion_Lst,self.Effect_Lst\n ,self.Player_Lager_Lst,self.UI_Lst]\n\n def Get_Player(self):\n return self.Player_Lst[0]\n # def MonsterBullet_Collision(self):\n # for Monster in self.Monster_List:\n # for PlayerBullet in self.Player_BulletLst:\n # Dist = math.sqrt((Monster.x - PlayerBullet.x) ** 2 + (Monster.y - PlayerBullet.y) ** 2)\n # if Dist <= 25:\n # Monster.Hp -= 1+self.Player_Lst[0].Power * 0.4\n # self.Player_Lst[0].Gage+=0.5\n # PlayerBullet.isDead = True\n # self.Effect_Lst.append(CEffect.Effect(PlayerBullet.x+random.randint(-15,15),PlayerBullet.y+random.randint(-15,15),30,27,30,27,12,0))\n\n def MonsterBullet_Collision(self):\n for Monster in self.Monster_List:\n for PlayerBullet in self.Player_BulletLst:\n if Monster.x + Monster.RadianX > PlayerBullet.x > Monster.x-Monster.RadianX and Monster.y + Monster.PivotY > PlayerBullet.y > Monster.y - Monster.PivotY:\n Monster.Hp -= 2 + self.Player_Lst[0].Power * 0.75\n self.Player_Lst[0].Gage += 0.5\n self.UI_Lst[3].Add_Score(random.randint(3, 7))\n PlayerBullet.isDead = True\n self.Effect_Lst.append(CEffect.Effect(PlayerBullet.x + random.randint(-15, 15),\n PlayerBullet.y + random.randint(-15, 15), 30, 27, 30, 27, 12,\n 0))\n\n def PlayerBullet_Collision(self):\n for Player in self.Player_Lst:\n for MonsterBullet in self.Monster_BulletList:\n Dist = math.sqrt((self.Player_Lst[0].x - MonsterBullet.x) ** 2 + (self.Player_Lst[0].y - MonsterBullet.y) ** 2)\n if Dist <=MonsterBullet.Radius and Player.IsShield is False:\n MonsterBullet.isDead = True\n main_state.SoundManager.PlaySound(14)\n if Player.SuperMode is False:\n Player.Life-=1;\n\n self.Effect_Lst.append(\n CEffect.Effect(self.Player_Lst[0].x + random.randint(-20, 20),\n self.Player_Lst[0].y + random.randint(-20, 20), 128, 128,\n 250, 250, 64, 5,0.3))\n\n def update(self):\n self.MonsterBullet_Collision()\n self.PlayerBullet_Collision()\n for n in self.ListManager:\n for m in n:\n self.Event=m.update()\n if self.Event == -1:\n n.remove(m)\n del (m)\n\n\n def draw(self):\n for n in self.ListManager:\n for m in n:\n m.draw()\n\n\n\n def GameOver(self):\n for Object in self.Monster_List:\n self.Monster_List.remove(Object)\n del(Object)\n for Object in self.Monster_BulletList:\n self.Monster_BulletList.remove(Object)\n del (Object)\n for Object in self.Boss_List:\n self.Boss_List.remove(Object)\n del (Object)\n\n\n def Delete_AllList(self):\n for List in self.ListManager:\n for Object in List:\n List.remove(Object)\n del(Object)\n\n","sub_path":"GameFrameWork/ListManagement.py","file_name":"ListManagement.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"651995072","text":"#!/usr/bin/env python3\n# -*- encoding:utf-8 -*-\nclass Solution(object):\n def validPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n isPalindrome = lambda s: s == s[::-1]\n strPart = lambda s, x: s[:x] + s[x + 1:]\n left = 0\n right = len(s) - 1\n while left < right:\n if s[left] != s[right]:\n return isPalindrome(strPart(s, left)) or isPalindrome(strPart(s, right))\n left += 1\n right -= 1\n return True\n\n# class Solution(object):\n# def validPalindrome(self, s):\n# \"\"\"\n# :type s: str\n# :rtype: bool\n# \"\"\"\n# isPalindrome = lambda x : x == x[::-1]\n# left, right = 0, len(s) - 1\n# while left <= right:\n# if s[left] == s[right]:\n# left += 1\n# right -= 1\n# else:\n# return isPalindrome(s[left + 1 : right + 1]) or isPalindrome(s[left: right])\n# return True","sub_path":"Week_09/680-验证回文字符串2.py","file_name":"680-验证回文字符串2.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"216776628","text":"from bson import DBRef, ObjectId\nfrom optparse import OptionParser\nfrom pprint import pprint\n\nparser = OptionParser()\nparser.add_option(\"-c\", \"--command\",\n dest=\"command\", default='get',\n help=\"print,delete\")\n\nparser.add_option(\"-e\", \"--entity\", dest=\"entity\", default=\"metric\")\nparser.add_option(\"-d\", \"--dashboard_id\", dest=\"dashboard_id\", default=None)\nparser.add_option(\"-i\", \"--id\", dest=\"id\", default=None)\nparser.add_option(\"-l\", \"--collection\", dest=\"collection\", default=\"metric_instances\")\nparser.add_option(\"-m\", \"--metric_instance_id\", dest=\"metric_instance_id\", default=None)\nparser.add_option(\"-n\", \"--environment\", dest=\"environment\", default='s1')\nparser.add_option(\"-t\", \"--team_id\", dest=\"team_id\", default=None)\nparser.add_option(\"--yes\", dest=\"yes\", action=\"store_true\", default=None)\n(options, args) = parser.parse_args()\n\ndef make_id_query(s):\n ids = s.replace('.', ' ').split(' ')\n oids = map(ObjectId, ids)\n if len(oids) > 1:\n return {'$in': oids}\n return oids[0]\n\ndef get_query():\n query = {}\n if options.id: query['_id'] = make_id_query(options.id)\n if options.metric_instance_id: query['metric_instance_id'] = ObjectId(options.metric_instance_id)\n if options.dashboard_id: query['dashboard_id'] = options.dashboard_id\n if options.team_id:\n if options.collection == 'channels':\n query['team'] = DBRef(\"projects\", ObjectId(options.team_id))\n else:\n query['team_id'] = options.team_id\n pprint(query)\n return query\n","sub_path":"common/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"361260299","text":"# this code gets a number from user and then prints the the word \"wow\" with\n# the number of times the letter o that the user defined at the first\n\n\n#solution\nnumber = input(\"please enter a number: \")\ntimes = int(number)\nmiddleO= \"o\"\nprint(\"w\"+times*middleO+\"w\")\n\n#a better solution\nnum = int(input(\"please enter a number: \"))\nprint(f\"w{'o'*numb}w\")\n\n","sub_path":"wOOOw.py","file_name":"wOOOw.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"129247781","text":"from urllib.parse import urljoin\n\nfrom ..core import *\nfrom ..utils import attributeerror_wrapper, typeerror_wrapper\n\nfrom ..vparsers import *\n\n\nclass SPInvestStatusParser(StatusParser):\n\n def get_mapper(self):\n return {\n \"DOSTĘPNE\": StatusParser.AVAILABLE,\n \"REZERWACJA\": StatusParser.RESERVED,\n \"SPRZEDANE\": StatusParser.SOLD\n }\n\n\nclass SPInvestParser(ConditionalWebpageParser):\n url = \"http://www.spinvest.pl/\"\n method = \"GET\"\n params = {\n \"rooms\": \"all\",\n \"size\": \"all\",\n \"floor\": \"all\",\n \"sold\": \"on\",\n \"page\": 1\n }\n\n schema = [\n DataUnit(label=\"Metraż\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\n DataUnit(label=\"Piętro\", parser=FloorParser(DOMTextExtractor()), id=\"floor\"),\n DataUnit(label=\"Pokoje\", parser=IntParser(DOMTextExtractor()), id=\"rooms\"),\n DataUnit(label=\"Numer\", parser=DOMTextExtractor(), id=\"number\"),\n DataUnit(label=\"None#0\", parser=NoneParser(), id=\"none_0\"),\n DataUnit(label=\"Plan\", parser=LinkParser(DOMElementExtractor(\"a\", 0)), id=\"plan\"),\n DataUnit(label=\"Karta\", parser=NoneParser(), id=\"details_none\"),\n DataUnit(label=\"None#1\", parser=NoneParser(), id=\"none_1\"),\n DataUnit(label=\"Status\", parser=SPInvestStatusParser(DOMTextExtractor()), id=\"status\"),\n DataUnit(label=\"None#2\", parser=NoneParser(), id=\"none_2\")\n ]\n\n @attributeerror_wrapper(return_value=[])\n def find_records(self, soup):\n return soup.find(\"div\", {\"id\": \"mieszkania\"}).find(\"table\")\\\n .find(\"tbody\").find_all(\"tr\")\n \n def split_record(self, record):\n return record.find_all(\"td\")\n\n @tryexcept_wrapper((TypeError, AttributeError), return_value=True)\n def is_last_page(self, soup):\n link = soup.find(\"div\", {\"class\": \"pager\"}).find(\"ul\").find_all(\"li\")[-1]\n return \"disabled\" in link.get(\"class\", [])\n\n def get_request_params(self):\n params = dict(self.params)\n self._page = getattr(self, \"_page\", 0) + 1\n params[\"page\"] = self._page\n return params\n\n def modify_record(self, record, soup=None):\n record[\"plan\"] = urljoin(self.url, record[\"plan\"])\n record[\"number\"] = \"{floor}/{number}\".format(**record)\n record[\"fid\"] = record[\"number\"]\n return record","sub_path":"parsers/spinvest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"347507403","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\\\nA silly little calculator implemented in JPython using\nJava components for the UI.\n\"\"\"\n\nimport java\nfrom java import awt\n\ndef exit(e): java.lang.System.exit(0)\n\ndef getField (f):\n\tt = f.getText ()\n\tif t == '':\n\t\treturn 0\n\telse:\n\t\treturn java.lang.Integer.parseInt (t)\n\ndef doMath (e):\n\tn1 = getField (f1)\n\tn2 = getField (f2)\n\tsum.setText (repr (n1 + n2))\n\tdiff.setText (repr (n1 - n2))\n\tprod.setText (repr (n1 * n2))\n\tquo.setText (repr (n1 / n2))\n\nf = awt.Frame ('BSH Calculator (jpython)', windowClosing=exit)\n\nf1 = awt.TextField (20, actionPerformed=doMath)\nf2 = awt.TextField (20, textValueChanged=doMath)\n\np = awt.Panel ()\np.setLayout (awt.GridLayout (2, 2))\np.add (awt.Label ('Enter Operand'))\np.add (f1)\np.add (awt.Label ('Enter Operand'))\np.add (f2)\n\nf.add ('North', p)\n\nf.add (\"Center\", awt.Label ('Results:'))\n\np = awt.Panel ()\np.setLayout (awt.GridLayout (4, 2))\np.add (awt.Label ('Sum'))\nsum = awt.TextField (20)\np.add (sum)\np.add (awt.Label ('Difference'))\ndiff = awt.TextField (20)\np.add (diff)\np.add (awt.Label ('Product'))\nprod = awt.TextField (20)\np.add (prod)\np.add (awt.Label ('Quotient'))\nquo = awt.TextField (20)\np.add (quo)\nf.add ('South', p)\n\nf.pack ()\nf.show ()\nf.toFront ()\n","sub_path":"samples/bsh/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"92078329","text":"# Write a program using a for loop that calculates exponentials. Your program should ask the user for a base\n# (base) and an exponent (exp), and calculate base**exp without using the ** operator.\n\n# These lines ask the user for input\nbase = eval(input(\"Base?\"))\nexp = eval(input(\"Exponent?\"))\n\n# 1. Use a for loop with a range statement to compute the final value. (Hint: think about initializing the\n# final value to 1 before the loop.\nresult = 1\nfor i in range(0,exp):\n result*=base\n# 2. Print the final value.\nprint(result)","sub_path":"Loops/exponentials.py","file_name":"exponentials.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"134000347","text":"import webapp2\n\n\n# Main Handler\nmain = open('index.html').read()\n\n\n# Main page will render index template\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n \"\"\"Index page\"\"\"\n self.response.write(main)\n\n\napp = webapp2.WSGIApplication([('/', MainPage)],\n debug=False)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"520603931","text":"'''\n NAMA = RIVALDO ISMIR\n NIM = A11.2019.12106\n KELP = A11.4118\n TGL = 24/11/2019\n'''\n\nbaris = 1 # inisiasi variable baris dengan nilai 1\nwhile baris <= 5: #mulai perulangan dengan nilai baris 1 sampai 5\n kol = 1 # inisiasi variable kol dengan nilai 1\n while kol <= 5: #mulai perulangan dengan nilai kol 1 sampai 5\n if baris <= kol: #melakukan pengecekan nilai baris , apakah nilai baris masih kurang atau sama dengan nilai kol\n print(\"*\", end=\" \") #print * dengan parameter end dengan value \" \" agar print selanjutnya tetap dalam baris yang sama dipisahkan dengan space\n else: #jika tidak memenuhi syarat di atas maka else berjalan\n print(\" \", end=\" \") #print space kosong dan menambahkan parameter end dengan value \" \" agar print selanjut nya tetap dalam baris dan dipisahkan spasi\n kol += 1 #menambahkan nilai kol agar nilai kol bertambah 1 setiap loop nya\n baris += 1 #menambahkan nilai baris agar nilai baris bertambah 1 setiap loop nya\n print(\"\") #print string kosong untuk membuat baris baru karena sebelumnya menggunakan end=\"\"","sub_path":"daspro_8/tugasku/nloop13.py","file_name":"nloop13.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"525697793","text":"################################################################################################################\nimport glob\nimport os\nfrom PIL import Image\n# Converts png images to jpg\n# NOTE: GOING TO CHANGE COLOR SLIGHTLY\n# NEED TO LOOK INTO WHY GIMP OR MSPAINT PRESERVES COLOR WHERE AS PILLOW DOES NOT?\n# MAYBE THAT'S NOT EVEN TRUE\n\ndef png_to_jpg(in_dir, out_dir=None):\n if in_dir == None:\n in_dir = \"\"\n else:\n if in_dir[-1] != \"/\":\n in_dir += \"/\"\n if out_dir == None:\n out_dir = \"\"\n else:\n if out_dir[-1] != \"/\":\n out_dir += \"/\"\n img_arr = sorted(glob.glob(in_dir + \"/*.png\"), reverse=True) \n for infile in img_arr:\n f, ext = os.path.splitext(infile)\n jpg_dir = out_dir + os.path.basename(f) + \".jpg\"\n if not os.path.isfile(jpg_dir):\n im = Image.open(infile)\n rgb_im = im.convert('RGB')\n rgb_im.save(jpg_dir, quality=100, subsampling=0)\n\n# PNG to JPG conversion\nimages_dir = \"images\"\npng_to_jpg(images_dir, images_dir)\n","sub_path":"png_to_jpg.py","file_name":"png_to_jpg.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"39178911","text":"#!/usr/bin/python3\n\"\"\"\nModule that prints a square\naccording to the size passed\n\"\"\"\n\n\ndef print_square(size):\n \"\"\" Prints square\n according to size\n \"\"\"\n if type(size) is not int or type(size) is float and size < 0:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n for r in range(size):\n for c in range(size):\n print(\"#\", end=\"\")\n print()\n","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"604345865","text":"import numpy as np\r\n# from bert_serving.client import BertClient\r\nfrom src.get_embedding import get_image_embed\r\nfrom src.milvus import milvus_search\r\nfrom src.mysql_toolkits import search_by_milvus_ids\r\n\r\n\r\n\r\ndef do_search(image,index_client,conn,cursor,model, device):\r\n\ttry:\r\n\t\tvec = get_image_embed(image,model, device)\r\n\texcept Exception as e:\r\n\t\tprint(\"image2embedding erroer: \",e)\r\n\t\treturn e\r\n\tstatus, results = milvus_search(index_client,vec)\r\n\tprint(results)\r\n\tif len(results) != 0:\r\n\t\tids = [res.id for res in results[0]]\r\n\t\tresults = search_by_milvus_ids(conn, cursor, ids)\r\n\t\treturn results\r\n\telse:\r\n\t\treturn \"there is no data\"\r\n\r\n","sub_path":"solutions/im2recipe/src/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"463285388","text":"import sys\nimport telebot\nfrom io import BytesIO\n\nimport telegram\nfrom flask import Flask, request, send_file\n\nfrom fsm import TocMachine\nfrom telegram.ext import Updater, CommandHandler, MessageHandler\n\nAPI_TOKEN = '489589959:AAFUyzPE9CwU-1AyetlpZUfL0kgnv4OsGQo'\nWEBHOOK_URL = 'https://4e9b7949.ngrok.io/hook'\n\napp = Flask(__name__)\nbot = telegram.Bot(token=API_TOKEN)\nupdater = Updater(token=API_TOKEN)\ndispatcher = updater.dispatcher\n\nmachine = TocMachine(\n states=[\n 'initial',\n 'state0',\n 'state1',\n 'state2',\n 'state3',\n 'state4',\n 'state5'\n # 'state6'\n ],\n transitions=[\n {\n 'trigger': 'advance',\n 'source': [\n 'state0',\n 'state2',\n 'state4',\n 'state5'\n ],\n 'dest': 'state1',\n 'conditions': 'to_a'\n },\n {\n 'trigger': 'advance',\n 'source': [\n 'state0',\n 'state1',\n 'state3',\n 'state4',\n 'state5'\n ],\n 'dest': 'state2',\n 'conditions': 'to_b'\n },\n # {\n # 'trigger': 'advance',\n # 'source': [\n # 'state0',\n # 'state2',\n # 'state4',\n # 'state5'\n # ],\n # 'dest': 'state6',\n # 'conditions': 'to_f'\n # },\n {\n 'trigger': 'go_back',\n 'source': [\n 'state1',\n 'state2'\n ],\n 'dest': 'state0'\n },\n {\n 'trigger':'advance',\n 'source': 'state1',\n 'dest': 'state3',\n 'conditions': 'a_to_c'\n },\n {\n 'trigger':'advance',\n 'source': 'state3',\n 'dest': 'state5',\n 'conditions': 'c_to_e'\n },\n {\n 'trigger':'advance',\n 'source': 'state2',\n 'dest': 'state4',\n 'conditions': 'b_to_d'\n },\n {\n 'trigger':'advance',\n 'source': [\n 'initial',\n 'state0',\n 'state1',\n 'state2',\n 'state3',\n 'state4',\n 'state5'\n ],\n 'dest': 'state0',\n 'conditions': 'welcome'\n }\n ],\n initial='initial',\n auto_transitions=False,\n show_conditions=True,\n)\n\ndef _set_webhook():\n status = bot.set_webhook(WEBHOOK_URL)\n if not status:\n print('Webhook setup failed')\n sys.exit(1)\n else:\n print('Your webhook URL has been set to \"{}\"'.format(WEBHOOK_URL))\n\n\n@app.route('/hook', methods=['POST'])\ndef webhook_handler():\n # if request.method == \"POST\":\n update = telegram.Update.de_json(request.get_json(force=True), bot)\n # bot.send_message(chat_id=bot.chat_id,text=\":)\")\n machine.advance(update) \n return 'ok'\n\n\n@app.route('/show-fsm', methods=['GET'])\ndef show_fsm():\n byte_io = BytesIO()\n machine.graph.draw(byte_io, prog='dot', format='png')\n byte_io.seek(0)\n return send_file(byte_io, attachment_filename='fsm.png', mimetype='image/png')\n\n# @bot.message_handler(commands=['help', 'start'])\n# def send_welcome(message):\n# bot.reply_to(message,\n# (\"Hi there, I am EchoBot.\\n\"\n# \"I am here to echo your kind words back to you.\"))\n\n# def start(bot, update):\n# update.message.reply_text(\"Welcome to my awesome bot!\")\n\n# @command(CommandHandler,'start')\n# def start(bot, update):\n# bot.sendMessage(chat_id=update.message.chat_id, text=\"I'm a bot, please talk to me!\")\n\n# def start():\n# update = telegram.Update.de_json(request.get_json(force=True), bot)\n# bot.sendMessage(chat_id=update.message.chat_id, text=\"I'm a bot, please talk to me!\")\n\nif __name__ == \"__main__\":\n _set_webhook()\n app.run()\n\n # start_handler = CommandHandler('start',start)\n # dispatcher.add_handler(start_handler)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"199291429","text":"'''\nCreated on 2016年4月10日\n\n@author: lin_jiang_yi\n'''\ndef checkio(text):#不用统计标点符号\n #[(number,a-z)]\n list_str = [[0,chr(char)] for char in range(97,123)]\n text = text.lower()\n for i in text:\n if i.isalpha():list_str[ord(i)-97][0]+=1\n num0 = 0\n char0 = None\n for num,char in list_str:\n if num>num0:\n num0 = num\n char0 = char\n return char0\n\nif __name__ == '__main__':\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert checkio(\"Hello World!\") == \"l\", \"Hello test\"\n assert checkio(\"How do you do?\") == \"o\", \"O is most wanted\"\n assert checkio(\"One\") == \"e\", \"All letter only once.\"\n assert checkio(\"Oops!\") == \"o\", \"Don't forget about lower case.\"\n assert checkio(\"AAaooo!!!!\") == \"a\", \"Only letters.\"\n assert checkio(\"abe\") == \"a\", \"The First.\"\n print(\"Start the long test\")\n assert checkio(\"a\" * 9000 + \"b\" * 1000) == \"a\", \"Long.\"\n print(\"The local tests are done.\")","sub_path":"Home/test_05_most_wanted_letter.py","file_name":"test_05_most_wanted_letter.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"284176021","text":"from selenium.common.exceptions import NoSuchElementException\nfrom pages.locators import MainPageLocators\n\nclass BasePage():\n def __init__(self, browser, url, timeout=3):\n self.browser = browser\n self.url = url\n self.browser.implicitly_wait(timeout)\n\n def open(self):\n self.browser.get(self.url)\n\n def is_element_present(self, how, what):\n try:\n self.browser.find_element(how, what)\n except NoSuchElementException:\n return False\n return True\n\n def should_be_exact_text(self, expected_text, real_text):\n assert expected_text in real_text, f\"Should be text '{expected_text}' in '{real_text}'\"\n\n\n\n def tour_cards_have_different_pictures(self):\n picture_on_tour_cards = self.browser.find_elements(*MainPageLocators.PICTURE_ON_TOUR_CARD)\n amount_of_tour_cards_with_picture = len(picture_on_tour_cards)\n print('Amount of tour cards with pictures ' + str(amount_of_tour_cards_with_picture))\n i = 0\n list_of_pictures = []\n for element in picture_on_tour_cards:\n new_picture = element.get_attribute(\"src\")\n print('Picture # ' + str(i) + '\\n' + new_picture)\n list_of_pictures.append(new_picture)\n i = i + 1\n list_of_pictures_set = set(list_of_pictures)\n print('Total ' + str(len(list_of_pictures)) + ' pictures, ' + str(len(list_of_pictures_set)) + ' of which are unique')\n assert len(list_of_pictures) == len(list_of_pictures_set), 'Duplicate pictures'\n\n def tour_cards_have_different_content(self):\n content_on_tour_cards = self.browser.find_elements(*MainPageLocators.CONTENT_ON_TOUR_CARD)\n amount_of_tour_cards_with_content = len(content_on_tour_cards)\n print('Amount of tour cards with content ' + str(amount_of_tour_cards_with_content))\n i = 0\n list_of_content = []\n for element in content_on_tour_cards:\n new_content = element.text\n list_of_content.append(new_content)\n print('Content # ' + str(i) + '\\n' + new_content)\n i = i + 1\n list_of_content_set = set(list_of_content)\n print('Total ' + str(len(list_of_content)) + ' contents, ' + str(len(list_of_content_set)) + ' of which are unique')\n assert len(list_of_content) == len(list_of_content_set), 'Duplicate content'\n\n def tour_cards_have_different_links(self):\n link_on_tour_cards = self.browser.find_elements(*MainPageLocators.LINK_ON_TOUR_CARD)\n amount_of_tour_cards_with_link = len(link_on_tour_cards)\n print('Amount of cards with link ' + str(amount_of_tour_cards_with_link))\n i = 0\n list_of_links = []\n for element in link_on_tour_cards:\n new_link = element.get_attribute('href')\n list_of_links.append(new_link)\n print('Link # ' + str(i) + '\\n' + new_link)\n i = i + 1 \n list_of_links_set = set(list_of_links)\n print('Total ' + str(len(list_of_links)) + ' links, ' + str(len(list_of_links_set)) + ' of which are unique')\n assert len(list_of_links) == len(list_of_links_set), 'Links do not lead to internal pages'\n\n def click_on_the_tour_cards_link(self):\n tour_cards_link = self.browser.find_element(*MainPageLocators.LINK_ON_TOUR_CARD)\n tour_cards_link.click()\n\n\n def get_amount_of_tour_cards(self):\n link_on_tour_cards = self.browser.find_elements(*MainPageLocators.LINK_ON_TOUR_CARD)\n amount_of_tour_cards_with_link = len(link_on_tour_cards)\n print('Amount of tour cards per page ' + str(amount_of_tour_cards_with_link))\n return amount_of_tour_cards_with_link\n\n","sub_path":"pages/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"323514395","text":"from django.db import models\n\nfrom wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel\nfrom wagtail.wagtailcore.fields import RichTextField\nfrom wagtail.wagtailsnippets.models import register_snippet\n\nfrom common.models import Address\n\n\nclass Owner(Address):\n CLASSIFICATION_CHOICES = (\n (1, 'Individual'),\n (2, 'Dealer'),\n )\n\n first_name = models.CharField(max_length=25, blank=True, null=True)\n middle_name = models.CharField(max_length=25, blank=True, null=True)\n last_name = models.CharField(max_length=25, blank=True, null=True)\n classification = models.PositiveSmallIntegerField(choices=CLASSIFICATION_CHOICES) \n about = RichTextField(blank=True, null=True) \n\n panels = [\n MultiFieldPanel((FieldPanel('first_name'),\n FieldPanel('middle_name'),\n FieldPanel('last_name'),\n FieldPanel('classification', classname='full'),\n FieldPanel('about', classname='full'),\n ), \"Owner Information\"),\n MultiFieldPanel((FieldPanel('block'),\n FieldPanel('lot'),\n FieldPanel('street'),\n FieldPanel('purok'),\n FieldPanel('sitio'),\n FieldPanel('barangay'),\n FieldPanel('municipality'),\n FieldPanel('province'),\n FieldPanel('region'),\n ), \"Address\"),\n ]\n\n def __str__(self):\n full_name = []\n if self.first_name:\n full_name.append(self.first_name)\n if self.middle_name:\n full_name.append(self.middle_name[:1] + '.')\n if self.last_name:\n full_name.append(self.last_name)\n return ' '.join(full_name)\n\nregister_snippet(Owner)\n","sub_path":"seller/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"422186085","text":"#FRAMES\r\n#Importar librería\r\nfrom tkinter import *\r\nfrom PIL import ImageTk,Image\r\n\r\nroot = Tk()\r\nroot.title(\"Code\")\r\nroot.iconbitmap('a.ico')\r\n\r\nframe = LabelFrame(root,text=\"This is my Frame......\", padx=15, pady=15)\r\nframe.pack(padx=100, pady=100 )\r\n\r\nb = Button(frame, text=\"Dont click here!\")\r\nb2 = Button(frame, text=\"Dont click here!\")\r\nb.grid(row=0, column=0)\r\nb2.grid(row=0, column=1)\r\n\r\n\r\n#Bucle infinito\r\nroot.mainloop()","sub_path":"PYTHON TKINTER -FREECODE CAMP/04_frame.py","file_name":"04_frame.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"149706902","text":"# 41. Write a Python program to convert a tuple to a string.\n\n# creating a tuple\ntup = ('s', 'u', 'd', 'e', 's', 'h', 'n', 'a')\n\n# converting a tuple to a string using join function\nfinal_output = ''.join(tup)\n\n# printing to get the result\nprint(final_output)","sub_path":"DtFourtyOne.py","file_name":"DtFourtyOne.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"2889830","text":"import logging\nfrom copy import deepcopy\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http.response import HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom rest_framework.decorators import api_view, parser_classes\nfrom rest_framework.parsers import FormParser\n\nfrom core.utils import host_required\nfrom cleanups.factories import cleanup_factory\nfrom cleanups.forms import CleanupFormSet\nfrom cleanups.serializers import Cleanup, Location, User\n\nlogger = logging.getLogger('cleanups.views')\n\n\n@host_required\n@login_required\n@parser_classes([FormParser])\ndef cleanup_edit(request, *args, **kwargs):\n logger.info(\"Edit user: %s\", request.user)\n context = {'cleanup': get_object_or_404(Cleanup, id=kwargs['pk'])}\n return render(request, 'cleanups/edit.html', context)\n\n\ndef cleanup_show(request, *args, **kwargs):\n cleanup = get_object_or_404(Cleanup, id=kwargs['pk'])\n gmap = settings.GOOGLE_MAPS_ENDPOINT + cleanup.gmap_query\n return render(request, 'cleanups/detail.html', {'cleanup': cleanup, 'gmap': gmap})\n\n\ndef cleanup_list(request):\n cleanups = Cleanup.objects.all().filter(date__gte=datetime.now())\n context = {'cleanups': cleanups}\n return render(request, 'cleanups/list.html', context)\n\n\n@login_required\n@parser_classes([FormParser])\ndef cleanup_new(request):\n context = {'form': CleanupFormSet()}\n return render(request, 'cleanups/new.html', context)\n\n\n@login_required\n@parser_classes([FormParser])\ndef cleanup_create(request):\n try:\n cleanup_data = cleanup_factory(deepcopy(request.POST))\n cleanup_data['location'] = Location.objects.create(**cleanup_data.get('location'))\n except (ObjectDoesNotExist, AttributeError):\n logger.exception('Error while creating a cleanup or location.')\n return redirect('cleanup-create')\n else:\n cleanup = Cleanup.objects.create(**cleanup_data)\n return render(request, 'cleanups/detail.html', {'user': request.user,\n 'cleanup': cleanup})\n\n\n@login_required\n@api_view(['PATCH', 'POST', 'PUT'])\n@parser_classes([FormParser])\ndef cleanup_join_view(request, *args, **kwargs):\n cleanup = Cleanup.objects.get(id=kwargs.get('pk'))\n participant = User.objects.get(username=request.POST.get('participants'))\n if participant in cleanup.participants.all():\n cleanup.participants.remove(participant)\n else:\n cleanup.participants.add(participant)\n cleanup.save()\n return render(request, 'cleanups/detail.html',\n {'cleanup': cleanup, 'participants': cleanup.participants.all()})\n\n\n@host_required\n@api_view(['POST', 'PUT', 'PATCH'])\n@parser_classes([FormParser])\ndef cleanup_update(request, *args, **kwargs):\n cleanup_data = cleanup_factory(deepcopy(request.data))\n Location.objects.filter(cleanup=kwargs['pk']).update(**cleanup_data.pop('location'))\n Cleanup.objects.filter(id=kwargs['pk']).update(**cleanup_data)\n cleanup = Cleanup.objects.get(id=kwargs['pk'])\n return render(request, 'cleanups/detail.html',\n {'cleanup': cleanup, 'participants': cleanup.participants.all()})\n\n\n@host_required\n@api_view(['POST', 'DELETE'])\ndef cleanup_delete(request, *args, **kwargs):\n cleanup = Cleanup.objects.get(id=kwargs['pk'])\n try:\n cleanup.delete()\n except (AssertionError, Exception):\n logger.exception('Error while deleting cleanup.')\n redirect(cleanup)\n return redirect('dashboard')\n","sub_path":"trashtalk/apps/cleanups/views/template_views.py","file_name":"template_views.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"408478119","text":"import argparse\nimport numpy as np\nimport cooler\n\nimport logging\nlog = logging.getLogger(__name__)\nlogging.getLogger('hicmatrix').setLevel(logging.ERROR)\n\nfrom multiprocessing import Process, Queue\nimport time\n\nfrom krbalancing import *\n\nfrom hicmatrix import HiCMatrix as hm\n# from hicexplorer._version import __version__\nfrom hicmatrix.lib import MatrixFileHandler\nfrom schicexplorer._version import __version__\n\n\ndef parse_arguments(args=None):\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n add_help=False,\n description='Correct each matrix of the given mcool matrix with KR correction.')\n\n parserRequired = parser.add_argument_group('Required arguments')\n\n parserRequired.add_argument('--matrix', '-m',\n help='Matrix to reduce in h5 format.',\n metavar='matrix.h5',\n required=True)\n\n parserRequired.add_argument('--outFileName', '-o',\n help='File name to save the resulting matrix, please add the mcool prefix.',\n required=True)\n # parserRequired.a\n parserOpt = parser.add_argument_group('Optional arguments')\n\n parserOpt.add_argument('--threads', '-t',\n help='Number of threads. Using the python multiprocessing module.',\n required=False,\n default=4,\n type=int)\n parserOpt.add_argument('--help', '-h', action='help', help='show this help message and exit')\n\n parserOpt.add_argument('--version', action='version',\n version='%(prog)s {}'.format(__version__))\n\n return parser\n\n\ndef compute_correction(pMatrixName, pMatrixList, pQueue):\n\n out_queue_list = []\n for matrix in pMatrixList:\n hic = hm.hiCMatrix(pMatrixName + '::' + matrix)\n\n kr = kr_balancing(hic.matrix.shape[0], hic.matrix.shape[1],\n hic.matrix.count_nonzero(), hic.matrix.indptr.astype(np.int64, copy=False),\n hic.matrix.indices.astype(np.int64, copy=False), hic.matrix.data.astype(np.float64, copy=False))\n kr.computeKR()\n correction_factors = kr.get_normalisation_vector(False).todense()\n hic.setCorrectionFactors(correction_factors)\n out_queue_list.append(hic)\n\n pQueue.put(out_queue_list)\n return\n\n\ndef main(args=None):\n\n args = parse_arguments().parse_args(args)\n\n threads = args.threads\n merged_matrices = [None] * threads\n matrices_list = cooler.fileops.list_coolers(args.matrix)\n if len(matrices_list) < threads:\n threads = len(matrices_list)\n all_data_collected = False\n thread_done = [False] * threads\n length_index = [None] * threads\n length_index[0] = 0\n matricesPerThread = len(matrices_list) // threads\n queue = [None] * threads\n process = [None] * threads\n for i in range(threads):\n\n if i < threads - 1:\n matrices_name_list = matrices_list[i * matricesPerThread:(i + 1) * matricesPerThread]\n length_index[i + 1] = length_index[i] + len(matrices_name_list)\n else:\n matrices_name_list = matrices_list[i * matricesPerThread:]\n\n queue[i] = Queue()\n process[i] = Process(target=compute_correction, kwargs=dict(\n pMatrixName=args.matrix,\n pMatrixList=matrices_name_list,\n pQueue=queue[i]\n )\n )\n\n process[i].start()\n\n while not all_data_collected:\n for i in range(threads):\n if queue[i] is not None and not queue[i].empty():\n merged_matrices[i] = queue[i].get()\n\n queue[i] = None\n process[i].join()\n process[i].terminate()\n process[i] = None\n thread_done[i] = True\n all_data_collected = True\n for thread in thread_done:\n if not thread:\n all_data_collected = False\n time.sleep(1)\n log.debug('merge it')\n\n merged_matrices = [item for sublist in merged_matrices for item in sublist]\n log.debug('len(merged_matrices) {}'.format(len(merged_matrices)))\n log.debug('len(matrices_list) {}'.format(len(matrices_list)))\n\n for i, hic_matrix in enumerate(merged_matrices):\n append = False\n if i > 0:\n append = True\n matrixFileHandlerOutput = MatrixFileHandler(\n pFileType='cool', pAppend=append, pFileWasH5=False)\n\n matrixFileHandlerOutput.set_matrix_variables(hic_matrix.matrix, hic_matrix.cut_intervals, hic_matrix.nan_bins,\n hic_matrix.correction_factors, hic_matrix.distance_counts)\n matrixFileHandlerOutput.save(args.outFileName + '::' + matrices_list[i], pSymmetric=True, pApplyCorrection=False)\n","sub_path":"schicexplorer/scHicCorrectMatrices.py","file_name":"scHicCorrectMatrices.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"16703170","text":"from tkinter import *\n\nwindow=Tk()\n\ndef km_to_miles():\n t1.delete('1.0', END)\n try :\n miles = float(e1_value.get()) * 1.6\n except ValueError:\n miles = \"INVALID\"\n t1.insert(END,miles)\n\ndef closeEverything():\n window.destroy()\n\nb1=Button(window,text=\"Execute\",command=km_to_miles)\nb1.grid(row=0,column=0)\n\nb2=Button(window,text=\"Close\",command=closeEverything)\nb2.grid(row=0,column=3)\n\ne1_value=StringVar()\ne1=Entry(window,textvariable=e1_value)\ne1.grid(row=0,column=1)\n\nt1=Text(window,height=1,width=20)\nt1.grid(row=0,column=2)\n\nwindow.mainloop()\n","sub_path":"Application/App5_GUI_App/convertor.py","file_name":"convertor.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"430944676","text":"# Checks the date in a fits image header, and if the year is 2011 \n# sets the RDNOISE key to 26.\n# The fact that this program needs to exist saddens me.\n#\n# Author: Ryan Muther, Union College, July 2013\n#\n# This will likely only work on linux. So if it breaks on something else, \n#check the function getFitsFiles(). It concatenates the directory the \n# program is currently working in a linux-specific manner\n\nfrom astropy.io import fits\nfrom pyraf import iraf\nimport os\n\ndef checkRN(filename):\n imageHeader = fits.open(filename)[0]\n hasDateObsKey = True\n dateString = \"\"\n \n try:\n dateString = imageHeader.header['DATE-OBS']\n except KeyError:\n hasDateObsKey = False\n \n\n year = dateString[:4]\n \n if (hasDateObsKey and year=='2011'):\n iraf.hedit(filename,'RDNOISE',26,add='yes',verify='no')\n print(\" \")\n \n \n\n#Returns a list of all the fits files in a directory\n#The a and arguments is completely irrelevent.\ndef getFitsFiles(a,dirname,files):\n for entry in files:\n if entry.endswith('.fits'):\n checkRN(dirname+\"/\"+entry)\n\nos.path.walk(os.getcwd(),getFitsFiles,None)\nprint('Done!')\n","sub_path":"student_code2014/checkRN.py","file_name":"checkRN.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"51603346","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import Bool\n\nimport random, numpy\nimport sys, getopt\nimport requests\nimport json\n\ndef callback(data, Parameters):\n\n HOST = Parameters[0]\n PORT = Parameters[1]\n ACTUATORNAME = Parameters[2]\n \n msg = DataConverter(data)\n ActuatorState = {'state': msg}\n\n r = requests.post('http://%s:%s/_openag/%s/set_state'%(HOST,PORT,ACTUATORNAME),\\\n data=json.dumps(ActuatorState),\\\n headers={\"Content-Type\": \"application/json\"})\n\ndef DataConverter(data):\n\n if(data.data):\n msg = 'true'\n else:\n msg = 'false'\n\n return msg\n \ndef Subscriber(argv):\n\n # In ROS, nodes are uniquely named. If two nodes with the same\n # node are launched, the previous one is kicked off. The\n # anonymous=True flag means that rospy will choose a unique\n # name for our 'listener' node so that multiple listeners can\n # run simultaneously.\n rospy.init_node('PFC_CouchDB_Feeder', anonymous=True)\n\n # Topic you want to subscribe\n rospy.Subscriber(argv[0], Bool, callback, argv[1:])\n \ndef Run(argv):\n\n # Information is obtained and processed\n Subscriber(argv)\n\n # spin() simply keeps python from exiting until this node is stopped\n rospy.spin()\n \nif __name__ == '__main__':\n \n if (len(sys.argv)<4):\n print ('Not enough arguments')\n print ('Use : CouchFeeder.py [TOPIC] [HOST] [PORT] [ACTUATOR NAME]')\n else:\n Run(sys.argv[1:])\n","sub_path":"src/CouchFeederBinary.py","file_name":"CouchFeederBinary.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"138029838","text":"import logging # pylint: disable=C0302\nimport json\nimport requests\nfrom sqlalchemy import func, desc, text\nfrom urllib.parse import urljoin\n\nfrom flask import request\n\nfrom src import exceptions\nfrom src.queries import response_name_constants\nfrom src.models import User, Track, Repost, RepostType, Follow, Playlist, Save, SaveType\nfrom src.utils import helpers\nfrom src.utils.config import shared_config\n\nfrom datetime import datetime, timedelta\n\nlogger = logging.getLogger(__name__)\n\n\n######## VARS ########\n\n\ndefaultLimit = 100\nminLimit = 1\nmaxLimit = 500\ndefaultOffset = 0\nminOffset = 0\n\n# Used when generating genre list to special case Electronic tunes\nelectronic_sub_genres = [\n 'Techno',\n 'Trap',\n 'House',\n 'Tech House',\n 'Deep House',\n 'Disco',\n 'Electro',\n 'Jungle',\n 'Progressive House',\n 'Hardstyle',\n 'Glitch Hop',\n 'Trance',\n 'Future Bass',\n 'Future House',\n 'Tropical House',\n 'Downtempo',\n 'Drum & Bass',\n 'Dubstep',\n 'Jersey Club',\n]\n\n######## HELPERS ########\n\n\ndef get_current_user_id(required=True):\n user_id_header = 'X-User-ID'\n uid = request.headers.get(user_id_header)\n try:\n if uid:\n uid = int(uid)\n except ValueError:\n raise exceptions.ArgumentError(\"must be valid integer\")\n if required and not uid:\n raise exceptions.ArgumentError(\"Need to include valid X-User-ID header\")\n\n return uid\n\n\ndef parse_sort_param(base_query, model, whitelist_sort_params):\n sort = request.args.get(\"sort\")\n if not sort:\n return base_query\n\n params = sort.split(',')\n try:\n params = {param[0]: param[1] for param in [p.split(':') for p in params]}\n except IndexError:\n raise exceptions.ArgumentError(\"Need to specify :asc or :desc on all parameters\")\n order_bys = []\n for field in params.keys():\n if field not in whitelist_sort_params:\n raise exceptions.ArgumentError('Parameter %s is invalid in sort' % field)\n attr = getattr(model, field)\n if params[field] == 'desc':\n attr = attr.desc()\n else:\n attr = attr.asc()\n order_bys.append(attr)\n\n return base_query.order_by(*order_bys)\n\n\n# given list of user ids and corresponding users, populates each user object with:\n# track_count, playlist_count, album_count, follower_count, followee_count, repost_count\n# if current_user_id available, populates does_current_user_follow, followee_follows\ndef populate_user_metadata(session, user_ids, users, current_user_id, with_track_save_count = False):\n # build dict of user id --> track count\n track_counts = (\n session.query(\n Track.owner_id,\n func.count(Track.owner_id)\n )\n .filter(\n Track.is_current == True,\n Track.is_delete == False,\n Track.is_unlisted == False,\n Track.owner_id.in_(user_ids)\n )\n .group_by(Track.owner_id)\n .all()\n )\n track_count_dict = {user_id: track_count for (user_id, track_count) in track_counts}\n\n # build dict of user id --> playlist count\n playlist_counts = (\n session.query(\n Playlist.playlist_owner_id,\n func.count(Playlist.playlist_owner_id)\n )\n .filter(\n Playlist.is_current == True,\n Playlist.is_album == False,\n Playlist.is_private == False,\n Playlist.is_delete == False,\n Playlist.playlist_owner_id.in_(user_ids)\n )\n .group_by(Playlist.playlist_owner_id)\n .all()\n )\n playlist_count_dict = {user_id: playlist_count for (user_id, playlist_count) in playlist_counts}\n\n # build dict of user id --> album count\n album_counts = (\n session.query(\n Playlist.playlist_owner_id,\n func.count(Playlist.playlist_owner_id)\n )\n .filter(\n Playlist.is_current == True,\n Playlist.is_album == True,\n Playlist.is_private == False,\n Playlist.is_delete == False,\n Playlist.playlist_owner_id.in_(user_ids)\n )\n .group_by(Playlist.playlist_owner_id)\n .all()\n )\n album_count_dict = {user_id: album_count for (user_id, album_count) in album_counts}\n\n # build dict of user id --> follower count\n follower_counts = (\n session.query(\n Follow.followee_user_id,\n func.count(Follow.followee_user_id)\n )\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.followee_user_id.in_(user_ids)\n )\n .group_by(Follow.followee_user_id)\n .all()\n )\n follower_count_dict = {user_id: follower_count for (user_id, follower_count) in follower_counts}\n\n # build dict of user id --> followee count\n followee_counts = (\n session.query(\n Follow.follower_user_id,\n func.count(Follow.follower_user_id)\n )\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.follower_user_id.in_(user_ids)\n )\n .group_by(Follow.follower_user_id)\n .all()\n )\n followee_count_dict = {user_id: followee_count for (user_id, followee_count) in followee_counts}\n\n # build dict of user id --> repost count\n repost_counts = (\n session.query(\n Repost.user_id,\n func.count(Repost.user_id)\n )\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.user_id.in_(user_ids)\n )\n .group_by(Repost.user_id)\n .all()\n )\n repost_count_dict = {user_id: repost_count for (user_id, repost_count) in repost_counts}\n track_save_count_dict = {}\n if with_track_save_count : \n # build dict of user id --> track save count\n track_save_counts = (\n session.query(\n Save.user_id,\n func.count(Save.user_id)\n )\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.save_type == SaveType.track,\n Save.user_id.in_(user_ids)\n )\n .group_by(Save.user_id)\n .all()\n )\n track_save_count_dict = {user_id: user_track_save_count for (user_id, user_track_save_count) in track_save_counts}\n\n # build dict of user id --> track blocknumber\n track_blocknumbers = (\n session.query(\n Track.owner_id,\n func.max(Track.blocknumber)\n )\n .filter(\n Track.is_current == True,\n Track.is_delete == False,\n Track.owner_id.in_(user_ids)\n )\n .group_by(Track.owner_id)\n .all()\n )\n track_blocknumber_dict = {user_id: track_blocknumber for (user_id, track_blocknumber) in track_blocknumbers}\n\n current_user_followed_user_ids = {}\n current_user_followee_follow_count_dict = {}\n if current_user_id:\n # does current user follow any of requested user ids\n current_user_followed_user_ids = (\n session.query(Follow.followee_user_id)\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.followee_user_id.in_(user_ids),\n Follow.follower_user_id == current_user_id\n )\n .all()\n )\n current_user_followed_user_ids = {r[0]: True for r in current_user_followed_user_ids}\n\n # build dict of user id --> followee follow count\n current_user_followees = (\n session.query(Follow.followee_user_id)\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.follower_user_id == current_user_id\n )\n )\n current_user_followees = {r[0]: True for r in current_user_followees}\n\n current_user_followee_follow_counts = (\n session.query(\n Follow.followee_user_id,\n func.count(Follow.followee_user_id)\n )\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.follower_user_id.in_(current_user_followees),\n Follow.followee_user_id.in_(user_ids)\n )\n .group_by(Follow.followee_user_id)\n .all()\n )\n current_user_followee_follow_count_dict = {user_id: followee_follow_count for (user_id, followee_follow_count) in current_user_followee_follow_counts}\n\n for user in users:\n user_id = user[\"user_id\"]\n user[response_name_constants.track_count] = track_count_dict.get(user_id, 0)\n user[response_name_constants.playlist_count] = playlist_count_dict.get(user_id, 0)\n user[response_name_constants.album_count] = album_count_dict.get(user_id, 0)\n user[response_name_constants.follower_count] = follower_count_dict.get(user_id, 0)\n user[response_name_constants.followee_count] = followee_count_dict.get(user_id, 0)\n user[response_name_constants.repost_count] = repost_count_dict.get(user_id, 0)\n user[response_name_constants.track_blocknumber] = track_blocknumber_dict.get(user_id, -1)\n if with_track_save_count:\n user[response_name_constants.track_save_count] = track_save_count_dict.get(user_id, 0)\n # current user specific\n user[response_name_constants.does_current_user_follow] = current_user_followed_user_ids.get(user_id, False)\n user[response_name_constants.current_user_followee_follow_count] = current_user_followee_follow_count_dict.get(user_id, 0)\n\n return users\n\n\n# given list of track ids and corresponding tracks, populates each track object with:\n# repost_count, save_count\n# if current_user_id available, populates followee_reposts, has_current_user_reposted, has_current_user_saved\ndef populate_track_metadata(session, track_ids, tracks, current_user_id):\n # build dict of track id --> repost count\n repost_counts = (\n session.query(\n Repost.repost_item_id,\n func.count(Repost.repost_item_id)\n )\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.repost_item_id.in_(track_ids),\n Repost.repost_type == RepostType.track\n )\n .group_by(Repost.repost_item_id)\n .all()\n )\n repost_count_dict = {track_id: repost_count for (track_id, repost_count) in repost_counts}\n\n # build dict of track id --> save count\n save_counts = (\n session.query(\n Save.save_item_id,\n func.count(Save.save_item_id)\n )\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.save_type == SaveType.track,\n Save.save_item_id.in_(track_ids)\n )\n .group_by(Save.save_item_id)\n .all()\n )\n save_count_dict = {track_id: save_count for (track_id, save_count) in save_counts}\n\n user_reposted_track_dict = {}\n user_saved_track_dict = {}\n followee_track_repost_dict = {}\n followee_track_save_dict = {}\n if current_user_id:\n # has current user reposted any of requested track ids\n user_reposted = (\n session.query(\n Repost.repost_item_id\n )\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.repost_item_id.in_(track_ids),\n Repost.repost_type == RepostType.track,\n Repost.user_id == current_user_id\n )\n .all()\n )\n user_reposted_track_dict = {repost[0]: True for repost in user_reposted}\n\n # has current user saved any of requested track ids\n user_saved_tracks_query = (\n session.query(Save.save_item_id)\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.user_id == current_user_id,\n Save.save_item_id.in_(track_ids),\n Save.save_type == SaveType.track\n )\n .all()\n )\n user_saved_track_dict = {save[0]: True for save in user_saved_tracks_query}\n\n # Get current user's followees.\n followees = (\n session.query(Follow.followee_user_id)\n .filter(\n Follow.follower_user_id == current_user_id,\n Follow.is_current == True,\n Follow.is_delete == False\n )\n )\n\n # build dict of track id --> followee reposts\n followee_track_reposts = (\n session.query(Repost)\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.repost_item_id.in_(track_ids),\n Repost.repost_type == RepostType.track,\n Repost.user_id.in_(followees)\n )\n )\n followee_track_reposts = helpers.query_result_to_list(followee_track_reposts)\n for track_repost in followee_track_reposts:\n if track_repost[\"repost_item_id\"] not in followee_track_repost_dict:\n followee_track_repost_dict[track_repost[\"repost_item_id\"]] = []\n followee_track_repost_dict[track_repost[\"repost_item_id\"]].append(track_repost)\n \n # Build dict of track id --> followee saves.\n followee_track_saves = (\n session.query(Save)\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.save_item_id.in_(track_ids),\n Save.save_type == SaveType.track,\n Save.user_id.in_(followees)\n )\n )\n followee_track_saves = helpers.query_result_to_list(followee_track_saves)\n for track_save in followee_track_saves:\n if track_save[\"save_item_id\"] not in followee_track_save_dict:\n followee_track_save_dict[track_save[\"save_item_id\"]] = []\n followee_track_save_dict[track_save[\"save_item_id\"]].append(track_save)\n\n for track in tracks:\n track_id = track[\"track_id\"]\n track[response_name_constants.repost_count] = repost_count_dict.get(track_id, 0)\n track[response_name_constants.save_count] = save_count_dict.get(track_id, 0)\n # current user specific\n track[response_name_constants.followee_reposts] = followee_track_repost_dict.get(track_id, [])\n track[response_name_constants.followee_saves] = followee_track_save_dict.get(track_id, [])\n track[response_name_constants.has_current_user_reposted] = user_reposted_track_dict.get(track_id, False)\n track[response_name_constants.has_current_user_saved] = user_saved_track_dict.get(track['track_id'], False)\n\n return tracks\n\n\n# given list of playlist ids and corresponding playlists, populates each playlist object with:\n# repost_count, save_count\n# if current_user_id available, populates followee_reposts, has_current_user_reposted, has_current_user_saved\ndef populate_playlist_metadata(session, playlist_ids, playlists, repost_types, save_types, current_user_id):\n # build dict of playlist id --> repost count\n playlist_repost_counts = dict(get_repost_counts(session, False, False, playlist_ids, repost_types))\n\n # build dict of playlist id --> save count\n playlist_save_counts = dict(get_save_counts(session, False, False, playlist_ids, save_types))\n\n user_reposted_playlist_dict = {}\n user_saved_playlist_dict = {}\n followee_playlist_repost_dict = {}\n followee_playlist_save_dict = {}\n if current_user_id:\n # has current user reposted any of requested playlist ids\n current_user_playlist_reposts = (\n session.query(Repost.repost_item_id)\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.repost_item_id.in_(playlist_ids),\n Repost.repost_type.in_(repost_types),\n Repost.user_id == current_user_id\n )\n .all()\n )\n user_reposted_playlist_dict = {r[0]: True for r in current_user_playlist_reposts}\n\n # has current user saved any of requested playlist ids\n user_saved_playlists_query = (\n session.query(Save.save_item_id)\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.user_id == current_user_id,\n Save.save_item_id.in_(playlist_ids),\n Save.save_type.in_(save_types)\n )\n .all()\n )\n user_saved_playlist_dict = {save[0]: True for save in user_saved_playlists_query}\n\n # Get current user's followees.\n followee_user_ids = (\n session.query(Follow.followee_user_id)\n .filter(\n Follow.follower_user_id == current_user_id,\n Follow.is_current == True,\n Follow.is_delete == False\n )\n .all()\n )\n \n # Build dict of playlist id --> followee reposts.\n followee_playlist_reposts = (\n session.query(Repost)\n .filter(\n Repost.is_current == True,\n Repost.is_delete == False,\n Repost.repost_item_id.in_(playlist_ids),\n Repost.repost_type.in_(repost_types),\n Repost.user_id.in_(followee_user_ids)\n )\n .all()\n )\n followee_playlist_reposts = helpers.query_result_to_list(followee_playlist_reposts)\n for playlist_repost in followee_playlist_reposts:\n if playlist_repost[\"repost_item_id\"] not in followee_playlist_repost_dict:\n followee_playlist_repost_dict[playlist_repost[\"repost_item_id\"]] = []\n followee_playlist_repost_dict[playlist_repost[\"repost_item_id\"]].append(playlist_repost)\n \n # Build dict of playlist id --> followee saves.\n followee_playlist_saves = (\n session.query(Save)\n .filter(\n Save.is_current == True,\n Save.is_delete == False,\n Save.save_item_id.in_(playlist_ids),\n Save.save_type.in_(save_types),\n Save.user_id.in_(followee_user_ids)\n )\n .all()\n )\n followee_playlist_saves = helpers.query_result_to_list(followee_playlist_saves)\n for playlist_save in followee_playlist_saves:\n if playlist_save[\"save_item_id\"] not in followee_playlist_save_dict:\n followee_playlist_save_dict[playlist_save[\"save_item_id\"]] = []\n followee_playlist_save_dict[playlist_save[\"save_item_id\"]].append(playlist_save)\n\n for playlist in playlists:\n playlist_id = playlist[\"playlist_id\"]\n playlist[response_name_constants.repost_count] = playlist_repost_counts.get(playlist_id, 0)\n playlist[response_name_constants.save_count] = playlist_save_counts.get(playlist_id, 0)\n # current user specific\n playlist[response_name_constants.followee_reposts] = followee_playlist_repost_dict.get(playlist_id, [])\n playlist[response_name_constants.followee_saves] = followee_playlist_save_dict.get(playlist_id, [])\n playlist[response_name_constants.has_current_user_reposted] = \\\n user_reposted_playlist_dict.get(playlist_id, False)\n playlist[response_name_constants.has_current_user_saved] = user_saved_playlist_dict.get(playlist_id, False)\n\n return playlists\n\ndef get_repost_counts_query(session, query_by_user_flag, query_repost_type_flag, filter_ids, repost_types, max_block_number=None):\n query_col = Repost.user_id if query_by_user_flag else Repost.repost_item_id\n\n repost_counts_query = None\n if query_repost_type_flag:\n repost_counts_query = session.query(\n query_col,\n func.count(query_col),\n Repost.repost_type\n )\n else:\n repost_counts_query = session.query(\n query_col,\n func.count(query_col),\n )\n\n repost_counts_query = repost_counts_query.filter(\n Repost.is_current == True,\n Repost.is_delete == False\n )\n\n if filter_ids:\n repost_counts_query = repost_counts_query.filter(\n query_col.in_(filter_ids)\n )\n if repost_types:\n repost_counts_query = repost_counts_query.filter(\n Repost.repost_type.in_(repost_types)\n )\n\n if query_repost_type_flag:\n repost_counts_query = repost_counts_query.group_by(\n query_col,\n Repost.repost_type\n )\n else:\n repost_counts_query = repost_counts_query.group_by(\n query_col\n )\n\n if max_block_number:\n repost_counts_query = repost_counts_query.filter(\n Repost.blocknumber <= max_block_number\n )\n\n return repost_counts_query\n\n# Gets the repost count for users or tracks with the filters specified in the params. \n# The time param {day, week, month, year} is used in generate_trending to create a windowed time frame for repost counts\ndef get_repost_counts(session, query_by_user_flag, query_repost_type_flag, filter_ids, repost_types, max_block_number=None, time=None):\n repost_counts_query = get_repost_counts_query(session, query_by_user_flag, query_repost_type_flag, filter_ids, repost_types, max_block_number)\n\n if time is not None:\n interval = \"NOW() - interval '1 {}'\".format(time)\n repost_counts_query = repost_counts_query.filter(\n Repost.created_at >= text(interval)\n )\n return repost_counts_query.all()\n\ndef get_save_counts_query(session, query_by_user_flag, query_save_type_flag, filter_ids, save_types, max_block_number=None):\n query_col = Save.user_id if query_by_user_flag else Save.save_item_id\n\n save_counts_query = None\n if query_save_type_flag:\n save_counts_query = session.query(\n query_col,\n func.count(query_col),\n Save.save_type\n )\n else:\n save_counts_query = session.query(\n query_col,\n func.count(query_col),\n )\n\n save_counts_query = save_counts_query.filter(\n Save.is_current == True,\n Save.is_delete == False\n )\n\n if filter_ids:\n save_counts_query = save_counts_query.filter(\n Save.save_item_id.in_(filter_ids)\n )\n if save_types:\n save_counts_query = save_counts_query.filter(\n Save.save_type.in_(save_types)\n )\n\n if query_save_type_flag:\n save_counts_query = save_counts_query.group_by(\n query_col,\n Save.save_type\n )\n else:\n save_counts_query = save_counts_query.group_by(\n query_col\n )\n\n if max_block_number:\n save_counts_query = save_counts_query.filter(\n Save.blocknumber <= max_block_number\n )\n\n return save_counts_query\n\n# Gets the save count for users or tracks with the filters specified in the params. \n# The time param {day, week, month, year} is used in generate_trending to create a windowed time frame for save counts\ndef get_save_counts(session, query_by_user_flag, query_save_type_flag, filter_ids, save_types, max_block_number=None, time=None):\n save_counts_query = get_save_counts_query(session, query_by_user_flag, query_save_type_flag, filter_ids, save_types, max_block_number)\n \n if time is not None:\n interval = \"NOW() - interval '1 {}'\".format(time)\n save_counts_query = save_counts_query.filter(\n Save.created_at >= text(interval)\n )\n return save_counts_query.all()\n\ndef get_followee_count_dict(session, user_ids):\n # build dict of user id --> followee count\n followee_counts = (\n session.query(\n Follow.follower_user_id,\n func.count(Follow.follower_user_id)\n )\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.follower_user_id.in_(user_ids)\n )\n .group_by(Follow.follower_user_id)\n .all()\n )\n followee_count_dict = {user_id: followee_count for (user_id, followee_count) in followee_counts}\n return followee_count_dict\n\ndef get_follower_count_dict(session, user_ids, max_block_number=None):\n follower_counts = (\n session.query(\n Follow.followee_user_id,\n func.count(Follow.followee_user_id)\n )\n .filter(\n Follow.is_current == True,\n Follow.is_delete == False,\n Follow.followee_user_id.in_(user_ids)\n )\n )\n\n if max_block_number:\n follower_counts = follower_counts.filter(Follow.blocknumber <= max_block_number)\n\n follower_counts = (\n follower_counts.group_by(Follow.followee_user_id).all()\n )\n\n follower_count_dict = \\\n {user_id: follower_count for (user_id, follower_count) in follower_counts}\n return follower_count_dict\n\n\ndef get_track_play_counts(track_ids):\n track_listen_counts = {}\n\n if not track_ids:\n return track_listen_counts\n\n identity_url = shared_config['discprov']['identity_service_url']\n # Create and query identity service endpoint\n identity_tracks_endpoint = urljoin(identity_url, 'tracks/listens')\n\n post_body = {}\n post_body['track_ids'] = track_ids\n try:\n resp = requests.post(identity_tracks_endpoint, json=post_body)\n except Exception as e:\n logger.error(\n f'Error retrieving play count - {identity_tracks_endpoint}, {e}'\n )\n return track_listen_counts\n\n json_resp = resp.json()\n keys = list(resp.json().keys())\n if not keys:\n return track_listen_counts\n\n # Scenario should never arise, since we don't impose date parameter on initial query\n if len(keys) != 1:\n raise Exception('Invalid number of keys')\n\n # Parse listen query results into track listen count dictionary\n date_key = keys[0]\n listen_count_json = json_resp[date_key]\n if 'listenCounts' in listen_count_json:\n for listen_info in listen_count_json['listenCounts']:\n current_id = listen_info['trackId']\n track_listen_counts[current_id] = listen_info['listens']\n return track_listen_counts\n\ndef get_pagination_vars():\n limit = min(\n max(request.args.get(\"limit\", default=defaultLimit, type=int), minLimit),\n maxLimit,\n )\n offset = max(request.args.get(\"offset\", default=defaultOffset, type=int), minOffset)\n return (limit, offset)\n\n\ndef paginate_query(query_obj, apply_offset=True):\n (limit, offset) = get_pagination_vars()\n query_obj = query_obj.limit(limit)\n return query_obj.offset(offset) if apply_offset else query_obj\n\ndef get_genre_list(genre):\n genre_list = []\n genre_list.append(genre)\n if genre == 'Electronic':\n genre_list = genre_list + electronic_sub_genres\n return genre_list\n\ndef get_users_by_id(session, user_ids):\n user_query = session.query(User).filter(User.is_current == True, User.wallet != None, User.handle != None)\n users_results = user_query.filter(User.user_id.in_(user_ids)).all()\n users = helpers.query_result_to_list(users_results)\n\n current_user_id = get_current_user_id(required=False)\n # bundle peripheral info into user results\n populated_users = populate_user_metadata(session, user_ids, users, current_user_id)\n user_map = {}\n for user in populated_users:\n user_map[user['user_id']] = user\n\n return user_map\n\n# Given an array of tracks and/or playlists, return an array of unique user ids\ndef get_users_ids(results):\n user_ids = []\n for result in results:\n if 'playlist_owner_id' in result:\n user_ids.append(int(result[\"playlist_owner_id\"]))\n elif 'owner_id' in result:\n user_ids.append(int(result['owner_id']))\n # Remove duplicate user ids\n user_ids = list(set(user_ids))\n return user_ids\n","sub_path":"discovery-provider/src/queries/query_helpers.py","file_name":"query_helpers.py","file_ext":"py","file_size_in_byte":28023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"348336393","text":"import torch\n\nfrom const import *\nfrom model.Transformer import Transformer\n\n\nclass TransformerHandler():\n def __init__(self, encoder_vocab: list, decoder_vocab: list, decoder_sos_idx: int, decoder_eos_idx: int = None):\n super(TransformerHandler, self).__init__()\n self.input = encoder_vocab\n self.output = decoder_vocab\n self.encoder_dim = len(encoder_vocab)\n self.decoder_dim = len(decoder_vocab)\n self.decoder_sos_idx = decoder_sos_idx\n self.decoder_pad_idx = decoder_vocab.index(PAD)\n self.encoder_pad_idx = encoder_vocab.index(PAD)\n\n if decoder_eos_idx is None:\n self.decoder_eos_idx = decoder_vocab.index(EOS)\n else:\n self.decoder_eos_idx = decoder_eos_idx\n self.transformer = Transformer(self.encoder_dim, self.decoder_dim, self.encoder_pad_idx, self.decoder_pad_idx)\n\n def forward(self, src: torch.Tensor, trg: torch.Tensor):\n src_mask = self.get_pad_mask(src, self.encoder_pad_idx)\n trg_mask = self.get_pad_mask(trg, self.decoder_pad_idx)\n output = self.transformer.forward(src.unsqueeze(1), trg.unsqueeze(1), src_mask, trg_mask)\n\n return output\n\n def get_pad_mask(self, seq, pad_idx):\n return (seq != pad_idx)\n","sub_path":"TransformerHandler.py","file_name":"TransformerHandler.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"648568790","text":"# Given two strings s and t, determine if they are isomorphic.\n\n# Two strings are isomorphic if the characters in s can be replaced to get t.\n\n# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.\n\n# For example,\n# Given \"egg\", \"add\", return true.\n\n# Given \"foo\", \"bar\", return false.\n\n# Given \"paper\", \"title\", return true.\n\nclass Solution(object):\n def isIsomorphic(self, s, t):\n smap, tmap = dict(), dict()\n for i in xrange(len(s)):\n if smap.has_key(s[i]):\n if smap[s[i]] != t[i]:\n return False\n elif tmap.has_key(t[i]):\n if tmap[t[i]] != s[i]:\n return False\n else:\n smap[s[i]] = t[i]\n tmap[t[i]] = s[i]\n return True\n","sub_path":"LEETCODE/Isomorphic_String.py","file_name":"Isomorphic_String.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"338920014","text":"\"\"\"\nAuthor: Travis Law\nDate: 08/19/2016\nVersion: 3.5.2\nSolutions for CodeAcademy Python Course\nUnit: 1\nLesson: Tip Calculator\nProblem: 5. The Total\nmisc: Done as part of the Regev Group Python Club at the Broad Institute.\n CodeAcademy uses Python 2.7.3, we are using Python 3.5.2.\n\"\"\"\nmeal = 44.50\ntax = 0.0675\ntip = 0.15\n\nmeal = meal + meal * tax\ntotal = meal + meal * tip\n\ntotalPrint = \"%.2f\" % total\n\nprint(totalPrint)\n","sub_path":"CodeAcademy/Lesson 02 - Tip Calculator/05 - The Total.py","file_name":"05 - The Total.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"493621664","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 8 16:57:35 2019\n\n@author: Roy\n\"\"\"\n\nx = 5\ny = 12\n\nz = x + y\n\nprint(z)\n\n# 1x = 3 Variables cannot start with a number\n\n# print = 7\n# new variable = 9 no spaces n variable names but an underscore is ok\nnew_variable = 9\n\n# z = x - y\n\n# a = 2.5\n# b = 3.14159\n# c = b * a ** 2 # c is equal to b multiplied by a^2 # This is difficult to follow so:\n\n# ## write with proper variable names:\n\n# radius = 2.5\n# pi =3.14159\n# area = pi * radius ** 2\n\n# phrase_1 = 'The cat sat on the mat!'\n# phrase_2 = 'And so did the dog!'\n# phrase_3 = phrase_1 + ' ' + phrase_2\n\nuser_input = int(input('How many apples do you have?\\n >>>> '))\n","sub_path":"Part4/Variables.py","file_name":"Variables.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"535977664","text":"from abc import ABCMeta, abstractmethod\nfrom functools import wraps\nfrom threading import Lock\nfrom typing import Optional, Any, Mapping, Type, Callable\nfrom uuid import uuid4, UUID\n\nimport requests\nfrom requests.exceptions import RequestException\n\nfrom .base import _BEFORE_HOOK_TYPE, _AFTER_HOOK_TYPE, _ERROR_HOOK_TYPE\nfrom .task import Task, _task_complete, _task_fail\nfrom ..base import random_token, ControllableContext, get_http_engine_class, get_values_from_response\nfrom ..config import DEFAULT_CHANNEL, DEFAULT_SLAVE_PORT\n\n_COMPLETE_TRIGGER_NAME = '__TASK_COMPLETE__'\n_FAIL_TRIGGER_NAME = '__TASK_FAIL__'\n\n\nclass _ISlaveConnection(ControllableContext, metaclass=ABCMeta):\n\n @abstractmethod\n def connect(self):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n def disconnect(self):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n def new_task(self, data: Optional[Mapping[str, Any]] = None):\n raise NotImplementedError # pragma: no cover\n\n def start(self):\n self.connect()\n\n def close(self):\n self.disconnect()\n\n\nclass SlaveConnection(_ISlaveConnection, metaclass=ABCMeta):\n\n def __init__(\n self,\n host: str,\n port: Optional[int] = None,\n https: bool = False,\n channel: Optional[int] = None,\n my_address: Optional[str] = None,\n token: Optional[str] = None\n ):\n # meta info part\n self.__channel = channel or DEFAULT_CHANNEL\n self.__my_address = my_address\n self.__token = token or random_token()\n\n # request part\n self.__http_engine = get_http_engine_class(\n headers={\n 'Channel': lambda: str(self.__channel),\n 'Token': lambda: self.__token,\n }\n )()(host, port or DEFAULT_SLAVE_PORT, https)\n\n # threading part\n self.__lock = Lock()\n self.__is_connected = False\n\n # task part\n self.__tasks = {}\n\n self.__init_triggers()\n\n def __request(self, method: str, path: str, data: Optional[Mapping[str, Any]] = None) -> requests.Response:\n return self.__http_engine.request(method, path, data)\n\n @property\n def is_connected(self) -> bool:\n with self.__lock:\n return self.__is_connected\n\n def _before_connect(self) -> Mapping[str, Any]:\n pass # pragma: no cover\n\n def _after_connect(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str, Any]]\n ) -> Any:\n pass # pragma: no cover\n\n def _error_connect(self, error: RequestException) -> Any:\n raise error # pragma: no cover\n\n def __connect(self):\n try:\n response = self.__request(\n 'POST', '/connect', {\n 'master': {\n 'address': self.__my_address,\n },\n 'data': (self._before_connect() or {})\n }\n )\n except RequestException as err:\n return self._error_connect(err)\n else:\n self.__is_connected = True\n return self._after_connect(*get_values_from_response(response))\n\n def connect(self):\n with self.__lock:\n return self.__connect()\n\n def _before_disconnect(self) -> Mapping[str, Any]:\n pass # pragma: no cover\n\n def _after_disconnect(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str, Any]]\n ) -> Any:\n pass # pragma: no cover\n\n def _error_disconnect(self, error: RequestException) -> Any:\n raise error # pragma: no cover\n\n def __disconnect(self):\n try:\n response = self.__request('DELETE', '/disconnect', {\n 'data': self._before_disconnect() or {},\n })\n except RequestException as err:\n print(err)\n return self._error_disconnect(err)\n else:\n self.__is_connected = False\n return self._after_disconnect(*get_values_from_response(response))\n\n def disconnect(self):\n with self.__lock:\n return self.__disconnect()\n\n def _after_update_learner(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str, Any]]\n ) -> Any:\n return data\n\n def _error_update_learners(self, error: RequestException) -> Any:\n raise error\n\n def __update_learners(self, learners):\n try:\n response = self.__request('POST', '/learners', learners)\n except RequestException as err:\n return self._error_update_learners(err)\n else:\n return self._after_update_learner(*get_values_from_response(response))\n\n def update_learners(self, learners):\n with self.__lock:\n return self.__update_learners(learners)\n\n def _before_new_task(self, data: Optional[Mapping[str, Any]] = None) -> Mapping[str, Any]:\n return data # pragma: no cover\n\n def _after_new_task(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str, Any]]\n ) -> Any:\n pass # pragma: no cover\n\n def _error_new_task(self, error: RequestException) -> Any:\n raise error # pragma: no cover\n\n def new_task(self, data: Optional[Mapping[str, Any]] = None) -> Task:\n with self.__lock:\n _uuid = uuid4()\n _task = Task(\n http_engine=self.__http_engine,\n data=data,\n task_id=_uuid,\n before_task_start=self._before_new_task,\n after_task_start=self._after_new_task,\n error_task_start=self._error_new_task,\n )\n\n self.__tasks[_uuid] = _task\n return _task\n\n def __task_complete(self, task_id: UUID, task_result: Mapping[str, Any]):\n _task = self.__tasks[task_id]\n _task_complete(_task, task_result)\n del self.__tasks[task_id]\n\n def __task_fail(self, task_id: UUID, task_result: Mapping[str, Any]):\n _task = self.__tasks[task_id]\n _task_fail(_task, task_result)\n del self.__tasks[task_id]\n\n def __task_complete_trigger(self, task_id: UUID, task_result: Mapping[str, Any]):\n with self.__lock:\n if task_id in self.__tasks.keys():\n return self.__task_complete(task_id, task_result)\n else:\n raise KeyError(\"Task {uuid} not found in this connection.\".format(uuid=repr(str(task_id))))\n\n def __task_fail_trigger(self, task_id: UUID, task_result: Mapping[str, Any]):\n with self.__lock:\n if task_id in self.__tasks.keys():\n return self.__task_fail(task_id, task_result)\n else:\n raise KeyError(\"Task {uuid} not found in this connection.\".format(uuid=repr(str(task_id))))\n\n def __init_triggers(self):\n setattr(self, _COMPLETE_TRIGGER_NAME, self.__task_complete_trigger)\n setattr(self, _FAIL_TRIGGER_NAME, self.__task_fail_trigger)\n\n\ndef _connection_task_complete(connection: SlaveConnection, task_id: UUID, task_result: Mapping[str, Any]):\n return getattr(connection, _COMPLETE_TRIGGER_NAME)(task_id, task_result)\n\n\ndef _connection_task_fail(connection: SlaveConnection, task_id: UUID, task_result: Mapping[str, Any]):\n return getattr(connection, _FAIL_TRIGGER_NAME)(task_id, task_result)\n\n\nclass SlaveConnectionProxy(_ISlaveConnection):\n\n def __init__(\n self,\n connection: SlaveConnection,\n after_connect: Optional[Callable] = None,\n after_disconnect: Optional[Callable] = None\n ):\n self.__connection = connection\n self.__lock = Lock()\n self.__after_connect = after_connect\n self.__after_disconnect = after_disconnect\n\n self.__init_triggers()\n\n @property\n def is_connected(self) -> bool:\n with self.__lock:\n return self.__connection.is_connected\n\n def connect(self):\n with self.__lock:\n result = self.__connection.connect()\n if self.__after_connect is not None:\n self.__after_connect(connection=self)\n return result\n\n def disconnect(self):\n with self.__lock:\n result = self.__connection.disconnect()\n if self.__after_disconnect is not None:\n self.__after_disconnect(connection=self)\n return result\n\n def new_task(self, data: Optional[Mapping[str, Any]] = None):\n with self.__lock:\n return self.__connection.new_task(data)\n \n def update_learners(self, learners):\n with self.__lock:\n return self.__connection.update_learners(learners)\n\n def __task_complete_trigger(self, task_id: UUID, task_result: Mapping[str, Any]):\n with self.__lock:\n return _connection_task_complete(self.__connection, task_id, task_result)\n\n def __task_fail_trigger(self, task_id: UUID, task_result: Mapping[str, Any]):\n with self.__lock:\n return _connection_task_fail(self.__connection, task_id, task_result)\n\n def __init_triggers(self):\n setattr(self, _COMPLETE_TRIGGER_NAME, self.__task_complete_trigger)\n setattr(self, _FAIL_TRIGGER_NAME, self.__task_fail_trigger)\n\n\ndef _proxy_task_complete(proxy: SlaveConnectionProxy, task_id: UUID, task_result: Mapping[str, Any]):\n return getattr(proxy, _COMPLETE_TRIGGER_NAME)(task_id, task_result)\n\n\ndef _proxy_task_fail(proxy: SlaveConnectionProxy, task_id: UUID, task_result: Mapping[str, Any]):\n return getattr(proxy, _FAIL_TRIGGER_NAME)(task_id, task_result)\n\n\ndef _slave_task_complete(connection: _ISlaveConnection, task_id: UUID, task_result: Mapping[str, Any]):\n if isinstance(connection, SlaveConnection):\n return _connection_task_complete(connection, task_id, task_result)\n elif isinstance(connection, SlaveConnectionProxy):\n return _proxy_task_complete(connection, task_id, task_result)\n else:\n raise TypeError(\n \"{expect1} or {expect2} expected, but {actual} found.\".format(\n expect1=SlaveConnection.__name__,\n expect2=SlaveConnectionProxy.__name__,\n actual=type(connection).__name__,\n )\n )\n\n\ndef _slave_task_fail(connection: _ISlaveConnection, task_id: UUID, task_result: Mapping[str, Any]):\n if isinstance(connection, SlaveConnection):\n return _connection_task_fail(connection, task_id, task_result)\n elif isinstance(connection, SlaveConnectionProxy):\n return _proxy_task_fail(connection, task_id, task_result)\n else:\n raise TypeError(\n \"{expect1} or {expect2} expected, but {actual} found.\".format(\n expect1=SlaveConnection.__name__,\n expect2=SlaveConnectionProxy.__name__,\n actual=type(connection).__name__,\n )\n )\n\n\ndef _default_wrap(func: Callable) -> Callable:\n\n @wraps(func)\n def _new_func(*args, **kwargs):\n if func:\n return func(*args, **kwargs)\n else:\n return None\n\n return _new_func\n\n\ndef _get_connection_class(\n before_new_task: Optional[_BEFORE_HOOK_TYPE] = None,\n after_new_task: Optional[_AFTER_HOOK_TYPE] = None,\n error_new_task: Optional[_ERROR_HOOK_TYPE] = None,\n before_connect: Optional[_BEFORE_HOOK_TYPE] = None,\n after_connect: Optional[_AFTER_HOOK_TYPE] = None,\n error_connect: Optional[_ERROR_HOOK_TYPE] = None,\n before_disconnect: Optional[_BEFORE_HOOK_TYPE] = None,\n after_disconnect: Optional[_AFTER_HOOK_TYPE] = None,\n error_disconnect: Optional[_ERROR_HOOK_TYPE] = None,\n) -> Type[SlaveConnection]:\n\n class _Connection(SlaveConnection):\n\n def _before_connect(self) -> Mapping[str, Any]:\n return _default_wrap(before_connect)() or {}\n\n def _after_connect(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str,\n Any]]\n ) -> Any:\n return _default_wrap(after_connect)(status_code, success, code, message, data)\n\n def _error_connect(self, error: RequestException) -> Any:\n return _default_wrap(error_connect)(error)\n\n def _before_disconnect(self) -> Mapping[str, Any]:\n return _default_wrap(before_disconnect)() or {}\n\n def _after_disconnect(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str,\n Any]]\n ) -> Any:\n return _default_wrap(after_disconnect)(status_code, success, code, message, data)\n\n def _error_disconnect(self, error: RequestException) -> Any:\n return _default_wrap(error_disconnect)(error)\n\n def _before_new_task(self, data: Optional[Mapping[str, Any]] = None) -> Mapping[str, Any]:\n return _default_wrap(before_new_task)(data) or {}\n\n def _after_new_task(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str,\n Any]]\n ) -> Any:\n return _default_wrap(after_new_task)(status_code, success, code, message, data)\n\n def _error_new_task(self, error: RequestException) -> Any:\n return _default_wrap(error_new_task)(error)\n\n return _Connection\n\nclass ServerConnection:\n\n def __init__(\n self,\n host: str,\n port: Optional[int] = None,\n api_version: str = \"v1alpha1\",\n https: bool = False,\n namespace: str = None,\n name: str = None,\n ):\n # request part\n self.__http_engine = get_http_engine_class(headers={})()(host, port, https)\n self.__api_version = api_version\n self.__namespace = namespace\n self.__my_name = name\n\n @property\n def api_version(self):\n return self.__api_version\n\n def __prefix_with_api_version(self, path):\n return self.__api_version + path\n\n def get_replicas(self, name: str = None):\n try:\n if name is None:\n params = {\"namespace\": self.__namespace, \"coordinator\": self.__my_name}\n else:\n params = {\"namespace\": self.__namespace, \"name\": name}\n response = self.__http_engine.request('GET', self.__prefix_with_api_version('/replicas'), params=params)\n except RequestException as err:\n return self._error_request(err)\n else:\n return self._after_request(*get_values_from_response(response))\n \n def post_replicas(self, data):\n try:\n data.update(\n {\n \"namespace\": self.__namespace, \n \"coordinator\": self.__my_name\n }\n )\n response = self.__http_engine.request('POST', self.__prefix_with_api_version('/replicas'), data=data)\n except RequestException as err:\n return self._error_request(err)\n else:\n return self._after_request(*get_values_from_response(response))\n\n def post_replicas_failed(self, collectors=[], learners=[]):\n try:\n data = {\n \"namespace\": self.__namespace, \n \"coordinator\": self.__my_name,\n \"collectors\": collectors,\n \"learners\": learners,\n }\n response = self.__http_engine.request('POST', self.__prefix_with_api_version('/replicas/failed'), data=data)\n except RequestException as err:\n return self._error_request(err)\n else:\n return self._after_request(*get_values_from_response(response))\n\n def delete_replicas(self, n_collectors=0, n_learners=0):\n try:\n data = {\n \"namespace\": self.__namespace, \n \"coordinator\": self.__my_name,\n \"collectors\": {\n \"replicas\": n_collectors, \n },\n \"learners\":{\n \"replicas\": n_learners,\n }\n }\n response = self.__http_engine.request('DELETE', self.__prefix_with_api_version('/replicas'), data=data)\n except RequestException as err:\n return self._error_request(err)\n else:\n return self._after_request(*get_values_from_response(response))\n\n def _after_request(\n self, status_code: int, success: bool, code: int, message: Optional[str], data: Optional[Mapping[str, Any]]\n ) -> Any:\n return success, code, message, data\n \n def _error_request(self, error: RequestException) -> Any:\n # raise error\n pass","sub_path":"config/samples/di-mock/interaction/master/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":17043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"126355745","text":"class Body:\n def _init_(self, mass, x, y, vx, vy, pixel_radius, r, g, b):\n self.mass = mass\n self.x = x\n self.y = y\n self.vx = vx\n self.vy = vy\n self.r = r\n self.g = g\n self.b = b\n self.pixel_radius = pixel_radius\n\n def distance(self, other):\n dx = self.x - other.x\n dy = self.y - other.y\n s = sqrt(dx * dx + dy * dy)\n return s\n\n def update_position(self, timestep):\n self.x += self.vx * timestep\n self.y += self.vy * timestep\n\n def update_velocity(self, ax, ay, timestep):\n self.vx += ax * timestep\n self.vy += ay * timestep\n\n def draw(self, cx, cy, pixels_per_meter):\n set_fill_color(self.r, self.g, self.b)\n draw_circle(cx + self.x * pixels_per_meter, cy + self.y * pixels_per_meter, self.pixel_radius)","sub_path":"CS1/LAB/LAB 2/trials/body00.py","file_name":"body00.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"643420074","text":"import sys\nimport threading\nimport time\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom collections import OrderedDict\nfrom contextlib import ExitStack\nfrom enum import Enum\nfrom typing import Dict, List, NamedTuple, Optional\n\nfrom dagster import check\nfrom dagster.core.errors import DagsterInvariantViolationError, DagsterRepositoryLocationLoadError\nfrom dagster.core.host_representation import (\n GrpcServerRepositoryLocation,\n RepositoryLocation,\n RepositoryLocationOrigin,\n)\nfrom dagster.core.host_representation.grpc_server_registry import (\n GrpcServerRegistry,\n ProcessGrpcServerRegistry,\n)\nfrom dagster.core.host_representation.grpc_server_state_subscriber import (\n LocationStateChangeEvent,\n LocationStateChangeEventType,\n LocationStateSubscriber,\n)\nfrom dagster.grpc.server_watcher import create_grpc_watch_thread\nfrom dagster.utils.error import SerializableErrorInfo, serializable_error_info_from_exc_info\n\n\nclass IWorkspace(ABC):\n @abstractmethod\n def get_location(self, origin):\n \"\"\"Return the RepositoryLocation for the given RepositoryLocationOrigin, or raise an error if there is an error loading it.\"\"\"\n\n\n# For locations that are loaded asynchronously\nclass WorkspaceLocationLoadStatus(Enum):\n LOADING = \"LOADING\" # Waiting for location to load or update\n LOADED = \"LOADED\" # Finished loading (may be an error)\n\n\nclass WorkspaceLocationEntry(NamedTuple):\n origin: RepositoryLocationOrigin\n repository_location: Optional[RepositoryLocation]\n load_error: Optional[SerializableErrorInfo]\n load_status: WorkspaceLocationLoadStatus\n display_metadata: Dict[str, str]\n update_timestamp: float\n\n\nclass Workspace(IWorkspace):\n \"\"\"An IWorkspace that maintains a fixed list of origins, loading repositorylocations\n for all of them on initialization.\"\"\"\n\n def __init__(self, workspace_load_target, grpc_server_registry=None):\n self._stack = ExitStack()\n\n # Guards changes to _location_dict, _location_error_dict, and _location_origin_dict\n self._lock = threading.Lock()\n\n # Only ever set up by main thread\n self._watch_thread_shutdown_events = {}\n self._watch_threads = {}\n\n self._state_subscribers: List[LocationStateSubscriber] = []\n\n from .cli_target import WorkspaceLoadTarget\n\n self._workspace_load_target = check.opt_inst_param(\n workspace_load_target, \"workspace_load_target\", WorkspaceLoadTarget\n )\n\n if grpc_server_registry:\n self._grpc_server_registry = check.inst_param(\n grpc_server_registry, \"grpc_server_registry\", GrpcServerRegistry\n )\n else:\n self._grpc_server_registry = self._stack.enter_context(\n ProcessGrpcServerRegistry(reload_interval=0, heartbeat_ttl=30)\n )\n\n self._location_entry_dict = OrderedDict()\n\n with self._lock:\n self._load_workspace()\n\n def _load_workspace(self):\n assert self._lock.locked()\n repository_location_origins = (\n self._workspace_load_target.create_origins() if self._workspace_load_target else []\n )\n\n check.list_param(\n repository_location_origins,\n \"repository_location_origins\",\n of_type=RepositoryLocationOrigin,\n )\n\n self._location_entry_dict = OrderedDict()\n\n for origin in repository_location_origins:\n check.invariant(\n self._location_entry_dict.get(origin.location_name) is None,\n 'Cannot have multiple locations with the same name, got multiple \"{name}\"'.format(\n name=origin.location_name,\n ),\n )\n\n if origin.supports_server_watch:\n self._start_watch_thread(origin)\n self._location_entry_dict[origin.location_name] = self._load_location(origin)\n\n # Can be overidden in subclasses that need different logic for loading repository\n # locations from origins\n def create_location_from_origin(self, origin):\n if not self._grpc_server_registry.supports_origin(origin):\n return origin.create_location()\n else:\n endpoint = (\n self._grpc_server_registry.reload_grpc_endpoint(origin)\n if self._grpc_server_registry.supports_reload\n else self._grpc_server_registry.get_grpc_endpoint(origin)\n )\n\n return GrpcServerRepositoryLocation(\n origin=origin,\n server_id=endpoint.server_id,\n port=endpoint.port,\n socket=endpoint.socket,\n host=endpoint.host,\n heartbeat=True,\n watch_server=False,\n grpc_server_registry=self._grpc_server_registry,\n )\n\n def add_state_subscriber(self, subscriber):\n self._state_subscribers.append(subscriber)\n\n def _send_state_event_to_subscribers(self, event: LocationStateChangeEvent) -> None:\n check.inst_param(event, \"event\", LocationStateChangeEvent)\n for subscriber in self._state_subscribers:\n subscriber.handle_event(event)\n\n def _start_watch_thread(self, origin):\n location_name = origin.location_name\n check.invariant(location_name not in self._watch_thread_shutdown_events)\n client = origin.create_client()\n shutdown_event, watch_thread = create_grpc_watch_thread(\n location_name,\n client,\n on_updated=lambda location_name, new_server_id: self._send_state_event_to_subscribers(\n LocationStateChangeEvent(\n LocationStateChangeEventType.LOCATION_UPDATED,\n location_name=location_name,\n message=\"Server has been updated.\",\n server_id=new_server_id,\n )\n ),\n on_error=lambda location_name: self._send_state_event_to_subscribers(\n LocationStateChangeEvent(\n LocationStateChangeEventType.LOCATION_ERROR,\n location_name=location_name,\n message=\"Unable to reconnect to server. You can reload the server once it is \"\n \"reachable again\",\n )\n ),\n )\n self._watch_thread_shutdown_events[location_name] = shutdown_event\n self._watch_threads[location_name] = watch_thread\n watch_thread.start()\n\n def _load_location(self, origin):\n assert self._lock.locked()\n location_name = origin.location_name\n location = None\n error = None\n try:\n location = self.create_location_from_origin(origin)\n except Exception: # pylint: disable=broad-except\n error = serializable_error_info_from_exc_info(sys.exc_info())\n warnings.warn(\n \"Error loading repository location {location_name}:{error_string}\".format(\n location_name=location_name, error_string=error.to_string()\n )\n )\n\n return WorkspaceLocationEntry(\n origin=origin,\n repository_location=location,\n load_error=error,\n load_status=WorkspaceLocationLoadStatus.LOADED,\n display_metadata=location.get_display_metadata()\n if location\n else origin.get_display_metadata(),\n update_timestamp=time.time(),\n )\n\n def create_snapshot(self):\n with self._lock:\n return self._location_entry_dict.copy()\n\n @property\n def repository_locations_count(self):\n with self._lock:\n return len(self._location_entry_dict)\n\n @property\n def repository_location_names(self):\n with self._lock:\n return list(self._location_entry_dict)\n\n def has_repository_location(self, location_name):\n check.str_param(location_name, \"location_name\")\n return self.get_repository_location(location_name) != None\n\n def get_repository_location(self, location_name: str) -> Optional[RepositoryLocation]:\n with self._lock:\n return (\n self._location_entry_dict.get(location_name).repository_location\n if location_name in self._location_entry_dict\n else None\n )\n\n def has_repository_location_error(self, location_name):\n check.str_param(location_name, \"location_name\")\n with self._lock:\n return (\n location_name in self._location_entry_dict\n and self._location_entry_dict[location_name].load_error\n )\n\n def reload_repository_location(self, location_name):\n # Can be called from a background thread\n with self._lock:\n # Relying on GC to clean up the old location once nothing else\n # is referencing it\n self._location_entry_dict[location_name] = self._load_location(\n self._location_entry_dict[location_name].origin\n )\n\n def shutdown_repository_location(self, location_name):\n with self._lock:\n self._location_entry_dict[location_name].origin.shutdown_server()\n\n def reload_workspace(self):\n # Can be called from a background thread\n with self._lock:\n self._cleanup_locations()\n self._load_workspace()\n\n def _cleanup_locations(self):\n assert self._lock.locked()\n for _, event in self._watch_thread_shutdown_events.items():\n event.set()\n for _, watch_thread in self._watch_threads.items():\n watch_thread.join()\n\n self._watch_thread_shutdown_events = {}\n self._watch_threads = {}\n\n for entry in self._location_entry_dict.values():\n if entry.repository_location:\n entry.repository_location.cleanup()\n\n self._location_entry_dict = OrderedDict()\n\n def get_location(self, origin):\n with self._lock:\n location_name = origin.location_name\n location_entry = self._location_entry_dict.get(location_name)\n if not location_entry:\n raise DagsterInvariantViolationError(\n f\"Location {location_name} does not exist in workspace\"\n )\n\n if location_entry.repository_location:\n return location_entry.repository_location\n\n error_info = location_entry.load_error\n raise DagsterRepositoryLocationLoadError(\n f\"Failure loading {location_name}: {error_info.to_string()}\",\n load_error_infos=[error_info],\n )\n\n def __enter__(self):\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n with self._lock:\n self._cleanup_locations()\n self._stack.close()\n","sub_path":"python_modules/dagster/dagster/cli/workspace/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":10845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"387183377","text":"from base64 import b64decode, b64encode\nfrom binascii import Error as binasciiError\nfrom Crypto.Hash import SHA256\nfrom Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5\nfrom Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5\nfrom Crypto.PublicKey import RSA\n\n\ndef rsa_import_key_pem(file_path):\n rsa_object = RSA.import_key(open(file_path, 'r').read())\n return rsa_object\n\n\n# response middleware sign\nserver_sign_pub_key = rsa_import_key_pem('')\nserver_sign_pri_key = rsa_import_key_pem('')\n\n\ndef en(pub_key, text):\n cipher = Cipher_pkcs1_v1_5.new(pub_key)\n cipher_text = cipher.encrypt(text.encode())\n return b64encode(cipher_text).decode()\n\n\ndef de(pri_key, text):\n try:\n cipher_text = b64decode(text)\n except binasciiError:\n return ''\n else:\n cipher = Cipher_pkcs1_v1_5.new(pri_key)\n try:\n message = cipher.decrypt(cipher_text, None)\n except ValueError:\n return ''\n else:\n return message.decode() if message else ''\n\n\ndef sign(pri_key, text):\n msg_hash = SHA256.new(b64encode(text.encode()))\n return b64encode(Signature_pkcs1_v1_5.new(pri_key).sign(msg_hash))\n\n\ndef verify(pub_key, text_hash, signature):\n try:\n return Signature_pkcs1_v1_5.new(pub_key).verify(text_hash, b64decode(signature))\n except (ValueError, TypeError):\n return False\n","sub_path":"backend/core/utils/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"25871862","text":"N = int(input())\nnumber = list(map(int, input().split()))\nnew_list = [0]\nlength = 0\nfor i in number:\n if(new_list[-1]new_list[mid]):\n start = mid + 1\n else:\n end = mid\n new_list[start] = i\n\nprint(length)","sub_path":"BOJ/[12015] 가장 긴 증가하는 부분 수열 2/n__aj22/12015_LIS2.py","file_name":"12015_LIS2.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"153487495","text":"import requests\nfrom flask import current_app\nfrom app.response import *\n\n\ndef validate_captcha(response_token, action_name):\n\tparams = {\n\t\t\"secret\": current_app.config.get(\"CAPTCHA_SECRET\"),\n\t\t\"response\": response_token\n\t}\n\n\tresponse = requests.post('https://www.google.com/recaptcha/api/siteverify', params=params)\n\tdata = response.json()\n\n\tif 'success' not in data:\n\t\traise APIException(APIException.unknown, 500)\n\n\tif not data['success'] or data['score'] < 0.5:\n\t\traise APIException(APIException.invalidCaptcha, 400)","sub_path":"app/util/captcha.py","file_name":"captcha.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"403928830","text":"# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\nimport os\n\nfrom azure.keyvault.administration import (\n KeyVaultAccessControlClient,\n KeyVaultDataAction,\n KeyVaultPermission,\n KeyVaultRoleScope,\n)\nfrom azure.identity import DefaultAzureCredential\n\n# ----------------------------------------------------------------------------------------------------------\n# Prerequisites:\n# 1. A managed HSM (https://docs.microsoft.com/azure/key-vault/managed-hsm/quick-create-cli)\n#\n# 2. azure-keyvault-administration and azure-identity libraries (pip install these)\n#\n# 3. Set environment variable MANAGED_HSM_URL with the URL of your managed HSM\n# \n# 4. Set up your environment to use azure-identity's DefaultAzureCredential. To authenticate a service principal with\n# environment variables, set AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID\n# (See https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/keyvault/azure-keyvault-administration#authenticate-the-client)\n#\n# ----------------------------------------------------------------------------------------------------------\n# Sample - demonstrates role definition and assignment operations for Managed HSM\n#\n# 1. Create a role definition (set_role_definition)\n#\n# 2. Update a role definition (set_role_definition)\n#\n# 3. Create a role assignment (create_role_assignment)\n#\n# 4. Delete a role assignment (delete_role_assignment)\n#\n# 5. Delete a role definition (delete_role_definition)\n# ----------------------------------------------------------------------------------------------------------\n\nMANAGED_HSM_URL = os.environ[\"MANAGED_HSM_URL\"]\n\n# Instantiate an access control client that will be used to call the service.\n# Here we use the DefaultAzureCredential, but any azure-identity credential can be used.\ncredential = DefaultAzureCredential()\nclient = KeyVaultAccessControlClient(vault_url=MANAGED_HSM_URL, credential=credential)\n\n# Let's first create a custom role definition. This role permits creating keys in a Managed HSM.\n# We'll provide a friendly role name, and let a unique role definition name (a GUID) be generated for us.\nprint(\"\\n.. Create a role definition\")\nrole_name = \"customRole\"\nscope = KeyVaultRoleScope.GLOBAL\npermissions = [KeyVaultPermission(data_actions=[KeyVaultDataAction.CREATE_HSM_KEY])]\nrole_definition = client.set_role_definition(scope=scope, role_name=role_name, permissions=permissions)\nprint(\"Role definition '{}' created successfully.\".format(role_definition.role_name))\n\n# Let's update our role definition to allow reading keys, but not allow creating keys.\n# To update an existing definition, pass the name keyword argument to set_role_definition. This is the unique name\n# of the role definition, which is stored in KeyVaultRoleDefinition.name.\nprint(\"\\n.. Update a role definition\")\nnew_permissions = [\n KeyVaultPermission(\n data_actions=[KeyVaultDataAction.READ_HSM_KEY],\n not_data_actions=[KeyVaultDataAction.CREATE_HSM_KEY]\n )\n]\nunique_definition_name = role_definition.name\nupdated_definition = client.set_role_definition(\n scope=scope, name=unique_definition_name, role_name=role_name, permissions=new_permissions\n)\nprint(\"Role definition '{}' updated successfully.\".format(updated_definition.role_name))\n\n# Now let's create a role assignment to apply our role definition to our service principal.\n# Since we don't provide the name keyword argument to create_role_definition, a unique role assignment name (a GUID)\n# is generated for us.\nprint(\"\\n.. Create a role assignment\")\nprincipal_id = os.environ[\"AZURE_CLIENT_ID\"]\ndefinition_id = updated_definition.id\nrole_assignment = client.create_role_assignment(scope=scope, definition_id=definition_id, principal_id=principal_id)\nprint(\"Role assignment created successfully.\")\n\n# Let's delete the role assignment.\nprint(\"\\n.. Delete a role assignment\")\nclient.delete_role_assignment(scope=scope, name=role_assignment.name)\nprint(\"Role assignment deleted successfully.\")\n\n# Finally, let's delete the role definiton as well.\nprint(\"\\n.. Delete a role definition\")\nclient.delete_role_definition(scope=scope, name=definition_id)\nprint(\"Role definition deleted successfully.\")\n","sub_path":"sdk/keyvault/azure-keyvault-administration/samples/access_control_operations.py","file_name":"access_control_operations.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"352984221","text":"import nibbler as nd\nfrom nibbler.trading import signals\nfrom nibbler.trading import strategy\nfrom nibbler import plot\nimport pandas as pd\nimport pathlib as pt\n\ncwd = pt.Path(__file__).parent\nresource_folder = cwd/\"../../resources\"\n\ndata_file = resource_folder/\"BitcoinBinance1hr.csv\"\ndataframe = pd.read_csv(data_file)\n\nif __name__ == \"__main__\":\n\n buy_signal = signals.buy.SavitzkyGolayMinFilteredGrads()\n sell_signal = signals.sell.SavitzkyGolayMaxFilteredGrads()\n\n strategy = strategy.MarketLong(\n buy_signal, sell_signal,\n leverage = 1,\n use_leverage = True\n )\n\n strategy.walk_dataset(dataframe.iloc[0:5000])\n plot.show(\n strategy.plot_trade_and_equity()\n )\n print(strategy.trade_log)\n strategy.save(\"strat\")\n","sub_path":"tests/strategy/test_2.py","file_name":"test_2.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"477290917","text":"# 题目:打印出杨辉三角形(要求打印出10行如下图)。  \n# 程序分析:无。\n\n# 程序源代码:\n\n# !/usr/bin/python\n# -*- coding: UTF-8 -*-\n\naa = [[1, 1]] # 初始化\nfor i in range(10 - 2): # 打印10行,计算的行数只有8行\n l_temp = [1] # 每行的第一个数为1\n for j in range(len(aa[i]) - 1): # 遍历上一行\n l_temp.append(aa[i][j] + aa[i][j + 1])\n else:\n l_temp.append(1) # 最后一行也为1\n aa.append(l_temp) # 加入list中\naa.insert(0, [1]) # 按要求添加第一行的元素\nfor i in aa:\n print(i) # 按要求输出\n","sub_path":"61.py","file_name":"61.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"597772940","text":"import requests\nfrom config.config import HOST\nimport logging\nimport json\nclass HttpRequest:\n def http_request(self,url,method,header,data=None,json=None):\n try:\n url =f'{HOST}'+url\n if method.upper()=='GET':\n logging.info(\"正在发送get请求,请求地址:{}, 请求参数{}\".format(url))\n res = requests.get(url=url,data=data,headers=header,verify=False, allow_redirects=False)\n elif method.upper()=='POST':\n if json:\n logging.info(\"正在发送请求,请求地址:{}, 请求参数{}\".format(url, json))\n res = requests.post(url=url,json=json,headers=header,verify=False, allow_redirects=False)\n else:\n logging.info(\"正在发送请求,请求地址:{}, 请求参数{}\".format(url, data))\n res = requests.post(url=url,data=data,headers=header,verify=False, allow_redirects=False)\n else:\n logging.info(\"正在发送请求,请求地址:{}, 请求参数{}\".format(url, data))\n print('请求方法不正确')\n except Exception as e:\n print(\"请求报错了:{0}\".format(e))\n raise e\n return res\n\nif __name__ == '__main__':\n url ='/api/community/app/post/search-of-home'\n method =\"POST\"\n header ={\"Content-Type\": \"application/x-www-form-urlencoded\",\"appaccesstoken\": \"604d8e0a9a8e6a1d05ef8cfc1f629ff47e5e2b45c1046a2c2b3c49a6bbe057e4aa92201e19ab7737b3b8f5c89e8187d762258ff7792483904a3cd8025831736fdaba82009e536e2425619ae2b6b08dfc5aac6671c47fbb0595437a200d60cca29b6535defd7d4abf1baf84b53b41408476a09d3d0e0e94bc660228cc630119e525\"}\n data ={\"success\":\"true\",\"message\":\"获取成功\",\"code\":\"0\",\"value[0].id\":\"21\",\"value[0].cityCode\":\"110100\",\"value[0].tagIds\":\",4,19,5,20\",\"value[0].name\":\"赛力斯大望京体验中心\"}\n res = HttpRequest().http_request(url, method, header, json=data)\n print(res.json())\n","sub_path":"pythonProject/tools/Http_request.py","file_name":"Http_request.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"104336875","text":"import json\nfrom autoprotocol.util import make_dottable_dict\n\ndef ligate(protocol, refs, params):\n '''\n Template for ligation_config.json file\n (change or add to defaults for your run):\n {\n \"refs\":{\n \"resources\": {\n \"id\": null,\n \"type\": \"384-pcr\",\n \"storage\": \"cold_20\",\n \"discard\": false\n },\n \"water\": {\n \"id\": null,\n \"type\": \"micro-1.5\",\n \"storage\": \"cold_4\",\n \"discard\": false\n },\n \"destination_plate\": {\n \"id\": null,\n \"type\": \"96-pcr\",\n \"storage\": \"cold_4\",\n \"discard\": false\n }\n },\n \"parameters\":{\n \"T4_Ligase\": \"resources/A1\",\n \"T4_buffer\": \"resources/A2\",\n \"cut_backbone\": \"resources/B1\",\n \"insert_1\": \"resources/B2\",\n \"insert_2\": \"resources/B3\",\n \"insert_3\": \"resources/B4\",\n \"construct_1\": \"destination_plate/B1\",\n \"construct_2\": \"destination_plate/B2\",\n \"construct_3\": \"destination_plate/B3\",\n \"ligase_vol\": \"3:microliter\",\n \"buffer_vol\": \"2:microliter\",\n \"source_DNA_vol\": \"1:microliter\",\n \"insert_vol\": \"3:microliter\",\n \"water_vol\": \"2:microliter\",\n \"ligation_time\": \"10:minute\",\n \"deactivation_time\": \"5:minute\",\n \"deactivation_temp\": \"65:celsius\"\n }\n }\n '''\n params = make_dottable_dict(params)\n refs = make_dottable_dict(refs)\n\n destination_wells = WellGroup([params.construct_1, params.construct_2, params.construct_3])\n\n #distribute water and backbone\n protocol.distribute(refs.water.well(0), destination_wells, params.water_vol, allow_carryover=True)\n protocol.distribute(params.cut_backbone, destination_wells, params.source_DNA_vol)\n\n #transfer buffer and ligase to all final wells\n protocol.transfer(params.T4_Ligase, destination_wells, params.ligase_vol)\n protocol.transfer(params.T4_buffer, destination_wells, params.buffer_vol)\n\n #transfer DNA to appropriate wells\n protocol.transfer(params.insert_1, destination_wells, params.insert_vol, mix_after=True)\n protocol.transfer(params.insert_2, params.construct_2, params.insert_vol, mix_after=True)\n protocol.transfer(params.insert_3, params.construct_3, params.insert_vol, mix_after=True)\n\n\n protocol.seal(\"destination_plate\")\n\n protocol.incubate(\"destination_plate\",\"ambient\", params.ligation_time)\n\n #thermocycle to deactivate enzyme\n protocol.thermocycle(\"destination_plate\", [\n {\"cycles\": 1, \"steps\": [\n {\"temperature\": params.deactivation_temp, \"duration\": params.deactivation_time},\n ]},\n ])\n\nif __name__ == '__main__':\n from autoprotocol.harness import run\n run(ligate)","sub_path":"autoprotocol/protocols/ligation.py","file_name":"ligation.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"81643704","text":"#!/usr/bin/python3\n\nimport re\nimport os\nimport sys\nimport time\nimport importlib\nimport subprocess\nfrom bar import bat\nfrom bar import vol\nfrom bar import date\nfrom bar import cpu\nfrom bar import mem\nfrom bar import blues\nfrom bar import light\nfrom bar import hot\nfrom bar import disk\n\n\nclass status_bar:\n def __init__(self, args: list[str]) -> None:\n self.map: dict = {\n \"bat\": (bat, \"MyBat\"),\n \"vol\": (vol, \"MyVol\"),\n \"date\": (date, \"MyDate\"),\n \"cpu\": (cpu, \"MyCpu\"),\n \"mem\": (mem, \"MyMem\"),\n \"blues\": (blues, \"MyBlues\"),\n \"light\": (light, \"MyLight\"),\n \"hot\": (hot, \"MyHot\"),\n \"disk\": (disk, \"MyDisk\"),\n }\n self.dwm = os.environ[\"DWM\"]\n self.imp = False\n\n if args[0] == \"cron\":\n self.cron()\n elif args[0] == \"update\":\n self.update(*args[1:])\n self.refresh()\n elif args[0] == \"updateall\" or args[0] == \"check\":\n self.update(\"bat\", \"vol\", \"date\", \"cpu\", \"mem\", \"blues\", \"light\", \"hot\", \"disk\")\n self.refresh()\n else:\n self.click(args[0], args[1])\n\n def cron(self) -> None:\n while True:\n try:\n t: float = time.time()\n f: time.struct_time = time.gmtime(t)\n run: int = int(time.strftime(\"%S\", f))\n\n _ = not run % 2 and self.update(\"bat\")\n _ = not run % 2 and self.update(\"vol\")\n _ = not run % 5 and self.update(\"cpu\")\n _ = not run % 5 and self.update(\"mem\")\n _ = not run % 2 and self.update(\"light\")\n _ = not run % 2 and self.update(\"blues\")\n _ = not run % 60 and self.update(\"date\")\n _ = not run % 10 and self.update(\"hot\")\n _ = not run % 60 and self.update(\"disk\")\n\n self.refresh()\n time.sleep(1)\n self.imp = True\n except UnicodeDecodeError:\n os.remove(self.dwm + \"/statusbar/tmp.py\")\n except FileNotFoundError:\n open(self.dwm + \"/statusbar/tmp.py\", \"w\").close()\n except Exception as err:\n self.statusbar_log(err.__str__())\n\n def update(self, *args) -> None:\n if len(args) < 1:\n return\n\n print(\"update\", *args, end=\" \")\n getattr(self.map[args[0]][0], self.map[args[0]][1])(\"update\")\n args = args[1:]\n\n _ = args and self.update(*args)\n\n def refresh(self):\n try:\n tmp = importlib.import_module(\"tmp\")\n _ = self.imp and importlib.reload(tmp)\n subprocess.Popen(\n [\n \"/bin/bash\",\n \"-c\",\n f'xsetroot -name \"{tmp.hot}{tmp.date}{tmp.cpu}{tmp.mem}{tmp.disk}{tmp.light}{tmp.vol}{tmp.blues}{tmp.bat}\"',\n ]\n )\n\n except Exception:\n self.check_tmp_content()\n\n def check_tmp_content(self):\n with open(self.dwm + \"/statusbar/tmp.py\", \"r+\") as f:\n lines = f.readlines()\n t = []\n\n f.seek(0)\n for i in lines:\n if not re.search(r\"^(cpu|mem|bat|vol|light|blues|date) = .*$\", i):\n continue\n t.append(i)\n f.truncate()\n f.writelines(t)\n\n def statusbar_log(self, content):\n with open(self.dwm + \"/statusbar/log\", \"w+\") as log:\n log.write(content)\n\n def click(self, *args) -> None:\n if len(args) < 2:\n return\n self.update(args[0])\n getattr(self.map[args[0]][0], self.map[args[0]][1])(\"click\", args[1])\n self.refresh()\n\n\nstatus_bar(sys.argv[1:])\n","sub_path":"statusbar/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"182565583","text":"#!usr/bin/python\n# -*- coding: utf-8 -*- \n\n\nimport numpy as np \nimport cv2 \n# initialize the known distance from the camera to the object, \n# which in this case is 24 inches \nKNOWN_DISTANCE = 27.0 \n# initialize the known object width, which in this case, \n# the piece of paper is 11 inches wide \nKNOWN_WIDTH = 11.69 \nKNOWN_HEIGHT = 8.27\nWARNING_DISTANCE = 1.0\n\ncap = cv2.VideoCapture(0)\nimg_path=\"DC1002.jpg\"\nfirstimg=cv2.imread(\"DC1002.jpg\")\n\nlast_photo = firstimg\nnew_photo = firstimg\nc=1\n# initialize the list of images that we'll be using \nIMAGE_PATHS = [\"DC10002.jpg\", \"DC10003.jpg\",\"DC10008.jpg\",\"DC10011.jpg\",\"DC10012.jpg\",\"DC1002.jpg\", \"DC1003.jpg\",\"DC1004.jpg\",\"DC10013.jpg\",\"DC10014.jpg\",\"DC10015.jpg\",\"DC10016.jpg\",\"DC10019.jpg\",\"DC10021.jpg\",\n\"DC10024.jpg\",\"DC10025.jpg\",\"DC10026.jpg\",\"DC10028.jpg\",\"DC10031.jpg\",\"DC10032.jpg\",\"DC10033.jpg\",\"DC10034.jpg\",\"DC10035.jpg\",\"DC10036.jpg\",\n\"DC10037.jpg\",\"DC10038.jpg\",\"DC10039.jpg\",\"DC10040.jpg\",\"DC10041.jpg\",\"DC10042.jpg\",\"DC10043.jpg\",\"DC10044.jpg\",\"DC10045.jpg\"]\ndef find_marker(image): \n gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \n # 将彩色图转化为灰度图 \n gray_img = cv2.GaussianBlur(gray_img, (5, 5), 0) \n #cv2.imshow(\"gray_img\",gray_img)\n # 高斯平滑去噪 \n #thresh_img=cv2.threshold(gray_img,127,255,cv2.THRESH_BINARY_INV)\n \n #cv2.imshow(\"thresh_img\",gray_img)\n\n edged_img = cv2.Canny(gray_img, 50, 125)\n # Canny算子阈值化 \n #cv2.imshow(\"edged_img\",edged_img) \n img, countours, hierarchy = cv2.findContours(edged_img.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n # 注意,findcontours函数会“原地”修改输入的图像。opencv3会返回三个值,分别是img, countours, hierarchy \n # 第二个参数表示轮廓的检索模式,cv2.RETR_EXTERNAL表示只检测外轮廓;v2.RETR_LIST检测的轮廓不建立等级关系 \n # cv2.RETR_CCOMP建立两个等级的轮廓;cv2.RETR_TREE建立一个等级树结构的轮廓。 \n # 第三个参数method为轮廓的近似办法,cv2.CHAIN_APPROX_NONE存储所有的轮廓点, \n # 相邻的两个点的像素位置差不超过1,即max(abs(x1 - x2),abs(y2 - y1)) == 1 \n # cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标, \n # 例如一个矩形轮廓只需4个点来保存轮廓信息 \n #cv2.drawContours(image,countours,-1,(0,0,255),2,8) \n # # 第三个参数指定绘制轮廓list中的哪条轮廓,如果是-1,则绘制其中的所有轮廓。 \n # \n #cv2.imshow('image', image) \n #print(len(countours))\n # 输出如下:15,即该图检测出15个轮廓 \n c = max(countours, key = cv2.contourArea) \n \n # 提取最大面积矩形对应的点集 \n rect = cv2.minAreaRect(c) \n #print(rect)\n # cv2.minAreaRect()函数返回矩形的中心点坐标,长宽,旋转角度[-90,0),当矩形水平或竖直时均返回-90 \n # c代表点集,返回rect[0]是最小外接矩形中心点坐标, \n # rect[1][0]是width,rect[1][1]是height,rect[2]是角度 \n\n # box = cv2.boxPoints(rect) # # 但是要绘制这个矩形,我们需要矩形的4个顶点坐标box, 通过函数cv2.boxPoints()获得, \n # # 即得到box:[[x0, y0], [x1, y1], [x2, y2], [x3, y3]] \n # # print(box),输出如下: \n # # [[508.09482 382.58597] \n # # [101.76947 371.29916] \n # # [109.783356 82.79956] \n # # [516.1087 94.086365]] \n # # # 根据检测到的矩形的顶点坐标box,我们可以将这个矩形绘制出来,如下所示: \n # for i in range(len(box)): \n # cv2.line(image, (box[i][0],box[i][1]),(box[(i+1)%4][0],box[(i+1)%4][1]),(0,0,255),2,8) \n # cv2.imshow('image', image) \n return rect \n# def Location(img_path,)\ndef distance_to_camera(knownWidth, focalLength, perWidth): \n return (knownWidth * focalLength) / perWidth \n\ndef calculate_focalDistance(img_path): \n first_image = cv2.imread(img_path) \n # cv2.imshow('first image',first_image) \n marker = find_marker(first_image) \n # 得到最小外接矩形的中心点坐标,长宽,旋转角度 \n \n # 其中marker[1][0]是该矩形的宽度,单位为像素 \n focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH \n # 获取摄像头的焦距 \n #print('焦距(focalLength )= ',focalLength) \n # 将计算得到的焦距打印出来 \n return focalLength\n\ndef calculate_Distance(image_path,focalLength_value,dis_x,dis_y,dis_z): \n # 加载每一个图像的路径,读取照片,找到A4纸的轮廓 \n # 然后计算A4纸到摄像头的距离 \n image = image_path \n cv2.imshow(\"image\", image) \n# cv2.waitKey(300) \n\n marker = find_marker(image) \n center_x=np.int0(marker[0][0])\n center_y=np.int0(marker[0][1])\n distance_inches = distance_to_camera(KNOWN_WIDTH,focalLength_value, marker[1][0]) \n # 计算得到目标物体到摄像头的距离,单位为英寸, \n # 注意,英寸与cm之间的单位换算为: 1英寸=2.54cm \n\n box = cv2.boxPoints(marker) \n # print( box ),输出类似如下: \n # [[508.09482 382.58597] \n # [101.76947 371.29916] \n # [109.783356 82.79956] \n # [516.1087 94.086365]] \n box =np.int0( box) \n # 将box数组中的每个坐标值都从浮点型转换为整形 \n # print( box ),输出类似如下: \n # [[508 382] \n # [101 371] \n # [109 82] \n # [516 94]] \n cv2.drawContours(image, [box], -1, (0, 0, 255), 2) \n # 在原图上绘制出目标物体的轮廓 \n\n cv2.line(image,(center_x,center_y),(center_x,center_y),(0,255,0),2)\n\n rdis_x=dis_x\n rdis_y=dis_y\n rdis_z=dis_z\n \n if abs(rdis_x) <= WARNING_DISTANCE and abs(rdis_y) <= WARNING_DISTANCE and abs(rdis_z) <= WARNING_DISTANCE:\n cv2.putText(image,\"System is normal\",(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n else:\n if abs(rdis_x) > WARNING_DISTANCE:\n cv2.putText(image,\"Warning : distance X exceeds threshold\",(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n else:\n if abs(rdis_y) > WARNING_DISTANCE:\n cv2.putText(image,\"Warning : distance Y exceeds threshold\",(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n else:\n if abs(rdis_z) > WARNING_DISTANCE:\n cv2.putText(image,\"Warning : distance Z exceeds threshold\",(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1) \n \n\n #cv2.putText(image,image_path,(10,20),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n cv2.putText(image,\"ActurlX=%2f\"%center_x,(image.shape[1] - 600, image.shape[0] - 50),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n\n cv2.putText(image,\"ActurlY=%2f\"%center_y,(image.shape[1] - 600, image.shape[0] - 30),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,0),1)\n\n cv2.putText(image, \"The distance from camera %.2fcm\" % (distance_inches * 2.54), (image.shape[1] - 600, image.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 1) \n # cv2.putText()函数可以在照片上添加文字 \n # cv2.putText(img, txt, (int(x),int(y)), fontFace, fontSize, fontColor, fontThickness) \n # 各参即为:照片/添加的文字/左上角坐标/字体/字体大小/颜色/字体粗细 \n cv2.imshow(\"image\", image)\n \ndef get_dis(image_path):\n image = image_path\n # cv2.imshow(\"image\", image) \n # cv2.waitKey(300) \n marker = find_marker(image)\n return marker\n\nif __name__ == \"__main__\": \n while(1):\n print(\"the num %2f\"%c)\n ret,frame = cap.read()\n last_photo=new_photo\n new_photo= frame\n\n img_path1 = \"DC1002.jpg\"\n img_path2 = \"DC1003.jpg\"\n img_path = \"DC1002.jpg\"\n focalLength = calculate_focalDistance(img_path)\n print(focalLength)\n\n# for i in range(0,30) :\n# img_path1 = IMAGE_PATHS[i]\n# img_path2 = IMAGE_PATHS[i+1]\n\n# print(IMAGE_PATHS[i])\n# print(IMAGE_PATHS[i+1])\n\n \n \n marker1=get_dis(last_photo)\n marker2=get_dis(new_photo)\n\n center_X1=marker1[0][0]\n center_Y1=marker1[0][1]\n\n center_X2=marker2[0][0]\n center_Y2=marker2[0][1]\n\n print(center_X1,center_Y1)\n print(center_X2,center_Y2)\n perWidth=marker1[1][0]\n\n dis_x=center_X1-center_X2\n dis_y=center_Y1-center_Y2\n\n rdis_x=dis_x*(KNOWN_WIDTH/perWidth)*2.54\n rdis_y=dis_y*(KNOWN_WIDTH/perWidth)*2.54\n\n center_Z1=distance_to_camera(KNOWN_WIDTH, focalLength, marker1[1][0])\n center_Z2=distance_to_camera(KNOWN_WIDTH, focalLength, marker2[1][0])\n\n rdis_z=(center_Z1-center_Z2)*2.54\n\n print(\"dis_x:%2fcm\"%abs(rdis_x))\n print(\"dis_y:%2fcm\"%abs(rdis_y))\n print(\"dis_z:%2fcm\"%abs(rdis_z))\n\n calculate_Distance(new_photo,focalLength,rdis_x,rdis_y,rdis_z)\n# cv2.waitKey(1000)\n \n if abs(rdis_x) <= WARNING_DISTANCE and abs(rdis_y) <= WARNING_DISTANCE and abs(rdis_z) <= WARNING_DISTANCE:\n print(\"System is normal\")\n else: \n if abs(rdis_x) > WARNING_DISTANCE:\n print(\"Warning : distance X exceeds threshold\")\n else:\n if abs(rdis_y) > WARNING_DISTANCE:\n print(\"Warning : distance y exceeds threshold\")\n else:\n if abs(rdis_z) > WARNING_DISTANCE:\n print(\"Warning : distance z exceeds threshold\")\n c=c+1\n if cv2.waitKey(1000) & 0xFF == ord('q'):\n break \n # 获得摄像头焦距 \n # for image_path in IMAGE_PATHS: \n # calculate_Distance(image_path,focalLength) \n # cv2.waitKey(1000000)\ncv2.destroyAllWindows() \n\n","sub_path":"shipingshendu.py","file_name":"shipingshendu.py","file_ext":"py","file_size_in_byte":9667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"48850935","text":"\"\"\"\nThis file contains views related to the AAC grading completed reports\n\"\"\"\nfrom django.http import Http404\nfrom django.utils.safestring import mark_safe\nfrom django.template.defaulttags import register\nfrom django.views.generic.edit import UpdateView, FormView\nfrom django.views.generic import TemplateView\nfrom django.urls import reverse_lazy\nfrom makeReports.models import GradedRubricItem, ReportSupplement, Report, RubricItem\nfrom makeReports.forms import SectionRubricForm, OverallCommentForm, SubmitGrade\nfrom makeReports.views.helperFunctions.section_context import (\n rubricItemsHelper, \n section1Context, \n section2Context, \n section3Context,\n section4Context\n)\nfrom makeReports.views.helperFunctions.mixins import AACReportMixin, AACOnlyMixin, DeptAACMixin\nfrom makeReports.views.helperFunctions.todos import todoGetter\n\n\ndef generateRubricItems(rIs,form,r):\n \"\"\"\n Generates graded rubric items based on grading form\n\n Args:\n rIs (list) : list of :class:`~makeReports.models.grading_models.RubricItem` in rubric\n form (Form) : completed form\n r (Report) : report\n \"\"\"\n for ri in rIs:\n if form.cleaned_data[\"rI\"+str(ri.pk)]:\n try:\n GRI = GradedRubricItem.objects.get(rubric=r.rubric, item=ri)\n GRI.grade = form.cleaned_data[\"rI\"+str(ri.pk)]\n GRI.save()\n except:\n gr = form.cleaned_data[\"rI\"+str(ri.pk)]\n if gr and (gr != \"\"):\n GradedRubricItem.objects.create(rubric=r.rubric, item=ri, grade=form.cleaned_data[\"rI\"+str(ri.pk)])\ndef getInitialRubric(rIs, r, initial):\n \"\"\"\n Initializes grading form based upon things already graded\n\n Args:\n rIs (list) : list of :class:`~makeReports.models.grading_models.RubricItem` in rubric\n form (Form) : completed form\n r (Report) : report\n \n Returns:\n dict : initial rubric values\n \"\"\"\n for ri in rIs:\n try:\n GRI = GradedRubricItem.objects.filter(rubric=r.rubric, item=ri).last()\n initial[\"rI\"+str(ri.pk)]=GRI.grade\n except:\n pass\n return initial\ndef allRubricItemsSomeGrades(rIs,gRIs):\n \"\"\"\n Generates dictionary with key of rubric items and value of grade.\n If no grade, the value is \"Not graded\"\n\n Args:\n rIs (list): list of :class:`~makeReports.models.grading_models.RubricItem`\n gRIs (list): list of :class:`~makeReports.models.grading_models.GradedRubricItem`\n \n Returns:\n dict : items and grades\n \"\"\"\n con = []\n for rI in rIs:\n gr = gRIs.filter(item=rI).last()\n if gr:\n con.append((rI, gr.get_grade_display))\n else:\n con.append((rI,\"Not graded\"))\n return con\n@register.simple_tag\ndef get_item(dictionary, key1, key2):\n \"\"\"\n Gets item from dictionary in dictionary\n\n Args:\n dictionary (dict) : outer dictionary\n key1 (str) : first dictionary key\n key2 (str) : second dictionary key\n \n Returns:\n obj : dictionary[key1][key2]\n \"\"\"\n s = dictionary.get(key1)\n if s:\n return mark_safe(s[key2])\n else:\n return \"\"\nclass GradingEntry(AACReportMixin,TemplateView):\n \"\"\"\n View that provides initial information on report to be graded\n\n Keyword Args:\n report (str): primary key of :class:`~makeReports.models.basic_models.Report` to grade\n \"\"\"\n template_name = 'makeReports/Grading/grading_entry.html'\n def get_context_data(self,**kwargs):\n \"\"\"\n Adds report supplements to the context\n\n Returns:\n dict : context needed to display view, including the report supplements\n \"\"\"\n context = super().get_context_data(**kwargs)\n context['reportSups'] = ReportSupplement.objects.filter(report=self.report)\n return context\nclass GradingView(AACOnlyMixin,FormView):\n \"\"\"\n View to grade one section of a form\n\n Keyword Args:\n report (str): primary key of current :class:`~makeReports.models.basic_models.Report` to grade\n \n Attributes:\n section (int): section number of section currently being graded\n \"\"\"\n form_class = SectionRubricForm\n def dispatch(self,request,*args,**kwargs):\n \"\"\"\n Dispatches view, and attaches :class:`~makeReports.models.basic_models.Report` and \n rubric items (:class:`~makeReports.models.grading_models.RubricItem`) to instance\n\n Args:\n request (HttpRequest): request to view page\n\n \n Keyword Args:\n report (str): primary key of current :class:`~makeReports.models.basic_models.Report` to grade\n \n Returns:\n HttpResponse : response of page to request\n \"\"\"\n try:\n self.report = Report.objects.get(pk=self.kwargs['report'])\n except Report.DoesNotExist:\n raise Http404(\"No report matching URL exists.\")\n self.rubricItems = RubricItem.objects.filter(\n rubricVersion=self.report.rubric.rubricVersion,\n section=self.section\n ).order_by(\"order\",\"pk\")\n return super().dispatch(request,*args,**kwargs)\n def get_success_url(self):\n \"\"\"\n Gets URL to go to upon success (grading the next section page)\n\n Returns:\n str : URL of next section's grading page\n \"\"\"\n return reverse_lazy(\"makeReports:grade-sec\"+str(self.section+1), args=[self.report.pk])\n def get_form_kwargs(self):\n \"\"\"\n Get form keyword arguments, including the rubric items\n\n Returns:\n dict : keyword arguments for the form\n \"\"\"\n kwargs= super().get_form_kwargs()\n kwargs['rubricItems'] = self.rubricItems\n return kwargs\n def form_valid(self,form):\n \"\"\"\n Generates all graded rubric items and sets the grading comment for the section\n \n Args:\n form (SectionRubricForm): filled out form to process\n \n Returns:\n HttpResponseRedirect : redirects to success URL given by get_success_url\n \"\"\"\n generateRubricItems(self.rubricItems,form,self.report)\n tempStr = \"section\"+str(self.section)+\"Comment\"\n setattr(self.report.rubric,tempStr, form.cleaned_data['section_comment'])\n self.report.rubric.save()\n return super().form_valid(form)\n def get_context_data(self, **kwargs):\n \"\"\"\n Gets template context, including the section, report, and rubric items\n \n Returns:\n dict : context for template\n \n \"\"\"\n context = super().get_context_data(**kwargs)\n context = rubricItemsHelper(self,context)\n context['section'] = self.section\n context['rpt'] = self.report\n context['toDo'] = todoGetter(self.section,self.report)\n context['reqTodo'] = len(context['toDo']['r'])\n context['sugTodo'] = len(context['toDo']['s'])\n return context\n def get_initial(self):\n initial = super().get_initial()\n initial = getInitialRubric(self.rubricItems,self.report,initial)\n return initial\nclass Section1Grading(GradingView):\n \"\"\"\n View for grading section 1\n \"\"\"\n section = 1\n template_name = \"makeReports/Grading/grading_section1.html\"\n #model = SLOInReport\n success_url = reverse_lazy(\"makeReports:admin-home\")\n def get_context_data(self, **kwargs):\n \"\"\"\n Returns the context for template needed to display section 1\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(Section1Grading,self).get_context_data(**kwargs)\n return section1Context(self,context)\n def get_initial(self):\n \"\"\"\n Initializes the section comment based upon current value\n\n Returns:\n dict : initial form values\n \"\"\"\n initial = super(Section1Grading,self).get_initial()\n initial['section_comment'] = self.report.rubric.section1Comment\n return initial\nclass Section2Grading(GradingView):\n \"\"\"\n View for grading section 2\n \"\"\"\n section = 2\n template_name = \"makeReports/Grading/grading_section2.html\"\n def get_context_data(self, **kwargs):\n \"\"\"\n Provides all context needed to display section 2 of the form\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(Section2Grading,self).get_context_data(**kwargs)\n return section2Context(self,context)\n def get_initial(self):\n \"\"\"\n Gets initial value for comment based upon current value\n\n Returns:\n dict : initial form values\n \"\"\"\n initial = super(Section2Grading,self).get_initial()\n initial['section_comment'] = self.report.rubric.section2Comment\n return initial\nclass Section3Grading(GradingView):\n \"\"\"\n View for grading section 3\n \"\"\"\n section = 3\n template_name = \"makeReports/Grading/grading_section3.html\"\n def get_context_data(self, **kwargs):\n \"\"\"\n Gets context needed to display section 3 of the form\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(Section3Grading,self).get_context_data(**kwargs)\n return section3Context(self,context)\n def get_initial(self):\n \"\"\"\n Gets initial form values, specifically the comment, based upon current value\n\n Returns:\n dict : initial form values\n \"\"\"\n initial = super(Section3Grading,self).get_initial()\n initial['section_comment'] = self.report.rubric.section3Comment\n return initial\nclass Section4Grading(GradingView):\n \"\"\"\n View for grading section 4\n \"\"\"\n section = 4\n template_name = \"makeReports/Grading/grading_section4.html\"\n def get_success_url(self):\n \"\"\"\n Gets URL to go to upon success (comment page)\n\n Returns:\n str : URL of overall comment page (:class:`~makeReports.views.grading_views.OverallComment`)\n \"\"\"\n return reverse_lazy(\"makeReports:grade-comment\", args=[self.report.pk])\n def get_context_data(self, **kwargs):\n \"\"\"\n Gets context needed to display section 4 of the form\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(Section4Grading,self).get_context_data(**kwargs)\n return section4Context(self,context)\n def get_initial(self):\n \"\"\"\n Gets the initial comment value based upon current value\n\n Returns:\n dict : initial form values\n \"\"\"\n initial = super(Section4Grading,self).get_initial()\n initial['section_comment'] = self.report.rubric.section4Comment\n return initial\nclass OverallComment(AACReportMixin,FormView):\n \"\"\"\n View to add an overall comment to the report\n \"\"\"\n form_class = OverallCommentForm\n template_name = \"makeReports/Grading/overall_comment.html\"\n def get_success_url(self):\n \"\"\"\n Gets URL to go to upon success (review the feedback page)\n\n Returns:\n str : URL of review the feedback page (:class:`~makeReports.views.grading_views.RubricReview`)\n \"\"\"\n return reverse_lazy(\"makeReports:rub-review\", args=[self.report.pk])\n def get_context_data(self,**kwargs):\n \"\"\"\n Returns template context, including the current report\n\n Returns:\n dict : context of template\n \"\"\"\n context = super(OverallComment,self).get_context_data(**kwargs)\n context['reportSups'] = ReportSupplement.objects.filter(report=self.report)\n context = section1Context(self,context)\n context = section2Context(self,context)\n context = section3Context(self,context)\n context = section4Context(self,context)\n context['toDo'] = todoGetter(4,self.report)\n context['reqTodo'] = len(context['toDo']['r'])\n context['sugTodo'] = len(context['toDo']['s'])\n return context\n def form_valid(self, form):\n \"\"\"\n Saves the comment to the database\n\n Args:\n form (Single2000Textbox): filled out form to process\n \n Returns:\n HttpResponseRedirect : redirects to success URL given by get_success_url\n \"\"\"\n self.report.rubric.generalComment = form.cleaned_data['text']\n self.report.rubric.save()\n return super(OverallComment,self).form_valid(form)\n def get_initial(self):\n \"\"\"\n Gets initial value of the comment passed upon current value\n\n Returns:\n dict : initial form values\n \"\"\"\n initial = super(OverallComment,self).get_initial()\n try:\n initial['text'] = self.report.rubric.generalComment\n except:\n pass\n return initial\nclass RubricReview(AACReportMixin, FormView):\n \"\"\"\n View to review graded rubric\n \"\"\"\n template_name = \"makeReports/Grading/rubric_review.html\"\n form_class = SubmitGrade\n def dispatch(self,request,*args,**kwargs):\n \"\"\"\n Dispatches the view and attaches the graded rubric items (:class:`~makeReports.models.grading_models.GradedRubricItem`) to the instance\n \n Args:\n request (HttpRequest): request to view page\n\n \n Returns:\n HttpResponse : response of page to request\n \"\"\"\n self.GRIs = GradedRubricItem.objects.filter(rubric__report__pk=self.kwargs['report'])\n return super(RubricReview,self).dispatch(request,*args,**kwargs)\n def get_form_kwargs(self):\n \"\"\"\n Gets the form keyword arguments, including whether the graded rubric is compelete\n\n Returns:\n dict : keyword arguments for form\n \"\"\"\n kwargs=super(RubricReview,self).get_form_kwargs()\n #valid iff there's a graded rubric item for every rubric item\n kwargs['valid'] = (self.GRIs.count() >= RubricItem.objects.filter(rubricVersion=self.report.rubric.rubricVersion).count())\n return kwargs\n def form_valid(self,form):\n \"\"\"\n Sets the rubric to complete and saves the rubric\n\n Args:\n form (SubmitGrade): filled out form to process\n \n Returns:\n HttpResponseRedirect : redirects to success URL given by get_success_url\n \"\"\"\n self.report.rubric.complete = True\n self.report.rubric.save()\n return super(RubricReview,self).form_valid(form)\n def get_success_url(self):\n \"\"\"\n Gets URL to go to upon success (return report option page)\n\n Returns:\n str : URL of return report option page (:class:`~makeReports.views.grading_views.ReturnReport`)\n \"\"\"\n return reverse_lazy('makeReports:ret-rept', args=[self.report.pk])\n def get_context_data(self,**kwargs):\n \"\"\"\n Gets the context data, including the report, the graded rubric and items, and the \n context needed to display the report\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(RubricReview,self).get_context_data(**kwargs)\n context['reportSups'] = ReportSupplement.objects.filter(report=self.report)\n rIs = RubricItem.objects.filter(rubricVersion=self.report.rubric.rubricVersion)\n context['gRub'] = self.report.rubric\n context['object_list'] = self.GRIs\n context['rIs1'] = allRubricItemsSomeGrades(rIs.filter(section=1).order_by(\"order\",\"pk\"),self.GRIs)\n context['rIs2'] = allRubricItemsSomeGrades(rIs.filter(section=2).order_by(\"order\",\"pk\"),self.GRIs)\n context['rIs3'] = allRubricItemsSomeGrades(rIs.filter(section=3).order_by(\"order\",\"pk\"),self.GRIs)\n context['rIs4'] = allRubricItemsSomeGrades(rIs.filter(section=4).order_by(\"order\",\"pk\"),self.GRIs)\n context = section1Context(self,context)\n context = section2Context(self,context)\n context = section3Context(self,context)\n context = section4Context(self,context)\n context['toDo'] = todoGetter(4,self.report)\n context['reqTodo'] = len(context['toDo']['r'])\n context['sugTodo'] = len(context['toDo']['s'])\n return context\nclass ReturnReport(AACOnlyMixin,UpdateView):\n \"\"\"\n View to return report to department for modification\n\n Keyword Args:\n pk (str): primary key of :class:`~makeReports.models.basic_models.Report` to return\n \"\"\"\n model = Report\n fields = ['returned']\n template_name = 'makeReports/Grading/returnReport.html'\n success_url = reverse_lazy('makeReports:admin-home')\n def form_valid(self,form):\n \"\"\"\n Sets the report to be returned, not submitted, and not complete\n\n Args:\n form (ModelForm): filled out form to process\n \n Returns:\n HttpResponseRedirect : redirects to success URL given by get_success_url\n \"\"\"\n if form.cleaned_data['returned']:\n self.object.submitted = False\n self.object.rubric.complete = False\n self.object.rubric.save()\n return super(ReturnReport,self).form_valid(form)\nclass Feedback(DeptAACMixin, TemplateView):\n \"\"\"\n View for department to view AAC feedback\n\n Keyword Args:\n report (str): primary key of :class:`~makeReports.models.basic_models.Report` to view feedback for\n \"\"\"\n model = GradedRubricItem\n template_name = \"makeReports/Grading/feedback.html\"\n def dispatch(self,request,*args,**kwargs):\n \"\"\"\n Dispatches view and attaches :class:`~makeReports.models.basic_models.Report` and \n graded items (:class:`~makeReports.models.grading_models.GradedRubricItem`) to the view\n\n Args:\n request (HttpRequest): request to view page\n \n Keyword Args:\n report (str): primary key of :class:`~makeReports.models.basic_models.Report` to view feedback for\n \n Returns:\n HttpResponse : response of page to request\n \"\"\"\n try:\n self.report = Report.objects.get(pk=self.kwargs['report'])\n except Report.DoesNotExist:\n raise Http404(\"No report matching URL exists.\")\n self.GRIs = GradedRubricItem.objects.filter(rubric__report=self.report)\n return super(Feedback,self).dispatch(request,*args,**kwargs)\n def get_success_url(self):\n \"\"\"\n Gets URL to go to upon success (return report option page)\n\n Returns:\n str : URL of return report option page (:class:`~makeReports.views.grading_views.ReturnReport`)\n \"\"\"\n return reverse_lazy('makeReports:ret-rept', args=[self.report.pk])\n def get_context_data(self, **kwargs):\n \"\"\"\n Gets context for the template, including the report, graded rubric items, and\n context needed to display the report\n\n Returns:\n dict : context for template\n \"\"\"\n context = super(Feedback,self).get_context_data(**kwargs)\n context['reportSups'] = ReportSupplement.objects.filter(report=self.report)\n context['rpt'] = self.report\n context['gRub'] = self.report.rubric\n context['gri1'] = self.GRIs.filter(item__section=1).order_by(\"item__order\",\"item__pk\")\n context['gri2'] = self.GRIs.filter(item__section=2).order_by(\"item__order\",\"item__pk\")\n context['gri3'] = self.GRIs.filter(item__section=3).order_by(\"item__order\",\"item__pk\")\n context['gri4'] = self.GRIs.filter(item__section=4).order_by(\"item__order\",\"item__pk\")\n context = section1Context(self,context)\n context = section2Context(self,context)\n context = section3Context(self,context)\n context = section4Context(self,context)\n return context\n","sub_path":"AACForm/makeReports/views/grading_views.py","file_name":"grading_views.py","file_ext":"py","file_size_in_byte":19775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"96146009","text":"#!/usr/bin/env python3\nfrom socket import *\nfrom grid import *\n\nimport select\nimport threading\nimport random\n\nimport sys\nimport re\n\n\n\nsymbols = [' ', 'O', 'X']\nEMPTY = 0\nJ1 = 1\nJ2 = 2\nNB_CELLS=9\n\nexpect_answer = 0;\n\nclass grid:\n\t\tcells = []\n\t\tdef __init__(self):\n\t\t\t\tself.cells = []\n\t\t\t\tfor i in range(NB_CELLS):\n\t\t\t\t\t\tself.cells.append(EMPTY)\n\n\t\tdef play(self, player, cellNum):\n\t\t\t\tassert(0<= cellNum and cellNum < NB_CELLS)\n\t\t\t\tassert(self.cells[cellNum] == EMPTY)\n\t\t\t\tself.cells[cellNum] = player\n\n\t\t\"\"\" Display the state of the game\n\t\t\t\tExample of output : \n\t\t\t\t-------\n\t\t\t\t|O| |X|\n\t\t\t\t-------\n\t\t\t\t|X|O| |\n\t\t\t\t-------\n\t\t\t\t| | |O| \n\t\t\t\t-------\n\t\t\"\"\"\n\t\tdef display(self):\n\t\t\t\tprint(\"-------------\")\n\t\t\t\tfor i in range(3):\n\t\t\t\t\t\tprint(\"|\",symbols[self.cells[i*3]], \"|\", symbols[self.cells[i*3+1]], \"|\", symbols[self.cells[i*3+2]], \"|\");\n\t\t\t\t\t\tprint(\"-------------\")\n\n\t\t\"\"\" Test if 'player' wins the game\"\"\"\n\t\tdef winner(self, player):\n\t\t\t\tassert(player==J1 or player==J2)\n\t\t\t\t# horizontal line\n\t\t\t\tfor y in range(3): \n\t\t\t\t\t\tif self.cells[y*3] == player and self.cells[y*3+1] == player and self.cells[y*3+2] == player:\n\t\t\t\t\t\t\t\t\t\treturn True\n\t\t\t\t# vertical line\n\t\t\t\tfor x in range(3): \n\t\t\t\t\t\tif self.cells[x] == player and self.cells[3+x] == player and self.cells[6+x] == player:\n\t\t\t\t\t\t\t\t\t\treturn True\n\t\t\t\t#diagonals :\n\t\t\t\tif self.cells[0] == player and self.cells[4] == player and self.cells[8] == player:\n\t\t\t\t\t\treturn True\n\t\t\t\tif self.cells[2] == player and self.cells[4] == player and self.cells[6] == player:\n\t\t\t\t\t\treturn True\n\t\t\t\treturn False\n\t\t\n\t\t\"\"\" Return the state of the game: -1 if the game is not over, EMPTY if DRAW; J1 if player 1 wins and J2 if player 2 wins.\n\t\t\"\"\"\n\t\tdef gameOver(self):\n\t\t\t\tif self.winner(J1):\n\t\t\t\t\t\treturn J1\n\t\t\t\tif self.winner(J2):\n\t\t\t\t\t\treturn J2\n\t\t\t\tfor i in range(NB_CELLS):\n\t\t\t\t\t\tif(self.cells[i] == EMPTY):\n\t\t\t\t\t\t\t\treturn -1\n\t\t\t\treturn 0\n\ndef displayStr(grid):\n\tgrid_str = \"$display $\"\n\tfor i in range(3):\n\t\t\tgrid_str = grid_str + str(grid.cells[i*3]) + str(grid.cells[i*3+1]) + str(grid.cells[i*3+2])\n\treturn grid_str\n\nclass Client:\n\n\tcId = None\n\tsocket = None\n\tscore = 0\n\tname = \"nameless\"\n\tcType = 0 #0 = spectator, 1=player\n\tcSpec = -1\n\n\tdef __init__(self, socket):\n\t\tself.socket = socket\n\t\tif socket != None:\n\t\t\tself.sendMessage(\"Connected.\\ntype 'help' to display available commands.\\n\")\n\n\tdef setId(self, cid):\n\t\tself.cId = cid\n\n\tdef sendMessage(self, text):\n\t\tself.socket.send(str.encode(text))\n\n\tdef setName(self, name):\n\t\tself.name = name\n\nclass Player:\n\n\tpGrid = None\n\tpClient = None\n\tpId = 0\n\tpIsAI = 0 # 0 if human, 1 if IA\n\tpGame = -2\n\tisWaiting = 0 #0 normal, 1 waiting for reconnection, -1 has disconnected\n\n\tdef __init__(self, client):\n\t\tself.pGrid = grid()\n\t\tself.pClient = client\n\n\tdef playAsIa(self):\n\t\tshot = random.randint(0,8)\n\t\twhile(self.pGrid.cells[shot] != EMPTY):\n\t\t\tshot = random.randint(0,8)\n\t\treturn shot\n\n\tdef setId(self, pid):\n\t\tself.pId = pid\n\n\tdef sendMessage(self, text):\n\t\tif self.pIsAI == 0:\n\t\t\tself.pClient.sendMessage(text)\n\n\tdef getPlayerGrid(self):\n\t\tgrid_str = displayStr(self.pGrid)\n\t\treturn grid_str\n\n\tdef displayGrid(self):\n\t\tself.sendMessage(self.getPlayerGrid())\n\nclass Host:\n\n\tlistClient = []\n\tlistSockets = []\n\tsocketListener = None\n\tcurrentPlayer = []\n\thGrid = []\n\tplayers = []\n\tspecs = []\n\n\tdef __init__(self, socketListener):\n\t\tself.socketListener = socketListener\n\t\tself.listSockets.append(socketListener)\n\n\tdef isGameOver(self, game):\n\t\tif self.hGrid[game].gameOver() != -1 :\n\t\t\tself.currentPlayer[game] = -1\n\t\treturn self.hGrid[game].gameOver()\n\n\tdef playMove(self, game, case):\t#returns True if ok\n\t\tif not(0 <= case <= 8):\n\t\t\treturn False\n\t\tif self.hGrid[game].cells[case] == EMPTY: #If the case is empty, we can play the move correctly\n\t\t\tself.hGrid[game].play(self.currentPlayer[game], case)\n\t\t\tself.players[2 * game + self.currentPlayer[game] - 1].pGrid.play(self.currentPlayer[game], case)\n\t\t\tself.players[2 * game + self.currentPlayer[game] - 1].displayGrid()\n\t\t\treturn True\n\t\telse: #else we can update his grid\n\t\t\tp = self.players[self.currentPlayer[game] - 1 + 2 * game]\n\t\t\tp.pGrid.cells[case] = self.hGrid[game].cells[case]\n\t\t\tp.displayGrid()\n\t\t\tp.sendMessage(\"$play\")\n\t\t\treturn False\n\n\tdef switchPlayer(self, game):\n\t\tif self.currentPlayer[game] == -1:\n\t\t\tself.currentPlayer[game] += 1\n\t\tself.currentPlayer[game] = (self.currentPlayer[game] % 2 ) + 1\n\t\tplayer = self.players[2 * game + self.currentPlayer[game] - 1]\n\t\tif player.pIsAI == 0:\n\t\t\tplayer.sendMessage(\"$play\")\n\t\telse:\n\t\t\tcorrect = False\n\t\t\twhile correct == False:\n\t\t\t\tcorrect = self.playMove(game, player.playAsIa())\n\t\t\tfor c in self.listClient:\n\t\t\t\tif c.cType != 1 and c.cSpec == player.pGame:\n\t\t\t\t\tc.sendMessage(displayStr(self.hGrid[player.pGame]))\n\t\t\tself.currentPlayer[game] = (self.currentPlayer[game] % 2 ) + 1\n\t\t\tplayer = self.players[2 * game + self.currentPlayer[game] - 1]\n\t\t\tplayer.sendMessage(\"$play\")\n\n\tdef addNewClient(self):\n\t\t(socket_recv, addr_recv) = self.socketListener.accept()\n\t\tc = Client(socket_recv)\n\t\tself.listClient.append(c)\n\t\tself.listSockets.append(socket_recv)\n\t\tc.setId(self.getNewClientId())\n\n\tdef setNewPlayer(self, client):\n\t\tp = Player(client)\n\t\tself.players.append(p)\n\t\tp.setId(len(self.players))\n\t\tp.pGame = -1\n\t\tclient.cType = 1\n\t\tclient.cSpec = -1\n\n\tdef setNewAIPlayer(self):\n\t\tclient = Client(None)\n\t\tclient.name = \"AI\"\n\t\tp = Player(client)\n\t\tself.players.append(p)\n\t\tp.setId(len(self.players))\n\t\tp.pGame = -1\n\t\tclient.cType = 2\n\t\tclient.cSpec = -1\n\t\tp.pIsAI = 1\n\n\tdef getPlayerId(self, socket):\n\t\tfor p in self.players:\n\t\t\tif p.pClient != None and socket == p.pClient.socket:\n\t\t\t\treturn p.pId\n\t\treturn -1\n\n\tdef getPlayer(self, pid):\n\t\tfor p in self.players:\n\t\t\tif pid == p.pId:\n\t\t\t\treturn p\n\t\treturn -1\n\n\tdef getClientId(self, socket):\n\t\tfor c in self.listClient:\n\t\t\tif socket == c.socket:\n\t\t\t\treturn c.cId\n\t\treturn -1\n\n\tdef getClient(self, cid):\n\t\tfor c in self.listClient:\n\t\t\tif cid == c.cId:\n\t\t\t\treturn c\n\t\treturn -1\n\n\tdef getNewClientId(self):\n\t\ti = 0\n\t\tfor c in self.listClient:\n\t\t\tif c.cId != None and c.cId > i:\n\t\t\t\ti = c.cId\n\t\treturn i + 1\n\n\tdef isGameReady(self):\n\t\tif len(self.players) > 1 and len(self.players)%2 == 0:\n\t\t\treturn 1\n\t\treturn 0\n\n\tdef startGame(self):\t####################\t\n\t\tprint(\"Game start\")\n\t\tself.hGrid.append(grid())\n\t\tgame = len(self.hGrid) - 1\n\t\tfor p in self.players:#The game starts, we can display players' grids\n\t\t\tif p.pGame == -1:\n\t\t\t\tp.pGame = game\n\t\t\t\tif p.pClient.socket != None:\n\t\t\t\t\tp.sendMessage(\"$gamestart\")\n\t\t\t\t\tp.displayGrid()\n\t\tself.currentPlayer.append(-1)\n\t\tself.switchPlayer(game)\n\n\tdef getScores(self):\n\t\tl = sorted(self.listClient, key=lambda x: x.score, reverse=True)\n\t\treturn l\n\n\tdef getScoresString(self):\n\t\tl = self.getScores()\n\t\ts = \"\"\n\t\tfor i in range(len(l)):\n\t\t\tif l[i].cType != 2:\n\t\t\t\ts += str(i + 1) + \":\" + l[i].name + \" with \" + str(l[i].score) + \" wins\\n\"\n\t\treturn s\n\n\tdef endGame(self, game):\n\t\tp1 = None\n\t\tp2 = None\n\t\tfor p in self.players:\n\t\t\tif p.pGame == game:\n\t\t\t\tif p.pClient != None:\n\t\t\t\t\tp.pClient.cType = 0\n\t\t\t\tif p1 == None:\n\t\t\t\t\tp1 = p\n\t\t\t\telse:\n\t\t\t\t\tp2 = p\n\n\t\tif p1 != None:\n\t\t\tp1.pClient = None\n\t\tif p2 != None:\n\t\t\tp2.pClient = None\n\t\tself.hGrid[game] = grid()\n\n\tdef getPlayers(self, game):\n\t\tp1 = None\n\t\tp2 = None\n\t\tfor p in self.players:\n\t\t\tif p.pClient != None and p.pGame == game:\n\t\t\t\tif p1 == None:\n\t\t\t\t\tp1 = p\n\t\t\t\telse:\n\t\t\t\t\tp2 = p\n\t\treturn (p1, p2)\n\n\tdef checkForFreeName(self, name):\n\t\tfor c in self.listClient:\n\t\t\tif c.name == name:\n\t\t\t\treturn self.checkForFreeName(name + \"_\")\n\t\treturn name\n\n\nclass thread_r(threading.Thread): #Thread for Reception\n\tdef __init__(self, s):\n\t\tthreading.Thread.__init__(self)\n\t\tself.socket_client = s\n\n\tdef run(self):\n\t\twhile(True):\n\t\t\tdata = bytes.decode(self.socket_client.recv(1024) ) #data from the server\n\t\t\tif (len(data) != 0):\n\t\t\t\tparsed_data = re.findall('\\$[a-zA-Z0-9]+', data)\n\t\t\t\tif parsed_data:\n\t\t\t\t\tfor i in range(len(parsed_data)):\n\t\t\t\t\t\tword = parsed_data[i]\n\n\t\t\t\t\t\tif word == \"$gamestart\":\n\t\t\t\t\t\t\tprint(\"Game started\")\n\t\t\t\t\t\telif word == \"$play\":\n\t\t\t\t\t\t\tprint(\"Play on a case (0 to 8):\")\n\n\t\t\t\t\t\telif word == \"$display\":\n\t\t\t\t\t\t\ti = i + 1\n\t\t\t\t\t\t\tword2 = parsed_data[i]\n\t\t\t\t\t\t\t#Displaying the grid\n\t\t\t\t\t\t\tgrid_str = \"-------------\\n\"\n\t\t\t\t\t\t\tfor case_i in range(3):\n\t\t\t\t\t\t\t\tgrid_str = grid_str + \"| \" + symbols[int(word2[case_i*3 + 1])] + \" | \" + symbols[int(word2[case_i*3+1 + 1])] + \" | \" + symbols[int(word2[case_i*3+2 + 1])] + \" |\\n\" + \"-------------\\n\"\n\t\t\t\t\t\t\tprint(grid_str)\n\n\t\t\t\t\t\telif word == \"$end\":\n\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\tword2 = parsed_data[i]\n\t\t\t\t\t\t\tif word2 == \"$win\":\n\t\t\t\t\t\t\t\tprint(\"You win\")\n\t\t\t\t\t\t\telif word2 == \"$loose\":\n\t\t\t\t\t\t\t\tprint(\"You loose\")\n\t\t\t\t\t\t\telif word2 == \"$draw\":\n\t\t\t\t\t\t\t\tprint(\"Draw !\")\n\n\t\t\t\telse:\n\t\t\t\t\tprint(data)\n\nclass thread_s(threading.Thread):#Thread for Emission\n\tdef __init__(self, s):\n\t\tthreading.Thread.__init__(self)\n\t\tself.socket_client = s\n\n\tdef run(self):\n\t\twhile True:\n\t\t\ttext = input(\"\")\n\t\t\tif text == \"help\":\n\t\t\t\tprint(\"Available commands : \\n name: \\t Change your current name to \\n play \\t\\t Start a game against another player\\n spec: \\t Watch game \\n playAI \\t Start a game against the AI\\n join:\\t Join an unfinished game against \\n quit\\t\\t Cancel a game\")\t\n\t\t\tself.socket_client.send(str.encode(text))\n\n#_________________________END OF CLASS DECLARATION ____________________________________________________________________________\n\ndef main_server():\n\tsocket_listen = socket(AF_INET, SOCK_STREAM, 0)\n\tsocket_listen.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\tsocket_listen.bind((gethostbyname(gethostname()), 7777))\n\tsocket_listen.listen(1)\n\n\tprint(\"Server is up at ( hostname = \" + gethostname()+ \" )\"+gethostbyname(gethostname()) + \"\\n You can connect using either of those as argument for the client.\")\n\thost = Host(socket_listen)\n\n\twhile(1):\n\t\tfor g in range(len(host.hGrid)):\n\t\t\tif (host.isGameOver(g) != -1): #if gameOver\n\t\t\t\tplayer1 = None\n\t\t\t\tplayer2 = None\n\t\t\t\tfor player in host.players:\n\t\t\t\t\tif (player.pGame == g):\n\t\t\t\t\t\tif player1 == None:\n\t\t\t\t\t\t\tplayer1 = player\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tplayer2 = player\n\t\t\t\tend_winner = host.isGameOver(g)\n\t\t\t\tif end_winner == EMPTY:#draw\n\t\t\t\t\tplayer.sendMessage(displayStr(host.hGrid[g]) + \" $end $draw\")\n\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\tif c.cId != cId and c.cType != 1:\n\t\t\t\t\t\t\tc.sendMessage(player1.pClient.name + \" and \" + player2.pClient.name + \" ended their game on a draw.\")\n\n\t\t\t\tif end_winner == J1:#player1 win\n\t\t\t\t\tplayer1.sendMessage(displayStr(host.hGrid[g]) + \" $end $win\")\n\t\t\t\t\tplayer2.sendMessage(displayStr(host.hGrid[g]) + \" $end $loose\")\n\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\tif c.cId != cId and c.cType != 1:\n\t\t\t\t\t\t\tc.sendMessage(player1.pClient.name + \" won against \" + player2.pClient.name + \".\")\n\t\t\t\t\tplayer1.pClient.score += 1\n\n\t\t\t\tif end_winner == J2:#player2 win\n\t\t\t\t\tplayer2.sendMessage(displayStr(host.hGrid[g]) + \" $end $win\")\n\t\t\t\t\tplayer1.sendMessage(displayStr(host.hGrid[g]) + \" $end $loose\")\n\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\tif c.cId != cId and c.cType != 1:\n\t\t\t\t\t\t\tc.sendMessage(player2.pClient.name + \" won against \" + player1.pClient.name + \".\")\n\t\t\t\t\tplayer2.pClient.score += 1\n\n\t\t\t\thost.endGame(g)\n\n\t\t(ready_sockets, [], []) = select.select(host.listSockets, [], [])\n\t\tfor current_socket in ready_sockets:\n\t\t\tif current_socket == host.socketListener: #Connexion of a new client\n\t\t\t\thost.addNewClient()\n\t\t\t\tprint(\"A new client connected\")\n\t\t\telse:\n\t\t\t\tcId = host.getClientId(current_socket)\n\t\t\t\tpId = host.getPlayerId(current_socket)\n\t\t\t\tbytes_recv = bytes.decode(current_socket.recv(1024))\n\t\t\t\tif len(bytes_recv) == 0 :#DECONNEXION of a client\n\t\t\t\t\tclient = host.getClient(host.getClientId(current_socket))\n\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\tif c.cType != 1 and c.cId != client.cId:\n\t\t\t\t\t\t\tc.sendMessage(client.name + \" disconnected.\")\n\t\t\t\t\tif client.cType == 1:\n\t\t\t\t\t\tplayer = host.getPlayer(host.getPlayerId(current_socket))\n\t\t\t\t\t\tplayer.isWaiting = -1\n\t\t\t\t\t\tplayer.pClient = None\n\t\t\t\t\tfor p in host.players:\n\t\t\t\t\t\tif p.pGame == player.pGame and p.pId != player.pId and p.pClient != None:\n\t\t\t\t\t\t\tp.sendMessage(\"Your opponent \" + client.name + \" has disconnected. You can wait for him to reconnect or quit by typing 'quit'.\")\n\t\t\t\t\t\t\tp.isWaiting = 1\n\t\t\t\t\thost.listClient.remove(client)\n\t\t\t\t\thost.listSockets.remove(current_socket)\n\t\t\t\t\tcurrent_socket.close()\n\n\t\t\t\telif pId != -1:\n\t\t\t\t\tplayer = host.getPlayer(pId)\n\t\t\t\t\tif bytes_recv == \"quit\":\n\t\t\t\t\t\t(p1, p2) = host.getPlayers(player.pGame)\n\t\t\t\t\t\tlog = \"Match canceled by \" + player.pClient.name\n\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\tif c.cType != 1:\n\t\t\t\t\t\t\t\tc.sendMessage(log)\n\t\t\t\t\t\tif p1 != None and p1.pClient != None:\n\t\t\t\t\t\t\tp1.sendMessage(log)\n\t\t\t\t\t\tif p2 != None and p2.pClient != None:\n\t\t\t\t\t\t\tp2.sendMessage(log)\n\t\t\t\t\t\thost.endGame(player.pGame)\n\t\t\t\t\tif pId == host.currentPlayer[player.pGame] + 2 * player.pGame:\n\t\t\t\t\t\ttry: #try to convert the message in an integer\n\t\t\t\t\t\t\tisMoveOk = host.playMove(player.pGame, int(bytes_recv))\n\t\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\t\tisMoveOk = False\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif isMoveOk: #if the move is good\n\t\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\t\tif c.cType != 1 and c.cSpec == player.pGame:\n\t\t\t\t\t\t\t\t\tc.sendMessage(displayStr(host.hGrid[player.pGame]))\n\t\t\t\t\t\t\thost.switchPlayer(player.pGame)\n\t\t\t\telse:\n\t\t\t\t\tclient = host.getClient(cId)\n\t\t\t\t\tif bytes_recv == \"play\":\n\t\t\t\t\t\thost.setNewPlayer(host.getClient(cId))\n\t\t\t\t\t\tif host.isGameReady() == 1:\n\t\t\t\t\t\t\thost.startGame()\n\t\t\t\t\t\t\tidGame = len(host.hGrid) - 1\n\t\t\t\t\t\t\t(p1, p2) = host.getPlayers(idGame)\n\t\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\t\tif c.cType != 1 :\n\t\t\t\t\t\t\t\t\tc.sendMessage(\"A game started between \" + p1.pClient.name + \" and \" + p2.pClient.name + \" (ID:\" + str(idGame) + \")\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(client.name + \" is looking for an opponent\")\n\t\t\t\t\t\t\thost.getClient(cId).sendMessage(\"Waiting for opponent...\")\n\t\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\t\tif c.cId != cId and c.cType != 1:\n\t\t\t\t\t\t\t\t\tc.sendMessage(client.name + \" is looking for an opponent\")\n\t\t\t\t\tif bytes_recv == \"playAI\":\n\t\t\t\t\t\thost.setNewPlayer(host.getClient(cId))\n\t\t\t\t\t\thost.setNewAIPlayer()\n\t\t\t\t\t\tif host.isGameReady() == 1:\n\t\t\t\t\t\t\thost.startGame()\n\t\t\t\t\t\t\tidGame = len(host.hGrid) - 1\n\t\t\t\t\t\t\t(p1, p2) = host.getPlayers(idGame)\n\t\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\t\tif c.cType != 1 :\n\t\t\t\t\t\t\t\t\tc.sendMessage(\"A game started between \" + p1.pClient.name + \" and the AI (ID:\" + str(idGame) + \")\")\n\t\t\t\t\tif bytes_recv == \"lead\":\n\t\t\t\t\t\tclient.sendMessage(host.getScoresString())\n\t\t\t\t\tif len(bytes_recv) > 4 and bytes_recv[4] == ':':\t\t\t\t#commande\n\t\t\t\t\t\tcommand = bytes_recv.split(':')\n\t\t\t\t\t\tif len(command) == 2:\n\t\t\t\t\t\t\tif command[0] == \"name\": \t\t\t#set client name\n\t\t\t\t\t\t\t\tlog = \"\"\n\t\t\t\t\t\t\t\tcommand[1] = host.checkForFreeName(command[1])\n\t\t\t\t\t\t\t\tif client.name == \"nameless\":\n\t\t\t\t\t\t\t\t\tlog = command[1] + \" joined\"\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tlog = client.name + \" changed name to \" + command[1]\n\t\t\t\t\t\t\t\tclient.setName(command[1])\n\t\t\t\t\t\t\t\tprint(log)\n\t\t\t\t\t\t\t\tfor c in host.listClient:\n\t\t\t\t\t\t\t\t\tif c.cType != 1 and c.cId != client.cId:\n\t\t\t\t\t\t\t\t\t\tc.sendMessage(log)\n\t\t\t\t\t\t\tif command[0] == \"spec\":\t\t\t#spectate a game\n\t\t\t\t\t\t\t\tg = int(command[1])\n\t\t\t\t\t\t\t\tclient.cSpec = g\n\t\t\t\t\t\t\tif command[0] == \"join\":\n\t\t\t\t\t\t\t\tfor p in host.players:\n\t\t\t\t\t\t\t\t\tif p.pClient != None and p.pClient.name == command[1]:\n\t\t\t\t\t\t\t\t\t\tif p.isWaiting == 1:\n\t\t\t\t\t\t\t\t\t\t\tfor p2 in host.players:\n\t\t\t\t\t\t\t\t\t\t\t\tif p2.isWaiting == -1 and p2.pGame == p.pGame:\n\t\t\t\t\t\t\t\t\t\t\t\t\tp2.pClient = client\n\t\t\t\t\t\t\t\t\t\t\t\t\tp2.isWaiting = 0\n\t\t\t\t\t\t\t\t\t\t\t\t\tp.isWaiting = 0\n\t\t\t\t\t\t\t\t\t\t\t\t\tclient.cType = 1\n\t\t\t\t\t\t\t\t\t\t\t\t\tclient.sendMessage(\"Reconnected against \" + p.pClient.name)\n\t\t\t\t\t\t\t\t\t\t\t\t\tp.pClient.sendMessage(\"Your opponent \" + client.name + \" reconnected.\")\n\n\n\n#_______________________________________END MAIN_SERVEUR _________________________________________________________________________________\n\ndef main_client(ip, port):#Creating two threads, one for emission, one for reception\n\tsocket_client = socket(AF_INET, SOCK_STREAM)\n\tsocket_client.connect((ip, port))\n\ttr = thread_r(socket_client)\n\tts = thread_s(socket_client)\n\n\ttr.start()\n\tts.start()\n\ndef main():#If there is no argument, we start the server, else we start as a client\n\targv = sys.argv\n\tif len(argv) == 1:\n\t\tmain_server()\n\telse:\n\t\tip = sys.argv[1]\n\t\tport = 7777\n\t\tmain_client(ip, port)\n\nmain()\n","sub_path":"main_reseau.py","file_name":"main_reseau.py","file_ext":"py","file_size_in_byte":16216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"313871577","text":"'''\nSolution - 1 (subsetsMaths)\nTime Complexity: O(n) -> no of elements in set\nSpace Complexity: O(1)\nDid this code successfully run on Leetcode : Yes\nExplanation:\nThe product of the sum of all subsets is equal to ((1+element1).. (1+elementn)) -1\nEg = 1,2,3\n(1+1)(2+1)(3+1)-1 = 23\nProof: a b => a +b +ab => (1+a) + b(1+a) -1 => (1+a) (1+b) -1\n\nSolution - 2 (subsetsBackTrack)\nTime Complexity: O(2^n * n) -> n for computing the product for each set\nSpace Complexity: O(n)\nDid this code successfully run on Leetcode : Yes\nExplanation:\nUse backtracking to create all subsets of a set and find product once its created and add it to a global sum.\n'''\n\nimport copy\nclass Solution:\n #solution-1\n def subsetsMaths(self, nums: List[int]) -> int:\n product = 1\n for num in nums:\n product *= (1 + num)\n return product - 1\n\n #Solution - 2\n def __init__(self):\n self.sum = 0\n\n def backtrack(self, solution: List[int], nums: List[int], state: List[int], index: int):\n # we will never have repeated elements hence just add\n\n if len(state) > 0:\n product = 1\n for i in range(0, len(state)):\n product *= state[i]\n self.sum += product\n\n for i in range(index, len(nums)):\n # add candidate\n state.append(nums[i])\n # backtrack\n self.backtrack(solution, nums, state, i + 1)\n # pops elements and adds combination, last pop will be an empty array and start with a new subtree\n # pop\n state.pop()\n\n def subsetsBackTrack(self, nums: List[int]) -> int:\n if nums == None:\n return []\n\n solution = []\n self.backtrack(solution, nums, [], 0)\n\n return self.sum","sub_path":"Sum of the products of all possible Subsets.py","file_name":"Sum of the products of all possible Subsets.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"556483896","text":"from featuer_generator import *\nfrom utils import *\nfrom trade_strategy import *\nfrom bi_lstm_model import Model\nfrom sklearn import metrics\nfrom keras.models import Sequential, load_model\n\nSTOCK_SYMBOL = 'GOOG'\nSTART_DATE = '2010-01-01'\nEND_DATE = '2021-04-30'\nROLLING_X = 3\nTRAIN_MODEL = True\nSAVE_MODEL_FILE_PATH = \"./saved_models/bi-lstm-21052021-e20-h7-p1.h5\"\n\nif __name__ == '__main__':\n df_input_data = get_raw_data(stock_symbol=STOCK_SYMBOL, start_date=START_DATE, end_date=END_DATE, plot_data=True)\n simple_features, df_input_data = derive_simple_features(data=df_input_data, rolling_x=7,\n plot_data=True)\n technical_indicator_features, df_input_data = get_technical_indicator_features(data=df_input_data,\n rolling_x=7, plot_data=True)\n\n selected_features = simple_features + technical_indicator_features\n fig_name_0 = \"corr_heat_map\"\n plot_corr_heatmap(fig_name=fig_name_0, cols=selected_features, data=df_input_data, save_fig=True)\n selected_targets = ['Adj Close']\n history_points = 28\n pred_points = 1\n X_train, X_test, y_train, y_test, scaler_y, y_test_date = train_test_split(data=df_input_data,\n train_test_split_ratio=0.9,\n features=selected_features,\n targets=selected_targets,\n history_points=history_points,\n pred_points=pred_points)\n y_train = y_train.reshape(y_train.shape[0], -1)\n y_test = y_test.reshape(y_test.shape[0], -1)\n if TRAIN_MODEL:\n model = Model(input_time_steps=history_points, input_dim=len(selected_features), output_time_steps=pred_points,\n output_dim=1)\n model.build_model()\n model.train(x=X_train, y=y_train, epochs=20, batch_size=32, save_dir=\"saved_models\")\n else:\n model = load_model(SAVE_MODEL_FILE_PATH)\n if isinstance(model, Sequential):\n print(model.summary())\n\n y_pred = model.predict(X_test)\n y_pred = scaler_y.inverse_transform(y_pred.reshape(-1, 1))\n y_test = scaler_y.inverse_transform(y_test.reshape(-1, 1))\n\n df_results = pd.DataFrame()\n df_results['real_price'] = pd.Series(y_test.reshape(-1))\n df_results['pred_price'] = pd.Series(y_pred.reshape(-1))\n df_results['Date'] = pd.Series(y_test_date)\n df_results['real_price_daily_return'] = df_results['real_price'].pct_change().values\n df_results['real_price_cumulative_return'] = (1 + df_results['real_price_daily_return']).cumprod() - 1\n df_results['pred_price_daily_return'] = df_results['pred_price'].pct_change().values\n df_results['pred_price_cumulative_return'] = (1 + df_results['pred_price_daily_return']).cumprod() - 1\n df_results['pred_err'] = (df_results['pred_price'] - df_results['real_price']) / df_results['real_price']\n df_results['pred_accuracy'] = df_results['pred_err'].abs()\n\n rmse = int(metrics.mean_squared_error(y_test.reshape(-1), y_pred.reshape(-1), squared=False))\n print(\"rmse: {}\".format(rmse))\n fig_name_1 = \"pred_results_rmse_{0}_hist_steps_{1}_pred_steps_{2}\".format(rmse, history_points, pred_points)\n plot_time_series_charts(model_name=\"bi-lstm\", figsize=(20, 8), xlabels=['Date', 'Date'], ylabels=['real_price', 'pred_price'],\n data=df_results, fig_name=fig_name_1, use_subplots=False,\n num_xticks=min(len(df_results), 50),\n num_annotations=min(len(df_results), 10))\n\n fig_name_2 = \"cumulative_returns_hist_steps_{0}_pred_steps_{1}\".format(history_points, pred_points)\n plot_time_series_charts(model_name=\"bi-lstm\", figsize=(20, 8), xlabels=['Date', 'Date'], ylabels=['real_price_cumulative_return',\n 'pred_price_cumulative_return'],\n data=df_results, fig_name=fig_name_2, use_subplots=False,\n num_xticks=min(len(df_results), 50),\n num_annotations=min(len(df_results), 10))\n\n fig_name_3 = \"pred_accuracy_hist_steps_{0}_pred_steps_{1}\".format(history_points, pred_points)\n plot_time_series_charts(model_name=\"bi-lstm\", figsize=(20, 8), xlabels=['Date'], ylabels=['pred_accuracy'],\n data=df_results, fig_name=fig_name_3, use_subplots=False,\n num_xticks=min(len(df_results), 50),\n num_annotations=min(len(df_results), 10))\n\n initial_invest = 100000\n buying_percentage_threshold = 0.003\n selling_percentage_threshold = 0.01\n trade_result, passive_trade_result, num_of_stocks, trade_action = buy_sell_trades(\n actual=df_results['real_price'].values.tolist(),\n predicted=df_results['pred_price'].values.tolist(),\n date=df_results['Date'].values.tolist(),\n invest_fund=initial_invest,\n history_points=history_points,\n pred_points=pred_points,\n buying_percentage_threshold=buying_percentage_threshold,\n selling_percentage_threshold=selling_percentage_threshold,\n model_name=\"bi_lstm\")\n\n df_results['trade_action'] = trade_action\n fig_name_4 = \"trade_action_hist_steps_{0}_pred_steps_{1}\".format(history_points, pred_points)\n plot_trade_action(model_name=\"bi-lstm\", figsize=(20, 8),\n fig_name=fig_name_4,\n xlabels=['Date', 'Date'],\n ylabels=['real_price', 'pred_price'],\n data=df_results,\n number_stock=num_of_stocks,\n initial_invest=initial_invest,\n passive_trade_result=passive_trade_result,\n asset=trade_result,\n rotation=45, num_xticks=50,\n num_annotations=len(df_results),\n save_fig=True)\n","sub_path":"XCS229ii-Project/Library/core/run_bi_lstm.py","file_name":"run_bi_lstm.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"67484060","text":"#!/usr/bin/python\n# -*-coding:Utf-8 -*\n\nfrom PyQt4 import QtGui, QtCore\n\n\nclass GraphicsViewPerso(QtGui.QGraphicsView):\n\n \"\"\"Classe perso qui permet d'implémenter un zoom pour la mosaïque\n http://stackoverflow.com/questions/12249875/pyqt4-mousepressevent-position-offset-in-qgraphicsview\"\"\"\n \n\n def __init__(self, parent = None):\n\n super(GraphicsViewPerso, self).__init__(parent)\n self.parent = parent\n self.setDragMode(QtGui.QGraphicsView.RubberBandDrag)\n self.setRenderHint(QtGui.QPainter.Antialiasing)\n self.setRenderHint(QtGui.QPainter.TextAntialiasing)\n\n\n def wheelEvent(self, event):\n\n \"\"\"On réimplémente la gestion de la molette\"\"\"\n\n super(GraphicsViewPerso, self).wheelEvent(event)\n\n modifiers = QtGui.QApplication.keyboardModifiers()\n\n #On zoome seulement si la touche Ctrl est enfoncée\n if modifiers == QtCore.Qt.ControlModifier:\n self.setTransformationAnchor(GraphicsViewPerso.AnchorUnderMouse)\n factor = 1.2\n if event.delta() < 0 :\n factor = 1.0 / factor\n self.scale(factor, factor)\n","sub_path":"graphicsview.py","file_name":"graphicsview.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"237767449","text":"import ipaddress as ip\nimport socket\n\n\ndef getLANip() -> ip.IPv4Address:\n \"\"\" get IP of own interface\n ref: http://stackoverflow.com/a/23822431\n \"\"\"\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n # don't use link local here (169.254.x.x) unless you have a specific need\n try:\n s.connect((\"\", 0))\n except OSError:\n s.connect((\"8.8.8.8\", 80)) # for BSD/Mac\n\n name = s.getsockname()[0]\n\n return ip.ip_address(name)\n\n\ndef validateservice(service: str, h: str, b: bytes) -> str:\n \"\"\"\n splitlines is in case the ASCII/UTF8 response is less than 32 bytes,\n hoping server sends a \\r\\n\n \"\"\"\n if not b: # empty reply\n return None\n # %% non-empty reply\n svc_txt = b.splitlines()[0].decode(\"utf-8\", \"ignore\")\n # %% optional service validation\n if service and service not in svc_txt.lower():\n return None\n\n return svc_txt\n\n\ndef netfromaddress(addr: ip.IPv4Address, mask: str = \"24\") -> ip.IPv4Network:\n\n if isinstance(addr, ip.IPv4Address):\n net = ip.ip_network(addr.exploded.rsplit(\".\", 1)[0] + \".0/{}\".format(mask))\n elif isinstance(addr, ip.IPv6Address):\n net = ip.ip_network(addr.exploded.rsplit(\":\", 1)[0] + \":0/{}\".format(mask))\n else:\n raise TypeError(addr)\n return net\n","sub_path":"src/findssh/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"240192767","text":"import pytest\nimport allure\n\nfrom ui.pages.settings_page import SourcesNewsSettingsPage\n\nfrom tests.base_test import PrepareNewsPage\n\n\nclass TestCaseValidateCheckbox(PrepareNewsPage):\n\n @pytest.mark.Android\n @allure.epic(\"News tests\")\n def test_validate_source_news(self, sources_news: SourcesNewsSettingsPage) -> None:\n\n # Проверка на появление галки рядом с пунктом 'Вести ФМ'.\n sources_news.check_checkbox()\n\n # Вернуться на главную страницу.\n sources_news.\\\n go_back().\\\n go_to('main-page')\n\n # Отобразить данные о новостях.\n self.main_page.send_query(\"News\")\n\n # Свайп до элемента.\n self.main_page.swipe_to_element(self.main_page.locators.LABEL_PLAYED_NAME)\n\n # Проверить новости с \"Вести ФМ\".\n with allure.step(\"Check Vesti FM\"):\n assert self.main_page.get_obj_text(self.main_page.locators.LABEL_PLAYED_NAME) == \"Вести ФМ\"\n","sub_path":"tests/test_news.py","file_name":"test_news.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"228349215","text":"#!/usr/bin/python3\n\"\"\"places\"\"\"\n\nfrom flask import abort, jsonify, make_response, request\nfrom models import storage\nfrom models.user import User\nfrom models.place import Place\nfrom models.city import City\nfrom api.v1.views import app_views\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_places(city_id):\n \"\"\"Get a list of places\"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n places = [plc.to_dict() for plc in city.places]\n return jsonify(places)\n\n\n@app_views.route('/places/', methods=['GET'],\n strict_slashes=False)\ndef get_place(place_id):\n \"\"\"get places information\"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\"Delete a place\"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n place.delete()\n storage.save()\n return jsonify({})\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef post_place(city_id):\n \"\"\"Create a new place\"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n if request.get_json() is None:\n abort(400, 'Not a JSON')\n if 'user_id' not in request.get_json():\n abort(400, 'Missing user_id')\n if 'name' not in request.get_json():\n abort(400, 'Missing name')\n req_json = request.get_json()\n req_json['city_id'] = city_id\n user = storage.get(User, req_json['user_id'])\n if user is None:\n abort(404)\n place = Place(**req_json)\n place.save()\n return make_response(jsonify(place.to_dict()), 201)\n\n\n@app_views.route('/places/', methods=['PUT'],\n strict_slashes=False)\ndef put_place(place_id):\n \"\"\"Update an existing place\"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n if request.get_json() is None:\n abort(400, 'Not a JSON')\n for a, v in request.get_json().items():\n if a not in ['id', 'user_id', 'city_id',\n 'created_at', 'updated_at']:\n setattr(place, a, v)\n place.save()\n return jsonify(place.to_dict())\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"647984282","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nfrom hamcrest import assert_that, equal_to_ignoring_whitespace, is_, has_item\n\nfrom hermes.config import hermes_config\nfrom hermes.interventions import InterventionsApi\nfrom hermes.helpers.random_data_generator import TextHelper\n\n\nclass TestUpdateInterventions(object):\n\n @pytest.mark.parametrize('intrv_id, name, desc', [\n (\n hermes_config['intervention2']['id'],\n TextHelper.get_random_text(1),\n TextHelper.get_random_text(1),\n ),\n (\n hermes_config['intervention2']['id'],\n TextHelper.get_random_text(191),\n TextHelper.get_random_text(100),\n )\n ])\n def test_update_intervention(self, logged_client, intrv_id, name, desc):\n code, result = InterventionsApi.update_intervention(\n intrv_id=intrv_id, name=name, desc=desc)\n assert_that(code, is_(200),\n 'Expected that code is \"%s\", but was \"%s\".' % (\n 200, code\n ))\n assert_that(result['name'], equal_to_ignoring_whitespace(name),\n 'Expected that name is \"%s\", but was \"%s\".' % (\n name, result['name']\n ))\n assert_that(result['desc'], equal_to_ignoring_whitespace(desc),\n 'Expected that desc is \"%s\", but was \"%s\".' % (\n desc, result['desc']\n ))\n\n @pytest.mark.parametrize('q_ids, base_id', [\n ([1, 2, 3, 4], 1, ),\n ([2], 2, )\n ])\n def test_update_intervention_questions(self, logged_client, config,\n q_ids, base_id):\n intrv_id = config['intervention2']['id']\n code, result = InterventionsApi.update_intervention(\n intrv_id=intrv_id, question_ids=q_ids,\n baseline_question_id=base_id)\n assert_that(code, is_(200),\n 'Expected that code is \"%s\", but was \"%s\".' % (200, code))\n result_q_ids = [int(item['id']) for item in\n result['intervention_questions']]\n for question in q_ids:\n assert_that(result_q_ids, has_item(question),\n 'Expected that question id \"%s\" is in \"%s\".' % (\n question, result_q_ids\n ))\n result_base_q_id = [int(item['id']) for item in\n result['intervention_questions']\n if item['priority'] == '1'][0]\n assert_that(result_base_q_id, is_(base_id),\n 'Expected that baseline question id is \"%s\", but was '\n '\"%s\".' % (base_id, result_base_q_id))\n","sub_path":"hermes_api_tests/tests/a-interventions/test_update_intervention.py","file_name":"test_update_intervention.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"484084729","text":"# A graph whose nodes have all been labeled can be represented by an adjacency\n# list, in which each row of the list contains the two node labels corresponding\n# to a unique edge.\n#\n# A directed graph (or digraph) is a graph containing directed edges, each of\n# which has an orientation. That is, a directed edge is represented by an arrow\n# instead of a line segment; the starting and ending nodes of an edge form its\n# tail and head, respectively. The directed edge with tail v and head w is\n# represented by (v,w) (but not by (w,v)). A directed loop is a directed edge of\n# the form (v,v).\n#\n# For a collection of strings and a positive integer k, the overlap graph for\n# the strings is a directed graph Ok in which each string is represented by a\n# node, and string s is connected to string t with a directed edge when there is\n# a length k suffix of s that matches a length k prefix of t, as long as s≠t; we\n# demand s≠t to prevent directed loops in the overlap graph (although directed\n# cycles may be present).\n#\n# Given: A collection of DNA strings in FASTA format having total length at most\n# 10 kbp.\n#\n# Return: The adjacency list corresponding to O3. You may return edges in any order.\n#\n# Sample Dataset\n# >Rosalind_0498\n# AAATAAA\n# >Rosalind_2391\n# AAATTTT\n# >Rosalind_2323\n# TTTTCCC\n# >Rosalind_0442\n# AAATCCC\n# >Rosalind_5013\n# GGGTGGG\n\n# Sample Output\n# Rosalind_0498 Rosalind_2391\n# Rosalind_0498 Rosalind_0442\n# Rosalind_2391 Rosalind_2323\nimport itertools\nfrom GC import make_seq_dict # I knew I would have to re-use this code!\n\nseq_dict = make_seq_dict('GRPH_input-train.txt')\n\ndef overlap_graph(seq_dict, k=3):\n for key1, key2 in itertools.product(seq_dict, seq_dict):\n if key1 == key2: continue\n elif seq_dict[key1][-k:].startswith(seq_dict[key2][:k]):\n print(key1, key2)\n\noverlap_graph(seq_dict, k=3)\n\nseq_dict_test = make_seq_dict('GRPH_input-test.txt')\n\noverlap_graph(seq_dict_test, k=3)\n\n# Same thing without itertools, but slightly less efficint\n\n# for key1 in seq_dict:\n# for key2 in seq_dict:\n# if key1 == key2:\n# continue\n# elif seq_dict[key1][-k:].startswith(seq_dict[key2][:k]):\n# print(key1, key2)","sub_path":"GRPH.py","file_name":"GRPH.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"75568626","text":"import os\nimport re\nimport json\nfrom datetime import datetime, timedelta\nimport time\nimport numpy as np\nimport pandas as pd\nfrom scipy.ndimage.filters import gaussian_filter1d\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\ndef parse_time_features(timestamp):\n '''\n Parse higher-dimensional time information from `timestamp`\n '''\n # Year, Month, Day of Month, Day of Week, Hour, Minutes, Seconds\n return [int(time.mktime(timestamp.timetuple())), timestamp.year, timestamp.month, timestamp.day, \n timestamp.weekday(), timestamp.hour, timestamp.minute, timestamp.second]\n\ndef parse_timestamp(date):\n '''\n Parse timestamp and higher-dimensional time information from `email` containing corpus of emails\n '''\n # parse timestamp \n timestamp = datetime.strptime(date[0:19], '%Y-%m-%dT%H:%M:%S')\n if date[19]=='+':\n timestamp-=timedelta(hours=int(date[20:22]), minutes = int(date[23:]))\n elif date[19]=='-':\n timestamp+=timedelta(hours=int(date[20:22]), minutes = int(date[23:]))\n return parse_time_features(timestamp)\n\ndef parse_email(email, filename, index, length):\n '''\n Parse timestamp, and higher-dimensional time information from `email` \n '''\n logging.debug(f'Parsing email {index} of {length} from file: {filename}')\n return [parse_timestamp(email['date'])[0], filename]\n\ndef events_to_rates(event_times, filter_bandwidth=1, num_bins=60, min_time = None, max_time=None, density = True):\n \"\"\" convert list of event times into rate function with a discrete time bin_size of 1/rates_per_unit.\n Uses a guassian filter over the empirical rate (histogram count / bin_size) \"\"\"\n\n if len(event_times) == 0: # if event times is an empty list or array\n logging.debug(\"empty event_times list/array\")\n return np.zeros(num_bins), np.zeros(num_bins)\n\n if not max_time:\n max_time = max(event_times)\n if not min_time:\n min_time = min(event_times)\n bins = np.linspace(min_time, max_time, num=num_bins + 1)\n rate_times = (bins[1:] + bins[:-1]) / 2\n\n bin_size = (max_time - min_time) / num_bins\n if density:\n counts = np.array(np.histogram(event_times, bins=bins)[0])\n sampled_rates = counts / sum(counts)\n else:\n counts = np.array(np.histogram(event_times, bins=bins)[0])\n sampled_rates = counts / bin_size\n rate_vals = gaussian_filter1d(sampled_rates, filter_bandwidth, mode=\"nearest\")\n return rate_vals, rate_times\n\n# walk through datapath and parse all jsonl files\ndatapath = 'dry_run_data'\nlogging.debug(f'Parsing emails from raw json files...\\n')\nall_emails = []\nfor path, _, files in os.walk(datapath):\n for file in files:\n if re.match(\".*.jsonl$\", file):\n fullpath = os.path.join(path, file)\n with open(fullpath) as data_file:\n emails = data_file.readlines()\n parsed_emails = [parse_email(json.loads(email), file, index, len(emails)) for index, email in enumerate(emails)]\n all_emails.extend(parsed_emails)\n\ntime_features = pd.DataFrame(all_emails, columns = ['Timestamp', 'file'])\n#time_features = pd.DataFrame(all_emails, columns = ['Timestamp','Year', 'Month', 'Day of Month', 'Day of Week', 'Hour', 'Minute', 'Seconds', 'file'])\n\n# convert timestamps to rates\nlogging.debug(f'Converting timestamps to rate functions...\\n')\ndays = 5\nhours = 24\nnum_bins = 60\nstart_date = \"2019-03-04\"\nstart_time = datetime.strptime(start_date, '%Y-%m-%d')\nmin_time = int(time.mktime(start_time.timetuple()))\nseries_size = 60 * 60 * 4\nwindow = 60\nmax_time = min_time + days * hours * 3600\n\n# create time series (1 series / hr --> 120 total series)\ntimes = time_features['Timestamp'].values.astype(int)\nattack_times = time_features.loc[time_features['file'] == 'recourse-attacks.jsonl']['Timestamp']\nseries_values = []\nseries_times = []\nseries_labels = []\nt = min_time\nwhile ((t + series_size) < max_time):\n events = times[(t <= times) & (times < (t + series_size))]\n rate_vals, rate_times = events_to_rates(times, \n num_bins = num_bins, \n filter_bandwidth = 1, \n density = False,\n min_time = t,\n max_time = t + series_size)\n series_values.append(rate_vals)\n series_times.append(rate_times)\n label = max([1 if (t <= at) & (at < (t + series_size)) else 0 for at in attack_times])\n series_labels.append(label)\n logging.debug(f\"Added time series with {len(events)} events and label {label}\")\n t += window\n\nlogging.debug(f'A total of {len(series_labels)} time series were created')\nlabels = np.array(series_labels)\n\n# generate high-dimensional time features from series_times\nlogging.debug(f'Generating high-dimensional time features from rate times...\\n')\nt_features = [[parse_time_features(datetime.fromtimestamp(t))[1:] for t in s] for s in series_times]\nX_data = [t_feat.append(vals) for t_feat, vals in zip(t_features, series_values)]\nX_data = np.vstack(t_features)\n\nassert len(labels) == X_data.shape[0], f\"The number of labels is {len(labels)}, but the number of records is {X_data.shape[0]}\"\n\n# splitting data into training and testing \ntrain_split = int(0.8 * len(labels))\nlogging.debug(f'Splitting data into training and testing sets...')\n'''if not os.path.isfile(datapath + \"/prepared/train_X.npy\"):\n os.mkdir(datapath + \"/prepared\")\n'''\nnp.save(datapath + \"/prepared/train_X_4_hrs.npy\", X_data[:train_split])\nnp.save(datapath + \"/prepared/train_y_4_hrs.npy\", labels[:train_split])\nnp.save(datapath + \"/prepared/test_X_4_hrs.npy\", X_data[train_split:])\nnp.save(datapath + \"/prepared/test_y_4_hrs.npy\", labels[train_split:])\n\nlogging.debug(f'Train set: March 4 - March 7 contains {train_split} series')\nlogging.debug(f'Test set: March 8 contains {len(labels) - train_split} series')\n","sub_path":"LSTM-FCN/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":5977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"521331167","text":"import click\n\nimport requests\n\n\n\n\nprompt_test = \"Enter the news source. Options are: BBC, CNN, DAILY-MAIL,ABC\"\n\n\n\n@click.command()\n@click.option('--source', prompt=prompt_test)\ndef cli(source):\n if source.lower() == 'bbc':\n url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=6ec52193c4974fd68ca3c25e7c33a950&pageSize=10'\n\n elif source.lower() == 'cnn':\n url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=6ec52193c4974fd68ca3c25e7c33a950&pageSize=10'\n\n elif source.lower() == 'daily-mail':\n url = 'https://newsapi.org/v2/top-headlines?sources=daily-mail&apiKey=6ec52193c4974fd68ca3c25e7c33a950&pageSize=10'\n\n elif source.lower() == 'abc':\n url = 'https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey=6ec52193c4974fd68ca3c25e7c33a950&pageSize=10'\n\n \n \n else:\n source.lower() != 'bbc', 'cnn', 'daily-mail', 'abc'\n message = print('source not found')\n return message\n\n news_request = requests.get(url)\n main_dict = news_request.json()\n article_dict = main_dict['articles']\n\n\n\n for articles in article_dict:\n click.echo(click.style('TITLE: ' + articles['title'], fg='red'))\n click.echo(click.style('DESCRIPTION: ' +\n articles['description'], fg='blue'))\n click.echo(click.style('URL: ' +\n articles['url'], fg='red'))\n click.echo('\\n')\n click.echo(click.wrap_text(articles['description'], 100))\n click.echo('\\n')\n click.echo('-' * 100)\n cli()\n \n\ncli()\n\n","sub_path":"new/newsapi.py","file_name":"newsapi.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"604077918","text":"# -*- coding: utf-8 -*-\n# @COPYRIGHT_begin\n#\n# Copyright [2015] Michał Szczygieł, M4GiK Software\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# @COPYRIGHT_end\nfrom django.template.defaultfilters import force_escape\nfrom django.utils.translation import ugettext_lazy as _\n\nauth_error_text = _('Authorization error. Re-login required.')\n\n\n# \\c errors - dictionary of the errors informations' keys and information\n# (for error informations without parameters):\nERRORS = {\n 'ok': _('No error'),\n }\n\n\ndef get_error(error_key):\n \"\"\"\n If error with \\c error_key exists, function returns it's message. Otherwise it returns \"*Unknown error :(*\" message.\n \"\"\"\n return force_escape(ERRORS.get(error_key) or error_key)","sub_path":"dev_cloud/core/utils/messages_codes.py","file_name":"messages_codes.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"366468962","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server.models.contact import Contact # noqa: F401,E501\nimport re # noqa: F401,E501\nfrom swagger_server import util\n\n\nclass School(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n def __init__(self, service_involvement: str=None, contact: Contact=None, school_name: str=None, admission_type: str=None): # noqa: E501\n \"\"\"School - a model defined in Swagger\n\n :param service_involvement: The service_involvement of this School. # noqa: E501\n :type service_involvement: str\n :param contact: The contact of this School. # noqa: E501\n :type contact: Contact\n :param school_name: The school_name of this School. # noqa: E501\n :type school_name: str\n :param admission_type: The admission_type of this School. # noqa: E501\n :type admission_type: str\n \"\"\"\n self.swagger_types = {\n 'service_involvement': str,\n 'contact': Contact,\n 'school_name': str,\n 'admission_type': str\n }\n\n self.attribute_map = {\n 'service_involvement': 'serviceInvolvement',\n 'contact': 'contact',\n 'school_name': 'schoolName',\n 'admission_type': 'admissionType'\n }\n self._service_involvement = service_involvement\n self._contact = contact\n self._school_name = school_name\n self._admission_type = admission_type\n\n @classmethod\n def from_dict(cls, dikt) -> 'School':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The School of this School. # noqa: E501\n :rtype: School\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def service_involvement(self) -> str:\n \"\"\"Gets the service_involvement of this School.\n\n\n :return: The service_involvement of this School.\n :rtype: str\n \"\"\"\n return self._service_involvement\n\n @service_involvement.setter\n def service_involvement(self, service_involvement: str):\n \"\"\"Sets the service_involvement of this School.\n\n\n :param service_involvement: The service_involvement of this School.\n :type service_involvement: str\n \"\"\"\n\n self._service_involvement = service_involvement\n\n @property\n def contact(self) -> Contact:\n \"\"\"Gets the contact of this School.\n\n\n :return: The contact of this School.\n :rtype: Contact\n \"\"\"\n return self._contact\n\n @contact.setter\n def contact(self, contact: Contact):\n \"\"\"Sets the contact of this School.\n\n\n :param contact: The contact of this School.\n :type contact: Contact\n \"\"\"\n\n self._contact = contact\n\n @property\n def school_name(self) -> str:\n \"\"\"Gets the school_name of this School.\n\n\n :return: The school_name of this School.\n :rtype: str\n \"\"\"\n return self._school_name\n\n @school_name.setter\n def school_name(self, school_name: str):\n \"\"\"Sets the school_name of this School.\n\n\n :param school_name: The school_name of this School.\n :type school_name: str\n \"\"\"\n\n self._school_name = school_name\n\n @property\n def admission_type(self) -> str:\n \"\"\"Gets the admission_type of this School.\n\n\n :return: The admission_type of this School.\n :rtype: str\n \"\"\"\n return self._admission_type\n\n @admission_type.setter\n def admission_type(self, admission_type: str):\n \"\"\"Sets the admission_type of this School.\n\n\n :param admission_type: The admission_type of this School.\n :type admission_type: str\n \"\"\"\n\n self._admission_type = admission_type\n","sub_path":"server/swagger_server/models/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"330432432","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\ncount=0\nlist1=[]\n\n\n# In[4]:\n\n\nwhile(count<11):\n print(count,end=\",\")\n list1.append(count)\n count+=1\n\n\n# In[5]:\n\n\nlist1\n\n\n# In[12]:\n\n\nfor X in range(1,6):\n count = 1\n print(f\"Value of X is {X}\")\n while(count<=X):\n print(\"\\t -->hello\")\n count+=1\n \n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Training/WhileLoop.py","file_name":"WhileLoop.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290871957","text":"# -*- coding: utf-8 -*-\nfrom PySide import QtGui, QtCore\nfrom ..libs import get_icon_path\n\n\nclass FrameLayout(QtGui.QVBoxLayout):\n def __init__(self, button_text=None, collapse_status=None, can_set=True, parent=None):\n super(FrameLayout, self).__init__(parent)\n style_sheet_str = \"background:transparent;\"\n self.setContentsMargins(0, 0, 0, 0)\n self.setAlignment(QtCore.Qt.AlignTop)\n self.setSpacing(0)\n self.button_text = button_text\n self.collapse_status = collapse_status\n self.can_set = can_set\n self.parent = parent\n\n btn_layout = QtGui.QHBoxLayout()\n btn_layout.setContentsMargins(0, 0, 0, 0)\n btn_layout.setSpacing(0)\n btn_layout.setAlignment(QtCore.Qt.AlignLeft)\n self.collapse_btn = QtGui.QToolButton()\n self.collapse_btn.setFixedHeight(25)\n self.collapse_btn.setStyleSheet(style_sheet_str)\n self.collapse_btn.setText(self.button_text)\n self.collapse_btn.setIconSize(QtCore.QSize(6, 6))\n self.collapse_btn.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)\n\n self.set_btn = QtGui.QToolButton()\n self.set_btn.setStyleSheet(style_sheet_str)\n setting_icon = QtGui.QIcon(get_icon_path.get_icon_path(\"setting.png\"))\n self.set_btn.setIcon(setting_icon)\n\n self.delete_btn = QtGui.QToolButton()\n self.delete_btn.setStyleSheet(style_sheet_str)\n delete_icon = QtGui.QIcon(get_icon_path.get_icon_path(\"delete.png\"))\n self.delete_btn.setIcon(delete_icon)\n\n btn_layout.addWidget(self.collapse_btn)\n if self.can_set:\n btn_layout.addStretch()\n btn_layout.addWidget(self.set_btn)\n btn_layout.addWidget(self.delete_btn)\n\n self.frame = QtGui.QFrame()\n\n self.addLayout(btn_layout)\n self.addWidget(self.frame)\n self.init_settings()\n self.set_signals()\n\n def init_settings(self):\n if self.collapse_status:\n self.set_collapse()\n else:\n self.set_expand()\n\n def set_signals(self):\n self.collapse_btn.clicked.connect(self.change_collapse)\n\n def change_collapse(self):\n self.collapse_status = not self.collapse_status\n self.init_settings()\n\n def set_collapse(self):\n self.collapse_btn.setArrowType(QtCore.Qt.RightArrow)\n self.frame.setHidden(True)\n\n def set_expand(self):\n self.collapse_btn.setArrowType(QtCore.Qt.DownArrow)\n self.frame.setHidden(False)\n","sub_path":"miraTools/app_manager/python/frameworks/frame_layout.py","file_name":"frame_layout.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"454260930","text":"####dados = dict()\n#dados['nome'] = str(input('Nome'))\n#dados['RG'] = int(input('Registro Geral'))\n#dados['CPF/CNPJ'] = int(input('CPF/CNPJ'))\n#dados['telefone'] = int(input('Telefone'))\n#print(dados)\n\nlistas= [[]]\nwhile True:\n print ('Digite: 1 para Cadastrar pessoa.')\n print ('Digite: 2 para Lista de Cadastro.')\n print ('Digite: 3 para Procurar Pessoa Específica.')\n decisao = int(input('Qual opção deseja? '))\n if decisao == 1:\n usuarios = []\n nome = input('Digite o Nome')\n RG = input('Digite o RG')\n CPFCNPJ = input('Digite CPF/CNPJ')\n telefone = input('Digite Telefone')\n usuarios.append(nome)\n usuarios.append(RG)\n usuarios.append(CPFCNPJ)\n usuarios.append(telefone)\n listas.append(usuarios)\n elif decisao == 2:\n for mostrar in listas:\n try:\n print(\"Nome: %s - Idade: %s - ID: %s\"%(mostrar[1],mostrar[2],mostrar[0]))\n except:\n print(\"Essa pessoa não possui algum dos valores a seguir: Nome, Idade, ID\")\n\nid = input(\"Digite o id da pessoa desejada: \")\nfor mostrar in listas:\n if id in mostrar:\n try:\n print(\"Nome: %s - Idade: %s - ID: %s\"%(mostrar[1],mostrar[2],mostrar[0]))\n except:\n print(\"Essa pessoa não possui algum dos valores a seguir: Nome, Idade, ID\")\n","sub_path":"Python/Cadastro.py","file_name":"Cadastro.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"9812486","text":"from django.db import models\n\n# Create your models here.\nfrom apps.accounts.models import Account\nfrom apps.products.models import Product\n\n\nclass Offer (models.Model):\n\n decline = -1\n pending = 0\n accept = 1\n rejected = 2\n revoked = 3\n\n status_choices = [\n (decline, \"Decline\"),\n (pending, \"Pending\"),\n (accept, \"Accept\"),\n (rejected, \"Rejected\"),\n (revoked, \"Revoked\"),\n ]\n\n offer_price = models.DecimalField(verbose_name=\"Offer Price\", max_digits=8, decimal_places=2, default=0)\n status = models.IntegerField(verbose_name=\"Status\", choices=status_choices, default=pending)\n buyer = models.ForeignKey(Account)\n product = models.ForeignKey(Product)\n","sub_path":"apps/offers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"489998343","text":"import BaseHTTPServer\nimport urlparse\n\nSTATIC_FILES = {\n 'console.html': 'text/html',\n 'style.css': 'text/css',\n 'console.js': 'text/javascript',\n 'calendar.html': 'text/html',\n 'calendar.js': 'text/html',\n '/': ('console.html', 'text/html'),\n}\n\nclass ConsoleRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def __init__(self):\n BaseHTTPRequestHandler.BaseHTTPRequestHandler.__init__(self)\n\n def do_GET(self):\n parsed_path = urlparse.urlparse(self.path)\n self.send_response(200)\n self.end_headers()\n self.wfile.write('OK')\n\ndef init_webserver(server_class=BaseHTTPServer.HTTPServer,\n handler_class=ConsoleRequestHandler):\n server_address = ('', 8000)\n httpd = server_class(server_address, handler_class)\n return httpd\n\ndef main():\n server = init_webserver()\n server.serve_forever()\n\nif __name__ == '__main__':\n main()\n","sub_path":"console/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"411180063","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 23 12:19:45 2015\n\n@author: razkevich\n\"\"\"\n\nfrom nolearn.dbn import DBN\n\nnet = DBN(\n [784, 300, 10],\n learn_rates=0.3,\n learn_rate_decays=0.9,\n epochs=10,\n verbose=1,\n )\n \n \n \nimport csv\nimport numpy as np\n\nwith open('D:\\\\train.csv', 'rb') as f:\n\tdata = list(csv.reader(f))\n\t\ntrain_data = np.array(data[1:])\nlabels = train_data[:, 0].astype('float')\ntrain_data = train_data[:, 1:].astype('float') / 255.0\n\nnet.fit(train_data, labels)\n\n\n\nwith open('D:\\\\test.csv', 'rb') as f:\n\tdata = list(csv.reader(f))\n\ntest_data = np.array(data[1:]).astype('float') / 255.0\npreds = net.predict(test_data)\n\nwith open('D:\\\\submission.csv', 'wb') as f:\n fieldnames = ['\"ImageId\"', '\"Label\"']\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n i = 1\n for elem in preds:\n writer.writerow({'\"ImageId\"': i, '\"Label\"': str(elem)})\n i += 1","sub_path":"mnist.py.py","file_name":"mnist.py.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"631611067","text":"\nfrom dogLib import DogL2\n\npup = DogL2(__file__)\n#print(pup.__doc__)\n\ndataset_list = ['LANDSAT_TM_C1']\n\npath = 125\nrow = 53\n\n\n\nscene_list = pup.return_l1_scene_list(path, row, dataset_list[0])\n\n\nfor scene in scene_list:\n print(scene)\n \n\n\n\n\n","sub_path":"service/order/wip/Old/path_row_tester.py","file_name":"path_row_tester.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"569804157","text":"from PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport cv2\nplt.style.use('fivethirtyeight')\n\n'''This module do the Phase shifting \ninterferometry method. This need call it as\npython PSI(I1,I2,I3,I4), where I1... are the images taken with the module PSI_Camera.py'''\n\nclass PSI_VES(object):\n def __init__(self, I0, I1, I2, I0_f, I1_f, I2_f):\n self._I0 = I0\n self._I1 = I1\n self._I2 = I2\n self._I0_f = I0_f\n self._I1_f = I1_f\n self._I2_f = I2_f\n\n def VES(self,I0,I1,I2):\n p = I0 - I1\n q = I1 - I2\n r = I0 - I2\n A1 = np.trace(np.dot(q.transpose(), r))\n B1 = np.trace(np.dot(q.transpose(), q)) * np.trace(np.dot(r.transpose(), r))\n A2 = np.trace(np.dot(p.transpose(), q))\n B2 = np.trace(np.dot(p.transpose(), p)) * np.trace(np.dot(q.transpose(), q))\n alpha1 = 2 * np.arccos(A1 / np.sqrt(B1))\n alpha2 = 2 * np.arccos(A2 / np.sqrt(B2))\n phi_wrapped = np.arctan2(I2 - I1 + (I0 - I2) * np.cos(alpha1) - (I0 - I1) * np.cos(\n alpha2), (I0 - I2) * np.sin(alpha1) - (I0 - I1) * np.sin(alpha2))\n print(alpha1,alpha2)\n return phi_wrapped\n\n def itoh_2D(self, W):\n renglon, columna = W.shape\n phi = np.zeros(W.shape)\n psi = np.zeros(W.shape)\n phi[0, 0] = W[0, 0]\n # Se Desenvuelve la primera columna\n for m in range(1, columna):\n Delta = W[0, m] - W[0, m - 1]\n WDelta = np.arctan2(np.sin(Delta), np.cos(Delta))\n phi[0, m] = phi[0, m - 1] + WDelta\n psi[0, :] = phi[0, :]\n\n for k in range(columna):\n psi[0, k] = W[0, k]\n for p in range(1, renglon):\n Delta = W[p, k] - W[p - 1, k]\n WDelta = np.arctan2(np.sin(Delta), np.cos(Delta))\n phi[p, k] = phi[p - 1, k] + WDelta\n return phi\n\n def plot(self):\n unwraped = self.itoh_2D(self.VES(self._I0, self._I1, self._I2))\n unwraped_f = self.itoh_2D(self.VES(self._I0_f, self._I1_f, self._I2_f))\n phase = unwraped-unwraped_f\n xlim = phase[0, :].size\n ylim = phase[:, 0].size\n x = np.linspace(0, xlim, xlim)\n y = np.linspace(0, ylim, ylim)\n X, Y = np.meshgrid(x, y)\n '''l = 170\n p = np.polyfit(y, unwraped[:, l], 1)\n portadora = np.zeros(unwraped.shape)\n for n in range(0, x.size):\n portadora[:, n] = y * p[0] + p[1]\n phase = portadora - unwraped'''\n fig = plt.figure()\n ax = fig.add_subplot(121, projection='3d')\n ax.plot_surface(X, Y, phase, cmap='gray')\n ax = fig.add_subplot(122)\n plt.imshow(phase,cmap='gray')\n plt.grid()\n plt.show()\n","sub_path":"PSI/PSI_VES.py","file_name":"PSI_VES.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"377857273","text":"\"\"\"\r\nDefinition of ListNode\r\nclass ListNode(object):\r\n\r\n def __init__(self, val, next=None):\r\n self.val = val\r\n self.next = next\r\n\"\"\"\r\nclass Solution:\r\n \"\"\"\r\n @param hashTable: A list of The first node of linked list\r\n @return: A list of The first node of linked list which have twice size\r\n \"\"\"\r\n def rehashing(self, hashTable):\r\n if hashTable == []:\r\n return []\r\n \r\n length = len(hashTable)\r\n new_hashTable = [None] * (length * 2)\r\n for head in hashTable:\r\n while head:\r\n id = self.hashcode(head.val, length * 2)\r\n node = new_hashTable[id]\r\n if node is None:\r\n new_hashTable[id] = ListNode(head.val)\r\n else:\r\n while node.next:\r\n node = node.next\r\n node.next = ListNode(head.val)\r\n head = head.next\r\n return new_hashTable\r\n\r\n def hashcode(self, key, capacity):\r\n return key % capacity","sub_path":"src/Rehashing.py","file_name":"Rehashing.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"528252298","text":"# ===========================\n# -*- coding:utf-8 -*-\n# Time :2021/1/19 14:47\n# Author :A0025-江苏-小丹\n# QQ:915155536\n# File :demo1.py\n# ===========================\nfrom appium import webdriver\nimport time\n\n# 配置信息\n# info = {\n# \"platformName\": \"Android\", # 平台名\n# \"platformVersion\": \"7.1.2\", # 平台版本号\n# \"deviceName\": \"127.0.0.1:62001\", # 设备名\n# \"appPackage\": \"com.android.settings\", # 包名\n# \"appActivity\": \"com.android.settings.Settings\", # 应用名\n# \"noRest\": False # 不允许重置\n# }\n\ninfo = {\n \"platformName\": \"Android\",\n \"platformVersion\": \"5.1.1\",\n \"deviceName\": \"192.168.200.187:5555\",\n \"appPackage\": \"com.hongsen.outdoor\",\n \"appActivity\": \"com.hongsen.outdoor.activity.MainActivity\",\n \"noRest\": False\n}\n\ndriver=webdriver.Remote('http://127.0.0.1:4723/wd/hub',info)\ndriver.find_element_by_id('com.hongsen.outdoor:id/tv_exit').click()\ntime.sleep(2)\ndriver.find_element_by_id('com.hongsen.outdoor:id/p_img_13').click()\ntime.sleep(2)\ndriver.find_element_by_id('com.hongsen.outdoor:id/tv_jq_dl').click()\n","sub_path":"sss/app/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"100054818","text":"\n\"\"\" Selection sort algorithm \"\"\"\ndef selection_sort(lst):\n cmp_count = 0\n mov_count = 0\n for i in range(len(lst) - 1):\n # Find the smallest item in the lst starting at i\n min_index = i\n for j in range(min_index + 1, len(lst)):\n if lst[j] < lst[min_index]:\n min_index = j\n cmp_count += 1\n # place smallest at the beginning (swap min index with i)\n if min_index != i: # no 'comparison' here (doesn't involve access to a list)\n lst[i], lst[min_index] = lst[min_index], lst[i]\n mov_count += 3 # indeed did a swap\n return (cmp_count, mov_count)\n\n","sub_path":"year2_1819/computer_programming_3_algorithms_data_structures/2019_01_26_16_02_32_255813_organised/w8_quadratic_sorting_algorithms/selection_sort_stats_v2.py","file_name":"selection_sort_stats_v2.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"201488191","text":"def prime(num):\n i = 2\n while(i < num):\n if num%i == 0:\n return False\n i+=1\n return(True)\n\nnum = input()\nnum = num.split()\nnum1 = int(num[0])\nnum2 = int(num[1])\ncount = 0\nwhile(num1<=num2):\n if(prime(num1)):\n count+=1\n num1+=1\nprint(count)\n","sub_path":"count_prime.py","file_name":"count_prime.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"588527846","text":"import json\nimport logging\nimport os\nimport threading\nimport time\nimport typing\n\nfrom game import db\n\nDEBRIEFING_LOG_EXTENSION = \"log\"\n\nclass DebriefingDeadUnitInfo:\n country_id = -1\n player_unit = False\n type = None\n\n def __init__(self, country_id, player_unit , type):\n self.country_id = country_id\n self.player_unit = player_unit\n self.type = type\n\n def __repr__(self):\n return str(self.country_id) + \" \" + str(self.player_unit) + \" \" + str(self.type)\n\nclass Debriefing:\n def __init__(self, state_data, game):\n self.base_capture_events = state_data[\"base_capture_events\"]\n self.killed_aircrafts = state_data[\"killed_aircrafts\"]\n self.killed_ground_units = state_data[\"killed_ground_units\"]\n self.weapons_fired = state_data[\"weapons_fired\"]\n self.mission_ended = state_data[\"mission_ended\"]\n self.destroyed_units = state_data[\"destroyed_objects_positions\"]\n\n self.__destroyed_units = []\n logging.info(\"--------------------------------\")\n logging.info(\"Starting Debriefing preprocessing\")\n logging.info(\"--------------------------------\")\n logging.info(self.base_capture_events)\n logging.info(self.killed_aircrafts)\n logging.info(self.killed_ground_units)\n logging.info(self.weapons_fired)\n logging.info(self.mission_ended)\n logging.info(self.destroyed_units)\n logging.info(\"--------------------------------\")\n\n self.player_country_id = db.country_id_from_name(game.player_country)\n self.enemy_country_id = db.country_id_from_name(game.enemy_country)\n\n self.dead_aircraft = []\n self.dead_units = []\n self.dead_aaa_groups = []\n self.dead_buildings = []\n\n for aircraft in self.killed_aircrafts:\n try:\n country = int(aircraft.split(\"|\")[1])\n type = db.unit_type_from_name(aircraft.split(\"|\")[4])\n player_unit = (country == self.player_country_id)\n aircraft = DebriefingDeadUnitInfo(country, player_unit, type)\n if type is not None:\n self.dead_aircraft.append(aircraft)\n except Exception as e:\n logging.error(e)\n\n for unit in self.killed_ground_units:\n try:\n country = int(unit.split(\"|\")[1])\n type = db.unit_type_from_name(unit.split(\"|\")[4])\n player_unit = (country == self.player_country_id)\n unit = DebriefingDeadUnitInfo(country, player_unit, type)\n if type is not None:\n self.dead_units.append(unit)\n except Exception as e:\n logging.error(e)\n\n for unit in self.killed_ground_units:\n for cp in game.theater.controlpoints:\n\n logging.info(cp.name)\n logging.info(cp.captured)\n\n if cp.captured:\n country = self.player_country_id\n else:\n country = self.enemy_country_id\n player_unit = (country == self.player_country_id)\n\n for i, ground_object in enumerate(cp.ground_objects):\n logging.info(unit)\n logging.info(ground_object.string_identifier)\n if ground_object.matches_string_identifier(unit):\n unit = DebriefingDeadUnitInfo(country, player_unit, ground_object.dcs_identifier)\n self.dead_buildings.append(unit)\n elif ground_object.dcs_identifier in [\"AA\", \"CARRIER\", \"LHA\"]:\n for g in ground_object.groups:\n for u in g.units:\n if u.name == unit:\n unit = DebriefingDeadUnitInfo(country, player_unit, db.unit_type_from_name(u.type))\n self.dead_units.append(unit)\n\n self.player_dead_aircraft = [a for a in self.dead_aircraft if a.country_id == self.player_country_id]\n self.enemy_dead_aircraft = [a for a in self.dead_aircraft if a.country_id == self.enemy_country_id]\n self.player_dead_units = [a for a in self.dead_units if a.country_id == self.player_country_id]\n self.enemy_dead_units = [a for a in self.dead_units if a.country_id == self.enemy_country_id]\n self.player_dead_buildings = [a for a in self.dead_buildings if a.country_id == self.player_country_id]\n self.enemy_dead_buildings = [a for a in self.dead_buildings if a.country_id == self.enemy_country_id]\n\n logging.info(self.player_dead_aircraft)\n logging.info(self.enemy_dead_aircraft)\n logging.info(self.player_dead_units)\n logging.info(self.enemy_dead_units)\n\n self.player_dead_aircraft_dict = {}\n for a in self.player_dead_aircraft:\n if a.type in self.player_dead_aircraft_dict.keys():\n self.player_dead_aircraft_dict[a.type] = self.player_dead_aircraft_dict[a.type] + 1\n else:\n self.player_dead_aircraft_dict[a.type] = 1\n\n self.enemy_dead_aircraft_dict = {}\n for a in self.enemy_dead_aircraft:\n if a.type in self.enemy_dead_aircraft_dict.keys():\n self.enemy_dead_aircraft_dict[a.type] = self.enemy_dead_aircraft_dict[a.type] + 1\n else:\n self.enemy_dead_aircraft_dict[a.type] = 1\n\n self.player_dead_units_dict = {}\n for a in self.player_dead_units:\n if a.type in self.player_dead_units_dict.keys():\n self.player_dead_units_dict[a.type] = self.player_dead_units_dict[a.type] + 1\n else:\n self.player_dead_units_dict[a.type] = 1\n\n self.enemy_dead_units_dict = {}\n for a in self.enemy_dead_units:\n if a.type in self.enemy_dead_units_dict.keys():\n self.enemy_dead_units_dict[a.type] = self.enemy_dead_units_dict[a.type] + 1\n else:\n self.enemy_dead_units_dict[a.type] = 1\n\n self.player_dead_buildings_dict = {}\n for a in self.player_dead_buildings:\n if a.type in self.player_dead_buildings_dict.keys():\n self.player_dead_buildings_dict[a.type] = self.player_dead_buildings_dict[a.type] + 1\n else:\n self.player_dead_buildings_dict[a.type] = 1\n\n self.enemy_dead_buildings_dict = {}\n for a in self.enemy_dead_buildings:\n if a.type in self.enemy_dead_buildings_dict.keys():\n self.enemy_dead_buildings_dict[a.type] = self.enemy_dead_buildings_dict[a.type] + 1\n else:\n self.enemy_dead_buildings_dict[a.type] = 1\n\n logging.info(\"--------------------------------\")\n logging.info(\"Debriefing pre process results :\")\n logging.info(\"--------------------------------\")\n logging.info(self.player_dead_aircraft_dict)\n logging.info(self.enemy_dead_aircraft_dict)\n logging.info(self.player_dead_units_dict)\n logging.info(self.enemy_dead_units_dict)\n logging.info(self.player_dead_buildings_dict)\n logging.info(self.enemy_dead_buildings_dict)\n\n\nclass PollDebriefingFileThread(threading.Thread):\n \"\"\"Thread class with a stop() method. The thread itself has to check\n regularly for the stopped() condition.\"\"\"\n\n def __init__(self, callback: typing.Callable, game):\n super(PollDebriefingFileThread, self).__init__()\n self._stop_event = threading.Event()\n self.callback = callback\n self.game = game\n\n def stop(self):\n self._stop_event.set()\n\n def stopped(self):\n return self._stop_event.is_set()\n\n def run(self):\n if os.path.isfile(\"state.json\"):\n last_modified = os.path.getmtime(\"state.json\")\n else:\n last_modified = 0\n while not self.stopped():\n if os.path.isfile(\"state.json\") and os.path.getmtime(\"state.json\") > last_modified:\n with open(\"state.json\", \"r\") as json_file:\n json_data = json.load(json_file)\n debriefing = Debriefing(json_data, self.game)\n self.callback(debriefing)\n break\n time.sleep(5)\n\n\ndef wait_for_debriefing(callback: typing.Callable, game)->PollDebriefingFileThread:\n thread = PollDebriefingFileThread(callback, game)\n thread.start()\n return thread\n\n","sub_path":"userdata/debriefing.py","file_name":"debriefing.py","file_ext":"py","file_size_in_byte":8465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"556887318","text":"from __future__ import division, absolute_import, print_function\n\nimport os\nimport os.path\nimport sys\nimport json\nimport pickle\nimport pandas as pd\nimport random\nimport threading\nimport time\nfrom flask import Flask, request, jsonify, send_from_directory, send_file, \\\n render_template, redirect, url_for, abort\nfrom tinyrecord import transaction\nfrom functools import wraps\n\nfrom . import stats, casting, utils\n\nfrom io import BytesIO\ntry:\n from io import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\napp = Flask(__name__)\nos.makedirs('db', exist_ok=True)\n\nwith open('sec_token.txt', 'rt') as f:\n SECURITY_TOKEN = f.readline().strip()\n\ntestpage_mutex = threading.Lock()\n\ncsv_database = 'database_mixed.csv'\npage_groups = [['idx_760_800.yaml',\n 'idx_680_720.yaml',\n 'idx_800_840.yaml',\n 'idx_720_760.yaml',\n 'idx_600_640.yaml',\n 'idx_40_80.yaml',\n 'idx_320_360.yaml'],\n ['idx_400_440.yaml',\n 'idx_480_520.yaml',\n 'idx_560_600.yaml',\n 'idx_0_40.yaml',\n 'idx_80_120.yaml',\n 'idx_520_560.yaml',\n 'idx_360_400.yaml'],\n ['idx_640_680.yaml',\n 'idx_440_480.yaml',\n 'idx_240_280.yaml',\n 'idx_160_200.yaml',\n 'idx_120_160.yaml',\n 'idx_200_240.yaml',\n 'idx_280_320.yaml']]\n\nip_group_map = {\n '138.37.90.152': 2,\n '66.249.66.50': 2,\n '82.13.188.176': 1,\n '10.100.0.3': 0,\n}\n\n# For testing\nip_group_map = {\n '138.37.90.152': 2,\n '66.249.66.50': 2,\n '127.0.0.1': 2,\n '82.13.188.176': 1,\n '10.100.0.3': 0,\n}\n\ndisjoint_pages = [\n 'idx_760_800.yaml',\n 'idx_680_720.yaml',\n 'idx_800_840.yaml',\n 'idx_720_760.yaml',\n 'idx_600_640.yaml',\n 'idx_40_80.yaml',\n 'idx_320_360.yaml',\n 'idx_400_440.yaml',\n 'idx_480_520.yaml',\n 'idx_560_600.yaml',\n 'idx_0_40.yaml',\n 'idx_80_120.yaml',\n 'idx_520_560.yaml',\n 'idx_360_400.yaml',\n 'idx_640_680.yaml',\n 'idx_440_480.yaml',\n 'idx_240_280.yaml',\n 'idx_160_200.yaml',\n 'idx_120_160.yaml',\n 'idx_200_240.yaml',\n 'idx_280_320.yaml'\n]\n\ndef get_user_ip():\n headers_list = request.headers.getlist(\"X-Forwarded-For\")\n user_ip = headers_list[0] if headers_list else request.remote_addr\n return user_ip\n\ndef only_admin_allowlist(f):\n @wraps(f)\n def wrapped(*args, **kwargs):\n if get_user_ip() in app.config['admin_allowlist']:\n return f(*args, **kwargs)\n else:\n return abort(403)\n return wrapped\n\ndef admin_or_token_allow(f):\n @wraps(f)\n def wrapped(*args, **kwargs):\n if get_user_ip() in app.config['admin_allowlist']:\n return f(*args, **kwargs)\n elif request.args.get('token', None) == SECURITY_TOKEN:\n return f(*args, **kwargs)\n else:\n # disable this for now\n #return abort(403)\n return f(*args, **kwargs)\n\n return wrapped\n\n\ndef get_seen_yaml_files(csv_database):\n if csv_database in os.listdir():\n df_og = pd.read_csv(csv_database)\n seen_files = list(df_og['configs'].unique())\n else: seen_files = []\n return seen_files\n\ndef select_unique_yaml_files():\n all_files = os.listdir(f'pymushra/pymushra/static/yamls/pages')\n\n #get seen files and remove them off the the list off all files\n seen_files = get_seen_yaml_files(csv_database)\n\n for file in seen_files:\n if file in all_files:\n all_files.remove(file)\n\n return all_files, seen_files\n\ndef pagemap_op(func):\n pagemap = {}\n with testpage_mutex:\n pagemap_path = 'pagemap.pickle'\n if os.path.isfile(pagemap_path):\n with open(pagemap_path, 'rb') as f:\n pagemap = pickle.load(f)\n \n pagemap_new = func(pagemap)\n with open(pagemap_path, 'wb') as f:\n pickle.dump(pagemap_new, f)\n \n return pagemap_new\n\n@app.route('/')\n#@app.route('/')\n@admin_or_token_allow\ndef home():\n user_ip = get_user_ip()\n \n def select_page(pagemap):\n if user_ip in pagemap:\n return pagemap\n \n all_conf_files, all_seen_files = select_unique_yaml_files()\n # no pagemap locking for now\n untaken_pages = all_conf_files # [p for p in all_conf_files if p not in pagemap.values()]\n \n untaken_disjoint_pages = [p for p in untaken_pages if p in disjoint_pages]\n untaken_extra_pages = [p for p in untaken_pages if p not in disjoint_pages]\n random.shuffle(untaken_disjoint_pages)\n random.shuffle(untaken_extra_pages)\n\n selected_page = (untaken_disjoint_pages + untaken_extra_pages)[0]\n pagemap[user_ip] = selected_page\n return pagemap\n\n pagemap = pagemap_op(select_page)\n conf_file = pagemap.get(user_ip, None)\n \n if conf_file is None:\n return render_template('finished.html', seen_files=all_seen_files)\n else:\n conf_file_path = f'static/yamls/pages/{conf_file}'\n return render_template('index.html', conf_file_path=conf_file_path)\n \n# try:\n# page_group = page_groups[ip_group_map[user_ip]]\n# page_group = [p for p in page_group if p not in all_seen_files]\n\n# if len(page_group) == 0:\n# return render_template('finished.html', seen_files=all_seen_files) \n\n# # select a random config file which has not yet been done so far \n# conf_file = page_group[random.randint(0, len(page_group)-1)]\n# print(conf_file, file=sys.stderr)\n# conf_file_path = f'static/yamls/pages/{conf_file}'\n# return render_template(url, conf_file_path=conf_file_path)\n \n# except KeyError:\n# return abort(403)\n\n@app.route('/test')\ndef test_page():\n conf_file_path = 'static/yamls/test.yaml'\n return render_template('index.html', conf_file_path=conf_file_path)\n\n\n@app.route('/finished')\n@only_admin_allowlist\ndef finishedExperiments():\n left_files, done_files = select_unique_yaml_files()\n return render_template('finished.html', left_files=left_files, done_files=done_files)\n\n@app.route('/results')\n#@only_admin_allowlist\ndef results():\n try:\n df_html = pd.read_csv(csv_database).to_html()\n return render_template('results.html', df_html=df_html)\n except:\n return abort(403)\n \n\n@app.route('/service/write.php', methods=['POST'])\n@app.route('//collect', methods=['POST'])\n@app.route('/collect', methods=['POST'])\ndef collect(testid=''):\n if request.headers['Content-Type'].startswith(\n 'application/x-www-form-urlencoded'\n ):\n try:\n db = app.config['db']\n payload = json.loads(request.form['sessionJSON'])\n payload = casting.cast_recursively(payload)\n\n\n insert = casting.json_to_dict(payload)\n\n user_ip = get_user_ip()\n #add db here\n\n columns = [k for k in payload['trials'][0]['responses'][0].keys()] + ['ip']\n #contains attributes - ['name', 'email', 'age', 'gender', 'subject_eval_ever']\n for i in payload['participant']['name']:\n columns.append(i)\n participant_metadata = payload['participant']['response']\n\n columns.append('uuid')\n columns.append('configs')\n \n uuid = payload['trials'][0]['questionaire']['uuid']\n config = payload['config'].split('/')[-1]\n if config == 'test.yaml': \n return jsonify({\n 'error': False,\n })\n uuids = []\n ips = []\n left_image = []\n right_image = []\n preferred_image = []\n snrs = []\n time = []\n configs = []\n # participant metadata\n name = []\n email = []\n age = []\n gender = []\n subjective_eval_ever = []\n\n for i in range(len(payload['trials'][0]['responses'])):\n # uuids.append(uuid)\n # ips.append(user_ip)\n configs.append(config)\n # name.append(participant_metadata[0])\n # email.append(participant_metadata[1])\n # age.append(participant_metadata[2])\n # gender.append(participant_metadata[3])\n # subjective_eval_ever.append(participant_metadata[4])\n left_image.append(\n payload['trials'][0]['responses'][i]['left_image'])\n right_image.append(\n payload['trials'][0]['responses'][i]['right_image'])\n preferred_image.append(\n payload['trials'][0]['responses'][i]['preferred_image'])\n time.append(\n payload['trials'][0]['responses'][i]['time'])\n\n df = pd.DataFrame(columns=columns)\n df['left_image'] = pd.Series(left_image)\n df['right_image'] = pd.Series(right_image)\n df['preferred_image'] = pd.Series(preferred_image)\n df['uuid'] = pd.Series(uuids)\n df['ip'] = pd.Series(ips)\n df['time'] = pd.Series(time)\n df['configs'] = pd.Series(configs)\n df['name'] = pd.Series(name)\n df['email'] = pd.Series(email)\n df['age'] = pd.Series(age)\n df['gender'] = pd.Series(gender)\n df['subjective_eval_ever'] = pd.Series(subjective_eval_ever)\n\n\n \n def update_everything_and_pagemap(pagemap):\n\n if csv_database in os.listdir():\n df_og = pd.read_csv(csv_database, index_col=False)\n df_og = df_og.append(df)\n df_og.to_csv(csv_database, index=False)\n else: df.to_csv(csv_database, index=False)\n\n collection = db.table(payload['trials'][0]['testId'])\n with transaction(collection):\n inserted_ids = collection.insert_multiple(insert)\n \n pagemap.pop(user_ip)\n return pagemap\n \n pagemap_op(update_everything_and_pagemap)\n \n return jsonify({\n 'error': False,\n 'message': \"Response saved successfully\"\n })\n except Exception as e:\n return jsonify({\n 'error': True,\n 'message': \"An error occurred: %s\" % str(e)\n })\n else:\n return \"415 Unsupported Media Type\", 415\n\n\n@app.route('/admin/')\n@app.route('/admin/list')\n@only_admin_allowlist\ndef admin_list():\n\n db = app.config['db']\n collection_names = db.tables()\n\n collection_dfs = [\n casting.collection_to_df(db.table(name)) for name in collection_names\n ]\n\n # print(collection_dfs)\n\n collections = [\n {\n 'id': name,\n 'participants': len(df['questionaire', 'uuid'].unique()),\n 'last_submission': df['wm', 'date'].max(),\n } for name, df in zip(collection_names, collection_dfs)\n if len(df) > 0\n ]\n\n# configs = utils.get_configs(\n# os.path.join(app.config['webmushra_dir'], \"configs\")\n# )\n\n return render_template(\n \"admin/list.html\",\n collections=collections,\n # configs=configs\n )\n\n\n@app.route('/admin/delete/')\n@only_admin_allowlist\ndef admin_delete(testid):\n collection = app.config['db'].table(testid)\n collection.drop()\n\n return redirect(url_for('admin_list'))\n\n\n@app.route('/admin/info//')\n@only_admin_allowlist\ndef admin_info(testid):\n collection = app.config['db'].table(testid)\n df = casting.collection_to_df(collection)\n try:\n configs = df['wm']['config'].unique().tolist()\n except KeyError:\n configs = []\n\n configs = map(os.path.basename, configs)\n\n return render_template(\n \"admin/info.html\",\n testId=testid,\n configs=configs\n )\n\n\n@app.route('/admin/latest//')\n@only_admin_allowlist\ndef admin_latest(testid):\n collection = app.config['db'].table(testid)\n latest = sorted(collection.all(), key=lambda x: x['date'], reverse=True)[0]\n return json.dumps(latest)\n\n\n@app.route('/admin/stats//')\n@only_admin_allowlist\ndef admin_stats(testid, stats_type='mushra'):\n collection = app.config['db'].table(testid)\n df = casting.collection_to_df(collection)\n df.columns = utils.flatten_columns(df.columns)\n # analyse mushra experiment\n try:\n if stats_type == \"mushra\":\n return stats.render_mushra(testid, df)\n except ValueError as e:\n return render_template(\n 'error/error.html', type=\"Value\", message=str(e)\n )\n return render_template('error/404.html'), 404\n\n\n@app.route(\n '/admin/download/.',\n defaults={'show_as': 'download'})\n@app.route(\n '/admin/download//.',\n defaults={'show_as': 'download'})\n@app.route(\n '/download//.',\n defaults={'show_as': 'download'})\n@app.route(\n '/download/.',\n defaults={'show_as': 'download'})\n@app.route(\n '/admin/show/.',\n defaults={'show_as': 'text'})\n@app.route(\n '/admin/show//.',\n defaults={'show_as': 'text'})\n#@only_admin_allowlist\ndef download(testid, show_as, statstype=None, filetype='csv'):\n allowed_types = ('csv', 'pickle', 'json', 'html')\n\n if show_as == 'download':\n as_attachment = True\n else:\n as_attachment = False\n\n if filetype not in allowed_types:\n return render_template(\n 'error/error.html',\n type=\"Value\",\n message=\"File type must be in %s\" % ','.join(allowed_types)\n )\n\n if filetype == \"pickle\" and not as_attachment:\n return render_template(\n 'error/error.html',\n type=\"Value\",\n message=\"Pickle data cannot be viewed\"\n )\n\n collection = app.config['db'].table(testid)\n df = casting.collection_to_df(collection)\n\n if statstype is not None:\n # subset by statstype\n df = df[df[('wm', 'type')] == statstype]\n\n # Merge hierarchical columns\n if filetype not in (\"pickle\", \"html\"):\n df.columns = utils.flatten_columns(df.columns.values)\n\n if len(df) == 0:\n return render_template(\n 'error/error.html',\n type=\"Value\",\n message=\"Data Frame was empty\"\n )\n\n if filetype == \"csv\":\n # We need to escape certain objects in the DF to prevent Segfaults\n mem = StringIO()\n casting.escape_objects(df).to_csv(\n mem,\n sep=\";\",\n index=False,\n encoding='utf-8'\n )\n\n elif filetype == \"html\":\n mem = StringIO()\n df.sort_index(axis=1).to_html(mem, classes=\"table table-striped\")\n\n elif filetype == \"pickle\":\n mem = BytesIO()\n pickle.dump(df, mem)\n\n elif filetype == \"json\":\n mem = StringIO()\n # We need to escape certain objects in the DF to prevent Segfaults\n casting.escape_objects(df).to_json(mem, orient='records')\n\n mem.seek(0)\n\n if (as_attachment or filetype != \"html\") and not isinstance(mem, BytesIO):\n mem2 = BytesIO()\n mem2.write(mem.getvalue().encode('utf-8'))\n mem2.seek(0)\n mem = mem2\n\n if as_attachment:\n return send_file(\n mem,\n attachment_filename=\"%s.%s\" % (testid, filetype),\n as_attachment=True,\n cache_timeout=-1\n )\n else:\n if filetype == \"html\":\n return render_template('admin/table.html', table=mem.getvalue())\n else:\n return send_file(\n mem,\n mimetype=\"text/plain\",\n cache_timeout=-1\n )\n\n\n@app.context_processor\ndef utility_processor():\n def significance_stars(p, alpha=0.05):\n return ''.join(\n [\n ''\n ] * stats.significance_class(p, alpha)\n )\n\n return dict(significance_stars=significance_stars)\n\n\n@app.template_filter('datetime')\ndef datetime_filter(value, format='%x %X'):\n return value.strftime(format)\n","sub_path":"Subjective-Evaluation-Images/pymushra/pymushra/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":16176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"284987471","text":"# -*- coding: utf-8 -*-\n\nimport smbus\nimport math\nfrom time import sleep\nimport flag\n\nDEV_ADDR = 0x68\n\nACCEL_XOUT = 0x3b\nACCEL_YOUT = 0x3d\nACCEL_ZOUT = 0x3f\nTEMP_OUT = 0x41\nGYRO_XOUT = 0x43\nGYRO_YOUT = 0x45\nGYRO_ZOUT = 0x47\n\nPWR_MGMT_1 = 0x6b\nPWR_MGMT_2 = 0x6c \n\nbus = smbus.SMBus(1)\nbus.write_byte_data(DEV_ADDR, PWR_MGMT_1, 0)\n\n\ndef read_word(adr):\n high = bus.read_byte_data(DEV_ADDR, adr)\n low = bus.read_byte_data(DEV_ADDR, adr+1)\n val = (high << 8) + low\n return val\n\n# Sensor data read\ndef read_word_sensor(adr):\n val = read_word(adr)\n if (val >= 0x8000): # minus\n return -((65535 - val) + 1)\n else: # plus\n return val\n\n\ndef get_temp():\n temp = read_word_sensor(TEMP_OUT)\n x = temp / 340 + 36.53 # data sheet(register map)記載の計算式.\n return x\n\n\ndef getGyro():\n x = read_word_sensor(GYRO_XOUT)/ 131.0\n y = read_word_sensor(GYRO_YOUT)/ 131.0\n z = read_word_sensor(GYRO_ZOUT)/ 131.0\n return [x, y, z]\n\n\ndef getAccel():\n x = read_word_sensor(ACCEL_XOUT)/ 16384.0\n y= read_word_sensor(ACCEL_YOUT)/ 16384.0\n z= read_word_sensor(ACCEL_ZOUT)/ 16384.0\n return [x, y, z]\n\n\nwhile 1:\n ax, ay, az = getAccel()\n gx, gy, gz = getGyro()\n if ax==0:\n ax=0.000001\n if ay==0:\n ay=0.000001\n if az==0:\n az=0.000001\n \n pitch=flag.flag_get(ax,ay,az)\n\n #print ('{0:4.3f}, {1:4.3f}, {2:4.3f}, {3:4.3f}, {4:4.3f}, {5:4.3f},' .format(gx, gy, gz, ax, ay, az))\n roll = math.atan(ay/az) * 57.324\n\n print('{0:4.3f}, x{1:4.3f}, y{2:4.3f}'.format(pitch, ax,ay))\n\n\n\n","sub_path":"gyro/gyro.py","file_name":"gyro.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"567488762","text":"#!/usr/bin/env python\n# coding: utf-8\n#@author: Devanathan N G\n\n# In[2]:\n\n\n# Import the modules\nimport cv2\nfrom sklearn.externals import joblib\nfrom skimage.feature import hog\nimport numpy as np\n\n\n# In[3]:\n\n\n# Load the classifier\nclf, pp = joblib.load(\"C:/Users/Raghav N G/Downloads/handwritten-MNIST-digit-recognition-master/digits_cls1.pkl\")\n\n\n# In[6]:\n\n\ndef main(): \n # Open Camera\n cap = cv2.VideoCapture(0)\n\n while (cap.isOpened()):\n # Capture frames from the camera\n ret, img = cap.read()\n # Apply get_img_contour_thresh function on frame\n img, contours, thresh = get_img_contour_thresh(img)\n \n ans = ''\n \n if len(contours) > 0:\n for ctr in contours:\n # Ranging contourArea\n if cv2.contourArea(ctr) > 1500 and cv2.contourArea(ctr)<5000 :\n # Get rectangles contains each contour i.e. digit\n rect = cv2.boundingRect(ctr)\n # Dimensions of rectangle\n x, y, w, h = rect\n \n # Making new image containing coutour for classification\n newImage = thresh[y:y + h, x:x + w]\n # Resize the image\n newImage = cv2.resize(newImage, (28, 28))\n # Calculate the HOG features\n newImage = np.array(newImage)\n hog_ft = hog(newImage, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False)\n # Perform classification\n hog_ft = pp.transform(np.array([hog_ft], 'float64'))\n ans = clf.predict(hog_ft)\n # Make the rectangular region around the digit and texting classified digit\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 4)\n cv2.putText(img, str(int(ans[0])), (x, y),cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 255), 3)\n \n #Showing frame and threshold\n cv2.imshow(\"Frame\", img)\n cv2.imshow(\"Contours\", thresh)\n k = cv2.waitKey(10)\n if k == 30:\n break\n \ndef get_img_contour_thresh(img):\n \n # Change color-space from BGR -> Gray\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # Apply Gaussian Blur and Threshold\n blur = cv2.GaussianBlur(gray, (5, 5), 0)\n ret, thresh = cv2.threshold(blur, 70, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n \n # Find contours\n _ , contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n return img, contours, thresh\n\n\n\n# In[ ]:\n\n\nmain()\n\n\n\n\n","sub_path":"Model/multidig_rec_vid.py","file_name":"multidig_rec_vid.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"151530988","text":"#!/usr/bin/env python-2.4.3\n#\n# September 2010, Benjamin Gaidioz \n#\n# Copyright (c) 2010 by cisco Systems, Inc.\n# All rights reserved.\n#\nimport os, sys\nos.environ['PY_XRUT_ROOT'] = os.path.dirname(os.path.dirname(os.path.abspath(sys.path[0])))\nsys.path[1:1] = [os.environ.get('PY_XRUT_ROOT') + '/modules']\nfrom utng import test_suite_t\nfrom xrut import ng_topology_t, routers\nfrom re import compile\nfrom time import sleep\nimport pdb\nfrom pre import predicate_t, prerequisite_t\n\ntopology = ng_topology_t({ '1': (\"one\", \"two\"),\n '2': (\"one\", \"two\"),\n '3': (\"one\", \"two\")},\n {\"one\":{\"multinode\":True}})\n\ntopology.add_extra_loopback(1)\n\none = routers[\"one\"]\ntwo = routers[\"two\"]\n\nclass pw_state(predicate_t):\n reg = compile(\"Group.*state is ([a-z]+)\")\n def __init__(self, router, neighbor, status):\n self._n = str(neighbor)\n self._r = router\n self._s = status\n self._error = None\n def test(self):\n show = self._r.send_command(\"show l2vpn xconnect neighbor %s detail\" % self._n)\n m = self.reg.search(show)\n if m.group(1) != self._s:\n self._error = \"XC neighbor %s is %s on %s\" % (self._n, self._s,\n self._r)\n return False\n else:\n return True\n\n def __str__(self):\n if self._error:\n return self._error\n else:\n return \"XC neighbor %s is %s on %s\" % (self._n, self._s, self._r)\n\nclass CSCtj72989 (test_suite_t):\n \"\"\"Test for CSCtj72989 (case requiring PWHE)\"\"\"\n one = routers[\"one\"]\n two = routers[\"two\"]\n required_config = {\"all-iox\":\n \"\"\"\nrouter ospf 1\n nsr\n retransmit-interval 10\n hello-interval 10\n nsf cisco\n area 1\n interface ${self.interfaces['Loopback0']}\n interface ${self.interfaces['Loopback1']}\n interface ${self.netifs['1']}\n !\n !\n!\n\n \"\"\",\n \"one\" : \"\"\"\ninterface PW-Ether1\n attach generic-interface-list ifl1\n!\ninterface PW-Ether2\n attach generic-interface-list ifl1\n!\nl2vpn\n xconnect group xg1\n p2p p1\n interface PW-Ether1\n neighbor ${routers[\"two\"].interfaces['Loopback0'].ipv4_prefix.address} pw-id 2\n !\n !\n p2p p2\n interface PW-Ether2\n neighbor ${routers[\"two\"].interfaces['Loopback1'].ipv4_prefix.address} pw-id 3\n !\n !\n !\n!\ngeneric-interface-list ifl1\n interface ${self.netifs['1']}\n!\nmpls ldp\n router-id ${self.interfaces['Loopback0'].ipv4_prefix.address}\n discovery targeted-hello accept\n interface ${self.netifs['1']}\n !\n!\n \"\"\",\n \"two\": \"\"\"\ninterface ${self.netifs['2']}\n no ipv4 address\n no ipv6 address\n l2transport\n !\n!\ninterface ${self.netifs['3']}\n no ipv4 address\n no ipv6 address\n l2transport\n !\n!\nl2vpn\n xconnect group xg1\n p2p p1\n interface ${self.netifs['2']}\n neighbor ${routers[\"one\"].interfaces['Loopback0'].ipv4_prefix.address} pw-id 2\n !\n !\n p2p p2\n interface ${self.netifs['3']}\n neighbor ${routers[\"one\"].interfaces['Loopback1'].ipv4_prefix.address} pw-id 3\n !\n !\n !\n!\nmpls ldp\n router-id ${self.interfaces['Loopback0'].ipv4_prefix.address}\n discovery targeted-hello accept\n interface ${self.netifs['1']}\n !\n!\n \"\"\"\n }\n\n def test_001_pws_are_up(self):\n \"\"\"check PWs are up on one and two\"\"\"\n prerequisite_t([\n pw_state(one, two.interfaces[\"Loopback0\"].ipv4_prefix.address, 'up'),\n pw_state(one, two.interfaces[\"Loopback1\"].ipv4_prefix.address, 'up'),\n pw_state(two, one.interfaces[\"Loopback0\"].ipv4_prefix.address, 'up'),\n pw_state(two, one.interfaces[\"Loopback1\"].ipv4_prefix.address, 'up')\n ],\n waittime=60, checktime=10).assert_test_case()\n\n def test_002_remove_l2vpn_config(self):\n one.config_verify(\"no l2vpn\")\n two.config_verify(\"no l2vpn\")\n\n def test_003_rollback_and_pws_are_up(self):\n one.send_command(\"rollback config last 1\")\n two.send_command(\"rollback config last 1\")\n prerequisite_t([\n pw_state(one, two.interfaces[\"Loopback0\"].ipv4_prefix.address, 'up'),\n pw_state(one, two.interfaces[\"Loopback1\"].ipv4_prefix.address, 'up'),\n pw_state(two, one.interfaces[\"Loopback0\"].ipv4_prefix.address, 'up'),\n pw_state(two, one.interfaces[\"Loopback1\"].ipv4_prefix.address, 'up')\n ],\n waittime=60, checktime=10).assert_test_case()\n\n def test_004_switch_ac_down_on_two(self):\n two.config_verify([\n \"interface ${self.netifs['2']} shutdown\",\n \"interface ${self.netifs['3']} shutdown\"\n ])\n\n def test_005_pws_are_down(self):\n prerequisite_t([\n pw_state(one, two.interfaces[\"Loopback0\"].ipv4_prefix.address, 'down'),\n pw_state(one, two.interfaces[\"Loopback1\"].ipv4_prefix.address, 'down'),\n pw_state(two, one.interfaces[\"Loopback0\"].ipv4_prefix.address, 'down'),\n pw_state(two, one.interfaces[\"Loopback1\"].ipv4_prefix.address, 'down')\n ],\n waittime=60, checktime=10).assert_test_case()\n\n def test_006_restart_l2vpn_mgr_on_one(self):\n one.send_command(\"proc restart l2vpn_mgr\")\n sleep(20)\n\n def test_007_pws_are_down(self):\n prerequisite_t([\n pw_state(one, two.interfaces[\"Loopback0\"].ipv4_prefix.address, 'down'),\n pw_state(one, two.interfaces[\"Loopback1\"].ipv4_prefix.address, 'down'),\n pw_state(two, one.interfaces[\"Loopback0\"].ipv4_prefix.address, 'down'),\n pw_state(two, one.interfaces[\"Loopback1\"].ipv4_prefix.address, 'down')\n ],\n waittime=60, checktime=10).assert_test_case()\n\nif __name__ == \"__main__\":\n rc = topology.execute_test(CSCtj72989())\nsys.exit(rc)\n","sub_path":"X-COPY/infra/test/xrut/l2vpn/ddts/CSCtj72989.py","file_name":"CSCtj72989.py","file_ext":"py","file_size_in_byte":5718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"559968465","text":"\n\nfrom xai.brain.wordbase.nouns._odour import _ODOUR\n\n#calss header\nclass _ODOURS(_ODOUR, ):\n\tdef __init__(self,): \n\t\t_ODOUR.__init__(self)\n\t\tself.name = \"ODOURS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"odour\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_odours.py","file_name":"_odours.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"106614591","text":"import sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef press(event):\n if event.key == 'q':\n plt.close(event.canvas.figure)\n sys.exit()\n\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1, aspect=\"equal\")\n\nfig.canvas.mpl_connect('key_press_event', press)\n\nviewAngle = np.pi / 4\npos = np.array([0, 2])\nimagePlaneDist = 0.5\n\nax.set_xlim(-3, 3)\nax.set_ylim(-0.1, 2.9)\n\n# Ground\ngroundLine = ax.plot([-3, 3], [0, 0])[0]\n\n\nimagePlaneIntersectionLine = ax.plot([], [], '.k')[0]\nimagePlaneLine = ax.plot([], [], '.-k')[0]\nleftViewLine = ax.plot([], [], '.-k')[0]\ncenterViewLine = ax.plot([], [], '--k')[0]\nrightViewLine = ax.plot([], [], '.-k')[0]\n\niterations = 250\npointOnImagePlanes = []\nangles = []\nfor i in np.cos(np.linspace(0, 10, iterations)):\n angle = np.pi * i/3\n rightIntersection = pos[1] * np.tan(angle + viewAngle/2) + pos[0]\n centerIntersection = pos[1] * np.tan(angle) + pos[0]\n leftIntersection = pos[1] * np.tan(angle - viewAngle/2) + pos[0]\n # Image plane normal\n n = np.array([centerIntersection, 0]) - pos\n n /= np.linalg.norm(n)\n # Image plane center\n p0 = n * imagePlaneDist + pos\n\n r = np.array([rightIntersection, 0]) - pos\n l = np.array([leftIntersection, 0]) - pos\n r /= np.linalg.norm(r)\n l /= np.linalg.norm(l)\n f = imagePlaneDist / np.cos(viewAngle/2)\n lI = l * f + pos\n rI = r * f + pos\n imagePlaneLine.set_data([lI[0], rI[0]], [lI[1], rI[1]])\n\n leftViewLine.set_data([pos[0], leftIntersection], [pos[1], 0])\n centerViewLine.set_data([pos[0], centerIntersection], [pos[1], 0])\n rightViewLine.set_data([pos[0], rightIntersection], [pos[1], 0])\n\n # Point on ground\n l0 = np.array([0.0, 0.0])\n # Line from point on ground to camera\n l = l0 - pos\n l /= np.linalg.norm(l)\n\n d = (p0 - l0).dot(n) / l.dot(n)\n imgInt = d * l + l0\n imagePlaneIntersectionLine.set_data(*imgInt)\n\n imgPlaneDir = rI - lI\n pointDir = rI - imgInt\n\n pointOnImagePlanes.append(2 * (pointDir[0] / imgPlaneDir[0] - 0.5))\n angles.append(angle * 180 / np.pi)\n plt.pause(0.001)\n\nplt.clf()\nplt.plot(angles, pointOnImagePlanes)\n# plt.plot([min(angles), max(angles)], [min(pointOnImagePlanes), max(pointOnImagePlanes)])\nplt.xlabel(\"Camera Angle\")\nplt.ylabel(\"Point's Position On Image Plane\")\nplt.show()\n\n","sub_path":"image_plane.py","file_name":"image_plane.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"303288341","text":"# Exercise 17.3. Write a str method for the Point class. Create a Point object and print it.\r\n\r\nimport math\r\n\r\nclass Point(object):\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def __str__(self):\r\n '''\r\n The __str__ method is useful for debugging. \r\n It allows you to pass a class object name\r\n to a standard print statement.\r\n '''\r\n return ('(%g, %g)' % (self.x, self.y))\r\n\r\n\r\ndef distance_between_points(a, b):\r\n _partOne = (b.y - a.y) ** 2\r\n _partTwo = (b.x - a.x) ** 2\r\n\r\n _dist = math.sqrt(_partOne + _partTwo)\r\n\r\n return _dist\r\n\r\nif __name__ == '__main__':\r\n a = Point(-1, 1)\r\n b = Point(3, 4)\r\n\r\n print (a)\r\n print (b)\r\n print(distance_between_points(a, b))\r\n","sub_path":"exercises/ex17_3.py","file_name":"ex17_3.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"250268389","text":"# for serial port\nimport serial # serial port\nfrom tkinter import *\nimport tkinter\nfrom PIL import Image,ImageTk \nimport threading\nfrom tkinter import messagebox\nimport codecs\nimport binascii\nimport string\nimport time\n\n# for plot\nimport numpy as np\nimport matplotlib # plot\nimport matplotlib.pyplot as plt # plot\nfrom scipy import linalg # linear algebra\n\n# image\nfrom scipy.misc import imread\nimport matplotlib.cbook as cbook\n\n\n\n# trackers info\nTrackers = np.array([\n [0,0]\n])\n\n# anchors info (Sıralama degismemeli!!!)\nAnchors = np.array([\n [0,0], # E5\n [1,200], # E6\n [100,1] # E7\n\n])\n# distances info\nDistances = np.array([0, 0, 0])\n# open interactive plot\ndatafile = cbook.get_sample_data('C:\\\\yonetim_ofisi.png')\nimg = imread(datafile)\nplt.imshow(img, extent=[0,2070,0,1700], aspect='auto')\nplt.axis([-500, 2070, -500, 1700])\nplt.ion()\nplt.pause(0.5)\n\n\n\n# serial port settings\nser = serial.Serial()\nser.baudrate = 115200\nprint(\"*********************\")\nser.port = \"COM5\"\nprint(\"*********************\")\nser.open()\nprint(\"Starting....\")\n# -----------------------------------------------\n# main loop\n# -----------------------------------------------\nwhile True:\n packet_sending = \"\"\n data = ser.readline()\n packet_sending += str(data,'utf-8')\n #deney =ser.readline(4)\n #lora_message = str(deney,'utf-8')\n if 'radio_rx' in packet_sending:\n ua = []\n ua = packet_sending.split('C1')\n ua_message =(\"C1\"+ua[1])\n print(\"Time : \",time.strftime('%T')) \n print(\"\\nPacket : \",ua_message)\n device_adress = ua_message[6:12]\n tracker_ua_adress = ua_message[18:24]\n \n anchor1_adress =\"------\"\n anchor1_rssi =\"------\"\n anchor2_adress =\"------\"\n anchor2_rssi =\"------\"\n anchor3_adress =\"------\"\n anchor3_rssi =\"------\"\n anchor4_adress =\"------\"\n anchor4_rssi =\"------\"\n anchor5_adress =\"------\"\n anchor5_rssi =\"------\"\n anchor6_adress =\"------\"\n anchor6_rssi =\"------\"\n \n #print(\"packet len : \",len(ua_message))\n if len(ua_message) > 32:\n anchor1_adress = ua_message[24:30]\n if (all(c in string.hexdigits for c in ua_message[30:34] )):\n anchor1_rssi = int(ua_message[30:34],16)\n if len(ua_message) > 42:\n anchor2_adress = ua_message[34:40]\n if (all(c in string.hexdigits for c in ua_message[40:44] )):\n anchor2_rssi = int(ua_message[40:44],16)\n if len(ua_message) > 52:\n anchor3_adress = ua_message[44:50]\n if (all(c in string.hexdigits for c in ua_message[50:54] )):\n anchor3_rssi = int(ua_message[50:54],16)\n if len(ua_message) > 62:\n anchor4_adress = ua_message[54:60]\n if (all(c in string.hexdigits for c in ua_message[60:64] )):\n anchor4_rssi = int(ua_message[60:64],16)\n if len(ua_message) > 72:\n anchor5_adress = ua_message[64:70]\n if (all(c in string.hexdigits for c in ua_message[70:74] )):\n anchor5_rssi = int(ua_message[70:74],16)\n if len(ua_message) > 82:\n anchor6_adress = ua_message[74:80]\n if (all(c in string.hexdigits for c in ua_message[70:72] )):\n anchor6_rssi = int(ua_message[80:84],16)\n\n print(\"Device Adress : \",device_adress.upper())\n print(\"Tracker Adress : \",tracker_ua_adress.upper())\n \n print(\"\\nAnchor1 Adress : \",anchor1_adress.upper())\n print(\"Anchor1 RSSI : \",anchor1_rssi)\n print(\"\\nAnchor2 Adress : \",anchor2_adress.upper())\n print(\"Anchor2 RSSI : \",anchor2_rssi)\n print(\"\\nAnchor3 Adress : \",anchor3_adress.upper())\n print(\"Anchor3 RSSI : \",anchor3_rssi)\n\n print(\"*************************\\n\")\n\n # -----------------------------------------------\n # compute triliteration\n # -----------------------------------------------\n # [A][xy] = [b]\n # ...............................................\n # parameters\n \n d1 = anchor1_rssi\n d2 = anchor2_rssi\n d3 = anchor3_rssi\n\n\n\n \n","sub_path":"UA_Basketball_Gui/UA_Basketball_GUI.py","file_name":"UA_Basketball_GUI.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"387487809","text":"import tensorflow as tf\n\n\ndef create_weights(shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.05))\n\n\ndef create_biases(size):\n return tf.Variable(tf.constant(0.05, shape=[size]))\n\n\ndef create_convolutional_layer(input,\n num_input_channels,\n conv_filter_size,\n num_filters):\n # We shall define the weights that will be trained using create_weights function.\n weights = create_weights(shape=[conv_filter_size, conv_filter_size, num_input_channels, num_filters])\n # We create biases using the create_biases function. These are also trained.\n biases = create_biases(num_filters)\n\n # Creating the convolutional layer\n layer = tf.nn.conv2d(input=input,\n filter=weights,\n strides=[1, 1, 1, 1],\n padding='SAME')\n\n layer += biases\n\n # We shall be using max-pooling.\n layer = tf.nn.max_pool(value=layer,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME')\n # Output of pooling is fed to Relu which is the activation function for us.\n layer = tf.nn.relu(layer)\n\n return layer\n\n\ndef create_flatten_layer(layer):\n # We know that the shape of the layer will be [batch_size img_size img_size num_channels]\n # But let's get it from the previous layer.\n layer_shape = layer.get_shape()\n\n # Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it.\n num_features = layer_shape[1:4].num_elements()\n\n # Now, we Flatten the layer so we shall have to reshape to num_features\n layer = tf.reshape(layer, [-1, num_features])\n\n return layer\n\n\ndef create_mynet(images, num_classes):\n\n # image settings\n num_channels = 3\n\n # Network graph params\n filter_size_conv1 = 3\n num_filters_conv1 = 32\n\n filter_size_conv2 = 3\n num_filters_conv2 = 32\n\n filter_size_conv3 = 3\n num_filters_conv3 = 64\n\n fc_layer_size = 128\n\n layer_conv1 = create_convolutional_layer(input=images,\n num_input_channels=num_channels,\n conv_filter_size=filter_size_conv1,\n num_filters=num_filters_conv1)\n layer_conv2 = create_convolutional_layer(input=layer_conv1,\n num_input_channels=num_filters_conv1,\n conv_filter_size=filter_size_conv2,\n num_filters=num_filters_conv2)\n\n layer_conv3 = create_convolutional_layer(input=layer_conv2,\n num_input_channels=num_filters_conv2,\n conv_filter_size=filter_size_conv3,\n num_filters=num_filters_conv3)\n\n layer_flat = create_flatten_layer(layer_conv3)\n\n layer_shape = layer_flat.get_shape()\n\n # Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it.\n num_features = layer_shape[1:4].num_elements()\n\n layer_fc1 = create_fc_layer(input=layer_flat,\n num_inputs=layer_flat.get_shape()[1:4].num_elements(),\n num_outputs=fc_layer_size,\n use_relu=True)\n\n layer_shape = layer_fc1.get_shape()\n\n # Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it.\n num_features = layer_shape[1:4].num_elements()\n\n layer_fc2 = create_fc_layer(input=layer_fc1,\n num_inputs=fc_layer_size,\n num_outputs=num_classes,\n use_relu=False)\n\n layer_shape = layer_fc2.get_shape()\n\n # Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it.\n num_features = layer_shape[1:4].num_elements()\n\n return layer_fc2\n\n\ndef create_fc_layer(input,\n num_inputs,\n num_outputs,\n use_relu=True):\n # Let's define trainable weights and biases.\n weights = create_weights(shape=[num_inputs, num_outputs])\n biases = create_biases(num_outputs)\n\n # Fully connected layer takes input x and produces wx+b.Since, these are matrices, we use matmul function in Tensorflow\n layer = tf.matmul(input, weights) + biases\n if use_relu:\n layer = tf.nn.relu(layer)\n\n return layer","sub_path":"trainer/mynet.py","file_name":"mynet.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"182068735","text":"# from replit import clear\r\n#HINT: You can call clear() to clear the output in the console.\r\nimport os\r\nfrom art import logo1\r\nprint(logo1)\r\n\r\nname_bid = {}\r\nend = False\r\n\r\ndef clear():\r\n if os.name == 'nt':\r\n _ = os.system('cls')\r\n else:\r\n _ = os.system('clear')\r\n\r\ndef find_highest_bid(bidding):\r\n highest_bid = 0\r\n winner = \"\"\r\n for x in bidding:\r\n bid_amount = bidding[x]\r\n if bid_amount > highest_bid:\r\n highest_bid = bid_amount\r\n winner = x\r\n print(f\"The winner is {winner} and the bid is {highest_bid}\")\r\n\r\n\r\nwhile not end:\r\n name = input(\"What's your name?: \")\r\n bid = int(input(\"What's your bid price?:$ \"))\r\n name_bid[name] = bid\r\n restart = input(\"Type 'Yes' if there any users to bid, if not type 'No':\").lower()\r\n if restart == \"no\":\r\n end = True\r\n find_highest_bid(name_bid)\r\n elif restart == \"yes\":\r\n clear()","sub_path":"CaesarCipher/exe13-1.py","file_name":"exe13-1.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"522504687","text":"import requests\nimport json\nfrom utilities.config import COLUMNS, DEFAULT_VALUE, ACCESS_KEY, TYPE_OF_REQUEST\nimport pandas as pd\nimport logging\nlogger = logging.getLogger()\n\n\ndef weather_api(origin_df):\n \"\"\"\n requests additional information using the weather\n API for the cities supplied in the 'sub_location' column.\n\n :param origin_csv: csv_file with scraped data\n :return: pd.DataFrame with added columns from the weather API\n \"\"\"\n\n # Read csv file to pandas and initialize new columns\n df = origin_df.copy()\n df[COLUMNS] = DEFAULT_VALUE\n # go over all unique locations and update columns, thus saving api calls\n unique_sub_locations = df['sub_location'].unique()\n for sub_location in unique_sub_locations:\n # Parameters for api request\n params = {\n 'access_key': ACCESS_KEY,\n 'query': sub_location,\n }\n api_result = requests.get(f'http://api.weatherstack.com/{TYPE_OF_REQUEST}', params)\n api_result_json = json.loads(api_result.content)\n if \"success\" in api_result_json.keys():\n if api_result_json[\"success\"] is False: # error code for usage_limit_reached\n if api_result_json[\"error\"][\"code\"] == 104:\n logger.info(f\"Monthly API subscription has reached its limit.\")\n break\n continue\n elif api_result.status_code != 200: # for bad result, skip to next location\n logger.info(f\"Weather API bad status code\")\n continue\n else:\n api_response = api_result.json()\n\n lat = api_response['location']['lat']\n lon = api_response['location']['lon']\n temperature = api_response['current']['temperature']\n feelslike = api_response['current']['feelslike']\n\n df.loc[df['sub_location'] == sub_location, COLUMNS] = lat, lon, temperature, feelslike\n logger.info(f\"Weather API finished all requests.\")\n return df\n","sub_path":"sources/weather_api.py","file_name":"weather_api.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"3148507","text":"\"\"\"\nMetrics across MAF range with quantiles dispersion\n\"\"\"\n\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nrootdir = os.path.dirname(os.path.dirname(os.getcwd()))\nsys.path.insert(0, rootdir)\n\nfrom VCFPooling.poolSNPs.metrics import quality as qual\nfrom VCFPooling.persotools.files import *\n\n\n# Data parameters and plotting features\n\nrQ = 1000\nbS = 0.01\nx_data = 'binned_maf' # 'binned_maf_info'\n\nsns.set(rc={'figure.figsize': (10, 8)})\nsns.set_style('whitegrid')\ndash_styles = [\n (1, 1),\n (3, 1, 1.5, 1),\n (5, 1, 1, 1),\n (5, 1, 2, 1, 2, 1),\n (2, 2, 3, 1.5),\n (1, 2.5, 3, 1.2),\n \"\",\n (4, 1.5),\n]\n\n\n# Configure data/plots paths\n\noutdir = '/home/camille/PoolImpHuman/results/20210319'\nif not os.path.exists(outdir):\n os.mkdir(outdir)\n\ntruegt = '/home/camille/PoolImpHuman/data/20210319/noNA18967.IMP.chr20.snps.gt.vcf.gz'\ntruegl = '/home/camille/PoolImpHuman/data/20210319/noNA18967.IMP.chr20.snps.gl.vcf.gz'\nimputed_beagle = '/home/camille/PoolImpHuman/data/20200709/noNA18967.IMP.chr20.pooled.imputed.vcf.gz'\nimputed_phaser = '/home/camille/PoolImpHuman/data/20210319/noNA18967.IMP.chr20.pooled.imputed.vcf.gz'\n\nprint('\\r\\nData written to {}'.format(outdir))\n\n\n# Function/Tools\n\ndef rollquants(dX: pd.DataFrame, dS1: pd.Series, dS2: pd.Series) -> pd.DataFrame:\n pdf1 = qual.QuantilesDataFrame(dX,\n dS1,\n bins_step=bS)\n pctY1 = pdf1.binnedX_rolling_quantilY(rollwin=rQ)\n pctY1['dataset'] = ['beagle'] * pctY1.shape[0]\n\n pdf2 = qual.QuantilesDataFrame(dX,\n dS2,\n bins_step=bS)\n pctY2 = pdf2.binnedX_rolling_quantilY(rollwin=rQ)\n pctY2['dataset'] = ['phaser'] * pctY2.shape[0]\n\n rollquants = pd.concat([pctY1, pctY2])\n\n return rollquants\n\n\n# Load data and check\n\nqbeaglegt = qual.QualityGT(truegt, imputed_beagle, 0, idx='chrom:pos')\nqbeaglegl = qual.QualityGL(truegl, imputed_beagle, 0, idx='chrom:pos')\n\nprint('\\r\\n{} variants from {} samples read from {}'.format(len(qbeaglegt.trueobj.variants),\n len(qbeaglegt.trueobj.samples),\n os.path.basename(truegt)))\nprint('\\r\\n{} variants from {} samples read from {}'.format(len(qbeaglegt.imputedobj.variants),\n len(qbeaglegt.imputedobj.samples),\n os.path.basename(imputed_beagle)))\nbgldiff = qbeaglegt.diff()\n\nqphasergt = qual.QualityGT(truegt, imputed_phaser, 0, idx='chrom:pos')\nqphasergl = qual.QualityGL(truegl, imputed_phaser, 0, idx='chrom:pos')\n\nprint('\\r\\n{} variants from {} samples read from {}'.format(len(qbeaglegl.trueobj.variants),\n len(qbeaglegl.trueobj.samples),\n os.path.basename(truegl)))\nprint('\\r\\n{} variants from {} samples read from {}'.format(len(qphasergl.imputedobj.variants),\n len(qphasergl.imputedobj.samples),\n os.path.basename(imputed_phaser)))\n\nprint('True AF INFO: \\r{}'.format(qbeaglegt.trueobj.aaf)) # af_info\nmafS = qbeaglegt.trueobj.maf # maf_info\n\nmetrics = {'precision_score': {'beagle': qbeaglegt.precision,\n 'phaser': qphasergt.precision},\n 'recall_score': {'beagle': qbeaglegt.recall,\n 'phaser': qphasergt.recall},\n 'f1_score': {'beagle': qbeaglegt.f1_score,\n 'phaser': qphasergt.f1_score},\n 'concordance': {'beagle': qbeaglegt.concordance(),\n 'phaser': qphasergt.concordance()},\n 'allelic_dos': None,\n 'cross_entropy': {'beagle': qbeaglegl.cross_entropy,\n 'phaser': qphasergl.cross_entropy}\n }\n\ndataquants = {'precision_score': os.path.join(outdir, 'rolling_quantiles_precision_score.json'),\n 'recall_score': os.path.join(outdir, 'rolling_quantiles_recall_score.json'),\n 'f1_score': os.path.join(outdir, 'rolling_quantiles_f1_score.json'),\n 'concordance': os.path.join(outdir, 'rolling_quantiles_concordance.json'),\n 'allelic_dos': None,\n 'cross_entropy': os.path.join(outdir, 'rolling_quantiles_cross_entropy.json')\n }\n\n\n# Process and write data\n\nfor metric, d in metrics.items():\n if d is not None:\n yS_beagle, yS_phaser = list(d.values())\n # Compute quantiles\n print('Computing quantiles for {}'.format(metric).ljust(80, '.'))\n pctY_comp = rollquants(mafS, yS_beagle, yS_phaser)\n # Compute mean over all markers\n print('Computing means for {}'.format(metric).ljust(80, '.'))\n pctY_comp['mean'] = pctY_comp['dataset'].apply(lambda x: yS_beagle.mean() if x == 'beagle' else yS_phaser.mean())\n jsonf = dataquants[metric]\n pctY_comp.to_json(jsonf,\n orient='records')\nprint(pctY_comp[pctY_comp['dataset'] == 'phaser'])\n\n\n# Read processed reshaped data for plotting and draw figures\n\nfor dquant, f in dataquants.items():\n if f is not None:\n dataf = pd.read_json(f, orient='records')\n meanf = {}\n\n gY = sns.lineplot(data=dataf[dataf.quantiles == 0.5], x=x_data, y=dquant,\n hue='dataset', palette=\"deep\", linewidth=1)\n for i, dset in enumerate(['beagle', 'phaser']):\n df = dataf[dataf['dataset'] == dset]\n meanf[dset] = df['mean'].mean()\n gY.fill_between(df[df.quantiles == 1.0][x_data],\n df[df.quantiles == 0.0][dquant],\n df[df.quantiles == 1.0][dquant],\n color=sns.color_palette('deep')[i],\n alpha=0.1)\n gY.fill_between(df[df.quantiles == 0.99][x_data],\n df[df.quantiles == 0.01][dquant],\n df[df.quantiles == 0.99][dquant],\n color=sns.color_palette('deep')[i],\n alpha=0.25)\n gY.fill_between(df[df.quantiles == 0.75][x_data],\n df[df.quantiles == 0.25][dquant],\n df[df.quantiles == 0.75][dquant],\n color=sns.color_palette('deep')[i],\n alpha=0.40)\n gY.set_xlabel('True minor allele frequency in {} population'.format('study' if x_data == 'binned_maf'\n else 'main'))\n handles, labels = gY.get_legend_handles_labels()\n labels[-2] = '{} (mean = {:.5f})'.format(labels[-2], meanf['beagle'])\n labels[-1] = '{} (mean = {:.5f})'.format(labels[-1], meanf['phaser'])\n gY.legend(handles, labels)\n plt.savefig(os.path.join(outdir, '{}_percentiles_rQ={}_bS={}_xdata={}.pdf'.format(dquant, rQ, bS, x_data.lstrip('binned_'))))\n plt.show()\n","sub_path":"poolSNPs/quantiles_plots.py","file_name":"quantiles_plots.py","file_ext":"py","file_size_in_byte":7291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"460162183","text":"# -*- coding: utf-8 -*-\n\nfrom mrsimulator import Simulator\nfrom mrsimulator.methods import one_d_spectrum\nfrom dash import Dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_daq as daq\nimport plotly.graph_objs as go\nfrom dash.dependencies import Input, Output, State\nimport datetime, json\nimport base64\n\nfrom mrsimulator.widgets import (\n spectrum_object_widget,\n plot_object_widget,\n direct_dimension_setup,\n)\n\n\n__author__ = \"Deepansh J. Srivastava\"\n__email__ = \"srivastava.90@osu.edu\"\n\n\nexternal_stylesheets = [\n \"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css\"\n]\n\n\nexternal_scripts = [\n 'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js'\n]\n\n\ncolors = {\n 'background': '#e2e2e2',\n 'text': '#585858'\n}\n\n\n\n# isotopomer = get_system()\ndef setup(app, simulator):\n app.layout = html.Div(className='container',\n # style={'background-color': '#303030', 'color': 'white'},\n # style={'backgroundColor': colors['background']},\n children=[\n # dcc.ConfirmDialog(\n # id='confirm',\n # message='Cannot process the current requeste.',\n # ),\n html.H1(\n children='mrsimulator',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n html.Div(children='A web application framework for NMR lineshape simulation.',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n html.Hr(),\n html.Div(className='row', children=[\n html.Div(className='col s12 m7 l7', id='output-data-upload'),\n html.Div(className='col s12 m5 l5', children=[\n dcc.Upload(\n id='upload_data',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select File')\n ]),\n style={\n 'width': '100%',\n 'height': '50px',\n 'lineHeight': '50px',\n 'borderWidth': '1px',\n 'borderStyle': 'dashed',\n 'borderRadius': '5px',\n 'textAlign': 'center',\n 'margin': '1px'\n },\n # Allow multiple files to be uploaded\n multiple=False\n ),\n html.Div(id='error_message', style={'textAlign': 'center'})\n ])\n ]),\n html.Hr(),\n html.Div(\n className='row',\n children=[\n html.Div(\n className='col s12 m7 l7',\n children=plot_object_widget()\n ),\n html.Div(\n className='col s12 m5 l5',\n children=spectrum_object_widget(direct_dimension_setup())#nuclei, simulator.isotope_list)\n )\n ]),\n ]\n )\n\n # @app.callback(\n # Output('tabs_content', 'children'),\n # [Input('tabs', 'value')]\n # )\n # def update_tab(value):\n # if value == 'direct_dimension':\n # return direct_dimension_setup()\n\n @app.callback(\n [\n Output('nmr_spectrum', 'figure'),\n ],\n [\n # Input('confirm', 'submit_n_clicks'),\n Input(component_id='spinning_frequency_in_kHz_coarse', component_property='value'),\n Input(component_id='spinning_frequency_in_kHz_fine', component_property='value'),\n Input(component_id='number_of_points', component_property='value'),\n Input(component_id='frequency_bandwidth_coarse', component_property='value'),\n Input(component_id='frequency_bandwidth_fine', component_property='value'),\n Input(component_id='reference_offset_coarse', component_property='value'),\n Input(component_id='reference_offset_fine', component_property='value'),\n Input(component_id='magnetic_flux_density', component_property='value'),\n # Input(component_id='MAS_switch', component_property='value'),\n Input(component_id='nucleus_id', component_property='value'),\n ])\n def update_plot(\n # submit_n_clicks,\n spinning_frequency_in_kHz_coarse,\n spinning_frequency_in_kHz_fine,\n number_of_points,\n frequency_bandwidth_coarse,\n frequency_bandwidth_fine,\n reference_offset_coarse,\n reference_offset_fine,\n magnetic_flux_density,\n # MAS_switch,\n nucleus_id):\n\n frequency_bandwidth = frequency_bandwidth_coarse + frequency_bandwidth_fine\n if number_of_points == 0 or frequency_bandwidth == 0 or nucleus_id in ['', None]:\n return empty_plot()\n\n spin_frequency = spinning_frequency_in_kHz_coarse+spinning_frequency_in_kHz_fine\n reference_offset = reference_offset_coarse + reference_offset_fine\n \n # if MAS_switch:\n rotor_angle_in_degree = 54.735\n # else:\n # rotor_angle_in_degree = 0\n\n simulator.spectrum = {\n \"direct_dimension\": {\n \"nucleus\": nucleus_id,\n \"magnetic_flux_density\": str(magnetic_flux_density) + \" T\",\n \"rotor_frequency\": str(spin_frequency)+' kHz',\n \"rotor_angle\": str(rotor_angle_in_degree)+' deg',\n \"number_of_points\": 2**number_of_points,\n \"spectral_width\": str(frequency_bandwidth)+' kHz',\n \"reference_offset\": str(reference_offset)+' kHz',\n }\n }\n\n freq, amp = simulator.run(one_d_spectrum)\n\n data_spinning = go.Scatter(x=freq/1000, y=amp/amp.max(),\n mode='lines', opacity=1.0, name=nucleus_id)\n x_label = str(nucleus_id + ' frequency / kHz')\n # print(x_label)\n return [{\n 'data': [data_spinning],\n 'layout': go.Layout(\n xaxis={\n 'type': 'linear',\n 'title': x_label, #'frequency / kHz',\n 'ticks': 'outside',\n 'showline': True,\n 'autorange': True\n },\n yaxis={\n 'type': 'linear',\n 'title': 'arbitrary unit',\n 'ticks': 'outside',\n 'showline': True,\n 'autorange': True,\n },\n autosize=True,\n transition={'duration': 600}, #'easing': 'quad-in-out'},\n margin={'l': 50, 'b': 40, 't': 5, 'r': 5},\n # legend={'x': 0, 'y': 1},\n hovermode='closest'\n )\n }]\n\n @app.callback(\n [\n Output('output-data-upload', 'children'),\n Output('error_message', 'children'),\n Output('nucleus_widget_id', 'children'),\n ],\n [Input('upload_data', 'contents')],\n [State('upload_data', 'filename'),\n State('upload_data', 'last_modified')])\n def update_isotopomers(list_of_contents, list_of_names, list_of_dates):\n # if list_of_contents is not None:\n FIRST = False\n children, success = parse_contents(simulator, list_of_contents, \n list_of_names,\n list_of_dates)\n \n\n if success:\n nuclei =[\n {'label': site_iso, 'value': site_iso}\n for site_iso in simulator.isotope_list\n ]\n \n if len(simulator.isotope_list) >= 1:\n value = simulator.isotope_list[0]\n else:\n value = ''\n nucleus_id = [\n dcc.Dropdown(\n id='nucleus_id',\n options=nuclei,\n value=value,\n style={\"display\": \"block\",\n \"margin-left\": \"auto\",\n \"margin-right\": \"auto\",\n \"width\": \"auto\"},\n ),\n ]\n else:\n simulator.isotopomers = []\n nucleus_id = [\n dcc.Dropdown(\n id='nucleus_id',\n style={\"display\": \"block\",\n \"margin-left\": \"auto\",\n \"margin-right\": \"auto\",\n \"width\": \"auto\"},\n ),\n ]\n return [children[0]], [children[1]], nucleus_id\n\n @app.callback(\n Output('Magnetic_flux_density_output_container', 'children'),\n [Input('magnetic_flux_density', 'value')]\n )\n def update_magnetic_flux_density(value):\n return 'Magnetic flux density {0} T @ {1} MHz'.format(\n value, '{0:.2f}'.format(42.57747892*value)\n )\n\n @app.callback(\n Output('spectrum_id', 'children'),\n [Input('nucleus_id', 'value')]\n )\n def update_spectrum_title(value):\n if value is None:\n return 'Spectrum'\n return '{} spectrum'.format(value)\n\n @app.callback(\n Output('number_of_points_output_container', 'children'),\n [Input('number_of_points', 'value')]\n )\n def update_number_of_points(value):\n return 'Number of points {}'.format(2**value)\n\n @app.callback(\n Output('spinning_frequency_output_container', 'children'),\n [Input('spinning_frequency_in_kHz_fine', 'value'),\n Input('spinning_frequency_in_kHz_coarse', 'value')]\n )\n def update_rotor_frequency(value1, value2):\n return 'Magic angle spinning {} kHz'.format(value1 + value2)\n\n @app.callback(\n Output('reference_offset_output_container', 'children'),\n [Input('reference_offset_fine', 'value'),\n Input('reference_offset_coarse', 'value')]\n )\n def update_reference_offset(value1, value2):\n return 'Reference offset {} kHz'.format(value1 + value2)\n\n @app.callback(\n Output('frequency_bandwidth_output_container', 'children'),\n [Input('frequency_bandwidth_fine', 'value'),\n Input('frequency_bandwidth_coarse', 'value')]\n )\n def update_frequency_bandwidth(value1, value2):\n return 'Spectral width {} kHz'.format(value1 + value2)\n\n\n# ['linear', 'quad', 'cubic', 'sin', 'exp', 'circle',\n# 'elastic', 'back', 'bounce', 'linear-in', 'quad-in',\n# 'cubic-in', 'sin-in', 'exp-in', 'circle-in', 'elastic-in',\n# 'back-in', 'bounce-in', 'linear-out', 'quad-out',\n# 'cubic-out', 'sin-out', 'exp-out', 'circle-out',\n# 'elastic-out', 'back-out', 'bounce-out', 'linear-in-out',\n# 'quad-in-out', 'cubic-in-out', 'sin-in-out', 'exp-in-out',\n# 'circle-in-out', 'elastic-in-out', 'back-in-out',\n# 'bounce-in-out']\n\n\ndef empty_plot():\n data = go.Scatter(x=[-1,1], y=[0,0], text='', mode='lines', opacity=1.0)\n # return [{'data': [data]}]\n return [{\n 'data': [data],\n 'layout': go.Layout(\n xaxis={\n 'type': 'linear',\n 'title': 'frequency / kHz',\n 'ticks': 'outside',\n 'showline': True,\n 'autorange': True\n },\n yaxis={\n 'type': 'linear',\n 'title': 'arbitrary unit',\n 'ticks': 'outside',\n 'showline': True,\n 'autorange': True,\n },\n autosize=True,\n transition={'duration': 500},\n margin={'l': 50, 'b': 40, 't': 5, 'r': 5},\n # legend={'x': 0, 'y': 1},\n hovermode='closest'\n )\n }]\n\n\ndef parse_contents(simulator, contents, filename, date):\n try:\n if 'json' in filename:\n content_type, content_string = contents.split(',')\n decoded = base64.b64decode(content_string)\n parse=json.loads(str(decoded, encoding=\"UTF-8\"))['isotopomers']\n # print(parse)\n simulator.isotopomers = parse\n return [html.Div([\n html.H5(filename),\n html.H6(datetime.datetime.fromtimestamp(date))\n ]), html.Label([\n 'Select a JSON serialized isotopomers file.'\n ])], True\n\n else:\n return ['', html.Label([\n 'A JSON file is required.'\n ])], False\n except: #Exception as e:\n # simulator.isotopomers = []\n # print(e)\n if FIRST:\n return ['', html.Label([\n 'Select a JSON serialized isotopomers file.'\n ])], False\n else:\n return ['', html.Label([\n 'There was an error reading the file.'\n ])], False\n\n\n\n\nif __name__ == '__main__':\n app = Dash(__name__)\n for css in external_stylesheets:\n app.css.append_css({\"external_url\": css})\n for js in external_scripts:\n app.scripts.append_script({'external_url': js})\n \n FIRST = True\n simulator = Simulator()\n setup(app, simulator)\n app.run_server(debug=True)\n","sub_path":"mrsimulator/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":13601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"455451450","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\nfrom qiniu import Auth\nfrom qiniu import put_file,etag,urlsafe_base64_encode\nimport qiniu.config\nimport os\nimport re\n\naccess_key = 'Emt5iZQPNqnV-5ZMCKHGptekc9Nzq0_lEgt8Cjak'\nsecret_key = '1nNE6t2A1hTqZXNMAHh2tefU_o3geiQvIci16H7L'\n\n#构建鉴权对象\nq = Auth(access_key, secret_key)\n\n#要上传的空间名\nbucket_name = 'onepiece'\n\n# #要保存的文件名\n# key = 'my-test.png'\ndef upload(picture_path):\n\tkeyprex = 'onepiece_'\n\twhich_hua = re.compile(r'\\d+').findall(picture_path)[0]\n\tfilename = os.path.split(picture_path)\n\tkey = keyprex+which_hua+'_'+filename[1]\n\t#生成上传Token,可以指定过期时间\n\tprint(key)\n\ttoken = q.upload_token(bucket_name,key,3600)\n\n\t#要上传文件的本地路径\n\tlocalfile = picture_path\n\n\tret , info = put_file(token,key,localfile)\n\t# print(info)\n\tassert ret['key'] == key \n\tassert ret['hash'] == etag(localfile)\n\tpicture_url = 'http://ompb5dzt6.bkt.clouddn.com/'+key\n\treturn picture_url\ndef upload_one_dir(dirname):\n\tall_filelists = os.listdir(dirname)\n\tpicture_urls = []\n\tfor filename in all_filelists:\n\t\tfull_filename = os.path.join(dirname,filename)\n\t\tpicture_urls.append(upload(full_filename))\n\treturn picture_urls\n\ndef write_url2txt(url_list):\n\tdirname = \"/home/zackzhao/tencent_comic/urls/\"\n\twhich_hua = re.compile(r'0\\d+').findall(url_list[0])[0]\n\tprint(which_hua)\n\tif not os.path.exists(dirname):\n\t\tos.makedirs(dirname)\n\tfilename = dirname+which_hua\n\n\twith open(filename,'w') as wf:\n\t\tfor url in url_list:\n\t\t\twf.write(url)\n\t\t\twf.write('\\n')\n\ndef main():\n\tdirname = \"/home/zackzhao/tencent_comic/海贼王_航海王/第0001话-第1话 ROMANCE DAWN 冒险的序幕\"\n\turl_list = upload_one_dir(dirname)\n\tprint(url_list)\n\twrite_url2txt(url_list)\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"test_qiniu.py","file_name":"test_qiniu.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"51954032","text":"#!/usr/bin/python\n\"\"\"\n (C) Copyright 2018-2020 Intel Corporation.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE\n The Governments rights to use, modify, reproduce, release, perform, display,\n or disclose this software are subject to the terms of the Apache License as\n provided in Contract No. B609815.\n Any reproduction of computer software, computer software documentation, or\n portions thereof marked with this legend must also reproduce the markings.\n\"\"\"\nfrom apricot import TestWithServers, skipForTicket\nfrom test_utils_pool import TestPool\nfrom test_utils_container import TestContainer\n\n\nclass RebuildWithIO(TestWithServers):\n \"\"\"Test class for pool rebuild during I/O.\n\n Test Class Description:\n This class contains tests for pool rebuild that feature I/O going on\n during the rebuild.\n\n :avocado: recursive\n \"\"\"\n\n @skipForTicket(\"DAOS-2922\")\n def test_rebuild_with_io(self):\n \"\"\"JIRA ID: Rebuild-003.\n\n Test Description:\n Trigger a rebuild while I/O is ongoing.\n\n Use Cases:\n single pool, single client performing continous read/write/verify\n sequence while failure/rebuild is triggered in another process\n\n :avocado: tags=all,pool,rebuild,pr,medium,rebuildwithio\n \"\"\"\n # Get the test params\n pool = TestPool(self.context, self.log,\n dmg_command=self.get_dmg_command())\n pool.get_params(self)\n container = TestContainer(pool)\n container.get_params(self)\n targets = self.params.get(\"targets\", \"/run/server_config/*\")\n # data = self.params.get(\"datasize\", \"/run/testparams/*\")\n rank = self.params.get(\"rank\", \"/run/testparams/*\")\n obj_class = self.params.get(\"object_class\", \"/run/testparams/*\")\n server_count = len(self.hostlist_servers)\n\n # Create a pool and verify the pool info before rebuild (also connects)\n pool.create()\n status = pool.check_pool_info(\n pi_nnodes=server_count,\n pi_ntargets=(server_count * targets), # DAOS-2799\n pi_ndisabled=0,\n )\n status &= pool.check_rebuild_status(\n rs_done=1, rs_obj_nr=0, rs_rec_nr=0, rs_errno=0)\n self.assertTrue(status, \"Error confirming pool info before rebuild\")\n\n # Create and open the contaner\n container.create()\n\n # Write data to the contianer for 30 seconds\n self.log.info(\n \"Wrote %s bytes to container %s\",\n container.execute_io(30, rank, obj_class), container.uuid)\n\n # Determine how many objects will need to be rebuilt\n container.get_target_rank_lists(\" prior to rebuild\")\n\n # Trigger rebuild\n pool.start_rebuild([rank], self.d_log)\n\n # Wait for recovery to start\n pool.wait_for_rebuild(True)\n\n # Write data to the contianer for another 30 seconds\n self.log.info(\n \"Wrote an additional %s bytes to container %s\",\n container.execute_io(30), container.uuid)\n\n # Wait for recovery to complete\n pool.wait_for_rebuild(False)\n\n # Check the pool information after the rebuild\n status = status = pool.check_pool_info(\n pi_nnodes=server_count,\n pi_ntargets=(server_count * targets), # DAOS-2799\n pi_ndisabled=targets, # DAOS-2799\n )\n status &= pool.check_rebuild_status(\n rs_done=1, rs_obj_nr=\">0\", rs_rec_nr=\">0\", rs_errno=0)\n self.assertTrue(status, \"Error confirming pool info after rebuild\")\n\n # Verify the data after rebuild\n self.assertTrue(\n container.read_objects(),\n \"Data verifiaction error after rebuild\")\n self.log.info(\"Test Passed\")\n","sub_path":"src/tests/ftest/pool/rebuild_with_io.py","file_name":"rebuild_with_io.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"501664057","text":"import calendar\nimport datetime\nimport os\nimport time\nfrom collections import Counter\nimport json\n\nimport numpy as np\nimport pandas as pd\n\n\ndef pad(seq, max_seq_len, pre=False):\n initial_len = len(seq)\n if max_seq_len < initial_len:\n return np.array(seq[:max_seq_len], dtype=\"int32\")\n to_fill = max_seq_len - initial_len\n array_to_fill = np.zeros(to_fill, dtype=\"int32\")\n data_tup = (array_to_fill, seq) if pre is True else (seq, array_to_fill)\n return np.concatenate(data_tup).astype(\"int32\")\n\n\ndef display_seq_statistics(dataset):\n ds_seq_len = dataset[\"sequence\"].apply(lambda x: len(x))\n min_seq = ds_seq_len.min()\n max_seq = ds_seq_len.max()\n std_seq = ds_seq_len.std()\n mean_seq = ds_seq_len.mean()\n cnt = Counter()\n for seq_len in ds_seq_len.values:\n cnt[seq_len] += 1\n sorted_cnt = sorted(cnt.items(), key=lambda x: x[0])\n for k, v in sorted_cnt:\n print(\"Seq len: {} -> count: {}\".format(k, v))\n print(\"Sequence length min: {} , max: {}, mean: {}, std: {}\".format(min_seq, max_seq, mean_seq, std_seq))\n\n\ndef create_seq_db_filter_top_k(path, topk=0, last_months=0):\n file = load_and_adapt(path, last_months=last_months)\n\n c = Counter(list(file['item_id']))\n\n if topk > 1:\n keeper = set([x[0] for x in c.most_common(topk)])\n file = file[file['item_id'].isin(keeper)]\n\n # group by session id and concat song_id\n groups = file.groupby('session_id')\n\n # convert item ids to string, then aggregate them to lists\n aggregated = groups['item_id'].agg({'sequence': lambda x: list(map(str, x))})\n init_ts = groups['ts'].min()\n users = groups['user_id'].min() # it's just fast, min doesn't actually make sense\n\n result = aggregated.join(init_ts).join(users)\n result.reset_index(inplace=True)\n return result\n\n\ndef dataset_to_gru4rec_format(dataset):\n \"\"\"\n Convert a list of sequences to GRU4Rec format.\n Based on this StackOverflow answer: https://stackoverflow.com/a/48532692\n :param dataset: the dataset to be transformed\n \"\"\"\n\n lst_col = 'sequence'\n df = dataset.reset_index()\n unstacked = pd.DataFrame({\n col: np.repeat(df[col].values, df[lst_col].str.len()) for col in df.columns.drop(lst_col)}\n ).assign(**{lst_col: np.concatenate(df[lst_col].values)})[df.columns]\n # ensure that events in the session have increasing timestamps\n unstacked['ts'] = unstacked['ts'] + unstacked.groupby('user_id').cumcount()\n unstacked.rename(columns={'sequence': 'item_id'}, inplace=True)\n return unstacked\n\n\ndef sequences_to_spfm_format(sequences, tmp_path='tmp/sequences.txt'):\n \"\"\"\n Convert a list of sequences to SPFM format and write them to `tmp_path`\n :param sequences: the list of sequences\n :param tmp_path: the path where sequences will be written in the SPFM format\n \"\"\"\n basedir = os.path.split(tmp_path)[0]\n os.makedirs(basedir, exist_ok=True)\n with open(tmp_path, 'w') as fout:\n for s in sequences:\n fout.write(' -1 '.join(map(str, s)))\n fout.write(' -2\\n')\n\n\ndef load_and_adapt(path, last_months=0):\n file_ext = os.path.splitext(path)[-1]\n if file_ext == '.csv':\n data = pd.read_csv(path, header=0)\n elif file_ext == '.hdf':\n data = pd.read_hdf(path)\n else:\n raise ValueError('Unsupported file {} having extension {}'.format(path, file_ext))\n\n col_names = ['session_id', 'user_id', 'item_id', 'ts'] + data.columns.values.tolist()[4:]\n data.columns = col_names\n\n if last_months > 0:\n def add_months(sourcedate, months):\n month = sourcedate.month - 1 + months\n year = int(sourcedate.year + month / 12)\n month = month % 12 + 1\n day = min(sourcedate.day, calendar.monthrange(year, month)[1])\n return datetime.date(year, month, day)\n\n lastdate = datetime.datetime.fromtimestamp(data.ts.max())\n firstdate = add_months(lastdate, -last_months)\n initial_unix = time.mktime(firstdate.timetuple())\n\n # filter out older interactions\n data = data[data['ts'] >= initial_unix]\n\n return data\n\n\ndef get_test_sequences(test_data, given_k):\n # we can run evaluation only over sequences longer than abs(LAST_K)\n test_sequences = test_data.loc[test_data['sequence'].map(len) > abs(given_k), 'sequence'].values\n return test_sequences\n\n\ndef get_test_sequences_and_users(test_data, given_k, train_users):\n # we can run evaluation only over sequences longer than abs(LAST_K)\n mask = test_data['sequence'].map(len) > abs(given_k)\n mask &= test_data['user_id'].isin(train_users)\n test_sequences = test_data.loc[mask, 'sequence'].values\n test_users = test_data.loc[mask, 'user_id'].values\n return test_sequences, test_users\n\n\ndef print_metrics(metrics, eval_results, rec_name, given_k, look_ahead, step, topn):\n print('Sequential evaluation for {} (GIVEN_K={}, LOOK_AHEAD={}, STEP={}, TOPN={})'.format(rec_name, given_k, look_ahead, step, topn))\n for mname, mvalue in zip(metrics.keys(), eval_results):\n print('\\t{}@{}: {:.4f}'.format(mname, topn, mvalue))\n\n\nclass WithMetadata:\n\n def load_metadata(self, path):\n \"\"\"\n loads a jsonl file. the structure of the file has to be as follows:\n - {'itemid': xxx, 'properties': [ {'property': 'xx', 'value':'xx', 'ts': xxx} ] }\n \"\"\"\n metadata = {}\n with open(path, 'r') as f:\n for line in f:\n data = json.loads(line)\n metadata[data['itemid']] = data\n return metadata\n","sub_path":"sars_tutorial/util/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"548767240","text":"#coding:utf-8\r\nfrom feather.db.mysql import util\r\n\r\n\r\ndef getTotal(filters):\r\n if filters:\r\n prers, args = util.formatCondition(filters)\r\n filterSql = 'where %s' % prers\r\n else:\r\n args = []\r\n filterSql = ''\r\n\r\n sql = \"SELECT COUNT(*) AS total FROM (SELECT opLog.*, account.userName FROM opLog LEFT JOIN account \" \\\r\n \"on opLog.accountId = account.id) as opLog \" + filterSql\r\n result = util.selectSql(sql, args=args)\r\n return result[0]['total']\r\n\r\n\r\ndef query(pagination, filters):\r\n if filters:\r\n prers, args = util.formatCondition(filters)\r\n filterSql = 'where %s' % prers\r\n else:\r\n args = []\r\n filterSql = ''\r\n\r\n current = pagination['current']\r\n pageSize = pagination['pageSize']\r\n sql = \"SELECT * FROM (SELECT opLog.*, account.userName FROM opLog LEFT JOIN account \" \\\r\n \"on opLog.accountId = account.id) as opLog \" + filterSql + \" ORDER BY `id` DESC LIMIT %s, %s\"\r\n args.extend(((current - 1) * pageSize, pageSize))\r\n return util.selectSql(sql, args=args)\r\n","sub_path":"after/server/app/share/db/dbOpLog.py","file_name":"dbOpLog.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"44190207","text":"#!/usr/bin/python3\n''' algorithm that finds a single peak in a list of integers'''\n\n\ndef find_peak(list_of_integers):\n '''find peak in list of ints'''\n list_size = len(list_of_integers)\n if list_size == 0:\n return None\n _list = list_of_integers\n for i in range(list_size):\n '''peak at the beginning'''\n if i == 1 and _list[i] < _list[0]:\n return _list[0]\n elif i == list_size - 1:\n '''peak at the end'''\n if i > 0 and _list[i] > _list[i - 1]:\n return _list[i]\n elif _list[i - 1] == _list[i]:\n '''plateau'''\n return _list[i]\n else:\n '''peak in the middle'''\n if i > 0 and _list[i] > _list[i - 1] and _list[i] > _list[i + 1]:\n return _list[i]\n","sub_path":"0x10-python-network_0/6-peak.py","file_name":"6-peak.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"559237100","text":"__author__ = 'HEEYOUNG'\n\nimport csv\nimport numpy as np\nimport sklearn\nimport sys\nfrom os import listdir\nfrom os.path import isfile, join\nimport os\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.Malware\nBASEDIR = \"H:/Malware_Data/\"\n\nif __name__ == '__main__':\n\n TrainList = []\n\n AC = db.AssemCnt\n AT = db.AssemCntTest\n AK = db.AssemKeys\n TL = db.TrainLabelds\n\n Com = AK.find().distinct(\"Com\")\n Com_info = {}\n idx = 0\n for c in Com:\n Com_info[c] = idx\n idx += 1\n\n '''\n Train = AC.find(timeout=False)\n\n TrainFeat = np.zeros((Train.count(), len(Com_info)))\n TrainLabel = np.zeros((Train.count(), 1))\n idx = 0\n for d in Train:\n for k in d.keys():\n if k == '_id':\n continue\n if k == 'Id':\n Info = TL.find_one({\"Id\": d[k]})\n TrainLabel[idx] = Info['Class']\n else:\n TrainFeat[idx, Com_info[k]] = d[k]\n idx += 1\n\n np.savetxt('TrFeat.csv', TrainFeat, delimiter=',') # Save features of training data\n np.savetxt('TrLabel.csv', TrainLabel, delimiter = ',')\n '''\n Test = AT.find(timeout=False)\n\n TestFeat = np.zeros((Test.count(), len(Com_info)))\n TestID = np.zeros((Test.count(), 1), dtype='str')\n idx = 0\n fout = open('TtID.csv', 'wb')\n writer = csv.writer(fout)\n for d in Test:\n for k in d.keys():\n if k == '_id':\n continue\n if k == 'Id':\n writer.writerow([d[k]])\n else:\n if k not in Com_info.keys():\n continue\n TestFeat[idx, Com_info[k]] = d[k]\n idx += 1\n\n np.savetxt('TtFeat.csv', TestFeat, delimiter=',')\n\n sys.exit()","sub_path":"FeatureGen.py","file_name":"FeatureGen.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"401525201","text":"import requests\nfrom bs4 import BeautifulSoup\nimport smtplib\nimport time\nURL = 'https://coinmarketcap.com/currencies/litecoin/'\nURL2 = 'https://coinmarketcap.com/currencies/bitcoin/'\nheaders = {\"User-Agent\": 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0'}\n\n\ndef check_price():\n\n page = requests.get(URL, headers=headers)\n page2 = requests.get(URL2, headers=headers)\n soup1 = BeautifulSoup(page.content, 'html.parser')\n soup2 = BeautifulSoup(soup1.prettify(), \"html.parser\")\n soup3 = BeautifulSoup(page2.content, 'html.parser')\n soup4 = BeautifulSoup(soup3.prettify(), 'html.parser')\n price = soup2.find(id=\"quote_price\").text\n price2 = soup4.find(id=\"quote_price\").text\n\n pricef1 = float(price[:18])*0.903763\n pricef2 = float(price2[:19])*0.903763\n\n print(\"Litecoin : \", pricef1, \" Euro\")\n print(\"\\nBitcoin : \", pricef2, \" Euro\")\n\n if(pricef1 > 75 and pricef2 > 10000):\n send_mail()\n elif(pricef1 > 76):\n send_mail()\n elif(pricef2 > 10000):\n send_mail()\n\n\ndef send_mail():\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login('pantpap15@gmail.com', 'okyf cnqo inry estc')\n server.sendmail(from_addr='pantpap15@gmail.com', to_addrs='thisispant@protonmail.com', msg=\"Anevikan Ta coins des : https://coinmarketcap.com/currencies\")\n print(\"\\nMail Sended !!\")\n server.quit()\n\n\nwhile(True):\n check_price()\n time.sleep(60*10)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"337476185","text":"import urllib\nimport sys\n\n##### How to run #####\n#>python soFetch.py search_term\n# \n#Example\n#>python soFetch.py 'big data'\n#######################\nif __name__ == '__main__':\n\tcmdargs = sys.argv\n\n\tsearch_term = cmdargs[1]\n\turl = 'http://careers.stackoverflow.com/jobs/feed?searchTerm='+search_term+'&location=usa'\n\tfilename = search_term+'.xml'\n\turllib.urlretrieve (url, filename)","sub_path":"teams/jobs_search/submission/soFetch.py","file_name":"soFetch.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"406411486","text":"import pandas as pd\nimport pymysql\nimport plotly\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input,Output\nfrom plotly import graph_objs as go\nfrom plotly.graph_objs import *\n\n\nmysql_user='root'\nmysql_pass='123456'\nmysql_host='118.24.26.227'\nmysql_port=3306\nmysql_data='job'\n\ncolors = [\"red\",\"rgb(0,116,217)\",\"rgb(255,65,54)\",\"rgb(133,20,75)\",\"rgb(255,133,27)\",\"green\",\"rgb(138 ,43, 226)\",\"rgb(47 ,79 ,79)\",\n \"#26CC58\", \"#28C86D\", \"#29C481\", \"#2AC093\", \"#2BBCA4\",\"#613099\",\"#F4EC15\", \"#DAF017\", \"#BBEC19\", \"9DE81B\"]\n\nmy_db=pymysql.connect(user=mysql_user,password=mysql_pass,host=mysql_host,port=mysql_port,database=mysql_data)\n\njob_data=pd.read_sql('select * from job_company',con=my_db)\n# print(job_data.head(10))\n# print(job_data.duplicated().sum())\n\n\na=job_data.groupby(by='city').size()\nb=job_data['salary_1'].groupby(job_data['city']).mean()\nc=job_data['salary_2'].groupby(job_data['city']).mean()\nbar_data=pd.concat([a,b,c],axis=1)\nprint(bar_data)\n\n\ndef bar_figure(va=20):\n s1=go.Bar(x=bar_data[bar_data.iloc[0:]>va].index[0],\n y=bar_data['salary_1'][0:va],\n name='salary_low',\n marker=go.Marker(color='#66CC99')\n )\n s2=go.Bar(x=bar_data[bar_data.iloc[0:]>va].index[0],\n y=bar_data['salary_2'][0:va],\n name='salary_high',\n marker=go.Marker(color='#99CC00'))\n data=[s1,s2]\n layout=Layout(title='不同城市的薪水区间',\n showlegend=True,\n legend=go.Legend(x=0,y=1),\n margin=go.Margin(l=0,d=0,r=0,t=0),\n )\n return go.Figure(data,layout)\n\n","sub_path":"wow/keshihua02.py","file_name":"keshihua02.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"402580321","text":"\"\"\"\n 给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。\n 如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。\n\n 示例:\n 输入: s = \"abcdefg\", k = 2\n 输出: \"bacdfeg\"\n 要求:\n 该字符串只包含小写的英文字母。\n 给定字符串的长度和 k 在[1, 10000]范围内。\n\"\"\"\n\n\nclass Solution:\n def reverseStr(self, s: str, k: int) -> str:\n \"\"\"每隔k个反转k个,末尾不够k个时全部反转\"\"\"\n s_list = list(s)\n for i in range(0, len(s), k * 2):\n s_list[i:i + k] = reversed(s_list[i: i + k])\n return \"\".join(s_list)\n","sub_path":"algorithm/LeetCode_541_反转字符串II.py","file_name":"LeetCode_541_反转字符串II.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"542563136","text":"#!/usr/bin/python3\n\nimport json\nimport sys\nfrom collections import defaultdict\n\nIGNORED_KEYS = {\n 'price', 'choice', 'leave', 'arrive', 'parking', 'internet', 'name',\n 'day', 'depart', 'type', 'food', 'area' , 'dest'\n}\n\ndef main():\n data = json.load(sys.stdin)\n\n ontology = defaultdict(set)\n\n for dialogue in data:\n for turn in dialogue['dialogue']:\n for sysact in turn['system_acts']:\n if not isinstance(sysact, (list, tuple)):\n continue\n\n key, value = sysact\n if key == 'none' or key in IGNORED_KEYS:\n continue\n ontology[key].add(value)\n\n ontology2 = dict()\n for key in ontology:\n ontology2[key] = list(ontology[key])\n\n json.dump(ontology2, fp=sys.stdout, indent=2)\n\n print(list(ontology.keys()), file=sys.stderr)\n\n\nif __name__ == '__main__':\n main()","sub_path":"get-sys-ontology.py","file_name":"get-sys-ontology.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"201870420","text":"# coding=utf-8\nimport os\nimport tempfile\n\n\nclass AdbExt(object):\n def __init__(self, util):\n self.__util = util\n self.temp_name = 'temp' # 如果是多个进程,可以修改这个变量,保证多个手机在pc上的文件不会冲突\n self.temp_pc_dir_path = tempfile.gettempdir()\n self.temp_device_dir_path = '/data/local/tmp'\n\n def get_pc_temp_name(self):\n return os.path.join(self.temp_pc_dir_path, self.temp_name)\n\n def dump(self, pc_name=None, pc_dir_path=None, device_path=None):\n pc_name = pc_name if pc_name else '{}.xml'.format(self.temp_name)\n pc_path, device_path = self.__get_pc_device_path(pc_name, pc_dir_path, device_path) # 获取绝对路径\n self.delete_from_pc(pc_path) # 删除电脑文件\n self.delete_from_device(device_path) # 删除手机文件\n try_count = 3\n while try_count: # 如果dump失败,多次尝试\n out = self.__util.shell('uiautomator dump {}'.format(device_path))\n if 'UI hierchary dumped to' in out: # 如果dump成功,退出循环\n break\n try_count -= 1\n if try_count == 0:\n raise NameError('dump xml fail!')\n self.pull(pc_name, pc_dir_path, device_path)\n\n def delete_from_device(self, path):\n self.__util.shell('rm -rf {}'.format(path))\n\n def delete_from_pc(self, path):\n if os.path.exists(path): os.remove(path)\n\n def __get_pc_device_path(self, pc_name, pc_dir_path=None, device_path=None):\n pc_dir_path = pc_dir_path if pc_dir_path else self.temp_pc_dir_path\n pc_path = '{}/{}'.format(pc_dir_path, pc_name)\n device_path = device_path if device_path else '{}/{}'.format(self.temp_device_dir_path, pc_name)\n return pc_path, device_path\n\n def screenshot(self, pc_name=None, pc_dir_path=None, use_pull=True):\n pc_name = pc_name if pc_name else '{}.png'.format(self.temp_name)\n pc_path, device_path = self.__get_pc_device_path(pc_name, pc_dir_path, None)\n self.delete_from_pc(pc_path) # 删除电脑文件\n if use_pull:\n self.__util.shell('screencap -p {}'.format(device_path))\n self.__util.adb('pull {} {}'.format(device_path, pc_path))\n return\n arg = 'adb -s {} exec-out screencap -p'.format(self.__util.sn)\n self.__util.cmd_out_save(arg, pc_path, mode='wb') # 这个命令可以直接将截图保存到电脑,节省了pull操作\n\n def pull(self, pc_name=None, pc_dir_path=None, device_path=None):\n pc_path, device_path = self.__get_pc_device_path(pc_name, pc_dir_path, device_path)\n self.__util.adb('pull {} {}'.format(device_path, pc_path))\n\n def click(self, x, y):\n self.__util.shell('input tap {} {}'.format(x, y))\n\n def stop(self, pkg):\n self.__util.shell('am force-stop {}'.format(pkg))\n\n def input(self, text):\n self.__util.shell('input text \"{}\"'.format(text.replace('&', '\\&')))\n\n def back(self, times=1):\n while times:\n self.__util.shell('input keyevent 4')\n times -= 1\n\n def enter(self, times=1):\n while times:\n self.__util.shell('input keyevent 66')\n times -= 1\n\n def swipe(self, e1=None, e2=None, start_x=None, start_y=None, end_x=None, end_y=None, duration=\" \"):\n \"\"\"\n 滑动事件,Android 4.4以上可选duration(ms)\n usage: swipe(e1, e2)\n swipe(e1, end_x=200, end_y=500)\n swipe(start_x=0.5, start_y=0.5, e2)\n \"\"\"\n if e1 is not None:\n start_x = e1[0]\n start_y = e1[1]\n if e2 is not None:\n end_x = e2[0]\n end_y = e2[1]\n if 0 < start_x < 1:\n start_x = start_x * self.width\n if 0 < start_y < 1:\n start_y = start_y * self.height\n if 0 < end_x < 1:\n end_x = end_x * self.width\n if 0 < end_y < 1:\n end_y = end_y * self.height\n\n self.__util.shell(\n \"input swipe %s %s %s %s %s\" % (str(start_x), str(start_y), str(end_x), str(end_y), str(duration)))\n\n def clear(self, pkg):\n \"\"\"\n 重置应用\n :param pkg:\n :return:\n \"\"\"\n self.__util.shell('pm clear {}'.format(pkg))\n\n def wake_up(self):\n '''\n 点亮屏幕\n :return:\n '''\n self.__util.shell('input keyevent KEYCODE_WAKEUP')\n","sub_path":"adbui/adb_ext.py","file_name":"adb_ext.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"364187521","text":"import torch\n\ndevice = torch.device(\"cpu\")\nsign = torch.sign\n\nclass Hopfield(object):\n \n def __init__(self,visible=100,hidden=0,bias = False):\n \n if hidden == 0:\n self.hidden_present = False\n else:\n self.hidden_present = True\n\n self.hidden_units = hidden\n self.visible_units = visible\n self.device = device\n\n self.total_units = hidden + visible\n\n self.W = torch.rand((self.total_units,self.total_units)).to(device)\n\n self.bias = bias\n if not bias:\n self.b = torch.rand((self.total_units,1)).to(device)\n else:\n self.b = torch.zeros((self.total_units,1)).to(device)\n\n self.state = torch.sign(torch.randn((self.total_units,1)).to(device))\n\n def energy(self):\n Wy = torch.mm(self.W,self.state)\n return - torch.mm(self.state.t(),Wy)\n\n def indexUpdate(self,index):\n Wj = self.W[index].view(self.W[index].shape[0],-1).t()\n self.state[index] = sign(self.b[index] + torch.mm(Wj,self.state))\n\n def seqUpdate(self):\n\n for i in range(self.total_units):\n self.indexUpdate(i)\n print(i,self.energy())","sub_path":"models/hopfield.py","file_name":"hopfield.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"214388496","text":"\nimport sys\nsys.stdin=open('input.txt','r')\n\ndef selectmax(top, bottom):\n if (top==6 and bottom==5) or (top==5 and bottom==6):\n m=4\n elif top==6 or bottom==6:\n m=5\n else: m=6\n return m\n\ndef select(N,maxn):\n for bg in range(6):\n n=0\n top=arr[n][bg]\n if bg&1:\n s=selectmax(top, arr[0][bg-1])\n else:\n s=selectmax(top, arr[0][bg+1])\n\n n=1\n while n 2:\n value = fib(n-1) + fib(n-2)\n\n #cache value and return it\n cache[n] = value\n return value \n \n\nfor n in range(1, 101):\n print(n, ':', fib(n))","sub_path":"recursion/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"581974101","text":"import pyttsx3\r\nimport speech_recognition as sr\r\nimport datetime\r\nimport wikipedia\r\nimport webbrowser\r\nimport os\r\nimport smtplib\r\nimport subprocess\r\nimport wolframalpha\r\nclient = wolframalpha.Client('(your wolframalpha_id')\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n# print(voices[2].id)\r\nengine.setProperty('voice', voices[1].id)\r\n\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good Morning!\")\r\n print(\"Good Morning!\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\")\r\n print(\"Good Afternoon!\")\r\n\r\n else:\r\n speak(\"Good Evening!\")\r\n print(\"Good Evening!\")\r\n\r\n speak(\"I am zira Sir. Please tell me how may I help you\")\r\n print(\"I am zira Sir. Please tell me how may I help you\")\r\n\r\ndef takeCommand():\r\n #It takes microphone input from the user and returns string output\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold = 2\r\n r.energy_threshold = 20000\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\")\r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n # print(e)\r\n print(\"Say again please...\")\r\n speak(\"Say again please...\")\r\n return \"\"\r\n return query\r\n\r\ndef sendEmail(to, content):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login('Your_mail_id', '(your_Password)')\r\n server.sendmail('Your_mail_id', to, content)\r\n server.close()\r\n\r\ndef note(text):\r\n date = datetime.datetime.now()\r\n file_name = str(date).replace(\":\", \"-\") + \"-note.txt\"\r\n with open(file_name, \"w\") as f:\r\n f.write(text)\r\n sublime =\"D:\\\\Sublime Text 3\\\\sublime_text\"\r\n\r\n subprocess.Popen([sublime, file_name])\r\n\r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n \r\n query = takeCommand().lower()\r\n\r\n\r\n if 'wikipedia' in query:\r\n speak('Searching Wikipedia...')\r\n query = query.replace(\"search\", \"\")\r\n query = query.replace(\"on wikipedia\", \"\")\r\n results = wikipedia.summary(query, sentences=5)\r\n speak(\"According to Wikipedia\")\r\n print(results)\r\n speak(results)\r\n elif 'hello' in query:\r\n speak(\"how are you?\")\r\n elif 'goodbye' in query:\r\n speak(\"OK, bye sir\")\r\n break\r\n\r\n elif 'youtube' in query:\r\n speak(\"Opening in youtube\")\r\n query = query.replace(\"play\",\"\")\r\n query = query.replace(\"on youtube\",\"\")\r\n query = query.replace(\" \", \"\")\r\n webbrowser.open(\"http://www.youtube.com/results?search_query=\" + ''.join(query))\r\n elif 'search book on' in query:\r\n speak(\"searching!\")\r\n query=query.replace(\"search book on\",\"\")\r\n webbrowser.open(\"https://libgen.is/search.php?req=\"+''.join(query))\r\n\r\n elif 'open google' in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'google' in query:\r\n query = query.replace(\"search\", \"\")\r\n query = query.replace(\"on google\", \"\")\r\n webbrowser.open(\"https://www.google.com/search?q=\" + ''.join(query))\r\n\r\n\r\n elif 'open stackoverflow' in query:\r\n webbrowser.open(\"stackoverflow.com\")\r\n\r\n elif 'open gmail' in query:\r\n webbrowser.open(\"https://mail.google.com/mail/u/0/#inbox\")\r\n\r\n\r\n elif 'play music' in query:\r\n music_dir = 'D:\\\\New folder\\song\\\\00-Kaabil (2016)'\r\n songs = os.listdir(music_dir)\r\n print(songs)\r\n os.startfile(os.path.join(music_dir, songs[0]))\r\n\r\n elif 'the time' in query:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n speak(f\"Sir, the time is {strTime}\")\r\n\r\n elif 'open sublime' in query:\r\n codePath = \"D:\\\\Sublime Text 3\\\\sublime_text\"\r\n os.startfile(codePath)\r\n elif 'open notepad' in query:\r\n notepad =\"C:\\\\WINDOWS\\\\system32\\\\notepad\"\r\n os.startfile(notepad)\r\n\r\n elif 'make a note' in query:\r\n speak(\"What would you like me to write down?\")\r\n note_text = takeCommand()\r\n note(note_text)\r\n speak(\"I've made a note of that.\")\r\n\r\n elif 'send email' in query:\r\n try:\r\n speak(\"What should I say?\")\r\n content = takeCommand()\r\n to = \"recievers_mail_id\"\r\n sendEmail(to, content)\r\n speak(\"Email has been sent!\")\r\n\r\n except Exception as e:\r\n print(e)\r\n speak(\"Sorry. I am not able to send this email\")\r\n\r\n else:\r\n try:\r\n try:\r\n res = client.query(query)\r\n results = next(res.results).text\r\n print(results)\r\n speak(results)\r\n except:\r\n results = wikipedia.summary(query, sentences=2)\r\n speak(results)\r\n except:\r\n speak('I don\\'t know Sir! Google is smarter than me!')\r\n\r\n webbrowser.open('www.google.com')","sub_path":"Voice Assistant/Voice_assistant.py","file_name":"Voice_assistant.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"600641569","text":"#dec model\r\n\r\n# Importing Libraries\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport month\r\n\r\n# Importing the dataset\r\ndataset = month.dec_data\r\nX = dataset[:,:4]\r\ny = dataset[:,4:]\r\n\r\n# dividing the dataset into features and target values\r\n#Choosing the YearAvgI_HP as the target value and Longitudes , latitudes ,elevation and the ExtSR as the features\r\nX1 = dataset[:,:4]\r\ny1 = y[:,0:1]\r\n\r\n# Splitting the dataset into training and test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train1,X_test1,y_train1,y_test1 = train_test_split(X1,y1,test_size = 0.3,random_state = 0)\r\n\r\n#fitting simple linear regression model to Training set\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor1 = LinearRegression()\r\nregressor1.fit(X_train1 , y_train1)\r\n\r\n#predictinfg the Test result set\r\ny_test_predict1 = regressor1.predict(X_test1)\r\n\r\n\r\n#Splitting the dataset for predecting the next feature YearAvgI_IncP\r\n#Now for finding the YearAvgI_Inc, we consider the predicted value of YearAvgI_HP as also a feature as it shows a high correlation\r\n\r\nX2 = dataset[:,0:5]\r\ny2 = y[:,1:2]\r\n\r\n# Splitting the dataset into training and test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train2,X_test2,y_train2,y_test2 = train_test_split(X2,y2,test_size = 0.3,random_state = 0)\r\n\r\n#fitting simple linear regression model to Training set\r\nregressor2 = LinearRegression()\r\nregressor2.fit(X_train2 , y_train2)\r\n\r\n#predictinfg the Test result set\r\ny_test_predict2 = regressor2.predict(X_test2)\r\n\r\n\r\n# Using the Features Longitude,latitude,elevation ExtSR for predicting the OptSlopeAngle\r\nX_train3,X_test3,y_train3,y_test3 = train_test_split(X,y[:,2:3],test_size = 0.3,random_state = 0)\r\nregressor3 = LinearRegression()\r\nregressor3.fit(X_train3,y_train3)\r\n\r\ny_test_predict3 = regressor3.predict(X_test3)\r\n\r\n\r\n#Predicting the YearAvgI_B\r\nX4 = dataset[:,:7]\r\ny4 = y[:,3:4]\r\nX_train4,X_test4,y_train4,y_test4 = train_test_split(X4,y4,test_size = 0.3,random_state = 0)\r\n\r\nregressor4 = LinearRegression()\r\nregressor4.fit(X_train4,y_train4)\r\n\r\ny_test_predict4 = regressor4.predict(X_test4)\r\n\r\n\r\n#Predecting the val of Ratio_D_G\r\nX5 = dataset[:,:8]\r\ny5 = y[:,4:5]\r\n\r\nX_train5,X_test5,y_train5,y_test5 = train_test_split(X5,y5,test_size = 0.3,random_state = 0)\r\n\r\nregressor5 = LinearRegression()\r\nregressor5.fit(X_train5,y_train5)\r\n\r\ny_test_predict5 = regressor5.predict(X_test5)\r\n\r\n'''# Plots\r\n\r\nplt.scatter(X_test1[:,0:1] , y_test1 , color = 'red')\r\nplt.scatter(X_test1[:,0:1] , regressor1.predict(X_test1) , color = 'blue')\r\nplt.title('longitude VS MonthAvgI_HP(December)')\r\nplt.xlabel('Longitude')\r\nplt.ylabel('MonthAvgI_HP')\r\nplt.show()\r\n\r\n\r\nplt.scatter(X_test2[:,0:1] , y_test2 , color = 'red')\r\nplt.scatter(X_test2[:,0:1] , regressor2.predict(X_test2) , color = 'blue')\r\nplt.title('longitude VS YearAvgI_IncP(December)')\r\nplt.xlabel('Longitude')\r\nplt.ylabel('YearAvgI_IncP')\r\nplt.show()\r\n\r\n\r\nplt.scatter(X_test3[:,0:1] , y_test3 , color = 'red')\r\nplt.scatter(X_test3[:,0:1] , regressor3.predict(X_test3) , color = 'blue')\r\nplt.title('longitude VS OptSlopeAngle(December)')\r\nplt.xlabel('Longitude')\r\nplt.ylabel('OptSopeAngle')\r\nplt.show()\r\n\r\nplt.scatter(X_test4[:,0:1] , y_test4 , color = 'red')\r\nplt.scatter(X_test4[:,0:1] , regressor4.predict(X_test4) , color = 'blue')\r\nplt.title('longitude VS YearAvgI_B(December)')\r\nplt.xlabel('Longitude')\r\nplt.ylabel('YearAvgI_B')\r\nplt.show()\r\n\r\n\r\nplt.scatter(X_test5[:,0:1] , y_test5 , color = 'red')\r\nplt.scatter(X_test5[:,0:1] , regressor5.predict(X_test5) , color = 'blue')\r\nplt.title('longitude VS Ratio_D_G(December)')\r\nplt.xlabel('Longitude')\r\nplt.ylabel('Ratio_D_G')\r\nplt.show()\r\n'''","sub_path":"dec_model.py","file_name":"dec_model.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"284753458","text":"import os, sys\nimport glob\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport re\nimport nltk\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n# gendoc.py -- Don't forget to put a reasonable amount code comments\n# in so that we better understand what you're doing when we grade!\n\n# add whatever additional imports you may need here\n\n\n\"\"\"\nNotes on pandas\n\"\"\"\n# df = pd.read_csv('ransom.csv') read csv files. we can print the dataframe print(df)\n# inspecting data frame df.head()\n# df.info()\n# selects a column in the file (suspect): suspect = credit_records['suspect'] or credit_records.suspect\n# select rows: you access by index like in lists\n\n\n\n\"\"\"\nPart 1\n\"\"\"\n\n#Opening the files, preprocessing the text. Lowercase, strip punctuation.\ndef vocabulary_list(directory, m=None): # add arg.foldername in the main when we call this function in the main bc the argument name directory is arbitrary\n \"\"\"\n Returns vocabulary list containing all words in all documents in every\n subfolder\n \"\"\"\n vocab_list = []\n for subfolder in os.listdir(directory):\n path_to_subfolder = os.path.join(directory, subfolder)\n for file in os.listdir(path_to_subfolder):\n path_to_file = os.path.join(path_to_subfolder, file)\n with open(path_to_file, \"r\", encoding=\"utf8\") as f:\n text = f.read()\n remove_punctuation = re.sub(r\"/[^\\s]+\", \"\", text).lower()\n clean_words = remove_punctuation.split()\n for word in clean_words:\n vocab_list.append(word)\n vocab_dict = dict(nltk.FreqDist(vocab_list))\n s=[(k,vocab_dict[k]) for k in sorted(vocab_dict, key=vocab_dict.get,reverse=True)]\n if m:\n s = s[:m]\n\n return [k for k,v in s]\n\ndef preprocessing(filenames):\n preprocess_text = []\n for f in filenames:\n file = open(f, \"r\", encoding = \"utf8\")\n text = file.read()\n remove_punctuation = re.sub(r\"/[^\\s]+\", \"\", text).lower()\n preprocess_text.append(remove_punctuation)\n return preprocess_text\n\n\ndef preprocessing_and_labels(directory, m=None):\n \"\"\"\n Creates a main dictionary with the topic + document name as key and\n subdictionaries with words as keys and word counts values as values\n \"\"\"\n label_maker = {} # main dict\n vocab = vocabulary_list(directory, m)\n vocab_dict = dict.fromkeys(vocab, 0)\n for topic in os.listdir(directory):\n path_to_subfolder = os.path.join(directory, topic) # we join the path from main folder to every subfolder and subsequently to every text doc inside them\n # this makes a dict from every word from vocab list and count of 0 to start with\n\n for file in os.listdir(path_to_subfolder):\n path_to_file = os.path.join(path_to_subfolder, file)\n counts = vocab_dict.copy() # smaller dict\n\n with open(path_to_file, \"r\", encoding=\"utf8\") as f:\n text = f.read()\n remove_punctuation = re.sub(r\"[^\\w\\s\\d]\", \"\", text).lower()\n clean_words = remove_punctuation.split()\n for word in clean_words:\n if word in vocab:\n counts[word] += 1\n label_maker[topic+\" \"+file] = counts # joining the name of subfolder and the doc in one single name and make it the key\n return label_maker\n\n\n\ndef vector_builder(directory, m=None):\n \"\"\"\n Create a vector or lists of appended values/counts from previously created\n dictionary.\n Every vector (little list) will be converted into an array and then into\n a dataframe from pandas.\n \"\"\"\n # this main vector list will be later converted into a np.array() which is basically a list of lists\n bigdict = preprocessing_and_labels(directory, m) # contains all smaller dictionaries which are each doc\n\n for label in bigdict.keys():\n main_vector_list = []\n for word, count in bigdict[label].items():\n main_vector_list.append(count)\n bigdict[label] = main_vector_list\n\n\n return bigdict\n\n\n\ndef matrix_builder(directory, m=None):\n \"\"\"\n Convert main_vector (which is a dictionary) into a dataframe from pandas.\n \"\"\"\n main_vector = vector_builder(directory, m)\n # matrix_array = np.array(main_vector)\n columns = vocabulary_list(directory, m) # this is a lists with all words\n matrix_dataframe = pd.DataFrame.from_dict(main_vector, orient='index', dtype=None, columns=columns)\n duplicates_list = matrix_dataframe[matrix_dataframe.duplicated()].index.tolist()\n matrix_dataframe = matrix_dataframe.drop_duplicates()\n print(\"These duplicated vectors have been dropped: \")\n for duplicate in duplicates_list:\n print(duplicate)\n return matrix_dataframe, main_vector, columns\n\n\ndef file_creator(dataframe):\n \"\"\"\n Prints dataframe into a new file\n \"\"\"\n dataframe.to_csv(args.outputfile, header=True)\n print(dataframe)\n return dataframe\n\n\n\n\n\n\n\n#import pdb;pdb.set_trace()\n\n\nparser = argparse.ArgumentParser(description=\"Generate term-document matrix.\")\nparser.add_argument(\"-T\", \"--tfidf\", action=\"store_true\", help=\"Apply tf-idf to the matrix.\")\nparser.add_argument(\"-S\", \"--svd\", metavar=\"N\", dest=\"svddims\", type=int,\n default=None,\n help=\"Use TruncatedSVD to truncate to N dimensions\")\nparser.add_argument(\"-B\", \"--base-vocab\", metavar=\"M\", dest=\"basedims\",\n type=int, default=None,\n help=\"Use the top M dims from the raw counts before further processing\")\nparser.add_argument(\"foldername\", type=str,\n help=\"The base folder name containing the two topic subfolders.\")\nparser.add_argument(\"outputfile\", type=str,\n help=\"The name of the output file for the matrix data.\")\n\n\n\n\n\nargs = parser.parse_args()\ndocuments = []\nfor topic in os.listdir(args.foldername):\n path_to_subfolder = os.path.join(args.foldername,\n topic) # we join the path from main folder to every subfolder and subsequently to every text doc inside them\n # this makes a dict from every word from vocab list and count of 0 to start with\n\n for file in os.listdir(path_to_subfolder):\n documents.append(os.path.join(path_to_subfolder, file))\nfiles_data = preprocessing(documents)\ndataframe, main_vector, columns = matrix_builder(args.foldername, args.basedims) # dataframes are excel files. you can output info very easily\nmain_array = np.array(list(main_vector.values()),dtype=float)\nmain_labels = [x for x in main_vector.keys()]\nfile_creator(dataframe)\nprint(\"Writing matrix to {}.\".format(args.outputfile))\n\nprint(\"Loading data from directory {}.\".format(args.foldername))\n\nif not args.basedims:\n print(\"Using full vocabulary.\")\nelse:\n print(\"Using only top {} terms by raw count.\".format(args.basedims))\n\nif args.tfidf:\n print(\"Applying tf-idf to raw counts.\")\n tfidfconverter = TfidfVectorizer(max_features = args.basedims)\n tfidfvector = tfidfconverter.fit_transform(files_data).toarray()\n tfidf_df = pd.DataFrame(data=tfidfvector,\n index= [x for x in documents],\n columns = tfidfconverter.get_feature_names())\n tfidf_df.to_csv(\"output.csv\", encoding=\"utf8\")\n\nif args.svddims:\n print(\"Truncating matrix to {} dimensions via singular value decomposition.\".format(args.svddims))\n svd = TruncatedSVD(n_components=args.svddims)\n svdT = svd.fit_transform(main_array)\n svdT_df = pd.DataFrame(data=svdT,\n index = main_labels,\n columns = [i for i in range(0,args.svddims)])\n svdT_df.to_csv(\"svdt_countvector.csv\", encoding=\"utf-8\")\n if args.tfidf:\n svd = TruncatedSVD(n_components=args.svddims)\n svdT = svd.fit_transform(tfidfvector)\n svdT_df = pd.DataFrame(data=svdT,\n index=[x for x in documents],\n columns=[i for i in range(0, args.svddims)])\n svdT_df.to_csv(\"svdt_tfidf.csv\", encoding=\"utf-8\")\n# THERE ARE SOME ERROR CONDITIONS YOU MAY HAVE TO HANDLE WITH CONTRADICTORY\n# PARAMETERS.\n","sub_path":"gendoc.py","file_name":"gendoc.py","file_ext":"py","file_size_in_byte":8273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"326998620","text":"import numpy as np\nimport copy\nfrom scipy.interpolate import PchipInterpolator, interp1d\nimport openmdao.api as om\nfrom wisdem.rotorse.geometry_tools.geometry import AirfoilShape, trailing_edge_smoothing, remap2grid\nfrom wisdem.rotorse.parametrize_rotor import ParametrizeBladeAero, ParametrizeBladeStruct\nfrom wisdem.commonse.utilities import arc_length, arc_length_deriv\n\nclass WindTurbineOntologyOpenMDAO(om.Group):\n # Openmdao group with all wind turbine data\n \n def initialize(self):\n self.options.declare('modeling_options')\n self.options.declare('opt_options')\n \n def setup(self):\n modeling_options = self.options['modeling_options']\n opt_options = self.options['opt_options']\n \n # Material dictionary inputs\n self.add_subsystem('materials', Materials(mat_init_options = modeling_options['materials']))\n \n # Airfoil dictionary inputs\n if modeling_options['flags']['airfoils']:\n airfoils = om.IndepVarComp()\n af_init_options = modeling_options['airfoils']\n n_af = af_init_options['n_af'] # Number of airfoils\n n_aoa = af_init_options['n_aoa']# Number of angle of attacks\n n_Re = af_init_options['n_Re'] # Number of Reynolds, so far hard set at 1\n n_tab = af_init_options['n_tab']# Number of tabulated data. For distributed aerodynamic control this could be > 1\n n_xy = af_init_options['n_xy'] # Number of coordinate points to describe the airfoil geometry\n airfoils.add_discrete_output('name', val=n_af * [''], desc='1D array of names of airfoils.')\n airfoils.add_output('ac', val=np.zeros(n_af), desc='1D array of the aerodynamic centers of each airfoil.')\n airfoils.add_output('r_thick', val=np.zeros(n_af), desc='1D array of the relative thicknesses of each airfoil.')\n airfoils.add_output('aoa', val=np.zeros(n_aoa), units='rad', desc='1D array of the angles of attack used to define the polars of the airfoils. All airfoils defined in openmdao share this grid.')\n airfoils.add_output('Re', val=np.zeros(n_Re), desc='1D array of the Reynolds numbers used to define the polars of the airfoils. All airfoils defined in openmdao share this grid.')\n airfoils.add_output('cl', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the lift coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n airfoils.add_output('cd', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the drag coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n airfoils.add_output('cm', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the moment coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n # Airfoil coordinates\n airfoils.add_output('coord_xy', val=np.zeros((n_af, n_xy, 2)), desc='3D array of the x and y airfoil coordinates of the n_af airfoils.')\n self.add_subsystem('airfoils', airfoils)\n \n # Blade inputs and connections from airfoils\n if modeling_options['flags']['blade']:\n self.add_subsystem('blade', Blade(blade_init_options = modeling_options['blade'], af_init_options = modeling_options['airfoils'], opt_options = opt_options))\n self.connect('airfoils.name', 'blade.interp_airfoils.name')\n self.connect('airfoils.r_thick', 'blade.interp_airfoils.r_thick')\n self.connect('airfoils.coord_xy','blade.interp_airfoils.coord_xy')\n self.connect('airfoils.aoa', 'blade.interp_airfoils.aoa')\n self.connect('airfoils.cl', 'blade.interp_airfoils.cl')\n self.connect('airfoils.cd', 'blade.interp_airfoils.cd')\n self.connect('airfoils.cm', 'blade.interp_airfoils.cm')\n \n # Hub inputs\n if modeling_options['flags']['hub']:\n self.add_subsystem('hub', Hub())\n \n # Nacelle inputs\n if modeling_options['flags']['nacelle']:\n nacelle = om.IndepVarComp()\n # Outer shape bem\n nacelle.add_output('uptilt', val=0.0, units='rad', desc='Nacelle uptilt angle. A standard machine has positive values.')\n nacelle.add_output('distance_tt_hub', val=0.0, units='m', desc='Vertical distance from tower top to hub center.')\n nacelle.add_output('overhang', val=0.0, units='m', desc='Horizontal distance from tower top to hub center.')\n # Mulit-body properties\n nacelle.add_output('above_yaw_mass', val=0.0, units='kg', desc='Mass of the nacelle above the yaw system')\n nacelle.add_output('yaw_mass', val=0.0, units='kg', desc='Mass of yaw system')\n nacelle.add_output('nacelle_cm', val=np.zeros(3), units='m', desc='Center of mass of the component in [x,y,z] for an arbitrary coordinate system')\n nacelle.add_output('nacelle_I', val=np.zeros(6), units='kg*m**2', desc=' moments of Inertia for the component [Ixx, Iyy, Izz] around its center of mass')\n # Drivetrain parameters\n nacelle.add_output('gear_ratio', val=0.0)\n nacelle.add_output('shaft_ratio', val=0.0)\n nacelle.add_discrete_output('planet_numbers', val=np.zeros(3))\n nacelle.add_output('shrink_disc_mass', val=0.0, units='kg')\n nacelle.add_output('carrier_mass', val=0.0, units='kg')\n nacelle.add_output('flange_length', val=0.0, units='m')\n nacelle.add_output('gearbox_input_xcm',val=0.0, units='m')\n nacelle.add_output('hss_input_length', val=0.0, units='m')\n nacelle.add_output('distance_hub2mb', val=0.0, units='m')\n nacelle.add_discrete_output('yaw_motors_number', val = 0)\n nacelle.add_output('gearbox_efficiency', val=0.0, desc='Efficiency of the gearbox. Set it equal to 1 for direct-drive machines')\n nacelle.add_output('generator_efficiency', val=0.0, desc='Efficiency of the generator.')\n self.add_subsystem('nacelle', nacelle)\n \n # Tower inputs\n if modeling_options['flags']['tower']:\n self.add_subsystem('tower', Tower(tower_init_options = modeling_options['tower']))\n\n if modeling_options['flags']['monopile']:\n self.add_subsystem('monopile', Monopile(monopile_init_options = modeling_options['monopile']))\n \n # Foundation inputs\n if modeling_options['flags']['foundation']:\n foundation_ivc = self.add_subsystem('foundation', om.IndepVarComp())\n foundation_ivc.add_output('height', val=0.0, units='m', desc='Foundation height in respect to the ground level.')\n\n # Control inputs\n if modeling_options['flags']['control']:\n ctrl_ivc = self.add_subsystem('control', om.IndepVarComp())\n ctrl_ivc.add_output('rated_power', val=0.0, units='W', desc='Electrical rated power of the generator.')\n ctrl_ivc.add_output('V_in', val=0.0, units='m/s', desc='Cut in wind speed. This is the wind speed where region II begins.')\n ctrl_ivc.add_output('V_out', val=0.0, units='m/s', desc='Cut out wind speed. This is the wind speed where region III ends.')\n ctrl_ivc.add_output('minOmega', val=0.0, units='rad/s', desc='Minimum allowed rotor speed.')\n ctrl_ivc.add_output('maxOmega', val=0.0, units='rad/s', desc='Maximum allowed rotor speed.')\n ctrl_ivc.add_output('max_TS', val=0.0, units='m/s', desc='Maximum allowed blade tip speed.')\n ctrl_ivc.add_output('max_pitch_rate', val=0.0, units='rad/s', desc='Maximum allowed blade pitch rate')\n ctrl_ivc.add_output('max_torque_rate', val=0.0, units='N*m/s', desc='Maximum allowed generator torque rate')\n ctrl_ivc.add_output('rated_TSR', val=0.0, desc='Constant tip speed ratio in region II.')\n ctrl_ivc.add_output('rated_pitch', val=0.0, units='rad', desc='Constant pitch angle in region II.')\n\n # Wind turbine configuration inputs\n conf_ivc = self.add_subsystem('configuration', om.IndepVarComp())\n conf_ivc.add_discrete_output('ws_class', val='', desc='IEC wind turbine class. I - offshore, II coastal, III - land-based, IV - low wind speed site.')\n conf_ivc.add_discrete_output('turb_class', val='', desc='IEC wind turbine category. A - high turbulence intensity (land-based), B - mid turbulence, C - low turbulence (offshore).')\n conf_ivc.add_discrete_output('gearbox_type', val='geared', desc='Gearbox configuration (geared, direct-drive, etc.).')\n conf_ivc.add_discrete_output('rotor_orientation', val='upwind', desc='Rotor orientation, either upwind or downwind.')\n conf_ivc.add_discrete_output('n_blades', val=3, desc='Number of blades of the rotor.')\n\n # Environment inputs\n if modeling_options['flags']['environment']:\n env_ivc = self.add_subsystem('env', om.IndepVarComp())\n env_ivc.add_output('rho_air', val=1.225, units='kg/m**3', desc='Density of air')\n env_ivc.add_output('mu_air', val=1.81e-5, units='kg/(m*s)', desc='Dynamic viscosity of air')\n env_ivc.add_output('shear_exp', val=0.2, desc='Shear exponent of the wind.')\n env_ivc.add_output('speed_sound_air', val=340., units='m/s', desc='Speed of sound in air.')\n env_ivc.add_output('weibull_k', val=2.0, desc='Shape parameter of the Weibull probability density function of the wind.')\n env_ivc.add_output('rho_water', val=1025., units='kg/m**3', desc='Density of ocean water')\n env_ivc.add_output('mu_water', val=1.3351e-3, units='kg/(m*s)', desc='Dynamic viscosity of ocean water')\n env_ivc.add_output('water_depth', val=0.0, units='m', desc='Water depth for analysis. Values > 0 mean offshore')\n env_ivc.add_output('hsig_wave', val=0.0, units='m', desc='Significant wave height')\n env_ivc.add_output('Tsig_wave', val=0.0, units='s', desc='Significant wave period')\n env_ivc.add_output('G_soil', val=140e6, units='N/m**2', desc='Shear stress of soil')\n env_ivc.add_output('nu_soil', val=0.4, desc='Poisson ratio of soil')\n\n if modeling_options['flags']['bos']: \n bos_ivc = self.add_subsystem('bos', om.IndepVarComp())\n bos_ivc.add_output('plant_turbine_spacing', 7, desc='Distance between turbines in rotor diameters')\n bos_ivc.add_output('plant_row_spacing', 7, desc='Distance between turbine rows in rotor diameters')\n bos_ivc.add_output('commissioning_pct', 0.01)\n bos_ivc.add_output('decommissioning_pct', 0.15)\n bos_ivc.add_output('distance_to_substation', 50.0, units='km')\n bos_ivc.add_output('distance_to_interconnection', 5.0, units='km')\n if modeling_options['offshore']:\n bos_ivc.add_output('site_distance', 40.0, units='km')\n bos_ivc.add_output('distance_to_landfall', 40.0, units='km')\n bos_ivc.add_output('port_cost_per_month', 2e6, units='USD/mo')\n bos_ivc.add_output('site_auction_price', 100e6, units='USD')\n bos_ivc.add_output('site_assessment_plan_cost', 1e6, units='USD')\n bos_ivc.add_output('site_assessment_cost', 25e6, units='USD')\n bos_ivc.add_output('construction_operations_plan_cost', 2.5e6, units='USD')\n bos_ivc.add_output('boem_review_cost', 0.0, units='USD')\n bos_ivc.add_output('design_install_plan_cost', 2.5e6, units='USD')\n else:\n bos_ivc.add_output('interconnect_voltage', 130.0, units='kV')\n \n # Cost analysis inputs\n if modeling_options['flags']['costs']:\n costs_ivc = self.add_subsystem('costs', om.IndepVarComp())\n costs_ivc.add_discrete_output('turbine_number', val=0, desc='Number of turbines at plant')\n costs_ivc.add_output('offset_tcc_per_kW' ,val=0.0, units='USD/kW', desc='Offset to turbine capital cost')\n costs_ivc.add_output('bos_per_kW' , val=0.0, units='USD/kW', desc='Balance of station/plant capital cost')\n costs_ivc.add_output('opex_per_kW', val=0.0, units='USD/kW/yr', desc='Average annual operational expenditures of the turbine')\n costs_ivc.add_output('wake_loss_factor', val=0.0, desc='The losses in AEP due to waked conditions')\n costs_ivc.add_output('fixed_charge_rate', val=0.0, desc = 'Fixed charge rate for coe calculation')\n costs_ivc.add_output('labor_rate', 0.0, units='USD/h')\n costs_ivc.add_output('painting_rate', 0.0, units='USD/m**2')\n \n # Assembly setup\n self.add_subsystem('assembly', WT_Assembly(blade_init_options = modeling_options['blade']))\n if modeling_options['flags']['blade']:\n self.connect('blade.outer_shape_bem.ref_axis', 'assembly.blade_ref_axis')\n if modeling_options['flags']['hub']:\n self.connect('hub.radius', 'assembly.hub_radius')\n if modeling_options['flags']['tower']:\n self.connect('tower.height', 'assembly.tower_height')\n if modeling_options['flags']['foundation']:\n self.connect('foundation.height', 'assembly.foundation_height')\n if modeling_options['flags']['nacelle']:\n self.connect('nacelle.distance_tt_hub', 'assembly.distance_tt_hub')\n if modeling_options['flags']['monopile']:\n self.connect('monopile.height', 'assembly.monopile_height')\n\n # Setup TSR optimization\n opt_var = self.add_subsystem('opt_var', om.IndepVarComp())\n opt_var.add_output('tsr_opt_gain', val = 1.0)\n # Multiply the initial tsr with the tsr gain\n exec_comp = om.ExecComp('tsr_opt = tsr_original * tsr_gain')\n self.add_subsystem('pc', exec_comp)\n self.connect('opt_var.tsr_opt_gain', 'pc.tsr_gain')\n if modeling_options['flags']['control']:\n self.connect('control.rated_TSR', 'pc.tsr_original')\n\nclass Blade(om.Group):\n # Openmdao group with components with the blade data coming from the input yaml file.\n def initialize(self):\n self.options.declare('blade_init_options')\n self.options.declare('af_init_options')\n self.options.declare('opt_options')\n \n def setup(self):\n # Options\n blade_init_options = self.options['blade_init_options']\n af_init_options = self.options['af_init_options']\n opt_options = self.options['opt_options']\n \n # Optimization parameters initialized as indipendent variable component\n opt_var = om.IndepVarComp()\n opt_var.add_output('s_opt_twist', val = np.ones(opt_options['optimization_variables']['blade']['aero_shape']['twist']['n_opt']))\n opt_var.add_output('s_opt_chord', val = np.ones(opt_options['optimization_variables']['blade']['aero_shape']['chord']['n_opt']))\n opt_var.add_output('twist_opt_gain', val = np.ones(opt_options['optimization_variables']['blade']['aero_shape']['twist']['n_opt']))\n opt_var.add_output('chord_opt_gain', val = np.ones(opt_options['optimization_variables']['blade']['aero_shape']['chord']['n_opt']))\n opt_var.add_output('af_position', val = np.ones(blade_init_options['n_af_span']))\n opt_var.add_output('spar_cap_ss_opt_gain', val = np.ones(opt_options['optimization_variables']['blade']['structure']['spar_cap_ss']['n_opt']))\n opt_var.add_output('spar_cap_ps_opt_gain', val = np.ones(opt_options['optimization_variables']['blade']['structure']['spar_cap_ps']['n_opt']))\n self.add_subsystem('opt_var',opt_var)\n\n # Import outer shape BEM\n self.add_subsystem('outer_shape_bem', Blade_Outer_Shape_BEM(blade_init_options = blade_init_options), promotes = ['length'])\n\n # Parametrize blade outer shape\n self.add_subsystem('pa', ParametrizeBladeAero(blade_init_options = blade_init_options, opt_options = opt_options)) # Parameterize aero (chord and twist)\n\n # Interpolate airfoil profiles and coordinates\n self.add_subsystem('interp_airfoils', Blade_Interp_Airfoils(blade_init_options = blade_init_options, af_init_options = af_init_options))\n \n # Connections to blade aero parametrization\n self.connect('opt_var.s_opt_twist', 'pa.s_opt_twist')\n self.connect('opt_var.s_opt_chord', 'pa.s_opt_chord')\n self.connect('opt_var.twist_opt_gain', 'pa.twist_opt_gain')\n self.connect('opt_var.chord_opt_gain', 'pa.chord_opt_gain')\n\n self.connect('outer_shape_bem.s', 'pa.s')\n self.connect('outer_shape_bem.twist', 'pa.twist_original')\n self.connect('outer_shape_bem.chord', 'pa.chord_original')\n\n # Connections from oute_shape_bem to interp_airfoils\n self.connect('outer_shape_bem.s', 'interp_airfoils.s')\n self.connect('pa.chord_param', 'interp_airfoils.chord')\n self.connect('outer_shape_bem.pitch_axis', 'interp_airfoils.pitch_axis')\n self.connect('opt_var.af_position', 'interp_airfoils.af_position')\n \n # If the flag is true, generate the 3D x,y,z points of the outer blade shape\n if blade_init_options['lofted_output'] == True:\n self.add_subsystem('blade_lofted', Blade_Lofted_Shape(blade_init_options = blade_init_options, af_init_options = af_init_options))\n self.connect('interp_airfoils.coord_xy_dim', 'blade_lofted.coord_xy_dim')\n self.connect('pa.twist_param', 'blade_lofted.twist')\n self.connect('outer_shape_bem.s', 'blade_lofted.s')\n self.connect('outer_shape_bem.ref_axis', 'blade_lofted.ref_axis')\n \n # Import blade internal structure data and remap composites on the outer blade shape\n self.add_subsystem('internal_structure_2d_fem', Blade_Internal_Structure_2D_FEM(blade_init_options = blade_init_options, af_init_options = af_init_options))\n self.connect('outer_shape_bem.s', 'internal_structure_2d_fem.s')\n self.connect('pa.twist_param', 'internal_structure_2d_fem.twist')\n self.connect('pa.chord_param', 'internal_structure_2d_fem.chord')\n self.connect('outer_shape_bem.pitch_axis', 'internal_structure_2d_fem.pitch_axis')\n self.connect('interp_airfoils.coord_xy_dim', 'internal_structure_2d_fem.coord_xy_dim')\n\n self.add_subsystem('ps', ParametrizeBladeStruct(blade_init_options = blade_init_options, opt_options = opt_options)) # Parameterize struct (spar caps ss and ps)\n\n # Connections to blade struct parametrization\n self.connect('opt_var.spar_cap_ss_opt_gain','ps.spar_cap_ss_opt_gain')\n self.connect('opt_var.spar_cap_ps_opt_gain','ps.spar_cap_ps_opt_gain')\n self.connect('outer_shape_bem.s', 'ps.s')\n # self.connect('internal_structure_2d_fem.layer_name', 'ps.layer_name')\n self.connect('internal_structure_2d_fem.layer_thickness', 'ps.layer_thickness_original')\n\nclass Blade_Outer_Shape_BEM(om.Group):\n # Openmdao group with the blade outer shape data coming from the input yaml file.\n def initialize(self):\n self.options.declare('blade_init_options')\n\n def setup(self):\n blade_init_options = self.options['blade_init_options']\n n_af_span = blade_init_options['n_af_span']\n self.n_span = n_span = blade_init_options['n_span']\n \n ivc = self.add_subsystem('blade_outer_shape_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('af_position', val=np.zeros(n_af_span), desc='1D array of the non dimensional positions of the airfoils af_used defined along blade span.')\n ivc.add_output('s_default', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n ivc.add_output('chord_yaml', val=np.zeros(n_span), units='m', desc='1D array of the chord values defined along blade span.')\n ivc.add_output('twist_yaml', val=np.zeros(n_span), units='rad', desc='1D array of the twist values defined along blade span. The twist is defined positive for negative rotations around the z axis (the same as in BeamDyn).')\n ivc.add_output('pitch_axis_yaml', val=np.zeros(n_span), desc='1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.')\n ivc.add_output('ref_axis_yaml', val=np.zeros((n_span,3)),units='m', desc='2D array of the coordinates (x,y,z) of the blade reference axis, defined along blade span. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n\n self.add_subsystem('compute_blade_outer_shape_bem', Compute_Blade_Outer_Shape_BEM(blade_init_options = blade_init_options), promotes = ['*'])\n\nclass Compute_Blade_Outer_Shape_BEM(om.ExplicitComponent):\n # Openmdao group with the blade outer shape data coming from the input yaml file.\n def initialize(self):\n self.options.declare('blade_init_options')\n\n def setup(self):\n blade_init_options = self.options['blade_init_options']\n n_af_span = blade_init_options['n_af_span']\n self.n_span = n_span = blade_init_options['n_span']\n if 'n_te_flaps' in blade_init_options.keys():\n n_te_flaps = blade_init_options['n_te_flaps']\n else:\n n_te_flaps = 0\n\n self.add_input('s_default', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n self.add_input('chord_yaml', val=np.zeros(n_span), units='m', desc='1D array of the chord values defined along blade span.')\n self.add_input('twist_yaml', val=np.zeros(n_span), units='rad', desc='1D array of the twist values defined along blade span. The twist is defined positive for negative rotations around the z axis (the same as in BeamDyn).')\n self.add_input('pitch_axis_yaml', val=np.zeros(n_span), desc='1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.')\n self.add_input('ref_axis_yaml', val=np.zeros((n_span,3)),units='m', desc='2D array of the coordinates (x,y,z) of the blade reference axis, defined along blade span. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n\n self.add_input('span_end', val=np.zeros(n_te_flaps), desc='1D array of the positions along blade span where something (a DAC device?) starts and we want a grid point. Only values between 0 and 1 are meaningful.')\n self.add_input('span_ext', val=np.zeros(n_te_flaps), desc='1D array of the extensions along blade span where something (a DAC device?) lives and we want a grid point. Only values between 0 and 1 are meaningful.')\n\n self.add_output('s', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n self.add_output('chord', val=np.zeros(n_span), units='m', desc='1D array of the chord values defined along blade span.')\n self.add_output('twist', val=np.zeros(n_span), units='rad', desc='1D array of the twist values defined along blade span. The twist is defined positive for negative rotations around the z axis (the same as in BeamDyn).')\n self.add_output('pitch_axis', val=np.zeros(n_span), desc='1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.')\n self.add_output('ref_axis', val=np.zeros((n_span,3)),units='m', desc='2D array of the coordinates (x,y,z) of the blade reference axis, defined along blade span. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n \n self.add_output('length', val = 0.0, units='m', desc='Scalar of the 3D blade length computed along its axis.')\n self.add_output('length_z', val = 0.0, units='m', desc='Scalar of the 1D blade length along z, i.e. the blade projection in the plane ignoring prebend and sweep. For a straight blade this is equal to length')\n \n def compute(self, inputs, outputs):\n \n # If devices are defined along span, manipulate the grid s to always have a grid point where it is needed, and reinterpolate the blade quantities, namely chord, twist, pitch axis, and reference axis\n if inputs['span_end'] > 0:\n nd_span_orig = np.linspace(0., 1.,self.n_span)\n\n chord_orig = np.interp(nd_span_orig, inputs['s_default'], inputs['chord_yaml'])\n twist_orig = np.interp(nd_span_orig, inputs['s_default'], inputs['twist_yaml'])\n pitch_axis_orig = np.interp(nd_span_orig, inputs['s_default'], inputs['pitch_axis_yaml'])\n ref_axis_orig = np.zeros((self.n_span, 3))\n ref_axis_orig[:, 0] = np.interp(nd_span_orig,inputs['s_default'],inputs['ref_axis_yaml'][:, 0])\n ref_axis_orig[:, 1] = np.interp(nd_span_orig,inputs['s_default'],inputs['ref_axis_yaml'][:, 1])\n ref_axis_orig[:, 2] = np.interp(nd_span_orig,inputs['s_default'],inputs['ref_axis_yaml'][:, 2])\n\n outputs['s'] = copy.copy(nd_span_orig)\n\n # Account for start and end positions\n if inputs['span_end'] >= 0.98:\n flap_start = 0.98 - inputs['span_ext']\n flap_end = 0.98\n print('WARNING: span_end point reached limits and was set to r/R = 0.98')\n else:\n flap_start = inputs['span_end'] - inputs['span_ext']\n flap_end = inputs['span_end']\n\n idx_flap_start = np.where(np.abs(nd_span_orig - flap_start) == (np.abs(nd_span_orig - flap_start)).min())[0][0]\n idx_flap_end = np.where(np.abs(nd_span_orig - flap_end) == (np.abs(nd_span_orig - flap_end)).min())[0][0]\n if idx_flap_start == idx_flap_end:\n idx_flap_end += 1\n outputs['s'][idx_flap_start] = flap_start\n outputs['s'][idx_flap_end] = flap_end\n outputs['chord'] = np.interp(outputs['s'], nd_span_orig, chord_orig)\n outputs['twist'] = np.interp(outputs['s'], nd_span_orig, twist_orig)\n outputs['pitch_axis'] = np.interp(outputs['s'], nd_span_orig, pitch_axis_orig)\n\n outputs['ref_axis'][:, 0] = np.interp(outputs['s'],nd_span_orig, ref_axis_orig[:, 0])\n outputs['ref_axis'][:, 1] = np.interp(outputs['s'],nd_span_orig, ref_axis_orig[:, 1])\n outputs['ref_axis'][:, 2] = np.interp(outputs['s'],nd_span_orig, ref_axis_orig[:, 2])\n else:\n outputs['s'] = inputs['s_default']\n outputs['chord'] = inputs['chord_yaml']\n outputs['twist'] = inputs['twist_yaml']\n outputs['pitch_axis'] = inputs['pitch_axis_yaml']\n outputs['ref_axis'] = inputs['ref_axis_yaml']\n\n outputs['length'] = arc_length(outputs['ref_axis'])[-1]\n outputs['length_z'] = outputs['ref_axis'][:,2][-1]\n\nclass Blade_Interp_Airfoils(om.ExplicitComponent):\n # Openmdao component to interpolate airfoil coordinates and airfoil polars along the span of the blade for a predefined set of airfoils coming from component Airfoils.\n # JPJ: can split this up into multiple components to ease derivative computation\n def initialize(self):\n self.options.declare('blade_init_options')\n self.options.declare('af_init_options')\n \n def setup(self):\n blade_init_options = self.options['blade_init_options']\n self.n_af_span = n_af_span = blade_init_options['n_af_span']\n self.n_span = n_span = blade_init_options['n_span']\n af_init_options = self.options['af_init_options']\n self.n_af = n_af = af_init_options['n_af'] # Number of airfoils\n self.n_aoa = n_aoa = af_init_options['n_aoa']# Number of angle of attacks\n self.n_Re = n_Re = af_init_options['n_Re'] # Number of Reynolds, so far hard set at 1\n self.n_tab = n_tab = af_init_options['n_tab']# Number of tabulated data. For distributed aerodynamic control this could be > 1\n self.n_xy = n_xy = af_init_options['n_xy'] # Number of coordinate points to describe the airfoil geometry\n self.af_used = af_init_options['af_used'] # Names of the airfoils adopted along blade span\n \n self.add_input('af_position', val=np.zeros(n_af_span), desc='1D array of the non dimensional positions of the airfoils af_used defined along blade span.')\n self.add_input('s', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n self.add_input('pitch_axis', val=np.zeros(n_span), desc='1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.')\n self.add_input('chord', val=np.zeros(n_span), units='m', desc='1D array of the chord values defined along blade span.')\n \n # Airfoil properties\n self.add_discrete_input('name', val=n_af * [''], desc='1D array of names of airfoils.')\n self.add_input('ac', val=np.zeros(n_af), desc='1D array of the aerodynamic centers of each airfoil.')\n self.add_input('r_thick', val=np.zeros(n_af), desc='1D array of the relative thicknesses of each airfoil.')\n self.add_input('aoa', val=np.zeros(n_aoa), units='rad', desc='1D array of the angles of attack used to define the polars of the airfoils. All airfoils defined in openmdao share this grid.')\n self.add_input('cl', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the lift coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n self.add_input('cd', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the drag coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n self.add_input('cm', val=np.zeros((n_af, n_aoa, n_Re, n_tab)), desc='4D array with the moment coefficients of the airfoils. Dimension 0 is along the different airfoils defined in the yaml, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n \n # Airfoil coordinates\n self.add_input('coord_xy', val=np.zeros((n_af, n_xy, 2)), desc='3D array of the x and y airfoil coordinates of the n_af airfoils.')\n \n # Polars and coordinates interpolated along span\n self.add_output('r_thick_interp', val=np.zeros(n_span), desc='1D array of the relative thicknesses of the blade defined along span.')\n self.add_output('ac_interp', val=np.zeros(n_span), desc='1D array of the aerodynamic center of the blade defined along span.')\n self.add_output('cl_interp', val=np.zeros((n_span, n_aoa, n_Re, n_tab)), desc='4D array with the lift coefficients of the airfoils. Dimension 0 is along the blade span for n_span stations, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n self.add_output('cd_interp', val=np.zeros((n_span, n_aoa, n_Re, n_tab)), desc='4D array with the drag coefficients of the airfoils. Dimension 0 is along the blade span for n_span stations, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n self.add_output('cm_interp', val=np.zeros((n_span, n_aoa, n_Re, n_tab)), desc='4D array with the moment coefficients of the airfoils. Dimension 0 is along the blade span for n_span stations, dimension 1 is along the angles of attack, dimension 2 is along the Reynolds number, dimension 3 is along the number of tabs, which may describe multiple sets at the same station, for example in presence of a flap.')\n self.add_output('coord_xy_interp', val=np.zeros((n_span, n_xy, 2)), desc='3D array of the non-dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations. The leading edge is place at x=0 and y=0.')\n self.add_output('coord_xy_dim', val=np.zeros((n_span, n_xy, 2)), units = 'm', desc='3D array of the dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations. The origin is placed at the pitch axis.')\n \n def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n \n # Reconstruct the blade relative thickness along span with a pchip\n r_thick_used = np.zeros(self.n_af_span)\n coord_xy_used = np.zeros((self.n_af_span, self.n_xy, 2))\n coord_xy_interp = np.zeros((self.n_span, self.n_xy, 2))\n coord_xy_dim = np.zeros((self.n_span, self.n_xy, 2))\n cl_used = np.zeros((self.n_af_span, self.n_aoa, self.n_Re, self.n_tab))\n cl_interp = np.zeros((self.n_span, self.n_aoa, self.n_Re, self.n_tab))\n cd_used = np.zeros((self.n_af_span, self.n_aoa, self.n_Re, self.n_tab))\n cd_interp = np.zeros((self.n_span, self.n_aoa, self.n_Re, self.n_tab))\n cm_used = np.zeros((self.n_af_span, self.n_aoa, self.n_Re, self.n_tab))\n cm_interp = np.zeros((self.n_span, self.n_aoa, self.n_Re, self.n_tab))\n \n for i in range(self.n_af_span):\n for j in range(self.n_af):\n if self.af_used[i] == discrete_inputs['name'][j]: \n r_thick_used[i] = inputs['r_thick'][j]\n coord_xy_used[i,:,:]= inputs['coord_xy'][j]\n cl_used[i,:,:,:] = inputs['cl'][j,:,:,:]\n cd_used[i,:,:,:] = inputs['cd'][j,:,:,:]\n cm_used[i,:,:,:] = inputs['cm'][j,:,:,:]\n break\n \n # Pchip does have an associated derivative method built-in:\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.PchipInterpolator.derivative.html#scipy.interpolate.PchipInterpolator.derivative\n spline = PchipInterpolator\n rthick_spline = spline(inputs['af_position'], r_thick_used)\n outputs['r_thick_interp'] = rthick_spline(inputs['s'])\n \n # Spanwise interpolation of the profile coordinates with a pchip\n r_thick_unique, indices = np.unique(r_thick_used, return_index = True)\n profile_spline = spline(r_thick_unique, coord_xy_used[indices, :, :]) \n coord_xy_interp = np.flip(profile_spline(np.flip(outputs['r_thick_interp'])), axis=0)\n \n \n for i in range(self.n_span):\n # Correction to move the leading edge (min x point) to (0,0)\n af_le = coord_xy_interp[i, np.argmin(coord_xy_interp[i,:,0]),:]\n coord_xy_interp[i,:,0] -= af_le[0]\n coord_xy_interp[i,:,1] -= af_le[1]\n c = max(coord_xy_interp[i,:,0]) - min(coord_xy_interp[i,:,0])\n coord_xy_interp[i,:,:] /= c\n # If the rel thickness is smaller than 0.4 apply a trailing ege smoothing step\n if outputs['r_thick_interp'][i] < 0.4: \n coord_xy_interp[i,:,:] = trailing_edge_smoothing(coord_xy_interp[i,:,:])\n \n pitch_axis = inputs['pitch_axis']\n chord = inputs['chord']\n\n \n coord_xy_dim = copy.copy(coord_xy_interp)\n coord_xy_dim[:,:,0] -= pitch_axis[:, np.newaxis]\n coord_xy_dim = coord_xy_dim*chord[:, np.newaxis, np.newaxis]\n \n \n # Spanwise interpolation of the airfoil polars with a pchip\n cl_spline = spline(r_thick_unique, cl_used[indices, :, :, :]) \n cl_interp = np.flip(cl_spline(np.flip(outputs['r_thick_interp'])), axis=0)\n cd_spline = spline(r_thick_unique, cd_used[indices, :, :, :]) \n cd_interp = np.flip(cd_spline(np.flip(outputs['r_thick_interp'])), axis=0)\n cm_spline = spline(r_thick_unique, cm_used[indices, :, :, :]) \n cm_interp = np.flip(cm_spline(np.flip(outputs['r_thick_interp'])), axis=0)\n \n \n # Plot interpolated polars\n # for i in range(self.n_span): \n # plt.plot(inputs['aoa'], cl_interp[i,:,0,0], 'b')\n # plt.plot(inputs['aoa'], cd_interp[i,:,0,0], 'r')\n # plt.plot(inputs['aoa'], cm_interp[i,:,0,0], 'k')\n # plt.title(i)\n # plt.show() \n \n outputs['coord_xy_interp'] = coord_xy_interp\n outputs['coord_xy_dim'] = coord_xy_dim\n outputs['cl_interp'] = cl_interp\n outputs['cd_interp'] = cd_interp\n outputs['cm_interp'] = cm_interp\n\n # # Plot interpolated coordinates\n # import matplotlib.pyplot as plt\n # for i in range(self.n_span): \n # plt.plot(coord_xy_interp[i,:,0], coord_xy_interp[i,:,1], 'k', label = 'coord_xy_interp')\n # plt.plot(coord_xy_dim[i,:,0], coord_xy_dim[i,:,1], 'b', label = 'coord_xy_dim')\n # plt.axis('equal')\n # plt.title(i)\n # plt.legend()\n # plt.show()\n\n\n # # Smoothing\n # import matplotlib.pyplot as plt\n # # plt.plot(inputs['s'], inputs['chord'] * outputs['r_thick_interp'])\n # # plt.show()\n\n # # Absolute Thickness\n # abs_thick_init = outputs['r_thick_interp']*inputs['chord']\n # s_interp_at = np.array([0.0, 0.02, 0.1, 0.2, 0.8, 1.0 ])\n # abs_thick_int1 = np.interp(s_interp_at, inputs['s'],abs_thick_init)\n # f_interp2 = PchipInterpolator(s_interp_at,abs_thick_int1)\n # abs_thick_int2 = f_interp2(inputs['s'])\n\n # # # Relative thickness\n # r_thick_interp = abs_thick_int2 / inputs['chord']\n # r_thick_airfoils = np.array([0.18, 0.211, 0.241, 0.301, 0.36 , 0.50, 1.00])\n # s_interp_rt = np.interp(r_thick_airfoils, np.flip(r_thick_interp),np.flip(inputs['s']))\n # f_interp2 = PchipInterpolator(np.flip(s_interp_rt, axis=0),np.flip(r_thick_airfoils, axis=0))\n # r_thick_int2 = f_interp2(inputs['s'])\n\n \n # frt, axrt = plt.subplots(1,1,figsize=(5.3, 4))\n # axrt.plot(inputs['s'], outputs['r_thick_interp']*100., c='k', label='Initial')\n # # axrt.plot(inputs['s'], r_thick_interp * 100., c='b', label='Interp')\n # # axrt.plot(s_interp_rt, r_thick_airfoils * 100., 'og', label='Airfoils')\n # # axrt.plot(inputs['s'], r_thick_int2 * 100., c='g', label='Reconstructed')\n # axrt.set(xlabel='r/R' , ylabel='Relative Thickness (%)')\n # axrt.legend()\n \n # fat, axat = plt.subplots(1,1,figsize=(5.3, 4))\n # axat.plot(inputs['s'], abs_thick_init, c='k', label='Initial')\n # # axat.plot(s_interp_at, abs_thick_int1, 'ko', label='Interp Points')\n # # axat.plot(inputs['s'], abs_thick_int2, c='b', label='PCHIP')\n # # axat.plot(inputs['s'], r_thick_int2 * inputs['chord'], c='g', label='Reconstructed')\n # axat.set(xlabel='r/R' , ylabel='Absolute Thickness (m)')\n # axat.legend()\n # plt.show()\n # print(np.flip(s_interp_rt))\n # exit()\n\nclass Blade_Lofted_Shape(om.ExplicitComponent):\n # Openmdao component to generate the x, y, z coordinates of the points describing the blade outer shape.\n def initialize(self):\n self.options.declare('blade_init_options')\n self.options.declare('af_init_options')\n \n def setup(self):\n blade_init_options = self.options['blade_init_options']\n af_init_options = self.options['af_init_options']\n self.n_span = n_span = blade_init_options['n_span']\n self.n_xy = n_xy = af_init_options['n_xy'] # Number of coordinate points to describe the airfoil geometry\n \n self.add_input('s', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n self.add_input('twist', val=np.zeros(n_span), units='rad', desc='1D array of the twist values defined along blade span. The twist is defined positive for negative rotations around the z axis (the same as in BeamDyn).')\n self.add_input('ref_axis', val=np.zeros((n_span,3)),units='m', desc='2D array of the coordinates (x,y,z) of the blade reference axis, defined along blade span. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n \n self.add_input('coord_xy_dim', val=np.zeros((n_span, n_xy, 2)), units = 'm', desc='3D array of the dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations. The origin is placed at the pitch axis.')\n \n self.add_output('coord_xy_dim_twisted',val=np.zeros((n_span, n_xy, 2)), units = 'm', desc='3D array of the dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations. The origin is placed at the pitch axis.')\n self.add_output('3D_shape', val = np.zeros((n_span * n_xy, 4)), units = 'm', desc='4D array of the s, and x, y, and z coordinates of the points describing the outer shape of the blade. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n \n def compute(self, inputs, outputs):\n\n for i in range(self.n_span):\n x = inputs['coord_xy_dim'][i,:,0]\n y = inputs['coord_xy_dim'][i,:,1]\n outputs['coord_xy_dim_twisted'][i,:,0] = x * np.cos(inputs['twist'][i]) - y * np.sin(inputs['twist'][i])\n outputs['coord_xy_dim_twisted'][i,:,1] = y * np.cos(inputs['twist'][i]) + x * np.sin(inputs['twist'][i])\n \n k=0\n for i in range(self.n_span):\n for j in range(self.n_xy):\n outputs['3D_shape'][k,:] = np.array([k, outputs['coord_xy_dim_twisted'][i,j,1], outputs['coord_xy_dim_twisted'][i,j,0], 0.0]) + np.hstack([0, inputs['ref_axis'][i,:]])\n k=k+1\n \n np.savetxt('3d_xyz_nrel5mw.dat', outputs['3D_shape'], header='\\t point number [-]\\t\\t\\t\\t x [m] \\t\\t\\t\\t\\t y [m] \\t\\t\\t\\t z [m] \\t\\t\\t\\t The coordinate system follows the BeamDyn one.')\n \n import matplotlib.pyplot as plt\n for i in range(self.n_span): \n plt.plot(outputs['coord_xy_dim_twisted'][i,:,0], outputs['coord_xy_dim_twisted'][i,:,1], 'k')\n plt.axis('equal')\n plt.title(i)\n plt.show()\n \n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.plot(outputs['3D_shape'][:,1],outputs['3D_shape'][:,2],outputs['3D_shape'][:,3])\n plt.show()\n\nclass Blade_Internal_Structure_2D_FEM(om.Group):\n # Openmdao group with the blade internal structure data coming from the input yaml file.\n def initialize(self):\n self.options.declare('blade_init_options')\n self.options.declare('af_init_options')\n\n def setup(self):\n blade_init_options = self.options['blade_init_options']\n af_init_options = self.options['af_init_options']\n self.n_span = n_span = blade_init_options['n_span']\n self.n_webs = n_webs = blade_init_options['n_webs']\n self.n_layers = n_layers = blade_init_options['n_layers']\n self.n_xy = n_xy = af_init_options['n_xy'] # Number of coordinate points to describe the airfoil geometry\n \n ivc = self.add_subsystem('blade_2dfem_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('layer_web', val=np.zeros(n_layers), desc='1D array of the web id the layer is associated to. If the layer is on the outer profile, this entry can simply stay equal to zero.')\n ivc.add_output('layer_thickness', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the thickness of the layers of the blade structure. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n ivc.add_output('layer_midpoint_nd', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional midpoint defined along the outer profile of a layer. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n ivc.add_discrete_output('layer_side', val=n_layers * [''], desc='1D array setting whether the layer is on the suction or pressure side. This entry is only used if definition_layer is equal to 1 or 2.')\n ivc.add_discrete_output('definition_web', val=np.zeros(n_webs), desc='1D array of flags identifying how webs are specified in the yaml. 1) offset+rotation=twist 2) offset+rotation')\n ivc.add_discrete_output('definition_layer', val=np.zeros(n_layers), desc='1D array of flags identifying how layers are specified in the yaml. 1) all around (skin, paint, ) 2) offset+rotation twist+width (spar caps) 3) offset+user defined rotation+width 4) midpoint TE+width (TE reinf) 5) midpoint LE+width (LE reinf) 6) layer position fixed to other layer (core fillers) 7) start and width 8) end and width 9) start and end nd 10) web layer')\n ivc.add_discrete_output('index_layer_start',val=np.zeros(n_layers), desc='Index used to fix a layer to another')\n ivc.add_discrete_output('index_layer_end', val=np.zeros(n_layers), desc='Index used to fix a layer to another')\n \n ivc.add_output('web_start_nd_yaml', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n ivc.add_output('web_end_nd_yaml', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n ivc.add_output('web_rotation_yaml', val=np.zeros((n_webs, n_span)), units='rad', desc='2D array of the rotation angle of the shear webs in respect to the chord line. The first dimension represents each shear web, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the web is built straight.')\n ivc.add_output('web_offset_y_pa_yaml', val=np.zeros((n_webs, n_span)), units='m', desc='2D array of the offset along the y axis to set the position of the shear webs. Positive values move the web towards the trailing edge, negative values towards the leading edge. The first dimension represents each shear web, the second dimension represents each entry along blade span.')\n ivc.add_output('layer_rotation_yaml', val=np.zeros((n_layers, n_span)), units='rad', desc='2D array of the rotation angle of a layer in respect to the chord line. The first dimension represents each layer, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the layer is built straight.')\n ivc.add_output('layer_start_nd_yaml', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n ivc.add_output('layer_end_nd_yaml', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n ivc.add_output('layer_offset_y_pa_yaml', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the offset along the y axis to set the position of a layer. Positive values move the layer towards the trailing edge, negative values towards the leading edge. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n ivc.add_output('layer_width_yaml', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the width along the outer profile of a layer. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n\n self.add_subsystem('compute_internal_structure_2d_fem', Compute_Blade_Internal_Structure_2D_FEM(blade_init_options = blade_init_options, af_init_options = af_init_options), promotes = ['*'])\n\nclass Compute_Blade_Internal_Structure_2D_FEM(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('blade_init_options')\n self.options.declare('af_init_options')\n\n def setup(self):\n blade_init_options = self.options['blade_init_options']\n af_init_options = self.options['af_init_options']\n self.n_span = n_span = blade_init_options['n_span']\n self.n_webs = n_webs = blade_init_options['n_webs']\n self.n_layers = n_layers = blade_init_options['n_layers']\n self.n_xy = n_xy = af_init_options['n_xy'] # Number of coordinate points to describe the airfoil geometry\n \n # From user defined yaml\n self.add_input('s', val=np.zeros(n_span), desc='1D array of the non-dimensional spanwise grid defined along blade axis (0-blade root, 1-blade tip)')\n self.add_input('web_rotation_yaml', val=np.zeros((n_webs, n_span)), units='rad', desc='2D array of the rotation angle of the shear webs in respect to the chord line. The first dimension represents each shear web, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the web is built straight.')\n self.add_input('web_offset_y_pa_yaml', val=np.zeros((n_webs, n_span)), units='m', desc='2D array of the offset along the y axis to set the position of the shear webs. Positive values move the web towards the trailing edge, negative values towards the leading edge. The first dimension represents each shear web, the second dimension represents each entry along blade span.')\n self.add_input('web_start_nd_yaml', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n self.add_input('web_end_nd_yaml', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n\n self.add_input('layer_web', val=np.zeros(n_layers), desc='1D array of the web id the layer is associated to. If the layer is on the outer profile, this entry can simply stay equal to zero.')\n self.add_input('layer_thickness', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the thickness of the layers of the blade structure. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_input('layer_rotation_yaml', val=np.zeros((n_layers, n_span)), units='rad', desc='2D array of the rotation angle of a layer in respect to the chord line. The first dimension represents each layer, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the layer is built straight.')\n self.add_input('layer_offset_y_pa_yaml',val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the offset along the y axis to set the position of a layer. Positive values move the layer towards the trailing edge, negative values towards the leading edge. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_input('layer_width_yaml', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the width along the outer profile of a layer. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_input('layer_midpoint_nd', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional midpoint defined along the outer profile of a layer. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_discrete_input('layer_side', val=n_layers * [''], desc='1D array setting whether the layer is on the suction or pressure side. This entry is only used if definition_layer is equal to 1 or 2.')\n self.add_input('layer_start_nd_yaml', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_input('layer_end_nd_yaml', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_discrete_input('definition_web', val=np.zeros(n_webs), desc='1D array of flags identifying how webs are specified in the yaml. 1) offset+rotation=twist 2) offset+rotation')\n self.add_discrete_input('definition_layer', val=np.zeros(n_layers), desc='1D array of flags identifying how layers are specified in the yaml. 1) all around (skin, paint, ) 2) offset+rotation twist+width (spar caps) 3) offset+user defined rotation+width 4) midpoint TE+width (TE reinf) 5) midpoint LE+width (LE reinf) 6) layer position fixed to other layer (core fillers) 7) start and width 8) end and width 9) start and end nd 10) web layer')\n self.add_discrete_input('index_layer_start',val=np.zeros(n_layers), desc='Index used to fix a layer to another')\n self.add_discrete_input('index_layer_end', val=np.zeros(n_layers), desc='Index used to fix a layer to another')\n\n # From blade outer shape\n self.add_input('coord_xy_dim', val=np.zeros((n_span, n_xy, 2)), units = 'm', desc='3D array of the dimensional x and y airfoil coordinates of the airfoils interpolated along span for n_span stations. The origin is placed at the pitch axis.')\n self.add_input('twist', val=np.zeros(n_span), units='rad', desc='1D array of the twist values defined along blade span. The twist is defined positive for negative rotations around the z axis (the same as in BeamDyn).')\n self.add_input('chord', val=np.zeros(n_span), units='m', desc='1D array of the chord values defined along blade span.')\n self.add_input('pitch_axis', val=np.zeros(n_span), desc='1D array of the chordwise position of the pitch axis (0-LE, 1-TE), defined along blade span.')\n\n self.add_output('web_rotation', val=np.zeros((n_webs, n_span)), units='rad', desc='2D array of the rotation angle of the shear webs in respect to the chord line. The first dimension represents each shear web, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the web is built straight.')\n self.add_output('web_start_nd', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n self.add_output('web_end_nd', val=np.zeros((n_webs, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a web. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each web, the second dimension represents each entry along blade span.')\n self.add_output('web_offset_y_pa',val=np.zeros((n_webs, n_span)), units='m', desc='2D array of the offset along the y axis to set the position of the shear webs. Positive values move the web towards the trailing edge, negative values towards the leading edge. The first dimension represents each shear web, the second dimension represents each entry along blade span.')\n self.add_output('layer_rotation', val=np.zeros((n_layers, n_span)),units='rad', desc='2D array of the rotation angle of a layer in respect to the chord line. The first dimension represents each layer, the second dimension represents each entry along blade span. If the rotation is equal to negative twist +- a constant, then the layer is built straight.')\n self.add_output('layer_start_nd', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional start point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_output('layer_end_nd', val=np.zeros((n_layers, n_span)), desc='2D array of the non-dimensional end point defined along the outer profile of a layer. The TE suction side is 0, the TE pressure side is 1. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_output('layer_offset_y_pa',val=np.zeros((n_layers, n_span)), units='m',desc='2D array of the offset along the y axis to set the position of a layer. Positive values move the layer towards the trailing edge, negative values towards the leading edge. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n self.add_output('layer_width', val=np.zeros((n_layers, n_span)), units='m', desc='2D array of the width along the outer profile of a layer. The first dimension represents each layer, the second dimension represents each entry along blade span.')\n\n # # These outputs don't depend on anything and should be refactored to be\n # # outputs that come from an om.IndepVarComp.\n # self.declare_partials('definition_layer', '*', dependent=False)\n # self.declare_partials('layer_offset_y_pa', '*', dependent=False)\n # self.declare_partials('layer_thickness', '*', dependent=False)\n # self.declare_partials('layer_web', '*', dependent=False)\n # self.declare_partials('layer_width', '*', dependent=False)\n # self.declare_partials('s', '*', dependent=False)\n # self.declare_partials('web_offset_y_pa', '*', dependent=False)\n \n # self.declare_partials('layer_end_nd', ['coord_xy_dim', 'twist'], method='fd')\n # self.declare_partials('layer_midpoint_nd', ['coord_xy_dim'], method='fd')\n # self.declare_partials('layer_rotation', ['twist'], method='fd')\n # self.declare_partials('layer_start_nd', ['coord_xy_dim', 'twist'], method='fd')\n # self.declare_partials('web_end_nd', ['coord_xy_dim', 'twist'], method='fd')\n # self.declare_partials('web_rotation', ['twist'], method='fd')\n # self.declare_partials('web_start_nd', ['coord_xy_dim', 'twist'], method='fd')\n\n def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n \n # Initialize temporary arrays for the outputs\n web_rotation = np.zeros((self.n_webs, self.n_span))\n layer_rotation = np.zeros((self.n_layers, self.n_span))\n web_start_nd = np.zeros((self.n_webs, self.n_span))\n web_end_nd = np.zeros((self.n_webs, self.n_span))\n layer_start_nd = np.zeros((self.n_layers, self.n_span))\n layer_end_nd = np.zeros((self.n_layers, self.n_span))\n\n layer_name = self.options['blade_init_options']['layer_name']\n layer_mat = self.options['blade_init_options']['layer_mat']\n web_name = self.options['blade_init_options']['web_name']\n\n # Loop through spanwise stations\n for i in range(self.n_span):\n # Compute the arc length (arc_L_i), the non-dimensional arc coordinates (xy_arc_i), and the non dimensional position of the leading edge of the profile at position i\n xy_coord_i = inputs['coord_xy_dim'][i,:,:]\n xy_arc_i = arc_length(xy_coord_i)\n arc_L_i = xy_arc_i[-1]\n xy_arc_i /= arc_L_i\n idx_le = np.argmin(xy_coord_i[:,0])\n LE_loc = xy_arc_i[idx_le]\n chord = inputs['chord'][i]\n p_le_i = inputs['pitch_axis'][i]\n ratio_SCmax = 0.8\n ratio_Websmax = 0.75\n\n # Loop through the webs and compute non-dimensional start and end positions along the profile\n for j in range(self.n_webs):\n\n offset = inputs['web_offset_y_pa_yaml'][j,i]\n # Geometry checks on webs \n if offset < ratio_Websmax * (- chord * p_le_i) or offset > ratio_Websmax * (chord * (1. - p_le_i)):\n offset_old = copy.copy(offset)\n if offset_old <= 0.:\n offset = ratio_Websmax * (- chord * p_le_i)\n else:\n offset = ratio_Websmax * (chord * (1. - p_le_i))\n \n outputs['web_offset_y_pa'][j,i] = copy.copy(offset)\n layer_resize_warning = 'WARNING: Web \"%s\" may be too large to fit within chord. \"offset_x_pa\" changed from %f to %f at R=%f (i=%d)'%(web_name[j], offset_old, offset, inputs['s'][i], i)\n print(layer_resize_warning)\n else:\n outputs['web_offset_y_pa'][j,i] = copy.copy(offset)\n\n if discrete_inputs['definition_web'][j] == 1:\n web_rotation[j,i] = - inputs['twist'][i]\n web_start_nd[j,i], web_end_nd[j,i] = calc_axis_intersection(inputs['coord_xy_dim'][i,:,:], - web_rotation[j,i], outputs['web_offset_y_pa'][j,i], [0.,0.], ['suction', 'pressure'])\n elif discrete_inputs['definition_web'][j] == 2:\n web_rotation[j,i] = - inputs['web_rotation_yaml'][j,i]\n web_start_nd[j,i], web_end_nd[j,i] = calc_axis_intersection(inputs['coord_xy_dim'][i,:,:], - web_rotation[j,i], outputs['web_offset_y_pa'][j,i], [0.,0.], ['suction', 'pressure'])\n if i == 0:\n print('WARNING: The web ' + web_name[j] + ' is defined with a user-defined rotation. If you are planning to run a twist optimization, you may want to rethink this definition.')\n if web_start_nd[j,i] < 0. or web_start_nd[j,i] > 1.:\n print('WARNING: Blade web ' + web_name[j] + ' at n.d. span position ' + str(inputs['s'][i]) + ' has the n.d. start point outside the TE. Please check the yaml input file.')\n if web_end_nd[j,i] < 0. or web_end_nd[j,i] > 1.:\n print('WARNING: Blade web ' + web_name[j] + ' at n.d. span position ' + str(inputs['s'][i]) + ' has the n.d. end point outside the TE. Please check the yaml input file.')\n elif discrete_inputs['definition_web'][j] == 3:\n web_start_nd[j,i] = inputs['web_start_nd_yaml'][j,i]\n web_end_nd[j,i] = inputs['web_end_nd_yaml'][j,i]\n else:\n exit('Blade web ' + web_name[j] + ' not described correctly. Please check the yaml input file.')\n \n # Loop through the layers and compute non-dimensional start and end positions along the profile for the different layer definitions\n for j in range(self.n_layers):\n if discrete_inputs['definition_layer'][j] == 1: # All around\n layer_start_nd[j,i] = 0.\n layer_end_nd[j,i] = 1.\n elif discrete_inputs['definition_layer'][j] == 2 or discrete_inputs['definition_layer'][j] == 3: # Midpoint and width\n if discrete_inputs['definition_layer'][j] == 2:\n layer_rotation[j,i] = - inputs['twist'][i]\n else:\n layer_rotation[j,i] = - inputs['layer_rotation_yaml'][j,i]\n midpoint = calc_axis_intersection(inputs['coord_xy_dim'][i,:,:], - layer_rotation[j,i], inputs['layer_offset_y_pa_yaml'][j,i], [0.,0.], [discrete_inputs['layer_side'][j]])[0]\n\n # Geometry check to make sure the spar caps does not exceed 80% of the chord\n width = inputs['layer_width_yaml'][j,i]\n offset = inputs['layer_offset_y_pa_yaml'][j,i]\n if offset + 0.5 * width > ratio_SCmax * chord * (1. - p_le_i) or offset - 0.5 * width < - ratio_SCmax * chord * p_le_i: # hitting TE or LE\n width_old = copy.copy(width)\n width = 2. * min([ratio_SCmax * (chord * p_le_i ) , ratio_SCmax * (chord * (1. - p_le_i))])\n offset = 0.0\n outputs['layer_width'][j,i] = copy.copy(width)\n outputs['layer_offset_y_pa'][j,i] = copy.copy(offset)\n layer_resize_warning = 'WARNING: Layer \"%s\" may be too large to fit within chord. \"offset_x_pa\" changed from %f to 0.0 and \"width\" changed from %f to %f at s=%f (i=%d)'%(layer_name[j], offset, width_old, width, inputs['s'][i], i)\n print(layer_resize_warning)\n else:\n outputs['layer_width'][j,i] = copy.copy(width)\n outputs['layer_offset_y_pa'][j,i] = copy.copy(offset)\n\n layer_start_nd[j,i] = midpoint-width/arc_L_i/2.\n layer_end_nd[j,i] = midpoint+width/arc_L_i/2.\n\n elif discrete_inputs['definition_layer'][j] == 4: # Midpoint and width\n midpoint = 1. \n inputs['layer_midpoint_nd'][j,i] = midpoint\n width = inputs['layer_width_yaml'][j,i]\n outputs['layer_width'][j,i] = copy.copy(width)\n layer_start_nd[j,i] = midpoint-width/arc_L_i/2.\n layer_end_nd[j,i] = width/arc_L_i/2.\n\n # Geometry check to prevent overlap between SC and TE reinf\n for k in range(self.n_layers):\n if discrete_inputs['definition_layer'][k] == 2 or discrete_inputs['definition_layer'][k] == 3:\n if layer_end_nd[j,i] > layer_start_nd[k,i] or layer_start_nd[j,i] < layer_end_nd[k,i]:\n print('WARNING: The trailing edge reinforcement extends above the spar caps at station ' + str(i) + '. Please reduce its width.')\n\n elif discrete_inputs['definition_layer'][j] == 5: # Midpoint and width\n midpoint = LE_loc\n inputs['layer_midpoint_nd'][j,i] = midpoint\n width = inputs['layer_width_yaml'][j,i]\n outputs['layer_width'][j,i] = copy.copy(width)\n layer_start_nd[j,i] = midpoint-width/arc_L_i/2.\n layer_end_nd[j,i] = midpoint+width/arc_L_i/2.\n # Geometry check to prevent overlap between SC and LE reinf\n for k in range(self.n_layers):\n if discrete_inputs['definition_layer'][k] == 2 or discrete_inputs['definition_layer'][k] == 3:\n if discrete_inputs['layer_side'][k] == 'suction' and layer_start_nd[j,i] < layer_end_nd[k,i]:\n print('WARNING: The leading edge reinforcement extends above the spar caps at station ' + str(i) + '. Please reduce its width.')\n elif discrete_inputs['layer_side'][k] == 'pressure' and layer_end_nd[j,i] > layer_start_nd[k,i]:\n print('WARNING: The leading edge reinforcement extends above the spar caps at station ' + str(i) + '. Please reduce its width.')\n else:\n pass\n elif discrete_inputs['definition_layer'][j] == 6: # Start and end locked to other element\n # if inputs['layer_start_nd'][j,i] > 1:\n layer_start_nd[j,i] = layer_end_nd[int(discrete_inputs['index_layer_start'][j]),i]\n # if inputs['layer_end_nd'][j,i] > 1:\n layer_end_nd[j,i] = layer_start_nd[int(discrete_inputs['index_layer_end'][j]),i]\n elif discrete_inputs['definition_layer'][j] == 7: # Start nd and width\n width = inputs['layer_width_yaml'][j,i]\n outputs['layer_width'][j,i] = copy.copy(width)\n layer_start_nd[j,i] = inputs['layer_start_nd_yaml'][j,i]\n layer_end_nd[j,i] = layer_start_nd[j,i] + width/arc_L_i\n elif discrete_inputs['definition_layer'][j] == 8: # End nd and width\n width = inputs['layer_width_yaml'][j,i]\n outputs['layer_width'][j,i] = copy.copy(width)\n layer_end_nd[j,i] = inputs['layer_end_nd_yaml'][j,i]\n layer_start_nd[j,i] = layer_end_nd[j,i] - width/arc_L_i\n elif discrete_inputs['definition_layer'][j] == 9: # Start and end nd positions\n layer_start_nd[j,i] = inputs['layer_start_nd_yaml'][j,i]\n layer_end_nd[j,i] = inputs['layer_end_nd_yaml'][j,i]\n elif discrete_inputs['definition_layer'][j] == 10: # Web layer\n pass\n elif discrete_inputs['definition_layer'][j] == 11: # Start nd arc locked to LE\n layer_start_nd[j,i] = LE_loc + 1.e-6\n layer_end_nd[j,i] = layer_start_nd[int(discrete_inputs['index_layer_end'][j]),i]\n elif discrete_inputs['definition_layer'][j] == 12: # End nd arc locked to LE\n layer_end_nd[j,i] = LE_loc - 1.e-6\n layer_start_nd[j,i] = layer_end_nd[int(discrete_inputs['index_layer_start'][j]),i]\n else:\n exit('Blade layer ' + str(layer_name[j]) + ' not described correctly. Please check the yaml input file.')\n \n # Assign openmdao outputs\n outputs['web_rotation'] = web_rotation\n outputs['web_start_nd'] = web_start_nd\n outputs['web_end_nd'] = web_end_nd\n outputs['layer_rotation'] = layer_rotation\n outputs['layer_start_nd'] = layer_start_nd\n outputs['layer_end_nd'] = layer_end_nd\n\ndef calc_axis_intersection(xy_coord, rotation, offset, p_le_d, side, thk=0.):\n # dimentional analysis that takes a rotation and offset from the pitch axis and calculates the airfoil intersection\n # rotation\n offset_x = offset*np.cos(rotation) + p_le_d[0]\n offset_y = offset*np.sin(rotation) + p_le_d[1]\n\n m_rot = np.sin(rotation)/np.cos(rotation) # slope of rotated axis\n plane_rot = [m_rot, -1*m_rot*p_le_d[0]+ p_le_d[1]] # coefficients for rotated axis line: a1*x + a0\n\n m_intersection = np.sin(rotation+np.pi/2.)/np.cos(rotation+np.pi/2.) # slope perpendicular to rotated axis\n plane_intersection = [m_intersection, -1*m_intersection*offset_x+offset_y] # coefficients for line perpendicular to rotated axis line at the offset: a1*x + a0\n \n # intersection between airfoil surface and the line perpendicular to the rotated/offset axis\n y_intersection = np.polyval(plane_intersection, xy_coord[:,0])\n \n idx_le = np.argmin(xy_coord[:,0])\n xy_coord_arc = arc_length(xy_coord)\n arc_L = xy_coord_arc[-1]\n xy_coord_arc /= arc_L\n \n idx_inter = np.argwhere(np.diff(np.sign(xy_coord[:,1] - y_intersection))).flatten() # find closest airfoil surface points to intersection \n \n midpoint_arc = []\n for sidei in side:\n if sidei.lower() == 'suction':\n tangent_line = np.polyfit(xy_coord[idx_inter[0]:idx_inter[0]+2, 0], xy_coord[idx_inter[0]:idx_inter[0]+2, 1], 1)\n elif sidei.lower() == 'pressure':\n tangent_line = np.polyfit(xy_coord[idx_inter[1]:idx_inter[1]+2, 0], xy_coord[idx_inter[1]:idx_inter[1]+2, 1], 1)\n\n midpoint_x = (tangent_line[1]-plane_intersection[1])/(plane_intersection[0]-tangent_line[0])\n midpoint_y = plane_intersection[0]*(tangent_line[1]-plane_intersection[1])/(plane_intersection[0]-tangent_line[0]) + plane_intersection[1]\n\n # convert to arc position\n if sidei.lower() == 'suction':\n x_half = xy_coord[:idx_le+1,0]\n arc_half = xy_coord_arc[:idx_le+1]\n\n elif sidei.lower() == 'pressure':\n x_half = xy_coord[idx_le:,0]\n arc_half = xy_coord_arc[idx_le:]\n \n midpoint_arc.append(remap2grid(x_half, arc_half, midpoint_x, spline=interp1d))\n\n return midpoint_arc\n\nclass Hub(om.Group):\n # Openmdao group with the hub data coming from the input yaml file.\n def setup(self):\n ivc = self.add_subsystem('hub_indep_vars', om.IndepVarComp(), promotes=['*'])\n \n ivc.add_output('diameter', val=0.0, units='m', desc='Diameter of the hub. It is equal to two times the distance of the blade root from the rotor center along the coned line.')\n ivc.add_output('cone', val=0.0, units='rad', desc='Cone angle of the rotor. It defines the angle between the rotor plane and the blade pitch axis. A standard machine has positive values.')\n ivc.add_output('drag_coeff', val=0.0, desc='Drag coefficient to estimate the aerodynamic forces generated by the hub.')\n\n ivc.add_output('system_mass', val=0.0, units='kg', desc='Mass of hub system')\n ivc.add_output('system_I', val=np.zeros(6), units='kg*m**2', desc='Mass moments of Inertia of hub [Ixx, Iyy, Izz, Ixy, Ixz, Iyz] around its center of mass in yaw-aligned c.s.')\n ivc.add_output('system_cm', val=np.zeros(3), units='m', desc='Center of mass in yaw-aligned c.s.')\n \n exec_comp = om.ExecComp('radius = 0.5 * diameter', units='m', radius={'desc' : 'Radius of the hub. It defines the distance of the blade root from the rotor center along the coned line.'})\n self.add_subsystem('compute_radius', exec_comp, promotes=['*'])\n\nclass ComputeGrid(om.ExplicitComponent):\n \"\"\"\n Compute the non-dimensional grid or a tower or monopile.\n \n Using the dimensional `ref_axis` array, this component computes the\n non-dimensional grid, height (vertical distance) and length (curve distance)\n of a tower or monopile.\n \"\"\"\n \n def initialize(self):\n self.options.declare('init_options')\n \n def setup(self):\n init_options = self.options['init_options']\n n_height = init_options['n_height']\n\n self.add_input('ref_axis', val=np.zeros((n_height, 3)), units='m', desc='2D array of the coordinates (x,y,z) of the tower reference axis. The coordinate system is the global coordinate system of OpenFAST: it is placed at tower base with x pointing downwind, y pointing on the side and z pointing vertically upwards. A standard tower configuration will have zero x and y values and positive z values.')\n \n self.add_output('s', val=np.zeros(n_height), desc='1D array of the non-dimensional grid defined along the tower axis (0-tower base, 1-tower top)')\n self.add_output('height', val=0.0, units='m', desc='Scalar of the tower height computed along the z axis.')\n self.add_output('length', val=0.0, units='m', desc='Scalar of the tower length computed along its curved axis. A standard straight tower will be as high as long.')\n \n # Declare all partial derivatives.\n self.declare_partials('height', 'ref_axis')\n self.declare_partials('length', 'ref_axis')\n self.declare_partials('s', 'ref_axis')\n \n def compute(self, inputs, outputs):\n # Compute tower height and tower length (a straight tower will be high as long)\n outputs['height'] = inputs['ref_axis'][-1,2] - inputs['ref_axis'][0,2]\n myarc = arc_length(inputs['ref_axis'])\n outputs['length'] = myarc[-1]\n \n if myarc[-1] > 0.0:\n outputs['s'] = myarc / myarc[-1]\n \n def compute_partials(self, inputs, partials):\n n_height = self.options['init_options']['n_height']\n partials['height','ref_axis'] = np.zeros((1,n_height*3))\n partials['height','ref_axis'][0,-1] = 1.0\n partials['height','ref_axis'][0,2] = -1.0\n arc_distances, d_arc_distances_d_points = arc_length_deriv(inputs['ref_axis'])\n \n # The length is based on only the final point in the arc,\n # but that final point has sensitivity to all ref_axis points\n partials['length', 'ref_axis'] = d_arc_distances_d_points[-1, :]\n \n # Do quotient rule to get the non-dimensional grid derivatives\n low_d_high = arc_distances[-1] * d_arc_distances_d_points\n high_d_low = np.outer(arc_distances, d_arc_distances_d_points[-1, :])\n partials['s', 'ref_axis'] = (low_d_high - high_d_low) / arc_distances[-1]**2\n \nclass Tower(om.Group):\n \n def initialize(self):\n self.options.declare('tower_init_options')\n \n def setup(self):\n tower_init_options = self.options['tower_init_options']\n n_height = tower_init_options['n_height']\n n_layers = tower_init_options['n_layers']\n \n ivc = self.add_subsystem('tower_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('ref_axis', val=np.zeros((n_height, 3)), units='m', desc='2D array of the coordinates (x,y,z) of the tower reference axis. The coordinate system is the global coordinate system of OpenFAST: it is placed at tower base with x pointing downwind, y pointing on the side and z pointing vertically upwards. A standard tower configuration will have zero x and y values and positive z values.')\n ivc.add_output('diameter', val=np.zeros(n_height), units='m', desc='1D array of the outer diameter values defined along the tower axis.')\n ivc.add_output('layer_thickness', val=np.zeros((n_layers, n_height-1)), units='m', desc='2D array of the thickness of the layers of the tower structure. The first dimension represents each layer, the second dimension represents each piecewise-constant entry of the tower sections.')\n ivc.add_output('outfitting_factor', val = 0.0, desc='Multiplier that accounts for secondary structure mass inside of tower')\n ivc.add_discrete_output('layer_name', val=[], desc='1D array of the names of the layers modeled in the tower structure.')\n ivc.add_discrete_output('layer_mat', val=[], desc='1D array of the names of the materials of each layer modeled in the tower structure.')\n \n self.add_subsystem('compute_tower_grid',\n ComputeGrid(init_options=tower_init_options),\n promotes=['*'])\n \nclass Monopile(om.Group):\n \n def initialize(self):\n self.options.declare('monopile_init_options')\n \n def setup(self):\n monopile_init_options = self.options['monopile_init_options']\n n_height = monopile_init_options['n_height']\n n_layers = monopile_init_options['n_layers']\n \n ivc = self.add_subsystem('monopile_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('diameter', val=np.zeros(n_height), units='m', desc='1D array of the outer diameter values defined along the tower axis.')\n ivc.add_discrete_output('layer_name', val=n_layers * [''], desc='1D array of the names of the layers modeled in the tower structure.')\n ivc.add_discrete_output('layer_mat', val=n_layers * [''], desc='1D array of the names of the materials of each layer modeled in the tower structure.')\n ivc.add_output('layer_thickness', val=np.zeros((n_layers, n_height-1)), units='m', desc='2D array of the thickness of the layers of the tower structure. The first dimension represents each layer, the second dimension represents each piecewise-constant entry of the tower sections.')\n ivc.add_output('outfitting_factor', val = 0.0, desc='Multiplier that accounts for secondary structure mass inside of tower')\n ivc.add_output('transition_piece_height', val = 0.0, units='m', desc='point mass height of transition piece above water line')\n ivc.add_output('transition_piece_mass', val = 0.0, units='kg', desc='point mass of transition piece')\n ivc.add_output('transition_piece_cost', val = 0.0, units='USD', desc='cost of transition piece')\n ivc.add_output('gravity_foundation_mass', val = 0.0, units='kg', desc='extra mass of gravity foundation')\n ivc.add_output('suctionpile_depth', val = 0.0, units='m', desc='depth of foundation in the soil')\n ivc.add_output('suctionpile_depth_diam_ratio', 0.0, desc='ratio of sunction pile depth to mudline monopile diameter')\n \n self.add_subsystem('compute_monopile_grid',\n ComputeGrid(init_options=monopile_init_options),\n promotes=['*'])\n \nclass Floating(om.Group):\n def initialize(self):\n self.options.declare('floating_init_options')\n\n def setup(self):\n floating_init_options = self.options['floating_init_options']\n\n ivc = self.add_subsystem('floating_indep_vars', om.IndepVarComp(), promotes=['*'])\n \n ivc.add_output('radius_to_offset_column', 0.0, units='m')\n ivc.add_discrete_output('number_of_offset_columns', 0)\n ivc.add_output('fairlead_location', 0.0)\n ivc.add_output('fairlead_offset_from_shell', 0.0, units='m')\n ivc.add_output('outfitting_cost_rate', 0.0, units='USD/kg')\n ivc.add_discrete_output('loading', 'hydrostatic')\n ivc.add_output('transition_piece_height', val = 0.0, units='m', desc='point mass height of transition piece above water line')\n ivc.add_output('transition_piece_mass', val = 0.0, units='kg', desc='point mass of transition piece')\n\n self.add_subsystem('main_column', Column(options=floating_init_options['column']['main']))\n self.add_subsystem('offset_column', Column(options=floating_init_options['column']['offset']))\n self.add_subsystem('tower', Tower(options=floating_init_options['tower']))\n self.add_subsystem('mooring', Mooring(options=floating_init_options['mooring'])) \n \nclass Column(om.Group):\n def initialize(self):\n self.options.declare('column_init_options')\n\n def setup(self):\n column_init_options = self.options['column_init_options']\n \n ivc = self.add_subsystem('column_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('diameter', val=np.zeros(n_height), units='m', desc='1D array of the outer diameter values defined along the column axis.')\n ivc.add_discrete_output('layer_name', val=n_layers * [''], desc='1D array of the names of the layers modeled in the columnn structure.')\n ivc.add_discrete_output('layer_mat', val=n_layers * [''], desc='1D array of the names of the materials of each layer modeled in the column structure.')\n ivc.add_output('layer_thickness', val=np.zeros((n_layers, n_height-1)), units='m', desc='2D array of the thickness of the layers of the column structure. The first dimension represents each layer, the second dimension represents each piecewise-constant entry of the column sections.')\n ivc.add_output('freeboard', 0.0, units='m') # Have to add here because cannot promote ivc from Column before needed by tower. Grr\n ivc.add_output('outfitting_factor', val = 0.0, desc='Multiplier that accounts for secondary structure mass inside of column')\n\n ivc.add_output('stiffener_web_height', np.zeros(n_sect), units='m')\n ivc.add_output('stiffener_web_thickness', np.zeros(n_sect), units='m')\n ivc.add_output('stiffener_flange_width', np.zeros(n_sect), units='m')\n ivc.add_output('stiffener_flange_thickness', np.zeros(n_sect), units='m')\n ivc.add_output('stiffener_spacing', np.zeros(n_sect), units='m')\n ivc.add_output('bulkhead_thickness', np.zeros(n_height), units='m')\n ivc.add_output('permanent_ballast_height', 0.0, units='m')\n ivc.add_output('buoyancy_tank_diameter', 0.0, units='m')\n ivc.add_output('buoyancy_tank_height', 0.0, units='m')\n ivc.add_output('buoyancy_tank_location', 0.0, units='m')\n \n self.add_subsystem('compute_monopile_grid',\n ComputeGrid(init_options=column_init_options),\n promotes=['*'])\n \nclass Mooring(om.Group):\n def initialize(self):\n self.options.declare('mooring_init_options')\n\n def setup(self):\n mooring_init_options = self.options['mooring_init_options']\n \n ivc = self.add_subsystem('mooring_indep_vars', om.IndepVarComp(), promotes=['*'])\n ivc.add_output('mooring_line_length', 0.0, units='m')\n ivc.add_output('anchor_radius', 0.0, units='m')\n ivc.add_output('mooring_diameter', 0.0, units='m')\n ivc.add_output('number_of_mooring_connections', 0)\n ivc.add_output('mooring_lines_per_connection', 0)\n ivc.add_discrete_output('mooring_type', 'chain')\n ivc.add_discrete_output('anchor_type', 'SUCTIONPILE')\n ivc.add_output('max_offset', 0.0, units='m')\n ivc.add_output('operational_heel', 0.0, units='deg')\n ivc.add_output('mooring_cost_factor', 0.0)\n ivc.add_output('max_survival_heel', 0.0, units='deg')\n \nclass ComputeMaterialsProperties(om.ExplicitComponent):\n # Openmdao component with the wind turbine materials coming from the input yaml file. The inputs and outputs are arrays where each entry represents a material\n \n def initialize(self):\n self.options.declare('mat_init_options')\n \n def setup(self):\n \n mat_init_options = self.options['mat_init_options']\n self.n_mat = n_mat = mat_init_options['n_mat']\n \n self.add_discrete_input('name', val=n_mat * [''], desc='1D array of names of materials.')\n self.add_discrete_input('component_id', val=-np.ones(n_mat), desc='1D array of flags to set whether a material is used in a blade: 0 - coating, 1 - sandwich filler , 2 - shell skin, 3 - shear webs, 4 - spar caps, 5 - TE reinf.isotropic.')\n self.add_input('rho_fiber', val=np.zeros(n_mat), units='kg/m**3',desc='1D array of the density of the fibers of the materials.')\n self.add_input('rho', val=np.zeros(n_mat), units='kg/m**3',desc='1D array of the density of the materials. For composites, this is the density of the laminate.')\n self.add_input('rho_area_dry', val=np.zeros(n_mat), units='kg/m**2',desc='1D array of the dry aerial density of the composite fabrics. Non-composite materials are kept at 0.')\n self.add_input('ply_t_from_yaml', val=np.zeros(n_mat), units='m', desc='1D array of the ply thicknesses of the materials. Non-composite materials are kept at 0.')\n self.add_input('fvf_from_yaml', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber volume fraction of the composite materials. Non-composite materials are kept at 0.')\n self.add_input('fwf_from_yaml', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber weight- fraction of the composite materials. Non-composite materials are kept at 0.')\n \n self.add_output('ply_t', val=np.zeros(n_mat), units='m', desc='1D array of the ply thicknesses of the materials. Non-composite materials are kept at 0.')\n self.add_output('fvf', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber volume fraction of the composite materials. Non-composite materials are kept at 0.')\n self.add_output('fwf', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber weight- fraction of the composite materials. Non-composite materials are kept at 0.')\n \n def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n \n density_resin = 0.\n for i in range(self.n_mat):\n if discrete_inputs['name'][i] == 'resin':\n density_resin = inputs['rho'][i]\n id_resin = i\n if density_resin==0.:\n exit('Error: a material named resin must be defined in the input yaml')\n \n fvf = np.zeros(self.n_mat)\n fwf = np.zeros(self.n_mat)\n ply_t = np.zeros(self.n_mat)\n \n for i in range(self.n_mat):\n if discrete_inputs['component_id'][i] > 1: # It's a composite\n \n # Formula to estimate the fiber volume fraction fvf from the laminate and the fiber densities\n fvf[i] = (inputs['rho'][i] - density_resin) / (inputs['rho_fiber'][i] - density_resin) \n if inputs['fvf_from_yaml'][i] > 0.:\n if abs(fvf[i] - inputs['fvf_from_yaml'][i]) > 1e-3:\n exit('Error: the fvf of composite ' + discrete_inputs['name'][i] + ' specified in the yaml is equal to '+ str(inputs['fvf_from_yaml'][i] * 100) + '%, but this value is not compatible to the other values provided. Given the fiber, laminate and resin densities, it should instead be equal to ' + str(fvf[i]*100.) + '%.')\n else:\n outputs['fvf'] = inputs['fvf_from_yaml']\n else:\n outputs['fvf'][i] = fvf[i]\n \n # Formula to estimate the fiber weight fraction fwf from the fiber volume fraction and the fiber densities\n fwf[i] = inputs['rho_fiber'][i] * outputs['fvf'][i] / (density_resin + ((inputs['rho_fiber'][i] - density_resin) * outputs['fvf'][i]))\n if inputs['fwf_from_yaml'][i] > 0.:\n if abs(fwf[i] - inputs['fwf_from_yaml'][i]) > 1e-3:\n exit('Error: the fwf of composite ' + discrete_inputs['name'][i] + ' specified in the yaml is equal to '+ str(inputs['fwf_from_yaml'][i] * 100) + '%, but this value is not compatible to the other values provided. It should instead be equal to ' + str(fwf[i]*100.) + '%')\n else:\n outputs['fwf'] = inputs['fwf_from_yaml']\n else:\n outputs['fwf'][i] = fwf[i]\n \n # Formula to estimate the plyt thickness ply_t of a laminate from the aerial density, the laminate density and the fiber weight fraction\n ply_t[i] = inputs['rho_area_dry'][i] / inputs['rho'][i] / outputs['fwf'][i]\n if inputs['ply_t_from_yaml'][i] > 0.:\n if abs(ply_t[i] - inputs['ply_t_from_yaml'][i]) > 1.e-4:\n exit('Error: the ply_t of composite ' + discrete_inputs['name'][i] + ' specified in the yaml is equal to '+ str(inputs['ply_t_from_yaml'][i]) + 'm, but this value is not compatible to the other values provided. It should instead be equal to ' + str(ply_t[i]) + 'm. Alternatively, adjust the aerial density to ' + str(outputs['ply_t'][i] * inputs['rho'][i] * outputs['fwf'][i]) + ' kg/m2.')\n else:\n outputs['ply_t'] = inputs['ply_t_from_yaml']\n else:\n outputs['ply_t'][i] = ply_t[i] \n \nclass Materials(om.Group):\n # Openmdao group with the wind turbine materials coming from the input yaml file.\n # The inputs and outputs are arrays where each entry represents a material\n \n def initialize(self):\n self.options.declare('mat_init_options')\n \n def setup(self):\n mat_init_options = self.options['mat_init_options']\n self.n_mat = n_mat = mat_init_options['n_mat']\n \n ivc = self.add_subsystem('materials_indep_vars', om.IndepVarComp(), promotes=['*'])\n \n ivc.add_discrete_output('orth', val=np.zeros(n_mat), desc='1D array of flags to set whether a material is isotropic (0) or orthtropic (1). Each entry represents a material.')\n ivc.add_output('E', val=np.zeros([n_mat, 3]), units='Pa', desc='2D array of the Youngs moduli of the materials. Each row represents a material, the three columns represent E11, E22 and E33.')\n ivc.add_output('G', val=np.zeros([n_mat, 3]), units='Pa', desc='2D array of the shear moduli of the materials. Each row represents a material, the three columns represent G12, G13 and G23.')\n ivc.add_output('nu', val=np.zeros([n_mat, 3]), desc='2D array of the Poisson ratio of the materials. Each row represents a material, the three columns represent nu12, nu13 and nu23.')\n ivc.add_output('Xt', val=np.zeros([n_mat, 3]), units='Pa', desc='2D array of the Ultimate Tensile Strength (UTS) of the materials. Each row represents a material, the three columns represent Xt12, Xt13 and Xt23.')\n ivc.add_output('Xc', val=np.zeros([n_mat, 3]), units='Pa', desc='2D array of the Ultimate Compressive Strength (UCS) of the materials. Each row represents a material, the three columns represent Xc12, Xc13 and Xc23.')\n ivc.add_output('sigma_y', val=np.zeros(n_mat), units='Pa', desc='Yield stress of the material (in the principle direction for composites).')\n ivc.add_output('unit_cost', val=np.zeros(n_mat), units='USD/kg', desc='1D array of the unit costs of the materials.')\n ivc.add_output('waste', val=np.zeros(n_mat), desc='1D array of the non-dimensional waste fraction of the materials.')\n ivc.add_output('roll_mass', val=np.zeros(n_mat), units='kg', desc='1D array of the roll mass of the composite fabrics. Non-composite materials are kept at 0.')\n \n ivc.add_discrete_output('name', val=n_mat * [''], desc='1D array of names of materials.')\n ivc.add_discrete_output('component_id', val=-np.ones(n_mat), desc='1D array of flags to set whether a material is used in a blade: 0 - coating, 1 - sandwich filler , 2 - shell skin, 3 - shear webs, 4 - spar caps, 5 - TE reinf.isotropic.')\n ivc.add_output('rho_fiber', val=np.zeros(n_mat), units='kg/m**3',desc='1D array of the density of the fibers of the materials.')\n ivc.add_output('rho', val=np.zeros(n_mat), units='kg/m**3',desc='1D array of the density of the materials. For composites, this is the density of the laminate.')\n ivc.add_output('rho_area_dry', val=np.zeros(n_mat), units='kg/m**2',desc='1D array of the dry aerial density of the composite fabrics. Non-composite materials are kept at 0.')\n ivc.add_output('ply_t_from_yaml', val=np.zeros(n_mat), units='m', desc='1D array of the ply thicknesses of the materials. Non-composite materials are kept at 0.')\n ivc.add_output('fvf_from_yaml', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber volume fraction of the composite materials. Non-composite materials are kept at 0.')\n ivc.add_output('fwf_from_yaml', val=np.zeros(n_mat), desc='1D array of the non-dimensional fiber weight- fraction of the composite materials. Non-composite materials are kept at 0.')\n \n self.add_subsystem('compute_materials_properties', ComputeMaterialsProperties(mat_init_options=mat_init_options), promotes=['*'])\n \nclass WT_Assembly(om.ExplicitComponent):\n # Openmdao component that computes assembly quantities, such as the rotor coordinate of the blade stations, the hub height, and the blade-tower clearance\n def initialize(self):\n self.options.declare('blade_init_options')\n\n def setup(self):\n n_span = self.options['blade_init_options']['n_span']\n\n self.add_input('blade_ref_axis', val=np.zeros((n_span,3)),units='m', desc='2D array of the coordinates (x,y,z) of the blade reference axis, defined along blade span. The coordinate system is the one of BeamDyn: it is placed at blade root with x pointing the suction side of the blade, y pointing the trailing edge and z along the blade span. A standard configuration will have negative x values (prebend), if swept positive y values, and positive z values.')\n self.add_input('hub_radius', val=0.0, units='m', desc='Radius of the hub. It defines the distance of the blade root from the rotor center along the coned line.')\n self.add_input('monopile_height', val=0.0, units='m', desc='Scalar of the monopile height computed along its axis from monopile base.')\n self.add_input('tower_height', val=0.0, units='m', desc='Scalar of the tower height computed along its axis from tower base.')\n self.add_input('foundation_height', val=0.0, units='m', desc='Scalar of the foundation height computed along its axis.')\n self.add_input('distance_tt_hub', val=0.0, units='m', desc='Vertical distance from tower top to hub center.')\n\n self.add_output('r_blade', val=np.zeros(n_span), units='m', desc='1D array of the dimensional spanwise grid defined along the rotor (hub radius to blade tip projected on the plane)')\n self.add_output('rotor_radius', val=0.0, units='m', desc='Scalar of the rotor radius, defined ignoring prebend and sweep curvatures, and cone and uptilt angles.')\n self.add_output('rotor_diameter', val=0.0, units='m', desc='Scalar of the rotor diameter, defined ignoring prebend and sweep curvatures, and cone and uptilt angles.')\n self.add_output('hub_height', val=0.0, units='m', desc='Height of the hub in the global reference system, i.e. distance rotor center to ground.')\n\n def compute(self, inputs, outputs):\n \n outputs['r_blade'] = inputs['blade_ref_axis'][:,2] + inputs['hub_radius']\n outputs['rotor_radius'] = outputs['r_blade'][-1]\n outputs['rotor_diameter'] = outputs['rotor_radius'] * 2.\n outputs['hub_height'] = inputs['monopile_height'] + inputs['tower_height'] + inputs['distance_tt_hub'] + inputs['foundation_height']\n","sub_path":"WISDEM/wisdem/glue_code/gc_WT_DataStruc.py","file_name":"gc_WT_DataStruc.py","file_ext":"py","file_size_in_byte":104149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"266685222","text":"from django.contrib.auth import logout, login, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom website.models.models import Profile, User\nfrom website.forms.forms import ProfileForm, EditUserForm, UserForm\n\ndef edit_account(request):\n \"\"\"This function allows the user to change his/her account settings including first name, last name, address, and phone number.\n \n Args:\n request (LIST): A list of tuples from the database pertaining to payment\n \n Returns:\n request: A list of tuples from the database\n template_name (HTML): The webpage's structure\n payment (DICT): This is the profile information stored inside of a dictionary\n\n Author:\n Nick Nash\n Adam Myers\n \"\"\"\n if request.method == \"POST\":\n user = User.objects.get(id=request.user.id)\n user.first_name = request.POST['first_name']\n user.last_name = request.POST['last_name']\n user.save()\n\n profile = Profile.objects.get(pk=request.user.id)\n profile_form = ProfileForm(request.POST or None, instance=profile)\n\n if profile_form.is_valid():\n profile_form.save()\n else:\n return show_edit_account(request, error=profile_form.errors.values())\n\n context = {'profile': profile, 'user': user}\n template_name = 'profile.html'\n return render(request, template_name, context)\n else:\n return show_edit_account(request)\n\ndef show_edit_account(request, error=False):\n u = request.user\n user_form = EditUserForm(initial={'first_name': u.first_name, 'last_name': u.last_name})\n\n u_p = Profile.objects.get(pk=u.id)\n profile_form = ProfileForm(initial={'address': u_p.address, 'phone_number': u_p.phone_number, 'city': u_p.city, 'state': u_p.state, 'zipcode': u_p.zipcode})\n\n if error == False:\n context = {'profile_form': profile_form, 'user_form': user_form}\n else:\n context = {'profile_form': profile_form, 'user_form': user_form, 'message': error}\n \n\n template_name = 'edit_account.html'\n return render(request, template_name, context)\n\n\n\n","sub_path":"website/views/edit_account_view.py","file_name":"edit_account_view.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"78538637","text":"'''\nCreated on 23.02.2013\n\n@author: mihai_000\n'''\n\nfrom Domain.Domain import Translation\n\nclass Repository:\n \"\"\"\n Stores and reads translations from memory and file\n \"\"\"\n \n def __init__(self,fName):\n \"\"\"\n Constructor\n parameter fName - string, file name\n translationList - list where all the translations will be memorized\n try to open the file for reading\n if IOError, then create the file, close it and then reopen it with reading capabilities\n run function readFile\n \"\"\"\n self.__fileName = fName\n self.translationList = list()\n try:\n self.__translationFile = open (self.__fileName,\"r\")\n except IOError:\n self.__translationFile = open (self.__fileName,\"w\")\n self.__translationFile.close()\n self.__translationFile = open (self.__fileName,\"r\")\n self.readFile()\n \n \n def readFile(self):\n \"\"\"\n Reads translations from file and stores them into local memory\n \n line - string\n translation - object of class Translation\n \"\"\"\n \n line = \"nonempty\"\n while line != \"\":\n line = self.__translationFile.readline()\n if line != \"\":\n elems = line.split(\",\")\n translation = Translation (elems[0].strip(), elems[1].strip(), elems[2].strip(), elems[3].strip())\n self.translationList.append(translation)\n self.__translationFile.close()\n \n def storeTranslation(self,sLang,word,dLang,transWord):\n \"\"\"\n Stores translation of given parameters\n \n sLang - source language, string\n word - source word, string\n dLang - destination language, string\n transWord - translated word, string\n \n open file with writing capabilities\n write translations from memory to file, one on a row\n return message\n \"\"\"\n trans = Translation (sLang,word,dLang,transWord)\n self.translationList.append(trans)\n self.__translationFile = open (self.__fileName,\"w\")\n for trans in self.translationList:\n self.__translationFile.write(str(trans.getSLang()) + \",\" + str(trans.getWord()) + \",\" + str(trans.getDLang()) + \",\" + str(trans.getTransWord()) + \"\\n\")\n self.__translationFile.close()\n return \"Translation added successfully!\" \n \n \n \n \nclass RepositoryForText:\n \"\"\"\n A repository class made only for reading and writing strings\n \"\"\"\n \n def readsFile (self,fileName):\n \"\"\"\n fileName - string, name of a file\n try to open the file with reading capabilities\n if error, return false, else return the row on which the text is\n \n text = string\n thefile - the file of name fileName\n \"\"\"\n try:\n thefile = open (fileName, \"r\") \n text = thefile.readline()\n thefile.close()\n return text\n except IOError:\n return False\n \n def storeText(self,text,dFile):\n \"\"\"\n Stores a given string in a given file\n \n text - string, the text we have to write in file\n dFile - string, name of the destination file\n \"\"\"\n thefile = open (dFile,\"w\")\n thefile.write(text)\n thefile.close()","sub_path":"An1/Sem1/FP/ExamFP2/Repository/Repository.py","file_name":"Repository.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"476331969","text":"# 먼저 생각하기\r\n# 일단 꽂는다\r\n# 먼저 다시 사용하는건 계속 꽂아놓고, 그렇지 않은 걸 뺀다\r\n# 3구 이상이면, 계속 살펴보면서, 먼저 나오는 애들은 저장해놓는다.\r\n# n-1구 까지 저장하고 나면, 해당없는 걸 빼버린다.\r\n# 3구짜리면, 앞으로 사용할 두개만 저장해놓고, 하나는 빼버린다.\r\n# 리스트를 하나씩 순회한다.\r\n# 더 이상 뒤에 연결할 것들이 없으면, 아무거나 뽑으면 된다.\r\n\r\nimport sys\r\nsys.stdin = open('input.txt', 'r')\r\nread = sys.stdin.readline\r\n\r\nhole, appliance = map(int, read().rstrip().split())\r\nplugged = []\r\n\r\nsequence = read().rstrip().split()\r\ncnt = 0\r\nf = -1\r\nif hole >= appliance:\r\n print(0)\r\nelse:\r\n while len(plugged) != hole:\r\n f += 1\r\n if sequence[f] in plugged:\r\n continue\r\n else:\r\n plugged.append(sequence[f])\r\n for i in range(hole, appliance):\r\n soon = []\r\n if sequence[i] in plugged:\r\n continue\r\n else:\r\n for j in range(i, appliance):\r\n if sequence[j] in plugged and sequence[j] not in soon:\r\n if len(soon) >= hole-1:\r\n break\r\n soon.append(sequence[j])\r\n # print('soon', soon)\r\n for unplug in plugged:\r\n if unplug not in soon:\r\n plugged.remove(unplug)\r\n cnt += 1\r\n break\r\n plugged.append(sequence[i])\r\n # print('plugged', plugged)\r\n print(cnt)\r\n\r\n\r\n'''\r\ntestcase 모음\r\n\r\n2 7\r\n2 3 2 3 1 2 7\r\n답: 2\r\n\r\n2 5\r\n5 2 2 3 5\r\n답: 1\r\n\r\n2 4\r\n5 3 1 5\r\n답: 1\r\n\r\n3 6\r\n1 1 1 1 2 3\r\n답: 0\r\n\r\n3 8\r\n1 2 3 4 1 1 1 2\r\n답: 1\r\n\r\n2 15\r\n3 2 1 2 1 2 1 2 1 3 3 3 3 3 3\r\n답: 2\r\n\r\n1 3\r\n1 2 1\r\n답: 2\r\n\r\n3 14\r\n1 4 3 2 5 4 3 2 5 3 4 2 3 4\r\n답 4\r\n\r\n3 11\r\n11 8 11 7 2 8 2 7 5 10 2\r\n답 3\r\n\r\n'''\r\n","sub_path":"12multtap.py","file_name":"12multtap.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"387452441","text":"__author__ = [\"Markus Löning\"]\n__all__ = [\"test_check_fh_bad_input_args\"]\n\nimport numpy as np\nimport pytest\nfrom pytest import raises\n\nfrom sktime.utils.validation.forecasting import check_fh_values\n\nbad_input_args = (\n (1, 2), # tuple\n [], # empty list\n np.array([]), # empty array\n 'some_string', # string\n 0.1, # float\n -0.1, # negative float\n [0.1, 2], # float in list\n np.array([0.1, 2]), # float in list\n True, # boolean\n [True, 2], # boolean in list\n np.array([1, 2, 2]), # duplicates\n)\n\n\n@pytest.mark.parametrize(\"arg\", bad_input_args)\ndef test_check_fh_bad_input_args(arg):\n with raises(TypeError):\n check_fh_values(arg)\n","sub_path":"sktime/utils/validation/tests/test_validation_forecasting.py","file_name":"test_validation_forecasting.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"305983990","text":"#!/usr/bin/env python\n\nimport logging\n\nfrom pybluetooth import BTStack\nfrom pybluetooth.synchronous import BTStackSynchronousUtils\n\n\nLOG = logging.getLogger(\"pybluetooth\")\n\nLOG.setLevel(logging.DEBUG)\nlsh = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s> %(message)s')\nlsh.setFormatter(formatter)\nLOG.addHandler(lsh)\n\nb = BTStack()\nb.start()\n\nu = BTStackSynchronousUtils(b)\n\n# Scan for a couple seconds, then print out the found reports:\n#reports = u.scan(2)\n#for report in reports:\n# report.show()\n\nimport signal\n\ndef sigHandler(x, y):\n print(\"signal Handler '{} '{}\".format(x, y))\n import sys\n sys.exit(-1)\n\n\nsignal.signal(signal.SIGTERM, sigHandler)\n\nfor i in range(100):\n import time\n time.sleep(5)\n print('.', end='', flush=True)\n# Tear down the stack:\nb.quit()\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"196618530","text":"###EVALUATION \nimport os\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport PIL\nimport torch\nfrom IQA_pytorch import SSIM, utils, LPIPSvgg\nfrom tqdm import tqdm\nimport math\n\ndef PSNR(predict, gt):\n predict = np.asarray(predict)\n gt = np.asarray(gt)\n \n mse = np.mean((predict-gt)**2)\n if mse ==0:\n return 100\n PIXEL_MAX = 255.0\n \n return 20*math.log10(PIXEL_MAX/math.sqrt(mse))\n\ndata_path = os.path.join('datas','MTN','testdata','RGB')\npredict_path = os.path.join('results_ther2rgb')\nif __name__ == '__main__':\n \n gt_list = os.listdir(data_path)\n gt_list.sort()\n predict_list = os.listdir(predict_path)\n predict_list.sort()\n\n ssim_score = 0\n psnr_score = 0\n lpips_score = 0\n\n for name in tqdm(predict_list):\n\n img_name = name.split('.png')[0]\n try:\n index = gt_list.index('LEFT'+img_name.split('THER')[1]+'.jpg')\n # index = gt_list.index(name)\n except:\n continue\n \n gt = Image.open(os.path.join(data_path,gt_list[index]))\n gt = gt.resize((256,256))\n\n predict = Image.open(os.path.join(predict_path,name))\n psnr_score += PSNR(predict, gt)\n\n gt = utils.prepare_image(gt).cuda()\n predict = utils.prepare_image(predict).cuda()\n\n model1 = SSIM(channels=3)\n model2 = LPIPSvgg(channels=3).cuda()\n\n ssim_score += model1(predict, gt, as_loss=False)\n lpips_score += model2(predict, gt, as_loss=False)\n\n print('avg_ssim_score: %.4f' % (ssim_score/len(predict_list)).item())\n print('avg_psnr_score: %.4f' %(psnr_score/len(predict_list)))\n print('avg_lpips_score: %.4f'%(lpips_score/len(predict_list)))\n","sub_path":"Pseudo-RGB/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"607794974","text":"import sys\nimport os\n\nif sys.platform.startswith('win') or sys.platform.startswith('cygwin'):\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__), \"freetype/lib/win32\")))\n sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__), \"freetype/lib/win64\")))\n\nfrom .text_tool_gui import TextToolDialog\nfrom .text_tool_fontpick import *\nfrom .text_tool_draw import Text, Point\n\nfrom .freetype import Face\n\nimport math\nimport wx\nimport pcbnew\nimport json\n\nclass TextTool(TextToolDialog):\n\n def __init__(self, board, action):\n super(TextTool, self).__init__(None)\n self.board = board\n self.configfilepath = \".\".join(self.board.GetFileName().split('.')[:-1])+\".text-tool-config\"\n self.action = action\n\n self.fonts = load_font_list()\n for f in self.fonts:\n self.font_list.Append(f)\n \n self.load_layers()\n\n self.load_config()\n\n for l in self.layer_selections:\n self.layer_list.SetSelection(l)\n\n self.text_field.ChangeValue(self.text_line)\n self.font_list.SetSelection(self.font_index)\n self.size_spin.SetValue(self.current_size)\n\n\n font_size_mm = self.current_size*0.352778\n self.size_status.SetLabel(\"pt (\"+str(round(font_size_mm, 2))+\" mm)\")\n\n def on_size_change( self, event ):\n self.current_size = self.size_spin.GetValue()\n font_size_mm = self.current_size*0.352778\n self.size_status.SetLabel(\"pt (\"+str(round(font_size_mm, 2))+\" mm)\")\n\n def load_layers( self, ):\n #layertable = {}\n numlayers = pcbnew.PCB_LAYER_ID_COUNT\n self.layers = []\n for i in range(numlayers):\n #layertable[i] = board.GetLayerName(i)\n if self.board.IsLayerEnabled(i) and i is not 50:\n self.layers.append(i)\n self.layer_list.Append(self.board.GetLayerName(i)+ \" (\" + str(i) + \")\")\n \n def run( self, event ):\n self.Destroy()\n\n self.layer_selections = self.layer_list.GetSelections()\n self.text_line = self.text_field.GetLineText(0)\n self.font_index = self.font_list.GetSelection()\n self.font_name = self.font_list.GetString(self.font_index)\n self.current_face = Face(self.fonts[self.font_name])\n print(self.layer_selections)\n self.current_size = self.size_spin.GetValue()\n\n self.save_config()\n\n t = Text(self.text_line, self.current_face, self.current_size)\n\n origin = self.board.GetBoardEdgesBoundingBox().Centre()\n for l in self.layer_selections:\n zone_container = t.draw(self.board, self.layers[l], origin=origin)\n\n def save_config(self):\n with open(self.configfilepath, \"w\") as config_file:\n config_file.write(json.dumps({\n \"layers\" : self.layer_selections,\n \"text\" : self.text_line,\n \"font_index\" : self.font_index,\n \"size\" : self.current_size\n })) \n def load_config(self):\n config = {}\n if os.path.isfile(self.configfilepath):\n with open(self.configfilepath, \"r\") as config_file:\n try:\n config = json.loads(config_file.read())\n except Exception as e:\n print(e)\n pass\n\n self.layer_selections = config['layers'] if \"layers\" in config else [0]\n self.text_line = config['text'] if \"text\" in config else \"KiCad\"\n self.font_index = config['font_index'] if \"font_index\" in config else 10\n self.current_size = config['size'] if \"size\" in config else 8\n\n def on_close( self, event ):\n self.Destroy()\n pass\n\nclass TextToolAction( pcbnew.ActionPlugin ):\n \n def defaults( self ):\n self.name = \"Text Tool\"\n self.category = \"Modify PCB\"\n self.description = \"Adds text to your PCB using system fonts\"\n self.icon_file_name = os.path.join(os.path.dirname(__file__), \"./text_tool.png\")\n\n def Run( self ):\n board = pcbnew.GetBoard()\n rt = TextTool(board, self)\n rt.ShowModal()\n\n","sub_path":"text_tool_action.py","file_name":"text_tool_action.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"49003454","text":"import pandas as pd\n\nread_file = pd.read_csv (r'C:\\Users\\Rishu\\Downloads\\tickitdb\\allusers_pipe.txt')\nread_file.columns = ['userid','username','firstname','lastname','city','state','email','phone','likesports','liketheatre','likeconcerts','likejazz','likeclassical','likeopera','likerock','likevegas','likebroadway','likemusicals']\nread_file.to_csv (r'C:\\Users\\Rishu\\Downloads\\tickitdb\\allusers_pipe.csv', index=None)\n\n\n\n# import tkinter as tk\n# from tkinter import filedialog\n# from tkinter import messagebox\n# import pandas as pd\n#\n# root= tk.Tk()\n#\n# canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue2', relief = 'raised')\n# canvas1.pack()\n#\n# label1 = tk.Label(root, text='File Conversion Tool', bg = 'lightsteelblue2')\n# label1.config(font=('helvetica', 20))\n# canvas1.create_window(150, 60, window=label1)\n#\n# def getTxt ():\n# global read_file\n#\n# import_file_path = filedialog.askopenfilename()\n# read_file = pd.read_csv(import_file_path)\n#\n# browseButtonTxt = tk.Button(text=\" Import Text File \", command=getTxt, bg='green', fg='white', font=('helvetica', 12, 'bold'))\n# canvas1.create_window(150, 130, window=browseButtonTxt)\n#\n# def convertToCsv ():\n# global read_file\n#\n# export_file_path = filedialog.asksaveasfilename(defaultextension='.csv')\n# read_file.to_csv (export_file_path, index = None)\n#\n# saveAsButtonCsv = tk.Button(text='Convert Text to CSV', command=convertToCsv, bg='green', fg='white', font=('helvetica', 12, 'bold'))\n# canvas1.create_window(150, 180, window=saveAsButtonCsv)\n#\n# def exitApplication():\n# MsgBox = tk.messagebox.askquestion ('Exit Application','Are you sure you want to exit the application',icon = 'warning')\n# if MsgBox == 'yes':\n# root.destroy()\n#\n# exitButton = tk.Button (root, text=' Exit Application ',command=exitApplication, bg='brown', fg='white', font=('helvetica', 12, 'bold'))\n# canvas1.create_window(150, 230, window=exitButton)\n#\n# root.mainloop()","sub_path":"F. OOPS-Python/test class.py","file_name":"test class.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616202568","text":"from config import *\r\nfrom sqlalchemy import func\r\nfrom domain import models\r\n\r\nclass DataImportMetaDataQuery():\r\n def __init__(self):\r\n self.stationCount = 0\r\n self.ecmwfCount = 0\r\n self.demCount = 0\r\n self.stationDataCount = 0\r\n self.ecmwfDataCount = 0\r\n self.demDataCount = 0\r\n\r\n def get(self):\r\n printout(\"Fetching data import meta data...\")\r\n self.stationCount = db.session.query(func.count(models.Station.stationCode)).one()[0]\r\n self.stationDataCount = db.session.query(func.count(models.StationData.stationDataId)).one()[0]\r\n self.ecmwfCount = db.session.query(func.count(models.Ecmwf.ecmwfId)).one()[0]\r\n self.ecmwfDataCount = db.session.query(func.count(models.EcmwfData.ecmwfDataId)).one()[0]\r\n self.demCount = db.session.query(func.count(models.Dem.demId)).one()[0]\r\n self.demDataCount = db.session.query(func.count(models.DemData.demDataId)).one()[0]\r\n printout(self.serialize)\r\n printout(\"Meta data fetched.\")\r\n\r\n @property\r\n def serialize(self):\r\n return {\r\n 'stationCount' : self.stationCount,\r\n 'ecmwfCount' : self.ecmwfCount,\r\n 'demCount' : self.demCount,\r\n 'stationDataCount' : self.stationDataCount,\r\n 'ecmwfDataCount' : self.ecmwfDataCount,\r\n 'demDataCount' : self.demDataCount\r\n }","sub_path":"domain/queries/data_import_meta_data_query.py","file_name":"data_import_meta_data_query.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"644507855","text":"def eh_primo(n):\n if n == 1 or n == 0:\n return False\n elif n == 2:\n return True\n else:\n if n%2 == 0:\n return False\n else:\n impar = 3\n while impar < n:\n if n%impar == 0:\n return False\n impar = impar + 2\n return True\n\ndef verifica_primos(lista):\n dic = {}\n i = 0\n while i < len(lista):\n a = lista[i]\n booleano = eh_primo(a)\n dicionario [a] = booleano\n i += 1\n return dicionario","sub_path":"backup/user_337/ch75_2020_04_10_17_43_00_013434.py","file_name":"ch75_2020_04_10_17_43_00_013434.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"601579769","text":"import tkinter as tk\ndef print_something():\n v = text_box.get(\"1.0\", \"end-1c\")\n m = v.split()\n cUnit = [\n ['inc','cm','*2.54'],\n ['inc','ft','/12'],\n ['cm','inc','/12'],\n ['cm','ft','*12'],\n ['ft','inc','*30.84'],\n ['py','cy','+543'],\n ['py','cy','-543'],\n ]\n try:\n for s in cUnit:\n if (m[1] == s[0] and m[3] == s[1]):\n revert = eval(m[0]+s[2]) \n label.config(text=revert) \n except:\n try: \n total = str(eval(v)) \n label.config(text=total)\n except:\n label.config(text=m)\n\nroot = tk.Tk()\nroot.geometry(\"245x300\")\nroot.title('Google')\nroot.configure(background='#34495e')\n\nbtn = tk.Button(root, text=\"Search\", command=print_something)\nbtn.place(x = 10,y = 60,width=40,height=40)\n\ntext_box = tk.Text(root, height=4, width=300)\ntext_box.pack()\n\nlabel = tk.Label(root)\nlabel.pack()\nroot.mainloop()","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"237387759","text":"# -*- coding: utf-8 -*-\n# Initialize App Engine and import the default settings (DB backend, etc.).\n# If you want to use a different backend you have to remove all occurences\n# of \"djangoappengine\" from this file.\nfrom djangoappengine.settings_base import *\n\nimport os\nimport sys\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nPROJECT_NAME = os.path.split(PROJECT_ROOT)[-1]\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, 'static/')\n\n#applications\n#sys.path.insert(0, os.path.join(PROJECT_ROOT, 'src'))\nsys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))\nsys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps/externals'))\n#sys.path.insert(0, os.path.join(PROJECT_ROOT, 'applications/libs'))\n#sys.path.insert(0, os.path.join(PROJECT_ROOT, 'applications/externals'))\n#sys.path.insert(0, os.path.join(PROJECT_ROOT, 'applications/internals'))\n\nSECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.contenttypes',\n 'django.contrib.auth',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'djangotoolbox',\n\t'registration',\n\t'kcms',\n\n # djangoappengine should come last, so it can override a few manage.py commands\n 'djangoappengine',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n 'django.core.context_processors.media',\n)\n\n# This test runner captures stdout and associates tracebacks with their\n# corresponding output. Helps a lot with print-debugging.\nTEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner'\n\nADMIN_MEDIA_PREFIX = '/media/admin/'\nTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)\n\nROOT_URLCONF = 'urls'\n\nTIME_ZONE = 'Europe/Berlin'\nLANGUAGE_CODE = 'en'\nLANGUAGES = (('de', 'German'),\n ('en', 'English'))\nUSE_I18N = True\n\nSITE_ID = 1\n\n#============== APPS EXT====================\nACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.\n\n# Activate django-dbindexer if available\ntry:\n import dbindexer\n DATABASES['native'] = DATABASES['default']\n DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}\n INSTALLED_APPS += ('dbindexer',)\n DBINDEXER_SITECONF = 'dbindexes'\n MIDDLEWARE_CLASSES = ('dbindexer.middleware.DBIndexerMiddleware',) + \\\n MIDDLEWARE_CLASSES\nexcept ImportError:\n pass\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"94272110","text":"from struct import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef read_file(filename):\n\tf = open(filename, \"rb\")\n\tchunk = f.read(2)\n\traw_input1 = []\n\twhile chunk:\n\t\traw_input1.append(unpack('= self.count:\n return \"\"\n try:\n ret = db_basic.cursor.fetchone()\n except:\n print(\"fetchone fail\")\n return \"\"\n self.position += 1\n return ret\n","sub_path":"app/db/db_ticker.py","file_name":"db_ticker.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"50433683","text":"import os\nimport random\n\nfrom requests_futures import sessions\n\nfrom vutil import *\n\n\ndef get_basset_chance(default):\n str_value = os.environ.get('basset_chance')\n if str_value:\n try:\n return float(str_value)\n except Exception as e:\n print(\"Failed to parse \\\"basset_chance\\\" '%s'! %s\" % (str_value, e))\n print(\"Using default \\\"basset_chance\\\": %s\" % default)\n return default\n\n\nbasset_chance = get_basset_chance(0.5)\n\n\ndef get_doggos(num=3, is_basset_lover=False):\n print(\"Acquiring doggos\")\n is_basset = is_basset_lover and random.random() < basset_chance\n if is_basset:\n print(\"Basset lover mode\")\n img_url = basset_url() if is_basset else dog_url(num)\n r1, r2 = get_async(img_url, \"https://dog-api.kinduff.com/api/facts\")\n images = get_bassets(r1, num) if is_basset else r1.json().get('data')\n return {\n 'images': images,\n 'text': head(r2.json().get('facts'))\n }\n\n\ndef dog_url(num):\n return \"https://api.thedogapi.co.uk/v2/dog.php?limit=%s\" % num\n\n\ndef basset_url():\n return \"https://dog.ceo/api/breed/hound/basset/images\"\n\n\ndef get_bassets(r, num):\n all_urls = r.json().get('message', [])\n url = random.sample(all_urls, num)\n return list({'url': x} for x in url)\n\n\ndef get_async(*urls):\n session = sessions.FuturesSession()\n futures = map(session.get, urls)\n return list(x.result() for x in futures)\n","sub_path":"src/doggos.py","file_name":"doggos.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"358343830","text":"import os\nimport sys\nimport unittest\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\n\nfrom seriesbr.helpers.dates import parse_date # noqa: E402\n\n\nclass TestDates(unittest.TestCase):\n \"\"\"Test date parser function\"\"\"\n\n def test_date_with_month_and_year(self):\n test = parse_date(\"08-2018\", api=\"bcb\")\n expected = \"01/08/2018\"\n self.assertEqual(test, expected)\n\n def test_date_full(self):\n test = parse_date(\"01-12-2018\", api=\"bcb\")\n expected = \"01/12/2018\"\n self.assertEqual(test, expected)\n\n def test_date_with_year_only_as_start_date(self):\n test = parse_date(\"2018\", api=\"bcb\")\n expected = \"01/01/2018\"\n self.assertEqual(test, expected)\n\n def test_date_with_year_only_as_end_date(self):\n test = parse_date(\"2018\", api=\"bcb\", start=False)\n expected = \"31/12/2018\"\n self.assertEqual(test, expected)\n\n def test_date_abbreviated_month(self):\n test = parse_date(\"oct2018\", api=\"bcb\")\n expected = \"01/10/2018\"\n self.assertEqual(test, expected)\n\n def test_date_complete_month(self):\n test = parse_date(\"january2018\", api=\"bcb\")\n expected = \"01/01/2018\"\n self.assertEqual(test, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n# vi: nowrap\n","sub_path":"tests/test_dates.py","file_name":"test_dates.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"343849819","text":"#!/usr/bin/python\n\nimport sys\nimport re\n\n# get sam file and output file\nsam_file = sys.argv[1]\nfiltered_sam_file = sys.argv[2]\n\nwith open(sam_file, 'r') as f_in:\n with open(filtered_sam_file, 'w') as f_out:\n for line in f_in:\n if line[0] != '@':\n # get NM and MD info from sam file\n line_list = line.split('\\t')\n NM = int([x for x in line_list if x.startswith('NM')][0].split(':')[2])\n MD = [x for x in line_list if x.startswith('MD')][0].split(':')[2].rstrip()\n MD = re.split('\\d+',MD)[1:-1]\n # filter unconverted reads and only allow adneine and cytosine conversion but not other bases\n if len(re.findall('fwd',filtered_sam_file)) == 1:\n if NM >= 2 and ((MD.count('A') + MD.count('C'))/NM) >= 0.8:\n f_out.write(line)\n if len(re.findall('rev',filtered_sam_file)) == 1:\n if NM >= 2 and ((MD.count('T') + MD.count('G'))/NM) >= 0.8:\n f_out.write(line)\n else:\n f_out.write(line)","sub_path":"scripts/sam_tag_filtering.py","file_name":"sam_tag_filtering.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"446205430","text":"from flask import Flask, request, render_template, redirect, url_for, session, g, abort, flash, make_response, jsonify, Response\nfrom datetime import timedelta\nfrom models import db\nfrom common.utility import auth_login_required, hashpass, login_required\nfrom common.restful import Serialization\nfrom common.token_manage import Token_Manager\nfrom app import app\nfrom config import cross_origin\n\n\ntask = Serialization()\ntokenauth = Token_Manager()\n\n@app.route('/api/v1/menu',methods=['GET','POST'])\n@cross_origin()\n@auth_login_required\ndef menu():\n if request.method == 'POST':\n t = request.headers.get('Authorization')\n auth = tokenauth.verify_auth_token(t)\n data ={'username': auth['username'],'menu':[\n {'menu':'Dashboard','url':'index','ifsubmenu':'no','id':'index'},\n {'menu':'IDC','url':'idc','ifsubmenu':'no','id':'idc'},\n {'menu':'Asset',\n 'url':'',\n 'ifsubmenu':'yes',\n 'id':'asset',\n 'submenu':[\n {'submenu_name':'physical','submenu_url':'physic','id':'physic'},\n \t {'submenu_name':'vm','submenu_url':'asset','id':'vm'},\n {'submenu_name':'recycle','submenu_url':'recycle','id':'recycle'},\n \t]\n },\n {'menu':'application',\n 'url':'',\n 'ifsubmenu':'yes',\n 'id': 'appli',\n 'submenu':[\n {'submenu_name':'product','submenu_url':'product'},\n \t {'submenu_name':'appcation','submenu_url':'app'},\n \t]\n }\n ]}\n\n return task.json_message_200(data), 200\n","sub_path":"cmdb-backend/resources/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"329489689","text":"from handlers.RunlengthHandler import RunlengthHandler\nfrom discrete_weibull_distribution import *\nimport random\nimport math\nimport sys\n\n\ndef plot_distribution(axes, x, y, alpha=1):\n color = [0.1,0.4,1]\n\n axes.bar(x, y, color=color, alpha=alpha)\n\n\ndef main():\n runlength_path = \"/home/ryan/data/Nanopore/ecoli/runnie/out/rad2_pass_runnie_0.out\"\n\n handler = RunlengthHandler(runlength_path)\n\n reads = handler.iterate_file(sequence_cutoff=100)\n\n n_distributions = 0\n\n x = numpy.arange(0, 10)\n\n print(\"Binning distributions...\")\n distribution_bins = [list() for i in range(60)]\n\n for r,read in enumerate(reads):\n data = read.data\n read_id = read.id\n\n for i,item in enumerate(data):\n if item.shape < 1:\n print(\"WARNING: beta less than 1\", item.shape)\n\n y = evaluate_discrete_weibull(shape=item.shape, scale=item.scale, x=x)\n\n # Get analytical mode for the continuous weibull using parameters\n mode = calculate_mode(scale=item.scale, shape=item.shape)\n\n # Generate window of +1 -1 around analytical mode\n min_index = max(0, round(mode) - 1)\n max_index = min_index + 2\n\n # Find numerical mode within window\n mode_numerical = min_index + numpy.argmax(y[min_index:max_index])\n\n true_mode = numpy.argmax(y)\n\n if true_mode != mode_numerical:\n print(\"ERROR: you are bad at approximating modes: \", true_mode, mode_numerical)\n\n # print(mode_numerical)\n\n if mode_numerical < len(distribution_bins):\n distribution_bins[mode_numerical].append([item.scale, item.shape])\n n_distributions += 1\n\n # print(item.scale, item.shape)\n # print(sum)\n # print(mode)\n\n # axes = pyplot.axes()\n #\n # plot_distribution(axes, x[:60], y[:60])\n #\n # pyplot.show()\n # pyplot.close()\n\n # if i == 1000:\n # break\n\n n_rows = 8\n\n figure, axes = pyplot.subplots(nrows=n_rows)\n\n print(\"Plotting...\")\n\n sample_size = 1000\n\n for b,bin in enumerate(distribution_bins[:n_rows]):\n alpha = 1/(sample_size/10)\n\n bin_sample = list()\n\n if len(bin) > 0:\n print(b)\n n_items = min(sample_size, len(bin))\n\n while len(bin_sample) < n_items:\n bin_sample.append(random.choice(bin)[:n_rows+5])\n\n for scale, shape in bin_sample:\n y = evaluate_discrete_weibull(scale=scale, shape=shape, x=x[:n_rows+5])\n axes[b].plot(x[:n_rows+5], y, color=\"blue\", alpha=alpha, linewidth=0.8)\n\n y = evaluate_discrete_weibull(scale=scale*1.0675, shape=shape, x=x[:n_rows+5])\n axes[b].plot(x[:n_rows+5], y, color=\"orange\", alpha=alpha, linewidth=0.8)\n\n label = \"%d\" % (b+1)\n\n axes[b].set_ylabel(label)\n\n axes[n_rows-1].set_xlabel(\"Run length\")\n axes[0].set_title(\"Binned length distributions\")\n\n pyplot.show()\n pyplot.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"plot_runnie_output_rescaled.py","file_name":"plot_runnie_output_rescaled.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"322604571","text":"import pickle\nimport matplotlib.pyplot as plt\n\n(stars,times,xyzuvw,xyzuvw_cov)=pickle.load(open(\"traceback_save.pkl\"))\n\npl_stars = []\nfor i in range(len(stars)):\n X = xyzuvw[i,80,0]\n Y = xyzuvw[i,80,1]\n Z = xyzuvw[i,80,2]\n if (-1900-45):\n pl_stars.append(i)\n \n\nfor i in range(len(stars)):\n if i in pl_stars:\n colour = 'r'\n else:\n colour = 'b'\n plt.plot(xyzuvw[i,:2,0], xyzuvw[i,:2,1], colour)\n\nplt.scatter(xyzuvw[:,0,0], xyzuvw[:,0,1])\n\nplt.title(\"Initial positions and velocities of bright stars near Pleiades\")\nplt.xlabel(\"X [pc]\")\nplt.ylabel(\"Y [pc]\")\nplt.savefig(\"plots/pleiades_intial_XY.png\")\nplt.show()\n\nplt.clf()\n\n","sub_path":"playground/junkpile/plot_pl.py","file_name":"plot_pl.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"444788613","text":"from SuPyModes.Geometry import Geometry, Circle, Fused3\nfrom SuPyModes.Solver import SuPySolver\nfrom SuPyModes.sellmeier import Fused_silica\n\n\nClad = Fused3(Radius = 62.5, Fusion = 0.8, Index = Fused_silica(1.55))\n\n\nClad0 = Circle( Position=Clad.C[0], Radi = 12, Index = Fused_silica(1.55)+0.003 )\n\nClad1 = Circle( Position=Clad.C[1], Radi = 12, Index = Fused_silica(1.55)+0.003 )\n\nClad2 = Circle( Position=Clad.C[2], Radi = 10, Index = Fused_silica(1.55)+0.003 )\n\n\nCore0 = Circle( Position=Clad.C[0], Radi = 4.2, Index = Fused_silica(1.55)+0.005 )\n\nCore1 = Circle( Position=Clad.C[1], Radi = 4.2, Index = Fused_silica(1.55)+0.005 )\n\nCore2 = Circle( Position=Clad.C[2], Radi = 4.2, Index = Fused_silica(1.55)+0.005 )\n\nGeo = Geometry(Objects = [Clad, Clad0, Clad1, Clad2, Core0, Core1, Core2],\n Xbound = [-120, 120],\n Ybound = [-110, 130],\n Nx = 10,\n Ny = 10)\n\n#Geo.Plot()\n\nSol = SuPySolver(Coupler=Geo)\n\nSuperModes = Sol.GetModes(wavelength = 1.55,\n Nstep = 100,\n Nsol = 7,\n debug = False,\n ITRi = 1,\n ITRf = 0.05,\n tolerance = 1e-20,\n error = 3,\n Xsym = 0,\n Ysym = 0 )\n\nSuperModes.Plot(Input=['All'], nMax=3)\n\"\"\"\nSuperModes.Save(Directory = 'lol.pdf',\n Input = ['Index', 'Coupling', 'Adiabatic', 'Fields'],\n nMax = 4)\n\"\"\"\n","sub_path":"SuPyModes/perso/results/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"409879173","text":"import requests\nimport json\nfrom twilio.rest import TwilioRestClient\n\nimport secrets\n\n#Twilio API Credentials\nclient = TwilioRestClient(secrets.account_sid, secrets.auth_token)\n\n#Dark Sky API get request\nresponse = requests.get(secrets.ds_key)\n\ndata = response.json()\n\n# Write JSON to file\n#with open('json.txt', 'w') as outfile:\n# json.dump(data, outfile)\n\ndays = ['\\nMon: ', 'Tue: ', 'Wed: ', 'Thu: ', 'Fri: ', 'Sat: ', 'Sun: ']\ntextSMS = \"\"\n\nfor i in range(0,7):\n avgTemp = str(round((data[\"daily\"][\"data\"][i][\"temperatureMin\"] + data[\"daily\"][\"data\"][i][\"temperatureMax\"])/2))\n precipProbability = str(round((data[\"daily\"][\"data\"][i][\"precipProbability\"] * 100)))\n textSMS += days[i] + avgTemp + \"F \" + precipProbability + \"%\\n\"\n\n\nmessage = client.messages.create(to=secrets.target_number, from_=secrets.twilio_number,\n body=textSMS)\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"516709677","text":"people_0 = {\n 'first_name': 'jenia',\n 'last_name': 'kubik',\n 'age': '34',\n 'city': 'ramat gan',\n }\npeople_1 = {\n 'first_name': 'lena',\n 'last_name': 'braun',\n 'age': '38',\n 'city': 'odessa',\n }\npeople_2 = {\n 'first_name': 'irina',\n 'last_name': 'rosenberg',\n 'age': '30',\n 'city': 'tel aviv',\n }\npeoples = [people_0 ,people_1 ,people_2]\nfor people in peoples:\n print(people) \n'''\nprint(people_0['first_name'].title(),\n people_0['last_name'].title(),\n people_0['age'] , people_0['city'])\nprint('His name is ' + people_0['first_name'].title())\nprint('His last name is ' + people_0['last_name'].title())\nprint('He is ' + people_0['age'] + ' old' )\nprint('He was born in ' + people_0['city'].title()) \n'''","sub_path":"alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"263862430","text":"from coeff import coeff\r\nfrom mpmath import exp , mp , mpf ,sqrt\r\nmp.pretty = True\r\n\r\n\r\nfrom pylab import plot,show,title\r\nfrom numpy import linspace\r\n\r\n\r\nh = .1\r\ns = [mpf((f * h)**3) for f in range(1,50)]\r\n\r\n\r\n\r\n# first diff\r\nOrd = 1; acc = 1 ; \r\n##j = 19\r\nds = []\r\nn = len(s) - acc - Ord + 1\r\nfor j in range(n):\r\n ds += [sum(coeff[Ord].get(acc)[i] * s[i+j] for i in range(acc + Ord))/h**Ord]\r\n ds[-1] = round(ds[-1] , 2*acc)\r\n##for j in range(n, len(s)-Ord):\r\n## ds += [ds[-1]]\r\nif acc > 1:\r\n for j in range(n, len(s)-Ord):\r\n # ds += [ds[-1]]\r\n acc = acc-1\r\n ds += [sum(coeff[Ord].get(acc)[i] * s[i+j] for i in range(acc + Ord)) / h**Ord]\r\n ds[-1] = round(ds[-1] , 2*acc)\r\nfor j in range(len(s)-Ord,len(s)):\r\n ds += [ds[-1]]\r\n\r\n\r\n#mp.dps = 6\r\n\r\nprint ((s[0])**(1/3) , s[0] , ds[0])\r\n\r\n\r\nxpoints = []\r\nypoints = []\r\nypoints += ds\r\nfor x in range(1,len(s)+1):\r\n xpoints += [x*h]\r\n \r\nplot(xpoints, ypoints)\r\ntitle('forward diff ord {:} with accuracy {:}'.format(Ord,acc))\r\nshow()\r\n","sub_path":"dif-test.py","file_name":"dif-test.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"124554242","text":"#!/usr/bin/python\n#Tools Dibuat Oleh CRTF4bD\n########################\n # #RECODE MANDUL EA# #\n########################\n\nhek=\"\"\"\n1 • Satelit Telkomsel •\n2 • Satelit XL •\n3 • Satelit SmartFren •\"\"\"\ninf=\"\"\"Makasih cok udah pakai tools ini\nhttps://github.com/CRTF4bD\"\"\"\nbrpm=\"\"\"1 ~1 Meter~\n2 ~17 Meter~\n3 ~38 Meter~\"\"\"\n\nimport os,time\nos.system(\"clear\")\n\nnama = input('Masukan Nama Author = ')\nif(nama == \"CRTF4bD\"):\n\tos.system(\"clear\")\n\tprint(\"Terimakasih telah memakai tools saya\")\nelse:\n\tprint(\"Nama Author Salah!!, Baca di Readme.md\")\n\tos.sys.exit()\n\nbanner=\"\"\"\n +-+-+-+-+-+-+-+\n |C|R|T|F|4|b|D|\n +-+-+-+-+-+-+-+\n• https://github.com/CRTF4bD •\"\"\"\nabis=\"\"\"===============================\"\"\"\n\nred='\\33[31;1m'\nyellow='\\33[33;1m'\ngreen='\\33[0;32m'\nprint(red+banner)\nprint(green+abis)\nsatelit=\"1 • Hack Satelit •\"\ninfo=\"2 • Info Tentang Author •\"\n\ntime.sleep(0.5)\nprint(yellow+satelit)\ntime.sleep(0.5)\nprint(yellow+info)\ntime.sleep(0.5)\nprint(green+abis)\n\npilih = input('Pilih Yang Mana? ==> ')\nif(pilih == \"1\"):\n\tos.system(\"clear\")\n\ttime.sleep(0.5)\n\tprint(red+banner)\n\ttime.sleep(0.5)\n\tprint(green+abis)\n\tprint(yellow+hek)\nelif(pilih == \"2\"):\n\tos.system(\"clear\")\n\ttime.sleep(0.5)\n\tprint(red+banner)\n\ttime.sleep(0.5)\n\tprint(green+abis)\n\tprint(red+inf)\n\tos.sys.exit()\nelse:\n\tprint(\"Gak ada cok\")\n\tos.sys.exit()\n\nplh =input('Pilih yang mana? ==> ')\nif(plh == \"1\"):\n\tprint(\"Sedang Di Geser\")\n\ttime.sleep(3.7)\n\tprint(\"[+] DONE[+]\")\n\tos.sys.exit()\nelif(plh == \"2\"):\n\tprint(\"Sedang Di Geser\")\n\ttime.sleep(5)\n\tprint(\"[+] DONE[+]\")\n\tos.sys.exit()\nelif(plh == \"3\"):\n\tprint(\"Sedang Di Geser\")\n\ttime.sleep(6.3)\n\tprint(\"[+] DONE[+]\")\n\tos.sys.exit()\nelse:\n\tprint(\"Gak ada cok\")\n\tos.sys.exit()\n\t\n######################\n #. # Mandul Lu # #\n######################","sub_path":"mpshh.py","file_name":"mpshh.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"652250359","text":"import numpy as np \nimport geopy\nimport geopy.distance\nfrom obspy import read, Trace, Stream\n\ndef read_picks(pick_file_name):\n\n stations = np.array([])\n phases = np.array([])\n return_dict_array = np.array([])\n\n with open(pick_file_name, 'r') as pick_file:\n\n picks_data = pick_file.readlines()\n\n for line in picks_data[1:]:\n station_id = line.split()[4]\n station = station_id.split(\".\")[1]\n phase = line.split()[8]\n # print (station, phase)\n stations = np.append(stations, station)\n phases = np.append(phases, phase)\n \n stations = np.unique(stations)\n phases = np.unique(phases)\n\n for station in stations:\n\n phs = np.array([])\n pk_times = np.array([])\n\n for line in picks_data[1:]:\n st_id = line.split()[4]\n st = st_id.split(\".\")[1]\n \n if st == station:\n phase = line.split()[8]\n pick_time = line.split()[1]+\"T\"+line.split()[2]\n phs = np.append(phs, phase)\n pk_times = np.append(pk_times, pick_time)\n\n p_pick = \"\"\n s_pick = \"\"\n\n for (ph, time) in zip(phs, pk_times):\n if ph == \"P\":\n p_pick = time\n \n elif ph == \"S\":\n s_pick = time\n\n # print (p_pick, s_pick)\n\n\n pk_dict = {\n \"station\": station,\n \"p_pick_time\": p_pick,\n \"s_pick_time\": s_pick,\n }\n return_dict_array = np.append(return_dict_array, pk_dict)\n # print (return_dict_array)\n return return_dict_array\n\ndef calc_rms(arr):\n\n rms = 0\n\n for a in arr:\n\n rms += a**2\n\n rms = np.sqrt(rms/len(arr))\n return rms\n\n\ndef calc_polarity(arr):\n\n cum_displacement = 0\n for a in arr:\n cum_displacement += a\n\n if cum_displacement < 0:\n polarity = -1\n\n elif cum_displacement > 0:\n polarity = 1\n\n return polarity\n\ndef create_ts_tp_grid(distances, depths, vp, vs, ts_tp_time, t_err):\n\n grid = np.zeros((len(depths), len(distances)))\n arc_distances = np.array([])\n \n for de, depth in enumerate(depths):\n for di, dist in enumerate(distances):\n\n R = np.sqrt(dist**2 + depth**2)\n tp = R/vp\n ts = R/vs\n tsp = ts-tp\n grid[de, di] = tsp\n # print (\"dd\", tsp-ts_tp_time)\n if np.abs(tsp - ts_tp_time) < t_err:\n# print (np.abs(tsp - ts_tp_time), R)\n arc_distances = np.append(arc_distances, R)\n# print (arc_distances) \n arc_distance = np.median(arc_distances)\n\n return grid, arc_distance\n\ndef calc_hypo_lat_lon(station_lat, station_lon, radius, azimuth):\n\n # Define starting point.\n start = geopy.Point(station_lon, station_lat)\n\n # Define a general distance object, initialized with a distance of 1 km.\n d = geopy.distance.distance(kilometers = radius)\n\n # Use the `destination` method with a bearing of 0 degrees (which is north)\n # in order to go from point `start` 1 km to north.\n point = d.destination(point=start, bearing=np.deg2rad(180-azimuth))\n point = repr(tuple(point))\n string = \"\".join(point)\n lon, lat = float(string[1:-1].split(\",\")[0]), float(string[1:-1].split(\",\")[1])\n return lon, lat\n\n\nfrom geographiclib.constants import Constants\nfrom geographiclib.geodesic import Geodesic\n\ndef getEndpoint(lat1, lon1, d, bearing):\n geod = Geodesic(Constants.WGS84_a, Constants.WGS84_f)\n d = geod.Direct(lat1, lon1, bearing, d * 1000)\n\n # print(getEndpoint(28.455556, -80.527778, 317.662819, 130.224835))\n # print (d['lon2'], d['lat2'])\n return d['lon2'], d['lat2']\n\ndef calc_ps_ratio(tr_z, tr_h1, tr_h2, z_twindow, h_twindow, p_arrival, s_arrival):\n\n print (tr_z, tr_h1, tr_h2)\n z_window = tr_z.slice(starttime=p_arrival-z_twindow, endtime=p_arrival+z_twindow, nearest_sample=True)\n h1_window = tr_h1.slice(starttime=s_arrival, endtime=s_arrival+h_twindow, nearest_sample=True)\n h2_window = tr_h2.slice(starttime=s_arrival, endtime=s_arrival+h_twindow, nearest_sample=True)\n\n max_z = np.max(z_window.data)\n max_h1 = np.max(h1_window.data)\n max_h2 = np.max(h2_window.data)\n average_hmax = np.mean(np.array([max_h1, max_h2]))\n\n ps_ratio = max_z/average_hmax\n return ps_ratio\n\n","sub_path":"sshypo_utils.py","file_name":"sshypo_utils.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"587356904","text":"import json, sys\n\nPY3 = sys.version_info >= (3,)\nif PY3:\n import pickle\nelse:\n import cPickle as pickle\nimport numpy as np\nfrom .DataExchange2 import DXMessage\nfrom .Meta import MetaNode\nfrom .bulk_data_transport import encodeData\n\nclass JobDescription:\n\n def __init__(self, dataset_name, fraction, worker_text, user_params, \n frame_selector, worker_tags, use_data_cache, auth_token, username, identity, \n data_mod_url, data_mod_token, bulk_data):\n self.DatasetName = dataset_name\n self.Fraction = fraction\n assert not not worker_text, \"JobDescription: worker text can not be empty\"\n self.WorkerText = worker_text\n self.HDescriptors = {}\n self.UserParams = user_params\n self.BulkData = bulk_data or {}\n self.WorkerTags = worker_tags\n self.UseDataCache = use_data_cache\n self.FrameSelector = frame_selector # Meta expression or None\n self.AuthToken = auth_token\n self.Username = username\n self.Identity = identity\n self.DataModificationToken = data_mod_token\n self.DataModificationURL = data_mod_url\n \n def addHistograms(self, hdescriptors):\n self.HDescriptors = hdescriptors\n \n def toDXMsg(self):\n msg = DXMessage(\"job_request\", \n data_mod_token = self.DataModificationToken,\n data_mod_url = self.DataModificationURL,\n fraction=self.Fraction, \n dataset_name=self.DatasetName, \n format=\"pickle\", \n username=self.Username,\n use_data_cache = \"yes\" if self.UseDataCache else \"no\")\n encoded_params = encodeData(self.UserParams)\n encoded_bulk = encodeData(self.BulkData)\n #print \"JobDescription: pickled_params=\", len(pickled_params)\n msg.append(\n bulk_data = encoded_bulk,\n worker_text=self.WorkerText,\n worker_tags=pickle.dumps(self.WorkerTags),\n user_params=encoded_params,\n histograms=json.dumps(self.HDescriptors),\n identity=self.Identity,\n auth_token = self.AuthToken\n )\n if self.FrameSelector is not None:\n msg.append(frame_selector=json.dumps(self.FrameSelector.serialize())) \n return msg\n \n @staticmethod\n def fromDXMsg(msg):\n format = msg[\"format\"]\n assert format == \"pickle\", \"Unknown job description encoding format %s\" % (format,)\n dataset_name = msg[\"dataset_name\"]\n username = msg[\"username\"]\n fraction = msg[\"fraction\"]\n auth_token = msg.get(\"auth_token\")\n data_mod_token = msg.get(\"data_mod_token\")\n data_mod_url = msg.get(\"data_mod_url\")\n identity = msg.get(\"identity\")\n hdescriptors = json.loads(msg[\"histograms\"])\n user_params = msg[\"user_params\"] # do not unpickle, pass as is to the workers\n bulk_data = msg[\"bulk_data\"] # do not unpickle, pass as is to the workers\n worker_tags = pickle.loads(msg[\"worker_tags\"])\n worker_text = msg[\"worker_text\"]\n use_data_cache = msg.get(\"use_data_cache\", \"yes\") != \"no\"\n frame_selector = msg.get(\"frame_selector\")\n if frame_selector is not None:\n frame_selector = MetaNode.deserialize(json.loads(frame_selector))\n \n desc = JobDescription(dataset_name, fraction, worker_text, user_params, frame_selector, worker_tags, use_data_cache, \n auth_token, username, identity, data_mod_url, data_mod_token,\n bulk_data)\n desc.addHistograms(hdescriptors)\n return desc\n\n \n \n \n \n","sub_path":"striped/common/JobDescription.py","file_name":"JobDescription.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"185796811","text":"import cv2\nimport pyautogui\nimport numpy as np\nimport socket\nimport pickle\nimport base64\n\nHOST = '192.168.1.27' \nPORT = 9999 \n\n\nsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket.connect((HOST,PORT))\n\n\n\ndef getframeandsend():\n screen = pyautogui.screenshot()\n frame = np.array(screen)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame, (1024, 576), interpolation=cv2.INTER_AREA)\n return frame\n\nwhile True:\n \n frame = getframeandsend()\n istrue , tosend = cv2.imencode(\".jpg\",frame,[int(cv2.IMWRITE_JPEG_QUALITY), 90])\n data = pickle.dumps(tosend)\n tosend = base64.b64encode(data)\n size = len(data)\n socket.send(tosend)\n\n ","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"522854267","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport logging\nimport logging.handlers\nimport math\nimport os\nimport sys\nfrom abc import ABC, abstractmethod\n\nimport cv2\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn import utils\n\nfrom src import loading\nfrom src.loading import DataSet\n\nLOG_FILE_PATH = 'data/logs/runs.txt'\nFORMAT = '[%(asctime)s] %(levelname)s %(message)s'\nLOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')\n\n_SIGN_LABELS_CACHE = {}\n\n\ndef get_logger(source, level=LOG_LEVEL):\n formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n file_handler = logging.handlers.RotatingFileHandler(LOG_FILE_PATH, 'a', 10 * 1024 * 1024)\n file_handler.setFormatter(formatter)\n screen_handler = logging.StreamHandler(stream=sys.stdout)\n screen_handler.setFormatter(formatter)\n logger = logging.getLogger(source)\n logger.setLevel(level)\n logger.addHandler(file_handler)\n logger.addHandler(screen_handler)\n return logger\n\n\nclass ParameterizedProcessor(ABC):\n _logger = get_logger('Parameterized processor')\n\n def __init__(self, name, parameters=None):\n self._name = name\n self._parameters = parameters\n\n @property\n def name(self):\n return self._name\n\n @property\n def parameters(self):\n return self._parameters\n\n @abstractmethod\n def process(self, data_set):\n raise Exception('Unimplemented')\n\n @property\n def info(self):\n return {'name': self._name, 'parameters': self._parameters}\n\n\ndef get_sign_labels_map():\n global _SIGN_LABELS_CACHE\n if not _SIGN_LABELS_CACHE:\n _SIGN_LABELS_CACHE = loading.read_sign_names_csv()\n return _SIGN_LABELS_CACHE\n\n\ndef to_sign_label(code):\n return get_sign_labels_map().get(code)\n\n\ndef get_sign_labels_dataframe():\n as_list = list(get_sign_labels_map().items())\n df = pd.DataFrame.from_records(as_list)\n df.columns = ['code', 'label']\n return df\n\n\ndef group_labels_by_counts(data_set):\n y = pd.DataFrame(data_set.y)\n counts = pd.DataFrame(y[0].value_counts())\n counts.columns = ['counts']\n counts['code'] = counts.index.astype('int64')\n\n sign_labels = get_sign_labels_dataframe()\n return sign_labels.merge(counts, on='code')\n\n\ndef get_summary(data_sets):\n summary = {}\n all_classes = set()\n\n for data_set in data_sets:\n summary[data_set.name] = {\n 'number-of-examples': data_set.count,\n 'image-shape': data_set.X[0].shape,\n 'no-of-classes': len(set(data_set.y))\n }\n all_classes = all_classes.union(set(data_set.y))\n summary['total-no-of-classes'] = len(all_classes)\n return summary\n\n\ndef read_image_for_lenet(image_path):\n \"\"\"\n https://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html#imread\n Apparently\n - cv2.imread() => BGR\n - matplotlib.image.imread() => RGB\n\n :param image_path:\n :return:\n \"\"\"\n img = cv2.imread(image_path)\n rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return cv2.resize(rgb, (32, 32), interpolation=cv2.INTER_CUBIC)\n\n\ndef plot_and_save(images, labels, filepath, n_cols=3):\n n_rows = int(math.ceil(len(images) / float(n_cols)))\n fig, axs = plt.subplots(n_rows, n_cols, figsize=(20, 20))\n fig.subplots_adjust(hspace=.2, wspace=.01)\n axs = axs.ravel()\n for i in range(n_rows * n_cols):\n axs[i].axis('off')\n if i < len(images):\n c_map = 'gray' if images[i].ndim == 2 else None\n axs[i].imshow(images[i], cmap=c_map)\n axs[i].set_title(labels[i])\n\n plt.savefig(filepath)\n\n\ndef shuffle(data_set):\n x, y = utils.shuffle(data_set.X, data_set.y)\n return DataSet(data_set.name, x, y, data_set.count)\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"639966381","text":"from django.contrib import messages\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import Group, User\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.shortcuts import render, redirect\nfrom zeep import Client\n\nfrom accounts.models import Forgot\nfrom sbs.Forms.PreRegidtrationForm import PreRegistrationForm\nfrom sbs.models import SportsClub, SportClubUser, Communication, Person\nfrom sbs.models.CategoryItem import CategoryItem\nfrom sbs.models.Coach import Coach\nfrom sbs.models.Level import Level\nfrom sbs.models.PreRegistration import PreRegistration\nfrom sbs.models.ReferenceCoach import ReferenceCoach\nfrom sbs.models.ReferenceReferee import ReferenceReferee\nfrom sbs.services import general_methods\nfrom sbs.models.EnumFields import EnumFields\n\n\ndef update_preRegistration(request, pk):\n perm = general_methods.control_access(request)\n\n if not perm:\n logout(request)\n return redirect('accounts:login')\n\n veri=PreRegistration.objects.get(pk=pk)\n\n try:\n if CategoryItem.objects.get(name=veri.kademe_definition):\n kategori = CategoryItem.objects.get(name=veri.kademe_definition)\n form = PreRegistrationForm(request.POST or None, request.FILES or None, instance=veri,\n initial={'kademe_definition': kategori.name})\n else:\n form = PreRegistrationForm(request.POST or None, request.FILES or None, instance=veri)\n except:\n form = PreRegistrationForm(request.POST or None, request.FILES or None, instance=veri)\n if request.method == 'POST':\n mail = request.POST.get('email')\n if mail != veri.email:\n if User.objects.filter(email=mail) or ReferenceCoach.objects.exclude(status=ReferenceCoach.DENIED).filter(\n email=mail) or ReferenceReferee.objects.exclude(status=ReferenceReferee.DENIED).filter(\n email=mail) or PreRegistration.objects.exclude(status=PreRegistration.DENIED).filter(\n email=mail):\n messages.warning(request, 'Mail adresi başka bir kullanici tarafından kullanilmaktadir.')\n return render(request, 'kulup/kulup-basvuru-duzenle.html',\n {'preRegistrationform': form, })\n\n tc = request.POST.get('tc')\n if tc != veri.tc:\n\n if Person.objects.filter(tc=tc) or ReferenceCoach.objects.exclude(status=ReferenceCoach.DENIED).filter(\n tc=tc) or ReferenceReferee.objects.exclude(status=ReferenceReferee.DENIED).filter(\n tc=tc) or PreRegistration.objects.exclude(status=PreRegistration.DENIED).filter(tc=tc):\n messages.warning(request, 'Tc kimlik numarasi sistemde kayıtlıdır. ')\n return render(request, 'kulup/kulup-basvuru-duzenle.html',\n {'preRegistrationform': form, })\n\n name = request.POST.get('first_name')\n surname = request.POST.get('last_name')\n year = request.POST.get('birthDate')\n year = year.split('/')\n\n client = Client('https://tckimlik.nvi.gov.tr/Service/KPSPublic.asmx?WSDL')\n\n if not (client.service.TCKimlikNoDogrula(tc, name, surname, year[2])):\n messages.warning(request, 'Tc kimlik numarasi ile isim,soyisim,dogum yılı bilgileri uyuşmamaktadır. ')\n return render(request, 'kulup/kulup-basvuru-duzenle.html',\n {'preRegistrationform': form, })\n form = PreRegistrationForm(request.POST, request.FILES or None, instance=veri)\n\n if form.is_valid():\n form.save()\n print(request.POST.get('kademe_definition'))\n\n messages.success(request,'Basarili bir şekilde kaydedildi ')\n return redirect('sbs:basvuru-listesi')\n else:\n messages.warning(request,'Alanlari kontrol ediniz')\n return render(request, 'kulup/kulup-basvuru-duzenle.html',\n {'preRegistrationform': form,})\n\n\n@login_required\ndef rejected_preRegistration(request,pk):\n perm = general_methods.control_access(request)\n if not perm:\n logout(request)\n return redirect('accounts:login')\n messages.success(request, 'Klup basvurusu reddedildi ')\n veri=PreRegistration.objects.get(pk=pk)\n veri.status=PreRegistration.DENIED\n veri.save()\n prepegidtration=PreRegistration.objects.all()\n log = str(veri.name) + \" Klup basvurusu reddedildi\"\n log = general_methods.logwrite(request, request.user, log)\n return render(request, 'kulup/kulupBasvuru.html',\n {'prepegidtration': prepegidtration })\n\n@login_required\ndef approve_preRegistration(request,pk):\n perm = general_methods.control_access(request)\n if not perm:\n logout(request)\n return redirect('accounts:login')\n basvuru=PreRegistration.objects.get(pk=pk)\n if basvuru.status!=PreRegistration.APPROVED:\n mail = basvuru.email\n if not (User.objects.filter(email=mail) or ReferenceCoach.objects.exclude(status=ReferenceCoach.DENIED).filter(\n email=mail) or ReferenceReferee.objects.exclude(status=ReferenceReferee.DENIED).filter(email=mail)):\n\n user = User()\n user.username = basvuru.email\n user.first_name = basvuru.first_name\n user.last_name = basvuru.last_name\n user.email = basvuru.email\n user.is_active = True\n user.is_staff = basvuru.is_staff\n group = Group.objects.get(name='KulupUye')\n password = User.objects.make_random_password()\n user.set_password(password)\n user.save()\n user.groups.add(group)\n user.save()\n\n # person kaydet\n person = Person()\n person.tc = basvuru.tc\n person.birthplace = basvuru.birthplace\n person.motherName = basvuru.motherName\n person.fatherName = basvuru.fatherName\n person.profileImage = basvuru.profileImage\n person.birthDate = basvuru.birthDate\n person.bloodType = basvuru.bloodType\n if basvuru.gender == 'Erkek':\n person.gender = Person.MALE\n else:\n person.gender = Person.FEMALE\n person.save()\n\n # Communication kaydet\n com = Communication()\n com.postalCode = basvuru.postalCode\n com.phoneNumber = basvuru.phoneNumber\n com.phoneNumber2 = basvuru.phoneNumber2\n com.address = basvuru.address\n com.city = basvuru.city\n com.country = basvuru.country\n com.save()\n\n Sportclup = SportClubUser()\n Sportclup.user = user\n Sportclup.person = person\n Sportclup.communication = com\n Sportclup.role = basvuru.role\n Sportclup.save()\n\n comclup = Communication()\n comclup.postalCode = basvuru.clubpostalCode\n comclup.phoneNumber = basvuru.clubphoneNumber\n comclup.phoneNumber2 = basvuru.clubphoneNumber2\n comclup.address = basvuru.clubaddress\n comclup.city = basvuru.clubcity\n comclup.country = basvuru.clubcountry\n comclup.save()\n\n # SportClup\n clup = SportsClub()\n clup.name = basvuru.name\n clup.shortName = basvuru.shortName\n clup.foundingDate = basvuru.foundingDate\n clup.clubMail = basvuru.clubMail\n clup.logo = basvuru.logo\n clup.isFormal = basvuru.isFormal\n clup.petition = basvuru.petition\n clup.communication = comclup\n clup.save()\n clup.clubUser.add(Sportclup)\n clup.save()\n # burada kadik\n if basvuru.isCoach:\n\n coach = Coach()\n coach.user = user\n coach.person = person\n coach.communication = com\n coach.iban = basvuru.iban\n coach.save()\n group = Group.objects.get(name='Antrenor')\n user.groups.add(group)\n user.save()\n grade = Level(\n startDate=basvuru.kademe_startDate,\n dekont=basvuru.kademe_belge,\n branch=EnumFields.HALTER.value)\n try:\n grade.definition = CategoryItem.objects.get(name=basvuru.kademe_definition)\n except:\n grade.definition = CategoryItem.objects.get(name='1.Kademe')\n\n grade.levelType = EnumFields.LEVELTYPE.GRADE\n grade.status = Level.APPROVED\n grade.isActive = True\n grade.save()\n coach.grades.add(grade)\n coach.save()\n\n clup.coachs.add(coach)\n clup.save()\n\n basvuru.status = PreRegistration.APPROVED\n basvuru.save()\n\n fdk = Forgot(user=user, status=False)\n fdk.save()\n\n html_content = ''\n subject, from_email, to = 'Bilgi Sistemi Kullanıcı Bilgileri', 'no-reply@halter.gov.tr', user.email\n html_content = '

TÜRKİYE HALTER FEDERASYONU BİLGİ SİSTEMİ

'\n html_content = html_content + '

Kullanıcı Adınız :' + str(fdk.user.username) + '

'\n html_content = html_content + '

Site adresi: https://sbs.halter.gov.tr:9443/sbs/profil-guncelle/?query=' + str(fdk.uuid) + '

'\n msg = EmailMultiAlternatives(subject, '', from_email, [to])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n messages.success(request, 'Başari ile kaydedildi')\n\n log = str(clup) + \" Klup basvurusu onaylandi\"\n log = general_methods.logwrite(request, request.user, log)\n\n try:\n # user kaydet\n print()\n except:\n messages.warning(request, 'Lütfen sistem yöneticisi ile görüşünüz ')\n log = str(basvuru.name) + \" Klup basvurusu hata oldu\"\n log = general_methods.logwrite(request, request.user, log)\n\n else:\n messages.warning(request, 'Mail adresi sistem de kayıtlıdır.')\n else:\n messages.warning(request,'Bu basvuru sisteme kaydedilmistir.')\n\n prepegidtration=PreRegistration.objects.all()\n return render(request, 'kulup/kulupBasvuru.html',\n {'prepegidtration': prepegidtration })\n\n\n\n\n@login_required\ndef return_preRegistration(request):\n perm = general_methods.control_access(request)\n\n\n if not perm:\n logout(request)\n return redirect('accounts:login')\n\n prepegidtration = PreRegistration.objects.all().order_by('-creationDate')\n return render(request, 'kulup/kulupBasvuru.html',\n {'prepegidtration': prepegidtration })\n\n","sub_path":"sbs/Views/PreRegistration.py","file_name":"PreRegistration.py","file_ext":"py","file_size_in_byte":11096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"408574239","text":"import json\r\nimport requests\r\n\r\njsonStr = ''\r\nwith open('dcard.json', 'r', encoding='utf-8') as f:\r\n jsonStr = f.read()\r\n\r\njsonData = json.loads(jsonStr)\r\n\r\n# for i in jsonData:\r\n# print(i)\r\n\r\nres = requests.get('https://www.dcard.tw/service/api/v2/posts?popular=true&limit=30&before=235984417')\r\nprint(res.text)","sub_path":"dcard_test1.py","file_name":"dcard_test1.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"616056520","text":"import datetime\n\nfrom decouple import config\n\nfrom sitef.resources import handler_request\n\nMERCHANT_ID = config('MERCHANT_ID')\nMERCHANT_KEY = config('MERCHANT_KEY', None)\n\nAUTH_TEST = handler_request.authentication_key(MERCHANT_ID, MERCHANT_KEY)\n\n\ndef next_charge():\n date = datetime.date.today()\n day = 5\n month = (date.month + 1) % 12\n month = month if 1 <= month <= 12 else 1\n year = int(date.year + (month + 1) / 12)\n return datetime.date(year, month, day)\n","sub_path":"tests/resources/sitef_test.py","file_name":"sitef_test.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"414487307","text":"# -*- coding: utf-8 -*-\nfrom chatterbot import ChatBot\n\n# Create a new chat bot named Charlie\n\nclass Meseek(ChatBot):\n DIALOG = [\n \"Salut\",\n \"Salut mec !\",\n \"Ca va mec\",\n \"OKLM\"\n ]\n\n\n def __init__(self, userId):\n super().__init__(userId, trainer='chatterbot.trainers.ListTrainer')\n super().train(self.DIALOG)\n\n","sub_path":"meseek/chat/f_chatterbot/chatterbot.py","file_name":"chatterbot.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"258207493","text":"import json\n\nfrom faros.client import FarosClient\nfrom urllib.parse import unquote\n\n\ndef full_star_doc(doc):\n statements = doc[\"Statement\"]\n\n statement_list = []\n if isinstance(statements, dict):\n statement_list = [statements]\n elif isinstance(statements, list):\n statement_list = statements\n else:\n return False\n\n for statement in statement_list:\n if statement[\"Effect\"] == \"Deny\":\n continue\n\n if \"Action\" not in statement:\n continue\n\n if isinstance(statement[\"Action\"], list):\n for action in statement[\"Action\"]:\n if action == \"*\":\n return True\n else:\n if statement[\"Action\"] == \"*\":\n return True\n\n return False\n\n\ndef full_star_policy(policy_list):\n for policy in policy_list:\n doc = policy[\"policyDocument\"]\n decoded_doc = json.loads(unquote(doc))\n if full_star_doc(decoded_doc):\n return True\n\n return False\n\n\ndef lambda_handler(event, context):\n client = FarosClient.from_event(event)\n\n query = \"\"\"{\n aws {\n iam {\n groupDetail {\n data {\n farosAccountId\n farosRegionId\n groupName\n groupId\n groupPolicyList {\n policyDocument\n policyName\n }\n }\n }\n }\n }\n }\"\"\"\n\n response = client.graphql_execute(query)\n groups = response[\"aws\"][\"iam\"][\"groupDetail\"][\"data\"]\n return [g for g in groups if full_star_policy(g[\"groupPolicyList\"])]\n","sub_path":"apps/iam-groups-with-all-action-policy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"385670774","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 8 16:46:31 2021\n\n@author: ndthang\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\nimport time\nimport random\nfrom model import DVFSModel\nfrom datagenerator import HPC_DVFS, labels,labelsZ, make_weights_for_balanced_classes\nfrom sklearn.preprocessing import StandardScaler\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import CosineAnnealingLR \nfrom warmup_scheduler import GradualWarmupScheduler\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport util\nfrom datetime import datetime\nimport json\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\")\n\n# hyperparmeter\nkfold = 0\nnum_fold = 5\nseed = 42\nwarmup_epo = 5\nbatch_size = 100\nnum_workers = 4\ndevice = torch.device('cuda')\nmodel_dir = 'logs14/'\n\ndef seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True # for faster training, but not deterministic\n \nseed_everything(seed)\n\n\n#load dataset for training\ndf = pd.read_csv('../../data4train/test.csv', na_filter= False, index_col=0)\n\n\nfrom pickle import load, dump\n#Load standarzation data training\nsc_train = load(open(f'{model_dir}/0_scaler.pkl', 'rb'))\nfeature_list = load(open(f'{model_dir}/0_feature_list.pkl', 'rb'))\ntest_df = df\n\ntest_loader_ = HPC_DVFS(df=test_df,mode='valid',feature_list = feature_list,sc=sc_train)\n\ntest_loader = torch.utils.data.DataLoader(test_loader_,batch_size=batch_size, num_workers=num_workers, pin_memory=True)\n\nmodels = []\nfor kfold in range(num_fold):\n model = DVFSModel(n_cont=len(feature_list), out_sz=len(labels),out_szz=len(labelsZ), szs=[1024,512,256, 128, 64], drops=[0.001,0.01,0.05, 0.1,0.2])\n model = model.to(device)\n model.load_state_dict(torch.load(f'{model_dir}_fold{kfold}_best_accuracy.pth',map_location='cuda:0'))\n model.eval()\n models.append(model)\n\nbar = tqdm(test_loader)\nPROB = []\nTARGETS_target = []\nTARGETS_targetZ = []\nTARGETS_target_id = []\nTARGETS_targetZ_id = []\nlosses = []\nPREDS_target = []\nPREDS_targetZ = []\nPREDS_target_id = []\nPREDS_targetZ_id = []\n\nwith torch.no_grad():\n for batch_idx, (inputarr, targets) in enumerate(bar):\n inputarr, target, targetZ = inputarr.to(device), targets['target'].to(device),targets['targetZ'].to(device)\n \n logits = []\n for i in range(num_fold):\n logit = models[i](inputarr)\n logits.append(logit)\n f_target = (logits[0][0]+logits[1][0]+logits[2][0]+logits[3][0]+logits[4][0])/num_fold\n PREDS_target += [f_target]\n PREDS_target_id += [torch.argmax(f_target,dim = 1)]\n \n TARGETS_target += [target.detach().cpu()]\n TARGETS_target_id += [torch.argmax(target,dim = 1).detach().cpu()]\n f_targetZ = (logits[0][1]+logits[1][1]+logits[2][1]+logits[3][1]+logits[4][1])/num_fold\n PREDS_targetZ += [f_targetZ]\n PREDS_targetZ_id += [torch.argmax(f_targetZ,dim = 1)]\n TARGETS_targetZ += [targetZ.detach().cpu()]\n TARGETS_targetZ_id += [torch.argmax(targetZ,dim = 1).detach().cpu()]\n \nPREDS_target = torch.cat(PREDS_target).cpu().numpy()\nPREDS_target_id = torch.cat(PREDS_target_id).cpu().numpy()\nTARGETS_target = torch.cat(TARGETS_target).cpu().numpy()\nTARGETS_target_id = torch.cat(TARGETS_target_id).cpu().numpy()\n\nPREDS_targetZ = torch.cat(PREDS_targetZ).cpu().numpy()\nTARGETS_targetZ = torch.cat(TARGETS_targetZ).cpu().numpy()\nPREDS_targetZ_id = torch.cat(PREDS_targetZ_id).cpu().numpy()\nTARGETS_targetZ_id = torch.cat(TARGETS_targetZ_id).cpu().numpy()\n\nroc_auc_target,roc_roc_dt = util.macro_multilabel_auc(TARGETS_target, PREDS_target, labels=labels)\nF1_target = util.F1_score_mul(TARGETS_target_id, PREDS_target_id)\naccuracy_target = util.accuracy_score_mul(TARGETS_target_id, PREDS_target_id)\n\nroc_auc_targetZ,roc_roc_dtZ = util.macro_multilabel_auc(TARGETS_targetZ, PREDS_targetZ, labels=labels)\nF1_targetZ = util.F1_score_mul(TARGETS_targetZ_id, PREDS_targetZ_id)\naccuracy_targetZ = util.accuracy_score_mul(TARGETS_targetZ_id, PREDS_targetZ_id)\n\nloss_valid = np.mean(losses)\n#return loss_valid, roc_auc_target, roc_auc_targetZ,F1_target, F1_targetZ, {'target':roc_roc_dt,'targetZ':roc_roc_dtZ}, accuracy_target,accuracy_targetZ\n\nfrom sklearn.metrics import accuracy_score, mean_squared_error, classification_report, f1_score\nfrom sklearn.metrics import roc_curve, auc, confusion_matrix\nimport seaborn as sns\ndef draw_cfm(y_test, preds):\n print(classification_report(y_test, preds))\n cfm = confusion_matrix(y_test, preds, labels = range(0,13))\n cm = cfm\n cfm = cfm.astype('float') / cfm.sum(axis=1)[:, np.newaxis]\n tmplabel = [i//100000 for i in labels]\n annot = np.empty_like(cfm).astype(str)\n nrows, ncols = cfm.shape\n for i in range(nrows):\n for j in range(ncols):\n c = cfm[i, j]*100\n if c == 0:\n annot[i, j] = ''\n else:\n annot[i, j] = '%.1f%%\\n%d' % (c,cm[i, j])\n plt.figure(figsize=(12,10))\n ax = sns.heatmap(cfm, annot=annot, fmt='',cmap=\"YlGnBu\")\n ax.set_xticklabels(tmplabel)\n ax.set_yticklabels(tmplabel)\n plt.xlabel('Predicted')\n plt.ylabel('True')\n plt.show() \n\nroc_auc = (roc_auc_target+roc_auc_targetZ)/2\nF1_total = (F1_targetZ + F1_target)/2\naccuracy_total = (accuracy_target + accuracy_targetZ)/2\ncontent = time.ctime() + ' ' + f'Fold {kfold}, \\\n loss_valid: {loss_valid:.5f}, roc_auc_target: {roc_auc_target:.6f}, roc_auc_targetZ: {roc_auc_targetZ:.6f}, total_roc_auc: {roc_auc:.6f},\\\n F1_target: {F1_target:.6f},F1_targetZ: {F1_targetZ:.6f},accuracy_target: {accuracy_target:.6f}, accuracy_targetZ: {accuracy_targetZ:.6f} .'\nprint(content)\ndraw_cfm(TARGETS_target_id, PREDS_target_id)\ndraw_cfm(TARGETS_targetZ_id, PREDS_targetZ_id)\nprint('mean_squared_error:',mean_squared_error(TARGETS_target_id, PREDS_target_id))\n","sub_path":"src/Modeling and evaluation/NN-multi-targets/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"382888709","text":"# 给定一幅由N × N矩阵表示的图像,其中每个像素的大小为4字节,编写一种方法,将图像旋转90度。\r\n\r\n# 不占用额外内存空间能否做到?\r\n\r\n#\r\n\r\n# 示例 1:\r\n\r\n# 给定 matrix =\r\n# [\r\n# [1,2,3],\r\n# [4,5,6],\r\n# [7,8,9]\r\n# ],\r\n\r\n# 原地旋转输入矩阵,使其变为:\r\n# [\r\n# [7,4,1],\r\n# [8,5,2],\r\n# [9,6,3]\r\n# ]\r\n# 示例 2:\r\n\r\n# 给定 matrix =\r\n# [\r\n# [ 5, 1, 9,11],\r\n# [ 2, 4, 8,10],\r\n# [13, 3, 6, 7],\r\n# [15,14,12,16]\r\n# ],\r\n\r\n# 原地旋转输入矩阵,使其变为:\r\n# [\r\n# [15,13, 2, 5],\r\n# [14, 3, 4, 1],\r\n# [12, 6, 8, 9],\r\n# [16, 7,10,11]\r\n# ]\r\n\r\n# 来源:力扣(LeetCode)\r\n# 链接:https://leetcode-cn.com/problems/rotate-matrix-lcci\r\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\r\n\r\nclass Solution:\r\n def rotate(self, matrix: List[List[int]]) -> None:\r\n \"\"\"\r\n Do not return anything, modify matrix in-place instead.\r\n \"\"\"\r\n # 只需要旋转([0,n-1], [1,n-2], [2, n-3]...)即可\r\n # 注意每一行的起始列应该是和该行的值一样\r\n # 画图\r\n # 注意r和c的边界\r\n n = len(matrix)\r\n for r in range(n // 2):\r\n for c in range(r, n - r - 1):\r\n s = matrix[r][c]\r\n matrix[r][c] = matrix[n - c - 1][r]\r\n matrix[n - c - 1][r] = matrix[n - r - 1][n - c - 1]\r\n matrix[n - r - 1][n - c - 1] = matrix[c][n - r - 1]\r\n matrix[c][n - r - 1] = s\r\n","sub_path":"Medium/面试题 01.07. 旋转矩阵.py","file_name":"面试题 01.07. 旋转矩阵.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"138258365","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\n\nfrom migen import *\n\nfrom litex.boards.targets import versa_ecp5\n\nfrom litex.soc.interconnect import wishbone\nfrom litex.soc.integration.soc_core import mem_decoder\nfrom litex.soc.integration.builder import Builder\n\n# LinuxSoC -----------------------------------------------------------------------------------------\n\nclass LinuxSoC(versa_ecp5.EthernetSoC):\n csr_map = {\n \"ddrphy\": 16,\n \"cpu\": 17,\n \"ethphy\": 18,\n \"ethmac\": 19\n }\n csr_map.update(versa_ecp5.EthernetSoC.csr_map)\n\n versa_ecp5.EthernetSoC.mem_map = {\n \"rom\": 0x00000000,\n \"sram\": 0x10000000,\n \"emulator_ram\": 0x20000000,\n \"ethmac\": 0x30000000,\n \"spiflash\": 0x50000000,\n \"main_ram\": 0xc0000000,\n \"csr\": 0xf0000000,\n }\n\n def __init__(self, toolchain=\"trellis\", local_ip=\"192.168.1.50\", remote_ip=\"192.168.1.100\"):\n versa_ecp5.EthernetSoC.__init__(self, cpu_type=\"vexriscv\", cpu_variant=\"linux\", toolchain=toolchain)\n self.cpu.use_external_variant(\"VexRiscv.v\")\n self.add_constant(\"NETBOOT_LINUX_VEXRISCV\", None)\n\n # machine mode emulator ram\n self.submodules.emulator_ram = wishbone.SRAM(0x4000)\n self.register_mem(\"emulator_ram\", self.mem_map[\"emulator_ram\"], self.emulator_ram.bus, 0x4000)\n\n local_ip = local_ip.split(\".\")\n remote_ip = remote_ip.split(\".\")\n\n self.add_constant(\"LOCALIP1\", int(local_ip[0]))\n self.add_constant(\"LOCALIP2\", int(local_ip[1]))\n self.add_constant(\"LOCALIP3\", int(local_ip[2]))\n self.add_constant(\"LOCALIP4\", int(local_ip[3]))\n\n self.add_constant(\"REMOTEIP1\", int(remote_ip[0]))\n self.add_constant(\"REMOTEIP2\", int(remote_ip[1]))\n self.add_constant(\"REMOTEIP3\", int(remote_ip[2]))\n self.add_constant(\"REMOTEIP4\", int(remote_ip[3]))\n\n\n# Build / Load -------------------------------------------------------------------------------------\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Linux on LiteX-VexRiscv\")\n parser.add_argument(\"--build\", action=\"store_true\", help=\"build bitstream\")\n parser.add_argument(\"--load\", action=\"store_true\", help=\"load bitstream (SRAM)\")\n parser.add_argument(\"--diamond\", action=\"store_true\", help=\"use Diamond instead of Trellis\")\n parser.add_argument(\"--local-ip\", default=\"192.168.1.50\", help=\"local IP address\")\n parser.add_argument(\"--remote-ip\", default=\"192.168.1.100\", help=\"remote IP address of TFTP server\")\n\n args = parser.parse_args()\n\n if args.diamond:\n toolchain_path = \"/usr/local/diamond/3.10_x64/bin/lin64\"\n else:\n toolchain_path = \"/usr/share/trellis\"\n\n if args.build:\n soc = LinuxSoC(toolchain=\"diamond\" if args.diamond else \"trellis\", local_ip=args.local_ip, remote_ip=args.remote_ip)\n builder = Builder(soc, output_dir=\"build_versa5g\")\n builder.build(toolchain_path=toolchain_path)\n if args.diamond:\n os.system(\"python3 prog/bit_to_svf.py build_versa5g/gateware/top.bit build_versa5g/gateware/top.svf\")\n\n if args.load:\n os.system(\"openocd -f prog/ecp5-versa5g.cfg -c \\\"transport select jtag; init; svf build_versa5g/gateware/top.svf; exit\\\"\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"versa_ecp5.py","file_name":"versa_ecp5.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"573000321","text":"import csv\nfrom collections import OrderedDict\nfrom utils import CommentedFile\n\n\ndef levenshtein(a, b):\n \"\"\"\n Calculates the Levenshtein distance between a and b.\n http://stackoverflow.com/questions/11563615/matching-incorrectly-spelt-words-with-correct-ones-in-python\n\n This is a straightforward implementation of a well-known algorithm, and thus\n probably shouldn't be covered by copyright to begin with. But in case it is,\n the author (Magnus Lie Hetland) has, to the extent possible under law,\n dedicated all copyright and related and neighboring rights to this software\n to the public domain worldwide, by distributing it under the CC0 license,\n version 1.0. This software is distributed without any warranty. For more\n information, see \n \"\"\"\n n, m = len(a), len(b)\n if n > m:\n # Make sure n <= m, to use O(min(n,m)) space\n a, b = b, a\n n, m = m, n\n\n current = range(n + 1)\n for i in range(1, m + 1):\n previous, current = current, [i] + [0] * n\n for j in range(1, n + 1):\n add, delete = previous[j] + 1, current[j - 1] + 1\n change = previous[j - 1]\n if a[j - 1] != b[i - 1]:\n change = change + 1\n current[j] = min(add, delete, change)\n\n return current[n]\n\n\nclass FreeStyle(object):\n\n def __init__(self, filter_dict={}):\n\n self.filter_dict = {}\n for k, v in filter_dict.iteritems():\n self.filter_dict[k.upper()] = v\n\n def match(self, word, max_cost=4):\n x = word.upper()\n matches = []\n for k, v in self.filter_dict.iteritems():\n cost = levenshtein(x, k)\n if cost <= max_cost:\n matches.append((cost, v))\n if matches:\n return min(matches, key=lambda t: t[0])[1]\n return None\n\n\nclass CsvFreeStyle(FreeStyle):\n\n def __init__(self, csv_file):\n super(CsvFreeStyle, self).__init__(\n filter_dict=self.read_csv(csv_file)\n )\n\n def read_csv(self, csv_file):\n \"\"\"\n Read CSV File\n The first row must be title columns\n \"\"\"\n reader = csv.DictReader(CommentedFile(open(csv_file, \"rb\")))\n title = reader.fieldnames\n m = OrderedDict()\n for row in reader:\n k = row[title[0]].strip()\n v = row[title[1]].strip()\n m[k] = v\n return m\n","sub_path":"SC/pyfsmsync/pyfsmsync/levenshtein.py","file_name":"levenshtein.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"223794337","text":"# 创建一个TCP的服务端\nimport socket\n\n# 1、创建一个socket:用作服务端\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# 2、绑定一个IP及端口号\n# 数据格式:需要接收一个元组类型的数据,第一个参数为IP地址,第二个参数为端口号\nserver.bind(('10.36.133.41', 19999))\n# 3、监听\n# 传入的值指定在拒绝连接之前,操作系统可以链接的最大链接量。该值至少为1,大\n# 部分的程序设置为5就可以了。\nserver.listen(5)\n\nprint('服务器启动成功。。。。。。')\n\n# 4、等待客户端的链接,会阻塞程序运行\n# 如果客户端可以链接成功,会返回socket address\nclientSocket, clientAddress = server.accept()\n# print(str(clientSocket))\n# print(clientAddress)\n\nwhile True:\n # 5、接收客户端数据\n data = clientSocket.recv(1024)\n print('客户端说:',data.decode('utf-8'))\n # 6、发送给客户端的数据\n sendData = input('请输入传给客户端的数据:')\n clientSocket.send(sendData.encode('utf-8'))\n","sub_path":"python/1-TCP-UDP/2-socket服务端.py","file_name":"2-socket服务端.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"402041010","text":"from flask import Flask , render_template , request , redirect\nimport base64,math\nimport redis\nimport string\nimport urlparse\nimport werkzeug.exceptions\n\napp=Flask(__name__)\nredis=redis.Redis()\n#r = redis.StrictRedis(host='localhost', port=6379, db=0)\n\ndef base62con(num):\n \n '''Using Base62 enconding as it gives 3.5 trillion combinations'''\n \n base = string.digits + string.lowercase + string.uppercase\n hashed_string = ''\n while num > 0:\n hashed_string = base[num % 62] + hashed_string\n num = num/62\n return hashed_string\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n \n@app.route('/shortified', methods=['POST'])\ndef return_shortened():\n url_to_parse = request.form['input-url']\n parts = urlparse.urlparse(url_to_parse)\n if not parts.scheme in ('http', 'https'):\n error = \"Please enter valid url\"\n else:\n short_id = shortified(url_to_parse)\n return render_template('result.html', short_id=short_id)\n\n\n@app.route(\"/\")\ndef expand_to_long_url(short_id):\n link_target = redis.get('url-target:' + short_id)\n if link_target is None:\n raise NotFound()\n return redirect(link_target)\n \n \ndef shortified(url):\n short_id = redis.get('reverse-url:' + url)\n if short_id is not None:\n return short_id\n url_num = redis.incr('last-url-id')\n short_id = b62_encode(url_num)\n redis.set('url-target:' + short_id, url)\n redis.set('reverse-url:' + url, short_id)\n return short_id\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"RedisSHORTURL/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"100138584","text":"import logging\nimport typing\n\nimport requests\n\nfrom librespot.core.ApResolver import ApResolver\nfrom librespot.metadata import AlbumId\nfrom librespot.metadata import ArtistId\nfrom librespot.metadata import EpisodeId\nfrom librespot.metadata import ShowId\nfrom librespot.metadata import TrackId\nfrom librespot.proto import Connect_pb2 as Connect\nfrom librespot.proto import Metadata_pb2 as Metadata\nfrom librespot.standard import Closeable\n\n\nclass ApiClient(Closeable):\n _LOGGER: logging = logging.getLogger(__name__)\n _session = None\n _baseUrl: str\n\n def __init__(self, session):\n self._session = session\n self._baseUrl = \"https://{}\".format(ApResolver.get_random_spclient())\n\n def build_request(\n self,\n method: str,\n suffix: str,\n headers: typing.Union[None, typing.Dict[str, str]],\n body: typing.Union[None, bytes],\n ) -> requests.PreparedRequest:\n request = requests.PreparedRequest()\n request.method = method\n request.data = body\n request.headers = {}\n if headers is not None:\n request.headers = headers\n request.headers[\"Authorization\"] = \"Bearer {}\".format(\n self._session.tokens().get(\"playlist-read\"))\n request.url = self._baseUrl + suffix\n return request\n\n def send(\n self,\n method: str,\n suffix: str,\n headers: typing.Union[None, typing.Dict[str, str]],\n body: typing.Union[None, bytes],\n ) -> requests.Response:\n resp = self._session.client().send(\n self.build_request(method, suffix, headers, body))\n return resp\n\n def put_connect_state(self, connection_id: str,\n proto: Connect.PutStateRequest) -> None:\n resp = self.send(\n \"PUT\",\n \"/connect-state/v1/devices/{}\".format(self._session.device_id()),\n {\n \"Content-Type\": \"application/protobuf\",\n \"X-Spotify-Connection-Id\": connection_id,\n },\n proto.SerializeToString(),\n )\n\n if resp.status_code == 413:\n self._LOGGER.warning(\n \"PUT state payload is too large: {} bytes uncompressed.\".\n format(len(proto.SerializeToString())))\n elif resp.status_code != 200:\n self._LOGGER.warning(\"PUT state returned {}. headers: {}\".format(\n resp.status_code, resp.headers))\n\n def get_metadata_4_track(self, track: TrackId) -> Metadata.Track:\n resp = self.send(\"GET\", \"/metadata/4/track/{}\".format(track.hex_id()),\n None, None)\n ApiClient.StatusCodeException.check_status(resp)\n\n body = resp.content\n if body is None:\n raise RuntimeError()\n proto = Metadata.Track()\n proto.ParseFromString(body)\n return proto\n\n def get_metadata_4_episode(self, episode: EpisodeId) -> Metadata.Episode:\n resp = self.send(\"GET\",\n \"/metadata/4/episode/{}\".format(episode.hex_id()),\n None, None)\n ApiClient.StatusCodeException.check_status(resp)\n\n body = resp.content\n if body is None:\n raise IOError()\n proto = Metadata.Episode()\n proto.ParseFromString(body)\n return proto\n\n def get_metadata_4_album(self, album: AlbumId) -> Metadata.Album:\n resp = self.send(\"GET\", \"/metadata/4/album/{}\".format(album.hex_id()),\n None, None)\n ApiClient.StatusCodeException.check_status(resp)\n\n body = resp.content\n if body is None:\n raise IOError()\n proto = Metadata.Album()\n proto.ParseFromString(body)\n return proto\n\n def get_metadata_4_artist(self, artist: ArtistId) -> Metadata.Artist:\n resp = self.send(\"GET\",\n \"/metadata/4/artist/{}\".format(artist.hex_id()), None,\n None)\n ApiClient.StatusCodeException.check_status(resp)\n\n body = resp.content\n if body is None:\n raise IOError()\n proto = Metadata.Artist()\n proto.ParseFromString(body)\n return proto\n\n def get_metadata_4_show(self, show: ShowId) -> Metadata.Show:\n resp = self.send(\"GET\", \"/metadata/4/show/{}\".format(show.hex_id()),\n None, None)\n ApiClient.StatusCodeException.check_status(resp)\n\n body = resp.content\n if body is None:\n raise IOError()\n proto = Metadata.Show()\n proto.ParseFromString(body)\n return proto\n\n class StatusCodeException(IOError):\n code: int\n\n def __init__(self, resp: requests.Response):\n super().__init__(resp.status_code)\n self.code = resp.status_code\n\n @staticmethod\n def check_status(resp: requests.Response) -> None:\n if resp.status_code != 200:\n raise ApiClient.StatusCodeException(resp)\n","sub_path":"librespot/dealer/ApiClient.py","file_name":"ApiClient.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"548731745","text":"# coding=utf-8\n\nfrom flask.ext.jsonpify import jsonify\nfrom flask import request\n\nfrom os import walk\nfrom config_default import static_url, cdn_static_url\n\n\nind_list = {\n u'交通运输': 'jtys',\n u'休闲服务': 'xxff',\n u'传媒': 'cm',\n u'公用事业': 'gysy',\n u'农林牧渔': 'nlmy',\n u'化工': 'hg',\n u'医药生物': 'yysw',\n u'商业贸易': 'symy',\n u'国防军工': 'gfjg',\n u'家用电器': 'jydq',\n u'建筑建材': 'jzjc',\n u'建筑装饰': 'jzzs',\n u'房地产': 'fdc',\n u'教育': 'jy',\n u'新能源': 'xny',\n u'有色金属': 'ysjs',\n u'机械设备': 'jxsb',\n u'汽车': 'qc',\n u'电子': 'dz',\n u'电气设备': 'dzsb',\n u'纺织服装': 'fzfz',\n u'综合': 'zh',\n u'计算机': 'jsj',\n u'轻工制造': 'qgzz',\n u'通信': 'tx',\n u'采掘': 'cj',\n u'钢铁': 'gt',\n u'银行': 'yh',\n u'非银金融': 'fyjr',\n u'食品饮料': 'spyl'\n}\n\n\nclass Assist:\n def __init__(self):\n pass\n\n @staticmethod\n def list_industry_img():\n industry = request.args.get('industry', '')\n\n data = []\n for (dir_path, dir_names, file_names) in walk('/data/static/img/industry_new/' + ind_list[industry]):\n data.extend(file_names)\n break\n\n result_data = []\n for item in data:\n result_data.append(cdn_static_url + '/img/industry_new/%s/%s' % (ind_list[industry], item))\n\n return jsonify(result_data)\n\n @staticmethod\n def list_res():\n dir_name = request.args.get('dir_name', '')\n\n data = []\n for (dir_path, dir_names, file_names) in walk('/data/static/' + dir_name):\n data.extend(file_names)\n break\n\n result_data = []\n for item in data:\n result_data.append(cdn_static_url + '/%s/%s' % (dir_name, item))\n\n return jsonify(result_data)\n","sub_path":"action/assist.py","file_name":"assist.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"211076187","text":"import numpy as np\nimport plotly.graph_objects as go\nfrom spacecraft import Spacecraft\n\n\ndef base_figure():\n \"\"\"Instantiate baseline Plotly Geo figure.\"\"\"\n fig = go.Figure(go.Scattergeo())\n fig.update_geos(\n #resolution=50,\n showcoastlines=True,\n coastlinecolor='#919191',\n showland=True,\n landcolor='#787878',\n showocean=True,\n oceancolor='black',\n showcountries=True,\n countrycolor='#919191',\n showlakes=False,\n visible=False\n )\n fig.update_layout(\n margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0},\n showlegend=False,\n dragmode=False,\n paper_bgcolor='black',\n )\n return fig\n\n\ndef add_track(fig, times, lat, lon, alt):\n \"\"\"Add ground track to Plotly Geo figure.\"\"\"\n fmt_times = [x.strftime(r'%Y-%j %H:%M:%Sz') for x in times]\n fig.add_trace(\n go.Scattergeo(\n lat = lat,\n lon = lon,\n customdata=np.c_[fmt_times, alt],\n mode = 'lines',\n line = dict(color='#ffed78'),\n hovertemplate='
'.join([\n 'Time: %{customdata[0]}',\n 'Latitude: %{lat:.2f}\\u00B0',\n 'Longitude: %{lon:.2f}\\u00B0',\n 'Altitude: %{customdata[1]:.0f} km'\n ]),\n )\n )\n return fig\n\n\ndef add_spacecraft(fig, name, lat, lon):\n \"\"\"Add spacecraft marker to Plotly Geo figure.\"\"\"\n for symbol in ['arrow-left', 'arrow-right', 'circle']:\n hover_name = None\n if symbol == 'circle':\n hover_name = name + ''\n fig.add_trace(\n go.Scattergeo(\n lat = lat,\n lon = lon,\n mode='markers',\n marker_symbol=symbol,\n marker_line_color='black',\n marker_color='#ffed78',\n hovertemplate=hover_name,\n marker_line_width=2,\n marker_size=15,\n )\n )\n return fig\n\n\ndef add_stations(fig, stations):\n \"\"\"Add ground station markers to Plotly Geo figure.\"\"\"\n for name, loc in stations.items():\n for symbol in ['arrow-up', 'triangle-sw']:\n hover_name = None\n if symbol == 'triangle-sw':\n hover_name = '
'.join([\n f'{name}',\n f'Latitude: {loc[\"Lat\"]:.2f}\\u00B0',\n f'Longitude: {loc[\"Lon\"]:.2f}\\u00B0',\n f'Altitude: {loc[\"Alt\"]:.0f} km'\n ])\n fig.add_trace(\n go.Scattergeo(\n lat = [loc['Lat']],\n lon = [loc['Lon']],\n mode='markers',\n marker_symbol=symbol,\n marker_line_color='white',\n marker_color='black',\n hovertemplate=hover_name,\n marker_line_width=2,\n marker_size=15,\n )\n )\n return fig\n\n\ndef add_visibility_lines(fig, i, el_con, sc_lat, sc_lon, stations):\n \"\"\"If spacecraft is in ground stations FOV, add line from spacecraft\n to station on Plotly Geo figure.\"\"\"\n for _, details in stations.items():\n if details['Elevation'][i] > el_con:\n fig.add_trace(\n go.Scattergeo(\n lat = [sc_lat, details['Lat']],\n lon = [sc_lon, details['Lon']],\n mode='lines',\n line = dict(color='#32ff2b'),\n hoverinfo='skip'\n )\n )\n return fig\n\n\ndef copy_fig(fig):\n \"\"\"Copy a Plotly Geo figure object.\"\"\"\n return go.Figure(fig)\n\n\ndef main():\n name = 'Cryosat 2'\n sc = Spacecraft(name, tle_file='inputs/platform.tle')\n fig = base_figure()\n fig = add_stations(fig, sc.stations)\n fig = add_track(fig, sc.times, sc.lat, sc.lon, sc.alt)\n fig = add_spacecraft(fig, name, sc.lat[:1], sc.lon[:1])\n fig.show()\n #print(sc.passes)\n\n\nif __name__ == '__main__':\n main()","sub_path":"track_plot.py","file_name":"track_plot.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"560875023","text":"import datetime\nfrom django.db import models\nfrom django.utils import timezone\n\nBOOK_STATUSES = (\n (1, 'unborrowed'),\n (2, 'borrowed'),\n)\n\nBORROW_STATUSES = (\n (1, 'borrow'),\n (2, 'return'),\n)\n\nclass User(models.Model):\n name = models.CharField(max_length=32)\n mail = models.EmailField()\n\nclass Book(models.Model):\n title = models.CharField(max_length=200)\n author = models.CharField(max_length=200)\n publisher = models.CharField(max_length=200) \n image_url = models.URLField(max_length=200, null=True)\n status = models.IntegerField(choices=BOOK_STATUSES)\n updated_at = models.DateTimeField(auto_now=True) \n created_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.title\n\n def is_borrowed(self):\n return self.status == 2\n\n def borrow_book(self):\n self.status = 2\n self.save()\n return 2\n\n def return_book(self):\n self.status = 1\n self.save()\n return 1\n\nclass BorrowHistory(models.Model):\n user = models.ForeignKey(User, related_name='borrow_history', on_delete=models.CASCADE)\n book = models.ForeignKey(Book, related_name='entries', on_delete=models.CASCADE)\n status = models.IntegerField(choices=BORROW_STATUSES)\n updated_at = models.DateTimeField(auto_now=True) \n created_at = models.DateTimeField(auto_now_add=True)\n","sub_path":"book_manager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"405363737","text":"#!/usr/bin/env python\n\n# Top level python script to create all necessary input files for the WCCR10 project\n\nimport input_utils\nimport read_output\nfrom make_molpro_input_mp2 import *\nfrom make_molpro_input_rpa import *\nimport os\n\ndef main(rxn_key,rxn_dict,cluster,\n high_theory,geom,\n read_output):\n\n # Determine which cluster is being used\n if cluster == 'cori':\n # TODO This needs to be made\n import make_cori_sbatch\n base_dir = make_cori_sbatch.base_dir\n qos = make_cori_sbatch.qos_premium\n batch_mem = make_cori_sbatch.batch_mem\n #high_num_cpus = 3\n #mol_mem = input_utils.calcMolMem(batch_mem,high_num_cpus)\n elif cluster == 'central':\n # TODO This needs to be made\n import make_central_sbatch\n base_dir = make_central_sbatch.base_dir\n queue = make_central_sbatch.queue_any\n batch_mem = make_central_sbatch.batch_mem\n #high_num_cpus = 3\n #mol_mem = input_utils.calcMolMem(batch_mem,high_num_cpus)\n else: # For tachus case\n import make_tachus_sbatch\n base_dir = make_tachus_sbatch.base_dir\n queue = make_tachus_sbatch.queue_cluster\n batch_mem = make_tachus_sbatch.batch_mem\n high_num_cpus = 3\n mol_mem = input_utils.calcMolMem(batch_mem,high_num_cpus)\n\n for high_item in high_theory:\n high = high_item[0]\n bs = high_item[1]\n if (not high == 'MP2') and (not \"RPA\" in high):\n raise ValueError('The specified high-level of theory is not supported. Theory: {:s}'.format(high))\n\n for mol_key in rxn_dict:\n mol_dict = rxn_dict[mol_key]\n # Create part of file_path\n geom_str=geom[0]+'_geom'\n high_str='df-'+high+'_'+bs\n path = os.path.join(base_dir,rxn_key,high_str,geom_str,mol_key)\n\n if (read_output):\n # Checks that the directory path already exists\n if not os.path.isdir(path):\n raise RuntimeError('The specified level theory has not been run. Theory: {:s}'.format(high_str))\n\n # Create name of output file\n molpro_out = '{0}.out'.format(mol_key)\n if not os.path.isfile(path):\n raise RuntimeError('Even though the path exists, there is no output file. Path: {:s}'.format(path))\n\n # Read the output file\n # TODO Perform a check to see if the job finished successfully\n # Or perform this check in read_output and populate an empty dictionary if output file didn't finish\n if high == 'MP2':\n key_word = high\n elif 'RPA' in high:\n key_word = high\n #read_output.readOutput(key_word)\n\n else:\n # Make directories for the new jobs\n try:\n os.makedirs(path)\n except OSError:\n pass\n\n # Create file names\n molpro_name = '{0}.mol'.format(mol_key)\n batch_name = '{0}.batch'.format(mol_key)\n job_name = mol_key + '_' + high_str\n # Create the batch files depending on the cluster\n if cluster == 'cori':\n # TODO This needs to be set up still\n #make_cori_sbatch.main(path,batch_name,job_name,queue,\n # high_num_cpus,batch_mem,molpro_name)\n pass\n elif cluster == 'central':\n # TODO This needs to be set up still\n #make_central_sbatch.main(path,batch_name,job_name,queue,\n # high_num_cpus,batch_mem,molpro_name)\n pass\n else:\n make_tachus_sbatch.main(path,batch_name,job_name,queue,\n high_num_cpus,batch_mem,molpro_name)\n\n if high == 'MP2':\n # Create the df-MP2 inputs\n make_molpro_input_mp2(mol_dict,path,molpro_name,\n basis=bs,memory=mol_mem)\n elif \"RPA\" in high:\n # Create the RPA inputs\n make_molpro_input_rpa(mol_dict,path,molpro_name,\n high,basis=bs,memory=mol_mem)\n","sub_path":"scripts_wccr10/psuedo_hi_level.py","file_name":"psuedo_hi_level.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"161470923","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import *\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass AsiaGlobalEquipmentType(models.Model):\n\t_name = 'asiaglobal.equipment_type'\n\n\tname = fields.Char(required=True)\n\nclass AsiaGlobalEngineModel(models.Model):\n\t_name = 'asiaglobal.engine_model'\n\n\tname = fields.Char(required=True)\n\tmanufacturer = fields.Many2one('asiaglobal.manufacturer')\n\nclass AsiaGlobalDriveAxleModel(models.Model):\n\t_name = 'asiaglobal.drive_axlemodel'\n\n\tname = fields.Char(required=True)\n\tmanufacturer = fields.Many2one('asiaglobal.manufacturer')\n\nclass AsiaGlobalTransmissionModel(models.Model):\n\t_name = 'asiaglobal.transmission_model'\n\n\tname = fields.Char(required=True)\n\tmanufacturer = fields.Many2one('asiaglobal.manufacturer')\n\nclass AsiaGlobalMastType(models.Model):\n\t_name = 'asiaglobal.mast_type'\n\n\tname = fields.Char(required=True)\n\nclass AsiaGlobalEquipmentProfile(models.Model):\n\t_name = 'asiaglobal.equipment_profile'\n\t_description = 'Equipment Profile'\n\t_inherit = ['mail.thread','mail.activity.mixin']\n\n\t@api.depends('job_expense_ids.amount_total')\n\tdef _amount_all(self):\n\t\t\"\"\"\n\t\tCompute the total amounts of the Expense.\n\t\t\"\"\"\n\t\tfor equipment in self:\n\t\t\tamount_expense_total = 0.0\n\t\t\tfor expense in equipment.job_expense_ids:\n\t\t\t\tamount_expense_total += expense.amount_total\n\t\t\tequipment.update({\n\t\t\t\t'amount_expense_total':amount_expense_total,\n\t\t\t})\n\n\t@api.one\n\tdef _compute_parts_fitted(self):\n\t\tparts_fitted = []\n\t\tfor job in self.jo_ids:\n\t\t\tfor report in job.service_report_ids:\n\t\t\t\tif report.is_parts_fitted == True and report.parts_fitted:\n\t\t\t\t\tfor parts in report.parts_fitted:\n\t\t\t\t\t\tparts_fitted.append(parts.id)\n\t\tself.parts_fitted = parts_fitted\n\n\t@api.one\n\tdef _compute_job_material_request(self):\n\t\tjob_material_request = []\n\t\tfor job in self.jo_ids:\n\t\t\tfor request in job.job_material_request_ids:\n\t\t\t\tjob_material_request.append(request.id)\n\t\tself.job_material_request_ids = job_material_request\n\n\tname = fields.Char(string='Equipment Profile', store=True, compute=\"_compute_name\")\n\tcustomer = fields.Many2one('res.partner', ondelete='cascade', required=True, track_visibility='onchange')\n\tship_to = fields.Many2one('res.partner', string='Ship To / Site Address')\n\tmanufacturer = fields.Many2one('asiaglobal.manufacturer')\n\tmodel = fields.Many2one('asiaglobal.manufacturer_model')\n\tserial_number = fields.Char()\n\n\tdate_in_service = fields.Date(required=True, default=fields.Datetime.now())\n\ttype = fields.Many2one('asiaglobal.equipment_type')\n\tcapacity = fields.Char()\n\n\tengine_make = fields.Many2one('asiaglobal.manufacturer')\n\tengine_model = fields.Many2one('asiaglobal.engine_model')\n\tengine_serial_number = fields.Char()\n\n\ttransmission_make = fields.Many2one('asiaglobal.manufacturer')\n\ttransmission_model = fields.Many2one('asiaglobal.transmission_model')\n\ttransmission_serial_number = fields.Char()\n\n\tdrive_axle_manufacturer = fields.Many2one('asiaglobal.manufacturer')\n\tdrive_axle_model = fields.Many2one('asiaglobal.drive_axlemodel')\n\tdrive_axle_serial_number = fields.Char()\n\n\ttraction_battery_capacity = fields.Char()\n\ttraction_battery_serial_number = fields.Char()\n\n\tbattery_1 = fields.Char()\n\tbattery_1_type = fields.Char(string='Type')\n\tbattery_1_serial = fields.Char(string='Serial Number')\n\n\tbattery_2 = fields.Char()\n\tbattery_2_type = fields.Char(string='Type')\n\tbattery_2_serial = fields.Char(string='Serial Number')\n\n\tbattery_3 = fields.Char()\n\tbattery_3_type = fields.Char(string='Type')\n\tbattery_3_serial = fields.Char(string='Serial Number')\n\n\tmast_type = fields.Many2one('asiaglobal.mast_type')\n\tmast_serial_number = fields.Char()\n\tforks = fields.Char()\n\tlift_height = fields.Char()\n\tgross_weight = fields.Char()\n\n\tmaintenance_contract = fields.Boolean()\n\tmaintenance_start_date = fields.Date(default=fields.Datetime.now())\n\tmaintenance_end_date = fields.Date(default=fields.Datetime.now())\n\tmaintenance_frequency_count = fields.Integer()\n\tmaintenance_frequency = fields.Selection([\n\t\t('day', 'Days'),\n\t\t('week', 'Weeks'),\n\t\t('month', 'Months'),\n\t\t('year', 'Years'),\n\t], default='day')\n\tnext_maintenance_date = fields.Date(default=fields.Datetime.now())\n\n\thour_meter = fields.Float(compute=\"_compute_hour_meter\")\n\n\t# WARRANTY\n\twarranty_date_acceptance = fields.Date(string='Date of Acceptance', default=fields.Datetime.now())\n\twarranty_year = fields.Float()\n\twarranty_hours = fields.Float()\n\n\tjo_ids = fields.One2many('asiaglobal.job_order', 'equipment_id', string='Job Orders', readonly=True)\n\n\t# RENTAL\n\trental_date_start = fields.Date(string='Start of Rental Period')\n\trental_date_end = fields.Date(string='End of Rental Period')\n\n\tequipment_owner_id = fields.Many2one('res.partner', string='Equipment Owner', track_visibility='onchange')\n\t\n\toperational = fields.Boolean(default=True)\n\toperational_message = fields.Char(string='Equipment Status', track_visibility='onchange')\n\n\tparts_fitted = fields.Many2many('asiaglobal.service_report_parts', string='Parts Fitted', compute='_compute_parts_fitted')\n\n\tjob_expense_ids = fields.One2many('asiaglobal.job_expense', 'equipment_id', string='Job Expense')\n\tamount_expense_total = fields.Float(string='Total Other Repair Costs', store=True, readonly=True, compute='_amount_all', track_visibility='always')\n\n\tjob_material_request_ids = fields.Many2many('asiaglobal.job_material_request_form', string='Job Material Request Form', compute='_compute_job_material_request')\n\n\t@api.multi\n\t@api.onchange('customer')\n\tdef onchange_customer(self):\n\t\tif not self.customer:\n\t\t\tself.update({\n\t\t\t\t'ship_to': False,\n\t\t\t})\n\t\t\treturn\n\n\t\taddr = self.customer.address_get(['delivery'])\n\t\tvalues = {\n\t\t\t'ship_to': addr['delivery'],\n\t\t}\n\n\t\tself.update(values)\n\n\t@api.onchange('operational')\n\tdef set_operational_message(self):\n\t\tif self.operational == True:\n\t\t\tself.operational_message = \"OPERATIONAL\"\n\t\telse:\n\t\t\tself.operational_message = \"NOT OPERATIONAL\"\n\n\t@api.one\n\t@api.depends('customer','manufacturer','model','serial_number')\n\tdef _compute_name(self):\n\t\tname = ''\n\t\tif self.customer:\n\t\t\tname += self.customer.name\n\n\t\tif self.manufacturer:\n\t\t\tname += ' - ' + self.manufacturer.name\n\n\t\tif self.model:\n\t\t\tname += ' - ' + self.model.name\n\n\t\tif self.serial_number:\n\t\t\tname += ' - ' + self.serial_number\n\n\t\tself.name = name\n\n\t@api.multi\n\tdef _compute_hour_meter(self):\n\t\tfor record in self:\n\t\t\tlatest_service_report_hour_meter = 0\n\t\t\tlatest_service_report_visit_date = False\n\t\t\tfor job in record.jo_ids:\n\t\t\t\tfor report in job.service_report_ids:\n\t\t\t\t\tif not latest_service_report_visit_date:\n\t\t\t\t\t\tlatest_service_report_visit_date = report.visit_date\n\t\t\t\t\t\tlatest_service_report_hour_meter = report.hour_meter\n\t\t\t\t\tif latest_service_report_visit_date < report.visit_date:\n\t\t\t\t\t\tlatest_service_report_visit_date = report.visit_date\n\t\t\t\t\t\tlatest_service_report_hour_meter = report.hour_meter\n\n\t\t\t\t\t_logger.info('BULRAEK')\n\t\t\t\t\t_logger.info(report.visit_date)\n\t\t\t\t\t_logger.info(latest_service_report_visit_date)\n\t\t\t\t\t_logger.info(latest_service_report_hour_meter)\n\n\t\t\trecord.hour_meter = latest_service_report_hour_meter\n\n\t@api.model\n\tdef create(self, vals):\n\t\tdate_in_service = vals.get('date_in_service')\n\t\tcount = vals.get('maintenance_frequency_count')\n\t\tfrequency = vals.get('maintenance_frequency')\n\t\tif date_in_service and count and frequency:\n\t\t\tvals['next_maintenance_date'] = self.get_maintenance_date(date_in_service,count,frequency)\n\n\t\tresult = super(AsiaGlobalEquipmentProfile, self).create(vals)\n\t\treturn result\n\n\t@api.model\n\tdef create_maintenance_jo(self, equipment_id, date):\n\t\tvalues = {\n\t\t\t'customer_id': equipment_id.customer.id,\n\t\t\t'ship_to': equipment_id.ship_to.id,\n\t\t\t'equipment_id': equipment_id.id,\n\t\t\t'manufacturer': equipment_id.manufacturer.id,\n\t\t\t'model': equipment_id.model.id,\n\t\t\t'serial_number': equipment_id.serial_number,\n\t\t\t'scheduled_date': date,\n\t\t\t'actual_repair_date': date,\n\t\t} \n\t\tjob_order = self.env['asiaglobal.job_order'].create(values)\n\t\treturn job_order","sub_path":"models/equipment.py","file_name":"equipment.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"513841999","text":"# Copyright (c) 2016 Intel Corporation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom vpnclient.utils import FH\nfrom vpnclient.v1_0.command_list import ListCommand\nfrom vpnclient.v1_0.command_resource import CommandResource\n\n_COMMAND_COLUMNS = (\n 'id',\n 'subject_pattern',\n 'description',\n)\n\n_HTTP_RESOURCE = 'users'\n\n_PK_COLUMN = 'id'\n\n\nclass CreateCertificateUser(CommandResource):\n \"\"\"Create a RBAC Certificate User\"\"\"\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n pk_column = _PK_COLUMN\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'subject-pattern',\n metavar='SUBJECT_PATTERN',\n help=FH(_(\"Pattern of Certificate's Subject or Alt. Name\")))\n\n parser.add_argument(\n '--description',\n help=FH(_(\"Description of RBAC Certificate User\")))\n\n return parser\n\n\nclass ShowCertificateUser(CommandResource):\n \"\"\"Show information of a given RBAC Certificate User\"\"\"\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n pk_column = _PK_COLUMN\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'id',\n metavar='RBAC_CERTIFICATE_USER',\n help=FH(_(\"ID of RBAC Certificate User to search\")))\n\n return parser\n\n\nclass ListCertificateUser(CommandResource):\n \"\"\"List all RBAC Certificate Users\"\"\"\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n pk_column = _PK_COLUMN\n\n @staticmethod\n def add_known_arguments(parser):\n return ListCommand.add_args(parser)\n\n\nclass UpdateCertificateUser(CommandResource):\n \"\"\"Update a given RBAC CertificateUser\"\"\"\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n pk_column = _PK_COLUMN\n\n @staticmethod\n def add_known_arguments(parser):\n\n parser.add_argument(\n 'id',\n metavar='RBAC_CERTIFICATE_USER',\n help=FH(_(\"ID of RBAC Certificate User to update\")))\n\n parser.add_argument(\n '--subject_pattern',\n help=FH(_(\"Pattern of Certificate's Subject or Alt. Name\")))\n\n parser.add_argument(\n '--description',\n help=FH(_(\"Description of RBAC Certificate User\")))\n\n return parser\n\n\nclass DeleteCertificateUser(CommandResource):\n \"\"\"Delete a given RBAC CertificateUser\"\"\"\n cmd_columns = _COMMAND_COLUMNS\n http_resource = _HTTP_RESOURCE\n pk_column = _PK_COLUMN\n\n @staticmethod\n def add_known_arguments(parser):\n parser.add_argument(\n 'id',\n metavar='RBAC_CERTIFICATE_USER',\n help=FH(_(\"ID of RBAC Certificate User to delete\")))\n\n return parser\n","sub_path":"IPSec_EMS/common/vpnclient/v1_0/rbac/rbac_certificate_user.py","file_name":"rbac_certificate_user.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"457637805","text":"'''\nLeia 2 valores inteiros (A e B). Após,\no programa deve mostrar uma mensagem \"Sao Multiplos\"\nou \"Nao sao Multiplos\", indicando se os valores lidos são múltiplos entre si.\n\nEntrada\nA entrada contém valores inteiros.\n\nSaída\nA saída deve conter uma das mensagens conforme descrito acima.\n'''\nentrada = input().split()\nA, B = int(entrada[0]), int(entrada[1])\nif B % A == 0 or A % B == 0:\n print(\"Sao Multiplos\")\nelse:\n print('Nao sao Multiplos')\n","sub_path":"Nivel 1/1044 Multiplos.py","file_name":"1044 Multiplos.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"286472344","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import proj3d\n\nu = np.linspace(0, 2 * np.pi, 100)\nv = np.linspace(0, np.pi, 100)\n\nx = np.outer(np.cos(u), np.sin(v))\ny = np.outer(np.sin(u), np.sin(v))\nz = np.outer(np.ones(np.size(u)), np.cos(v))\n\nfig = plt.figure()\nax = fig.add_subplot('111', projection='3d')\nax.plot_surface(x, y, z, rstride=5, cstride=5, color='y', alpha=0.1)\n\n\n# define a set of points on the sphere in any way you like\ndef convert_spherical_array_to_cartesian_array(spherical_coord_array, angle_measure='radians'):\n\t\"\"\"\n\tTake shape (N,3) spherical_coord_array (r,theta,phi) and return an array of\n\tthe same shape in cartesian coordinate form (x,y,z). Based on the\n\tequations provided at:\n\thttp://en.wikipedia.org/wiki/List_of_common_coordinate_transformations#From_spherical_coordinates\n\tuse radians for the angles by default, degrees if angle_measure == 'degrees'\n\t\"\"\"\n\tcartesian_coord_array = np.zeros(spherical_coord_array.shape)\n\t# convert to radians if degrees are used in input\n\tif angle_measure == 'degrees':\n\t\tspherical_coord_array[...,1] = np.deg2rad(spherical_coord_array[...,1])\n\t\tspherical_coord_array[...,2] = np.deg2rad(spherical_coord_array[...,2])\n\t# now the conversion to Cartesian coords\n\tcartesian_coord_array[...,0] = spherical_coord_array[...,0] * np.cos(spherical_coord_array[...,1]) * np.sin(spherical_coord_array[...,2])\n\tcartesian_coord_array[...,1] = spherical_coord_array[...,0] * np.sin(spherical_coord_array[...,1]) * np.sin(spherical_coord_array[...,2])\n\tcartesian_coord_array[...,2] = spherical_coord_array[...,0] * np.cos(spherical_coord_array[...,2])\n\treturn cartesian_coord_array\n\n# generate random points on the unit sphere\ndef generate_random_array_spherical_generators(num_generators, sphere_radius, prng_object):\n\t\"\"\"\n\tRecoded using standard uniform selector over theta and acos phi,\n\thttp://mathworld.wolfram.com/SpherePointPicking.html\n\tSame as in iPython notebook version\n\t\"\"\"\n\tu = prng_object.uniform(low=0,high=1,size=num_generators)\n\tv = prng_object.uniform(low=0,high=1,size=num_generators)\n\ttheta_array = 2 * np.pi * u\n\tphi_array = np.arccos((2*v - 1.0))\n\tr_array = sphere_radius * np.ones((num_generators,))\n\tspherical_polar_data = np.column_stack((r_array,theta_array, phi_array))\n\tcartesian_random_points = convert_spherical_array_to_cartesian_array(spherical_polar_data)\n\treturn cartesian_random_points\n\nfrom scipy.spatial import SphericalVoronoi\n\npoints = generate_random_array_spherical_generators(50,1, np.random.RandomState(117))\n\nfig = plt.figure()\nax = fig.add_subplot('111', projection='3d')\nax.plot_surface(x, y, z, rstride=5, cstride=5, color='y', alpha=0.1)\nax.scatter(points[:,0], points[:,1], points[:,2])\n\nradius = 1\ncenter = np.array([0,0,0])\nsv = SphericalVoronoi(points, radius, center)\n\nfig = plt.figure()\nax = fig.add_subplot('111', projection='3d')\nax.plot_surface(x, y, z, rstride=5, cstride=5, color='y', alpha=0.1)\nax.scatter(points[:,0], points[:,1], points[:,2])\nax.scatter(sv.vertices[:,0], sv.vertices[:,1], sv.vertices[:,2], color='r')\n\n\nfrom matplotlib import colors\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\nfig = plt.figure()\nax = fig.add_subplot('111', projection='3d')\nax.plot_surface(x, y, z, rstride=5, cstride=5, color='y', alpha=0.1)\nax.scatter(points[:,0], points[:,1], points[:,2])\n\nsv.sort_vertices_of_regions()\n# this is not yet completely accurate\nfor n in range(0, len(sv.regions)):\n\tregion = sv.regions[n]\n\tax.scatter(points[n, 0], points[n, 1], points[n, 2], c='b')\n\trandom_color = colors.rgb2hex(np.random.rand(3))\n\tpolygon = Poly3DCollection([sv.vertices[region]], alpha=1.0)\n\tpolygon.set_color(random_color)\n\tax.add_collection3d(polygon)\n\nplt.show()\n","sub_path":"Projects/awest/code/experiments/voronoi.py","file_name":"voronoi.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"119258005","text":"import pygame\r\n\r\npygame.init()\r\n\r\n# window creation\r\nwin = pygame.display.set_mode((800, 600))\r\npygame.display.set_caption(\"Space Invader\")\r\nicon = pygame.image.load('data/Enemy.png')\r\npygame.display.set_icon(icon)\r\nclock = pygame.time.Clock()\r\nscore = 0\r\nlevel = 0\r\ncurr_bullet = 0\r\nbutton_unpressed = True\r\n\r\n\r\nclass Bullet:\r\n bulletIMG = pygame.transform.scale(pygame.image.load('data/bullet.png'), (32, 32))\r\n\r\n def __init__(self):\r\n self.x_pos = 0\r\n self.y_pos = 480\r\n self.y_vel = 5\r\n self.x_acc = 0\r\n self.y_acc = 10\r\n self.state = False\r\n\r\n def fire_bullet(self, x, y):\r\n self.state = True\r\n win.blit(self.bulletIMG, (x + 16, y - 32))\r\n\r\n def get_mask(self):\r\n return pygame.mask.from_surface(self.bulletIMG)\r\n\r\n\r\nclass Player:\r\n playerIMG = pygame.transform.scale(pygame.image.load(\"data/Player.png\"), (64, 64))\r\n\r\n def __init__(self):\r\n self.x_pos = 370\r\n self.y_pos = 480\r\n self.x_vel = 0\r\n self.x_acc = 10\r\n\r\n def player(self, x, y):\r\n win.blit(self.playerIMG, (x, y))\r\n\r\n def get_mask(self):\r\n return pygame.mask.from_surface(self.playerIMG)\r\n\r\n\r\nclass Enemy:\r\n enemyIMG = pygame.transform.scale(pygame.image.load(\"data/Enemy2.png\"), (64, 64))\r\n enemy2IMG = pygame.transform.scale(pygame.image.load(\"data/Enemy3.png\"), (64, 64))\r\n enemy3IMG = pygame.transform.scale(pygame.image.load(\"data/Enemy4.png\"), (64, 64))\r\n enemy4IMG = pygame.transform.scale(pygame.image.load(\"data/Enemy5.png\"), (64, 64))\r\n enemy5IMG = pygame.transform.scale(pygame.image.load(\"data/Enemy6.png\"), (64, 64))\r\n enemyBossIMG = pygame.transform.scale(pygame.image.load(\"data/EnemyBoss.png\"), (128, 64))\r\n\r\n def __init__(self, x, y, h):\r\n self.x_pos = x\r\n self.y_pos = y\r\n self.x_vel = 5\r\n self.x_acc = 5\r\n self.y_acc = 64\r\n self.health = h\r\n self.bossShield = 0\r\n\r\n if self.health > 5:\r\n self.bossShield = self.health - 5\r\n self.health = 5\r\n\r\n self.images = {\r\n 0: self.enemyIMG,\r\n 1: self.enemy2IMG,\r\n 2: self.enemy3IMG,\r\n 3: self.enemy4IMG,\r\n 4: self.enemy5IMG,\r\n 5: self.enemyBossIMG,\r\n }\r\n\r\n def enemy(self, x, y):\r\n if self.bossShield == 0:\r\n win.blit(self.images[self.health], (x, y))\r\n else:\r\n win.blit(self.images[5], (x, y))\r\n\r\n def get_mask(self):\r\n return pygame.mask.from_surface(self.enemyIMG)\r\n\r\nclass EnemyBunch:\r\n pass\r\n\r\nbullets = []\r\nplayer = Player()\r\nenemys = []\r\n\r\nfor i in range(0, 20):\r\n y = int(i / 5) + 1\r\n x = i % 5\r\n enemys.append(Enemy(x * 80, y * 64 - 150, 0))\r\n\r\n\r\ndef is_collision(bul, enm):\r\n enemy_mask = bul.get_mask()\r\n bullet_mask = enm.get_mask()\r\n\r\n offset = (enm.x_pos - bul.x_pos, enm.y_pos - round(bul.y_pos))\r\n\r\n point = enemy_mask.overlap(bullet_mask, offset)\r\n\r\n if point:\r\n return True\r\n\r\n return False\r\n\r\n\r\n# Game Loop\r\nrunning = True\r\nwhile running:\r\n clock.tick(60)\r\n win.fill((15, 0, 85))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n pygame.quit()\r\n quit()\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n player.x_vel = -player.x_acc\r\n button_unpressed = False\r\n if event.key == pygame.K_RIGHT:\r\n player.x_vel = player.x_acc\r\n button_unpressed = False\r\n if event.key == pygame.K_SPACE and button_unpressed and curr_bullet < 3:\r\n bullets.append(Bullet())\r\n bullets[curr_bullet].x_pos = player.x_pos\r\n bullets[curr_bullet].fire_bullet(bullets[curr_bullet].x_pos, bullets[curr_bullet].y_pos)\r\n curr_bullet += 1\r\n button_unpressed = False\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_SPACE:\r\n player.x_vel = 0\r\n button_unpressed = True\r\n\r\n player.x_pos += player.x_vel\r\n if player.x_pos >= win.get_width() - 64:\r\n player.x_pos = win.get_width() - 64\r\n elif player.x_pos < 0:\r\n player.x_pos = 0\r\n\r\n for enemy in enemys:\r\n enemy.x_pos += enemy.x_vel\r\n if enemy.x_pos >= win.get_width() - 64:\r\n enemy.x_pos = win.get_width() - 64\r\n enemy.x_vel = -enemy.x_acc\r\n enemy.y_pos += enemy.y_acc\r\n elif enemy.x_pos < 0:\r\n enemy.x_pos = 0\r\n enemy.x_vel = enemy.x_acc\r\n enemy.y_pos += enemy.y_acc\r\n for bullet in bullets:\r\n if bullet.state:\r\n bullet.fire_bullet(bullet.x_pos, bullet.y_pos)\r\n bullet.y_pos -= bullet.y_acc\r\n if bullet.y_pos < 0:\r\n bullet.y_pos = player.y_pos\r\n bullet.state = False\r\n bullets.remove(bullet)\r\n curr_bullet -= 1\r\n for enemy in enemys:\r\n if is_collision(bullet, enemy):\r\n bullet.y_pos = player.y_pos\r\n bullet.state = False\r\n bullets.remove(bullet)\r\n curr_bullet -= 1\r\n if enemy.bossShield > 0:\r\n enemy.bossShield -= 1\r\n else:\r\n enemy.health -= 1\r\n if enemy.health < 0:\r\n score += 1\r\n print(score)\r\n enemys.remove(enemy)\r\n\r\n player.player(player.x_pos, player.y_pos)\r\n for enemy in enemys:\r\n enemy.enemy(enemy.x_pos, enemy.y_pos)\r\n pygame.display.flip()\r\n pygame.display.update()\r\n\r\n if not enemys:\r\n level += 1\r\n if level == 1:\r\n enemys.append(Enemy(3 * 80, 2 * 64 - 150, 15))\r\n else:\r\n for i in range(0, 20):\r\n y = int(i / 5) + 1\r\n x = i % 5\r\n if level == 1:\r\n enemys.append(Enemy(x * 80, y * 64 - 150, 1))\r\n elif level == 2:\r\n enemys.append(Enemy(x * 80, y * 64 - 150, 2))\r\n elif level == 3:\r\n enemys.append(Enemy(x * 80, y * 64 - 150, 3))\r\n else:\r\n enemys.append(Enemy(x * 80, y * 64 - 150, 4))\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"375132829","text":"#!/usr/bin/python3.6\n\n# Input data files are available in the \"../data/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nimport sys\nimport random\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport albumentations as albu\n\nimport keras\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing.image import load_img\nfrom keras.models import Model, load_model, save_model\nfrom keras.layers import Input,Dropout,BatchNormalization,Activation,Add, Dense, Flatten\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tqdm import tqdm\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras.utils import to_categorical\nfrom keras import optimizers\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom segmentation_models import Unet\nfrom segmentation_models.backbones import get_preprocessing\n\n\n\nSEED = 42\nVERSION = 2\nBATCH_SIZE = 32\nNUM_FOLDS = 5\nimage_size = 197\n\n\n# Loading of training/testing ids and depths\ntrain_df = pd.read_csv(\"../data/train.csv\", index_col=\"id\", usecols=[0])\ndepths_df = pd.read_csv(\"../data/depths.csv\", index_col=\"id\")\ntrain_df = train_df.join(depths_df)\ntest_df = pd.DataFrame(index=depths_df[~depths_df.index.isin(train_df.index)].index)\ntest_df = test_df.join(depths_df)\n\nlen(train_df)\n\n\ntrain_df[\"images\"] = [np.array(load_img(\"../data/train/images/{}.png\".format(idx), interpolation='nearest',\n target_size=(image_size, image_size),\n color_mode = \"grayscale\",)) for idx in tqdm(train_df.index)]\n\ntrain_df[\"masks\"] = [np.array(load_img(\"../data/train/masks/{}.png\".format(idx), interpolation='nearest',\n target_size=(image_size, image_size),\n color_mode = \"grayscale\",)) for idx in tqdm(train_df.index)]\n\ntest_df[\"images\"] = [np.array(load_img(\"../data/test/images/{}.png\".format(idx), interpolation='nearest',\n target_size=(image_size, image_size),\n color_mode = \"grayscale\")) for idx in tqdm(test_df.index)]\n\ntrain_df[\"coverage\"] = train_df.masks.map(np.sum) / pow(image_size, 2) / 255\n\ndef cov_to_class(val):\n for i in range(0, 11):\n if val * 10 <= i :\n return i\n\ntrain_df[\"coverage_class\"] = train_df.coverage.map(cov_to_class)\n\n\ndef get_class(img, th=10):\n img_sum = np.array([i.sum() for i in img])\n return np.array(img_sum>th).astype(int)\n\ndef add_depth_coord(images):\n \"\"\" Takes dataset (N, W, H, 1) returns (N, W, H, 3). \"\"\"\n assert(len(images.shape) == 4)\n channel1 = np.zeros_like(images)\n\n h = images.shape[1]\n for row, const in enumerate(np.linspace(0, 1, h)):\n channel1[:, row, ...] = const\n\n channel2 = images * channel1\n images = np.concatenate([images, channel1, channel2], axis=-1)\n return images\n\n\nx_train = np.array(train_df.images.tolist()).reshape(-1, image_size, image_size, 1)\ny_train = np.array(train_df.masks.tolist()).reshape(-1, image_size, image_size, 1)\n# x_test = np.array(test_df.images.tolist()).reshape(-1, image_size, image_size, 1)\ntrain_cls = np.array(train_df.coverage_class)\n\nclass Datagen(keras.utils.Sequence):\n \"\"\" Returns batchs of images which are augmented and resized. \"\"\"\n def __init__(self, x, y, valid):\n assert(x.shape[0] == y.shape[0])\n self.x = x\n self.y = y\n self.valid = valid\n self.preprocessing_fn = get_preprocessing('resnet50')\n\n SZ = image_size\n\n self.augs = albu.Compose([\n # albu.OneOf([albu.RandomSizedCrop(min_max_height=(SZ//2, SZ), height=SZ, width=SZ, p=0.5),\n # albu.PadIfNeeded(min_height=SZ, min_width=SZ, p=0.5)], p=1),\n # albu.VerticalFlip(p=0.5),\n # albu.HorizontalFlip(p=0.5),\n # albu.RandomRotate90(p=0.5),\n albu.Rotate(p=0.5, limit=10),\n albu.OneOf([\n albu.ElasticTransform(p=0.5, alpha=120, sigma=120 * 0.05, alpha_affine=120 * 0.03),\n albu.GridDistortion(p=0.5),\n albu.OpticalDistortion(p=1, distort_limit=2, shift_limit=0.5)\n ], p=0.8),\n # albu.CLAHE(p=0.8),\n # albu.RandomContrast(p=0.8),\n albu.RandomBrightness(p=0.8),\n albu.RandomGamma(p=0.8)])\n\n print(\"created Datagen: x\", x.shape, \"y\", y.shape)\n\n def __getitem__(self, idx):\n assert(idx < len(self))\n\n x = self.x[idx * BATCH_SIZE : (idx + 1) * BATCH_SIZE]\n y = self.y[idx * BATCH_SIZE : (idx + 1) * BATCH_SIZE]\n\n if not self.valid:\n xa = []\n for image in x :\n augmented = self.augs(image=image)\n xa.append(augmented[\"image\"].reshape(image_size, image_size, 1))\n\n x = np.array(xa).reshape(-1, image_size, image_size, 1)\n\n x = add_depth_coord(x)\n return self.preprocessing_fn(x), y\n\n def __len__(self):\n return int(np.ceil(self.x.shape[0] / BATCH_SIZE))\n\nfolds = StratifiedKFold(NUM_FOLDS, shuffle=True, random_state=666)\n\nfor fold, indices in enumerate(folds.split(x_train, train_df.coverage_class)):\n print(\"==================== fold %d\" % fold)\n train_idx, valid_idx = indices\n x_tr, y_tr = x_train[train_idx], y_train[train_idx]\n x_val, y_val = x_train[valid_idx], y_train[valid_idx]\n\n\n #Data augmentation\n x_tr = np.append(x_tr, [np.fliplr(x) for x in x_tr], axis=0)\n y_tr = get_class(np.append(y_tr, [np.fliplr(x) for x in y_tr], axis=0)).flatten()\n y_val = get_class(y_val).flatten()\n\n resnet_model = ResNet50(input_shape=(image_size, image_size, 3), weights='imagenet', include_top=False)\n input_x = resnet_model.input\n output_layer = Flatten()(resnet_model.output)\n output_layer = Dense(1, activation='sigmoid')(output_layer)\n model = Model(input_x, output_layer)\n learning_rate = 0.001\n c = optimizers.adam(lr = learning_rate)\n model.compile(optimizer=c, loss='binary_crossentropy', metrics=['accuracy'])\n\n\n save_model_name = '../output/resnet50_class_v%d_fold%d_acc{val_acc:.02f}_epoch{epoch:02d}.model' % (VERSION, fold)\n early_stopping = EarlyStopping(monitor='val_acc', mode = 'max', patience=10, verbose=1)\n model_checkpoint = ModelCheckpoint(save_model_name, monitor='val_acc',\n mode = 'max', save_best_only=True, verbose=1)\n reduce_lr = ReduceLROnPlateau(monitor='val_acc', mode = 'max', factor=0.5, patience=5, min_lr=0.0001, verbose=1)\n\n epochs = 400\n batch_size = 32\n cw = compute_class_weight(\"balanced\", np.unique(y_tr), y_tr)\n print(\"class_weight: \", cw)\n history = model.fit_generator(Datagen(x_tr, y_tr, valid=False),\n validation_data=Datagen(x_val, y_val, valid=True),\n epochs=epochs, callbacks=[early_stopping, model_checkpoint, reduce_lr],\n use_multiprocessing=True, workers=12,\n shuffle=False, verbose=1,\n class_weight=cw)\n\n# classes_df = pd.DataFrame(index=test_df.index)\n# classes_df['class'] = model.predict(preprocess_input(add_depth_coord(x_test)))\n# test_df.to_csv(f'../output/resnet50_class_v{VERSION}.csv', index=True)\n","sub_path":"code_artyom/resnet50_classifier_01.py","file_name":"resnet50_classifier_01.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"333989717","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=C,R,W\nfrom collections import defaultdict\n\nfrom flask import g\nfrom flask_appbuilder.security.sqla import models as ab_models\n\nfrom superset import db\n\n\ndef bootstrap_user_data(username=None, include_perms=False):\n if not username:\n username = g.user.username\n\n user = (\n db.session.query(ab_models.User)\n .filter_by(username=username)\n .one()\n )\n\n payload = {\n 'username': user.username,\n 'firstName': user.first_name,\n 'lastName': user.last_name,\n 'userId': user.id,\n 'isActive': user.is_active,\n 'createdOn': user.created_on.isoformat(),\n 'email': user.email,\n }\n\n if include_perms:\n roles, permissions = get_permissions(user)\n payload['roles'] = roles\n payload['permissions'] = permissions\n\n return payload\n\n\ndef get_permissions(user):\n if not user.roles:\n raise AttributeError('User object does not have roles')\n\n roles = {}\n permissions = defaultdict(set)\n for role in user.roles:\n perms = set()\n for perm in role.permissions:\n if perm.permission and perm.view_menu:\n perms.add(\n (perm.permission.name, perm.view_menu.name),\n )\n if perm.permission.name in ('datasource_access',\n 'database_access'):\n permissions[perm.permission.name].add(perm.view_menu.name)\n roles[role.name] = [\n [perm.permission.name, perm.view_menu.name]\n for perm in role.permissions\n if perm.permission and perm.view_menu\n ]\n\n return roles, permissions\n","sub_path":"superset/views/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"275473264","text":"# erdo version 0.12\n# developed by Joe Goldfrank and last modified on 21 Jan\n#\n#the wizard can make anything happen\n#(Howard and Abbas, Foundations of Decision Analysis, Figure 9.3)\n\n# from __future__ import print_function, division\nfrom copy import deepcopy, copy\nfrom graphviz import Digraph\nimport numpy as np\n\n#float to string\ndef shorten(x):\n return str(round(x, 3))\n\n# default risk-neutral value function\ndef risk_neutral(x):\n return(x)\n\n#alternative function for testing only\ndef risk_double(x):\n return 2*x\n\n#uncertainty node\nclass Uncertainty_node:\n def __init__(self, name='Uncertainty Node', children=[], verbose=False):\n self.u = 0\n self.val = 0\n self.name = name\n self.children = deepcopy(children)\n self.verbose = verbose\n self.cycled = 0\n self.is_test = False\n self.testval = None\n\n def clone(self, condition = ' copy', cost=0):\n node = Uncertainty_node(name=self.name + condition)\n for c in self.children:\n node.children.append([c[0].clone(condition = condition, cost=cost),c[1]])\n return node\n\n def child(self, other_node, prob):\n self.children.append([other_node,prob])\n\n\n def utility(self):\n self.u = 0\n self.check = 0\n for i in range(len(self.children)):\n self.check += self.children[i][1]\n if self.check != 1:\n if self.verbose == True:\n print('Uncertainty node \\'' + self.name + '\\' probabilities do not sum to one, normalizing')\n for i in range(len(self.children)):\n if self.check != 0:\n self.children[i][1] = self.children[i][1] / self.check\n if self.check == 0:\n self.children[i][1] = 0\n for i in range(len(self.children)):\n self.u += self.children[i][0].utility() * self.children[i][1]\n return self.u\n\n def node(self):\n return 'uncertainty'\n\n def value(self):\n self.val = 0\n self.check = 0\n for i in range(len(self.children)):\n self.check += self.children[i][1]\n if self.check != 1:\n if self.verbose == True: print('Uncertainty node \\'' + self.name + '\\' probabilities do not sum to one, normalizing')\n for i in range(len(self.children)):\n self.children[i][1] = self.children[i][1] / self.check\n for i in range(len(self.children)):\n self.val += self.children[i][0].value() * self.children[i][1]\n return self.val\n\n def label(self):\n self.utility()\n if self.is_test == True:\n return (self.name + '\\n Expected Utility: ' + shorten(self.u) + '\\n Test Value: ' + shorten(self.testval))\n else: return (self.name + '\\n Expected Utility: ' + shorten(self.u))\n\n#decision node\nclass Decision_node:\n def __init__(self, name='Decision Node', children=[]):\n self.val = 0\n self.u = 0\n self.name = name\n self.decision = None\n self.children = deepcopy(children)\n self.is_test = False\n self.is_control = False\n self.testval = None\n self.cost = None\n\n def clone(self, condition=' copy', cost=0):\n node = Decision_node(name=self.name + condition, children=[])\n for c in self.children:\n node.children.append(c.clone(condition=condition, cost=cost))\n return node\n\n def child(self, other_node):\n self.children.append(other_node)\n\n def value(self):\n self.best = 0\n for i in range(len(self.children)):\n if self.children[i].value() >= self.children[0].value(): self.best = i\n self.val = self.children[self.best].value()\n return self.children[self.best].value()\n\n def utility(self):\n self.best = 0\n for i in range(len(self.children)):\n if self.children[i].utility() >= self.children[0].utility(): self.best = i\n self.u = self.children[self.best].utility()\n self.decision = self.children[self.best].name\n return self.children[self.best].utility()\n\n def node(self):\n return 'decision'\n\n def label(self):\n if self.is_test == True: return (self.name + '\\n Decision: ' + str(self.decision) + '\\n Expected Utility: ' + shorten(self.u) + '\\n Test Value: ' + shorten(self.testval) + '\\n Test Cost: ' + shorten(self.cost))\n if self.is_control == True: return (self.name + '\\n Decision: ' + str(self.decision) + '\\n Expected Utility: ' + shorten(self.u) + '\\n Control Value: ' + shorten(self.testval) + '\\n Control Cost: ' + shorten(self.cost))\n return (self.name + '\\n Decision: ' + str(self.decision) + '\\n Expected Utility: ' + shorten(self.u))\n\n#value node\nclass Value_node:\n def __init__(self, val, u=risk_neutral, name='Value Node'):\n if not isinstance(val, (int, float)): raise TypeError('Value node: \\'val\\' expected an int or float')\n if not callable(u): raise TypeError('Value node: \\'u\\' expected a function')\n self.val = val\n self.ufunc = u\n self.u = u(val)\n self.name = name\n def utility(self): return self.u\n def value(self): return self.val\n def node(self): return 'value'\n def label(self):\n return (self.name + '\\n Utility: ' + shorten(self.u))\n def clone(self, condition = ' copy', cost=0):\n node = Value_node(self.val-cost, name=self.name + condition, u=self.ufunc)\n return node\n\ndef add_to_graph(graph, node):\n #check current node type and set shape\n current_node = node\n if current_node.node() == 'decision': graph.attr('node', shape='box')\n if current_node.node() == 'uncertainty': graph.attr('node', shape='ellipse')\n if current_node.node() == 'value': graph.attr('node', shape='octagon')\n #graph.attr('node', shape='underline')\n graph.node(current_node.name, label=current_node.label())\n if current_node.node() == 'value':\n return\n if len(current_node.children) > 0:\n for i in range(len(current_node.children)):\n if current_node.node() == 'uncertainty':\n add_to_graph(graph, current_node.children[i][0])\n graph.edge(current_node.name, current_node.children[i][0].name, label=shorten(current_node.children[i][1]))\n else:\n add_to_graph(graph, current_node.children[i])\n graph.edge(current_node.name, current_node.children[i].name, label='')\n return\n\ndef create_graph(top_node, filename='decision_tree'):\n top_node.utility()\n current_node = top_node\n g = Digraph('Decision Tree', filename=filename)\n g.attr(rankdir='LR', size='8,5')\n add_to_graph(g, top_node)\n g.view()\n\ndef wave_wand(current, node):\n if current.node() == 'uncertainty':\n for c in current.children:\n if c[0].name[0:len(node)] == node:\n for c in current.children:\n if c[0].name[0:len(node)] == node: c[1] = 1\n else: c[1] = 0\n return\n else: wave_wand(c[0], node)\n return\n if current.node() == 'decision':\n for c in current.children:\n wave_wand(c, node)\n return\n if current.node() == 'value': return\n\ndef summon_the_wizard(target_graph, target_node, wizard_name='Summon The Wizard', paythewizard=0, condition='Wizard'):\n #the wizard can make *anything* happen\n new = []\n new.append(target_graph.clone(condition = \" | \" + condition))\n new.append(target_graph.clone(condition = \" | No \" + condition))\n if isinstance(target_node, str):\n wave_wand(new[0], target_node)\n wizard = Decision_node(name=str(wizard_name) + '?')\n wizard.child(new[0])\n wizard.child(new[1])\n wizard.is_control = True\n wizard.cost = paythewizard\n wizard.testval = (new[0].utility()-new[1].utility())\n return wizard\n if isintance(target_node, (tuple, list)):\n for t in target_node:\n wave_wand(new[0], t)\n wizard = Decision_node(name=str(wizard_name) + '?')\n wizard.is_control = True\n wizard.cost = paythewizard\n wizard.testval = (new[0].utility()-new[1].utility())\n wizard.child(new[0])\n wizard.child(new[1])\n return wizard\n\ndef add_control(target_graph, target_node, name='Control', cost=0, condition='Control'):\n return summon_the_wizard(target_graph, target_node, wizard_name=name, paythewizard=cost, condition=condition)\n\ndef uncertainty_check(e, unc):\n e = e\n found = 0\n if e.node() == 'decision':\n #print('d - checking ' + str(e.name))\n for c in e.children:\n if c.name[0:len(unc)] == unc:\n #print('found ' + c.name[0:len(unc)])\n found = 1\n if len(c.children) != 2: raise AttributeError('Uncertainty to be tested must only have two possibilities')\n else:\n negstring = \" | \\\"\" + (c.children[0][0].name.split('|')[0]) + \"\\\"\"\n posstring = \" | \\\"\" + (c.children[1][0].name.split('|')[0]) + \"\\\"\"\n negprob = c.children[0][1]\n posprob = c.children[1][1]\n return [negstring, posstring, negprob, posprob]\n #for c in e.children:\n temp = uncertainty_check(c, unc)\n if temp != False:\n return temp\n elif e.node() == 'uncertainty':\n #print('u - checking ' + str(e.name))\n for c in e.children:\n if c[0].name[0:len(unc)] == unc:\n #print('found ' + c[0].name[0:len(unc)])\n found = 1\n if len(c[0].children) != 2: raise AttributeError('Uncertainty to be tested must only have two possibilities')\n else:\n negstring = \" | \\\"\" + (c[0].children[0][0].name.split('|')[0]) + \"\\\"\"\n posstring = \" | \\\"\" + (c[0].children[1][0].name.split('|')[0]) + \"\\\"\"\n negprob = c[0].children[0][1]\n posprob = c[0].children[1][1]\n return [negstring, posstring, negprob, posprob]\n if found == 0:\n #print ('not found ' + str(e.name))\n for c in e.children:\n #print(c[0].name)\n temp = uncertainty_check(c[0], unc)\n if temp != False:\n return temp\n elif e.node() == 'value':\n #print('Value node ' + str(e.name))\n return False\n return False\n\ndef uncertainty_check_multi(e, unc):\n e = e\n found = 0\n if e.node() == 'decision':\n #print('d - checking ' + str(e.name))\n for c in e.children:\n if c.name[0:len(unc)] == unc:\n #print('found ' + c.name[0:len(unc)])\n found = 1\n probs = []\n for i in range(len(c[0].children)):\n probs.append(c[0].childrenb[i][1])\n return probs\n temp = uncertainty_check_multi(c, unc)\n if temp != False:\n return temp\n elif e.node() == 'uncertainty':\n #print('u - checking ' + str(e.name))\n for c in e.children:\n if c[0].name[0:len(unc)] == unc:\n #print('found ' + c[0].name[0:len(unc)])\n found = 1\n probs = []\n for i in range(len(c[0].children)):\n probs.append(c[0].children[i][1])\n return probs\n if found == 0:\n #print ('not found ' + str(e.name))\n for c in e.children:\n #print(c[0].name)\n temp = uncertainty_check_multi(c[0], unc)\n if temp != False:\n return temp\n elif e.node() == 'value':\n #print('Value node ' + str(e.name))\n return False\n return False\n\n\ndef uncertainty_mod(e, unc, neg, pos):\n found = 0\n if e.node() == 'decision':\n #print('d - checking ' + str(e.name))\n for c in e.children:\n if c.name[0:len(unc)] == unc:\n #print('found ' + c.name[0:len(unc)])\n found = 1\n if len(c.children) != 2: raise AttributeError('Uncertainty to be tested must only have two possibilities')\n else:\n #print('doing it')\n #print('before: ' +str(c.children[0][1]))\n c.children[0][1] = neg\n c.children[1][1] = pos\n #print('after: ' +str(c.children[0][1]))\n return True\n temp = uncertainty_mod(c, unc, pos, neg)\n if temp != False:return temp\n elif e.node() == 'uncertainty':\n #print('u - checking ' + str(e.name))\n for c in e.children:\n if c[0].name[0:len(unc)] == unc:\n #print('found! ' + c[0].name[0:len(unc)])\n found = 1\n if len(c[0].children) != 2: raise AttributeError('Uncertainty to be tested must only have two possibilities')\n else:\n #print('doing it')\n #print('before: ' +str(c[0].children[0][1]))\n c[0].children[0][1] = neg\n c[0].children[1][1] = pos\n #print('after: ' +str(c[0].children[0][1]))\n return True\n if found == 0:\n #print ('not found ' + str(e.name))\n for c in e.children:\n ##print(c[0].name)\n temp = uncertainty_mod(c[0], unc, neg, pos)\n if temp != False: return temp\n elif e.node() == 'value':\n #print('Value node ' + str(e.name))\n return False\n return False\n\ndef uncertainty_mod_multi(e, unc, likely):\n found = 0\n if e.node() == 'decision':\n #print('d - checking ' + str(e.name))\n for c in e.children:\n if c.name[0:len(unc)] == unc:\n #print('found ' + c.name[0:len(unc)])\n found = 1\n for i in range(likely):\n c.children[i][1] = likely[i]\n return True\n temp = uncertainty_mod_multi(c, unc, likely)\n if temp != False:return temp\n elif e.node() == 'uncertainty':\n #print('u - checking ' + str(e.name))\n for c in e.children:\n if c[0].name[0:len(unc)] == unc:\n found = 1\n for i in range(len(likely)):\n c[0].children[i][1] = likely[i]\n return True\n if found == 0:\n #print ('not found ' + str(e.name))\n for c in e.children:\n ##print(c[0].name)\n temp = uncertainty_mod_multi(c[0], unc, likely)\n if temp != False: return temp\n elif e.node() == 'value':\n #print('Value node ' + str(e.name))\n return False\n return False\n#uncertainty must be one or two levels below the decision\ndef add_test(decision, uncertainty, truepos=1, trueneg=1, testname='Test', cost=0):\n posstring = ''\n negstring = ''\n\n if isinstance(uncertainty, str):\n temp = uncertainty_check(decision, uncertainty)\n if temp != False: negstring, posstring, negprob, posprob = temp\n else:\n #print(temp)\n raise AttributeError('Uncertainty node does not exist within specified decision')\n\n # compute marginal probabilities for test\n # format: test_reality\n pos_pos = posprob * truepos\n neg_pos = posprob * (1-truepos)\n neg_neg = negprob * trueneg\n pos_neg = negprob * (1-trueneg)\n\n #bayesian inference\n if (pos_pos + pos_neg) == 0:\n pos_postest, neg_postest = 0,0\n else:\n pos_postest = pos_pos / (pos_pos + pos_neg)\n neg_postest = pos_neg / (pos_pos + pos_neg)\n if (neg_pos + neg_neg) == 0:\n pos_negest, neg_negtest = 0,0\n else:\n pos_negtest = neg_pos / (neg_pos + neg_neg)\n neg_negtest = neg_neg / (neg_pos + neg_neg)\n prob_postest = (pos_pos + pos_neg) / (pos_pos + neg_pos + neg_neg + pos_neg)\n prob_negtest = (neg_pos + neg_neg) / (pos_pos + neg_pos + neg_neg + pos_neg)\n\n new = []\n new.append(decision.clone(condition = negstring))\n new.append(decision.clone(condition = posstring))\n new.append(decision.clone(condition = ' | No Test'))\n #print('--making modifications--')\n\n '''for c in new[0].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_negtest\n c.children[1][1] = pos_negtest'''\n uncertainty_mod(new[0], uncertainty, neg_negtest, pos_negtest)\n uncertainty_mod(new[1], uncertainty, neg_postest, pos_postest)\n #print(new[0].children[1].children[1][0].children[0][1])\n '''for c in new[1].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_postest\n c.children[1][1] = pos_postest'''\n\n new_uncertain = Uncertainty_node(name=testname, children=[[new[0], prob_negtest],[new[1], prob_postest]])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[2]])\n\n if new_uncertain.utility() - new[2].utility() > 0: test_value = new_uncertain.utility() - new[2].utility()\n else: test_value = 0\n new[0] = (decision.clone(condition = negstring, cost=cost))\n new[1] = (decision.clone(condition = posstring, cost=cost))\n '''for c in new[0].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_negtest\n c.children[1][1] = pos_negtest\n\n for c in new[1].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_postest\n c.children[1][1] = pos_postest'''\n uncertainty_mod(new[0], uncertainty, neg_negtest, pos_negtest)\n uncertainty_mod(new[1], uncertainty, neg_postest, pos_postest)\n new_uncertain = Uncertainty_node(name=testname, children=[[new[0], prob_negtest],[new[1], prob_postest]])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[2]])\n test_decision.is_test = True\n test_decision.testval = test_value\n test_decision.cost = cost\n return test_decision\n elif isinstance(uncertainty, (list, tuple)):\n temp = uncertainty_check(decision, uncertainty[0])\n if temp != False: negstring, posstring, negprob, posprob = temp\n else:\n #print(temp)\n raise AttributeError('Uncertainty node does not exist within specified decision')\n\n # compute marginal probabilities for test\n # format: test_reality\n pos_pos = posprob * truepos\n neg_pos = posprob * (1-truepos)\n neg_neg = negprob * trueneg\n pos_neg = negprob * (1-trueneg)\n\n #bayesian inference\n if (pos_pos + pos_neg) == 0:\n pos_postest, neg_postest = 0,0\n else:\n pos_postest = pos_pos / (pos_pos + pos_neg)\n neg_postest = pos_neg / (pos_pos + pos_neg)\n if (neg_pos + neg_neg) == 0:\n pos_negest, neg_negtest = 0,0\n else:\n pos_negtest = neg_pos / (neg_pos + neg_neg)\n neg_negtest = neg_neg / (neg_pos + neg_neg)\n prob_postest = (pos_pos + pos_neg) / (pos_pos + neg_pos + neg_neg + pos_neg)\n prob_negtest = (neg_pos + neg_neg) / (pos_pos + neg_pos + neg_neg + pos_neg)\n\n new = []\n new.append(decision.clone(condition = negstring))\n new.append(decision.clone(condition = posstring))\n new.append(decision.clone(condition = ' | No Test'))\n #print('--making modifications--')\n\n '''for c in new[0].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_negtest\n c.children[1][1] = pos_negtest'''\n for u in uncertainty:\n uncertainty_mod(new[0], u, neg_negtest, pos_negtest)\n uncertainty_mod(new[1], u, neg_postest, pos_postest)\n #print(new[0].children[1].children[1][0].children[0][1])\n '''for c in new[1].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_postest\n c.children[1][1] = pos_postest'''\n\n new_uncertain = Uncertainty_node(name=testname, children=[[new[0], prob_negtest],[new[1], prob_postest]])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[2]])\n\n if new_uncertain.utility() - new[2].utility() > 0: test_value = new_uncertain.utility() - new[2].utility()\n else: test_value = 0\n new[0] = (decision.clone(condition = negstring, cost=cost))\n new[1] = (decision.clone(condition = posstring, cost=cost))\n '''for c in new[0].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_negtest\n c.children[1][1] = pos_negtest\n\n for c in new[1].children:\n if c.name[0:len(uncertainty)] == uncertainty:\n c.children[0][1] = neg_postest\n c.children[1][1] = pos_postest'''\n for u in uncertainty:\n uncertainty_mod(new[0], u, neg_negtest, pos_negtest)\n uncertainty_mod(new[1], u, neg_postest, pos_postest)\n new_uncertain = Uncertainty_node(name=testname, children=[[new[0], prob_negtest],[new[1], prob_postest]])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[2]])\n test_decision.is_test = True\n test_decision.testval = test_value\n test_decision.cost = cost\n return test_decision\n\n# temporarily require a list/tuple of strings, even if only one element\n# testbehavior format [['0', '1', '2'], ['0', '1', '2'], ['0', '1', '2']] for distinctions 0, 1, 2\n# e.g. testbehavior[i][j] = p(\"j\" | i)\n# distinctions format is list of names, e.g. ['0name', '1name', '2name']\n#\ndef add_multi_test(decision, uncertainty, testbehavior, distinctions, testname='Test', cost=0):\n if isinstance(uncertainty, (list, tuple)):\n #temp = uncertainty_check(decision, uncertainty[0])\n #if temp != False: negstring, posstring, negprob, posprob = temp\n #else:\n #print(temp)\n # raise AttributeError('Uncertainty node does not exist within specified decision')\n\n # compute marginal probabilities for test\n # marginals is array of marginals e.g. marginals[i][j] = p(i)*p(\"j\" | i)\n # testbehavior - probability of indicating j given i\n probs = uncertainty_check_multi(decision, uncertainty[0])\n marginals = np.zeros((len(testbehavior),len(testbehavior)))\n for i in range(len(testbehavior)):\n for j in range(len(testbehavior[i])):\n marginals[i][j] = probs[i]*testbehavior[i][j]\n\n #print(marginals)\n\n #bayesian inference\n #likelihoods - probability of i given indicating j\n #likelihoods[i][j] = p(i | \"j\")\n marginal_sums = np.zeros(len(marginals))\n for i in range(len(marginals)):\n for j in range(len(marginals)):\n marginal_sums[j] += marginals[i][j]\n\n likelihoods = np.zeros((len(testbehavior),len(testbehavior)))\n for i in range(len(testbehavior)):\n for j in range(len(testbehavior)):\n likelihoods[i][j] = marginals[i][j]/marginal_sums[j]\n\n print(likelihoods)\n\n\n new = []\n for i in range(len(likelihoods)):\n new.append(decision.clone(condition = \" | \\\"\" + distinctions[i] + \"\\\"\") )\n likely = []\n for j in range(len(likelihoods)):\n likely.append(likelihoods[j][i])\n for u in uncertainty:\n uncertainty_mod_multi(new[i], u, likely)\n new.append(decision.clone(condition = 'No Test'))\n\n new_uncertain = Uncertainty_node(name=testname)\n for i in range(len(new)-1):\n new_uncertain.child(new[i],marginal_sums[i])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[-1]])\n\n if new_uncertain.utility() - new[-1].utility() > 0: test_value = new_uncertain.utility() - new[-1].utility()\n else: test_value = 0\n\n '''new[0] = (decision.clone(condition = negstring, cost=cost))\n new[1] = (decision.clone(condition = posstring, cost=cost))\n for u in uncertainty:\n uncertainty_mod(new[0], u, neg_negtest, pos_negtest)\n uncertainty_mod(new[1], u, neg_postest, pos_postest)\n new_uncertain = Uncertainty_node(name=testname, children=[[new[0], prob_negtest],[new[1], prob_postest]])\n test_decision = Decision_node(name=\"Test Decision\", children=[new_uncertain, new[2]])'''\n test_decision.is_test = True\n test_decision.testval = test_value\n test_decision.cost = cost\n return test_decision\n\n#test case\n#party problem from Howard and Abbas\n#with examples of control and testing\n'''from erdo import *\n\nsun_o = Value_node(1, name='Sunshine | Outdoors')\nrain_o = Value_node(0, name='Rain | Outdoors')\noutdoors = Uncertainty_node(name='Outdoors')\noutdoors.child(sun_o, .4)\noutdoors.child(rain_o, .6)\nsun_p = Value_node(.95, name='Sunshine | Porch')\nrain_p = Value_node(.32, name='Rain | Porch')\nporch = Uncertainty_node(name='Porch')\nporch.child(sun_p, .4)\nporch.child(rain_p, .6)\nsun_i = Value_node(.57, name='Sunshine | Indoors')\nrain_i = Value_node(.67, name='Rain | Indoors')\nindoors = Uncertainty_node(name='Indoors')\nindoors.child(sun_i, .4)\nindoors.child(rain_i, .6)\nparty = Decision_node(name='Party Location?')\nparty.child(outdoors)\nparty.child(porch)\nparty.child(indoors)\n#test = add_test(party, ('Outdoors','Porch','Indoors'), trueneg = .9, truepos = .9, cost=.05)\nwizard = summon_the_wizard(party, 'Rain')\ncreate_graph(wizard,filename='party_problem')\n#create_graph(party, filename='party')\n'''\n","sub_path":"erdo.py","file_name":"erdo.py","file_ext":"py","file_size_in_byte":25947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"504796658","text":"\n\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n left = {}\n right = {}\n res = -1\n for i, c in enumerate(s):\n if c not in left:\n left[c] = i\n else:\n right[c] = i\n res = max(res, right[c] - left[c]-1)\n return res\n\n\n\ns = \"aa\"\nres = Solution().maxLengthBetweenEqualCharacters(s)\nprint(res)","sub_path":"string/1624_largest_substring_between_two_equal_characters/1624_largest_substring_between_two_equal_characters.py","file_name":"1624_largest_substring_between_two_equal_characters.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"562717321","text":"from __future__ import print_function\r\nimport sys\r\nimport os\r\nimport datetime\r\nimport random\r\nimport xlsxwriter\r\n\r\ndef main(filename):\r\n Time_list = []\r\n with open(filename, \"r\") as f:\r\n Time_list = f.readlines()\r\n\r\n f.close()\r\n\r\n\r\n late_list = []\r\n now = datetime.datetime.now()\r\n day = datetime.timedelta(days=-2) #往前推2天\r\n start = now + day\r\n \r\n for Time in Time_list:\r\n time = datetime.datetime.strptime(Time.strip(), \"%d/%m/%Y %H:%M:%S\")\r\n if time>= start and time <= now:\r\n late_list.append(time)\r\n\r\n\r\n workbook = xlsxwriter.Workbook(filename.rstrip(\".txt\") + \"-late1000.xlsx\")\r\n worksheet = workbook.add_worksheet()\r\n worksheet.set_column(\"A:A\", len(Time_list[0]))\r\n\r\n late_list.sort()\r\n for i in range(1000):\r\n worksheet.write(\"A\"+str(i+1), late_list[-(i+1)].strftime(\"%d/%m/%Y %H:%M:%S\"))\r\n\r\n workbook.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) != 2:\r\n print(\"Bad input, argument number must be one filename\\n\")\r\n exit()\r\n elif os.path.exists(sys.argv[1]) == False:\r\n print(\"Bad input, no such file\\n\")\r\n exit()\r\n starttime = datetime.datetime.now()\r\n main(sys.argv[1])\r\n endtime = datetime.datetime.now()\r\n print(\"runtime:\", (endtime - starttime).seconds)\r\n","sub_path":"Solution_500_v3.py","file_name":"Solution_500_v3.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"36715073","text":"# task1.3\nfrom pyamg.gallery.diffusion import diffusion_stencil_2d\nfrom pyamg.gallery import stencil_grid\nsten = diffusion_stencil_2d(type='FD', \\\n epsilon=0.001, theta=3.1416/3.0)\nA = stencil_grid(sten, (100,100), format='csr')\n\n# task1.4\nfrom pyamg import *\nml = smoothed_aggregation_solver(A)\nprint(ml)\nprint(ml.levels[0].A.shape)\n# Use up-arrow to edit previous command\nprint(ml.levels[0].P.shape) \nprint(ml.levels[0].R.shape)\n","sub_path":"archive/copper_2012_workshop/task1.4.py","file_name":"task1.4.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"22225798","text":"from django import forms\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_summernote.widgets import SummernoteWidget\n\nfrom .models import SupportingDocument, TalkProposal, TutorialProposal\n\n\nclass ProposalForm(forms.ModelForm):\n\n def clean_description(self):\n value = self.cleaned_data[\"description\"]\n if len(value) > 400:\n raise forms.ValidationError(\n u\"De samenvatting mag maximaal 400 karakters zijn\"\n )\n return value\n\n\nclass TalkProposalForm(ProposalForm):\n\n class Meta:\n model = TalkProposal\n fields = [\n \"title\",\n \"audience_level\",\n \"description\",\n \"abstract\",\n \"additional_notes\",\n \"akkoordverklaring\",\n ]\n widgets = {\n 'abstract': SummernoteWidget(attrs={'width': '100%', 'height': '300px'}),\n \"additional_notes\": SummernoteWidget(attrs={'width': '100%', 'height': '300px'}),\n }\n\n def __init__(self, *args, **kwargs):\n super(TalkProposalForm, self).__init__(*args, **kwargs)\n self.fields[\"akkoordverklaring\"].required = True\n\n\nclass TutorialProposalForm(ProposalForm):\n\n class Meta:\n model = TutorialProposal\n fields = [\n \"title\",\n \"audience_level\",\n \"description\",\n \"abstract\",\n \"additional_notes\",\n \"akkoordverklaring\",\n ]\n widgets = {\n \"abstract\": SummernoteWidget(attrs={'width': '100%', 'height': '300px'}),\n \"additional_notes\": SummernoteWidget(attrs={'width': '100%', 'height': '300px'}),\n }\n\n def __init__(self, *args, **kwargs):\n super(TutorialProposalForm, self).__init__(*args, **kwargs)\n self.fields[\"akkoordverklaring\"].required = True\n\n\n# @@@ generic proposal form\n\n\nclass AddSpeakerForm(forms.Form):\n\n email = forms.EmailField(\n label=_(\"Email\")\n )\n\n def __init__(self, *args, **kwargs):\n self.proposal = kwargs.pop(\"proposal\")\n super(AddSpeakerForm, self).__init__(*args, **kwargs)\n\n def clean_email(self):\n value = self.cleaned_data[\"email\"]\n exists = self.proposal.additional_speakers.filter(\n Q(user=None, invite_email=value) |\n Q(user__email=value)\n ).exists()\n if exists:\n raise forms.ValidationError(\"Deze email is al uitgenodigd.\")\n return value\n\n\nclass SupportingDocumentCreateForm(forms.ModelForm):\n\n class Meta:\n model = SupportingDocument\n fields = [\n \"file\",\n \"description\",\n ]\n","sub_path":"src/proposals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"265386556","text":"import sys\nimport numpy as np\n\nimport theano\nimport theano.tensor as T\nfrom updates import Adagrad\nfrom tqdm import tqdm\nfrom rng import t_rng, np_rng\nfrom theano_utils import floatX, sharedX\n\n\ndef sqr_dist(x, y, e=1e-8):\n if x.ndim == 2:\n\n xx = T.sqr(T.sqrt((x * x).sum(axis=1) + e))\n yy = T.sqr(T.sqrt((y * y).sum(axis=1) + e))\n dist = T.dot(x, y.T)\n dist *= -2.\n dist += xx.dimshuffle(0, 'x')\n dist += yy.dimshuffle('x', 0)\n\n else:\n raise NotImplementedError\n\n return dist\n\n\ndef median_distance(H, e=1e-6):\n if H.ndim != 2:\n raise NotImplementedError\n\n V = H.flatten()\n # median distance\n h = T.switch(T.eq((V.shape[0] % 2), 0),\n # if even vector\n T.mean(T.sort(V)[((V.shape[0] // 2) - 1): ((V.shape[0] // 2) + 1)]),\n # if odd vector\n T.sort(V)[V.shape[0] // 2])\n\n # h = h / T.log(H.shape[0] + 1).astype(theano.config.floatX)\n return h\n\n\ndef poly_kernel(x, e=1e-8):\n x = x - T.mean(x, axis=0)\n kxy = 1 + T.dot(x, x.T)\n dxkxy = x * x.shape[0].astype(theano.config.floatX)\n\n return kxy, dxkxy\n\n\ndef rbf_kernel(x):\n H = sqr_dist(x, x)\n h = median_distance(H)\n\n kxy = T.exp(-H / h)\n\n dxkxy = -T.dot(kxy, x)\n sumkxy = T.sum(kxy, axis=1).dimshuffle(0, 'x')\n dxkxy = (dxkxy + x * sumkxy) * 2. / h\n\n return kxy, dxkxy\n\n\ndef graphical_rbf_kernel(x, N):\n def graphical_rbf(nbrs_i, i, x): # i_th dimension, neighbors of x_i\n # xn = x * nbrs_i.reshape((1, -1)).astype(theano.config.floatX)\n selected = T.neq(nbrs_i, 0).nonzero()[0]\n new_i = T.eq(selected, i).nonzero()[0]\n\n xn = x[:, selected]\n kxy, dxkxy = rbf_kernel(xn)\n # kxy, dxkxy = poly_kernel(xn)\n return kxy, dxkxy[:, new_i].flatten()\n\n kernel_info, _ = theano.scan(fn=graphical_rbf, outputs_info=None, sequences=[N, T.arange(N.shape[0])],\n non_sequences=[x])\n kxy, dxkxy = kernel_info\n return kxy, dxkxy\n\n\n","sub_path":"struct_grad_free.py","file_name":"struct_grad_free.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"516873038","text":"import discord\r\nfrom random import randint\r\nfrom time import sleep\r\n\r\nclient = discord.Client()\r\n\r\ngame_started = False\r\nnight = False\r\nday = False\r\n\r\nplayers = {1:\"Кек\", 2:\"Сас\", 3:\"Пуп\", 4:\"Лол\"}\r\nmafia = {}\r\ncivil = {}\r\n\r\n\r\ni = 1\r\nchannel = 0\r\n#_______ответ на меседжи________\r\n@client.event\r\nasync def on_message(message):\r\n print(message.content)\r\n global game_started\r\n global i\r\n global night\r\n global day\r\n global channel\r\n guild = message.guild\r\n# ________________Рега_______________________\r\n if message.content.find (\"!join\") != -1 and game_started == False:\r\n print(players)\r\n if len(players) <= 3:\r\n players[1 + len(players)] = str(message.author.name)\r\n await message.channel.send(\"в игре участвуют:\")\r\n await message.channel.send(players)\r\n await message.channel.send (\"для старта необходимо еще: \" + str(5-len(players))+\" игрока\")\r\n elif len(players) <= 4 and game_started == False:\r\n players[1 + len(players)] = str(message.author.name)\r\n await message.channel.send(\"в игре участвуют:\")\r\n await message.channel.send(players)\r\n await message.channel.send(\"Для начала игры введите start\")\r\n game_started = True\r\n print(game_started)\r\n#_______________Игровой цикл_________________\r\n if message.content.find (\"!start\") != -1 and game_started == True:\r\n await message.channel.send(\"Игра начнется через 5 секунд\")\r\n await guild.create_role(name = \"Игрок\")\r\n await guild.create_role(name = \"Игрoк\")\r\n await guild.create_text_channel(\"мафиозники\")\r\n #_______жеребьевка________________________\r\n while i <= len(players):\r\n sidecheck = randint(0, 1)\r\n if sidecheck == 0 and len(mafia) == 0:\r\n mafia[1 + len(mafia)] = players[i]\r\n elif sidecheck == 0 and len(mafia) == 1:\r\n civil[1 + len(civil)] = players[i]\r\n elif sidecheck == 1 and len(mafia) == 0:\r\n mafia[1 + len(mafia)] = players[i]\r\n elif sidecheck == 1:\r\n civil[1 + len(civil)] = players[i]\r\n i = i+1\r\n print(mafia)\r\n print(civil)\r\n #______________________________________\r\n await message.channel.send(\"Чтобы узнать вашу крату введите side\")\r\n sleep(5)\r\n await message.channel.send(\"Наступила ночь, мафиозники выбирают кого завалить\")\r\n if message.content.find (\"Мафия убила \") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n await message.channel.send(\"Наступил день.\")\r\n if message.content.find (\" был мирным!\") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n await message.channel.send(\"Наступила ночь, мафиозники выбирают кого завалить\")\r\n\r\n\r\n\r\n#___________________________________голосование мафии_____________________________\r\n if message.content.find(\"Наступила ночь, мафиозники выбирают кого завалить\") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n night = True\r\n channel = discord.utils.get(guild.channels, name=\"мафиозники\")\r\n await channel.send (\"Чтобы убить игрока напишите shoot # с номером нужного игрока\")\r\n await channel.send(players)\r\n if message.content.find(\"!shoot 1\") != -1 and message.channel == channel and night == True:\r\n channel = discord.utils.get(guild.channels, name=\"general\")\r\n await channel.send(\"Мафия убила \" + players[1])\r\n del players[1]\r\n night = False\r\n if message.content.find(\"!shoot 2\") != -1 and message.channel == channel and night == True:\r\n channel = discord.utils.get(guild.channels, name=\"general\")\r\n await channel.send(\"Мафия убила \" + players[2])\r\n del players[2]\r\n night = False\r\n if message.content.find(\"!shoot 3\") != -1 and message.channel == channel and night == True:\r\n channel = discord.utils.get(guild.channels, name=\"general\")\r\n await channel.send(\"Мафия убила \" + players[3])\r\n del players[3]\r\n night = False\r\n if message.content.find(\"!shoot 4\") != -1 and message.channel == channel and night == True:\r\n channel = discord.utils.get(guild.channels, name=\"general\")\r\n await channel.send(\"Мафия убила \" + players[4])\r\n del players[4]\r\n night = False\r\n if message.content.find(\"!shoot 5\") != -1 and message.channel == channel and night == True:\r\n channel = discord.utils.get(guild.channels, name=\"general\")\r\n await channel.send(\"Мафия убила \" + players[5])\r\n del players[5]\r\n night = False\r\n # ___________________________________голосование мирных_____________________________\r\n if message.content.find (\"Наступил день.\") != -1 and message.author.name == \"Зубенко Михаил Петрович\" and len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n elif message.content.find (\"Наступил день.\") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n day = True\r\n await message.channel.send (\"Чтобы начать голосование напишите vote\")\r\n if message.content.find(\"!vote\") != -1 and day == True:\r\n await channel.send(\"Голосование началось!\")\r\n await channel.send(\"Напишите kill # с номером предполагаемого мафиозника, и я устраню его!\")\r\n await channel.send(players)\r\n if message.content.find(\"!kill 1\") != -1 and day == True:\r\n for position, name in civil.items():\r\n if name == players[1]:\r\n await message.channel.send(str(players[1]) + \" был мирным!\")\r\n del players[1]\r\n day = False\r\n if len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n for position, name in mafia.items():\r\n if name == players[1]:\r\n await message.channel.send(str(players[1]) + \" был мафиозником!\")\r\n await message.channel.send(\"Мирные победили!\")\r\n if message.content.find(\"!kill 2\") != -1 and day == True:\r\n for position, name in civil.items():\r\n if name == players[2]:\r\n await message.channel.send(str(players[2]) + \" был мирным!\")\r\n del players[2]\r\n day = False\r\n if len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n for position, name in mafia.items():\r\n if name == players[2]:\r\n await message.channel.send(str(players[2]) + \" был мафиозником!\")\r\n await message.channel.send(\"Мирные победили!\")\r\n if message.content.find(\"!kill 3\") != -1 and day == True:\r\n for position, name in civil.items():\r\n if name == players[3]:\r\n await message.channel.send(str(players[3]) + \" был мирным!\")\r\n del players[3]\r\n day = False\r\n if len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n for position, name in mafia.items():\r\n if name == players[3]:\r\n await message.channel.send(str(players[3]) + \" был мафиозником!\")\r\n await message.channel.send(\"Мирные победили!\")\r\n if message.content.find(\"!kill 4\") != -1 and day == True:\r\n for position, name in civil.items():\r\n if name == players[4]:\r\n await message.channel.send(str(players[4]) + \" был мирным!\")\r\n del players[4]\r\n day = False\r\n if len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n for position, name in mafia.items():\r\n if name == players[4]:\r\n await message.channel.send(str(players[4]) + \" был мафиозником!\")\r\n await message.channel.send(\"Мирные победили!\")\r\n if message.content.find(\"!kill 5\") != -1 and day == True:\r\n for position, name in civil.items():\r\n if name == players[5]:\r\n await message.channel.send(str(players[5]) + \" был мирным!\")\r\n del players[5]\r\n day = False\r\n if len(players) == 2:\r\n await message.channel.send(\"Мафиозники победили!\")\r\n for position, name in mafia.items():\r\n if name == players[5]:\r\n await message.channel.send(str(players[5]) + \" был мафиозником!\")\r\n await message.channel.send(\"Мирные победили!\")\r\n\r\n#_____________________________Победа______________________________________\r\n if message.content.find(\"Мирные победили!\") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n await message.channel.send(\"Игра окончена!\")\r\n game_started = False\r\n night = False\r\n players.clear()\r\n mafia.clear()\r\n civil.clear()\r\n day = False\r\n i = 1\r\n elif message.content.find(\"Мафиозники победили!\") != -1 and message.author.name == \"Зубенко Михаил Петрович\":\r\n await message.channel.send(\"Игра окончена!\")\r\n game_started = False\r\n night = False\r\n players.clear()\r\n mafia.clear()\r\n civil.clear()\r\n day = False\r\n i = 1\r\n\r\n#_______________Отправка ролей в пм_________________________________\r\n if message.content.find(\"!side\") != -1 and game_started == True:\r\n print(message.author.name)\r\n for position, name in mafia.items():\r\n if name == message.author.name:\r\n await message.author.send(\"Ты мафиозник!\")\r\n role = discord.utils.get(message.guild.roles, name=\"Игрок\")\r\n user = message.author\r\n await user.add_roles(role)\r\n for position, name in civil.items():\r\n if name == message.author.name:\r\n await message.author.send(\"Ты горожанин!\")\r\n role = discord.utils.get(message.guild.roles, name=\"Игрок\")\r\n user = message.author\r\n await user.add_roles(role)\r\n\r\n if message.content.find(\"!help\") != -1:\r\n await message.channel.send(\"\"\"\r\n Список команд (Перед каждой командой необходимо поставить ! знак):\r\n help - список команд\r\n join - присоедениться к игре\r\n start - начать игру (необходимо от 5 человек)\r\n side - узнать свою карту\r\n shoot # - убить игрока под номером # (только в канале мафии)\r\n vote - начать голосование\r\n kill # - убить игрока, которого вы считаете мафией (только в игровом канале)\r\n \"\"\")\r\n\r\n\r\n\r\n\r\n\r\nclient.run(\"NTc4MzE5MzU0NDA0NDA1MjUw.XN_5LA.wANJT2w9AnSNHBDRLOp3CytlbiI\")\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"370724800","text":"from PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\nimport sys\n\nclass MainWindow(QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.setWindowTitle('008_widgets')\n\n widget = QLabel('Hello')\n font = widget.font()\n font.setPointSize(30)\n widget.setFont(font)\n widget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n\n #widgetCbox = QCheckBox()\n #widgetCbox.setChecked(True)\n #Partially checked = neither yes or no\n #widgetCbox.setCheckState(Qt.PartiallyChecked)\n #widgetCbox.stateChanged.connect(self.show_state)\n\n comboBox = QComboBox()\n comboBox.addItems(['One', 'Two', 'Three'])\n comboBox.currentIndexChanged.connect(self.index_changed)\n #sends index to the function\n comboBox.currentIndexChanged[str].connect(self.text_changed)\n #sends text to the function\n\n #QListWidget = similar to combobox except not a drop-down, everything is listed\n\n #QLineEdit\n #textChanged - programmatic change\n #textEdited - user Edit\n\n #def show_state(self, s):\n #print(s)\n #checked = 2, uncheked = 0, partial = 1\n\n\n '''\n layout = QVBoxLayout()\n\n widgets = [QCheckBox,\n QComboBox,\n QDateEdit,\n QDateTimeEdit,\n QDial,\n QDoubleSpinBox,\n QFontComboBox,\n QLCDNumber,\n QLabel,\n QLineEdit,\n QProgressBar,\n QPushButton,\n QRadioButton,\n QSlider,\n QSpinBox,\n QTimeEdit]\n\n for w in widgets:\n layout.addWidget(w() )\n\n widget = QWidget()\n widget.setLayout(layout)\n '''\n\n self.setCentralWidget(comboBox)\n\n #self.show()\n\napp = QApplication([])\n\nwindow = MainWindow()\nwindow.show()\n\nsys.exit(app.exec_())","sub_path":"008_widgets.py","file_name":"008_widgets.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"63592107","text":"import time\nimport pandas as pd\nimport numpy as np\nimport os\n#from collections import Counter\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"path\n \n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!\\nPlease choose the city:')\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = input(\"which city you would like to go for? Chicago,New York City, Washington\\n\")\n city = city.lower()\n while city not in CITY_DATA.keys ():\n city = input(\"Oops, please select the city from the list:\")\n city = city.lower()\n \n FilterRange={\"month\",\"day\",\"none\"}\n Filter = input('Would you like to filter the data by month, day or not at all? Type None for for no time filter:\\n')\n Filter = Filter.lower()\n\n while Filter not in FilterRange:\n Filter = input('Please type month, day or none:')\n Filter = Filter.lower()\n if Filter ==\"month\":\n # TO DO: get user input for month (all, january, february, ... , june)\n day=7;#7=all\n month_range=np.linspace(1,12,12,dtype=np.int) \n #try:\n month = int(input(\"0-all, 1-Jan, 2-Feb, 3-March, 4-April, 5-May, 6-June,7-July, 8-Aug ,9-Sep, 10-Oct , 11-Nov, 12-Dec\\n which month you would like to go for:\"))\n \n while month not in month_range:\n month_range=np.linspace(0,12,13,dtype=np.int) \n month = int(input(\"Oops, please type an interger from 0 to 12:\"))\n \n elif Filter ==\"day\":\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n month=0;#0=all\n day = int(input(\"0-Sunday,1-Monday,2-Tuesday,3-Wednesday,4-Thursday, 5-Friday, 6-Saturday, 7-all \\n which day you would like to go for?\"))\n day_range=np.linspace(0,7,8,dtype=np.int) \n while day not in day_range:\n day = int(input(\"Oops, please type an interger from 0 to 6:\"))\n\n elif Filter ==\"none\":\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n month=0;#0=all\n day=7;#7=all \n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n\n # load data file into a dataframe\n #df = pd.read_csv(CITY_DATA[city])\n filepath=os.path.join(os.path.dirname(__file__))\n filename=CITY_DATA[city]\n df = pd.read_csv(filepath + \"/data/\"+filename)\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.day_name()\n\n # filter by month if applicable\n if month != 0:#0=all\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 7:#7=all\n # filter by day of week to create the new dataframe\n Weekday=[\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\", \"Friday\", \"Saturday\"]\n df = df[df['day_of_week'] == Weekday[day]]\n return df\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n month_counts = df['month'].value_counts()\n months = ['January', 'February', 'March', 'April', 'May', 'June',\"July\",\"August\"]\n common_month_word = months[month_counts.index[0]-1]\n print(\"the most common month is: {}\".format(common_month_word)+\" Count:{}\".format(month_counts.values[0]))\n \n # TO DO: display the most common day of week\n weekday_counts = df['day_of_week'].value_counts()\n print(\"the most common day of week is:{}\".format(weekday_counts.index[0])+\" Count:{}\".format(weekday_counts.values[0]))\n # TO DO: display the most common start hour\n df[\"hour\"] = df['Start Time'].dt.hour\n common_used_value(df,\"hour\") \n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n common_used_value(df,'Start Station') \n \n\n # TO DO: display most commonly used end station\n common_used_value(df,'End Station') \n\n # TO DO: display most frequent combination of start station and end station trip\n top = df.groupby(['Start Station', 'End Station']).size().idxmax() \n print(\"The most frequent combination of start station and end station trip is {} to {}\".format(top[0], top[1]))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time \n # TO DO: display mean travel time\n TotalTravelTime=np.sum(df[\"Trip Duration\"])\n MeanTravelTime=np.mean(df[\"Trip Duration\"]) \n print(\"Total Travel Time:{}\".format(TotalTravelTime)+\"s\")\n print(\"Mean Travel Time:{}\".format(MeanTravelTime)+\"s\")\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n if \"User Type\" in df: \n UserType_counts = df[\"User Type\"].value_counts().dropna(axis = 0)\n print(\"Subscriber number:{}\".format(UserType_counts.get(\"Subscriber\")))\n print(\"Customer number:{}\".format(UserType_counts.get(\"Customer\")))\n\n # TO DO: Display counts of gender\n if \"Gender\" in df:\n \n Gender_counts = df[\"Gender\"].value_counts().dropna(axis = 0)\n print(\"Male number:{}\".format(Gender_counts.get(\"Male\")))\n print(\"Female number:{}\".format(Gender_counts.get(\"Female\"))) \n\n # TO DO: Display earliest, most recent, and most common year of birth\n if \"Birth Year\" in df:\n print (\"The earlist year of birth:\", min(df[\"Birth Year\"].dropna(axis = 0)))\n print (\"The recent year of birth:\", max(df[\"Birth Year\"].dropna(axis = 0)))\n common_used_value(df,\"Birth Year\") \n if \"User Type\" or \"Gender\" or \"Birth Year\" not in df:\n print(\"Sorry. No Info. for User type.\")\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef common_used_value(df,parameter):\n \n parameter_counts = df[parameter].value_counts()\n\n \n common_parameter_list=[]\n for a in range(0,len(parameter_counts)):\n if parameter_counts.values[a]==parameter_counts.values[0]:\n common_parameter_list.append(parameter_counts.index[a])\n print(\"the most common {} is: {}\".format(parameter.lower(),parameter_counts.index[0])+\" Count:{}\".format(parameter_counts.values[0]))\n \n \n \n \n \ndef main():\n while True:\n city, month, day = get_filters()\n\n df = load_data(city, month, day)\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n \n \n \n \n\n","sub_path":"P1 bike_sharing/bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"139942407","text":"import pytest\n\nfrom sentry.api.bases.group import get_group\nfrom sentry.api.exceptions import ResourceDoesNotExist\nfrom sentry.models import Group, GroupRedirect\nfrom sentry.testutils import TestCase\n\n\nclass GroupEndpointTestCase(TestCase):\n def test_get_group_respects_redirect(self):\n group = self.create_group()\n duplicate_id = self.create_group().id\n Group.objects.filter(id=duplicate_id).delete()\n GroupRedirect.objects.create(\n group_id=group.id,\n previous_group_id=duplicate_id,\n )\n\n assert get_group(duplicate_id).id == group.id\n\n # We shouldn't end up in a case where the redirect points to a bad\n # reference, but testing this path for completeness.\n group.delete()\n\n with pytest.raises(ResourceDoesNotExist):\n get_group(duplicate_id)\n","sub_path":"tests/sentry/api/bases/test_group.py","file_name":"test_group.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"58311453","text":"'''\r\nAuthor Junbong Jang\r\nDate 3/14/2021\r\n\r\nTo train models on datasets that are cropped and processed\r\n'''\r\n\r\nimport sys\r\nsys.path.append('..')\r\nsys.path.append('../data_handle')\r\n\r\nimport numpy as np\r\nimport time\r\nimport os.path\r\nimport gc\r\nfrom datetime import datetime\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard\r\nfrom tensorflow.keras import backend as K\r\nfrom tensorflow.keras.utils import plot_model\r\n\r\nfrom debug_utils import *\r\nfrom UserParams import UserParams\r\nfrom custom_callback import TimeHistory, TrainableLossWeightsCallback\r\nfrom model_builder import build_model_train\r\nfrom data_generator_MTL import get_data_generator_MTL\r\nfrom data_generator_classifier import get_data_generator_classifier\r\nfrom train_data_generator import get_data_generator\r\nfrom train_data_generator_3D import get_data_generator_3D, get_data_generator_3D_all\r\n\r\n\r\ndef train_model(constants, model_index, frame, repeat_index, history_path):\r\n model_name = constants.model_names[model_index]\r\n print(' round_num:', constants.round_num, ' model name:', model_name, ' frame:', frame, ' repeat_index:', repeat_index)\r\n args = constants.get_args() # get hyper parameters\r\n\r\n # leave-one-movie-out cross validation so don't use the test movie\r\n train_val_dataset_names = [x for i, x in enumerate(constants.dataset_names) if i != model_index]\r\n print('train_val_dataset_names:', train_val_dataset_names)\r\n\r\n if 'paxillin_TIRF' in train_val_dataset_names[0] and \\\r\n ('specialist' in constants.strategy_type or 'single_micro' in constants.strategy_type):\r\n process_type = 'normalize'\r\n elif 'process_clip' in constants.strategy_type:\r\n process_type = 'clip'\r\n elif 'minmax_normalize' in constants.strategy_type:\r\n process_type = 'minmax_normalize'\r\n else:\r\n process_type = 'standardize'\r\n print('process_type', process_type)\r\n\r\n # ---------------------- Load Data Generator --------------------------\r\n if 'FNA' in constants.strategy_type:\r\n train_x, train_y, valid_x, valid_y = get_data_generator_MTL(train_val_dataset_names, repeat_index, args.crop_mode, constants.img_format, 'train')\r\n if '_classifier' in constants.strategy_type and 'regressor' not in constants.strategy_type:\r\n # get mask class list only\r\n train_y = train_y[2]\r\n valid_y = valid_y[2]\r\n\r\n elif '_classifier_regressor' in constants.strategy_type:\r\n # get mask area list and class list\r\n train_y = (train_y[1], train_y[2])\r\n valid_y = (valid_y[1], valid_y[2])\r\n\r\n else:\r\n train_y = [train_y[0], train_x, train_y[1], train_y[2]]\r\n valid_y = [valid_y[0], valid_x, valid_y[1], valid_y[2]]\r\n\r\n elif '_3D' in constants.strategy_type:\r\n train_x, train_y, valid_x, valid_y = get_data_generator_3D_all(train_val_dataset_names,\r\n repeat_index, args.crop_mode, constants.img_format, process_type, args.input_depth)\r\n elif 'temporal' in constants.strategy_type:\r\n aug_batch_size = 64\r\n train_x, train_y, valid_x, valid_y = get_data_generator_3D(train_val_dataset_names, frame,\r\n repeat_index, args.crop_mode, constants.img_format, aug_batch_size, process_type)\r\n else:\r\n aug_batch_size = 64\r\n train_x, train_y, valid_x, valid_y = get_data_generator(constants.round_num, train_val_dataset_names,\r\n model_name, frame, repeat_index, args.crop_mode, constants.img_format, aug_batch_size, process_type, history_path)\r\n\r\n if \"deeplabv3\" == str(constants.strategy_type) or \"EFF_B\" in str(constants.strategy_type) \\\r\n or 'imagenet_pretrained' in str(constants.strategy_type)\\\r\n or 'vit_classifier' in str(constants.strategy_type):\r\n K.set_image_data_format('channels_last')\r\n # first channel to last channel\r\n train_x = np.moveaxis(train_x, 1, -1)\r\n valid_x = np.moveaxis(valid_x, 1, -1)\r\n if 'classifier' not in str(constants.strategy_type):\r\n train_y = np.moveaxis(train_y, 1, -1)\r\n valid_y = np.moveaxis(valid_y, 1, -1)\r\n print('train_x', train_x.shape, 'valid_x', valid_x.shape)\r\n \r\n # ---------------------- Build the model ----------------------\r\n # multiple gpu training\r\n # strategy = tf.distribute.MirroredStrategy()\r\n # with strategy.scope():\r\n model = build_model_train(constants, args, frame, model_name)\r\n\r\n # ---------------------- Sanity Check the model ----------------------\r\n print(model.summary())\r\n print('Num of layers: ', len(model.layers))\r\n # print('FLOPS: ', get_flops()) # run this after model compilation\r\n # check_loaded_weights(constants)\r\n if repeat_index == 0:\r\n plot_model(model, to_file='model_plots/model_round{}_{}_train.png'.format(constants.round_num,\r\n constants.strategy_type),\r\n show_shapes=True, show_layer_names=True, dpi=144)\r\n\r\n # ---------------------- Fit the Model ----------------------\r\n\r\n print('Fit Model...', args.epochs, args.patience)\r\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, verbose=1, min_lr=1e-6)\r\n earlyStopping = EarlyStopping(monitor='val_loss', patience=args.patience, verbose=0, mode='auto') # args.patience\r\n model_checkpoint = ModelCheckpoint(\r\n 'results/model_round{}_{}/model_frame{}_{}_repeat{}.hdf5'.format(constants.round_num, constants.strategy_type,\r\n str(frame), model_name,\r\n str(repeat_index)),\r\n monitor='val_loss', save_best_only=True)\r\n\r\n time_callback = TimeHistory()\r\n trainable_loss_weights_callback = TrainableLossWeightsCallback(model)\r\n logdir = 'results/history_round{}_{}/tensorboard_frame{}_{}_repeat{}_{}'.format(constants.round_num,\r\n constants.strategy_type, str(frame),\r\n model_name,\r\n str(repeat_index),\r\n datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\r\n\r\n # reference https://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/engine/training.py#L1823-L1861\r\n if \"VGG19_classifier_custom_loss\" in str(constants.strategy_type) or \"VGG19_MTL_auto\" in str(constants.strategy_type):\r\n hist = model.fit([train_x, *train_y],\r\n epochs=args.epochs,\r\n verbose=1,\r\n workers=1,\r\n batch_size=args.train_batch_size,\r\n validation_data=([valid_x, *valid_y]),\r\n callbacks=[model_checkpoint, earlyStopping, time_callback, trainable_loss_weights_callback, TensorBoard(log_dir=logdir)])\r\n hist.history['trainable_loss_weights'] = trainable_loss_weights_callback.history_of_trainable_loss_weights\r\n\r\n else:\r\n hist = model.fit(train_x, train_y,\r\n epochs=args.epochs,\r\n verbose=1,\r\n workers=1,\r\n batch_size = args.train_batch_size,\r\n validation_data=(valid_x, valid_y),\r\n callbacks=[model_checkpoint, reduce_lr, earlyStopping, time_callback, TensorBoard(log_dir=logdir)])\r\n\r\n # ---------------------- Save the Training History ----------------------\r\n hist.history['times'] = time_callback.times\r\n print('Save History...')\r\n np.save('results/history_round{}_{}/history_frame{}_{}_repeat{}.npy'.format(constants.round_num,\r\n constants.strategy_type, str(frame),\r\n model_name,\r\n str(repeat_index)), hist.history)\r\n K.clear_session()\r\n\r\n return\r\n\r\n\r\nif __name__ == \"__main__\":\r\n K.set_image_data_format('channels_first')\r\n print(K.image_data_format())\r\n constants = UserParams('train')\r\n\r\n history_path = 'results/history_round{}_{}/'.format(constants.round_num, constants.strategy_type)\r\n print(history_path)\r\n if not os.path.exists(history_path):\r\n os.makedirs(history_path)\r\n if not os.path.exists('results/model_round{}_{}/'.format(constants.round_num, constants.strategy_type)):\r\n os.makedirs('results/model_round{}_{}/'.format(constants.round_num, constants.strategy_type))\r\n for repeat_index in range(constants.REPEAT_MAX):\r\n for frame_index in range(len(constants.frame_list)):\r\n for model_index in range(len(constants.model_names)):\r\n frame = constants.frame_list[frame_index]\r\n start_time = time.time()\r\n train_model(constants, model_index, frame, repeat_index, history_path)\r\n elapsed_time = time.time() - start_time\r\n print('Elapsed Time:', elapsed_time / 3600, 'hr')\r\n gc.collect()\r\n","sub_path":"models/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"230044910","text":"import warnings\n\nfrom markdown_it.token import Token, nest_tokens, NestedTokens\n\n\ndef test_token():\n token = Token(\"name\", \"tag\", 0)\n assert token.as_dict() == {\n \"type\": \"name\",\n \"tag\": \"tag\",\n \"nesting\": 0,\n \"attrs\": None,\n \"map\": None,\n \"level\": 0,\n \"children\": None,\n \"content\": \"\",\n \"markup\": \"\",\n \"info\": \"\",\n \"meta\": {},\n \"block\": False,\n \"hidden\": False,\n }\n token.attrSet(\"a\", \"b\")\n assert token.attrGet(\"a\") == \"b\"\n token.attrJoin(\"a\", \"c\")\n assert token.attrGet(\"a\") == \"b c\"\n token.attrPush([\"x\", \"y\"])\n assert token.attrGet(\"x\") == \"y\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n assert token.attrIndex(\"a\") == 0\n assert token.attrIndex(\"x\") == 1\n assert token.attrIndex(\"j\") == -1\n\n\ndef test_serialization():\n token = Token(\"name\", \"tag\", 0, children=[Token(\"other\", \"tag2\", 0)])\n assert token == Token.from_dict(token.as_dict())\n\n\ndef test_nest_tokens():\n tokens = nest_tokens(\n [\n Token(\"start\", \"\", 0),\n Token(\"open\", \"\", 1),\n Token(\"open_inner\", \"\", 1),\n Token(\"inner\", \"\", 0),\n Token(\"close_inner\", \"\", -1),\n Token(\"close\", \"\", -1),\n Token(\"end\", \"\", 0),\n ]\n )\n assert [t.type for t in tokens] == [\"start\", \"open\", \"end\"]\n assert isinstance(tokens[0], Token)\n assert isinstance(tokens[1], NestedTokens)\n assert isinstance(tokens[2], Token)\n\n nested = tokens[1]\n assert nested.opening.type == \"open\"\n assert nested.closing.type == \"close\"\n assert len(nested.children) == 1\n assert nested.children[0].type == \"open_inner\"\n\n nested2 = nested.children[0]\n assert nested2.opening.type == \"open_inner\"\n assert nested2.closing.type == \"close_inner\"\n assert len(nested2.children) == 1\n assert nested2.children[0].type == \"inner\"\n","sub_path":"tests/test_api/test_token.py","file_name":"test_token.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"61720301","text":"import turtle\nimport random\n\nwindow = turtle.Screen()\n\nsquare = turtle.Turtle() # define the turtle responsible for drawing the square\nsquare.speed(0) # make the turtle draw at light-speed\nsquare.hideturtle() # make the turtle itself invisible\n\n# draw_square performs all the drawing relating to the on-screen square\ndef draw_square():\n square.up()\n square.goto(-200, 200)\n square.down()\n\n for _ in range(4):\n square.forward(50)\n square.right(90)\ndraw_square()\nsquare.up()\nsquare.goto(-205, 205)\nsquare.write(\"Change Color\")\n\npencil = turtle.Turtle() # define the turtle that will be the color-changing pencil\npencil.shape(\"circle\") # make the turtle look like a dot\n\n# drawing_controls changes the pencil to a random color\n# when a user clicks inside the square\ndef drawing_controls(x, y):\n if (-200 <= x <= -150) and (150 <= y <= 200):\n red = random.random()\n green = random.random()\n blue = random.random()\n pencil.color(red, green, blue)\n square.color(red, green, blue)\n draw_square()\n\nwindow.onclick(drawing_controls) # call drawing_controls whenever the user clicks the turtle window\n\npencil.onrelease(pencil.goto)\nturtle.done() # ensure the file can run on the command line\n","sub_path":"In-Labs/1/etch-a-sketch.py","file_name":"etch-a-sketch.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"36138553","text":"class Solution(object):\n def maxChunksToSorted(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n # Min, Max, Chunk\n leng = len(arr)\n smin = [0 for _ in range(leng)]\n smax = [0 for _ in range(leng)]\n \n smin[-1] = arr[-1] \n smax[0] = arr[0]\n for i in range(1, leng):\n smax[i] = max(smax[i-1],arr[i])\n smin[-i-1] = min(smin[-i], arr[-i-1])\n \n result = 1\n for i in range(leng-1):\n if smax[i]<=smin[i+1]:\n result += 1\n\n return result\n \n\ns = Solution()\nprint(s.maxChunksToSorted([4, 3, 2, 1, 0]))\n","sub_path":"py.old/Prob7/Prob768.py","file_name":"Prob768.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"202940800","text":"import constants\nimport utils\nimport bluetooth._bluetooth as bluez\nimport struct\n\n\n### HCI commands. ###\n\ndef hci_le_read_local_supported_features(sock):\n cmd_pkt = \"\"\n bluez.hci_send_cmd(sock, constants.OGF_LE_CTL,\n constants.OCF_LE_READ_LOCAL_SUPPORTED_FEATURES,\n cmd_pkt)\n\ndef hci_le_read_remote_used_features(sock, handle):\n cmd_pkt = struct.pack(\" 3:\n result[\"command_return_values\"] = pkt[3:]\n # Since we only care about BLE commands, we ignore the command return values\n # here. A full-powered bluetooth parsing module would check the OCF above\n # and parse the return values based on that OCF. We return the return values\n # to the user should the used want to parse the return values.\n return result\n\ndef _handle_command_status(pkt):\n result = {}\n status, ncmd, opcode = struct.unpack(\" 16):\n print('A senha deve conter entre 6 e 16 caracteres')\n break\n elif not re.search(\"[a-z]\", senha):\n print('A senha deve ter ao menos uma letra minúscula')\n break\n elif not re.search(\"[0-9]\", senha):\n print('A senha deve conter ao menos um número')\n break\n elif not re.search(\"[A-Z]\", senha):\n print('A senha deve conter ao menos uma letra maiúscula')\n break\n elif not re.search(\"[$#@*!&]\", senha):\n print('A senha deve conter ao menos um caractere especial')\n break\n elif re.search(\"\\s\", senha):\n break\n else:\n print('Senha cadastrada com sucesso!!!')\n x = False\n break\n\nif x:\n print('Senha inválida!!!')\n\n","sub_path":"Exercicios/Valida senha.py","file_name":"Valida senha.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"615637340","text":"\"\"\"Minecraft URL Configuration\"\"\"\r\nfrom django.urls import path\r\nfrom .api import *\r\n\r\n\r\nurlpatterns = [\r\n # Enlaces Funciones para el AntiParches\r\n path('login/', auth_anticheat, name=\"api_login\"),\r\n path('logout/', logout_anticheat, name=\"api_logout\"),\r\n path('refresh/', refresh_anticheat, name=\"api_refresh\"),\r\n path('news/', news, name=\"api_news\"),\r\n path('status/', user_status, name=\"api_user_status\"),\r\n path('black/', user_black, name=\"api_black\"),\r\n path('white/', user_white, name=\"api_white\"),\r\n path('ban/', user_ban, name=\"api_white\"),\r\n path('skins/', user_skins, name=\"api_skins_upload\"),\r\n path('online/', online, name=\"api_online\"),\r\n path('check/version/', check_version, name=\"api_check_version\"),\r\n path('check/mods/', check_mods, name=\"api_check_mods\"),\r\n path('check/resources/', check_resources, name=\"api_check_resources\"),\r\n path('client/update/', update, name=\"api_update_client\"),\r\n path('friends/', friends, name=\"api_search_friends\"),\r\n path('crash/', user_crash, name=\"api_crash\"),\r\n # Enlaces Funciones para la Web\r\n path('user/', search_user, name=\"api_search_user\"),\r\n path('rcon/', rcon_send, name=\"api_rcon\"),\r\n #path('server/logs/', server_logs, name=\"api_server_logs\"),\r\n #path('server/start/', server_start, name=\"api_server_start\"),\r\n #path('server/stop/', server_stop, name=\"api_server_stop\"),\r\n #path('server/restart/', server_restart, name=\"api_server_restart\"),\r\n]","sub_path":"system/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"654260974","text":"from .obtainFeatures import getWormFeaturesFilt\nfrom ..ske_filt import _get_feat_filt_param\n\ndef _get_feats_param(p):\n return {\n 'feat_filt_param': _get_feat_filt_param(p),\n 'split_traj_time' : p['split_traj_time'],\n 'is_single_worm': p['analysis_type'] == 'SINGLE_WORM_SHAFER'\n }\n\ndef args_(fn, param):\n # getWormFeatures\n \n\n requirements = ['SKE_CREATE']\n if param.p_dict['analysis_type'] == 'SINGLE_WORM_SHAFER':\n from functools import partial\n from ..contour_orient import isGoodVentralOrient\n requirements += ['CONTOUR_ORIENT', ('is_valid_contour', partial(isGoodVentralOrient, fn['skeletons']))]\n \n from ..stage_aligment import isGoodStageAligment \n requirements += ['STAGE_ALIGMENT', ('is_valid_alignment', partial(isGoodStageAligment, fn['skeletons']))]\n\n #arguments used by AnalysisPoints.py\n return {\n 'func': getWormFeaturesFilt,\n 'argkws': {'skeletons_file': fn['skeletons'], 'features_file': fn['features'],\n **_get_feats_param(param.p_dict),\n 'use_skel_filter': True, 'use_manual_join': False\n },\n 'input_files' : [fn['skeletons']],\n 'output_files': [fn['features']],\n 'requirements' : requirements,\n }","sub_path":"tierpsy/analysis/feat_create/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"236132534","text":"# -*- coding: utf-8 -*-\n__module_class_names__ = [\n \"Auth\",\n \"Autojoin\",\n \"Join\",\n \"Part\",\n \"Nick\",\n \"Send\",\n \"Msg\",\n \"Reload\",\n \"CoreDump\",\n ]\n\nfrom bot import Module\nimport traceback,os.path\nimport pickle,hashlib\n\nFNAME_A = os.path.expanduser('~/.ircbot/modulefiles/bot_admins.pickle')\nbot_admins = list() # (\"nick\", md5(\"password\"), \"nick!username@host\")\n\nclass Autojoin(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"cmd\"\n self.rule = r\"376.*\"\n \n def run(self, bot, params):\n for chan in bot.config[\"channels\"]:\n bot.msg(\"JOIN %s\" % chan)\n #bot.say(chan, \"Hello!\")\n\nclass Auth(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"^\\.auth[ ]+([^ ]+)[ ]+([^ ]+)$\"\n global bot_admins\n try:\n bot_admins = pickle.Unpickler(open(FNAME_A,'rb')).load()\n except EOFError:\n bot.verbose_msg(\"error ! cannot load administrators data\")\n \n def run(self, bot, params):\n global bot_admins\n if bot.sender in [x[2] for x in bot_admins]:\n bot.say(bot.sender.split(\"!\")[0],\"You already are authorized.\")\n return\n username = bot.match.groups()[0]\n password = bot.match.groups()[1].encode(bot.config[\"encoding\"])\n password = hashlib.md5(password).hexdigest()\n for x in bot_admins:\n print(\"%s,%s == %s,%s\" % (username,password,x[0],x[1]))\n if (username,password) == (x[0],x[1]):\n x[2] = bot.sender\n bot.say(bot.sender.split(\"!\")[0],\"Succesfully authorized.\")\n pickle.Pickler(open(FNAME_A,'wb')).dump(bot_admins)\n return\n bot.say(bot.sender.split(\"!\")[0],\"Unable to authorize.\")\n\nclass Join(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"\\.join (\\#[^ ]+)\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n bot.msg(\"JOIN %s\" % bot.match.groups()[0])\n bot.say(bot.match.groups()[0], \"Hello!\")\n #bot.say(bot.match.groups()[0], \"I have been told to join this channel by %s\" % params[0])\n\nclass Part(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"\\.part (\\#[^ ]+)\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n bot.msg(\"PART %s\" % bot.match.groups(0))\n\nclass Nick(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"\\.nick ([^ ]+)\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n bot.conf.nick = bot.match.group(0)\n bot.msg(\"NICK %s\" % bot.match.groups(0))\n\nclass Msg(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"\\.msg (\\#[^ ]+)[ ]+([^ ].*)\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n bot.say(bot.match.group(1),bot.match.group(2))\n\nclass Send(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"\\.send[ ]+([^ ].*)\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n bot.msg(bot.match.groups()[0])\n\nclass Reload(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"^\\.(reload|unload)[ ]+([^ ]+)$\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n mn = bot.match.groups()[1]\n nick = params[0].split(\"!\")[0]\n try:\n bot.unload_module(mn)\n except:\n bot.say(nick, \"Unloading of module %s FAILED!\" % mn)\n traceback.print_exc()\n else:\n bot.say(nick, \"Unloading of module %s SUCCESSFUL!\" % mn)\n if bot.match.groups()[0]=='unload':\n return\n try:\n bot.load_module(mn)\n except:\n bot.say(nick, \"Reloading of module %s FAILED!\" % mn)\n traceback.print_exc()\n else:\n bot.say(nick, \"Reloading of module %s SUCCESSFUL!\" % mn)\n\nclass CoreDump(Module):\n def __init__(self, bot, config):\n Module.__init__(self, bot, config)\n self.handler_type = \"privmsg\"\n self.rule = r\"^\\.core_dump$\"\n \n def run(self, bot, params):\n if bot.sender not in [x[2] for x in bot_admins]:\n return\n #bot.say(bot.sender.split(\"!\")[0],\"yeah!\")\n for k in bot.modules:\n print(k)\n for m in bot.modules[k]:\n print(\"\\t%s\" % m[2])\n","sub_path":"ircbot/modules/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"382164235","text":"# Copyright 2012 Dorival de Moraes Pedroso. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nfrom numpy import array, zeros, dot, transpose, outer, sqrt, ones\nfrom tlfem.quadrature import get_ips, ip_coords\nfrom tlfem.shape import get_shape_fcn, shape_derivs, face_integ, face_coords\n\nclass EelasticPorous2D:\n def __init__(self, verts, params):\n \"\"\"\n 2D elasticity problem with porous media\n =======================================\n Example of input:\n global_id tag x y\n verts = [[3, -100, 0.0, 0.0],\n [4, -100, 1.0, 0.0],\n [7, -100, 1.0, 1.0],\n [1, -100, 0.0, 1.0]]\n params = {'E':1., 'nu':1., 'pstress':True, 'thick':1.,\n 'geom':'tri3', 'ipe':'QuaIp4', 'rho':1.0}\n pstress : plane-stress instead of plane-strain? [optional]\n thick : thickness for plane-stress only [optional]\n ipe : [optional] integration points\n geom types:\n tri3, tri6, qua4, qua8\n INPUT:\n verts : list of vertices\n params : dictionary of parameters\n STORED:\n geom : geometry key pair, ex: (tri6,tri3), (qua8,qua4)\n fce, fcf : element and face shape/deriv functions\n nne, nnf : element and face number of nodes\n ipe, ipf : integration points of element and edge/face\n rho : density [optional]\n E : Young modulus\n nu : Poisson's coefficient\n pstress : is plane-stress problem instead of plane-strain?\n thick : thickness for plane-stress problems\n has_load : has applied distributed load to any side\n xy : matrix of coordinates of nodes\n D : constitutive modulus (matrix)\n K : stiffness matrix\n \"\"\"\n # set geometry\n if isinstance(params['geom'],str):\n self.geoU = params['geom']\n self.geoP = params['geom']\n else:\n self.geoU = params['geom'][0]\n self.geoP = params['geom'][1]\n self.fceU, self.nneU, self.fcfU, self.nnfU = get_shape_fcn(self.geoU)\n self.fceP, self.nneP, self.fcfP, self.nnfP = get_shape_fcn(self.geoP)\n self.ipeU, self.ipfU = get_ips(self.geoU)\n self.ipeP, self.ipfP = get_ips(self.geoP)\n if 'ipeU' in params: self.ipeU = params['ipeU']\n if 'ipeP' in params: self.ipeP = params['ipeP']\n\n # check\n if len(verts) != self.nneU:\n raise Exception('this element needs %d vertices exactly'%self.nneU)\n\n # set data\n self.E = params['E'] # Young modulus\n self.nu = params['nu'] # Poisson's coefficient\n self.kx = params['kx'] # x-conductivity\n self.ky = params['ky'] # y-conductivity\n self.has_load = False # has distributed loads\n self.has_flux = False # has flux specified\n\n # other parameters\n rhoS = params['rhoS'] # density of solid grains\n rhoW = params['rhoW'] # water real density\n gamW = params['gamW'] # water unit weight of reference\n eta = params['eta'] # porosity\n Kw = params['Kw'] # water bulk modulus\n rho = (1.0-eta)*rhoS + eta*rhoW # density of mixture\n Cwb = eta / Kw\n\n # matrix of nodal coordinates\n self.xyU = zeros((2,self.nneU)) # 2 => 2D\n self.xyP = zeros((2,self.nneP)) # 2 => 2D\n for n, v in enumerate(verts):\n self.xyU[0][n] = v[2] # x-coordinates\n self.xyU[1][n] = v[3] # y-coordinates\n if n < self.nneP:\n self.xyP[0][n] = v[2] # x-coordinates\n self.xyP[1][n] = v[3] # y-coordinates\n\n # constitutive matrix (plane strain)\n nu = self.nu # Poisson coef\n cf = self.E / ((1.0 + nu) * (1.0 - 2.0 * nu))\n self.D = cf * array([[1.-nu , nu , nu , 0. ],\n [nu , 1.-nu , nu , 0. ],\n [nu , nu , 1.-nu , 0. ],\n [0. , 0. , 0. , 1.-2.*nu]])\n\n # conductivity matrix\n self.kap = array([[self.kx / gamW, 0.0],\n [0.0, self.ky / gamW]])\n\n # iota tensor\n self.iota = array([1., 1., 1., 0.])\n\n # K, M, Q and O matrices\n self.K = zeros((self.nneU*2,self.nneU*2))\n self.M = zeros((self.nneU*2,self.nneU*2))\n self.Q = zeros((self.nneU*2,self.nneP))\n self.O = zeros((self.nneP,self.nneU*2))\n for ip in self.ipeU:\n # K and M\n S, G, detJ = shape_derivs(self.xyU, self.fceU, ip)\n B = self.calc_B(G)\n N = self.calc_N(S)\n cf = detJ * ip[2]\n self.K += cf * dot(transpose(B), dot(self.D, B))\n self.M += (cf * rho) * dot(transpose(N), N)\n # Q and O\n Sb, Gb, _ = shape_derivs(self.xyP, self.fceP, ip)\n self.Q += cf * dot(transpose(B), outer(self.iota, Sb))\n self.O += (cf * rhoW) * dot(Gb, dot(self.kap, N))\n #print detJ, detJb, detJ-detJb\n\n # L and H matrices\n self.L = zeros((self.nneP,self.nneP))\n self.H = zeros((self.nneP,self.nneP))\n for ip in self.ipeP:\n Sb, Gb, detJb = shape_derivs(self.xyP, self.fceP, ip)\n cf = detJb * ip[2]\n self.L += (cf * Cwb) * outer(Sb, Sb)\n self.H += cf * dot(Gb, dot(self.kap, transpose(Gb)))\n\n # local equation numbers\n neqs = self.nneU*2 + self.nneP\n self.eqsP = [2+n*3 for n in range(self.nneP)]\n self.eqsU = [i for i in range(neqs) if i not in self.eqsP]\n\n def info(self):\n \"\"\"\n Get Solution Variables\n ======================\n \"\"\"\n sovs = [('ux','uy','pw') for _ in range(self.nneP)]\n sovs.extend([('ux','uy') for _ in range(self.nneP,self.nneU)])\n return sovs, {'fx':'ux', 'fy':'uy'}, \\\n ['sxE','syE','szE','sxyE', 'ex','ey','ez','exy']\n\n def get_amaps(self, amap):\n \"\"\"\n Get separated assembly maps\n ===========================\n INPUT:\n amap : global assembly map corresponding to 'sovs' returned by info\n RETURNS:\n amapU : assembly map for U sovs\n amapP : assembly map for P sovs\n \"\"\"\n return [amap[i] for i in self.eqsU], [amap[i] for i in self.eqsP]\n\n def clear_bcs(self):\n \"\"\"\n Clear boundary conditions\n =========================\n \"\"\"\n self.has_load = False\n self.has_flux = False\n\n def set_nat_bcs(self, edge_num, bc_type, values):\n \"\"\"\n Set natural (or mixed) boundary conditions\n ==========================================\n INPUT:\n edge_num : edge number => side of triangle\n bc_type : 'qxqy', 'qnqt' distributed loads\n values : list with 2 items => values of distributed loads\n STORED:\n Fq : force vector\n has_load : has loads applied to any side?\n RETURNS:\n None\n \"\"\"\n # check\n if not bc_type in ['qxqy', 'qnqt']:\n raise Exception('boundary condition type == %s is not available' % bc_type)\n\n # coordinates and indices of edge/face nodes\n xyfU, fnoU = face_coords(self.xyU, edge_num, self.nneU)\n\n # calc loads\n if not self.has_load: self.Fq = zeros(self.nneU*2)\n for ip in self.ipfU:\n Sf, detJf, dxydr = face_integ(xyfU, self.fcfU, ip)\n # qn and qt => find qx and qy\n if bc_type == 'qnqt':\n nx, ny = dxydr[1], -dxydr[0] # normal multiplied by detJf\n qn, qt = values[0], values[1]\n qx = nx*qn - ny*qt\n qy = ny*qn + nx*qt\n # qx and qy\n else:\n qx = values[0] * detJf\n qy = values[1] * detJf\n for i, n in enumerate(fnoU):\n self.Fq[0+n*2] += ip[2] * qx * Sf[i]\n self.Fq[1+n*2] += ip[2] * qy * Sf[i]\n\n # set flag\n self.has_load = True\n\n def calc_M(self): return self.M\n def calc_K(self): return self.K\n def calc_O(self): return self.O\n def calc_Q(self): return self.Q\n def calc_L(self): return self.L\n def calc_H(self): return self.H\n\n def calc_F(self):\n \"\"\"\n Calculate vector F = Fe\n =======================\n \"\"\"\n if self.has_load: return self.Fq\n else: return zeros(self.nneU*2)\n\n def calc_Fb(self):\n \"\"\"\n Calculate vector Fb = Fbe\n =========================\n \"\"\"\n if self.has_flux: return self.Fb\n else: return zeros(self.nneP)\n\n def secondary(self, UPe):\n \"\"\"\n Calculate secondary variables\n =============================\n INPUT:\n UPe : vector of primary variables at each node\n STORED:\n None\n RETURNS:\n svs : dictionary with secondary values\n \"\"\"\n Ue = array([UPe[i] for i in self.eqsU])\n Pe = array([UPe[i] for i in self.eqsP])\n nip = len(self.ipeU)\n svs = {'sxE':zeros(nip), 'syE':zeros(nip), 'szE':zeros(nip), 'sxyE':zeros(nip), # effective values\n 'ex' :zeros(nip), 'ey' :zeros(nip), 'ez' :zeros(nip), 'exy' :zeros(nip)}\n sq2 = sqrt(2.0)\n for k, ip in enumerate(self.ipeU):\n S, G, _ = shape_derivs(self.xyU, self.fceU, ip)\n B = self.calc_B(G)\n eps = dot(B, Ue) # strains\n sig = dot(self.D, eps) # stresses\n svs['sxE' ][k] = sig[0]\n svs['syE' ][k] = sig[1]\n svs['szE' ][k] = sig[2]\n svs['sxyE'][k] = sig[3]/sq2\n svs['ex' ][k] = eps[0]\n svs['ey' ][k] = eps[1]\n svs['ez' ][k] = eps[2]\n svs['exy' ][k] = eps[3]/sq2\n return svs\n\n def get_ips(self):\n \"\"\"\n Get integration points\n ======================\n \"\"\"\n ips = []\n for ip in self.ipeU:\n S, _ = self.fceU(ip[0], ip[1])\n ips.append(ip_coords(S, self.xy))\n return ips\n\n def calc_B(self, G):\n \"\"\"\n Calculate B matrix\n ==================\n INPUT:\n G : gradient of shape functions at a selected ip\n RETURNS:\n B : B matrix\n \"\"\"\n sq2 = sqrt(2.0)\n B = zeros((4,2*self.nneU)) # 4 stress components, 2D*nne\n for n in range(self.nneU):\n B[0,0+n*2] = G[n,0]\n B[1,1+n*2] = G[n,1]\n B[3,0+n*2] = G[n,1]/sq2\n B[3,1+n*2] = G[n,0]/sq2\n return B\n\n def calc_N(self, S):\n \"\"\"\n Calculate N matrix\n ==================\n INPUT:\n S : shape functions at a selected ip\n RETURNS:\n N : N matrix\n \"\"\"\n N = zeros((2,2*self.nneU)) # 2D, 2D*nne\n for n in range(self.nneU):\n N[0,0+n*2] = S[n]\n N[1,1+n*2] = S[n]\n return N\n","sub_path":"tlfem/EelasticPorous2D.py","file_name":"EelasticPorous2D.py","file_ext":"py","file_size_in_byte":11365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"309022211","text":"# Problem Set 4B\r\n# Name: \r\n# Collaborators:\r\n# Time Spent: x:xx\r\nimport string #导入string这个模块\r\n#print string.letters #包含所有字母(大写或小写)的字符串\r\n#print string.lowercase #包含所有小写字母的字符串\r\n#print string.uppercase #包含所有大写字母的字符串\r\n#print string.punctuation #包含所有标点的字符串\r\n#print string.ascii_letters #与string.letters一样\r\ndef add_space(strings,integer):\r\n #该函数可以在一个字符串的特定位置增加空格\r\n #经测试可以使用\r\n return strings[0:integer]+\" \"+strings[integer:]\r\ndef change(character,shift):\r\n # 该函数返回移动后的字母,返回的是字符串类型\r\n #charecter是字符串类型,shift是整数\r\n #经测试可以正常使用\r\n length=26\r\n number=0\r\n if character in string.ascii_lowercase:\r\n for i in range(0,length):\r\n if character==string.ascii_lowercase[i]:\r\n number=i\r\n break\r\n number=number+shift\r\n else:\r\n for i in range(0,length):\r\n if character==string.ascii_uppercase[i]:\r\n number=i\r\n break\r\n number=number+shift\r\n if number>=26:\r\n number=number-26\r\n if character in string.ascii_lowercase:\r\n return string.ascii_lowercase[number]\r\n else:\r\n return string.ascii_uppercase[number]\r\n### HELPER CODE ###\r\ndef load_words(file_name):\r\n #该函数输入文件名,返回列表类型的有效单词\r\n '''\r\n file_name (string): the name of the file containing \r\n the list of words to load \r\n \r\n Returns: a list of valid words. Words are strings of lowercase letters.\r\n \r\n Depending on the size of the word list, this function may\r\n take a while to finish.\r\n '''\r\n #print(\"Loading word list from file...\")\r\n # inFile: file\r\n inFile = open(file_name, 'r')\r\n # wordlist: list of strings\r\n wordlist = []\r\n for line in inFile:\r\n wordlist.extend([word.lower() for word in line.split(' ')])\r\n #print(\" \", len(wordlist), \"words loaded.\")\r\n return wordlist\r\n\r\ndef is_word(word_list, word):\r\n #该函数判断word是否有效,不考虑大小写和标点\r\n #返回 True or False\r\n '''\r\n Determines if word is a valid word, ignoring\r\n capitalization and punctuation\r\n\r\n word_list (list): list of words in the dictionary.\r\n word (string): a possible word.\r\n \r\n Returns: True if word is in word_list, False otherwise\r\n\r\n Example:\r\n >>> is_word(word_list, 'bat') returns\r\n True\r\n >>> is_word(word_list, 'asdf') returns\r\n False\r\n '''\r\n word = word.lower()\r\n word = word.strip(\" !@#$%^&*()-_+={}[]|\\:;'<>?,./\\\"\")\r\n return word in word_list\r\n\r\ndef get_story_string():\r\n #返回加密文本\r\n \"\"\"\r\n Returns: a story in encrypted text.\r\n \"\"\"\r\n f = open(\"story.txt\", \"r\")\r\n story = str(f.read())\r\n f.close()\r\n return story\r\n\r\n### END HELPER CODE ###\r\n\r\nWORDLIST_FILENAME = 'words.txt'\r\n\r\nclass Message(object):\r\n def __init__(self, text):\r\n self.message_text=text\r\n self.valid_words = load_words(\"words.txt\")\r\n #列表类型\r\n\r\n def get_message_text(self):\r\n '''\r\n Used to safely access self.message_text outside of the class\r\n \r\n Returns: self.message_text\r\n '''\r\n return self.message_text\r\n\r\n def get_valid_words(self):\r\n '''\r\n Used to safely access a copy of self.valid_words outside of the class.\r\n This helps you avoid accidentally mutating class attributes.\r\n \r\n Returns: a COPY of self.valid_words\r\n '''\r\n valid_words_copy=self.valid_words[:]\r\n return valid_words_copy\r\n\r\n def build_shift_dict(self, shift):\r\n '''\r\n Creates a dictionary that can be used to apply a cipher to a letter.\r\n The dictionary maps every uppercase and lowercase letter to a\r\n character shifted down the alphabet by the input shift. The dictionary\r\n should have 52 keys of all the uppercase letters and all the lowercase\r\n letters only. \r\n # 创建字典,字典只能有52个关键字,分别是所有的大小写字母\r\n shift (integer): the amount by which to shift every letter of the \r\n alphabet. 0 <= shift < 26\r\n shift是int类型,小于26大于等于0\r\n Returns: a dictionary mapping a letter (string) to \r\n another letter (string). \r\n #返回的是字典类型,string:string\r\n '''\r\n shift_dict={}\r\n for i in string.ascii_lowercase:\r\n shift_dict[i]=change(i,shift)\r\n for i in string.ascii_uppercase:\r\n shift_dict[i]=change(i,shift)\r\n return shift_dict\r\n \r\n\r\n\r\n def apply_shift(self, shift):\r\n '''\r\n Applies the Caesar Cipher to self.message_text with the input shift.\r\n Creates a new string that is self.message_text shifted down the\r\n alphabet by some number of characters determined by the input shift \r\n \r\n shift (integer): the shift with which to encrypt the message.\r\n 0 <= shift < 26\r\n #返回转换完成的text,字符串类型\r\n Returns: the message text (string) in which every character is shifted\r\n down the alphabet by the input shift\r\n '''\r\n #self.message\r\n shifted_message=\"\"\r\n message_text_list=self.message_text.split()\r\n for i in message_text_list:\r\n for j in i:\r\n if j not in string.ascii_uppercase and j not in string.ascii_lowercase:\r\n shifted_message=shifted_message+j\r\n else:\r\n shifted_message=shifted_message+change(j,shift)\r\n return shifted_message\r\n\r\n\r\n\r\nclass PlaintextMessage(Message):\r\n def __init__(self, text, shift):\r\n '''\r\n Initializes a PlaintextMessage object \r\n \r\n text (string): the message's text\r\n shift (integer): the shift associated with this message\r\n s\r\n A PlaintextMessage object inherits from Message and has five attributes:\r\n self.message_text (string, determined by input text)\r\n self.valid_words (list, determined using helper function load_words)\r\n self.shift (integer, determined by input shift)\r\n self.encryption_dict (dictionary, built using shift)\r\n self.message_text_encrypted (string, created using shift)\r\n\r\n '''\r\n Message.__init__(self, text)\r\n self.shift=shift\r\n #加密字典\r\n self.encryption_dict=Message.build_shift_dict(self, shift)\r\n #加密文本\r\n self.message_text_encrypted=Message.apply_shift(self, shift)\r\n\r\n\r\n def get_shift(self):\r\n '''\r\n Used to safely access self.shift outside of the class\r\n \r\n Returns: self.shift\r\n '''\r\n return self.shift\r\n\r\n\r\n def get_encryption_dict(self):\r\n '''\r\n Used to safely access a copy self.encryption_dict outside of the class\r\n \r\n Returns: a COPY of self.encryption_dict\r\n '''\r\n encryption_dict_copy=self.encryption_dict.copy() \r\n return encryption_dict_copy\r\n def get_message_text_encrypted(self):\r\n '''\r\n Used to safely access self.message_text_encrypted outside of the class\r\n \r\n Returns: self.message_text_encrypted\r\n '''\r\n return self.message_text_encrypted\r\n \r\n\r\n def change_shift(self, shift):\r\n '''\r\n Changes self.shift of the PlaintextMessage and updates other \r\n attributes determined by shift. \r\n \r\n shift (integer): the new shift that should be associated with this message.\r\n 0 <= shift < 26\r\n #改变该类的shift值,更新随之变化的其他属性,无返回值\r\n '''\r\n self.shift=shift\r\n #加密字典\r\n self.encryption_dict=build_shift_dict(self, shift)\r\n #加密文本\r\n self.message_text_encrypted=apply_shift(self, shift)\r\n\r\n\r\n\r\n\r\nclass CiphertextMessage(Message):\r\n def __init__(self, text):\r\n '''\r\n Initializes a CiphertextMessage object\r\n \r\n text (string): the message's text\r\n\r\n a CiphertextMessage object has two attributes:\r\n self.message_text (string, determined by input text)\r\n self.valid_words (list, determined using helper function load_words)\r\n '''\r\n Message.__init__(self, text)\r\n\r\n def decrypt_message(self):\r\n #解密method\r\n #使用​is_word(wordlist, word)和string.split\r\n #注意:is_word(wordlist, word)不考虑标点和其它特殊字符,去掉了所有特殊字符\r\n #找到最好的shift,即与最多valid_word相对应的shift\r\n #加密为s,解密为26-s\r\n #若有多个best shift,任选一个,并返回其对应的解密messages\r\n #返回元组,(best shift,decrypted message)\r\n '''\r\n Decrypt self.message_text by trying every possible shift value\r\n and find the \"best\" one. We will define \"best\" as the shift that\r\n creates the maximum number of real words when we use apply_shift(shift)\r\n on the message text. If s is the original shift value used to encrypt\r\n the message, then we would expect 26 - s to be the best shift value \r\n for decrypting it.\r\n\r\n Note: if multiple shifts are equally good such that they all create \r\n the maximum number of valid words, you may choose any of those shifts \r\n (and their corresponding decrypted messages) to return\r\n\r\n Returns: a tuple of the best shift value used to decrypt the message\r\n and the decrypted message text using that shift value\r\n '''\r\n max_key=0\r\n shift_dictionary={}#创建一个字典,关键字为shift,数值为各个shift所对应的valid_word个数\r\n #创建字典,储存空格出现的位置\r\n space_dic={}\r\n num_space=0\r\n for i in self.message_text:\r\n if i ==\" \":\r\n space_dic[num_space]=1\r\n num_space=num_space+1\r\n else:\r\n num_space=num_space+1\r\n #print(space_dic)\r\n decrypt_message_list=self.message_text.split()#将各个单词分隔,存入列表中\r\n for i in range(0,26):#每一次shift循环\r\n num=0\r\n for j in decrypt_message_list:\r\n #print(j)\r\n k=Message(j)\r\n #print(Message.apply_shift(k,i))\r\n if is_word(load_words(WORDLIST_FILENAME),Message.apply_shift(k,i) ) ==True:\r\n num=num+1\r\n shift_dictionary[i]=num\r\n maximum_shift=max(shift_dictionary.values())\r\n #print(shift_dictionary)\r\n for key,values in shift_dictionary.items():\r\n if values==maximum_shift:\r\n max_key=key\r\n break\r\n final_message=Message.apply_shift(self,max_key)\r\n for i in space_dic.keys():\r\n final_message=add_space(final_message,int(i))\r\n\r\n\r\n return (max_key,final_message)\r\n\r\n\r\n\r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n# #Example test case (PlaintextMessage)\r\n plaintext = PlaintextMessage('hello', 2)\r\n print('Expected Output: jgnnq')\r\n print('Actual Output:', plaintext.get_message_text_encrypted())\r\n plaintext = PlaintextMessage('HI,ALice', 3)\r\n print('Expected Output: KL,DOlfh')\r\n print('Actual Output:', plaintext.get_message_text_encrypted())\r\n\r\n# #Example test case (CiphertextMessage)\r\n ciphertext = CiphertextMessage('jgnnq')\r\n print('Expected Output:', (24, 'hello'))\r\n print('Actual Output:', ciphertext.decrypt_message())\r\n ciphertext = CiphertextMessage('JK, yqtnf!')\r\n print('Expected Output:', (24, 'HI, world!'))\r\n print('Actual Output:', ciphertext.decrypt_message())\r\n #print(is_word(load_words(WORDLIST_FILENAME),\"HI!\"))\r\n ciphertextMessage=CiphertextMessage(get_story_string())\r\n print(ciphertextMessage.decrypt_message())\r\n \r\n\r\n","sub_path":"my_pset_code/ps4/ps4b.py","file_name":"ps4b.py","file_ext":"py","file_size_in_byte":12172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"244740068","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n===============================================================\nauthor:xieqiqi\nemail:xieqiqi@jd.com\ndate:2018\nintroduction:\n load model and predict!\n 加载保存的模型,并完成预测!\n===============================================================\n\"\"\"\nimport argparse,os,pickle\nimport torch\nfrom config import Config\nfrom models import Encoder_for_batch,Decoder_Luong_AM_for_batch\nfrom data_helper import sent2id_for_inference\nfrom train import predict_for_inference\nPAD_token=0\nSOS_token=1\nEOS_token=2\ndef parse_arguments():\n parse = argparse.ArgumentParser(description='Hyperparams of this project!')\n #\n parse.add_argument('--encoder_hidden_dim', type=int, default=256,help='Hidden dim of encoder!')\n parse.add_argument('--encoder_embed_dim', type=int, default=256,help='Embed dim of encoder!')\n parse.add_argument('--encoder_num_layers', type=int, default=1,help='Num layers of encoder!')\n #\n parse.add_argument('--decoder_hidden_dim', type=int, default=256,help='Hidden dim of decoder!')\n parse.add_argument('--decoder_embed_dim', type=int, default=256,help='Embed dim of decoder!')\n parse.add_argument('--decoder_num_layers', type=int, default=1,help='Num layers of decoder!')\n parse.add_argument('--decoder_droupOut_p',type=float,default=0.5,help='DroupOut prob of decoder!')\n parse.add_argument('--decoder_method',type=str,default='general',help='Align methods of AM in decoder!')\n #\n parse.add_argument('--epochs', type=int, default=10,help='number of epochs for train')\n parse.add_argument('--batch_size', type=int, default=20,help='number of epochs for train')\n parse.add_argument('--lr', type=float, default=0.0001,help='initial learning rate')\n parse.add_argument('--grad_clip', type=float, default=5.0,help='Gradient max clip!')\n parse.add_argument('--teacher_forcing_ratio',type=float,default=0.5,help='Teacher forcing ratio!')\n #\n parse.add_argument('--Base_path', type=str, default='/Users/xieqiqi/Documents/pyenv/xuexi/pytorch-seq2seq-Am/pytorch_seq2seq_final/data/', help='Base path!')\n parse.add_argument('--Save_path', type=str, default='/Users/xieqiqi/Documents/pyenv/xuexi/pytorch-seq2seq-Am/pytorch_seq2seq_final/data/save_0/',\n help='Save path!')\n #\n parse.add_argument('--mode',type=str,default='inference',help='Type of mode!')\n #\n return parse.parse_args()\nprint(\"==================================================================\")\nargs=parse_arguments()\nencoder_model_save_name=os.path.join(args.Save_path,\"encoder_%d.pt\")\ndecoder_model_save_name=os.path.join(args.Save_path,\"decoder_%d.pt\")\nprint(\"=============================定义网络===============================\")\nprint(\"初始化config!\")\nconfig=Config(encoder_vocab_size=None,\n encoder_hidden_dim=args.encoder_hidden_dim,\n encoder_embed_dim=args.encoder_embed_dim,encoder_num_layers=args.encoder_num_layers,\n decoder_vocab_size=None,decoder_hidden_dim=args.decoder_hidden_dim,\n decoder_embed_dim=args.decoder_embed_dim,decoder_num_layers=args.decoder_num_layers,\n decoder_droupOut_p=args.decoder_droupOut_p,decoder_method=args.decoder_method,\n epoches=args.epochs,batch_size=args.batch_size,lr=args.lr,gradient_clip=args.grad_clip,\n teacher_forcing_ratio=args.teacher_forcing_ratio)\nprint(\"==================================================================\")\nprint(\"Models initializing....\")\nencoder=Encoder_for_batch(config).cuda() if torch.cuda.is_available() else Encoder_for_batch(config)\ndecoder=Decoder_Luong_AM_for_batch(config).cuda() if torch.cuda.is_available() else Decoder_Luong_AM_for_batch(config)\n# 定义网络\nprint(\"==========================加载网络参数==============================\")\n# 加载网络参数\nencoder.load_state_dict(torch.load(encoder_model_save_name))\ndecoder.load_state_dict(torch.load(decoder_model_save_name))\nprint(\"======================预测========================================\")\n# 用新加载的参数进行预测\nif(args.mode=='inference'):\n print(\"Inferencing...!\")\n print(\"loading target id to wd!\")\n with open(\"data/save/target_id2Wd\", \"rb\") as fr:\n target_index2Wd = pickle.load(fr)\n while(1):\n print('Please input your sentence:')\n demo_sent = input()\n if demo_sent == '' or demo_sent.isspace():\n print('See you next time!')\n break\n else:\n demo_sent = sent2id_for_inference(input_sent=demo_sent)\n #predit!\n predict_ids=predict_for_inference(sent_id=demo_sent,encoder=encoder,decoder=decoder)\n #解码!\n translate=\"\"\n for id in predict_ids:\n if(id==EOS_token):\n print(\"source sentence:\",demo_sent)\n print(\"translate result:\",translate)\n else:\n translate+=(target_index2Wd[id]+' ')","sub_path":"pytorch_seq2seq_final/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"116169069","text":"import archinfo\nfrom .errors import CLEOperationError, CLECompatibilityError, CLEError\nfrom .memory import Clemory\nfrom abc import ABCMeta\nimport os\n\nimport logging\nl = logging.getLogger('cle.generic')\n\n__all__ = ('Region', 'Segment', 'Section', 'Symbol', 'Relocation', 'AbsObj')\n\nclass Region(object):\n \"\"\"\n A region of memory that is mapped in the object's file.\n\n offset is the offset into the file the region starts\n vaddr (or just addr) is the virtual address\n filesize (or just size) is the size of the region in the file\n memsize (or vsize) is the size of the region when loaded into memory\n \"\"\"\n def __init__(self, offset, vaddr, size, vsize):\n self.vaddr = vaddr\n self.memsize = vsize\n self.filesize = size\n self.offset = offset\n\n def contains_addr(self, addr):\n return (addr >= self.vaddr) and (addr < self.vaddr + self.memsize)\n\n def contains_offset(self, offset):\n return (offset >= self.offset) and (offset < self.offset + self.filesize)\n\n def addr_to_offset(self, addr):\n offset = addr - self.vaddr + self.offset\n if not self.contains_offset(offset):\n return None\n return offset\n\n def offset_to_addr(self, offset):\n addr = offset - self.offset + self.vaddr\n if not self.contains_addr(addr):\n return None\n return addr\n\n @property\n def max_addr(self):\n return self.vaddr + self.memsize - 1\n\n @property\n def min_addr(self):\n return self.vaddr\n\n @property\n def max_offset(self):\n return self.offset + self.filesize - 1\n\n def min_offset(self):\n return self.offset\n\n\nclass Segment(Region):\n \"\"\" Simple representation of an ELF file segment\"\"\"\n pass\n\nclass Section(Region):\n \"\"\" Simple representation of an ELF file section\"\"\"\n def __init__(self, name, offset, vaddr, size, sectype, entsize, flags, link, info, align):\n super(Section, self).__init__(offset, vaddr, size, size)\n self.name = name\n self.type = sectype\n self.entsize = entsize\n self.flags = flags\n self.link = link\n self.info = info\n self.align = align\n\nclass Symbol(object):\n \"\"\"\n Representation of a symbol from a binary file. Smart enough to rebase itself.\n\n There should never be more than one Symbol instance representing a single\n symbol. To make sure of this, only use the get_symbol method in the backend\n objects.\n \"\"\"\n def __init__(self, owner, name, addr, size, binding, sym_type, sh_info):\n super(Symbol, self).__init__()\n self.owner_obj = owner\n self.name = name\n self.addr = addr\n self.size = size\n self.binding = binding\n self.type = sym_type\n self.sh_info = sh_info if sh_info != 'SHN_UNDEF' else None\n self.resolved = False\n self.resolvedby = None\n if self.addr != 0:\n self.owner_obj.symbols_by_addr[self.addr] = self\n\n def resolve(self, obj):\n self.resolved = True\n self.resolvedby = obj\n self.owner_obj.resolved_imports.append(self)\n\n @property\n def rebased_addr(self):\n return self.addr + self.owner_obj.rebase_addr\n\n @property\n def is_import(self):\n return self.sh_info is None and (self.binding == 'STB_GLOBAL' or \\\n self.binding == 'STB_WEAK' or \\\n self.binding == 'STT_FUNC')\n\n @property\n def is_export(self):\n return self.sh_info is not None and (self.binding == 'STB_GLOBAL' or \\\n self.binding == 'STB_WEAK')\n\nclass Relocation(object):\n \"\"\"\n A representation of a relocation in a binary file. Smart enough to\n relocate itself.\n \"\"\"\n def __init__(self, owner, symbol, addr, r_type, addend=None):\n super(Relocation, self).__init__()\n self.owner_obj = owner\n self.arch = owner.arch\n self.symbol = symbol\n self.addr = addr\n self.type = r_type\n self.is_rela = addend is not None\n self._addend = addend\n self.resolvedby = None\n self.resolved = False\n if self.symbol is not None and self.symbol.is_import:\n self.owner_obj.imports[self.symbol.name] = self\n\n @property\n def addend(self):\n if self.is_rela:\n return self._addend\n else:\n return self.owner_obj.memory.read_addr_at(self.addr)\n\n def resolve(self, obj):\n self.resolvedby = obj\n self.resolved = True\n if self.symbol is not None:\n self.symbol.resolve(obj)\n\n @property\n def rebased_addr(self):\n return self.addr + self.owner_obj.rebase_addr\n\n def relocate(self, solist):\n \"\"\"\n Applies this relocation. Will make changes to the memory object of the\n object it came from.\n\n @param solist A list of objects from which to resolve symbols\n \"\"\"\n if self.type == 'mips_local':\n return self.reloc_mips_local()\n elif self.type == 'mips_global':\n return self.reloc_mips_global(solist)\n elif self.type in self.arch.reloc_s:\n return self.reloc_global(solist)\n elif self.type in self.arch.reloc_s_a:\n return self.reloc_absolute(solist)\n elif self.type in self.arch.reloc_b_a:\n return self.reloc_relative()\n elif self.type in self.arch.reloc_copy:\n return self.reloc_copy(solist)\n elif self.type in self.arch.reloc_tls_mod_id:\n return self.reloc_tls_mod_id()\n elif self.type in self.arch.reloc_tls_offset:\n return self.reloc_tls_offset()\n else:\n l.warning(\"Unknown reloc type: %d\", self.type)\n\n def reloc_global(self, solist):\n if not self.resolve_symbol(solist):\n return False\n self.owner_obj.memory.write_addr_at(self.addr, self.resolvedby.rebased_addr)\n return True\n\n def reloc_absolute(self, solist):\n if not self.resolve_symbol(solist):\n return False\n self.owner_obj.memory.write_addr_at(self.addr, self.resolvedby.rebased_addr)\n return True\n\n def reloc_relative(self):\n self.owner_obj.memory.write_addr_at(self.addr, self.addend + self.owner_obj.rebase_addr)\n self.resolve(None)\n return True\n\n def reloc_copy(self, solist):\n if not self.resolve_symbol(solist):\n return False\n val = self.resolvedby.owner_obj.memory.read_addr_at(self.resolvedby.addr)\n self.owner_obj.memory.write_addr_at(self.addr, val)\n return True\n\n def reloc_tls_mod_id(self):\n self.owner_obj.memory.write_addr_at(self.addr, self.owner_obj.tls_module_id)\n self.resolve(None)\n return True\n\n @staticmethod\n def reloc_tls_offset():\n return False\n\n def reloc_mips_global(self, solist):\n if not self.resolve_symbol(solist):\n return False\n #delta = -self.owner_obj._dynamic['DT_MIPS_BASE_ADDRESS']\n addr = self.addr #+ delta\n # this causes crashes when not using the ld_fallback, for some reason\n self.owner_obj.memory.write_addr_at(addr, self.resolvedby.rebased_addr)\n return True\n\n def reloc_mips_local(self):\n if self.owner_obj.rebase_addr == 0:\n self.resolve(None)\n return True # don't touch local relocations on the main bin\n delta = self.owner_obj.rebase_addr - self.owner_obj._dynamic['DT_MIPS_BASE_ADDRESS']\n if delta == 0:\n self.resolve(None)\n return True\n elif delta < 0:\n raise CLEOperationError(\"We are relocating a MIPS object at a lower address than\"\n \" its static base address. This is weird.\")\n val = self.owner_obj.memory.read_addr_at(self.addr)\n if val == 0:\n l.error(\"Address in local GOT at %#x is 0?\", self.rebased_addr)\n return False\n newval = val + delta\n self.owner_obj.memory.write_addr_at(self.addr, newval)\n self.resolve(None)\n return True\n\n def resolve_symbol(self, solist):\n weak_result = None\n for so in solist:\n symbol = so.get_symbol(self.symbol.name)\n if symbol is not None and symbol.is_export:\n if symbol.binding == 'STB_GLOBAL':\n self.resolve(symbol)\n return True\n elif weak_result is None:\n weak_result = symbol\n\n if weak_result is not None:\n self.resolve(weak_result)\n return True\n\n # If that doesn't do it, we also look into local symbols\n for so in solist:\n symbol = so.get_symbol(self.symbol.name)\n if symbol is not None and symbol is not self.symbol and symbol.addr != 0:\n l.warning(\"Matched %s to local symbol of %s. Is this possible?\", self.symbol.name, so.binary)\n self.resolve(symbol)\n return True\n return False\n\nclass AbsObj(object):\n __metaclass__ = ABCMeta\n\n \"\"\"\n Main abstract class for CLE binary objects.\n \"\"\"\n\n def __init__(self, binary, compatible_with=None, filetype='unknown', **kwargs):\n \"\"\"\n args: binary\n kwargs: {load=True, custom_base_addr=None, custom_entry_point=None,\n custom_offset=None}\n \"\"\"\n\n # Unfold the kwargs and convert them to class attributes\n for k,v in kwargs.iteritems():\n setattr(self, k, v)\n\n self.binary = binary\n self._entry = None\n self.segments = [] # List of segments\n self.sections = [] # List of sections\n self.sections_map = {} # Mapping from section name to section\n self.symbols_by_addr = {}\n self.imports = {}\n self.resolved_imports = []\n self.relocs = []\n self.jmprel = {}\n self.symbols = None # Object's symbols\n self.arch = None\n self.filetype = filetype\n self.os = 'windows' if self.filetype == 'pe' else 'unix'\n self.compatible_with = compatible_with\n\n # These are set by cle, and should not be overriden manually\n self.rebase_addr = 0 # not to be set manually - used by CLE\n self.tls_module_id = None\n\n self.object_type = None\n self.deps = [] # Needed shared objects (libraries dependencies)\n self.linking = None # Dynamic or static linking\n self.requested_base = None\n self.pic = False\n\n # Custom options\n self._custom_entry_point = kwargs.get('custom_entry_point', None)\n self.provides = None\n\n self.memory = None\n self.ppc64_initial_rtoc = None\n\n custom_arch = kwargs.get('custom_arch', None)\n if custom_arch is None:\n self.arch = None\n elif isinstance(custom_arch, str):\n self.set_arch(archinfo.arch_from_id(custom_arch))\n elif isinstance(custom_arch, archinfo.Arch):\n self.set_arch(custom_arch)\n elif isinstance(custom_arch, type) and issubclass(custom_arch, archinfo.Arch):\n self.set_arch(custom_arch())\n else:\n raise CLEError(\"Bad parameter: custom_arch=%s\" % custom_arch)\n\n supported_filetypes = []\n\n def __repr__(self):\n return '<%s Object %s, maps [%#x:%#x]>' % (self.__class__.__name__, os.path.basename(self.binary), self.get_min_addr() + self.rebase_addr, self.get_max_addr() + self.rebase_addr)\n\n def set_arch(self, arch):\n if self.compatible_with is not None and self.compatible_with.arch != arch:\n raise CLECompatibilityError(\"Binary %s not compatible with arch %s\" % (self.binary, self.compatible_with.arch))\n self.arch = arch\n self.memory = Clemory(arch) # Private virtual address space, without relocations\n\n @property\n def entry(self):\n if self._custom_entry_point is not None:\n return self._custom_entry_point + self.rebase_addr\n return self._entry + self.rebase_addr\n\n def contains_addr(self, addr):\n \"\"\" Is @vaddr in one of the binary's segments we have loaded ?\n (i.e., is it mapped into memory ?)\n\n WARNING: in the case of relocatable objects (e.g., libraries), this\n function works with relative addresses (wrt the start of the object).\n Remember that statically, the Elf headers define a virtual address of 0\n for relocatable objects.\n\n If you try to use this function with a runtime address of a relocated\n object, you should consider substracting the rebase_addr value to @addr\n beforehands.\n \"\"\"\n for i in self.segments:\n if i.contains_addr(addr):\n return True\n return False\n\n def find_segment_containing(self, vaddr):\n \"\"\" Returns the segment that contains @vaddr, or None \"\"\"\n for s in self.segments:\n if s.contains_addr(vaddr):\n return s\n\n def find_section_containing(self, vaddr):\n \"\"\" Returns the section that contains @vaddr, or None \"\"\"\n for s in self.sections:\n if s.contains_addr(vaddr):\n return s\n\n def addr_to_offset(self, addr):\n for s in self.segments:\n if s.contains_addr(addr):\n return s.addr_to_offset(addr)\n return None\n\n def offset_to_addr(self, offset):\n for s in self.segments:\n if s.contains_offset(offset):\n return s.offset_to_addr(offset)\n\n def get_min_addr(self):\n \"\"\"\n Return the virtual address of the segment that has the lowest address.\n WARNING: this is calculated BEFORE rebasing the binaries, therefore,\n this is only relevant to executable files, as shared libraries should always\n have 0 as their text segment load addresseses.\n \"\"\"\n\n out = None\n for segment in self.segments:\n if out is None or segment.min_addr < out:\n out = segment.min_addr\n return out\n\n def get_max_addr(self):\n \"\"\" This returns the highest virtual address contained in any loaded\n segment of the binary, BEFORE rebasing.\n\n NOTE: relocation is taken into consideration by ld, not here.\n \"\"\"\n\n out = None\n for segment in self.segments:\n if out is None or segment.max_addr > out:\n out = segment.max_addr\n return out\n\n def set_got_entry(self, symbol_name, newaddr):\n '''\n This overrides the address of the function defined by @symbol with\n the new address @newaddr.\n This is used to call simprocedures instead of actual code\n '''\n\n if symbol_name not in self.imports:\n l.warning(\"Could not override the address of symbol %s: symbol entry not \"\n \"found in GOT\", symbol_name)\n return\n\n self.memory.write_addr_at(self.imports[symbol_name].addr, newaddr)\n\n","sub_path":"cle/absobj.py","file_name":"absobj.py","file_ext":"py","file_size_in_byte":15029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"165587035","text":"import os\nimport argparse\nimport sys\n\ndef get_location(text):\n lines = text.split(\"\\n\")\n res = []\n for line in lines:\n if not line.startswith(\"~~ location\"):\n break\n _, _, key, path = line.split()\n res.append((key, path))\n return res\n\ndef render(text, key):\n lines = text.split(\"\\n\")\n res = []\n\n in_flag = True\n for line in lines:\n if not line.startswith(\"~~\"):\n if in_flag:\n res.append(line)\n continue\n args = line.split()\n if args[1] == \"location\":\n continue\n elif args[1] == \"contentstart\":\n if args[2] != key:\n in_flag = False\n elif args[1] == \"contentend\":\n if args[2] != key:\n in_flag = True\n elif args[1] == \"include\":\n res.extend(render(open(args[2], 'r', encoding='utf-8').read(), key))\n else:\n raise RuntimeError(\"Unknown tags %s\" % args[1])\n return res\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--check', action='store_true', dest='check')\n cargs = parser.parse_args()\n\n for filename in os.listdir(\"./\"):\n if not filename.endswith(\".md\") and not filename.endswith(\".rst\"):\n continue\n print(filename)\n file = open(filename, \"r\", encoding='utf-8').read()\n\n locations = get_location(file)\n for key, path in locations:\n text = render(file, key)\n if cargs.check:\n realtext = open(path, 'r', encoding='utf-8').read().split(\"\\n\")\n if realtext[-1] != \"\" or len(text) + 1 != len(realtext):\n print(\"Line number\")\n print(\"\\t%s: %d\" % (path, len(text)))\n print(\"\\t%s: %d\" % (filename, len(realtext) - 1))\n raise ValueError(\"It seems docs [%s] is not synced with metadocs [%s]. Please change metadocs and then run update_docs !\" % (path, filename))\n for i, (t, rt) in enumerate(zip(text, realtext)):\n if t != rt:\n print(\"At Line %d:\" % i)\n print(\"\\t%s: %s\" % (path, t))\n print(\"\\t%s: %s\" % (filename, rt))\n raise ValueError(\"It seems docs [%s] is not synced with metadocs [%s]. Please change metadocs and then run update_docs !\" % (path, filename))\n else:\n open(path, 'w', encoding='utf-8').write(\"\\n\".join(text) + \"\\n\")\n print(\"render %s with %s\" % (path, key))\n","sub_path":"docs/meta/update_doc.py","file_name":"update_doc.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"638793973","text":"#proj2.py\nfrom bs4 import BeautifulSoup\nimport urllib.request\nfrom urllib.request import urlopen\nimport ssl\n\n#### Problem 1 ####\nprint('\\n*********** PROBLEM 1 ***********')\nprint('New York Times -- First 10 Story Headings\\n')\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = 'http://www.nytimes.com'\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\nheadlines = soup.find_all(class_ = \"story-heading\")\nfor (headline, i) in zip(headlines, range(1, 11)):\n\tif headline.a:\n\t\tprint(headline.a.text.replace(\"\\n\", \" \").strip())\n\telse:\n\t\tprint(headline.contents[0].strip())\n\n#### Problem 2 ####\nprint('\\n*********** PROBLEM 2 ***********')\nprint('Michigan Daily -- MOST READ\\n')\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = 'https://www.michigandaily.com/'\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\nheadlines = soup.find_all(\"div\", class_ = \"view view-most-read view-id-most_read view-display-id-panel_pane_1 view-dom-id-99658157999dd0ac5aa62c2b284dd266\")\nfor headline in headlines:\n\tprint (headline.get_text())\n\n#### Problem 3 ####\nprint('\\n*********** PROBLEM 3 ***********')\nprint(\"Mark's page -- Alt tags\\n\")\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = 'http://newmantaylor.com/gallery.html'\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\nimgs = soup.find_all('img')\nfor img in imgs:\n\ttry:\n\t\talt_text = img['alt']\n\t\tprint(alt_text)\n\texcept:\n\t\tprint('No alternative text provided!!')\n\n\n#### Problem 4 ####\nprint('\\n*********** PROBLEM 4 ***********')\nprint(\"UMSI faculty directory emails\\n\")\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nprefix = \"https://\"\nhost = \"www.si.umich.edu\"\ncount = 1\n\ndef print_email(href, count):\n\turl = prefix + host + href\n\treq = urllib.request.Request(url, None, {'User-Agent':'SI_CLASS'})\n\thtml = urlopen(req, context=ctx).read()\n\tsoup = BeautifulSoup(html, \"html.parser\")\n\n\temails = soup.find_all('div', class_ = \"field field-name-field-person-email field-type-email field-label-inline clearfix\")\n\tfor email in emails:\n\t\tprof_email = email.find('div', class_ = 'field-item even')\n\t\tprint(count, prof_email.get_text())\n\ndef faculty_email(link_href, count):\n\turl = prefix + host + link_href\n\treq = urllib.request.Request(url, None, {'User-Agent':'SI_CLASS'})\n\thtml = urlopen(req, context=ctx).read()\n\tsoup = BeautifulSoup(html, \"html.parser\")\n\tcontact_details = soup.find_all('div', class_ = 'field field-name-contact-details field-type-ds field-label-hidden')\n\tfor contact in contact_details:\n\t\tprof = contact.find('div', class_ = 'field-item even')\n\t\thref = prof.a['href']\n\t\tprint_email(href, count)\n\t\tcount += 1\n\tnext_link = soup.find('li', class_ = 'pager-next last')\n\tif next_link.a:\n\t\tlink_href = next_link.a['href']\n\t\tfaculty_email(link_href, count)\n\telse:\n\t\texit()\n\ninitial_href = '/directory?field_person_firstname_value=&field_person_lastname_value=&rid=4'\nfaculty_email(initial_href, count)\n\n\n\n","sub_path":"proj2.py","file_name":"proj2.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"459479945","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\n\nclass BonanzaSpider(scrapy.Spider):\n name = 'bonanza'\n start_urls = ['https://www.bonanzasatrangi.com/pk/unstitched/','https://www.bonanzasatrangi.com/pk/pret/','https://www.bonanzasatrangi.com/pk/kids/','https://www.bonanzasatrangi.com/pk/accessories/dupatta/','https://www.bonanzasatrangi.com/pk/accessories/shalwar/','https://www.bonanzasatrangi.com/pk/accessories/trouser/','https://www.bonanzasatrangi.com/pk/accessories/jeggings/']\n\n def parse(self, response):\n i=response.url\n cat_name={}\n if re.search(\"(?i)Unstitched\", i):\n cat_name={\"cat_name\": \"Unstitched\"}\n elif re.search(\"(?i)Pret\", i):\n cat_name={\"cat_name\": \"IDEAS PRET\"}\n elif re.search(\"(?i)kid\", i):\n cat_name={\"cat_name\": \"KIDS\"}\n elif re.search(\"(?i)dupatta\", i):\n cat_name={\"cat_name\": \"Stole/Shawl\"}\n elif re.search(\"(?i)shalwar\", i) or re.search(\"(?i)trouser\", i) or re.search(\"(?i)jeggings\", i):\n cat_name={\"cat_name\": \"SALT\"}\n yield scrapy.Request(i, callback=self.all_products, meta=cat_name)\n\n def all_products(self,response):\n prod_page_urls=response.xpath('//*[@class=\"product-name\"]/a/@href').extract()\n for url in prod_page_urls:\n yield scrapy.Request(url, callback=self.product_page, meta=response.meta)\n next_page=response.xpath('//*[@class=\"action next\"]/@href').extract_first()\n if next_page!=None:\n yield scrapy.Request(next_page, callback=self.all_products, meta=response.meta)\n\n\n def product_page(self,response):\n converted_price=0\n img_url=response.xpath('//*[@class=\"MagicZoom\"]/@href').extract_first()\n title=response.xpath('//*[@class=\"product-name\"]/span/text()').extract_first()\n price=response.xpath('//*[@itemprop=\"price\"]/span/text()').extract_first()\n if price!=None:\n match = re.search(r'([\\D]+)([\\d,]+)',price)\n converted_price=int(match.group(2).replace(',',''))\n prod_page=response.url\n\n yield {\"img_url\":img_url,\n \"title\":title,\n \"Price\":converted_price,\n \"prod_page\":prod_page,\n 'cat_name': response.meta['cat_name'],\n \"Brand\":\"Bonanza Satrangi\"\n\n }\n","sub_path":"Scrapers/gulahmed_store/spiders/bonanza.py","file_name":"bonanza.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"218514844","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('receipt',views.ListUserPaymentReceiptView.as_view(),name = 'details'),\n path('receipt/add/',views.CreateUserPaymentReceiptView.as_view(),name = 'add'),\n path('receipt//edit/',views.UpdateUserPaymentReceiptView.as_view(),name = 'put'),\n\n path('package',views.ListEmployeePackageView.as_view(),name = 'details'),\n path('package/add/',views.CreateEmployeePackageView.as_view(),name = 'add'),\n path('package//edit/',views.UpdateEmployeePackageView.as_view(),name = 'put'),\n\n path('bill',views.ListUserEmployeePaymentBillView.as_view(),name = 'details'),\n path('bill/add/',views.CreateUserEmployeePaymentBillView.as_view(),name = 'add'),\n path('bill//edit/',views.UpdateUserEmployeePaymentBillView.as_view(),name = 'put'),\n \n\n]","sub_path":"payroll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"322515636","text":"r\"\"\"Venti - small and speedy web-projects.\"\"\"\n\nfrom . import utils\nfrom os import path\nfrom threading import local\nfrom traceback import format_exc\nfrom werkzeug import http\nfrom werkzeug import urls\nfrom werkzeug import useragents\nfrom werkzeug.formparser import parse_form_data\nimport logging\nimport sys\n\n\nthis = local()\nlogger = logging.getLogger(name=__name__)\n\n\nclass Request(object):\n\n r\"\"\"Request object that wraps around the WSGI evironment.\n\n Our recommandation is that you use the helper methods provided by this\n package to read from the request. Alternativly you can use\n :func:`get_request` method to retrieve the current Request in the\n active thread.\n\n **Parameters**\n\n :param environ: WSGI environment.\n :type environ: dict\n\n **Attributes**\n\n :ivar _environ: Original WSGI environment.\n :ivar cookies: A dictionary containing all cookies.\n :ivar host: The hostname of the server.\n :ivar method: Request method (GET, POST, etc.).\n :ivar path: Requested path (/some/article).\n :ivar query: Query dictionary (?some=true).\n :ivar form: Form dictionary, using POST, PUT, etc.\n :ivar json: JSON dictionary, if the request was an `application/json`\n content-type request.\n :ivar params: Dictionary containing all the input (query, form, json).\n :ivar files: Dictionary containing all the form files.\n :ivar user_agent: A werkzeug `UserAgent`_ instance.\n :ivar files: Dictionary containing all the form files.\n\n :ivar accept_type: The HTTP_ACCEPT header of the request, what your\n requester accepts in return (application/json or text/html).\n :ivar content_type: The HTTP_CONTENT_TYPE header, what your requester has\n send to you (application/json or application/x-www-form-urlencoded).\n\n .. _UserAgent: http://werkzeug.pocoo.org/docs/utils/\\\n #werkzeug.useragents.UserAgent\n \"\"\"\n\n def __init__(self, environ):\n self._environ = environ\n self.cookies = http.parse_cookie(environ)\n\n self.host = environ['HTTP_HOST']\n self.method = environ['REQUEST_METHOD']\n self.path = environ['PATH_INFO']\n\n self.query = utils.flatten_multidict(\n urls.url_decode(environ['QUERY_STRING']))\n\n stream, form, files = parse_form_data(environ)\n\n self.form = utils.flatten_multidict(form)\n self.files = utils.flatten_multidict(files,\n lambda v: len(v.filename),\n _update_file)\n self.params = dict(self.query.items() + self.form.items() +\n self.files.items())\n self.user_agent = useragents.UserAgent(environ)\n\n self.accept_type = environ.get('HTTP_ACCEPT', '')\n self.content_type = environ.get('HTTP_CONTENT_TYPE', '')\n\n if 'application/json' in self.content_type:\n self.json = utils.json_loads(stream.read())\n self.params.update(self.json)\n else:\n self.json = None\n\n\nclass Response(object):\n\n r\"\"\"Response object that wraps around the WSGI evironment.\n\n Our recommandation is that you use the helper methods provided by this\n package to write to the request. Alternativly you can use\n :func:`get_response` method to retrieve the current Response in the\n active thread.\n\n **Parameters**\n\n :param environ: WSGI environment.\n :param start_response: WSGI start-response callable.\n :type environ: dict\n :type start_response: callable\n\n **Attributes**\n\n :ivar _environ: Original WSGI environment.\n :ivar _start_response: Original WSGI start_response callback.\n :ivar charset: The encoding charset to respond with.\n Defaults to `'utf-8'`.\n :ivar status_code: The status-code of the response. This is the integer\n part to the status code, the full line can be accessed through the\n :meth:`Response.status` attribute.\n :ivar headers: An :class:`utils.HeadersDict` dictionary that will contain\n all the response headers.\n Defaults to `{'content-type': 'text/html'}`.\n :ivar body: The body to respond with. This will be encoded using the active\n charset when :meth:`Response.respond` is called.\n\n \"\"\"\n\n def __init__(self, environ, start_response):\n self._environ = environ\n self._start_response = start_response\n\n self.charset = 'utf-8'\n self.status_code = 200\n self.headers = utils.HeadersDict()\n self.headers['content-type'] = 'text/html'\n self.body = ''\n\n @property\n def status(self):\n r\"\"\"The status-code of the response with a HTTP status message.\n\n **Parameters**\n\n :rtype: str\n\n **Basic Examples** ::\n\n '200 OK'\n '404 Not Found'\n\n \"\"\"\n return '{:d} {:s}'.format(self.status_code,\n http.HTTP_STATUS_CODES[self.status_code])\n\n def respond(self):\n r\"\"\"Start the WSGI response.\"\"\"\n self._start_response(self.status, self.headers.to_list())\n\n if self.charset is not None:\n if self.body is None:\n return [u''.encode(self.charset)]\n else:\n return [self.body.encode(self.charset)]\n else:\n if self.body is None:\n return [u'']\n else:\n return [self.body]\n\n\ndef setup(environ, start_response):\n r\"\"\"Setup the local thread.\n\n **Parameters**\n\n :param environ: The WSGI environ parameter.\n :param start_response: Start the response callable.\n :type environ: dict\n :type start_response: callable\n :rtype: Request\n\n \"\"\"\n setattr(this, 'request', Request(environ))\n setattr(this, 'response', Response(environ, start_response))\n setattr(this, 'data', dict())\n\n return get_request()\n\n\ndef get_request():\n r\"\"\"Retrieve the Request from the local thread.\n\n **Parameters**\n\n :rtype: Request\n \"\"\"\n return getattr(this, 'request')\n\n\ndef get_response():\n r\"\"\"Retrieve the Response from the local thread.\n\n **Parameters**\n\n :rtype: Response\n \"\"\"\n return getattr(this, 'response')\n\n\ndef params():\n r\"\"\"Retrieve the parameters of the Request.\"\"\"\n return get_request().params\n\n\ndef respond():\n r\"\"\"Respond with the current state of the Response object.\"\"\"\n return get_response().respond()\n\n\ndef clear():\n r\"\"\"Remove all content from the response body.\"\"\"\n get_response().body = ''\n\n\ndef echo(*args):\n r\"\"\"Add content to the response body.\n\n Multiple arguments are joined with a space ' '. No new line is automaticly\n added.\n\n **Parameters**\n\n :param \\*args: One or more items to add to the body.\n :type \\*args: list of str\n\n **Basic Usage** ::\n\n venti.echo('One', 'two', 'three')\n # 'One two three'\n\n \"\"\"\n get_response().body += ' '.join([unicode(a) for a in args])\n\n\ndef json(value, status=None):\n r\"\"\"Respond with JSON.\n\n Automaticly dumps the value as JSON and sets the correct content-type.\n\n **Parameters**\n\n :param value: Value to dump.\n :param status: New status code.\n Defaults to `None`.\n :type value: mixed\n :type status: int or None.\n\n **Basic Usage** ::\n\n venti.json({'name': 'Venti'})\n # '{\"name\": \"Venti\"}'\n\n \"\"\"\n header('content-type', 'application/json')\n if status is not None:\n status_code(status)\n get_response().body = utils.json_dumps(value)\n\n\ndef exception(clear_response=True):\n r\"\"\"Format exception and add it to the response body.\"\"\"\n exc_type, exc, trace = sys.exc_info()\n if clear_response:\n clear()\n\n server_error()\n echo('
')\n    echo(format_exc())\n\n    logger.exception(exc)\n\n    sys.exc_clear()\n\n\ndef header(key, value):\n    r\"\"\"Attach a header to the response.\n\n    This will overwrite a previous set header with the same key.\n\n    **Parameters**\n\n    :param key: Name of the header like 'Content-Type' or 'Location'.\n    :param value: Value of the header, like 'http://google.com'.\n    :type key: str\n    :type value: str\n\n    **Basic Usage** ::\n\n        venti.header('location', 'http://google.com')\n        venti.header('content-type', 'application/pdf')\n\n    \"\"\"\n    get_response().headers[key] = value\n\n\ndef set_cookie(name, value='', max_age=None,\n               path='/', domain=None, secure=False, httponly=True):\n    r\"\"\"Set a cookie in the response.\n\n    You can only set one cookie at a time!\n\n    **Parameters**\n\n    :param name: Name of the cookie.\n    :param value: Cookie value (should always be a string).\n    :param max_age: In seconds, how long the cookie should last, or `None` if\n        the cookie should last as long as the browser session.\n        Defaults to `None`.\n    :param path: Limit the cookie to a specific path.\n        Defaults to `'/'`.\n    :param domain: Set it to `.example.com` to set it as a cross-domain cookie.\n        Otherwise it's bound to a specific (or current) domain.\n        Defaults to `None`.\n    :param secure: If `True`, the cookie is only available via HTTPS.\n        Defaults to `False`.\n    :param httponly: If `True`, disallows JavaScript to access the cookie.\n        Defaults to `True`.\n    :type name: str\n    :type value: str\n    :type max_age: int or None\n    :type path: str\n    :type domain: str or None\n    :type secure: bool\n    :type httponly: bool\n\n    **Basic Usage** ::\n\n        venti.set_cookie('session_id', 6001,\n                          max_age=60 * 60 * 8,  # 8 hours\n                          secure=get_request().is_secure)\n\n    \"\"\"\n    header('set-cookie', http.dump_cookie(\n        name, value=value, max_age=max_age,\n        path=path, domain=domain,\n        secure=secure, httponly=httponly,\n        charset=get_response().charset, sync_expires=True))\n\n\ndef get_cookie(name):\n    r\"\"\"Retrieve the value of a cookie from the request.\n\n    **Parameters**\n\n    :param name: The name of the cookie.\n    :type name: str\n    :rtype: str\n\n    **Basic Usage** ::\n\n        try:\n            session_id = venti.get_cookie('session_id')\n        except KeyError as err:\n            pass  # session_id not available\n        else:\n            pass  # session_id available\n\n    \"\"\"\n    return get_request().cookies[name]\n\n\ndef del_cookie(name, path='/', domain=None, secure=False,\n               httponly=True):\n    r\"\"\"Remove a cookie from the jar.\n\n    This wil simply overwrite a currently set cookie with a zero age and\n    zero value. Make sure you match `path`, `domain`, `secure` and `httponly`\n    with the cookie that is set.\n\n    **Parameters**\n\n    :param name: Name of the cookie.\n    :param path: Limit the cookie to a specific path.\n        Defaults to `'/'`.\n    :param domain: Set it to `.example.com` to set it as a cross-domain cookie.\n        Otherwise it's bound to a specific (or current) domain.\n        Defaults to `None`.\n    :param secure: If `True`, the cookie is only available via HTTPS.\n        Defaults to `False`.\n    :param httponly: If `True`, disallows JavaScript to access the cookie.\n        Defaults to `True`.\n    :type name: str\n    :type path: str\n    :type domain: str or None\n    :type secure: bool\n    :type httponly: bool\n\n    **Basic Usage** ::\n\n        venti.del_cookie('session_id',\n                         secure=get_request().is_secure)\n\n    \"\"\"\n    set_cookie(name, max_age=0, path=path, domain=domain,\n               secure=secure, httponly=httponly)\n\n\ndef status_code(code):\n    r\"\"\"Set the response status-code.\n\n    **Parameters**\n\n    :param code: The new status-code of the response.\n    :type code: int\n    \"\"\"\n    get_response().status_code = code\n\n\ndef redirect(location, status=302):\n    status_code(302)\n    header('Location', location)\n\n\ndef unauthorized():\n    r\"\"\"Respond with a 401 - Unauthorized status.\"\"\"\n    status_code(401)\n\n\ndef forbidden():\n    r\"\"\"Respond with a 403 - Forbidden status.\"\"\"\n    status_code(403)\n\n\ndef not_found():\n    r\"\"\"Respond with a 404 - Not Found status.\"\"\"\n    status_code(404)\n\n\ndef server_error():\n    r\"\"\"Respond with a 500 - Internal Server Error status.\"\"\"\n    status_code(500)\n\n\ndef store(name, value):\n    getattr(this, 'data')[name] = value\n\n\ndef retrieve(name, default=None):\n    return getattr(this, 'data').get(name, default)\n\n\ndef _update_file(filestorage):\n    filestorage.secure_filename = path.basename(filestorage.filename)\n    return filestorage\n","sub_path":"venti/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":12389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"524247969","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom rest_framework import viewsets\n\nfrom .serializers import BookSerializer\nfrom .models import Book\nfrom .forms import AddBook\n\n\ndef index(request):\n    \"\"\"method is_voted to Book model.\n    Checks, if user already voted for the Book\"\"\"\n\n    if not request.user.is_authenticated():\n        return redirect(LOGIN_URL)\n    data = {'books': Book.objects.all()}\n    return render(request, 'books/index.html', data)\n\n\nLOGIN_URL = '/login'\nCATALOG_URL = '/books'\n\n\nclass BookViewSet(viewsets.ModelViewSet):\n    queryset = Book.objects.all()\n    serializer_class = BookSerializer\n\n\ndef new_book(request):\n    if not request.user.is_authenticated():\n        return redirect(LOGIN_URL)\n    if request.method == 'POST':\n        form = AddBook(request.POST, request.FILES)\n        if form.is_valid():\n            book = Book(\n                book_name=form.cleaned_data['book_name'],\n                author=form.cleaned_data['author'],\n                book_year=form.cleaned_data['book_year'],\n                isbn=form.cleaned_data['isbn'],\n                page_count=form.cleaned_data['page_count'],\n                voting_closed=False,\n                image=request.FILES['image']\n            )\n            book.save()\n            return HttpResponseRedirect(CATALOG_URL)\n    else:\n        form = AddBook()\n    return render(request, 'books/new_book.html', {'form': form})\n\n\ndef detail(request, book_id):\n    if request.method == 'GET':\n        book = get_object_or_404(Book, id=book_id)\n        return render(request, 'books/book_detail.html', {'book': book})\n\n\ndef vote(request, book_id):\n    if not request.user.is_authenticated():\n        return redirect(LOGIN_URL)\n    book = Book.objects.get(id=book_id)\n    if request.user in book.voters.all():\n        book.voters.remove(request.user)\n    else:\n        book.voters.add(request.user)\n    book.save()\n    return HttpResponseRedirect(CATALOG_URL)\n\n","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"74877413","text":"\"\"\"LoaderPool class.\n\nChunkLoader has one or more of these. They load data in worker pools.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom concurrent.futures import (\n    CancelledError,\n    Future,\n    ProcessPoolExecutor,\n    ThreadPoolExecutor,\n)\nfrom typing import TYPE_CHECKING, Callable, Dict, List, Optional, Union\n\n# Executor for either a thread pool or a process pool.\nPoolExecutor = Union[ThreadPoolExecutor, ProcessPoolExecutor]\n\nLOGGER = logging.getLogger(\"napari.loader\")\n\nDoneCallback = Optional[Callable[[Future], None]]\n\nif TYPE_CHECKING:\n    from napari.components.experimental.chunk._request import ChunkRequest\n\n\nclass LoaderPool:\n    \"\"\"Loads chunks asynchronously in worker threads or processes.\n\n    We cannot call np.asarray() in the GUI thread because it might block on\n    IO or a computation. So we call np.asarray() in _chunk_loader_worker()\n    instead.\n\n    Parameters\n    ----------\n    config : dict\n        Our configuration, see napari.utils._octree.py for format.\n    on_done_loader : Callable[[Future], None]\n        Called when a future finishes.\n\n    Attributes\n    ----------\n    force_synchronous : bool\n        If True all requests are loaded synchronously.\n    num_workers : int\n        The number of workers.\n    use_processes | bool\n        Use processess as workers, otherwise use threads.\n    _executor : PoolExecutor\n        The thread or process pool executor.\n    _futures : Dict[ChunkRequest, Future]\n        In progress futures for each layer (data_id).\n    _delay_queue : DelayQueue\n        Requests sit in here for a bit before submission.\n    \"\"\"\n\n    def __init__(\n        self, config: dict, on_done_loader: DoneCallback = None\n    ) -> None:\n        from napari.components.experimental.chunk._delay_queue import (\n            DelayQueue,\n        )\n\n        self.config = config\n        self._on_done_loader = on_done_loader\n\n        self.num_workers: int = int(config['num_workers'])\n        self.use_processes: bool = bool(config.get('use_processes', False))\n\n        self._executor: PoolExecutor = _create_executor(\n            self.use_processes, self.num_workers\n        )\n        self._futures: Dict[ChunkRequest, Future] = {}\n        self._delay_queue = DelayQueue(config['delay_queue_ms'], self._submit)\n\n    def load_async(self, request: ChunkRequest) -> None:\n        \"\"\"Load this request asynchronously.\n\n        Parameters\n        ----------\n        request : ChunkRequest\n            The request to load.\n        \"\"\"\n        # Add to the DelayQueue which will call our self._submit() method\n        # right away, if zero delay, or after the configured delay.\n        self._delay_queue.add(request)\n\n    def cancel_requests(\n        self, should_cancel: Callable[[ChunkRequest], bool]\n    ) -> List[ChunkRequest]:\n        \"\"\"Cancel pending requests based on the given filter.\n\n        Parameters\n        ----------\n        should_cancel : Callable[[ChunkRequest], bool]\n            Cancel the request if this returns True.\n\n        Returns\n        -------\n        List[ChunkRequests]\n            The requests that were cancelled, if any.\n        \"\"\"\n        # Cancelling requests in the delay queue is fast and easy.\n        cancelled = self._delay_queue.cancel_requests(should_cancel)\n\n        num_before = len(self._futures)\n\n        # Cancelling futures may or may not work. Future.cancel() will\n        # return False if the worker is already loading the request and it\n        # cannot be cancelled.\n        for request in list(self._futures.keys()):\n            if self._futures[request].cancel():\n                del self._futures[request]\n                cancelled.append(request)\n\n        num_after = len(self._futures)\n        num_cancelled = num_before - num_after\n\n        LOGGER.debug(\n            \"cancel_requests: %d -> %d futures (cancelled %d)\",\n            num_before,\n            num_after,\n            num_cancelled,\n        )\n\n        return cancelled\n\n    def _submit(self, request: ChunkRequest) -> Optional[Future]:\n        \"\"\"Initiate an asynchronous load of the given request.\n\n        Parameters\n        ----------\n        request : ChunkRequest\n            Contains the arrays to load.\n        \"\"\"\n        # Submit the future. Have it call self._done when finished.\n        future = self._executor.submit(_chunk_loader_worker, request)\n        future.add_done_callback(self._on_done)\n        self._futures[request] = future\n\n        LOGGER.debug(\n            \"_submit_async: %s elapsed=%.3fms num_futures=%d\",\n            request.location,\n            request.elapsed_ms,\n            len(self._futures),\n        )\n\n        return future\n\n    def _on_done(self, future: Future) -> None:\n        \"\"\"Called when a future finishes.\n\n        future : Future\n            This is the future that finished.\n        \"\"\"\n        try:\n            request = self._get_request(future)\n        except ValueError:\n            return  # Pool not running? App exit in progress?\n\n        if request is None:\n            return  # Future was cancelled, nothing to do.\n\n        # Tell the loader this request finished.\n        if self._on_done_loader is not None:\n            self._on_done_loader(request)\n\n    def shutdown(self) -> None:\n        \"\"\"Shutdown the pool.\"\"\"\n        # Avoid crashes or hangs on exit.\n        self._delay_queue.shutdown()\n        self._executor.shutdown(wait=True)\n\n    @staticmethod\n    def _get_request(future: Future) -> Optional[ChunkRequest]:\n        \"\"\"Return the ChunkRequest for this future.\n\n        Parameters\n        ----------\n        future : Future\n            Get the request from this future.\n\n        Returns\n        -------\n        Optional[ChunkRequest]\n            The ChunkRequest or None if the future was cancelled.\n        \"\"\"\n        try:\n            # Our future has already finished since this is being\n            # called from Chunk_Request._done(), so result() will\n            # never block. But we can see if it finished or was\n            # cancelled. Although we don't care right now.\n            return future.result()\n        except CancelledError:\n            return None\n\n\ndef _create_executor(use_processes: bool, num_workers: int) -> PoolExecutor:\n    \"\"\"Return the thread or process pool executor.\n\n    Parameters\n    ----------\n    use_processes : bool\n        If True use processes, otherwise threads.\n    num_workers : int\n        The number of worker threads or processes.\n    \"\"\"\n    if use_processes:\n        LOGGER.debug(\"Process pool num_workers=%d\", num_workers)\n        return ProcessPoolExecutor(max_workers=num_workers)\n\n    LOGGER.debug(\"Thread pool num_workers=%d\", num_workers)\n    return ThreadPoolExecutor(max_workers=num_workers)\n\n\ndef _chunk_loader_worker(request: ChunkRequest) -> ChunkRequest:\n    \"\"\"This is the worker thread or process that loads the array.\n\n    We call np.asarray() in a worker because it might lead to IO or\n    computation which would block the GUI thread.\n\n    Parameters\n    ----------\n    request : ChunkRequest\n        The request to load.\n    \"\"\"\n    request.load_chunks()  # loads all chunks in the request\n    return request\n","sub_path":"napari/components/experimental/chunk/_pool.py","file_name":"_pool.py","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"583020168","text":"# coding=utf-8\n\nimport dbutil\n\nconn = dbutil.connect(\"mysql://admin:admin2048az@192.168.50.95:3306/capvision_fun\")\n\n\ndef get_labels():\n    conn.all(\n        '''\n        SELECT l.label_id , l.demand_id, l.label, l.type, p.project_id\n        FROM capvision_fun.last7_proj_labels  l\n        JOIN capvision_fun.last_7_day_project p on\n        (l.project_id = p.project_id AND p.project_id > 0) OR (l.demand_id = p.confirm_demand_id AND l.demand_id > 0)\n        WHERE\n            l.type IN (41, 42, 43, 44, 71, 72, 73, 74)\n        AND l.label != ''\n        AND l.is_delete = 0\n        AND p.project_create_time >= '2017-03-01'\n        AND p.txt_structure = 'C_li;In'\n        ORDER BY p.project_id DESC\n        '''\n    )\n","sub_path":"test/update_x3.py","file_name":"update_x3.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"179412916","text":"import logging\nimport os\n\nimport simulacra as si\n\n\nFILE_NAME = os.path.splitext(os.path.basename(__file__))[0]\nOUT_DIR = os.path.join(os.getcwd(), 'out', FILE_NAME)\n\n\nclass Foo(si.Beet):\n    def __init__(self, name, a = 5):\n        self.a = a\n\n        super().__init__(name)\n\n    def info(self):\n        info = super().info()\n\n        foo_info = si.Info(header = 'foo info')\n        foo_info.children['a'] = self.a\n        # sup_info.fields['FOO INFO'] = foo_info\n\n        info.add_info(foo_info)\n\n        return info\n\n\nclass BarSim(si.Simulation):\n    def __init__(self, spec):\n        super().__init__(spec)\n\n        self.car = spec.foo * spec.bar\n\n    def info(self):\n        info = super().info()\n\n        info.add_field('car', self.car)\n\n        return info\n\n\nclass Bat:\n    def __init__(self, species = 'brown'):\n        self.species = species\n\n    def info(self):\n        info = si.Info(header = 'Bat')\n        info.add_field('species', self.species)\n\n        return info\n\n\nclass BarSpec(si.Specification):\n    def __init__(self, name, foo = 5, bar = 3, bat = Bat(), pot = si.Summand(), **kwargs):\n        self.foo = foo\n        self.bar = bar\n        self.bat = bat\n        self.pot = pot\n\n        super().__init__(name, simulation_type = BarSim, **kwargs)\n\n    def info(self):\n        info = super().info()\n\n        info.add_field('foo', self.foo)\n        info.add_field('car', self.bar)\n\n        info.add_info(self.bat.info())\n        info.add_info(self.pot.info())\n\n        return info\n\nif __name__ == '__main__':\n    with si.utils.LogManager('simulacra', stdout_logs = True, stdout_level = logging.DEBUG) as logger:\n        foo = Foo('foo', a = 6)\n\n        print(foo.info())\n        print()\n\n        spec = BarSpec('test', file_name = 'foo', pot = si.Summand() + si.Summand())\n        sim = spec.to_simulation()\n\n        print(spec.info())\n\n        print()\n        print('-' * 80)\n        print()\n\n        print(sim.info())\n        # print(sim.info().fields)\n        print()\n","sub_path":"dev/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"440950241","text":"from bs4 import BeautifulSoup\nimport requests\n\n\nclass FullHistory:\n    \"\"\"\n    History class\n    \"\"\"\n\n    def __init__(self, vin):\n        self.vin = vin\n\n    url = \"https://auto-hub.info/autofax-info\"\n\n\n    cookies = {\n        '_ga': 'GA1.2.600433859.1565793366',\n        '_gid': 'GA1.2.364435926.1565793366',\n    }\n\n    headers = {\n        'Origin': 'https://auto-hub.info',\n        'Upgrade-Insecure-Requests': '1',\n        'DNT': '1',\n        'Content-Type': 'application/x-www-form-urlencoded',\n        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',\n        'Sec-Fetch-Mode': 'navigate',\n        'Sec-Fetch-User': '?1',\n        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n        'proxy-authorization': 'Basic bnVsbCZudWxsOm51bGw='\n    }\n    login_data = {\n        '_token': 'sIxV1JMvUZjKJ0DxGAELEpq1FbfOIZzUSNm3GgU7',\n        'email': 'piter.parker2221@ukr.net',\n        'password': 'outsider2706'\n    }\n\n    @property\n    def data(self):\n        with requests.Session() as s:\n            r = s.get(url='https://auto-hub.info/login', headers=self.headers)\n            soup = BeautifulSoup(r.content, 'html.parser')\n            _token = soup.find('input', {'type': 'hidden'}).get('value')\n            print(_token)\n            login_data = {\n                \"_token\": _token,\n                \"email\": \"piter.parker2221@ukr.net\",\n                \"password\": \"outsider2706\"\n            }\n\n            r = s.post(url='https://auto-hub.info/login', data=login_data, headers=self.headers)\n            soup = BeautifulSoup(r.content, 'html.parser')\n            _token = soup.findAll('meta')\n            real_login_cookie = s.cookies.get_dict()\n            real_login_token = _token[2]['content']\n\n            self.cookies.update(real_login_cookie)\n            payload = {\n                    '_token': real_login_token,\n                    'vin_numb': self.vin,\n                }\n            r = s.post(url=self.url, data=payload, headers=self.headers, cookies=real_login_cookie)\n            return r.text\n\n\nif __name__ == '__main__':\n    vin = '3GCUKREC8EG420756'\n    VH = FullHistory(vin)\n","sub_path":"app/core/parser/vin_full_history/FullHistory.py","file_name":"FullHistory.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"270063689","text":"from django.conf.urls import url\nfrom rest_framework.routers import SimpleRouter\n\nimport core.views\nfrom core.routers import AddEditRouter\nfrom . import views\n\nadd_edit_router = AddEditRouter()\n\nrouter = SimpleRouter()\nrouter.register(r'tags', views.TagListView, base_name='tag')\nrouter.register(r'events', core.views.EventViewSet, base_name='event')\nrouter.register(r'jobs', core.views.JobViewSet, base_name='job')\nrouter.register(r'users', views.ProfileViewSet, base_name='profile')\n\nurlpatterns = [\n    url(r'^users/follow/$', views.ToggleFollowUser.as_view(), name='follow-user'),\n    url(r'^events/calendar/$', core.views.EventCalendarList.as_view(), name='event-calendar'),\n    url(r'^events/(?P\\d+)/edit/$', views.EventUpdateView.as_view(), name='event-edit'),\n    url(r'^events/add/$', views.EventCreateView.as_view(), name='event-add'),\n    url(r'^jobs/(?P\\d+)/edit/$', views.JobUpdateView.as_view(), name='job-edit'),\n    url(r'^jobs/add/$', views.JobCreateView.as_view(), name='job-add'),\n    url(r'^about/contact/sent/$', views.ContactSentView.as_view(template_name='home/about/contact-sent.jinja'), name='contact-sent'),\n    url(r'^users/(?P[\\w\\.\\-@]+)/edit/$', views.ProfileUpdateView.as_view(), name='profile-edit'),\n]\n\nurlpatterns.append(url(r'users/(?P(\\w+))/upload_picture/$', views.MemberProfileImageUploadView.as_view()))\n\nurlpatterns += add_edit_router.urls\nurlpatterns += router.urls\n","sub_path":"django/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"27383932","text":"import app1\nimport app2\nimport intro\nimport archi\nimport streamlit as st\nPAGES = {\n    \"Introduction\": intro,\n    \"Predictions\": app1,\n    \"Data Analysis\": app2,\n    \" Project Architecture\": archi\n\n}\n\n\ndef edu_func(X):\n\n    X['Dem_edu'] = X['Dem_edu'].replace({'Uninformative response': 0, 'None': 1, 'Up to 6 years of school': 2, 'Up to 9 years of school': 3, 'Up to 12 years of school': 4, 'Some College, short continuing education or equivalent': 5, 'College degree, bachelor, master': 6, 'PhD/Doctorate': 7})\n    return X[['Dem_edu']]\n\n\ndef edu_mom_func(X):\n    X['Dem_edu_mom'] = X['Dem_edu_mom'].replace({'Uninformative response': 0, 'None': 1, 'Up to 6 years of school': 2, 'Up to 9 years of school': 3, 'Up to 12 years of school': 4, 'Some College or equivalent': 5, 'College degree': 6, 'PhD/Doctorate': 7})\n    return X[['Dem_edu_mom']]\n\n\ndef edu_risk_group(X):\n    X['Dem_riskgroup'] = X['Dem_riskgroup'].replace({'No': 1, 'Not sure': 2, 'Yes': 3})\n    return X[['Dem_riskgroup']]\n\n\ndef dem_expat_func(X):\n    X['Dem_Expat'] = X['Dem_Expat'].replace({'no': 0, 'yes': 1})\n    return X[['Dem_Expat']]\n\n\nst.sidebar.title('Navigation')\nselection = st.sidebar.radio(\"Go to\", list(PAGES.keys()))\npage = PAGES[selection]\npage.app()\n\n\n\n","sub_path":"mainpage.py","file_name":"mainpage.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"36482556","text":"from PySide2 import QtCore, QtWidgets, QtGui\r\nimport os, subprocess\r\nfrom pathlib import Path, PureWindowsPath\r\n\r\nDEFAULT_CONFIG_BEGIN = \"from os import path\\n\\\r\nfrom pengtest import toolbox\\n\\\r\nfrom types import SimpleNamespace\\n\\\r\ncommands = SimpleNamespace()\\n\\\r\ngeneral = SimpleNamespace()\\n\\\r\nbuild = SimpleNamespace()\\n\\\r\nbuild.vm = SimpleNamespace()\\n\\\r\nsettings_path = \\\"Settings\\\"\\n\\\r\nroot_path = path.dirname(path.abspath(__file__))\\n\\\r\nsettings_path = path.abspath(path.join(root_path, settings_path))\\n\\\r\ngeneral.result_path = \\\"Results\\\"\\n\\\r\ngeneral.result_file = \\\"result.csv\\\"\\n\\\r\ngeneral.error_log = \\\"error.log\\\"\\n\\\r\ngeneral.summary_file = \\\"summary.csv\\\"\\n\\\r\nbuild.base = None\\n\\\r\nbuild.destination = \\\"Source/Subject\\\"\\n\\\r\nbuild.resources = None\\n\\\r\nbuild.subject_src = \\\"Source/Subject\\\"\\n\\\r\nbuild.subject_bin = \\\"Build/Subject\\\"\\n\\\r\nbuild.framework_src = \\\"Source/Framework\\\"\\n\\\r\nbuild.framework_bin = \\\"Build/Framework\\\"\\n\\\r\nbuild.prep_cmd = [\\\"xcopy\\\", \\\"$source_dir\\\\\\\\\\\", \\\"$build_dir\\\"]\\n\\\r\nbuild.compile_cmd = []\\n\"\r\n\r\nDEFAULT_CONFIG_END = \"project = toolbox.load_module(path.join(settings_path, \\\"project.py\\\"))\"\r\n\r\nclass VmPage(QtWidgets.QWidget):\r\n    def __init__(self):\r\n        super().__init__()\r\n\r\n        self.layout = QtWidgets.QGridLayout()\r\n\r\n        self.createVMInfoFields()\r\n        self.createFileInfoFields()\r\n        self.createDirInfoFields()\r\n        self.createCmdInfoFields()\r\n\r\n        self.generateButton = QtWidgets.QPushButton(\"Generate Config\")\r\n        self.generateButton.setFixedHeight(50)\r\n        self.generateButton.setFixedWidth(100)\r\n        self.generateButton.clicked.connect(self.writeConfig)\r\n        self.layout.addWidget(self.generateButton)\r\n\r\n        self.setLayout(self.layout)\r\n\r\n    def createVMInfoFields(self):\r\n        self.typeLabel = QtWidgets.QLabel(\"VM Type:\")\r\n        self.typeLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.typeLabel, 0, 0)\r\n        self.typeDropdown = QtWidgets.QComboBox()\r\n        self.typeDropdown.addItem(\"VMWare\")\r\n        self.layout.addWidget(self.typeDropdown, 1, 0)\r\n\r\n        self.nameLabel = QtWidgets.QLabel(\"VM Name:\")\r\n        self.nameLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.nameLabel, 2, 0)\r\n        self.nameField = QtWidgets.QLineEdit(\"\")\r\n        self.nameField.setFixedWidth(500)\r\n        self.layout.addWidget(self.nameField, 3, 0)\r\n\r\n        self.snapshotLabel = QtWidgets.QLabel(\"Snapshot Name:\")\r\n        self.snapshotLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.snapshotLabel, 4, 0)\r\n        self.snapshotField = QtWidgets.QLineEdit(\"\")\r\n        self.snapshotField.setFixedWidth(500)\r\n        self.layout.addWidget(self.snapshotField, 5, 0)\r\n\r\n        self.ipLabel = QtWidgets.QLabel(\"VM IP Address:\")\r\n        self.ipLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.ipLabel, 6, 0)\r\n        self.ipField = QtWidgets.QLineEdit(\"\")\r\n        self.ipField.setFixedWidth(500)\r\n        self.layout.addWidget(self.ipField, 7, 0)\r\n\r\n        self.portLabel = QtWidgets.QLabel(\"VM Port:\")\r\n        self.portLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.portLabel, 8, 0)\r\n        self.portField = QtWidgets.QLineEdit(\"\")\r\n        self.portField.setFixedWidth(50)\r\n        self.layout.addWidget(self.portField, 9, 0)\r\n\r\n        self.userLabel = QtWidgets.QLabel(\"Username:\")\r\n        self.userLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.userLabel, 10, 0)\r\n        self.userField = QtWidgets.QLineEdit(\"\")\r\n        self.userField.setFixedWidth(500)\r\n        self.layout.addWidget(self.userField, 11, 0)\r\n\r\n        self.passwordLabel = QtWidgets.QLabel(\"Password:\")\r\n        self.passwordLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.passwordLabel, 12, 0)\r\n        self.passwordField = QtWidgets.QLineEdit(\"\")\r\n        self.passwordField.setFixedWidth(500)\r\n        self.layout.addWidget(self.passwordField, 13, 0)\r\n\r\n        self.bootLabel = QtWidgets.QLabel(\"VM Boot Time (in seconds):\")\r\n        self.bootLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.bootLabel, 14, 0)\r\n        self.bootField = QtWidgets.QLineEdit(\"\")\r\n        self.bootField.setFixedWidth(50)\r\n        self.layout.addWidget(self.bootField, 15, 0)\r\n\r\n    def createFileInfoFields(self):\r\n        self.stagingLabel = QtWidgets.QLabel(\"Staging Files (enter as comma separated list):\")\r\n        self.stagingLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.stagingLabel, 16, 0)\r\n        self.stagingField = QtWidgets.QLineEdit(\"\")\r\n        self.stagingField.setFixedWidth(500)\r\n        self.layout.addWidget(self.stagingField, 17, 0)\r\n\r\n        self.payloadLabel = QtWidgets.QLabel(\"Payload Files (enter as comma separated list):\")\r\n        self.payloadLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.payloadLabel, 18, 0)\r\n        self.payloadField = QtWidgets.QLineEdit(\"\")\r\n        self.payloadField.setFixedWidth(500)\r\n        self.layout.addWidget(self.payloadField, 19, 0)\r\n\r\n        self.resultLabel = QtWidgets.QLabel(\"Result Files (enter as comma separated list):\")\r\n        self.resultLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.resultLabel, 20, 0)\r\n        self.resultField = QtWidgets.QLineEdit(\"\")\r\n        self.resultField.setFixedWidth(500)\r\n        self.layout.addWidget(self.resultField, 21, 0)\r\n\r\n    def createDirInfoFields(self):\r\n        self.stagdirLabel = QtWidgets.QLabel(\"Staging Directory:\")\r\n        self.stagdirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.stagdirLabel, 0, 1)\r\n        self.stagdirField = QtWidgets.QLineEdit(\"\")\r\n        self.stagdirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.stagdirField, 1, 1)\r\n        self.stagingSelect = QtWidgets.QPushButton(\"Browse\")\r\n        self.stagingSelect.setFixedWidth(100)\r\n        self.stagingSelect.clicked.connect(lambda: self.filePicker(\"Staging\"))\r\n        self.layout.addWidget(self.stagingSelect, 1, 2)\r\n\r\n        self.paydirLabel = QtWidgets.QLabel(\"Payload Directory (Test Suite Directory):\")\r\n        self.paydirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.paydirLabel, 2, 1)\r\n        self.paydirField = QtWidgets.QLineEdit(\"\")\r\n        self.paydirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.paydirField, 3, 1)\r\n        self.payloadSelect = QtWidgets.QPushButton(\"Browse\")\r\n        self.payloadSelect.setFixedWidth(100)\r\n        self.payloadSelect.clicked.connect(lambda: self.filePicker(\"Payload\"))\r\n        self.layout.addWidget(self.payloadSelect, 3, 2)\r\n\r\n        self.resultdirLabel = QtWidgets.QLabel(\"Results Directory:\")\r\n        self.resultdirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.resultdirLabel, 4, 1)\r\n        self.resultdirField = QtWidgets.QLineEdit(\"\")\r\n        self.resultdirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.resultdirField, 5, 1)\r\n        self.resultSelect = QtWidgets.QPushButton(\"Browse\")\r\n        self.resultSelect.setFixedWidth(100)\r\n        self.resultSelect.clicked.connect(lambda: self.filePicker(\"Result\"))\r\n        self.layout.addWidget(self.resultSelect, 5, 2)\r\n\r\n        self.remdirLabel = QtWidgets.QLabel(\"Remote Project Directory:\")\r\n        self.remdirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.remdirLabel, 6, 1)\r\n        self.remdirField = QtWidgets.QLineEdit(\"\")\r\n        self.remdirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.remdirField, 7, 1)\r\n\r\n        self.remstagdirLabel = QtWidgets.QLabel(\"Remote Staging Directory:\")\r\n        self.remstagdirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.remstagdirLabel, 8, 1)\r\n        self.remstagdirField = QtWidgets.QLineEdit(\"\")\r\n        self.remstagdirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.remstagdirField, 9, 1)\r\n\r\n        self.rempaydirLabel = QtWidgets.QLabel(\"Remote Payload Directory:\")\r\n        self.rempaydirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.rempaydirLabel, 10, 1)\r\n        self.rempaydirField = QtWidgets.QLineEdit(\"\")\r\n        self.rempaydirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.rempaydirField, 11, 1)\r\n\r\n        self.remresdirLabel = QtWidgets.QLabel(\"Remote Results Directory:\")\r\n        self.remresdirLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.remresdirLabel, 12, 1)\r\n        self.remresdirField = QtWidgets.QLineEdit(\"\")\r\n        self.remresdirField.setFixedWidth(500)\r\n        self.layout.addWidget(self.remresdirField, 13, 1)\r\n\r\n    def createCmdInfoFields(self):\r\n        self.buildLabel = QtWidgets.QLabel(\"Build Command:\")\r\n        self.buildLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.buildLabel, 14, 1)\r\n        self.buildField = QtWidgets.QLineEdit(\"\")\r\n        self.buildField.setFixedWidth(500)\r\n        self.layout.addWidget(self.buildField, 15, 1)\r\n\r\n        self.stageLabel = QtWidgets.QLabel(\"Stage Command:\")\r\n        self.stageLabel.setMaximumHeight(30)\r\n        self.layout.addWidget(self.stageLabel, 16, 1)\r\n        self.stageField = QtWidgets.QLineEdit(\"\")\r\n        self.stageField.setFixedWidth(500)\r\n        self.layout.addWidget(self.stageField, 17, 1)\r\n\r\n    def filePicker(self, dir):\r\n        # Determine which directory line it was called on\r\n        if dir == \"Staging\":\r\n            widget = self.stagdirField\r\n        elif dir == \"Payload\":\r\n            widget = self.paydirField\r\n        elif dir == \"Result\":\r\n            widget = self.resultdirField\r\n        else:\r\n            return\r\n        \r\n        dialog = QtWidgets.QFileDialog(self)\r\n        dialog.setFileMode(QtWidgets.QFileDialog.Directory)\r\n        dialog.setWindowTitle(\"Select \" + dir + \" Directory\")\r\n        dialog.setOptions(QtWidgets.QFileDialog.ShowDirsOnly)\r\n        dialog.setDirectory(widget.text())\r\n\r\n        if dialog.exec_():\r\n            widget.setText(dialog.selectedFiles()[0])\r\n\r\n    def writeConfig(self):\r\n        # First verify that all input fields have been filled in\r\n        isComplete = self.verifyInput()\r\n\r\n        if not isComplete:\r\n            # If the input fields are not filled in, then do not create config\r\n            return\r\n\r\n        # Get the current directory\r\n        cur_dir = os.getcwd()\r\n\r\n        # Change the directory to the root of the test suite\r\n        os.chdir(self.paydirField.text())\r\n\r\n        # Write the config variables to config.py\r\n        with open(\"config.py\", \"a+\") as file:\r\n            content = DEFAULT_CONFIG_BEGIN\r\n            content += \"build.vm.is_vm = True\\n\"\r\n            content += \"build.vm.type = \\\"\" + self.typeDropdown.currentText() + \"\\\"\\n\"\r\n            content += \"build.vm.name = \\\"\" + self.nameField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.snapshot = \\\"\" + self.snapshotField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.ip = \\\"\" + self.ipField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.port = \\\"\" + self.portField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.user = \\\"\" + self.userField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.passwd = \\\"\" + self.passwordField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.boot_time = \" + self.bootField.text() + \"\\n\"\r\n            \r\n            # The files are entered as a comma list, so split the string\r\n            content += self.splitString(self.stagingField.text(), \"staging\")\r\n            content += self.splitString(self.payloadField.text(), \"payload\")\r\n            content += self.splitString(self.resultField.text(), \"result\")\r\n\r\n            # Convert WSL paths to Windows paths\r\n            stagDir = self.convertPath(self.stagdirField.text())\r\n            content += \"build.vm.staging_dir = \\\"\" + stagDir + \"\\\"\\n\"\r\n            payDir = self.convertPath(self.paydirField.text())\r\n            content += \"build.vm.payload_dir = \\\"\" + payDir + \"\\\"\\n\"\r\n            resultDir = self.convertPath(self.resultdirField.text())\r\n            content += \"build.vm.result_dir = \\\"\" + resultDir + \"\\\"\\n\"\r\n\r\n            content += \"build.vm.build_cmd = \\\"\" + self.buildField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.stage_cmd = \\\"\" + self.stageField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.remote_proj_dir = \\\"\" + self.remdirField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.remote_staging_dir = \\\"\" + self.remstagdirField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.remote_payload_dir = \\\"\" + self.rempaydirField.text() + \"\\\"\\n\"\r\n            content += \"build.vm.remote_result_dir = \\\"\" + self.remresdirField.text() + \"\\\"\\n\"\r\n            content += DEFAULT_CONFIG_END\r\n            file.write(content)\r\n\r\n        # Change back to the initial directory\r\n        os.chdir(cur_dir)\r\n\r\n    def convertPath(self, path):\r\n        # Convert WSL paths to Windows paths using WSL's built in wslpath command\r\n        process = subprocess.Popen(['wslpath', '-w', path], stdout=subprocess.PIPE)\r\n        windows_path = process.stdout.readline().decode('utf-8')\r\n\r\n        # This comes with a new line, so strip it off\r\n        windows_path = windows_path[:len(windows_path) - 1]\r\n        return windows_path\r\n\r\n    def verifyInput(self):\r\n        # List of all fields on the page\r\n        varList = [self.typeDropdown.currentText(), self.nameField.text(), self.snapshotField.text(), \\\r\n            self.ipField.text(), self.portField.text(), self.userField.text(), self.passwordField.text(), \\\r\n            self.bootField.text(), self.stagingField.text(), self.payloadField.text(), self.resultField.text(), \\\r\n            self.stagdirField.text(), self.paydirField.text(), self.resultdirField.text(), self.buildField.text(), \\\r\n            self.stageField.text(), self.remdirField.text(), self.remstagdirField.text(), self.rempaydirField.text(), \\\r\n            self.remresdirField.text()]\r\n\r\n        error = \"\"\r\n        isComplete = True\r\n\r\n        for v in varList:\r\n            # Check all fields for input\r\n            if v == \"\":\r\n                error += \"Please provide input to all fields. \"\r\n                isComplete = False\r\n                break\r\n\r\n        # Check if the boot and port fields contain positive integers\r\n        if not self.bootField.text().isdigit():\r\n            error += \"Please provide a positive integer for boot time. \"\r\n            isComplete = False\r\n\r\n        if not self.portField.text().isdigit():\r\n            error += \"Please provide a positive integer for port number. \"\r\n            isComplete = False\r\n\r\n        if not isComplete:\r\n            # Create a message box popup with the error, if there is one\r\n            msgBox = QtWidgets.QMessageBox()\r\n            msgBox.setWindowTitle(\"Error generating config\")\r\n            msgBox.setText(error)\r\n            msgBox.exec_()\r\n\r\n        return isComplete\r\n        \r\n    \r\n    def splitString(self, string, dirType):\r\n        # Remove any spaces\r\n        staging = string.replace(' ','')\r\n\r\n        # Split on commas\r\n        l = staging.split(',')\r\n\r\n        content = \"\"\r\n        content += \"build.vm.\" + dirType + \"_files = [\"\r\n        i = 0\r\n\r\n        # Iterate over every file, adding it to the string formatted correctly\r\n        for f in l:\r\n            content += \"\\\"\" + f + \"\\\"\"\r\n            if i == len(l) - 1:\r\n                content += \"]\\n\"\r\n            else:\r\n                content += \", \"\r\n                i += 1\r\n        return content\r\n","sub_path":"pengtest/vmPage.py","file_name":"vmPage.py","file_ext":"py","file_size_in_byte":15357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"177144375","text":"from flask import Flask, request, jsonify, render_template\nimport pickle\nimport numpy as np\n\napp = Flask(__name__)\nmodel = pickle.load(open('randomforest.pkl', 'rb'))\n\n\n@app.route('/')\ndef home():\n    return render_template('index.html')\n\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n    '''\n    For rendering results in GUI\n    '''\n    int_features = [float(x) for x in request.form.values()]\n    final_features = np.log(int_features)\n    final_features = final_features.reshape(-1,1)\n    prediction = model.predict(final_features)\n    output = round(float(np.exp(prediction)),2)\n\n    return render_template('index.html',\n                           prediction_text=\"The predicted closing price of your desired stock is {}\".format(output))\n\n\nif __name__ == \"__main__\":\n    app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"297432967","text":"from itertools import permutations\r\n\r\ndef is_prime(num):\r\n    if num < 2:\r\n        return False\r\n    for i in range(2, int(num**0.5)+1):\r\n        if num % i == 0:\r\n            return False\r\n    return True\r\n\r\ndef solution(numbers):\r\n    answer = 0\r\n    result = []\r\n    for i in range(1, len(numbers)+1):\r\n        nums = list(map(''.join, permutations(numbers,i)))\r\n        for num in list(set(nums)):\r\n            if is_prime(int(num)):\r\n                result.append(int(num))\r\n    \r\n    answer = len(set(result))\r\n    return answer","sub_path":"brute_force_search/42839.py","file_name":"42839.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"599324445","text":"import json, os\nimport pygama.pargen.energy_optimisation as om\nfrom util.utils import run_splitter\nimport pygama.math.peak_fitting as pgf\nfrom collections import OrderedDict\nimport pickle\nimport argparse\nimport pathlib\nimport time\nimport numpy as np\nfrom util.metadata_loading import *\n\nargparser = argparse.ArgumentParser()\n#argparser.add_argument(\"raw_files\", help=\"raw_files\", nargs='*',type=str)\nargparser.add_argument(\"raw_files\", help=\"raw_filelist\", type=str)\nargparser.add_argument(\"--configs\", help=\"configs\", type=str, required=True)\nargparser.add_argument(\"--decay_const\", help=\"decay_const\", type=str, required=True)\n\nargparser.add_argument(\"--datatype\", help=\"Datatype\", type=str, required=True)\nargparser.add_argument(\"--timestamp\", help=\"Timestamp\", type=str, required=True)\nargparser.add_argument(\"--channel\", help=\"Channel\", type=str, required=True)\nargparser.add_argument(\"--peak\", help=\"peak\", type=float, required=True)\n\nargparser.add_argument(\"--output_path\", help=\"output_path\", type=str)\nargs = argparser.parse_args()\n\npeaks_keV = np.array([238.632,   583.191, 727.330, 860.564, 1620.5, 2614.553])\n#kev_widths = [(10,10), (25,40), (25,40),(25,40),(25,40), (50,50)]\n#funcs = [pgf.gauss_step, pgf.radford_peak, pgf.radford_peak,pgf.radford_peak,pgf.radford_peak, pgf.radford_peak]\n\nif args.peak == 2614.553:\n        kev_widths = (70, 70)\n        n_processes = 19\n        func = pgf.extended_radford_pdf\n        gof_func = pgf.radford_pdf\nelif args.peak == 238.632:\n    kev_widths = (10,10)\n    n_processes = 5\n    func = pgf.extended_gauss_step_pdf\n    gof_func = pgf.gauss_step_pdf\nelse:\n    kev_widths = (25,55)\n    n_processes = 19\n    func = pgf.extended_radford_pdf\n    gof_func = pgf.radford_pdf\n    \npeak_idx = np.where(peaks_keV == args.peak)[0][0]\n\nwith open(args.raw_files) as f:\n    files = f.read().splitlines()\n\nraw_files = sorted(files)\n\ncfg_file = os.path.join(args.configs, 'key_resolve.jsonl')\nconfigs = config_catalog.get_config(cfg_file, args.configs, args.timestamp, args.datatype)\nconfig_dict = configs['snakemake_rules']['pars_dsp_egrid'][\"inputs\"]['processing_chain'][args.channel]\nopt_json = configs['snakemake_rules']['pars_dsp_egrid'][\"inputs\"][\"optimiser_config\"][args.channel]\n\nwith open(args.decay_const, 'r') as t:\n    db_dict = json.load(t)[args.channel]\n\nwith open(opt_json, 'r') as r:\n    opt_dict = json.load(r)\n\nwf_idxs = om.event_selection(raw_files, f'{args.channel}/raw', config_dict, db_dict, peaks_keV, peak_idx, kev_widths)\n\n\nprint('Loaded configs')\n\nparameters=['cuspEmax'] #'zacEmax', 'trapEmax', \n\nt0 = time.time()\n\ngrid_out = om.run_optimisation_multiprocessed(raw_files, opt_dict, config_dict, cuts = wf_idxs, \n            lh5_path = f'{args.channel}/raw' , fom = om.fom_all_fit, db_dict = db_dict,  n_events=10000, \n            processes=n_processes, parameter=parameters, func=func, gof_func = gof_func,\n            peak=args.peak, kev_width=kev_widths) \n    \nt1 = time.time()\n\nprint(f'Calculated Grid in {(t1-t0)/60} minutes')\n\nsave_dict = {}\nfor i,param in enumerate(parameters):\n    save_dict[param] = grid_out[i]\n    \npathlib.Path(os.path.dirname(args.output_path)).mkdir(parents=True, exist_ok=True)\nwith open(args.output_path,\"wb\") as f:\n    pickle.dump(save_dict,f)\n","sub_path":"scripts/pars_dsp_egrids.py","file_name":"pars_dsp_egrids.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"18068375","text":"#from __future__ import print_function\nfrom Exscript.util.interact import read_login\nfrom Exscript.protocols import SSH2\nimport sys\n#import Exscript\nimport platform\n\nfh = open(\"output.txt\", 'a')\nplatform = platform.system()\naccount = read_login()\n\n#conn = SSH2(debug=255)\nconn = SSH2()\n#conn.buffer = 2048\n#conn.set_driver('ios')\n#conn.set_timeout(5)\n\nconn.connect('')\nconn.login(account)\n\nconn.execute('term len 0')\nconn.execute('show running')\nif platform == 'Windows':\n    fh.write(conn.response)\n    fh.write('\\r\\n')\nelse:\n    fh.write(conn.response)\n    fh.write('\\n')\n#print(conn.response)\n\n#print(conn.response, end='', file=fh)\n#print >> fh, conn.response\n\n#conn.send('exit\\r')\nconn.close()\nfh.close()\n\n#fh.close()\n","sub_path":"ssh-test2.py","file_name":"ssh-test2.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"46385043","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\nimport logging\nfrom typing import Dict\n\nimport psutil\nfrom opentelemetry.metrics import Meter, Observer\nfrom opentelemetry.sdk.metrics import UpDownSumObserver\n\nfrom azure_monitor.sdk.auto_collection.utils import AutoCollectionType\n\nlogger = logging.getLogger(__name__)\nPROCESS = psutil.Process()\n\n\nclass PerformanceMetrics:\n    \"\"\"Starts auto collection of performance metrics, including\n    \"Processor time as a percentage\", \"Amount of available memory\n    in bytes\", \"Process CPU usage as a percentage\" and \"Amount of\n    memory process has used in bytes\" metrics.\n\n    Args:\n        meter: OpenTelemetry Meter\n        labels: Dictionary of labels\n        collection_type: Standard or Live Metrics\n    \"\"\"\n\n    def __init__(\n        self,\n        meter: Meter,\n        labels: Dict[str, str],\n        collection_type: AutoCollectionType,\n    ):\n        self._meter = meter\n        self._labels = labels\n\n        self._meter.register_observer(\n            callback=self._track_cpu,\n            name=\"\\\\Processor(_Total)\\\\% Processor Time\",\n            description=\"Processor time as a percentage\",\n            unit=\"percentage\",\n            value_type=float,\n            observer_type=UpDownSumObserver,\n        )\n\n        if collection_type == AutoCollectionType.STANDARD_METRICS:\n            self._meter.register_observer(\n                callback=self._track_memory,\n                name=\"\\\\Memory\\\\Available Bytes\",\n                description=\"Amount of available memory in bytes\",\n                unit=\"byte\",\n                value_type=int,\n                observer_type=UpDownSumObserver,\n            )\n            self._meter.register_observer(\n                callback=self._track_process_cpu,\n                name=\"\\\\Process(??APP_WIN32_PROC??)\\\\% Processor Time\",\n                description=\"Process CPU usage as a percentage\",\n                unit=\"percentage\",\n                value_type=float,\n                observer_type=UpDownSumObserver,\n            )\n            self._meter.register_observer(\n                callback=self._track_process_memory,\n                name=\"\\\\Process(??APP_WIN32_PROC??)\\\\Private Bytes\",\n                description=\"Amount of memory process has used in bytes\",\n                unit=\"byte\",\n                value_type=int,\n                observer_type=UpDownSumObserver,\n            )\n        if collection_type == AutoCollectionType.LIVE_METRICS:\n            self._meter.register_observer(\n                callback=self._track_commited_memory,\n                name=\"\\\\Memory\\\\Committed Bytes\",\n                description=\"Amount of committed memory in bytes\",\n                unit=\"byte\",\n                value_type=int,\n                observer_type=UpDownSumObserver,\n            )\n\n    def _track_cpu(self, observer: Observer) -> None:\n        \"\"\" Track CPU time\n\n        Processor time is defined as a float representing the current system\n        wide CPU utilization minus idle CPU time as a percentage. Idle CPU\n        time is defined as the time spent doing nothing. Return values range\n        from 0.0 to 100.0 inclusive.\n        \"\"\"\n        cpu_times_percent = psutil.cpu_times_percent()\n        observer.observe(100.0 - cpu_times_percent.idle, self._labels)\n\n    def _track_memory(self, observer: Observer) -> None:\n        \"\"\" Track Memory\n\n        Available memory is defined as memory that can be given instantly to\n        processes without the system going into swap.\n        \"\"\"\n        observer.observe(psutil.virtual_memory().available, self._labels)\n\n    def _track_process_cpu(self, observer: Observer) -> None:\n        \"\"\" Track Process CPU time\n\n        Returns a derived gauge for the CPU usage for the current process.\n        Return values range from 0.0 to 100.0 inclusive.\n        \"\"\"\n        try:\n            # In the case of a process running on multiple threads on different\n            # CPU cores, the returned value of cpu_percent() can be > 100.0. We\n            # normalize the cpu process using the number of logical CPUs\n            cpu_count = psutil.cpu_count(logical=True)\n            observer.observe(PROCESS.cpu_percent() / cpu_count, self._labels)\n        except Exception:  # pylint: disable=broad-except\n            logger.exception(\"Error handling get process cpu usage.\")\n\n    def _track_process_memory(self, observer: Observer) -> None:\n        \"\"\" Track Memory\n\n         Available memory is defined as memory that can be given instantly to\n        processes without the system going into swap.\n        \"\"\"\n        try:\n            observer.observe(PROCESS.memory_info().rss, self._labels)\n        except Exception:  # pylint: disable=broad-except\n            logger.exception(\"Error handling get process private bytes.\")\n\n    def _track_commited_memory(self, observer: Observer) -> None:\n        \"\"\" Track Commited Memory\n\n        Available commited memory is defined as total memory minus available memory.\n        \"\"\"\n        observer.observe(\n            psutil.virtual_memory().total - psutil.virtual_memory().available,\n            self._labels,\n        )\n","sub_path":"azure_monitor/src/azure_monitor/sdk/auto_collection/performance_metrics.py","file_name":"performance_metrics.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"505599141","text":"from manipuladorLista import gerarLista\nfrom manipuladorLista import checarOrdenacao\n\ndef mesclar(lista1, lista2):\n    '''mescla duas listas ordenadas'''\n    index1 = index2 = 0\n    lista_mesclada = []\n    while index1 < len(lista1) and index2 < len(lista2):\n        if lista1[index1] < lista2[index2]:\n            lista_mesclada.append(lista1[index1])\n            index1+=1\n        else:\n            lista_mesclada.append(lista2[index2])\n            index2+=1\n            \n    #soma os itens que sobraram\n    return lista_mesclada + lista1[index1:] + lista2[index2:]\n\ndef merge(lista):\n    if len(lista) == 1:\n        return lista\n    pivo_index = len(lista)//2\n\n    #em cada recurasao, divide novamente, e ao fim mescla\n    return mesclar(merge(lista[:pivo_index]), merge(lista[pivo_index:]))\n\nif __name__ == \"__main__\":\n    for i in range(100):\n           print(checarOrdenacao(merge(gerarLista(5, 10))))\n\n\n","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"203886096","text":"while True:\n    broken = input('-1 to exit x,y,x,y...:')\n    if broken == \"-1\":\n        break\n    broken = broken.replace(',',' ').split()\n    out = \"canvas.fillStyle = '#F0F';\\ncanvas.beginPath();\\ncanvas.moveTo(\" + str(int(broken[0])) + \",\" + str(int(broken[1])) + \");\\n\"\n    piece1 = broken[0::2]\n    piece2 = broken[1::2]\n    for i in range(len(piece1)-1):\n        out += \"canvas.lineTo(\" + str(int(piece1[i+1])) + \",\" + str(int(piece2[i+1])) + \");\\n\"\n    out += \"canvas.closePath();\\ncanvas.fill();\"\n    print(out)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"319585882","text":"import os\nfrom pathlib import Path\nimport logging\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport pickle\nimport json\nlogger = logging.getLogger()\n\ndef init_logger(log_file=None, log_file_level=logging.NOTSET):\n    '''\n    Example:\n        >>> init_logger(log_file)\n        >>> logger.info(\"abc'\")\n    '''\n    if isinstance(log_file,Path):\n        log_file = str(log_file)\n    log_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s -   %(message)s',\n                                   datefmt='%m/%d/%Y %H:%M:%S')\n\n    logger = logging.getLogger()\n    logger.setLevel(logging.INFO)\n    console_handler = logging.StreamHandler()\n    console_handler.setFormatter(log_format)\n    logger.handlers = [console_handler]\n    if log_file and log_file != '':\n        file_handler = logging.FileHandler(log_file)\n        file_handler.setLevel(log_file_level)\n        # file_handler.setFormatter(log_format)\n        logger.addHandler(file_handler)\n    return logger\n\n\ndef seed_everything(seed=1029):\n    '''\n    设置整个开发环境的seed\n    :param seed:\n    :param device:\n    :return:\n    '''\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.set_random_seed(seed)#?\n\ndef save_pickle(data, file_path):\n    '''\n    保存成pickle文件\n    :param data:\n    :param file_name:\n    :param pickle_path:\n    :return:\n    '''\n    if isinstance(file_path, Path):\n        file_path = str(file_path)\n    with open(file_path, 'wb') as f:\n        pickle.dump(data, f)\n\n\ndef load_pickle(input_file):\n    '''\n    读取pickle文件\n    :param pickle_path:\n    :param file_name:\n    :return:\n    '''\n    with open(str(input_file), 'rb') as f:\n        data = pickle.load(f)\n    return data\n\n\ndef save_model(sess, model, path, logger):\n    checkpoint_path = os.path.join(path, \"best.ckpt\")\n    model.saver.save(sess, checkpoint_path)\n    logger.info(\"model saved\")\n\n\ndef create_model(session, Model_class, path,config,data,logger):\n    # create model, reuse parameters if exists\n    model = Model_class(config,data)\n\n    ckpt = tf.train.get_checkpoint_state(path)\n    if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n        logger.info(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n        model.saver.restore(session, ckpt.model_checkpoint_path)\n    else:\n        logger.info(\"Created model with fresh parameters.\")\n        session.run(tf.global_variables_initializer())\n\n    return model\n\n\ndef json_to_text(file_path,data):\n    '''\n    将json list写入text文件中\n    :param file_path:\n    :param data:\n    :return:\n    '''\n    if not isinstance(file_path, Path):\n        file_path = Path(file_path)\n    with open(str(file_path), 'w') as fw:\n        for line in data:\n            line = json.dumps(line, ensure_ascii=False)\n            fw.write(line + '\\n')\n\n\n#make batch\ndef batchify_with_label(input_batch_list):\n    # word_Ids, biword_Ids, gaz_Ids, label_Ids, gazs, gazs_count, layergazmasks\n    batch_size = len(input_batch_list)\n    words = [sent[0] for sent in input_batch_list]\n    biwords = [sent[1] for sent in input_batch_list]\n    gazs = [sent[2] for sent in input_batch_list]\n    labels = [sent[3] for sent in input_batch_list]\n    layer_gazs = [sent[4] for sent in input_batch_list]#word-->gazs\n    gaz_count = [sent[5] for sent in input_batch_list]\n    gaz_mask = [sent[6] for sent in input_batch_list]\n\n    word_seq_lengths = list(map(len, words))\n    max_seq_len = max(word_seq_lengths)\n    word_seq_tensor = np.zeros((batch_size,max_seq_len))#0\n    biword_seq_tensor= np.zeros((batch_size,max_seq_len))\n    label_seq_tensor = np.zeros((batch_size,max_seq_len))#0\n    mask = np.zeros((batch_size,max_seq_len))\n\n    gaz_num = [len(layer_gazs[i][0][0]) for i in range(batch_size)]#就看第一个位置,应为其他位置已经做过padding了\n    max_gaz_num = max(gaz_num)\n    layer_gaz_tensor = np.zeros((batch_size, max_seq_len, 4, max_gaz_num))\n    gaz_count_tensor = np.zeros((batch_size, max_seq_len, 4, max_gaz_num))\n    gaz_mask_tensor = np.ones((batch_size, max_seq_len, 4, max_gaz_num))#padding是1\n\n    for b, (seq,biseq,label, seqlen, layergaz, gazmask, gazcount,gaznum) in enumerate(zip(words,biwords,labels, word_seq_lengths, layer_gazs, gaz_mask, gaz_count,gaz_num)):\n\n        word_seq_tensor[b, :seqlen] = np.asarray(seq)\n        biword_seq_tensor[b, :seqlen]=np.asarray(biseq)\n        label_seq_tensor[b, :seqlen] = np.asarray(label)\n        layer_gaz_tensor[b, :seqlen, :, :gaznum] = np.asarray(layergaz)\n        mask[b, :seqlen] = np.asarray([1]*int(seqlen))#padding是0\n        gaz_mask_tensor[b, :seqlen, :, :gaznum] = np.asarray(gazmask)\n        gaz_count_tensor[b, :seqlen, :, :gaznum] = np.asarray(gazcount)\n        gaz_count_tensor[b, seqlen:] = 1#计数\n\n\n    return gazs,word_seq_tensor,biword_seq_tensor,word_seq_lengths,label_seq_tensor,layer_gaz_tensor,gaz_count_tensor,gaz_mask_tensor,mask\n","sub_path":"transformer+onlstm/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"434885972","text":"# coding: utf-8\n# +-------------------------------------------------------------------\n# | 宝塔Windows面板\n# +-------------------------------------------------------------------\n# | Copyright (c) 2015-2019 宝塔软件(http://bt.cn) All rights reserved.\n\n# +-------------------------------------------------------------------\nimport os\nimport sys\nsys.path.append(\"class/\")\nimport public\nimport db\nimport json\nimport time\nimport binascii \nimport base64,system\nfrom BTPanel import session\n   \n \nclass btpatch_main:\n    __setupPath = 'plugin/btpatch';\r\n    __panelPath = os.getenv(\"BT_PANEL\")\n\n    __server_version = None;\n    def __init__(self):\n        import system\n        self.__server_version = system.system().GetSystemVersion()\n\n\n     #获取列表\r\n    def get_list(self,get):\r\n        self.get_cloud_list(get);\r\n        jsonFile = self.__setupPath + '/list.json';\r\n        if not os.path.exists(jsonFile): return public.returnMsg(False,'配置文件不存在!');\r\n        data = {}\r\n        data = json.loads(public.readFile(jsonFile));\r\n        \r\n        systeminfo = public.ExecShell('systeminfo | findstr KB',None,None,None,True)\r\n        result = []\r\n        for info in data:\r\n            info['status'] = False\r\n           \r\n            downurl = \"\";\r\n            for version in info['os']:\r\n                if self.__server_version.lower().find(version.lower()) >= 0:\r\n                    if version in info[\"downurl\"]:                         \r\n                       downurl = info[\"downurl\"][version]     \r\n                       if type(downurl) != str:\r\n                           downurl = \"|\".join(downurl)\r\n                    if type(info['patch']) != str:\r\n                        info['patch'] = info['patch'][version]\r\n                    break;\r\n            if systeminfo[0].find(info['patch']) >=0 : info['status'] = True\r\n            info[\"downurl\"] = downurl\r\n            result.append(info);\r\n            print(result)\r\n        return result;\r\n\r\n    #安装补丁\r\n    def setup_patch(self,get):\r\n        url = get.url\r\n        patch = get.patch;\r\n\r\n        if not url:\r\n            return public.returnMsg(False,'不在影响范围或未找到相应的补丁.');\r\n        tmpPath = \"C:/Temp/\" + patch + \".msu\"\r\n        public.downloadFile(url,tmpPath)\r\n        if not os.path.exists(tmpPath):\r\n            return public.returnMsg(False,'补丁下载失败,请检查网络原因。');\r\n        os.system(\"wusa.exe %s /quiet \" % (tmpPath.replace(\"/\",\"\\\\\")))\r\n\r\n        result = public.ExecShell('systeminfo | findstr KB',None,None,None,True)\r\n\r\n        if result[0].find(patch) >=0 :\r\n            return public.returnMsg(True,'安装补丁【'+ patch + '】成功');\r\n        return public.returnMsg(False,'安装失败,请检查系统是否关闭更新,或手动运行【'+tmpPath+'】进行安装。');\r\n\r\n        #从云端获取列表\r\n    def get_cloud_list(self,get):\r\n        try:\r\n            jsonFile = self.__setupPath + '/list.json'\r\n            if not 'patch' in session or not os.path.exists(jsonFile):\r\n                downloadUrl = public.get_url() + '/win/install/plugin/btpatch/list.json';\r\n         \r\n                tmp = json.loads(public.httpGet(downloadUrl,3));\r\n\r\n                if not tmp: return public.returnMsg(False,'从云端获取失败!');\r\n                \r\n                public.writeFile(jsonFile,json.dumps(tmp));\r\n                \r\n                session['patch'] = True\r\n                return public.returnMsg(True,'更新成功!');\r\n            return public.returnMsg(True,'无需更新!');\r\n        except:\r\n            return public.returnMsg(False,'从云端获取失败!');","sub_path":"sgAiHE7JlTRNnV6c/c8ed6db1593e65bedd3e435019ffb86282407923.py","file_name":"c8ed6db1593e65bedd3e435019ffb86282407923.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"496504554","text":"# 制作浅复制\n\nxs = [[1, 2, 3, ], [4, 5, 6]]\nxy = list(xs)\n\nxs.append([7, 8])  # 不会有影响\n\nxs[1][0] = 'x'  # 会造成 xy 的变化\nprint(xs)\nprint(xy)\n\n\n# 制作深复制\n# copy 模块中的 copy,copy() 和 copy.deepcopy() 函数可以复制任何对象\nimport copy\n\nzx = [[1, 2, 3], [4, 5, 6]]\nzy = copy.deepcopy(zx)\n\nzx.append([7, 8])\nzx[1][0] = 'x'   # 不会对 zy 造成任何影响\n\nprint(zx)\nprint(zy)\n\n\n# 复制任意对象\nclass Point:\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\n    def __repr__(self):\n        return f'Point({self.x}, {self.y})'\n\n\nclass Rectangle:\n    def __init__(self, topleft, bottomright):\n        self.topleft = topleft\n        self.bottomtight = bottomright\n\n    def __repr__(self):\n        return f'Rectangle({self.topleft}, {self.bottomtight})'\n\n\nrect = Rectangle(Point(0, 1), Point(5, 6))\nsrect = copy.copy(rect)\n\nrect.topleft.x = 999\nxrect = copy.deepcopy(rect)\nxrect.topleft.x = 888\n\n\nprint(rect)\nprint(srect)\nprint('----------deepcopy------------')\nprint(rect)\nprint(xrect)","sub_path":"Python特性/Chapter_4/4_4 克隆对象.py","file_name":"4_4 克隆对象.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"202898120","text":"import applescript\nimport time\n\nfrom easytrader.trader.trader import BaseTrader\n\nscpt = applescript.AppleScript('''\n\t#--------------------------------------------------------------------------------------\n\ton foo()\n\t\treturn \"你好\"\n\tend foo\n\t\n\t#--------------------------------------------------------------------------------------\n\ton toPage(itemid)\n\t\tmy _toPage(44) -- to 预留信息修改页面,起到刷新页面的效果\n\t\tmy _toPage(itemid)\n\tend toPage\n\n\t#--------------------------------------------------------------------------------------\n\ton _toPage(itemid)\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\tset frontmost to false\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t--  构造菜单项列表\n\t\t\t\t\tset menulist to {}\n\t\t\t\t\ttry\n\t\t\t\t\t\tset menulist to row of outline 1 of scroll area 1 of group 1\n\t\t\t\t\ton error\n\t\t\t\t\t\tset menulist to row of outline 1 of scroll area 1 of group 3\n\t\t\t\t\tend try\n\n\t\t\t\t\t--选中某个菜单项\n\t\t\t\t\tset selecteditem to get the item itemid of menulist\n\t\t\t\t\tset value of attribute \"AXSelected\" of the selecteditem to true\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\n\tend _toPage\n\n\t#--------------------------------------------------------------------------------------\n\ton login()\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\t--set frontmost to true\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\tset value of text field 2 to \"981626\"\n\t\t\t\t\tset value of text field 1 to \"2614\"\n\t\t\t\t\tclick checkbox \"登  录\"  \n\t\t\t\t\tset _str to 1\n\t\t\t\t\treturn _str\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\n\tend login\n\n\t#--------------------------------------------------------------------------------------\n\ton buy_entrust(para, isdo)\n\t\tset v_stock_code to item 1 of para\n\t\tset v_price to item 2 of para\n\t\tset v_count to item 3 of para\n\t\n\t\tset v_result to {}\n\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 买入委托\n\t\t\t\t\tmy toPage(1)\n\n\t\t\t\t\t-- 检查标志\n\t\t\t\t\tset value of text field 3 to \"\"\n\n\t\t\t\t\t-- 证券代码\n\t\t\t\t\tset value of attribute \"AXFocused\" of text field 1 to true\n\t\t\t\t\tset value of text field 1 to v_stock_code\n\t\t\t\t\taction \"AXConfirm\" of text field 1\n\n\t\t\t\t\t-- 等待刷新股票名称\n\t\t\t\t\trepeat until the length of (get value of text field 3) > 0\n\t\t\t\t\tend repeat\n\n\t\t\t\t\t-- 证券价格\n\t\t\t\t\tset value of text field 3 to v_price\n\n\t\t\t\t\t-- 证券数量\n\t\t\t\t\tset value of text field 2 to v_count\n\n\t\t\t\t\t-- 对于逆回购,按钮显示为\"融资委托\",其他产品,显示为\"买入委托\"\n\t\t\t\t\tif button \"买入委托\" exists\n\t\t\t\t\t\tclick button \"买入委托\"\n\t\t\t\t\telse if button \"融资委托\" exists\n\t\t\t\t\t\tclick button \"融资委托\"\n\t\t\t\t\tend if\n\t\t\t\tend tell\n\n\t\t\t\t-- 等待弹出窗口\"委托确认提示\"\n\t\t\t\trepeat until window \"委托确认提示\" exists\n\t\t\t\tend repeat\n\t\t\t\t\n\t\t\t\tset v_result to v_result & (get name of static text 1 of window \"委托确认提示\")\n\t\t\t\tif isdo then\n\t\t\t\t\tset v_result to v_result & \"Y\"\n\t\t\t\t\ttell button \"买入\" of window \"委托确认提示\" to click\n\t\t\t\telse\n\t\t\t\t\tset v_result to v_result & \"N\"\n\t\t\t\t\ttell button \"取消\" of window \"委托确认提示\" to click\n\t\t\t\t\treturn v_result\n\t\t\t\tend if\n\n\t\t\t\t-- 等待确认结果窗口返回\n\t\t\t\t--repeat until window 1 exists\n\t\t\t\t--end repeat\n\t\t\t\trepeat until button \"确认\" of window 1  exists\n\t\t\t\tend repeat\n\n\t\t\t\tset v_result to v_result & (get name of static text of window 1)\n\t\t\t\ttell button \"确认\" of window 1 to click\n\n\t\t\t\treturn v_result\n\t\t\tend tell\n\t\tend tell\n\tend buy_entrust\n\n\t#--------------------------------------------------------------------------------------\n\ton sell_entrust(para, isdo)\n\t\tset v_stock_code to item 1 of para\n\t\tset v_price to item 2 of para\n\t\tset v_count to item 3 of para\n\t\n\t\tset v_result to {}\n\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 卖出委托\n\t\t\t\t\tmy toPage(2)\n\n\t\t\t\t\t-- 检查标志\n\t\t\t\t\tset value of text field 3 to \"\"\n\n\t\t\t\t\t-- 证券代码\n\t\t\t\t\tset value of attribute \"AXFocused\" of text field 1 to true\n\t\t\t\t\tset value of text field 1 to v_stock_code \n\t\t\t\t\taction \"AXConfirm\" of text field 1\n\t\t\t\t\t\n\t\t\t\t\t-- 等待刷新股票名称\n\t\t\t\t\trepeat until the length of (get value of text field 3) > 0\n\t\t\t\t\tend repeat\n\n\t\t\t\t\t-- 证券价格\n\t\t\t\t\tset value of text field 3 to v_price\n\n\t\t\t\t\t-- 证券数量\n\t\t\t\t\tset value of text field 2 to v_count\n\n\t\t\t\t\t-- 对于逆回购,按钮显示为\"融券委托\",其他产品,显示为\"卖出委托\"\n\t\t\t\t\tif button \"卖出委托\" exists\n\t\t\t\t\t\tclick button \"卖出委托\"\n\t\t\t\t\telse if button \"融券委托\" exists\n\t\t\t\t\t\tclick button \"融券委托\"\n\t\t\t\t\tend if\n\t\t\t\tend tell\n\n\t\t\t\t-- 等待弹出窗口\"委托确认提示\"\n\t\t\t\trepeat until window \"委托确认提示\" exists\n\t\t\t\tend repeat\n\n\t\t\t\tset v_result to v_result & (get name of static text 1 of window \"委托确认提示\")\n\t\t\t\tif isdo then\n\t\t\t\t\tset v_result to v_result & \"Y\"\n\t\t\t\t\ttell button \"卖出\" of window \"委托确认提示\" to click\n\t\t\t\telse\n\t\t\t\t\tset v_result to v_result & \"N\"\n\t\t\t\t\ttell button \"取消\" of window \"委托确认提示\" to click\n\t\t\t\t\treturn v_result\n\t\t\t\tend if\n\n\n\t\t\t\t-- 等待确认结果窗口返回\n\t\t\t\t--repeat until window 1 exists\n\t\t\t\t--end repeat\n\t\t\t\trepeat until button \"确认\" of window 1  exists\n\t\t\t\tend repeat\n\n\t\t\t\tset v_result to v_result & (get name of static text of window 1)\n\t\t\t\ttell button \"确认\" of window 1 to click\n\n\t\t\t\treturn v_result\n\t\t\tend tell\n\t\tend tell\n\tend sell_entrust\n\n\t#--------------------------------------------------------------------------------------\n\ton cancel_entrust(para, isdo)\n\t\tset v_result to {}\n\t\tset v_count to 0\n\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\t\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 委托撤单\n\t\t\t\t\tmy toPage(3)\n\n\t\t\t\t\t-- 等待委托数据加载\n\t\t\t\t\t--repeat until row of table of scroll area 1 exists -- fix no row data\n\t\t\t\t\t--end repeat\n\t\t\t\t\tdelay 0.1\n\n\t\t\t\t\t-- 如果有委托数据,则执行撤单\n\t\t\t\t\tif get the (count of row of table of scroll area 1) > 0 then\n\t\t\t\t\t\tif value of attribute \"AXValue\" of checkbox \"全选\" = 0 then\n\t\t\t\t\t\t\tset v_count to get the (count of row of table of scroll area 1) as integer\n\t\t\t\t\t\t\tclick checkbox \"全选\"\n\t\t\t\t\t\tend if\n\t\t\t\t\telse\n\t\t\t\t\t\tset v_result to v_result & \"NO entrust data to cancel\" & \"N\"\n\t\t\t\t\t\treturn v_result\n\t\t\t\t\tend if\n\n\t\t\t\t\t-- 全部撤单\n\t\t\t\t\tignoring application responses --忽略应用的反馈\n\t\t\t\t\t\tclick button \"撤 单\"\n\t\t\t\t\tend ignoring\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\n\n\t\t-- 杀掉 System Events 应用\n\t\tdelay 0.1 --自定义 UI 反馈的等待时间为0.1 秒\n\t\tdo shell script \"killall System\\\\\\ Events\"   -- outside in applescript editor using two \\\\\n\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\t-- afer do\n\t\t\t\tif v_count > 1 then\n\t\t\t\t\t-- 等待弹出窗口\"委托确认提示\"\n\t\t\t\t\trepeat until window \"委托确认提示\" exists\n\t\t\t\t\tend repeat\n\t\t\t\t\t\n\t\t\t\t\tset v_result to v_result & (get value of static text 1 of window \"委托确认提示\")\n\t\t\t\t\tif isdo then\n\t\t\t\t\t\tset v_result to v_result & \"Y\"\n\t\t\t\t\t\ttell button \"撤单\" of window \"委托确认提示\" to click\n\t\t\t\t\telse\n\t\t\t\t\t\tset v_result to v_result & \"N\"\n\t\t\t\t\t\ttell button \"取消\" of window \"委托确认提示\" to click\n\t\t\t\t\t\treturn v_result\n\t\t\t\t\tend if\n\t\t\t\telse if v_count = 1 then\n\t\t\t\t\t-- 等待弹出窗口\"委托撤单确认\"\n\t\t\t\t\trepeat until window \"委托撤单确认\" exists\n\t\t\t\t\tend repeat\n\n\t\t\t\t\tset v_result to v_result & (get value of static text 1 of window \"委托撤单确认\")\n\t\t\t\t\tif isdo then\n\t\t\t\t\t\tset v_result to v_result & \"Y\"\n\t\t\t\t\t\ttell button \"撤单\" of window \"委托撤单确认\" to click\n\t\t\t\t\telse\n\t\t\t\t\t\tset v_result to v_result & \"N\"\n\t\t\t\t\t\ttell button \"取消\" of window \"委托撤单确认\" to click\n\t\t\t\t\t\treturn v_result\n\t\t\t\t\tend if\n\t\t\t\tend if\n\n\t\t\t\t-- 等待确认结果窗口返回\n\t\t\t\t--repeat until window 1 exists\n\t\t\t\t--end repeat\n\t\t\t\trepeat until button \"确认\" of window 1 exists\n\t\t\t\tend repeat\n\n\t\t\t\tset v_result to v_result & (get name of static text of window 1)\n\t\t\t\ttell button \"确认\" of window 1 to click\n\n\t\t\t\treturn v_result\n\t\t\tend tell\n\t\tend tell\n\tend cancel_entrust\n\n\t#--------------------------------------------------------------------------------------\n\ton queryAssets()\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 资产查询\n\t\t\t\t\tmy toPage(4)\n\n\t\t\t\t\t-- to do\n\t\t\t\t\tdelay 0.3\n\n\t\t\t\t\t-- 资金信息\n\t\t\t\t\tset a0 to name of buttons of group 1 of table 1 of scroll area 1\n\t\t\t\t\tset a1 to value of UI elements of row of table 1 of scroll area 1\n\t\t\t\t\t\n\t\t\t\t\t-- 持仓信息\n\t\t\t\t\tset a2 to name of buttons of group 1 of table 1 of scroll area 2\n\t\t\t\t\tset a3 to value of UI elements of row of table 1 of scroll area 2\n\t\t\t\n\t\t\t\t\tset result to {a0, a1, a2, a3}\n\t\t\t\t\treturn result\n\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\n\tend queryAssets\n\n\t#--------------------------------------------------------------------------------------\n\ton queryTransaction()\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 成交查询\n\t\t\t\t\tmy toPage(5)\n\n\t\t\t\t\t-- to do\n\t\t\t\t\tdelay 0.2\n\n\t\t\t\t\t-- 成交信息\n\t\t\t\t\tset a0 to name of buttons of group 1 of table 1 of scroll area 1\n\t\t\t\t\tset a1 to value of UI elements of row of table 1 of scroll area 1\n\t\t\t\n\t\t\t\t\tset result to {a0, a1}\n\t\t\t\t\treturn result\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\n\tend queryTrasaction\n\n\t#--------------------------------------------------------------------------------------\n\ton queryEntrust()\n\t\ttell application \"System Events\"\n\t\t\ttell process \"银河玖乐Mac版\"\n\t\t\t\ttell window \"银河玖乐Mac版 V1.0.3\"\n\t\t\t\t\t-- 选中 委托查询\n\t\t\t\t\tmy toPage(6)\n\n\t\t\t\t\t-- to do\n\t\t\t\t\treturn 1\n\t\t\t\tend tell\n\t\t\tend tell\n\t\tend tell\t\n\tend queryEntrust\n''')\n\n\n# --------------------------------------------------------------------------------------\nclass Account :\n\t# ['资金帐号', '银行名称', '币种', '资金余额', '可用资金', '参考市值', '总资产']\n\tdef __init__(self, lname):\n\t\tself.acctId_desc = lname[0]\n\t\tself.bankName_desc = lname[1]\n\t\tself.currency_desc = lname[2]\n\t\tself.balance_desc = lname[3]\n\t\tself.available_desc = lname[4]\n\t\tself.marketValue_desc = lname[5]\n\t\tself.totalAssets_desc = lname[6]\n\n\tdef initData(self, ldata) :\n\t\tif len(ldata) > 0 :\n\t\t\tself.acctId = ldata[0]\n\t\t\tself.bankName = ldata[1]\n\t\t\tself.currency = ldata[2]\n\t\t\tself.balance = ldata[3]\n\t\t\tself.available = ldata[4]\n\t\t\tself.marketValue = ldata[5]\n\t\t\tself.totalAssets = ldata[6]\n\n\tdef __str__(self) :\n\t\tss = \"{}:{},{}:{},{}:{}\".format(self.totalAssets_desc, self.totalAssets,\n\t\t\t\t\t\t\t\t\t\tself.available_desc, self.available, self.balance_desc, self.balance)\n\t\treturn ss\n\n\n# --------------------------------------------------------------------------------------\nclass CapitalInfo :\n\tdef __init__(self, lacc) :\n\t\tself.lacc = lacc\n\n\tdef __str__(self) :\n\t\t_str = \"\\n资金信息\\n\"\n\t\tfor acc in self.lacc :\n\t\t\t_str = _str + str(acc) + '\\n'\n\t\treturn _str\n\n# --------------------------------------------------------------------------------------\nclass Security:\n\t# '证券名称', '证券代码', '当前持仓', '参考盈亏', '股份余额', '股份可用', '参考市值', '参考市价', '参考成本价', '盈亏比例(%)', '买入冻结', '卖出冻结', '股东代码', '交易市场'\n\tdef __init__(self, lname):\n\t\tself.secName_desc = lname[0]\n\t\tself.secCode_desc = lname[1]\n\t\tself.currentCount_desc = lname[2]\n\t\tself.balanceCount_desc = lname[4]\n\t\tself.availableCount_desc = lname[5]\n\t\tself.marketValue_desc = lname[6]\n\t\tself.holderCode_desc = lname[12]\n\t\tself.market_desc = lname[13]\n\n\tdef initData(self, ldata) :\n\t\tif len(ldata) > 0 :\n\t\t\tself.secName = ldata[0]\n\t\t\tself.secCode = ldata[1]\n\t\t\tself.currentCount = ldata[2]\n\t\t\tself.balanceCount = ldata[4]\n\t\t\tself.availableCount = ldata[5]\n\t\t\tself.marketValue = ldata[6]\n\t\t\tself.holderCode = ldata[12]\n\t\t\tself.market = ldata[13]\n\n\tdef __str__(self) :\n\t\tss = \"{}:{},{}:{},{}:{},{}:{},{}:{}\".format(self.secCode_desc, self.secCode,self.secName_desc, self.secName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.currentCount_desc, self.currentCount, self.availableCount_desc,\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.availableCount, self.marketValue_desc, self.marketValue)\n\t\treturn ss\n\n# --------------------------------------------------------------------------------------\nclass PositionInfo :\n\tdef __init__(self, lsec) :\n\t\tself.lsec = lsec\n\n\tdef __str__(self) :\n\t\t_str = \"\\n持仓信息\\n\"\n\t\tfor sec in self.lsec :\n\t\t\t_str = _str + str(sec) + '\\n'\n\t\treturn _str\n\n# --------------------------------------------------------------------------------------\n#['证券名称', '证券代码', '成交日期', '成交时间', '成交价格', '成交数量', '成交金额', '买卖标志', '委托序号', '股东代码', '交易市场']\nclass Transaction :\n\tdef __init__(self, lname):\n\t\tself.secName_desc = lname[0]\n\t\tself.secCode_desc = lname[1]\n\t\tself.tradeDate_desc = lname[2]\n\t\tself.tradeTime_desc = lname[3]\n\t\tself.tradePrice_desc = lname[4]\n\t\tself.tradeCount_desc = lname[5]\n\t\tself.tradeAmount_desc = lname[6]\n\t\tself.tradeOp_desc = lname[7]\n\t\tself.holderCode_desc = lname[9]\n\t\tself.market_desc = lname[10]\n\n\tdef initData(self, ldata) :\n\t\tif len(ldata) > 0 :\n\t\t\tself.secName = ldata[0]\n\t\t\tself.secCode = ldata[1]\n\t\t\tself.tradeDate = ldata[2]\n\t\t\tself.tradeTime = ldata[3]\n\t\t\tself.tradePrice = ldata[4]\n\t\t\tself.tradeCount = ldata[5]\n\t\t\tself.tradeAmount = str(ldata[6])\n\t\t\tself.tradeOp = ldata[7]\n\t\t\tself.holderCode = ldata[9]\n\t\t\tself.market = ldata[10]\n\n\tdef __str__(self) :\n\t\tss = \"{}:{},{}:{},{}:{},{}:{},{}:{},{}:{},{}:{}\".format(self.secCode_desc, self.secCode,self.secName_desc, self.secName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradePrice_desc, self.tradePrice, self.tradeCount_desc, self.tradeCount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradeAmount_desc, self.tradeAmount, self.tradeAmount_desc, self.tradeAmount,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.tradeOp_desc, self.tradeOp)\n\t\treturn ss\n\n# --------------------------------------------------------------------------------------\nclass TransactionInfo :\n\tdef __init__(self, ltra) :\n\t\tself.ltra = ltra\n\n\tdef __str__(self) :\n\t\t_str = \"\\n成交信息\\n\"\n\t\tfor tra in self.ltra :\n\t\t\t_str = _str + str(tra) + '\\n'\n\t\treturn _str\n\n\n\n# --------------------------------------------------------------------------------------\n# --------------------------------------------------------------------------------------\nclass YHClientTrader(BaseTrader):\n\t#\n\t# YHClientTrader - main class to transaction in a real-time way by YH client\n\t#\n\t# ----------------------------------------------------------------------------------\n\tdef __init__(self):\n\t\tpass\n\n\tdef prepare(self,\n        config_path=None,\n        user=None,\n        password=None,\n        exe_path=None,\n        comm_password=None,\n        **kwargs):\n\t\tpass\n\n\tdef exit(self):\n\t\tpass\n\n\t# ----------------------------------------------------------------------------------\n\tdef login(self):\n\t\tresult = scpt.call('login')\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------\n\tdef buy(self, security, price, shares, isdo=False):\n\t\tstart = time.time()\n\t\tprint(\"###BUY### start -- %s:%s:%s\" % (security, price, shares))\n\t\tresult = scpt.call('buy_entrust', [security, str(price), str(shares)], isdo)\n\t\tprint(\"###BUY### %s\" % (self.formatResult(result)))\n\t\tprint(\"###BUY### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------\n\tdef sell(self, security, price, shares, isdo=False):\n\t\tstart = time.time()\n\t\tprint(\"###SEL### start -- %s:%s:%s\" % (security, price, shares))\n\t\tresult = scpt.call('sell_entrust', [security, str(price), str(shares)], isdo)\n\t\tprint(\"###SEL### %s\" % (self.formatResult(result)))\n\t\tprint(\"###SEL### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\tdef cancel_entrusts(self):\n\t\treturn self.cancel_entrust(para=None)\n\n\t# ----------------------------------------------------------------------------------\n\tdef cancel_entrust(self, para=None, isdo=False):\n\t\tstart = time.time()\n\t\tprint(\"###CAN### start -- cancel all entrust\")\n\t\tresult = scpt.call('cancel_entrust', para, isdo)\n\t\tprint(\"###CAN### %s\" % (self.formatResult(result)))\n\t\tprint(\"###CAN### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------\n\t@property\n\tdef balance(self):\n\t\tstart = time.time()\n\t\tprint(\"###ASS### start -- query assets\")\n\t\tresult = scpt.call('queryAssets')\n\n\t\tlcap = []\n\t\tcapName = result[0]\n\t\tfor x, capData in enumerate(result[1]):\n\t\t\tcapData = result[1][x]\n\t\t\tacc = Account(capName)\n\t\t\tacc.initData(capData)\n\t\t\tlcap.append(acc)\n\t\tcapInfo = CapitalInfo(lcap)\n\n\t\tlpos = []\n\t\tposName = result[2]\n\t\tfor x, posData in enumerate(result[3]):\n\t\t\tposData = result[3][x]\n\t\t\tsec = Security(posName)\n\t\t\tsec.initData(posData)\n\t\t\tlpos.append(sec)\n\t\tposInfo = PositionInfo(lpos)\n\n\t\tprint(\"###ASS### %s%s\" % (capInfo, posInfo))\n\t\tprint(\"###ASS### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\t@property\n\tdef position(self):\n\t\treturn self.balance()\n\n\t# ----------------------------------------------------------------------------------\n\tdef transaction(self):\n\t\tstart = time.time()\n\t\tprint(\"###TRA### start -- query transcation\")\n\t\tresult = scpt.call('queryTransaction')\n\n\t\tltra = []\n\t\ttraName = result[0]\n\t\tfor x, traData in enumerate(result[1]):\n\t\t\ttraData = result[1][x]\n\t\t\ttra = Transaction(traName)\n\t\t\ttra.initData(traData)\n\t\t\tif tra.tradeAmount != '.00' :\n\t\t\t\tltra.append(tra)\n\t\ttraInfo = TransactionInfo(ltra)\n\n\t\tprint(\"###TRA### %s\" % traInfo)\n\t\tprint(\"###TRA### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------\n\tdef entrust(self):\n\t\tstart = time.time()\n\t\tprint(\"###ENT### start -- query entrust\")\n\t\tresult = scpt.call('queryEntrust')\n\t\tprint(\"###ENT### %s\" % result)\n\t\tprint(\"###ENT### end -- \", round(time.time() - start, 2), \"seconds\")\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------\n\tdef formatResult(self, result):\n\t\t# ['买入委托\\n0560507210\\n159901\\n深100ETF\\n限价委托\\n3.005\\n100', 'Y', '错误', '-150906130[-150906130]资金可用数不足,尚需300.60', AEType(b'msng')]\n\t\t# ['买入委托\\n0560507210\\n159901\\n深100ETF\\n限价委托\\n3.005\\n100', 'N']\n\t\t# ['\\n确定要撤销选中的所有委托?', 'Y', '温馨提示', '批量撤单\\n���功数量:0\\n失败数量:3', AEType(b'msng')]\n\t\tif len(result) == 2:\n\t\t\tcon = result[0].replace('\\n', '|')\n\t\t\tre = \"{}\".format(result[1])\n\t\telif len(result) == 5:\n\t\t\tcon = result[0].replace('\\n', '|')\n\t\t\tre = \"{} {}:{}\".format(result[1], result[2], result[3].replace('\\n', '|'))\n\t\telse:\n\t\t\treturn result\n\t\treturn \"[条件]{} [结果]{}\".format(con, re)\n\n\n\n# --------------------------------------------------------------------------------------\n# --------------------------------------------------------------------------------------\n# BELOW CODE FOR TEST PURPOSE\n\n# demo data\n# - test buy list\nbuylist = [['204001','5.500','100'],\n\t\t\t['131810','5.500','100'],\n\t\t\t['511850','95.000','100'],\n\t\t\t['159901','3.005','100'],\n\t\t\t['600993','11.88','100'],\n\t\t\t['300005','2.99','100']]\n\n# - test sell list\nselllist = [['204001','5.500','100'],\n\t\t\t['131810','5.500','100'],\n\t\t\t['159901','3.500','100'],\n\t\t\t['511660','100.02','1'],\n\t\t\t['511850','100.03','100']]\n\n# Test with buy and sell lit\ndef testbuyNsellist() :\n\t# 构造YHClientTrader的实例\n\ttrader = YHClientTrader()\n\n\tfor item in buylist :\n\t\ttrader.buy(item, isdo=True)\n\n\tfor item in selllist :\n\t\ttrader.sell(item, isdo=True)\n\n\n# General TEST\ndef test():\n\t# 构造YHClientTrader的实例\n\ttrader = YHClientTrader()\n\t# GC-001:204001 R-001:131810 财富宝E:511850 深100ETF:159901\n\t#trader.buy(['159901', '3.005', '100'], isdo=True) # 深100ETF\n\ttrader.buy(['131810', '5.500', '100'], isdo=False) # R-001\n\t#trader.buy(['511810', '95', '100'], isdo=True)\n\t#trader.sell(['159901', '3.340', '300'], isdo=True)\n\t#trader.sell(['131810', '5.500', '50'], isdo=True)\n\t#trader.sell(['511990', '105', '100'], isdo=True)\n\t#trader.cancel(isdo=True)\n\t#trader.queryAssets()\n\t# trader.queryTransaction()\n\t#trader.queryEntrust()\n\t#trader.formatResult(\"\")\n\n\n# Regression TEST\ndef testall() :\n\tn = 0\n\twhile n < 1:\n\t\ttest()\n\t\t#testbuyNsellist()\n\t\tn += 1\n\n\n# --------------------------------------------------------------------------------------\n\nif __name__ == '__main__' :\n\t#testall()\n\ttest()\n\n\n\n\n\n\n\n","sub_path":"easytrader/trader/client/mac/yh_clienttrader.py","file_name":"yh_clienttrader.py","file_ext":"py","file_size_in_byte":20615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"378514463","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass Equation(models.Model):\n    id_equation = models.IntegerField(db_column='id_Equation', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    type = models.TextField(blank=True, null=False)\n\n    class Meta:\n        db_table = 'Equation'\n\n\nclass EquationHasOperateur(models.Model):\n    id_equation = models.ForeignKey(Equation, db_column='id_Equation', blank=True, null=False)  # Field name made lowercase.\n    nom_operateur = models.ForeignKey('Operateur', db_column='nom_Operateur', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Equation_has_Operateur'\n\n\nclass EquationHasParametre(models.Model):\n    id_equation = models.ForeignKey(Equation, db_column='id_Equation', blank=True, null=False)  # Field name made lowercase.\n    nom_parametre = models.TextField(db_column='nom_Parametre', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Equation_has_Parametre'\n\n\nclass EquationHasSequation(models.Model):\n    id_equation = models.ForeignKey(Equation, db_column='id_Equation', blank=True, null=False)  # Field name made lowercase.\n    id_sequation = models.ForeignKey('SEquation', db_column='id_SEquation', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Equation_has_SEquation'\n\n\nclass EquationHasVariable(models.Model):\n    id_equation = models.ForeignKey('Equation',db_column='id_Equation', null=False)  # Field name made lowercase.\n    id_Variable = models.ForeignKey('Variable', db_column='id_Variable', null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Equation_has_Variable'\n\n\nclass Operateur(models.Model):\n    nom_operateur = models.TextField(db_column='nom_Operateur', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Operateur'\n\n\nclass Parametre(models.Model):\n    nom_parametre = models.TextField(db_column='nom_Parametre', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    valeur = models.TextField(blank=True, null=True)  # This field type is a guess.\n\n    class Meta:\n        db_table = 'Parametre'\n\n\nclass Profil(models.Model):\n    idprofil = models.IntegerField(db_column='idProfil', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    nomprofil = models.TextField(db_column='nomProfil', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Profil'\n\n\nclass SEquation(models.Model):\n    id_sequation = models.IntegerField(db_column='id_SEquation', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'S_Equation'\n\n\nclass Secteur(models.Model):\n    id_secteur = models.IntegerField(db_column='id_Secteur', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    nom_secteur = models.TextField(db_column='nom_Secteur', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Secteur'\n\n\nclass Temps(models.Model):\n    annee = models.IntegerField(primary_key=True, blank=True, null=False)\n\n    class Meta:\n        db_table = 'Temps'\n\n\nclass Users(models.Model):\n    idusers = models.IntegerField(db_column='idUsers', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    prenom = models.TextField(blank=True, null=True)\n    nom = models.TextField(blank=True, null=True)\n    login = models.TextField(blank=True, null=True)\n    password = models.TextField(blank=True, null=True)\n    idprofil = models.IntegerField(db_column='idProfil', blank=True, null=False)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Users'\n\n\nclass Valeur(models.Model):\n    id_valeur = models.IntegerField(db_column='id_Valeur', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    valeur = models.TextField(blank=True, null=True)  # This field type is a guess.\n    annee = models.IntegerField(blank=True, null=True)\n\n    class Meta:\n        db_table = 'Valeur'\n\n\nclass Variable(models.Model):\n    id_variable = models.IntegerField(db_column='id_Variable', primary_key=True, blank=True, null=False)  # Field name made lowercase.\n    nom_variable = models.TextField(db_column='nom_Variable', blank=True, null=True)  # Field name made lowercase.\n    type = models.TextField(blank=True, null=True)\n    description = models.TextField(blank=True, null=True)\n    sect_var = models.ForeignKey(Secteur, db_column='sect_var', blank=True, null=True)\n    id_valeur = models.ForeignKey(Valeur, db_column='id_Valeur', blank=True, null=True)  # Field name made lowercase.\n\n    class Meta:\n        db_table = 'Variable'\n","sub_path":"ModelMacroEconomique/ModelMacroEconomique/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"384631182","text":"# -*- coding: utf-8 -*-\nfrom dwi_ml.models.embeddings_on_tensors import keys_to_embeddings\nfrom dwi_ml.models.projects.positional_encoding import (\n    keys_to_positional_encodings)\nfrom dwi_ml.models.projects.transforming_tractography import (\n    AbstractTransformerModel)\nfrom dwi_ml.models.utils.direction_getters import check_args_direction_getter\n\nsphere_choices = ['symmetric362', 'symmetric642', 'symmetric724',\n                  'repulsion724', 'repulsion100', 'repulsion200']\n\n\ndef add_transformers_model_args(p):\n    \"\"\" Parameters for TransformingTractography\"\"\"\n    # Mandatory args\n    p.add_argument(\n        'input_group_name',\n        help='Name of the input volume in the hdf5 dataset.')\n    p.add_argument(\n        'streamline_group_name',\n        help=\"Name of the streamlines group in the hdf5 dataset.\")\n\n    # Optional args\n\n    # Step_size / compress\n    AbstractTransformerModel.add_args_main_model(p)\n\n    gx = p.add_argument_group(\"Embedding of the input (X)\")\n    gx.add_argument(\n        '--embedding_key_x', default='nn_embedding',\n        choices=keys_to_embeddings.keys(), metavar='key',\n        help=\"Type of data embedding to use. One of 'no_embedding', \\n\"\n             \"'nn_embedding' (default) or 'cnn_embedding'.\")\n    gx.add_argument(\n        '--embedding_size_x', type=int, metavar='n',\n        help=\"REQUIRED FOR TTST MODELS: \\n\"\n             \"(For TTO and TTS models, embedding size is d_model)\"\n             \"Embedding size for x. Total d_model will be \\n\"\n             \"embedding_size_x + embedding_size_t.\")\n    gx.add_argument(\n        '--position_encoding', default='sinusoidal', metavar='key',\n        choices=keys_to_positional_encodings.keys(),\n        help=\"Type of positional embedding to use. One of 'sinusoidal' \"\n             \"(default)\\n or 'relational'. \")\n\n    gt = p.add_argument_group(\"Embedding of the target (Y)\\n\"\n                              \"(FOR MODELS TTO and TTST)\")\n    gt.add_argument(\n        '--SOS_token_type', default='as_label',\n        choices=['as_label'] + sphere_choices,\n        help=\"Type of token. SOS is always added in the decoder. \"\n             \"Choices are as_label (a \"\n             \"fourth dimension) or \\nas class (directions are sent to classes \"\n             \"on the chosen sphere, and \\nan additional class is added for \"\n             \"SOS.\")\n    gt.add_argument(\n        '--target_embedding', default='nn_embedding',\n        choices=keys_to_embeddings.keys(), metavar='key',\n        help=\"Type of data embedding to use. One of 'no_embedding', \\n\"\n             \"'nn_embedding' (default) or 'cnn_embedding'.\")\n    gt.add_argument(\n        '--embedding_size_t', type=int, metavar='n',\n        help=\"REQUIRED FOR TTST MODEL: Embedding size for t. \\n\"\n             \"Total d_model will be embedding_size_x + embedding_size_t.\")\n\n    gtt = p.add_argument_group(title='Transformer: main layers')\n    gtt.add_argument(\n        '--model', choices={'TTO', 'TTS', 'TTST'}, default='TTO',\n        help=\"One model of transformer amongst the following:\\n\"\n             \" - TTO: Original model. Encoder - Decoder. \\n\"\n             \"   Encoder's input = MRI. Decoder's input = the previous \"\n             \"direction.\\n\"\n             \" - TTS: Encoder only. Input = MRI (TTS for 'Source').\\n\"\n             \" - TTST: Encoder only. Input and previous direction \"\n             \"concatenated. (TTST for 'Source + Target'). See [1].\\n\"\n             \"[1]: https://arxiv.org/abs/1905.06596\")\n    gtt.add_argument(\n        '--d_model', type=int, metavar='n',\n        help=\"REQUIRED FOR TTO AND TTS MODELS:\\n\"\n             \"Output size that will kept constant in all layers to allow skip \"\n             \"connections\\n (embedding size, ffnn output size, attention size).\"\n             \"\\nDefault in Vaswani: 4096.\")\n    gtt.add_argument(\n        '--max_len', type=int, default=1000, metavar='n',\n        help=\"Longest sequence allowed. Other sequences will be zero-padded \\n\"\n             \"up to that length (but attention can't attend to padded \"\n             \"timepoints).\\nPlease beware that this value influences strongly \"\n             \"the executing time and heaviness.\\nAlso used with sinusoidal \"\n             \"position embedding. [%(default)s]\")\n    gtt.add_argument(\n        '--nheads', type=int, default=8, metavar='n',\n        help=\"Number of heads per layer. Could be different for each layer \\n\"\n             \"but we decided not to implement this possibility. [%(default)s]\")\n    gtt.add_argument(\n        '--n_layers_e', type=int, default=6, metavar='n',\n        help=\"Number of encoding layers. [%(default)s]\")\n    gtt.add_argument(\n        '--n_layers_d', type=int, metavar='n',\n        help=\"TTO MODEL ONLY: Number of decoding layers. Default: Same as \"\n             \"n_layer_e.\")\n    gtt.add_argument(\n        '--dropout_rate', type=float, default=0.1, metavar='r',\n        help=\"Dropout rate for all dropout layers. Again, could be different\\n\"\n             \"in every layers but that's not the choice we made.\\n\"\n             \"Needed in embedding, encoder and decoder. [%(default)s]\")\n    gtt.add_argument(\n        '--ffnn_hidden_size', type=int, default=None, metavar='n',\n        help=\"Size of the feed-forward neural network (FFNN) layer in the \\n\"\n             \"encoder and decoder layers. The FFNN is composed of two linear\\n\"\n             \"layers. This is the size of the output of the first one. \\n\"\n             \"Default: data_embedding_size/2\")\n    gtt.add_argument(\n        '--activation', choices=['relu', 'gelu'], default='relu',\n        metavar='key',\n        help=\"Choice of activation function in the FFNN. One of 'relu' or \\n\"\n             \"'gelu'. [%(default)s]\")\n    gtt.add_argument(\n        '--norm_first', type=bool, default=False, metavar='True/False',\n        help=\"If True, encoder and decoder layers will perform LayerNorm \"\n             \"before \\nother attention and feedforward operations, otherwise \"\n             \"after.\\n Torch default + in original paper: False. \\nIn the \"\n             \"tensor2tensor code, they suggest that learning is more robust \"\n             \"when \\npreprocessing each layer with the norm. Default: False.\")\n    gtt.add_argument(\n        \"--start_from_copy_prev\", action='store_true',\n        help=\"If set, final_output = previous_dir + model_output.\")\n\n    g = p.add_argument_group(\"Neighborhood\")\n    AbstractTransformerModel.add_neighborhood_args_to_parser(g)\n\n    g = p.add_argument_group(\"Output\")\n    AbstractTransformerModel.add_args_tracking_model(g)\n","sub_path":"dwi_ml/models/projects/transformers_utils.py","file_name":"transformers_utils.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"406546288","text":"#!/home/uesleisutil/anaconda3/bin/python python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFile name:     make_roms_grid.py\nAuthor:        Ueslei Adriano Sutil\nEmail:         uesleisutil1@gmail.com\nCreated:       17 June 2016\nLast modified: 04 July 2019\nVersion:       6.1\n\nVariable options:\n    - grd_name         As mentioned in gridid.txt Pyroms file;\n    - intrp_method    'linear' or 'nn' for nearest neightborhood;\n    - grid_resolution  The ETOPO1 spatial resolution is 1/60°. If you desire a 1/12° spatial resolution, choose 5 because 5/60 = 1/12°\n                       The SRTM30+ spatial resolution is 1/120°. If you desire a 1/12° spatial resolution, choose 10 because 10/120 = 1/12°;\n    - max_depth        The grid max depth (m). \n\nDownload ETOPO1 here:\n    https://rda.ucar.edu/datasets/ds759.4/index.html#!description\nReference: \n    Amante, C. and B. W. Eakins, 2009: ETOPO1 1 Arc-Minute Global Relief Model: Procedures, Data Sources and Analysis. 24, NOAA Technical Memorandum NESDIS NGDC, 19 pp.\n\nDownload SRTM30_plus here:\n    https://topex.ucsd.edu/WWW_html/srtm30_plus.html\nReference:\n    Becker, J. J., D. T. Sandwell, W. H. F. Smith, J. Braud, B. Binder, J. Depner, D. Fabre, J. Factor, S. Ingalls, S-H. Kim, R. Ladner, K. Marks, S. Nelson, A. Pharaoh, R. Trimmer, J. Von Rosenberg, G. Wallace, P. Weatherall., Global Bathymetry and Elevation Data at 30 Arc Seconds Resolution: SRTM30_PLUS, Marine Geodesy, 32:4, 355-371, 2009.\n\"\"\"\n\nfrom   mpl_toolkits.basemap import Basemap\nfrom   bathy_smoother       import bathy_tools, bathy_smoothing\nimport mpl_toolkits.basemap as mp\nimport numpy                as np\nimport netCDF4\nimport pyroms\nimport pyroms_toolbox\nfrom   sty                 import bg\n\n# Outputs names.\ngrd_name              = 'atlsw_op'\ngrd_final             = grd_name+'_grd.nc'\netopo1_dir            = '/home/ueslei/Documents/model2roms/grid/etopo1.nc'\nsrtm_dir              = '/home/ueslei/Documents/model2roms/grid/topo30_atlsw.nc'\n\n# Grid settings.\nhmin                  = 20\ntheta_b               = 0.6\ntheta_s               = 5.0\nTcline                = 50\nN                     = 30\nrmax                  = 0.45\nintrp_method          = 'linear'\ngrid_resolution       = 10\nmax_depth             = -5000\n\n\n# NOTE: Do not need to change above.\n\n# Open bathymetry file.\nprint(bg.da_cyan+\"Choose the Digital Elevation Model: (1) ETOPO1 or (2) SRTM30+, then press the [ENTER] buttom:\"+bg.rs)\ngrid_choice = input()\nif grid_choice==\"1\":\n    data = netCDF4.Dataset(etopo1_dir, 'r')\n    lons = data.variables[u'x'][:]\n    lats = data.variables[u'y'][:]\n    cota = data.variables[u'z'][:]\n    cota = np.array(cota, dtype='float32')\nelif grid_choice==\"2\":\n    data = netCDF4.Dataset(srtm_dir, 'r')\n    lons = data.variables[u'lon'][:]\n    lats = data.variables[u'lat'][:]\n    cota = data.variables[u'z'][:]\n    cota = np.array(cota, dtype='float32')\n\n# Grid max depth.\nhcopy = cota.copy()\nfor i in range(len(cota[:,1])):\n    for j in range(len(cota[1,:])):\n        if hcopy[i,j]<=max_depth:\n            hcopy[i,j]=max_depth\ncota = hcopy\n\n# Generating the desired resolution.\nresol     = lons[1]-lons[0]\nresol     = (resol*grid_resolution)\nprint(bg.da_cyan+'The ROMS grid spatial resolution is:',resol*100,'km x',resol*100,'km.'+bg.rs)\nlons1     = np.arange(lons.min(),lons.max(),resol)\nlats1     = np.arange(lats.min(),lats.max(),resol)\nlon1,lat1 = np.meshgrid(lons1, lats1)\ncota1     = mp.interp(cota,lons,lats,lon1,lat1,checkbounds=False,masked=False,order=1)\n\n# Grid dimension.\nMm   = len(lats1)\nLm   = len(lons1)\nlon0 = lons1.min() ; lat0 =lats1.max()\nlon1 = lons1.min() ; lat1 =lats1.min()\nlon2 = lons1.max() ; lat2 =lats1.min()\nlon3 = lons1.max() ; lat3 =lats1.max()\n\n# Choosing grid projection.\nprint(bg.da_cyan+\"Choose the ROMS grid projection: (1) Mercator, (2) Polar or (3) Lambert Conformal, then press the [ENTER] buttom:\"+bg.rs)\nmap_projection = input()\nif map_projection=='1':\n    map = Basemap(projection='merc', llcrnrlon=lons1.min(), llcrnrlat=lats1.min(),urcrnrlon=lons1.max(), urcrnrlat=lats1.max(), resolution='f')\nif map_projection=='2':\n    map = Basemap(projection='spstere',boundinglat=-45,lon_0=90,resolution='f') \nif map_projection=='3':\n    map = Basemap(width=12000000,height=9000000,rsphere=(6378137.00,6356752.3142),resolution='f',area_thresh=1000.,projection='lcc',lat_0=lat0, lat_1=lat1, lat_2=lat3, lon_0 =lon0)\n\nlonp = np.array([lon0, lon1, lon2, lon3])\nlatp = np.array([lat0, lat1, lat2, lat3])\nbeta = np.array([1., 1., 1., 1.])\n\n# Start generating the new grid.\nhgrd       = pyroms.grid.Gridgen(lonp, latp, beta, (Mm,Lm),proj=map)\nlonv, latv = map(hgrd.x_vert, hgrd.y_vert, inverse=True)\nhgrd       = pyroms.grid.CGrid_geo(lonv, latv, map)\n\nfor verts in map.coastsegs:\n    hgrd.mask_polygon(verts)\n\n# Check the ocean-continent mask and edit if necessary.\ncoast = pyroms.utility.get_coast_from_map(map)\npyroms.grid.edit_mask_mesh_ij(hgrd, coast=coast)\n\n# Interpolate new bathymetry.\nh = mp.interp(cota1,lons1,lats1,hgrd.lon_rho,hgrd.lat_rho,checkbounds=False,masked=False,order=0)\n\n# Save raw bathymetry.\nhraw=h.copy()\n\n# ROMS depth is positive.\nhh = -h\n\n# Depth deeper than hmin.\nh = np.where(hh < hmin, hmin, hh)\n\n# Smooth the raw bathy using the direct iterative method from Martinho and Batteen (2006).\nRoughMat = bathy_tools.RoughnessMatrix(h, hgrd.mask_rho)\nprint ('Currently, the max roughness value is: ', RoughMat.max())\nh        = bathy_smoothing.smoothing_Positive_rx0(hgrd.mask_rho, h, rmax)\nh        = bathy_smoothing.smoothing_Laplacian_rx0(hgrd.mask_rho, h, rmax)\nRoughMat = bathy_tools.RoughnessMatrix(h, hgrd.mask_rho)\nprint (('After the filters, the max roughness value is: ', RoughMat.max()))\nhgrd.h   = h\n\n# Vertical levels.\nvgrd = pyroms.vgrid.s_coordinate_4(h, theta_b, theta_s, Tcline, N, hraw=hraw)\n\n# ROMS grid.\ngrd = pyroms.grid.ROMS_Grid(grd_name, hgrd, vgrd)\n\n# Write grid to netcdf file.\npyroms.grid.write_ROMS_grid(grd, grd_final)\n","sub_path":"grid/make_roms_grid.py","file_name":"make_roms_grid.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"140274799","text":"combustiveis = {1: ['Alcool', 0], 2: ['Gasolina', 0], 3: ['Diesel', 0]}\n\nwhile True:\n\n    tipo = int(input())\n\n    if tipo == 4:\n        break\n    elif tipo in combustiveis:\n        combustiveis[tipo][1] += 1\n\nprint('MUITO OBRIGADO')\n\nfor combustivel in combustiveis.items():\n\n    print(combustivel[1][0] + ':', combustivel[1][1])\n","sub_path":"URIs/Iniciante/1134.py","file_name":"1134.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"475167991","text":"import io\nimport ctypes\nInstNotFound = \"Instruction NOT FOUND \"\nRegNotFound = \"Register NOT FOUND \"\n#Перевод числа в бинарную строку со знаковым разрешением\ndef Addr2Bin(num, length):\n    i = bin(num)\n    if (num < 0):\n        i = i[3:]\n    else:\n        i = i[2:]\n\n    if len(i) > length - 1: # Проверка на превышение лимита\n        ERROR(\"Error while translate number \" + str(num) + \". Length's limit exceeded.\")\n\n    i = i.zfill(length-1)\n    if num < 0:\n        i = '1' + i\n    else:\n        i = '0' + i\n\n    return i;\n#Перевод числа в бинарную строку без знакового разрешения\ndef Addr2BinU(num, length):\n    i = bin(num)\n    if (num < 0):\n        i = i[3:]\n    else:\n        i = i[2:]\n    if len(i) > length: # Проверка на превышение лимита\n        ERROR(\"Error while translate number \" + str(num) + \". Length's limit exceeded.\")\n\n    i = i.zfill(length)\n    return i;\n#Перевод строки в число,с учетом системы счисления\ndef Str2Num(strnum):\n    num = 0\n    if strnum.startswith('0X'): # Проверяем на 16-ю систему счисления\n        num = int(strnum[2:], 16)\n\n    elif strnum.startswith('0B'): # Проверяем на 2-ю систему счисления\n        num = int(strnum[2:], 2)\n\n    else: # Если не то не другое, значит 10-я система счисления\n        num = int(strnum)\n\n    return num\n#Удаление запятых между символами\ndef DeleteCommas(elements):\n    for i in range(len(elements)):\n        if elements[i].endswith(\",\"):\n            elements[i] = elements[i][:-1]\n\n    return elements;\n# Функция вывода ошибки\ndef ERROR (error_string):\n    ctypes.windll.user32.MessageBoxW(0, error_string, 'Error', 0)\n    exit(0)\n#Функция вывода в бинарный файл\ndef WriteBinary(ofile, data):\n    cur = 0\n    while cur < len(data):\n        c = int(data[cur:cur+8], 2)\n        ofile.write(bytes(chr(c), 'iso8859-1'))\n        cur += 8\n#Функция разделения файла по директивам\ndef SplitToDierctives(ofile):\n    directs = {};\n    curr_d = \"\";\n    for line in ofile:\n        line = line.strip() + '\\n'\n        line = line.upper();\n        if line.startswith('#') :\n            continue;\n\n        if '#' in line: # Удаление комментария в строке\n            line = line[:line.find('#')] + '\\n'\n            line = line.strip() + '\\n'\n\n        if line.startswith('.'): # Нахождение директив\n            # Обработка .code и .data\n            if line.startswith('.CODE'):\n                curr_d = \".CODE\"\n                if \".CODE\" not in directs:\n                    directs[\".CODE\"] = '';\n\n            if line.startswith('.DATA'):\n                curr_d = \".DATA\"\n                if \".DATA\" not in directs:\n                    directs[\".DATA\"] = '';\n\n        else:\n            if curr_d != '':\n                if len(line) > 1:\n                    directs[curr_d] += line\n\n            elif len(line) > 1:\n                curr_d = '.CODE'\n                directs[curr_d] = line\n\n    return directs;\n#Функция для получения меток и удаления их из кода\ndef GetLabels(code):\n    ncode = [];\n    labels = {};\n    addr = 0;\n    for line in code:\n        if \":\" in line:\n            line_elements = line.split(\":\")\n            labels[line_elements[0]] = addr;\n            if len(line_elements[1]) > 3:\n                ncode.append(line_elements[1].strip())\n\n        else:\n            ncode.append(line)\n\n        addr += 4;\n\n    return [ncode, labels]\n#.data\n#name value\n#name1 [value1,value2,value3...]\n#name2[20]\n#Функция для обработки директивы .DATA\ndef ParseData(data):\n    dataD = \"\";\n    keys = {}\n    for line in data:\n        if \"[\" not in line:\n            line = line.split(\" \")\n            if len(line) == 2:\n                keys[line[0]] = int(len(dataD)/8)\n                dataD += Addr2Bin(Str2Num(line[1]), 32)\n            else:\n                ERROR(\"Error while .data parsing in line: \" + line)\n        elif \" \" not in line:\n            if \"[\" in line:\n                line = line.split(\"[\")\n                if len(line) == 2:\n                    num = Str2Num(line[1][:-1])\n                    for i in range(num):\n                        keys[line[0] + \"[\"+ str(i) + \"]\"] = int(len(dataD)/8)\n                        dataD += Addr2Bin(0, 32)\n                else:\n                    ERROR(\"Error while .data parsing in line: \" + line)\n            else:\n                ERROR(\"Error while .data parsing in line: \" + line)\n        else:\n            line = line.split(\" \")\n            if len(line) == 2:\n                if line[1].startswith(\"[\") and line[1].endswith(\"]\"):\n                    line[1] = line[1][1:-1]\n                    line[1] = line[1].split(\",\")\n                    for i in range(len(line[1])):\n                        keys[line[0] + \"[\"+ str(i) + \"]\"] = int(len(dataD)/8)\n                        dataD += Addr2Bin(Str2Num(line[1][i]), 32)\n                else:\n                    ERROR(\"Error while .data parsing in line: \" + line)\n            else:\n                ERROR(\"Error while .data parsing in line: \" + line)\n\n    return [keys, dataD]\n\n#Функция для чтения конфигурационного файла\ndef readConfig(file_addr):\n    cfg = open(file_addr)\n    result = {}\n    for line in cfg:\n        line = line.split(\"=\")\n        line[0] = line[0].strip()\n        line[1] = line[1].strip()\n        result[line[0]] = line[1];\n\n    return result;\n","sub_path":"assembler/Service.py","file_name":"Service.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"135930678","text":"#coding=utf-8\n#\"py play MP3\"\nimport pygame,sys\n  \nfilename = \"Path\\ filename.mp3\"\npygame.init()\npygame.mixer.init()\nscreen_size = (500, 180)  \nbackgroundcolor = (0, 0, 0)  \n\n#创建一个窗口,窗口大小为500*300   \ntry:\n    screen = pygame.display.set_mode(screen_size)\nexcept pygame.error as e:\n    print(e)\n    pygame.quit()\n    exit()\n\n#定义窗口的标题 \npygame.display.set_caption('Alert')  \n#用颜色填充窗口  \nscreen.fill(backgroundcolor)\npygame.time.delay(1000)\npygame.mixer.music.set_volume(0.5)\npygame.mixer.music.load(filename)\npygame.mixer.music.play(1000)\n#创建字体对象\nmy_font = pygame.font.SysFont('microsofttaile',22)\n#得到字体的高度值\nfont_height = my_font.get_linesize()\ny = screen_size[1]-font_height\nscreen.blit(my_font.render(\"Alert info! press E or exit to exit\", True, (255,255,255)), (0, y/2)) \n\nwhile True:\n     for event in pygame.event.get():\n         if event.type == pygame.QUIT:\n             sys.exit()\n         if event.type == pygame.KEYDOWN:\n             if event.key == pygame.K_e:\n                 sys.exit()\n     #    screen.blit(bg, (0, 0))\n         pygame.display.update()\n","sub_path":"bellRing.py","file_name":"bellRing.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"610643853","text":"class Solution(object):\n    def twoSum(self, numbers, t):\n        if not numbers: return []\n        def bs(nums, l, r, t):\n            l, r = min(l, len(nums)-1), max(0, r)\n            if nums[l] == t or l >= r: return l\n            if nums[r] == t: return r\n            midx = (l+r)//2\n            if nums[midx] == t: return midx\n            if nums[midx] > t: return bs(nums, l, midx-1, t)\n            return bs(nums, midx+1, r, t)\n        midx = bs(numbers, 0, len(numbers)-1, int(t/2))\n        l, r, d = midx, midx+1, {}\n        while l>=0 or r= 0:\n                if numbers[l] in d: return list(sorted([d[numbers[l]]+1, l+1]))\n                d[t-numbers[l]], l = l, l-1\n            if r < len(numbers):\n                if numbers[r] in d: return list(sorted([d[numbers[r]]+1, r+1]))\n                d[t-numbers[r]], r = r, r+1\n        return []","sub_path":"src/cgml/leetcode/enumerated/_167e_two_sum_array_input_sorted.py","file_name":"_167e_two_sum_array_input_sorted.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"528964179","text":"from flask import Flask, jsonify, request\napp = Flask(__name__)\n# define a predict function as an endpoint \n@app.route(\"/predict\", methods=[\"GET\",\"POST\"])\ndef predict():\n    data = {\"success\": False}\n    # get the request parameters\n    params = request.json\n    if (params == None):\n        params = request.args\n    # if parameters are found, echo the msg parameter \n    if (params != None):\n        data[\"response\"] = params.get(\"msg\")\n        data[\"success\"] = True\n        data['fuckery'] = True\n    # return a response in json format \n    return jsonify(data)\n# start the flask app, allow remote connections\napp.run(host='0.0.0.0')","sub_path":"Week5/aws_flask.py","file_name":"aws_flask.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"485493173","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom django.shortcuts import redirect\n\nfrom .models import Lesson\nfrom .forms import PostForm\ndef lessons_list(request):\n    lessons = Lesson.objects.order_by('lesson_name')\n    return render(request, 'my_app/lessons_list.html', {'lessons': lessons})\n\n\ndef lesson_new(request):\n    if request.method == \"POST\":\n        form = PostForm(request.POST)\n\n        if form.is_valid():\n            post = form.save(commit=False)\n            post.author = request.user\n            post.created_date = timezone.now()\n            post.save()\n            return redirect('lessons_list')\n    else:\n        form = PostForm()\n        return render(request, 'my_app/post_edit.html',{'form': form})\n\n","sub_path":"my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"229184877","text":"from sklearn import linear_model, cross_validation, datasets,\\\n    metrics\nimport mord\nimport numpy as np\n\nboston = datasets.load_boston()\nX, y = boston.data, np.round(boston.target).astype(np.int)\ny -= y.min()\n\nclf1 = linear_model.LogisticRegression(\n    solver='lbfgs', multi_class='multinomial')\nclf1.fit(X, y)\nprint('Mean Absolute Error of LogisticRegression: %s' %\n      metrics.mean_absolute_error(clf1.predict(X), y))\n\n\nclf2 = mord.LogisticAT(alpha=1.)\nclf2.fit(X, y)\nprint('Mean Absolute Error of LogisticAT %s' %\n      metrics.mean_absolute_error(clf2.predict(X), y))\n","sub_path":"examples/bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"605984173","text":"\"\"\"Module capable of generating an animation made of \ngeometrical shapes moving around randomly on a screen.\n\"\"\"\n\nimport pygame\nimport random as rd\nimport numpy as np\n\nimport os\nimport sys\nCURRENT_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(CURRENT_DIR))\n\nfrom constants import nb_images_train, nb_images_test, nb_obj, a, b, c\nfrom utils import normalized_sigmoid_fkt as sig_moid\nsigmoid = lambda x: sig_moid(x, a=0.2, b=14)\n\nnp.random.seed(123)\n\ndflt_dir = \"../data/\"\nif not os.path.exists(dflt_dir):\n    os.makedirs(dflt_dir)\n    print(\"Created cached directory to store the generated files\")\n\npy_sv = dflt_dir + \"pyobj_dir/\"\nif not os.path.exists(py_sv):\n    os.makedirs(py_sv)\n\ntrnset_arr = \"y_trn.npy\"\ntstset_arr = \"y_tst.npy\"\n\ntrnset_sv = py_sv + trnset_arr\ntstset_sv = py_sv + tstset_arr\n\nanim_dir = dflt_dir + \"anim/\"\nif not os.path.exists(anim_dir):\n    os.makedirs(anim_dir)\n\n\nblack = 0, 0, 0\nwhite = 255, 255, 255\nred = 80, 80, 80\ngreen = 150, 150, 150\nblue = 0, 0, 0\nblue = green = red = white  # might be temporary\ncolors = [red, green, blue]\nincr = -400\nnb_images = nb_images_train + nb_images_test\n\nsquare_size = 20\ncircle_radius = 20\nsize = width, height = 300, 200\n\nx = 50\nleft_edge = x\nright_edge = x + a\ntop_edge = 0\nbottom_edge = b\n\npygame.init()\nscreen = pygame.display.set_mode(size)\n\n\ndef random_color():\n    i = rd.randrange(len(colors))\n    return colors[i]\n\n\ndef random_speed():\n    \"\"\"Produces a random speed when called\n    \t:return [a, b]\n    \t:a : float in [-2; -1] or [1; 2]\n    \t:b : same\n    \"\"\"\n    dirx, diry = rd.randint(0, 1), rd.randint(0, 1)\n    return [rd.uniform(1, 2) * (-1) ** dirx, rd.uniform(1, 2) * (-1) ** diry]\n\n\nclass Obj():\n    \"\"\" Objects that will pass through the screen \"\"\"\n\n    def __init__(self, rect, img=None, shape=None, color=None):\n        self.rect = rect\n        self.speed = random_speed()\n        self.img = img\n        self.color = random_color() if color is None else color\n        self.shape = shape\n\n\nobj_patterns = []\nli_obj = []\n\npathname = os.path.dirname(sys.argv[0])\nball = pygame.image.load(os.path.abspath(pathname) + \"/ball.bmp\")\nballrect = ball.get_rect()\n\n\ndef new_square():\n    \"\"\"Pops a new square either on the right or the left of the screen\n    (chosen randomly)\n    \"\"\"\n   \n    choice = rd.randint(0, 1)\n    squarect = pygame.Rect(0 if choice else width - x, rd.randrange(height - x),\n                           square_size, square_size)\n    return squarect, None, \"square\"\n\n\ndef new_circle():\n    \"\"\"Pops a new circle\"\"\"\n\n    choice = rd.randint(0, 1)\n    circle_rect = pygame.Rect(0 if choice else width - 2 * circle_radius,\n                              rd.randrange(\n                                  height - 2 * circle_radius), 2 * circle_radius,\n                              2 * circle_radius)\n    return circle_rect, None, \"circle\"\n\n\ndef new_ball():\n    return ball.get_rect(), ball\n\nobj_patterns.append(new_square)\nobj_patterns.append(new_circle)\n# obj_patterns.append(new_ball)\n\n\ndef add_obj():\n    \"\"\" Génère un objet pris au hasard parmi les types possibles \"\"\"\n    i = rd.randrange(len(obj_patterns))\n    r, img, shape = obj_patterns[i]()\n    li_obj.append(Obj(r, img, shape=shape))\n\n# Génère les objets de l'animation\n#r, img = new_ball()\n#li_obj.append(Obj(r, img))\nr, img, _ = new_circle()\nli_obj.append(Obj(r, img, shape=\"circle\"))\nr, img, _ = new_square()\nli_obj.append(Obj(r, img, shape=\"square\"))\n\n\n# Already added 2 objs\nfor _ in range(nb_obj - 2):\n    add_obj()\n\n\ndef bounce(obj):\n    rect, speed = obj.rect, obj.speed\n    obj.rect = rect.move(speed)\n    if obj.rect.left < 0 or obj.rect.right > width:\n        obj.speed[0] *= -1\n        r = rd.random()\n        if r > 0.5:\n            obj.speed[1] *= -1\n    if obj.rect.top < 0 or obj.rect.bottom > height:\n        obj.speed[1] *= -1\n        r = rd.random()\n        if r > 0.5:\n            obj.speed[0] *= -1\n\n\ndef in_screen(obj):\n    if obj.rect.left > left_edge and obj.rect.right < right_edge and \\\n       obj.rect.top > top_edge and obj.rect.bottom < bottom_edge:\n        return 1.\n    else:\n        return abs(sigmoid(portion_in_screen(obj)))\n        # return 0\n\n\ndef portion_in_screen(obj):\n    w_prop = 0.\n    h_prop = 0.\n    if obj.rect.right < left_edge or obj.rect.left > right_edge or \\\n       obj.rect.top > bottom_edge:\n        return 0.\n    if obj.rect.right >= left_edge and obj.rect.left <= left_edge:\n        w_prop = (obj.rect.right - left_edge) / obj.rect.width\n    elif obj.rect.left <= right_edge and obj.rect.right >= right_edge:\n        w_prop = (right_edge - obj.rect.left) / obj.rect.width\n    if obj.rect.bottom >= top_edge and obj.rect.top < top_edge:\n        h_prop = (obj.rect.bottom - top_edge) / obj.rect.height\n    elif obj.rect.top <= bottom_edge and obj.rect.bottom >= bottom_edge:\n        h_prop = (bottom_edge - obj.rect.top) / obj.rect.height\n    return (w_prop if h_prop == 0. else (h_prop if w_prop == 0. else (w_prop + h_prop) / 2))\n\n\ndef dist(u, v):\n    (x, y), (z, t) = u, v\n    return sqrt((x - z)**2 + (y - t)**2)\n\n\ndef in_obj(x, y, obj):\n    \"\"\" Is this pixel in the obj or not ? \"\"\"\n    if obj.shape == \"square\":\n        if x >= obj.rect.left and x <= obj.rect.right and y >= obj.rect.top and y <= obj.rect.bottom:\n            return 1.\n        else:\n            return 0.\n    elif obj.shape == \"circle\":\n        if dist(obj.rect.center, (x, y)) <= circle_radius:\n            return 1.\n        else:\n            return 0.\n    print(\"Error in in_obj\")\n\nif len(sys.argv) <= 2:\n    print(\"Default directory for saving images:\", dflt_dir)\n    data_dir = dflt_dir\nelse:\n    data_dir = sys.argv[2]\n\n# Gère l'enregistrement des images générées\nif len(sys.argv) > 1 and sys.argv[1] == \"-s\":\n    print(\"Saving animation and monitoring at\", dflt_dir)\n    eventual_output = lambda: pygame.image.save(\n        screen, anim_dir + str(incr) + \".bmp\")\nelse:\n    eventual_output = lambda: None\n    print(\"Not saving anything. Use argument -s to save in\", dflt_dir)\n\n# Contiennent les \"bonnes réponses\"\n# +1 car on ajoute -1 au début\ny_train = np.array([0.] * (nb_images_train * (nb_obj))\n                   ).reshape(nb_images_train, nb_obj)\ny_test = np.array([0.] * (nb_images_test * (nb_obj))\n                  ).reshape(nb_images_test, nb_obj)\n\n# un peu complexe : pour chaque pixel (a*b dans chaque image), on stocke à\n# chaque instant (nb_images instants) son appartenance aux différents objets\n# sous forme d'une indicatrice (nb_obj objets)\n# y_train_temp = np.array([0.] * (a*b * nb_images_train * nb_obj)\n#                   ).reshape(a*b, nb_images_train, nb_obj)\n# y_test_temp = np.array([0.] * (a*b * nb_images_test * nb_obj)\n#                  ).reshape(a*b, nb_images_test, nb_obj)\n\n# Déroulement de l'animation\nwhile incr <= nb_images:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            sys.exit()\n\n    # drawing the image\n    screen.fill(black)\n    for o in li_obj:\n        bounce(o)\n        if o.shape == \"square\":\n            pygame.draw.rect(screen, o.color, o.rect)\n        elif o.shape == \"circle\":\n            x_pos, y_pos = o.rect.left + circle_radius, o.rect.top + circle_radius\n            pygame.draw.circle(screen, o.color, (x_pos, y_pos), circle_radius)\n        else:\n            screen.blit(o.img, o.rect)\n\n    # refresh the screen. useless for training, but ok for visualizing thedata\n    # being generated\n    pygame.display.flip()\n\n    # Remplit les vecteurs de présence des différents objets\n    # Taille nb_obj\n    if incr <= nb_images_train and incr > 0:\n        for i, o in enumerate(li_obj):\n            y_train[incr - 1][i] = in_screen(o)\n\n#        for x in range(a):\n#            for y in range(b):\n#                for (i, o) in enumerate(li_obj):\n#                    y_train_temp[g(x,y)][incr-1][i] = in_obj(x,y,o)\n\n    elif incr > nb_images_train:\n        for i, o in enumerate(li_obj):\n            y_test[incr - (nb_images_train + 1)][i] = in_screen(o)\n\n#        for x in range(a):\n#            for y in range(b):\n#                for (i, o) in enumerate(li_obj):\n#                    y_test_temp[g(x,y)][incr-(nb_images_train+1)][i] = in_obj(x,y,o)\n\n    # Enregistre l'image selon la situation\n    if incr > 0:\n        eventual_output()\n\n    incr += 1\n\n\n# Cropping images and drawing score\nif 1:\n    from PIL import Image, ImageFont, ImageDraw\n#    font = ImageFont.truetype(\"sans-serif.ttf\", 16)\n    box = (left_edge, top_edge, right_edge, bottom_edge)\n    ind_pic = 1\n    y_trn_ind = []\n    y_tst_ind = []\n    for i in range(1, nb_images + 1):\n        img_path = anim_dir + str(i) + \".bmp\"\n        try:\n            img = Image.open(img_path)\n        except:\n            print(\"Program exiting.\")\n            print(\"Maybe you forgot to use -s and have no files saved yet.\")\n            sys.exit(0)\n\n        area = img.crop(box)\n        y = y_train[i - 1] if i <= nb_images_train else y_test[i -\n                                                               (nb_images_train + 1)]\n        l = [(i + 1) for i in range(nb_obj)]\n        if sum(y) == 0.:\n            # if sum(y) not in l:\n            os.remove(img_path)\n            print(\"Removed\", img_path)\n        else:\n            text = str(y)\n            area.save(anim_dir + str(ind_pic) + \".bmp\", \"BMP\")\n            draw = ImageDraw.Draw(area)\n            draw.text((0, 0), text, (255, 255, 255))\n            monit_dir = dflt_dir + \"monitor/\"\n            if not os.path.exists(monit_dir):\n                os.makedirs(monit_dir)\n            area.save(monit_dir + str(ind_pic) + \".bmp\", \"BMP\")\n            ind_pic += 1\n            if i <= nb_images_train:\n                y_trn_ind.append(i - 1)\n            else:\n                y_tst_ind.append(i - (nb_images_train + 1))\n\n\ny_train = y_train[y_trn_ind]\ny_test = y_test[y_tst_ind]\n\nprint(\"Saving y_train and y_test to\", py_sv)\nnp.save(trnset_sv, y_train)\nnp.save(tstset_sv, y_test)\n\n#print(\"Saving y_train_temp and y_test_temp to\", path_train_temp, \"and\", path_test_temp)\n#np.save(py_sv + , y_train_temp)\n#np.save(path_test_temp, y_test_temp)\n","sub_path":"munge/animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":10069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"310622107","text":"\"\"\" Handle symmetry factor stuff\n\"\"\"\n\nimport automol\nfrom routines.es._routines import conformer\n\n\ndef symmetry_factor(sym_model, spc_dct_i, spc_info, dist_names,\n                    saddle, frm_bnd_key, brk_bnd_key, tors_names,\n                    tors_cnf_save_fs, tors_min_cnf_locs,\n                    sym_cnf_save_fs, sym_min_cnf_locs):\n    \"\"\" Get the overall factor for a species\n    \"\"\"\n\n    form_coords = []\n    if 'sym' in spc_dct_i:\n        sym_factor = spc_dct_i['sym']\n        print('sym_factor from spc_dct_i:', sym_factor)\n    else:\n        if sym_model == 'sampling':\n            if not sym_min_cnf_locs:\n                # Fix the return statement here\n                print('ERROR: Reference geometry is missing for symmetry',\n                      'for species {}'.format(spc_info[0]))\n                return '', 0.\n            sym_geo = sym_cnf_save_fs[-1].file.geometry.read(sym_min_cnf_locs)\n            sym_ene = sym_cnf_save_fs[-1].file.energy.read(sym_min_cnf_locs)\n            if dist_names:\n                zma = tors_cnf_save_fs[-1].file.zmatrix.read(\n                    tors_min_cnf_locs)\n                form_coords = list(\n                    automol.zmatrix.bond_idxs(zma, dist_names[0]))\n                form_coords.extend(list(dist_names[1]))\n            sym_factor = conformer.symmetry_factor(\n                sym_geo, sym_ene, sym_cnf_save_fs, saddle,\n                frm_bnd_key, brk_bnd_key, form_coords, tors_names)\n            print('sym_factor from conformer sampling:', sym_factor)\n        elif sym_model == '1dhr':\n            print('Warning: the 1DHR based symmetry number',\n                  'has not yet been implemented, setting symf to 1.0')\n            sym_factor = 1.0\n        else:\n            # print('Warning: no symmetry model requested,',\n            #       'setting symmetry factor to 1.0')\n            sym_factor = 1.0\n\n    return sym_factor\n\n\ndef tors_mods_on_sym_factor(tors_min_cnf_locs, tors_cnf_save_fs, saddle=False):\n    \"\"\" Decrease the overall molecular symmetry factor by the\n        torsional mode symmetry numbers\n    \"\"\"\n    if tors_min_cnf_locs is not None:\n\n        # Get geometry for the torsional minimum\n        zma = tors_cnf_save_fs[-1].file.zmatrix.read(\n            tors_min_cnf_locs)\n\n        # Set torsional stuff\n        tors_sym_nums = tors.get_tors_sym_nums(\n            spc_dct_i, zma, tors_cnf_save_fs,\n            frm_bnd_key, brk_bnd_key, saddle=False)\n\n        # Divide total sym_factor by rotor sym number\n        for sym_num in tors_sym_nums:\n            sym_factor /= sym_num\n\n    return sym_factor\n","sub_path":"routines/pf/messf/_sym.py","file_name":"_sym.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"253338946","text":"import os\nfrom os import path\nfrom functools import reduce\nimport re\nimport pandas as pd\nfrom rouge import Rouge\nimport nltk\nfrom nltk.tokenize import wordpunct_tokenize\nimport numpy as np\nimport random\nimport sys\nimport tqdm\nfrom collections import Counter\nfrom nltk.translate.bleu_score import corpus_bleu\n\n\ngold_path = sys.argv[1]\ncand_path = sys.argv[2]\nif len(sys.argv) > 3:\n    text_path = sys.argv[3]\nelse:\n    text_path = None\n\ndef calc_duplicate_n_grams_rate(documents):\n    all_ngrams_count = Counter()\n    duplicate_ngrams_count = Counter()\n    for doc in documents:\n        words = doc.split(\" \")\n        for n in range(1, 5):\n            ngrams = [tuple(words[i:i+n]) for i in range(len(words)-n+1)]\n            unique_ngrams = set(ngrams)\n            all_ngrams_count[n] += len(ngrams)\n            duplicate_ngrams_count[n] += len(ngrams) - len(unique_ngrams)\n    return {n: duplicate_ngrams_count[n]/all_ngrams_count[n] if all_ngrams_count[n] else 0.0\n            for n in range(1, 5)}\n\n\ndef calc_metrics(refs, hyps, data, metric=\"all\", meteor_jar=None):\n    metrics = dict()\n    metrics[\"count\"] = len(hyps)\n    metrics[\"text_example\"] = data[-1]\n    metrics[\"ref_example\"] = refs[-1]\n    metrics[\"hyp_example\"] = hyps[-1]\n    many_refs = [[r] if r is not list else r for r in refs]\n    if metric in (\"bleu\", \"all\"):\n        metrics[\"bleu\"] = corpus_bleu(many_refs, hyps)\n    if metric in (\"rouge\", \"all\"):\n        rouge = Rouge()\n        scores = rouge.get_scores(hyps, refs, avg=True)\n        metrics.update(scores)\n    if metric in (\"meteor\", \"all\") and meteor_jar is not None and os.path.exists(meteor_jar):\n        meteor = Meteor(meteor_jar, language=\"ru\")\n        metrics[\"meteor\"] = meteor.compute_score(hyps, many_refs)\n    if metric in (\"duplicate_ngrams\", \"all\"):\n        metrics[\"duplicate_ngrams\"] = dict()\n        metrics[\"duplicate_ngrams\"].update(calc_duplicate_n_grams_rate(hyps))\n    return metrics\n\n\ndef print_metrics(refs, hyps, data, metric=\"all\", meteor_jar=None):\n    metrics = calc_metrics(refs, hyps, data, metric, meteor_jar)\n\n    print(\"-------------METRICS-------------\")\n    print(\"Count:\\t\", metrics[\"count\"])\n    print(\"Text:\\t\", metrics[\"text_example\"])\n    print(\"Ref:\\t\", metrics[\"ref_example\"])\n    print(\"Hyp:\\t\", metrics[\"hyp_example\"])\n\n    if \"bleu\" in metrics:\n        print(\"BLEU:     \\t{:3.2f}\".format(metrics[\"bleu\"] * 100.0))\n    if \"rouge-1\" in metrics:\n        print(\"ROUGE-1-F:\\t{:3.1f}\".format(metrics[\"rouge-1\"]['f'] * 100.0))\n        print(\"ROUGE-2-F:\\t{:3.1f}\".format(metrics[\"rouge-2\"]['f'] * 100.0))\n        print(\"ROUGE-L-F:\\t{:3.1f}\".format(metrics[\"rouge-l\"]['f'] * 100.0))\n        print('ROUGE-mean\\t{:3.1f}'.format((metrics[\"rouge-1\"]['f'] + \\\n                                            metrics[\"rouge-2\"]['f'] + \\\n                                            metrics[\"rouge-l\"]['f']) * 100.0 / 3))\n    if \"meteor\" in metrics:\n        print(\"METEOR:   \\t{:3.2f}\".format(metrics[\"meteor\"] * 100.0))\n    if \"duplicate_ngrams\" in metrics:\n        print(\"Dup 1-grams:\\t{:3.2f}\".format(metrics[\"duplicate_ngrams\"][1] * 100.0))\n        print(\"Dup 2-grams:\\t{:3.2f}\".format(metrics[\"duplicate_ngrams\"][2] * 100.0))\n        print(\"Dup 3-grams:\\t{:3.2f}\".format(metrics[\"duplicate_ngrams\"][3] * 100.0))\n\n\nwith open(gold_path, 'r') as f:\n    gold = f.readlines()\n\ngold  = [' '.join(wordpunct_tokenize(el.strip())) for el in gold]\n\n\nwith open(cand_path, 'r') as f:\n    cand = f.readlines()\n\ncand = [' '.join(wordpunct_tokenize(el.strip())) for el in cand]\n\nif text_path is None:\n    text = ['' for el in range(len(gold))]\nelse:\n    with open(text_path, 'r') as f:\n        text = f.readlines()\n\nprint_metrics(gold, cand, text)\n","sub_path":"src/eval_results.py","file_name":"eval_results.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"145252481","text":"#不停止一直循环输入\nwhile True:\n    # 输入语句\n    tel=input(\"请输入手机号:(输入q退出):\")\n    if tel!=\"q\":#判断是否为q\n        if tel.isdigit():#此方法判断该字符串是否为数字组成\n            if len(tel)==11:#判断字符串长度是否为11位\n                # 使用字符串表达式判断字符串前三位数据区间是否在范围内\n                if eval(tel[:3])>=130 and eval(tel[:3])<=150:\n                    print(\"你输入的手机号是{},属于移动\".format(tel))#条件成立输入语句及把输入字符串值赋值format\n                elif eval(tel[:3])>=151 and eval(tel[:3])<=170:\n                    print(\"你输入的手机号是{},属于联通\".format(tel))\n                elif eval(tel[:3])>=171 and eval(tel[:3])<=199:\n                    print(\"你输入的手机号是{},属于电信\".format(tel))\n                else:\n                    print(\"你输入的电话号码是{},不在号码段内\".format(tel))\n            else:\n                print(\"你输入的电话号码是{},长度是{},位数不对\".format(tel,len(tel)))\n        else:\n            print(\"你输入的电话号码是{},输入的含有非数字\".format(tel,len(tel)))\n    else:\n        break\n","sub_path":"lianxi/tel_lianxi.py","file_name":"tel_lianxi.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"161958227","text":"\"\"\"\n   Inspired by PyXL, register.py.\n\"\"\"\n# stdlib\nfrom __future__ import with_statement\nfrom __future__ import print_function\nimport ast\nimport cStringIO\nimport codecs\nimport encodings\nimport sys\nfrom encodings import utf_8\n\n# third party\nimport astor.codegen\n\n# local\nfrom hy.importer import import_buffer_to_hst, incr_import_buffer_to_ast\nfrom hy.lex import tokenize, LexException, PrematureEndOfInput\n\ndef hy_transform(stream):\n    \"\"\"\n    - read a python code stream\n    - extract lisp code\n    - generate python ast\n    \"\"\"\n    try:\n        py_buffer = \"\"\n        lisp_expr = \"\"\n        prv_char = None\n        in_lisp = False\n        counter = 0\n        ctx = {}\n        for char in stream.read():\n            if not in_lisp and prv_char == \"@\" and char == \"(\":\n                in_lisp = True\n                lisp_expr = \"(\"\n                counter += 1\n                py_buffer = py_buffer[:-1]\n            elif in_lisp:\n                lisp_expr += char\n                if char == \")\":\n                    counter -= 1\n                elif char == \"(\":\n                    counter += 1\n                if counter == 0:\n                    in_lisp = False\n                    genc, ctx = incr_import_buffer_to_ast(lisp_expr, \"none\", ctx=ctx)\n                    py_buffer += astor.codegen.to_source(genc)\n            else:\n                py_buffer += char\n            prv_char = char\n        output = py_buffer\n    except Exception as exc:\n        print(exc)\n        raise\n\n    return output.rstrip()\n\ndef hy_transform_string(text):\n    stream = cStringIO.StringIO(text)\n    return hy_transform(stream)\n\ndef hy_decode(input, errors='strict'):\n    return utf_8.decode(hy_transform_string(input), errors)\n\nclass HyIncrementalDecoder(utf_8.IncrementalDecoder):\n    def decode(self, input, final=False):\n        self.buffer += input\n        if final:\n            buff = self.buffer\n            self.buffer = ''\n            return super(HyIncrementalDecoder, self).decode(\n                hy_transform_string(buff), final=True)\n\nclass HyStreamReader(utf_8.StreamReader):\n    def __init__(self, *args, **kwargs):\n        codecs.StreamReader.__init__(self, *args, **kwargs)\n        self.stream = cStringIO.StringIO(hy_transform(self.stream))\n\ndef search_function(encoding):\n    if encoding != 'hy': \n        return None\n    # Assume utf8 encoding\n    utf8 = encodings.search_function('utf8')\n    return codecs.CodecInfo(\n        name = 'hy',\n        encode = utf8.encode,\n        decode = hy_decode,\n        incrementalencoder = utf8.incrementalencoder,\n        incrementaldecoder = HyIncrementalDecoder,\n        streamreader = HyStreamReader,\n        streamwriter = utf8.streamwriter)\n\ncodecs.register(search_function)\n\n","sub_path":"hy/contrib/hysyntax.py","file_name":"hysyntax.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"169979811","text":"#! /usr/bin/python\n\nimport string\nimport os\nimport sys\n\nfrom Misc import misc, parameters_misc\n\ndefault_bench = \"Hailstone/hailstone\"\ninstall_base = misc.base_install_path()\nquartus_base_path = misc.quartus_base_path\n\ndef test_bench(parameters, default_bench = default_bench, install_base = install_base):\n    assembler_base = os.path.join(install_base, \"Assembler\")\n    test_bench_template = string.Template(\n\"\"\"module ${CPU_NAME}_test_bench\n#(\n    parameter       A_WORD_WIDTH                = ${A_WORD_WIDTH},\n    parameter       B_WORD_WIDTH                = ${B_WORD_WIDTH},\n\n    parameter       INSTR_WIDTH                 = ${INSTR_WIDTH},\n\n    parameter       A_IO_READ_PORT_COUNT        = ${A_IO_READ_PORT_COUNT},\n    parameter       A_IO_WRITE_PORT_COUNT       = ${A_IO_WRITE_PORT_COUNT},\n    parameter       B_IO_READ_PORT_COUNT        = ${B_IO_READ_PORT_COUNT},\n    parameter       B_IO_WRITE_PORT_COUNT       = ${B_IO_WRITE_PORT_COUNT},\n\n    parameter       A_INIT_FILE                 = \"${assembler_base}/${default_bench}.A\",\n    parameter       B_INIT_FILE                 = \"${assembler_base}/${default_bench}.B\",\n    parameter       I_INIT_FILE                 = \"${assembler_base}/${default_bench}.I\",\n    parameter       PC_INIT_FILE                = \"${assembler_base}/${default_bench}.PC\",\n\n    parameter       A_DEFAULT_OFFSET_INIT_FILE  = \"${assembler_base}/${default_bench}.ADO\",\n    parameter       B_DEFAULT_OFFSET_INIT_FILE  = \"${assembler_base}/${default_bench}.BDO\",\n    parameter       D_DEFAULT_OFFSET_INIT_FILE  = \"${assembler_base}/${default_bench}.DDO\",\n\n    parameter       A_PROGRAMMED_OFFSETS_INIT_FILE  = \"${assembler_base}/${default_bench}.APO\",\n    parameter       B_PROGRAMMED_OFFSETS_INIT_FILE  = \"${assembler_base}/${default_bench}.BPO\",\n    parameter       D_PROGRAMMED_OFFSETS_INIT_FILE  = \"${assembler_base}/${default_bench}.DPO\",\n\n    parameter       A_INCREMENTS_INIT_FILE  = \"${assembler_base}/${default_bench}.AIN\",\n    parameter       B_INCREMENTS_INIT_FILE  = \"${assembler_base}/${default_bench}.BIN\",\n    parameter       D_INCREMENTS_INIT_FILE  = \"${assembler_base}/${default_bench}.DIN\",\n\n    parameter       ORIGIN_INIT_FILE       = \"${assembler_base}/${default_bench}.BO\",\n    parameter       DESTINATION_INIT_FILE  = \"${assembler_base}/${default_bench}.BD\",\n    parameter       CONDITION_INIT_FILE    = \"${assembler_base}/${default_bench}.BC\",\n    parameter       PREDICTION_INIT_FILE    = \"${assembler_base}/${default_bench}.BP\",\n    parameter       PREDICTION_ENABLE_INIT_FILE    = \"${assembler_base}/${default_bench}.BPE\",\n\n    parameter       INSTR_DECODER_INIT_FILE = \"${assembler_base}/${default_bench}.IDM\"\n)\n(\n    output  wire    [INSTR_WIDTH-1:0]                           I_read_data,\n\n    output  reg     [(A_WORD_WIDTH * A_IO_READ_PORT_COUNT)-1:0] A_in,\n    output  wire    [(               A_IO_READ_PORT_COUNT)-1:0] A_rden,\n    output  reg     [(               A_IO_READ_PORT_COUNT)-1:0] A_in_EF,\n    output  wire    [(A_WORD_WIDTH * A_IO_WRITE_PORT_COUNT)-1:0] A_out, \n    output  wire    [(               A_IO_WRITE_PORT_COUNT)-1:0] A_wren,\n    output  reg     [(               A_IO_WRITE_PORT_COUNT)-1:0] A_out_EF,\n    \n    output  reg     [(B_WORD_WIDTH * B_IO_READ_PORT_COUNT)-1:0] B_in,\n    output  wire    [(               B_IO_READ_PORT_COUNT)-1:0] B_rden,\n    output  reg     [(               B_IO_READ_PORT_COUNT)-1:0] B_in_EF,\n    output  wire    [(B_WORD_WIDTH * B_IO_WRITE_PORT_COUNT)-1:0] B_out, \n    output  wire    [(               B_IO_WRITE_PORT_COUNT)-1:0] B_wren,    \n    output  reg     [(               B_IO_WRITE_PORT_COUNT)-1:0] B_out_EF\n);\n    integer     cycle;\n    reg         clock;\n    reg         half_clock;\n\n    initial begin\n        cycle       = 0;\n        clock       = 0;\n        half_clock  = 0;\n        A_in        = -1;\n        B_in        = -1;\n        A_in_EF     = -1;\n        A_out_EF    = 0;\n        B_in_EF     = -1;\n        B_out_EF    = 0;\n        `DELAY_CLOCK_CYCLES(20000) $$stop;\n    end\n\n    always begin\n        `DELAY_CLOCK_HALF_PERIOD clock <= ~clock;\n    end\n\n    always @(posedge clock) begin\n        half_clock <= ~half_clock;\n    end\n\n    always @(posedge clock) begin\n        cycle <= cycle + 1;\n    end\n\n    reg                     A_valid;\n    reg [A_WORD_WIDTH-1:0]  A_data;\n\n    // End Hailstone at end of sequence.\n    always @(posedge clock) begin\n\n        A_valid <= A_wren[0] == 1'b1;\n        A_data  <= A_out[0 +: A_WORD_WIDTH];\n\n        if (A_valid) begin\n            $$display(\"AOUT: %d\", A_data);\n        end\n\n        if (A_valid && A_data == 'd1) begin\n            $$stop;\n        end\n    end\n\n    // Periodically stall write ports\n    // to test I/O predication on Hailstone\n    always @(posedge clock) begin\n        if (cycle % 100 == 0) begin\n            A_out_EF <= ~A_out_EF;\n            B_out_EF <= ~B_out_EF;\n        end\n    end\n\n//    always begin\n//        // Read Empty, Write Full\n//        `DELAY_CLOCK_CYCLES(100)\n//        A_in_EF  = 0;\n//        A_out_EF = -1;\n//        B_in_EF  = 0;\n//        B_out_EF = -1;\n        \n//        // Read Full, Write Empty\n//        `DELAY_CLOCK_CYCLES(100)\n//        A_in_EF  = -1;\n//        A_out_EF = 0;\n//        B_in_EF  = -1;\n//        B_out_EF = 0;\n\n//        // Read Empty, Write Empty\n//        `DELAY_CLOCK_CYCLES(100)\n//        A_in_EF  = 0;\n//        A_out_EF = 0;\n//        B_in_EF  = 0;\n//        B_out_EF = 0;\n\n//        // Read Full, Write Full\n//        `DELAY_CLOCK_CYCLES(100)\n//        A_in_EF  = -1;\n//        A_out_EF = -1;\n//        B_in_EF  = -1;\n//        B_out_EF = -1;\n\n//    end\n\n    ${CPU_NAME} \n    #(\n        .A_INIT_FILE                    (A_INIT_FILE),\n        .B_INIT_FILE                    (B_INIT_FILE),\n        .I_INIT_FILE                    (I_INIT_FILE),\n        .PC_INIT_FILE                   (PC_INIT_FILE),\n\n        .A_DEFAULT_OFFSET_INIT_FILE     (A_DEFAULT_OFFSET_INIT_FILE),\n        .B_DEFAULT_OFFSET_INIT_FILE     (B_DEFAULT_OFFSET_INIT_FILE),\n        .D_DEFAULT_OFFSET_INIT_FILE     (D_DEFAULT_OFFSET_INIT_FILE),\n\n        .A_PROGRAMMED_OFFSETS_INIT_FILE     (A_PROGRAMMED_OFFSETS_INIT_FILE),\n        .B_PROGRAMMED_OFFSETS_INIT_FILE     (B_PROGRAMMED_OFFSETS_INIT_FILE),\n        .D_PROGRAMMED_OFFSETS_INIT_FILE     (D_PROGRAMMED_OFFSETS_INIT_FILE),\n\n        .A_INCREMENTS_INIT_FILE     (A_INCREMENTS_INIT_FILE),\n        .B_INCREMENTS_INIT_FILE     (B_INCREMENTS_INIT_FILE),\n        .D_INCREMENTS_INIT_FILE     (D_INCREMENTS_INIT_FILE),\n\n        .ORIGIN_INIT_FILE           (ORIGIN_INIT_FILE),\n        .DESTINATION_INIT_FILE      (DESTINATION_INIT_FILE),\n        .CONDITION_INIT_FILE        (CONDITION_INIT_FILE),\n        .PREDICTION_INIT_FILE        (PREDICTION_INIT_FILE),\n        .PREDICTION_ENABLE_INIT_FILE        (PREDICTION_ENABLE_INIT_FILE),\n        .INSTR_DECODER_INIT_FILE        (INSTR_DECODER_INIT_FILE)\n    )\n    DUT \n    (\n        .clock              (clock),\n\n        .I_wren_other       (`HIGH),\n\n        .I_read_data        (I_read_data),\n\n        .A_in               (A_in),\n        .A_rden             (A_rden),\n        .A_in_EF            (A_in_EF),\n        .A_out              (A_out),\n        .A_wren             (A_wren),\n        .A_out_EF           (A_out_EF),\n        \n        .B_in               (B_in),\n        .B_rden             (B_rden),\n        .B_in_EF            (B_in_EF),\n        .B_out              (B_out),\n        .B_wren             (B_wren),\n        .B_out_EF           (B_out_EF)\n    );\nendmodule\n\"\"\")\n    parameters[\"default_bench\"] = default_bench\n    parameters[\"assembler_base\"] = assembler_base\n    return test_bench_template.substitute(parameters)\n\ndef test_bench_script(parameters, default_bench = default_bench, install_base = install_base, quartus_base_path = quartus_base_path):\n    test_bench_script_template = string.Template(\n\"\"\"#! /bin/bash\n\nINSTALL_BASE=\"${install_base}\"\n\nTOP_LEVEL_MODULE=\"${CPU_NAME}_test_bench\"\nTESTBENCH=\"./$${TOP_LEVEL_MODULE}.v\"\n\nLPM_LIBRARY=\"${quartus_base_path}/quartus/eda/sim_lib/220model.v\"\nALT_LIBRARY=\"${quartus_base_path}/quartus/eda/sim_lib/altera_mf.v\"\n\nOCTAVO=\"$$INSTALL_BASE/Octavo/Misc/params.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/delay_line.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Address_Decoder.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Address_Translator.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Addressed_Mux.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Translated_Addressed_Mux.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Instruction_Annuller.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Thread_Number.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Enabled_Registers.v \\\\\n        $$INSTALL_BASE/Octavo/Misc/Instr_Decoder.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/ALU/AddSub_Carry_Select.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/ALU/AddSub_Ripple_Carry.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/ALU/Mult.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/ALU/Bitwise.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/ALU/ALU.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/DataPath.v \\\\\n        $$INSTALL_BASE/Octavo/DataPath/InstructionDecoder.v \\\\\n        $$INSTALL_BASE/Octavo/ControlPath/Controller.v \\\\\n        $$INSTALL_BASE/Octavo/ControlPath/ControlPath.v \\\\\n        $$INSTALL_BASE/Octavo/Memory/RAM_SDP.v \\\\\n        $$INSTALL_BASE/Octavo/Memory/RAM_SDP_no_fw.v \\\\\n        $$INSTALL_BASE/Octavo/Memory/Write_Enable.v \\\\\n        $$INSTALL_BASE/Octavo/Memory/Memory.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Address_Adder.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Addressing_Mapped_AB.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Addressing_Mapped_D.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Addressing_Thread_Number.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Addressing.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Address_Translation.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Default_Offset.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Increment_Adder.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Increments.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Programmed_Offsets.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Write_Priority.v \\\\\n        $$INSTALL_BASE/Octavo/Addressing/Write_Synchronize.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Check_Mapped.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Check.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Condition.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Destination.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Folding.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branching_Flags.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branching_Thread_Number.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Origin.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Origin_Check.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Cancel.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Prediction.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/Branch_Prediction_Enable.v \\\\\n        $$INSTALL_BASE/Octavo/Branching/OR_Reducer.v \\\\\n        $$INSTALL_BASE/Octavo/IO/EmptyFullBit.v \\\\\n        $$INSTALL_BASE/Octavo/IO/IO_Active.v \\\\\n        $$INSTALL_BASE/Octavo/IO/IO_All_Ready.v \\\\\n        $$INSTALL_BASE/Octavo/IO/IO_Check.v \\\\\n        $$INSTALL_BASE/Octavo/IO/IO_Read.v \\\\\n        $$INSTALL_BASE/Octavo/IO/IO_Write.v \\\\\n        $$INSTALL_BASE/Octavo/IO/Port_Active.v \\\\\n        $$INSTALL_BASE/Octavo/Octavo/Scalar.v \\\\\n        ../${CPU_NAME}.v \\\\\n\"\n\nVLIB=\"work\"\n\nVSIM_ACTIONS=\"vcd file $$TOP_LEVEL_MODULE.vcd ; vcd add -r /* ; run -all ; quit\"\n\nrm $$TOP_LEVEL_MODULE.wlf $$TOP_LEVEL_MODULE.vcd\nvlib $$VLIB 2>&1 > LOG\nvlog -mfcu -incr -lint $$LPM_LIBRARY $$ALT_LIBRARY $$OCTAVO $$TESTBENCH 2>&1 >> LOG\nvsim -voptargs=\"+acc\" -c -do \"$$VSIM_ACTIONS\" $$TOP_LEVEL_MODULE 2>&1 >> LOG\nvcd2wlf $$TOP_LEVEL_MODULE.vcd $$TOP_LEVEL_MODULE.wlf 2>&1 >> LOG\nrm vsim.wlf\ngrep AOUT LOG | sed -e's/# AOUT:\\s*//' > output\n\"\"\")\n    parameters[\"default_bench\"]     = default_bench\n    parameters[\"install_base\"]      = install_base\n    parameters[\"quartus_base_path\"] = quartus_base_path\n    return test_bench_script_template.substitute(parameters)\n\ndef main(parameters = {}):\n    name                = parameters[\"CPU_NAME\"]\n    test_bench_name     = name + \"_\" + misc.bench_name\n    test_bench_file     = test_bench(parameters)\n    test_bench_run      = test_bench_script(parameters)\n    test_bench_dir      = os.path.join(os.getcwd(), misc.bench_name)\n    misc.write_file(test_bench_dir, test_bench_name + \".v\", test_bench_file)\n    misc.write_file(test_bench_dir, \"run_\" + misc.bench_name, test_bench_run)\n    misc.make_file_executable(test_bench_dir, \"run_\" + misc.bench_name)\n    \nif __name__ == \"__main__\":\n    parameters          = parameters_misc.parse_cmdline(sys.argv[1:])\n    main(parameters)\n","sub_path":"Generator/Scalar/Scalar_test_bench.py","file_name":"Scalar_test_bench.py","file_ext":"py","file_size_in_byte":12705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"57075608","text":"'''\nCreated on Jul 11, 2016\n\n@author: xmiao\n'''\n\nfrom Company_LIB import *\nfrom Deal_LIB import *\nfrom DB_LIB import *\n\n\nif __name__ == '__main__':\n    \n    db = DB_LIB();\n    company = Company_LIB();\n    deal = Deal_LIB();\n    \n    db.updateTables();\n    \n    company.createNewCompany();\n    deal.createNewDeal();\n    \n    company.updateExistCompany();\n    \n    db.updateDealAssociatedCompanyId();\n    \n    deal.updateNewDealAssociation();\n    deal.updateExistDealAssociation();\n    deal.updateExistDeal();\n    \n","sub_path":"lib/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"570656853","text":"#!/usr/bin/python3\n# coding=utf-8\n\ndef app(enviro, start_response):\n    \"\"\"\n    enviro 接收服务器状态信息\n    start_response 返回响应行,响应头\n    return 返回响应体\n    \"\"\"\n    status = \"200 OK\"\n    response_headers = [('Content-Type', 'text/html'), ('Server','MyHttpServer')]\n    start_response(status, response_headers)\n\n    return str(enviro) + \"Hello , It's outer app\"\n","sub_path":"j12day/wsgipy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"388469089","text":"#!/usr/bin/env python\nimport RPi.GPIO as GPIO\nimport time\n\nRCLK  = 11\nSRCLK = 12\nSDI   = 13\n\n#left reg controlls row\n#right reg controlls column\n\n#data fed right->left\n\n#code_H = [0x01,0xff,0x80,0xff,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff]\n#code_L = [0x00,0x7f,0x00,0xfe,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f]\n\ncTab = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]\nvTab = [0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f]\n\nc =    [0x00, 0x00, 0xfc, 0xfc, 0xfc, 0xfc, 0x00, 0x00]\ns =    [0x00, 0x00, 0xfc, 0x00, 0x00, 0x3f, 0x00, 0x00]\nr =    [0b11000000, 0b11000000, 0b00111100, 0b00111100, 0b11000000, 0b11000000, 0b00111100, 0b00111100]\n\nblank = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]\ngrid = [0b01010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101, 0b01010101]\n\nflashDelay = 0.0005\n\ndef print_msg():\n        print( 'Program is running...')\n        print( 'Please press Ctrl+C to end the program...')\n\ndef setup():\n        GPIO.setmode(GPIO.BOARD)    # Number GPIOs by its physical location\n        GPIO.setup(SDI, GPIO.OUT)\n        GPIO.setup(RCLK, GPIO.OUT)\n        GPIO.setup(SRCLK, GPIO.OUT)\n        GPIO.output(SDI, GPIO.LOW)\n        GPIO.output(RCLK, GPIO.LOW)\n        GPIO.output(SRCLK, GPIO.LOW)\n\ndef hc595_in(dat):\n        for bit in range(0, 8): \n                GPIO.output(SDI, 0x80 & (dat << bit))\n                GPIO.output(SRCLK, GPIO.HIGH)\n                #time.sleep(0.00001)\n                GPIO.output(SRCLK, GPIO.LOW)\n\ndef hc595_out():\n        GPIO.output(RCLK, GPIO.HIGH)\n        #time.sleep(0.001)\n        GPIO.output(RCLK, GPIO.LOW)\n\ndef showChar(char, sec):\n    duration = int(sec / flashDelay) #not actually accurate\n    #print(duration)\n    \n    for i in range(duration):\n        for j in range(0, len(char)):\n            hc595_in(cTab[j])\n            hc595_in(char[j])\n            hc595_out()\n        time.sleep(flashDelay)\n        \ndef dotScan(delay):\n    for i in range(8):\n        for j in range(8):\n            hc595_in(cTab[i])\n            hc595_in(vTab[j])\n            hc595_out()\n            time.sleep(delay)\n            \ndef sccrc(delay, blankDelay):\n    showChar(s, delay)\n    showChar(blank, blankDelay)\n                \n    showChar(c, delay)\n    showChar(blank, blankDelay)\n                \n    showChar(c, delay)\n    showChar(blank, blankDelay)\n                \n    showChar(r, delay)\n    showChar(blank, blankDelay)\n                \n    showChar(c, delay)\n    showChar(blank, blankDelay)\n    \n    showChar(grid, 0.3)\n    showChar(blank, 0.1)\n                \n\ndef loop():\n    while True:\n        dotScan(0.05)\n        sccrc(0.3, 0.05)\n        time.sleep(0.1)\n\ndef destroy():   # When program ending, the function is executed. \n        GPIO.cleanup()\n\nif __name__ == '__main__':   # Program starting from here \n        print_msg()\n        setup() \n        try:\n                loop()  \n        except KeyboardInterrupt:  \n                destroy()  \n","sub_path":"ledMatrix.py","file_name":"ledMatrix.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"111982183","text":"import json\n\nfrom d3ct.plugins.log_loggers import PLUGIN_LOG\nfrom d3ct.plugins.base import PluginBase\n\n\nclass Converter(PluginBase):\n\n    def __init__(self, call_params, runtime_infos):\n        PluginBase.__init__(self, call_params, runtime_infos)\n        self._data = None\n\n        try:\n            if 'inp' in self.call_params:\n                f = open(self.call_params['inp'], \"r\")\n                input_raw = f.read()\n                self.inp_data = json.loads(input_raw)\n            else:\n                PLUGIN_LOG.error('no inp value found in: %s', self.call_params)\n                exit(1)\n        except FileNotFoundError as err:\n            PLUGIN_LOG.error(err)\n            exit(1)\n\n    def traverse(self, py_obj):\n        PLUGIN_LOG.debug(\"json_overlay.Converter.traverse()\")\n        if 'uuid' in py_obj:\n            for obj in self.inp_data['objects']:\n                if obj['uuid'] == py_obj['uuid']:\n                    py_obj.update(obj)\n        if 'children' in py_obj:\n            for child in py_obj['children']:\n                self.traverse(child)\n\n    def trans(self, py_obj):\n        PLUGIN_LOG.debug(\"json_overlay.Converter.trans()\")\n        PLUGIN_LOG.debug(\"    call params: %s\", str(self.call_params))\n        self.traverse(py_obj)\n        self._data = py_obj\n        return self._data\n","sub_path":"d3ct/plugins/json_overlay.py","file_name":"json_overlay.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"595681028","text":"##\n## This program demonstrates interacting with the Fannie MAE\n## Exchange portal to retrieve manufactured housing data.\n##\n## The Exchange can run example queries against the API's and show you the invocation\n## as a CURL command. You can use the link below to help you convert CURL parameters\n## and formatting into Python.\n##\n## https://curl.trillworks.com/\n##\n\n## import the necessary support libraries\n##\nimport requests\nimport json\nimport csv\nfrom collections import Counter\n\n## set up the request object - replace \"YOUR_AUTH_KEY\" with your actual\n## authentication key from the Exchange. Please remember YOUR_AUTH_KEY changes\n## every 60 minutes. You'll need to grab the new key from your profile or by\n## re-executing one of the sample commands on \"The Exchange\" and copying\n## YOUR_AUTH_KEY from the curl command\n##\nheaders = {\n    'accept': 'application/json',\n    'Authorization':    'cfIdi7Z4uCnXM7Ccd4DHmN2tzf3P6SHiZaOuuo25',\n}\n\noffenses = ['aggravated-assault','burglary', 'larceny', 'motor-vehicle-theft', 'homicide', 'rape', 'robbery', 'arson', 'violent-crime', 'property-crime']\n## submit a request to the exchange asking for all the\n## manufactured housing acquisitions (loans)\n##\noffense = offenses[1]\nstate = 'VA'\nresponse = requests.get('https://api.usa.gov/crime/fbi/sapi/api/data/nibrs/'+offense+'/offense/states/'+state+'/count?api_key=cfIdi7Z4uCnXM7Ccd4DHmN2tzf3P6SHiZaOuuo25', headers=headers)\n\n# region = 'West'\n# response = requests.get('https://api.usa.gov/crime/fbi/sapi/api/data/nibrs/'+offense+'/offense/regions/'+region+'/count?api_key=cfIdi7Z4uCnXM7Ccd4DHmN2tzf3P6SHiZaOuuo25', headers=headers)\n\n## grab the response (formatted as json)\n##\nresponseJSON = response.json()\n\nprint ('crime by offense and state results')\nprint (responseJSON)\ndata = open('crimes.csv', 'w')\ncsvwriter = csv.writer(data)\ncount = 0\nfor datum in responseJSON:\n    for x in responseJSON[datum]:\n        print(x)\n        if count == 0:\n\n             header = x.keys()\n             print(header)\n             csvwriter.writerow(header)\n\n             count += 1\n        csvwriter.writerow(x.values())\n    break\ndata.close()\nprint ('--------------------------------------------------')\n","sub_path":"crimes/crimedata.py","file_name":"crimedata.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"407141498","text":"import tensorflow as tf\nimport math\nimport predict_unlabel\nimport scipy.io as sio\nlabel = predict_unlabel.predict_models()\nimport numpy as np\nimport cnn_indices\ndata_cnn = cnn_indices.read_data_sets()\nimport rnn_indices\ndata_rnn = rnn_indices.read_data_sets()\nimport julei\n\nimport new_class_sample_update\n\n\nbatch_size = 5000\nnum_input = 17  # MNIST data input (img shape: 28*28)\ntimesteps = 6\nlogits_cnn = np.zeros((1, 9), dtype=np.float64)\nprob_cnn = np.zeros((1, 9), dtype=np.float64)\nlogits_rnn = np.zeros((1, 9), dtype=np.float64)\nprob_rnn = np.zeros((1, 9), dtype=np.float64)\n\n\nfor index1 in range((data_cnn.unlabel._num_examples // batch_size) + 1):\n    batch_x1 = data_cnn.unlabel.next_batch_test(batch_size)\n    logits_cnn_med, prob_cnn_med = label.cnn.predict1(batch_x1)\n    logits_cnn = np.concatenate((logits_cnn, logits_cnn_med), axis=0)\n    prob_cnn = np.concatenate((prob_cnn, prob_cnn_med), axis=0)\n\nfor index2 in range((data_rnn.unlabel._num_examples // batch_size) + 1):\n    batch_x2 = data_rnn.unlabel.next_batch_test(batch_size)\n    if index2 == (data_rnn.unlabel._num_examples // batch_size):\n        batch_x2 = batch_x2.reshape(((data_rnn.unlabel._num_examples % batch_size), timesteps, num_input))\n    else:\n        batch_x2 = batch_x2.reshape((batch_size, timesteps, num_input))\n    logits_rnn_med, prob_rnn_med = label.rnn.predict2(batch_x2)\n    logits_rnn = np.concatenate((logits_rnn, logits_rnn_med), axis=0)\n    prob_rnn = np.concatenate((prob_rnn, prob_rnn_med), axis=0)\n\nprob_cnn = prob_cnn[1:]\nprob_rnn = prob_rnn[1:]\nlogits_rnn = logits_rnn[1:]\nlogits_cnn = logits_cnn[1:]\n# find same predicted label of two networks\nlabel_cnn = np.argmax(prob_cnn, axis=1) + 1\nlabel_rnn = np.argmax(prob_rnn, axis=1) + 1\nsame_indices = np.where(label_cnn == label_rnn)\nbig_dif = np.where(label_cnn != label_rnn)\n\nbatch_cnn_center = data_cnn.train.next_batch_test(284)\n\nlogits_cnn_center, prob_center_cnn = label.cnn.predict1(batch_cnn_center)\nlabel_center_cnn = np.argmax(prob_center_cnn, axis=1) + 1\ncenter_indices1 = []\njuleicenter1 = {}\nfor i in range(9):\n    indices = [j for j, x in enumerate(label_center_cnn.tolist()) if x == i+1]\n    np.random.shuffle(indices)\n    juleicenter1[i] = indices[:1]\n    center_indices1 += juleicenter1[i]\ncnn_center_data = logits_cnn_center[center_indices1]\nlogits_cnn = np.concatenate((cnn_center_data, logits_cnn), axis=0)\n\nbatch_rnn_center = data_rnn.train.next_batch_test(284)\nbatch_rnn_center = batch_rnn_center.reshape((284, timesteps, num_input))\nlogits_rnn_center, prob_center_rnn = label.rnn.predict2(batch_rnn_center)\nlabel_center_rnn = np.argmax(prob_center_rnn, axis=1) + 1\ncenter_indices2 = []\njuleicenter2 = {}\nfor i in range(9):\n    indices = [j for j, x in enumerate(label_center_rnn.tolist()) if x == i+1]\n    np.random.shuffle(indices)\n    juleicenter2[i] = indices[:1]\n    center_indices2 += juleicenter2[i]\nrnn_center_data = logits_rnn_center[center_indices2]\nlogits_rnn = np.concatenate((rnn_center_data, logits_rnn), axis=0)\n\nnorm_rnn = np.zeros((logits_rnn.shape[0], logits_rnn.shape[1]), dtype=np.float32)\nnorm_cnn = np.zeros((logits_cnn.shape[0], logits_cnn.shape[1]), dtype=np.float32)\nmax_cnn = np.amax(logits_cnn, axis=1)\nmin_cnn = np.amin(logits_cnn, axis=1)\nsubstract_cnn = [x-y for x, y in zip(max_cnn, min_cnn)]\nmax_rnn = np.amax(logits_rnn, axis=1)\nmin_rnn = np.amin(logits_rnn, axis=1)\nsubstract_rnn = [x-y for x, y in zip(max_rnn, min_rnn)]\nfor i in range(logits_cnn.shape[0]):\n    for j in range(logits_cnn.shape[1]):\n        norm_cnn[i][j] = (logits_cnn[i][j] - min_cnn[i]) / substract_cnn[i]\n        norm_rnn[i][j] = (logits_rnn[i][j] - min_rnn[i]) / substract_rnn[i]\ncnn_center = norm_cnn[:9]\ncnn_unlabeled = norm_cnn[9:]\nrnn_center = norm_rnn[:9]\nrnn_unlabeled = norm_rnn[9:]\n\ndef update_cnn():\n    max_diff_cnn = [x-y for x, y in zip(rnn_unlabeled, cnn_unlabeled)]\n    max_dcpe_cnn = np.argmax(max_diff_cnn, axis=1) + 1\n    remove_same_cnn = (big_dif[0]).tolist()\n    np.random.shuffle(remove_same_cnn)\n    same_indexall_cnn = (same_indices[0]).tolist()\n    np.random.shuffle(same_indexall_cnn)\n    print(\"kmeans and cnn same samples begin\")\n    kmeannetcnnsame_indices = julei.predict(cnn_unlabeled[same_indexall_cnn], cnn_center,\n                                            label_cnn[same_indexall_cnn], same_indexall_cnn)\n    same_cnn_index = new_class_sample_update.update1(kmeannetcnnsame_indices, label_cnn, same_indexall_cnn)\n    # same_cnn_index = new_class_sample_update.update(same_indexall_cnn, label_cnn)\n\n    print(\"kmeans and cnn dcpe samples begin\")\n    #\n    kmeannetcnndcpe_indices = julei.predict(cnn_unlabeled[remove_same_cnn], cnn_center,\n                                            max_dcpe_cnn[remove_same_cnn], remove_same_cnn)\n    dcpe_cnn_index = new_class_sample_update.update2(kmeannetcnndcpe_indices, max_dcpe_cnn, remove_same_cnn)\n    # dcpe_cnn_index = new_class_sample_update.update(remove_same_cnn, max_dcpe_cnn)\n    cnn_index_all = same_cnn_index + dcpe_cnn_index\n    cnn_label_all = np.concatenate((label_cnn[same_cnn_index], max_dcpe_cnn[dcpe_cnn_index]), axis=0)\n\n    labeled_sets_cnn = np.load('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/labeled_index.npy')\n    unlabeled_sets_cnn = np.load('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/unlabeled_index.npy')\n    mat_gt_cnn = sio.loadmat(\"/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/PaviaU_gt.mat\")\n    GT_cnn = mat_gt_cnn['paviaU_gt']\n    cnn_index_bigmap = unlabeled_sets_cnn[cnn_index_all]\n    update_labeled_sets_cnn = np.concatenate((labeled_sets_cnn, cnn_index_bigmap), axis=0)\n    gt_col_cnn = GT_cnn.reshape((GT_cnn.shape[0]*GT_cnn.shape[1], ))\n    cnn_index_bigmap = cnn_index_bigmap.tolist()\n    gt_col_cnn[cnn_index_bigmap] = cnn_label_all\n    real_gt_cnn = gt_col_cnn.reshape((GT_cnn.shape[0], GT_cnn.shape[1]))\n    # unlabeled_sets_cnn = list(set(unlabeled_sets_cnn.tolist()).difference(set(cnn_index_bigmap)))\n    np.random.shuffle(update_labeled_sets_cnn)\n    np.save('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/unlabeled_index.npy', unlabeled_sets_cnn)\n    np.save('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/labeled_index.npy', update_labeled_sets_cnn)\n    sio.savemat('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/cnn/PaviaU_gt.mat', {'paviaU_gt': real_gt_cnn})\n    return ()\n\n\ndef update_rnn():\n    max_diff_rnn = [x - y for x, y in zip(cnn_unlabeled, rnn_unlabeled)]\n    max_dcpe_rnn = np.argmax(max_diff_rnn, axis=1) + 1\n    remove_same_rnn = (big_dif[0]).tolist()\n    np.random.shuffle(remove_same_rnn)\n    same_indexall_rnn = (same_indices[0]).tolist()\n    np.random.shuffle(same_indexall_rnn)\n    print(\"kmeans and rnn same samples begin\")\n    kmeannetrnnsame_indices = julei.predict(rnn_unlabeled[same_indexall_rnn], rnn_center,\n                                         label_rnn[same_indexall_rnn], same_indexall_rnn)\n    same_rnn_index = new_class_sample_update.update1(kmeannetrnnsame_indices, label_rnn, same_indexall_rnn)\n    # same_rnn_index = new_class_sample_update.update(same_indexall_rnn, label_rnn)\n    print(\"kmeans and rnn dcpe samples begin\")\n    kmeannetrnndcpe_indices = julei.predict(rnn_unlabeled[remove_same_rnn], rnn_center,\n                                             max_dcpe_rnn[remove_same_rnn], remove_same_rnn)\n    dcpe_rnn_index = new_class_sample_update.update2(kmeannetrnndcpe_indices, max_dcpe_rnn, remove_same_rnn)\n    # dcpe_rnn_index = new_class_sample_update.update(remove_same_rnn, max_dcpe_rnn)\n    rnn_index_all = same_rnn_index + dcpe_rnn_index\n    rnn_label_all = np.concatenate((label_rnn[same_rnn_index], max_dcpe_rnn[dcpe_rnn_index]), axis=0)\n\n    labeled_sets_rnn = np.load('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/labeled_index.npy')\n    unlabeled_sets_rnn = np.load('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/unlabeled_index.npy')\n    mat_gt_rnn = sio.loadmat(\"/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/PaviaU_gt.mat\")\n    GT_rnn = mat_gt_rnn['paviaU_gt']\n    rnn_index_bigmap = unlabeled_sets_rnn[rnn_index_all]\n    update_labeled_sets_rnn = np.concatenate((labeled_sets_rnn, rnn_index_bigmap), axis=0)\n    gt_col_rnn = GT_rnn.reshape((GT_rnn.shape[0] * GT_rnn.shape[1],))\n    gt_col_rnn[rnn_index_bigmap] = rnn_label_all\n    real_gt_rnn = gt_col_rnn.reshape((GT_rnn.shape[0], GT_rnn.shape[1]))\n    # unlabeled_sets_rnn = list(set(unlabeled_sets_rnn.tolist()).difference(set(rnn_index_bigmap)))\n    np.random.shuffle(update_labeled_sets_rnn)\n    np.save('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/unlabeled_index.npy', unlabeled_sets_rnn)\n    np.save('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/labeled_index.npy', update_labeled_sets_rnn)\n    sio.savemat('/home/asdf/Documents/juyan/paper/paviau/mdcpe/newmdcpe/data/rnn/PaviaU_gt.mat', {'paviaU_gt': real_gt_rnn})\n    return ()\n\n\nupdate_cnn()\nupdate_rnn()\n\n\n\n\n","sub_path":"training code/paviau/mdcpe/code/unlabel_test.py","file_name":"unlabel_test.py","file_ext":"py","file_size_in_byte":8993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"52175855","text":"class Solution(object):\n    def accountsMerge(self, accounts):\n        \"\"\"\n        :type accounts: List[List[str]]\n        :rtype: List[List[str]]\n        \"\"\"\n        eset = set()\n        owner = {}\n        parent = {}\n        result = collections.defaultdict(list)\n        def findParent(e):\n            rank = 0\n            while parent[e] != e:\n                rank += 1\n                e = parent[e]\n            return e, rank\n        def merge(a, b):\n            pa, ra = findParent(a)\n            pb, rb = findParent(b)\n            if ra < rb: parent[pa] = pb\n            else: parent[pb] = pa\n        for account in accounts:\n            name, emails = account[0], account[1:]\n            for email in emails:\n                eset.add(email)\n                owner[email] = name\n                if email not in parent: parent[email] = email\n            for email in emails[1:]:\n                merge(emails[0], email)\n        for email in eset:\n            result[findParent(email)[0]].append(email)\n        return [[owner[k]] + sorted(v) for k, v in result.iteritems()]\n","sub_path":"721-Accounts Merge.py","file_name":"721-Accounts Merge.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"276483549","text":"#!/usr/bin/env python2.7\nimport httplib, urllib\nimport time\n\ndef stallPost(id, active, handicapped):\n    params = urllib.urlencode({\n        'stallId' : id,\n        'active' : active,\n        'handicapped' : handicapped\n        })\n    headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\n               \"Accept\": \"text/plain\"}\n    conn = httplib.HTTPConnection(\"lrshit.herokuapp.com\", 80)\n    conn.request(\"POST\", \"/api/stalls\",\n                 params, headers)\n    response = conn.getresponse()\n    data = response.read()\n    conn.close()\n\n","sub_path":"python/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"471664039","text":"from django.views.decorators.csrf import csrf_exempt\nfrom django.conf.urls import url\nfrom imp_man.views import show_restructure_file, static_page, show_pdf_file, execute_operations, execute_module, \\\n    JsonModel,  HistoryModel , DinamicTemplate, OperationRecord    \nfrom django.views.decorators.gzip import gzip_page\n\nurlpatterns = (\n    url(r'^static_page/', static_page, name='static_page'),\n    url(r'^show_pdf_file/(?P[\\w|\\/\\.]+)/$', show_pdf_file, name='show_pdf_file'),\n    url(r'^show_restructure_file/(?P[\\w|\\/\\.\\s]+)/$', show_restructure_file, name='show_restructure_file'),\n    url(r'^operation_record/$', csrf_exempt(OperationRecord.as_view()), name='operation_record'),\n    url(r'^execute_operations', execute_operations, name='execute_operations'),\n    url(r'^execute_module', execute_module, name='execute_module'),\n    url(r'^get_jsonmodel/$', gzip_page(csrf_exempt(JsonModel.as_view())), name='get_jsonmodel'),\n    url(r'^dinamic_template/$', gzip_page(csrf_exempt(DinamicTemplate.as_view())), name='dinamic_template'),\n    url(r'^history_model/$',HistoryModel.as_view(), name='history_model'),\n)\n","sub_path":"imp_man/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"334024100","text":"import pcl\nimport random\nimport numpy as np\nimport vtk\n\nclass ICP():\n    def __init__(self):\n        self.previous = []\n\n    def icp_algorithm(self, point_cloud):\n        if len(self.previous) is 0:\n            return point_cloud\n        else:\n            cloud_in = pcl.PointCloud()\n            cloud_out = pcl.PointCloud()\n            cloud_in.from_list(self.previous)\n            cloud_out.from_list(point_cloud)\n            icp = cloud_in.make_IterativeClosestPoint()\n\n            ## ICP algorithm ##\n            converged, transf, estimate, fitness = icp.icp(cloud_in, cloud_out)\n            rotation = transf[0:3,0:3]\n            translation = transf[3,0:3] \n            transformed = np.add(np.matmul(estimate, rotation),translation)\n            self.previous = transformed\n            return transformed\n\n# def main():\n#     ##load cloud point\n#     cloud_in = pcl.PointCloud()\n#     cloud_out = pcl.PointCloud()\n#     cloud_in.from_file(bytes(b'/home/haeyeon/Lidar/data1/1.pcd'))\n#     pointCloud = vpc.VtkPointCloud()\n#     for i in range(cloud_in.size):\n#         pointCloud.addPoint(cloud_in[i],1)\n    \n#     ## Iteratively load the pcd data \n#     for i in range(2,1200,100):\n#         filename = '/home/haeyeon/cocel/data1/{}.pcd'.format(i)\n#         print(filename)\n#         cloud_out.from_file(filename.encode())\n#         icp = cloud_in.make_IterativeClosestPoint()\n#         ## ICP algorithm ##\n#         converged, transf, estimate, fitness = icp.icp(cloud_in, cloud_out)\n#         ## Transfrom the input point cloud\n#         rotation = transf[0:3,0:3]\n#         translation = transf[3,0:3]  \n#         converted = np.add(np.matmul(estimate, rotation),translation)\n#         if(converged):\n#             for j in range(estimate.size):\n#                 new_points = converted[j,0:3]\n#                 pointCloud.addPoint(new_points,0)\n\n\n#     renderer = vtk.vtkRenderer()\n#     renderWindow = vtk.vtkRenderWindow()\n#     renderWindow.AddRenderer(renderer)\n\n#     renderWindowInteractor = vtk.vtkRenderWindowInteractor()\n#     renderWindowInteractor.SetRenderWindow(renderWindow)\n#     renderer.AddActor(pointCloud.point_vtkActor)\n#     renderer.SetBackground(0.0, 0.0, 0.0)\n#     renderWindow.Render()\n#     renderWindowInteractor.Initialize()\n\n#     renderWindowInteractor.Start()\n\n\n\n\n# if __name__ == \"__main__\":\n#     main()","sub_path":"ICP_realtime/ICP.py","file_name":"ICP.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"479323536","text":"\"\"\"empty message\r\n\r\nRevision ID: b3ffa77b48fb\r\nRevises: e07501b5dc77\r\nCreate Date: 2016-08-13 18:46:53.144505\r\n\r\n\"\"\"\r\n\r\n# revision identifiers, used by Alembic.\r\nrevision = 'b3ffa77b48fb'\r\ndown_revision = 'e07501b5dc77'\r\n\r\nfrom alembic import op\r\nimport sqlalchemy as sa\r\nfrom maestro.auth.models import Password\r\nfrom maestro import db\r\n\r\ndef upgrade():\r\n    ### commands auto generated by Alembic - please adjust! ###\n    op.create_table('facebook_auth',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('mayan_id', sa.Integer(), nullable=False),\n    sa.Column('facebook_id', sa.String(length=64), nullable=False),\n    sa.ForeignKeyConstraint(['mayan_id'], [u'mayan.id'], ),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('facebook_id'),\n    sa.UniqueConstraint('mayan_id')\n    )\n    op.create_table('maya_auth',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('mayan_id', sa.Integer(), nullable=False),\n    sa.Column('password', Password(length=64), nullable=False),\n    sa.ForeignKeyConstraint(['mayan_id'], [u'mayan.id'], ),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('mayan_id')\n    )\n\n    op.drop_constraint(u'mayan_id_fkey', 'mayan', type_='foreignkey')\n\n    op.drop_constraint(u'async_operation_user_profile_id_fkey', 'async_operation', type_='foreignkey')\n    op.drop_column(u'async_operation', 'user_profile_id')\n\n    op.drop_table('user_profile')\n\n    op.add_column(u'async_operation', sa.Column('facebook_auth_id', sa.Integer(), nullable=True))\n    op.create_foreign_key(None, 'async_operation', 'facebook_auth', ['facebook_auth_id'], ['id'])\n\n    sql = sa.text(\"CREATE SEQUENCE mayan_id_seq START WITH 105;ALTER TABLE mayan ALTER id SET DEFAULT NEXTVAL('mayan_id_seq');\")\n    result = db.engine.execute(sql)\n\n\n    ### end Alembic commands ###\n\r\n\r\ndef downgrade():\r\n    ### commands auto generated by Alembic - please adjust! ###\n    op.create_table('user_profile',\n    sa.Column('id', sa.INTEGER(), nullable=False),\n    sa.Column('facebook_id', sa.VARCHAR(length=64), autoincrement=False, nullable=False),\n    sa.Column('first_name', sa.VARCHAR(length=64), autoincrement=False, nullable=True),\n    sa.Column('last_name', sa.VARCHAR(length=64), autoincrement=False, nullable=True),\n    sa.Column('email', sa.VARCHAR(length=64), autoincrement=False, nullable=True),\n    sa.PrimaryKeyConstraint('id', name=u'user_profile_pkey'),\n    sa.UniqueConstraint('email', name=u'user_profile_email_key'),\n    sa.UniqueConstraint('facebook_id', name=u'user_profile_facebook_id_key')\n    )\n    op.create_foreign_key(u'mayan_id_fkey', 'mayan', 'user_profile', ['id'], ['id'])\n    op.add_column(u'async_operation', sa.Column('user_profile_id', sa.INTEGER(), autoincrement=False, nullable=True))\n    op.drop_constraint(None, 'async_operation', type_='foreignkey')\n    op.create_foreign_key(u'async_operation_user_profile_id_fkey', 'async_operation', 'user_profile', ['user_profile_id'], ['id'])\n    op.drop_column(u'async_operation', 'facebook_auth_id')\n    op.drop_table('maya_auth')\n    op.drop_table('facebook_auth')\n    ### end Alembic commands ###\r\n","sub_path":"migrations/versions/b3ffa77b48fb_.py","file_name":"b3ffa77b48fb_.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"153368751","text":"import gym\nimport numpy as np\nimport os\nimport yaml\n\nfrom gym.envs.robot_locomotion_group.drake.shoe.open_loop import (\n    get_instructions,\n    instructions_to_x,\n)\n\nshoe_dir = os.path.dirname(os.path.abspath(__file__))\nconfig_path = os.path.join(shoe_dir, \"config.yaml\")\nconfig = yaml.safe_load(open(config_path, \"r\"))\nenv = gym.make(\"Shoe-v0\", config=config)\nenv.reset()\n\nopen_loop = get_instructions()\ni = 0\naction = None\nwhile True:\n    obs, _, success, _ = env.step(action)\n    action = None\n    # If grippers not moving, do next stage\n    if np.linalg.norm(obs) < 0.02:\n        if i >= len(open_loop):\n            print(\"Done\")\n            break\n        print(f\"Executing move {i}\")\n        action = instructions_to_x([open_loop[i]])\n        i += 1\n\n    if not success:\n        break\n","sub_path":"gym/envs/robot_locomotion_group/drake/shoe/test_gym.py","file_name":"test_gym.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"170395964","text":"from minio import Minio\r\nfrom minio import CopyConditions\r\nimport os\r\nimport glob\r\nimport uuid\r\n\r\nACCESS_KEY = \"xx\"\r\nSECRET_KEY = \"xx\"\r\n\r\n#Initialise MinioClient\r\nminioClient = Minio('127.0.0.1:9000',\r\n                  access_key= ACCESS_KEY,\r\n                  secret_key= SECRET_KEY,\r\n                  secure=False)\r\n\r\n# Insert output from Deepspeech into this variable\r\nmetadata = {\"Transcript\": \"xx\",\r\n            \"Entities\":\"[[['xx','xx']],[['xx','xx']]]\"\r\n            }\r\n\r\n# Append metadata onto original video and upload to new Minio Bucket\r\ntry:\r\n    copy_result = minioClient.copy_object(\"output_Bucket\", \"updatedFileName\",\r\n                                          \"original_Bucket/fileToBeUpdated\",\r\n                                          metadata=metadata)   \r\nexcept ResponseError as err:\r\n        print(err)\r\n\r\n# Error-Checking to validate metadata has been appended to the corresponding video\r\ntry:\r\n    print(minioClient.fget_object(bucket_name=\"output_Bucket\", object_name=\"updatedFileName\"))\r\nexcept ResponseError as err:\r\n    print(err)\r\n","sub_path":"AppendMetaDataToVideo.py","file_name":"AppendMetaDataToVideo.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"447179522","text":"#!/usr/bin/env python2\n'''Buttons/Button Box\n\nThis demo shows various button box configurations available.  It also\nuses stock buttons, and use of mnemonics for navigation.\n'''\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\ndef create_bbox(horizontal=True, title=None, spacing=0,\n        layout=gtk.BUTTONBOX_SPREAD):\n    frame = gtk.Frame(title)\n\n    if horizontal:\n        bbox = gtk.HButtonBox()\n    else:\n        bbox = gtk.VButtonBox()\n\n    bbox.set_border_width(5)\n    bbox.set_layout(layout)\n    bbox.set_spacing(spacing)\n    frame.add(bbox)\n\n    button = gtk.Button(stock='gtk-ok')\n    bbox.add(button)\n\n    button = gtk.Button(stock='gtk-cancel')\n    bbox.add(button)\n\n    button = gtk.Button(stock='gtk-help')\n    bbox.add(button)\n\n    return frame\n\nclass ButtonBoxDemo(gtk.Window):\n    def __init__(self, parent=None):\n        # Create the toplevel window\n        gtk.Window.__init__(self)\n        try:\n            self.set_screen(parent.get_screen())\n        except AttributeError:\n            self.connect('destroy', lambda *w: gtk.main_quit())\n\n        self.set_title(self.__class__.__name__)\n        self.set_border_width(10)\n\n        main_vbox = gtk.VBox()\n        self.add(main_vbox)\n\n        frame_horiz = gtk.Frame(\"Horizontal Button Boxes\")\n        main_vbox.pack_start(frame_horiz, padding=10)\n\n        vbox = gtk.VBox()\n        vbox.set_border_width(10)\n        frame_horiz.add(vbox)\n\n        vbox.pack_start(create_bbox(True, \"Spread\", 40, gtk.BUTTONBOX_SPREAD),\n                padding=0)\n        vbox.pack_start(create_bbox(True, \"Edge\", 40, gtk.BUTTONBOX_EDGE),\n                padding=5)\n        vbox.pack_start(create_bbox(True, \"Start\", 40, gtk.BUTTONBOX_START),\n                padding=5)\n        vbox.pack_start(create_bbox(True, \"End\", 40, gtk.BUTTONBOX_END),\n                padding=5)\n\n        frame_vert = gtk.Frame(\"Vertical Button Boxes\")\n        main_vbox.pack_start(frame_vert, padding=10)\n\n        hbox = gtk.HBox()\n        hbox.set_border_width(10)\n        frame_vert.add(hbox)\n\n        hbox.pack_start(create_bbox(False, \"Spread\", 40, gtk.BUTTONBOX_SPREAD),\n                padding=0)\n        hbox.pack_start(create_bbox(False, \"Edge\", 40, gtk.BUTTONBOX_EDGE),\n                padding=5)\n        hbox.pack_start(create_bbox(False, \"Start\", 40, gtk.BUTTONBOX_START),\n                padding=5)\n        hbox.pack_start(create_bbox(False, \"End\", 40, gtk.BUTTONBOX_END),\n                padding=5)\n\n        self.show_all()\n\ndef main():\n    ButtonBoxDemo()\n    gtk.main()\n\nif __name__ == '__main__':\n    main()\n","sub_path":"PyGtk/demos/buttonbox.py","file_name":"buttonbox.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"152098472","text":"from PIL import Image\n\ndef size2Iphone5(img):\n    x, y = img.size\n    # 1136 * 640\n    out = img.resize((1136,640),Image.ANTIALIAS)\n    out.save('result.jpg','JPEG')\n\nif __name__ == '__main__':\n    filename = 'Harden.jpg'\n    img = Image.open(filename)\n    size2Iphone5(img)","sub_path":"0005.py","file_name":"0005.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"296611208","text":"\"\"\"\nBEHAVIOR RL episodes replay entrypoint\n\"\"\"\n\nimport argparse\nimport datetime\nimport os\nimport pprint\n\nimport bddl\nimport h5py\nimport numpy as np\n\nimport igibson\nfrom igibson.activity.activity_base import iGBEHAVIORActivityInstance\nfrom igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRendererSettings\nfrom igibson.render.mesh_renderer.mesh_renderer_vr import VrSettings\nfrom igibson.simulator import Simulator\nfrom igibson.utils.git_utils import project_git_info\nfrom igibson.utils.ig_logging import IGLogReader, IGLogWriter\nfrom igibson.utils.utils import parse_str_config\n\n\ndef verify_determinism(in_log_path, out_log_path):\n    is_deterministic = True\n    with h5py.File(in_log_path) as original_file, h5py.File(out_log_path) as new_file:\n        for obj in original_file[\"physics_data\"]:\n            for attribute in original_file[\"physics_data\"][obj]:\n                is_close = np.isclose(\n                    original_file[\"physics_data\"][obj][attribute], new_file[\"physics_data\"][obj][attribute]\n                ).all()\n                is_deterministic = is_deterministic and is_close\n                if not is_close:\n                    print(\"Mismatch for obj {} with mismatched attribute {}\".format(obj, attribute))\n    return bool(is_deterministic)\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser(description=\"Run and collect an ATUS demo\")\n    parser.add_argument(\"--vr_log_path\", type=str, help=\"Path (and filename) of vr log to replay\")\n    parser.add_argument(\n        \"--vr_replay_log_path\", type=str, help=\"Path (and filename) of file to save replay to (for debugging)\"\n    )\n    parser.add_argument(\n        \"--frame_save_path\",\n        type=str,\n        help=\"Path to save frames (frame number added automatically, as well as .jpg extension)\",\n    )\n    parser.add_argument(\n        \"--disable_save\",\n        action=\"store_true\",\n        help=\"Whether to disable saving log of replayed trajectory, used for validation.\",\n    )\n    parser.add_argument(\"--profile\", action=\"store_true\", help=\"Whether to print profiling data.\")\n    parser.add_argument(\n        \"--mode\",\n        type=str,\n        choices=[\"headless\", \"vr\", \"simple\"],\n        help=\"Whether to disable replay through VR and use iggui instead.\",\n    )\n    return parser.parse_args()\n\n\ndef replay_demo(\n    in_log_path,\n    out_log_path=None,\n    disable_save=False,\n    frame_save_path=None,\n    verbose=True,\n    mode=\"headless\",\n    start_callbacks=[],\n    step_callbacks=[],\n    end_callbacks=[],\n    profile=False,\n):\n    \"\"\"\n    Replay a BEHAVIOR demo.\n\n    Note that this returns, but does not check for determinism. Use safe_replay_demo to assert for determinism\n    when using in scenarios where determinism is important.\n\n    @param in_log_path: the path of the BEHAVIOR demo log to replay.\n    @param out_log_path: the path of the new BEHAVIOR demo log to save from the replay.\n    @param frame_save_path: the path to save frame images to. None to disable frame image saving.\n    @param mode: which rendering mode (\"headless\", \"simple\", \"vr\"). In simple mode, the demo will be replayed with simple robot view.\n    @param disable_save: Whether saving the replay as a BEHAVIOR demo log should be disabled.\n    @param profile: Whether the replay should be profiled, with profiler output to stdout.\n    @param start_callback: A callback function that will be called immediately before starting to replay steps. Should\n        take a single argument, an iGBEHAVIORActivityInstance.\n    @param step_callback: A callback function that will be called immediately following each replayed step. Should\n        take a single argument, an iGBEHAVIORActivityInstance.\n    @param end_callback: A callback function that will be called when replay has finished. Should take a single\n        argument, an iGBEHAVIORActivityInstance.\n    @return if disable_save is True, returns None. Otherwise, returns a boolean indicating if replay was deterministic.\n    \"\"\"\n    # HDR files for PBR rendering\n    hdr_texture = os.path.join(igibson.ig_dataset_path, \"scenes\", \"background\", \"probe_02.hdr\")\n    hdr_texture2 = os.path.join(igibson.ig_dataset_path, \"scenes\", \"background\", \"probe_03.hdr\")\n    light_modulation_map_filename = os.path.join(\n        igibson.ig_dataset_path, \"scenes\", \"Rs_int\", \"layout\", \"floor_lighttype_0.png\"\n    )\n    background_texture = os.path.join(igibson.ig_dataset_path, \"scenes\", \"background\", \"urban_street_01.jpg\")\n\n    # VR rendering settings\n    vr_rendering_settings = MeshRendererSettings(\n        optimized=True,\n        fullscreen=False,\n        env_texture_filename=hdr_texture,\n        env_texture_filename2=hdr_texture2,\n        env_texture_filename3=background_texture,\n        light_modulation_map_filename=light_modulation_map_filename,\n        enable_shadow=True,\n        enable_pbr=True,\n        msaa=False,\n        light_dimming_factor=1.0,\n    )\n\n    # Check mode\n    assert mode in [\"headless\", \"vr\", \"simple\"]\n\n    # Initialize settings to save action replay frames\n    vr_settings = VrSettings(config_str=IGLogReader.read_metadata_attr(in_log_path, \"/metadata/vr_settings\"))\n    vr_settings.set_frame_save_path(frame_save_path)\n\n    task = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/atus_activity\")\n    task_id = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/activity_definition\")\n    scene = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/scene_id\")\n    physics_timestep = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/physics_timestep\")\n    render_timestep = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/render_timestep\")\n    filter_objects = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/filter_objects\")\n\n    logged_git_info = IGLogReader.read_metadata_attr(in_log_path, \"/metadata/git_info\")\n    logged_git_info = parse_str_config(logged_git_info)\n    git_info = project_git_info()\n    pp = pprint.PrettyPrinter(indent=4)\n\n    for key in logged_git_info.keys():\n        logged_git_info[key].pop(\"directory\", None)\n        git_info[key].pop(\"directory\", None)\n        if logged_git_info[key] != git_info[key] and verbose:\n            print(\"Warning, difference in git commits for repo: {}. This may impact deterministic replay\".format(key))\n            print(\"Logged git info:\\n\")\n            pp.pprint(logged_git_info[key])\n            print(\"Current git info:\\n\")\n            pp.pprint(git_info[key])\n\n    # VR system settings\n    s = Simulator(\n        mode=mode,\n        physics_timestep=physics_timestep,\n        render_timestep=render_timestep,\n        rendering_settings=vr_rendering_settings,\n        vr_settings=vr_settings,\n        image_width=1280,\n        image_height=720,\n    )\n\n    igtn_task = iGBEHAVIORActivityInstance(task, task_id)\n    igtn_task.initialize_simulator(\n        simulator=s,\n        scene_id=scene,\n        scene_kwargs={\n            \"urdf_file\": \"{}_neurips_task_{}_{}_0_fixed_furniture\".format(scene, task, task_id),\n        },\n        load_clutter=True,\n        online_sampling=False,\n    )\n    vr_agent = igtn_task.simulator.robots[0]\n    vr_agent.activate()\n    igtn_task.reset_scene(snapshot_id=igtn_task.initial_state)\n    # set the constraints to the current poses\n    vr_agent.apply_action(np.zeros(28))\n\n    if not in_log_path:\n        raise RuntimeError(\"Must provide a VR log path to run action replay!\")\n    log_reader = IGLogReader(in_log_path, log_status=False)\n\n    log_writer = None\n    if not disable_save:\n        timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n        if out_log_path == None:\n            out_log_path = \"{}_{}_{}_{}_replay.hdf5\".format(task, task_id, scene, timestamp)\n\n        log_writer = IGLogWriter(\n            s,\n            log_filepath=out_log_path,\n            task=igtn_task,\n            store_vr=False,\n            vr_robot=vr_agent,\n            profiling_mode=profile,\n            filter_objects=filter_objects,\n        )\n        log_writer.set_up_data_storage()\n\n    for callback in start_callbacks:\n        callback(igtn_task, log_reader)\n\n    task_done = False\n    while log_reader.get_data_left_to_read():\n\n        action = log_reader.get_agent_action(\"vr_robot\")\n        # Get relevant VR action data and update VR agent\n        vr_agent.apply_action(action)\n\n        if not disable_save:\n            log_writer.process_frame()\n\n        igtn_task.simulator.step(print_stats=profile)\n        task_done, _ = igtn_task.check_success()\n\n        # Set camera each frame\n        if mode == \"vr\":\n            log_reader.set_replay_camera(s)\n\n        for callback in step_callbacks:\n            callback(igtn_task, log_reader)\n\n        # Per-step determinism check. Activate if necessary.\n        # things_to_compare = [thing for thing in log_writer.name_path_data if thing[0] == \"physics_data\"]\n        # for thing in things_to_compare:\n        #     thing_path = \"/\".join(thing)\n        #     fc = log_reader.frame_counter % log_writer.frames_before_write\n        #     if fc == log_writer.frames_before_write - 1:\n        #         continue\n        #     replayed = log_writer.get_data_for_name_path(thing)[fc]\n        #     original = log_reader.read_value(thing_path)\n        #     if not np.all(replayed == original):\n        #         print(\"%s not equal in %d\" % (thing_path, log_reader.frame_counter))\n        #     if not np.isclose(replayed, original).all():\n        #         print(\"%s not close in %d\" % (thing_path, log_reader.frame_counter))\n\n    print(\"Demo was succesfully completed: \", task_done)\n\n    demo_statistics = {}\n    for callback in end_callbacks:\n        callback(igtn_task, log_reader)\n\n    s.disconnect()\n\n    is_deterministic = None\n    if not disable_save:\n        log_writer.end_log_session()\n        is_deterministic = verify_determinism(in_log_path, out_log_path)\n        print(\"Demo was deterministic: \", is_deterministic)\n\n    demo_statistics = {\n        \"deterministic\": is_deterministic,\n        \"task\": task,\n        \"task_id\": int(task_id),\n        \"scene\": scene,\n        \"task_done\": task_done,\n        \"total_frame_num\": log_reader.total_frame_num,\n    }\n    return demo_statistics\n\n\ndef safe_replay_demo(*args, **kwargs):\n    \"\"\"Replays a demo, asserting that it was deterministic.\"\"\"\n    demo_statistics = replay_demo(*args, **kwargs)\n    assert (\n        demo_statistics[\"deterministic\"] == True\n    ), \"Replay was not deterministic (or was executed with disable_save=True).\"\n\n\ndef main():\n    args = parse_args()\n    bddl.set_backend(\"iGibson\")\n    replay_demo(\n        args.vr_log_path,\n        out_log_path=args.vr_replay_log_path,\n        disable_save=args.disable_save,\n        frame_save_path=args.frame_save_path,\n        mode=args.mode,\n        profile=args.profile,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n","sub_path":"igibson/examples/behavior/behavior_demo_replay_rl.py","file_name":"behavior_demo_replay_rl.py","file_ext":"py","file_size_in_byte":10771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"403608645","text":"# Add save file\n# Save money and unlocked parts\n# Eg. Read unlocked and locked engines file to lists\n# If engine purchased, move to unlocked list\n# At save, write locked and unlocked to save file to be read from next time\n\nimport time, random\nfrom tkinter import *\n\n# Chassis File\nc = open('chassis.txt','r').read()\ncl = c.split('\\n')\n\n# Engine File\ne = open('engines.txt','r').read()\nel = e.split('\\n')\n\n# Master\nmaster = Tk()\nmaster.title('SPyDR v1.0')\nmaster.geometry('800x450')\n# master.wm_attributes('-transparentcolor', master['bg'])\nmaster.resizable(False, False)\n\n# Background\nbkg = PhotoImage(file='bkg2.gif')\nsetb = Label(master, image=bkg)\nsetb.place(x=0, y=0, relwidth=1, relheight=1)\n\n# Title Widgets\ntitleframe = Frame(master, height=30, width=800, bg='black')\ntitleframe.pack_propagate(0)\ntitleframe.grid(row=0,column=0)\n\ntitle = Label(titleframe, text='SPyDR', bg='#420051', fg='white')\ntitle.pack(fill=X, expand=1)\n#subtitle = Label(titleframe, text='Super Python Drag Racer', bg='#420051', fg='white')\n#subtitle.pack(fill=x, expand=1)\n\n### Info (Username and Money)\n# Master Info Frame\nifm = Frame(master, height=45, width=800)\nifm.pack_propagate(0)\nifm.grid(row=1,column=0,sticky='w')\n\n# Info Frame 1\nif1 = Frame(ifm, height=45, width=200)\nif1.pack_propagate(0)\nif1.grid(row=0,column=0,sticky='w')\n\n# Info Frame 2\nif2 = Frame(ifm, height=45, width=200)\nif2.pack_propagate(0)\nif2.grid(row=0,column=1,sticky='w')\n\n# Info Frame 3\nif3 = Frame(ifm, height=45, width=200)\nif3.pack_propagate(0)\nif3.grid(row=0,column=2,sticky='w')\n\n# Info Frame 4\nif4 = Frame(ifm, height=45, width=200)\nif4.pack_propagate(0)\nif4.grid(row=0,column=3,sticky='w')\n\n# 'Username' text label\nuserlab = Label(if1, text='USER:')\nuserlab.pack(fill=X, expand=1)\n\n# Username entry field\ndef clr(event):\n    event.widget.delete(0, 'end')\n    return None\n\nuserent = Entry(if2)\nuserent.insert(0,'Enter Username')\nuserent.bind('', clr)\nuserent.pack(fill=BOTH, expand=1)\n#user = userent.get()\n\n# 'Money' text label\nmoneytext = Label(if3, text='MONEY:',anchor='e')\nmoneytext.pack(fill=X, expand=1)\n\n# Money label\nmoney = 0\nmoneyvar = StringVar(if4)\nmoneytext = '£'+str(money)\nmoneyvar.set(moneytext)\nmoneylab = Label(if4, textvariable=moneyvar)\nmoneylab.pack(fill=X, expand=1)\n\n# Widgets and Output Box Master Frame\nwaomframe = Frame(master, height=250, width=800,bg='black')\nwaomframe.pack_propagate(0)\nwaomframe.grid(row=2,column=0,sticky='w')\n\n### Car Modification Widgets\nwidframe = Frame(waomframe, height=250, width=400, bg='black')\nwidframe.pack_propagate(0)\nwidframe.grid(row=0,column=0,sticky='news')\n\n# Chassis Widgets\nchaslab = Label(widframe, text='CHASSIS:', width=27, bg='black', fg='white', relief=SUNKEN).grid(row=0, column=0, sticky='news')\nchasddvar = StringVar(widframe)\nchasddselect = '--Select Chassis--'\nchasddvar.set(chasddselect) # Starting text\nchasdd = OptionMenu(widframe, chasddvar, *cl) # *cl = list of options from chassis.txt\nchasdd.config(width=27)\nchasdd.grid(row=0,column=1)\n\n# Engine Widgets\nenglab = Label(widframe, text='ENGINE:', bg='black', fg='white', relief=SUNKEN).grid(row=1, column=0, sticky='news')\nengddvar = StringVar(widframe)\nengddselect = '--Select Engine--'\nengddvar.set(engddselect)\nengdd = OptionMenu(widframe, engddvar, *el)\nengdd.grid(row=1,column=1, sticky='ew')\n\n# Nitrous Widgets\nnitlab = Label(widframe, text='NITROUS:', bg='black', fg='white', relief=SUNKEN).grid(row=2, column=0, sticky='news')\nnitddvar = StringVar(widframe)\nnitddselect = '--Select Nitrous--'\nnitddvar.set(nitddselect)\nnl = ['None','5l Tank']\nnitdd = OptionMenu(widframe, nitddvar, *nl)\nnitdd.grid(row=2,column=1, sticky='ew')\n\n### Output Box\nopframe = Frame(waomframe, height=200, width=400, relief=SUNKEN, bg='black')\nopframe.pack_propagate(0)\nopframe.grid(row=0,column=1,sticky='e')\n\noutvar = StringVar(master)\noutvarph = '''Welcome to the SPyDR drag strip.\nPlease build your car to be raced.'''\noutvar.set(outvarph)\nouttext = Label(opframe, textvariable=outvar, fg='cyan', bg='black', justify=CENTER, relief=SUNKEN)\nouttext.pack(fill=BOTH, expand=1)\n\n### Race and Shift Buttons\n# RaS Master Frame\nbtnframe = Frame(waomframe, height=50, width=400, bg='black')\nbtnframe.pack_propagate(0)\nbtnframe.grid(row=1,column=1)\n\n# Start Race Button Frame\nrbframe = Frame(btnframe, height=50, width=200,bg='black')\nrbframe.pack_propagate(0)\nrbframe.grid(row=0,column=0)\n\n### Message Box\nmessframe = Frame(waomframe, width=200, height=49)\nmessframe.pack_propagate(0)\nmessframe.grid(row=1,column=0,sticky='new')\n\nmesslab = Label(messframe, text='Warning: Using Nitrous may cause engine failiures.', fg='red', bg='black')\nmesslab.pack(fill=BOTH, expand=1)\n\n# Build Car Button\ndef build():\n    chasph = chasddvar.get()\n    engph = engddvar.get()\n    nitph = nitddvar.get()\n    \n    if chasph == chasddselect or engph == engddselect or nitph == nitddselect:\n        outvarph = 'Error. Please select parts for your car...'\n        outvar.set(outvarph)\n    else:\n        outvarph = ('''Your car has been built!\\n\\n\nChassis: '''+chasph+'\\nEngine: '+engph+'\\nNitrous: '+nitph)\n        outvar.set(outvarph)\n        outtext.pack(fill=BOTH, expand=1)\n\n        rbutton.config(state='normal')\n\n# Shift Button Frame\nshframe = Frame(btnframe, height=50, width=200,bg='black')\nshframe.pack_propagate(0)\nshframe.grid(row=0,column=1)\n    \n\n### CODE ###\n\n\n# Finding Opponent            \ndef findingopp():\n    outvarph = 'Finding opponent, please wait...'\n    outvar.set(outvarph)\n    print('finding')\n\n#  Found Opponent\ndef foundopp():\n    outvarph = 'Opponent found. Race commencing in 5 seconds...\\n\\n'\n    \n    co = random.choice(cl)\n    eo = random.choice(el)\n    nit = random.choice(['y','n'])\n    global avgo\n    avgo = round(random.uniform(0,0.8),3)\n\n    nitph = nitddvar.get()\n    if nitph != 'None':\n        fail = random.randint(1,3)\n        if fail == 1:\n            avgo += random.uniform(0.2,0.5)\n            avgo = round(avgo,3)\n\n    oppdata = ('Your opponent has a:\\n'+co+'\\n'+'with a '+eo)\n    outvar.set(outvarph+oppdata)\n    print('found')\n\n# Start Race Button (on button click)\ndef start():\n    rbutton.config(state='disabled')\n    build.config(state='disabled')\n    engdd.configure(state='disabled')\n    chasdd.configure(state='disabled')\n    nitdd.configure(state='disabled')\n    prog()\n    #shbutton.config(state='normal')\n# Start Now Text\ndef startnow():\n    shbutton.config(state='normal')\n    outvarph = 'Drag race starts NOW!'\n    outvar.set(outvarph)\n\n\n###   Needs working on:\n# Shifloop\ndef shiftloop():\n    t1 = time.perf_counter()\n    outvar.set('SHIFT NOW!')\n\n    shbutton.wait_variable(shvar)\n\n    t = round(time.perf_counter()-t1,3)\n    times += t\n    outvarph = ('Gear Shift took '+str(t)+' seconds\\n')\n    outvar.set(outvarph)\n# Shiftcode\ndef shiftcode():\n    global times\n    global avg\n    shiftdata = ''\n    times = 0\n\n    for loop in range(5):\n        shwait = random.randint(1,5)*1000\n        master.after(shwait,shiftloop)\n\n    avg = round(times/5,3)\n    outvarph = ('\\n\\nYour Average shift time was: '+str(avg))\n    outvar.set(outvarph)\n    outvarph = 'Your shifting speed was '\n    if 00.7:\n        outvarph+'not worth waiting for'\n    outvar.set(outvarph)\n\n    nitph = nitddvar.get()\n    if nitph != 'None':\n        fail = random.randint(1,3)\n        if fail == 1:\n            times += random.uniform(0.2,0.5)\n            avg = round(times/5,3)\n            outvarph = ('Oh dear. You have blown a head gasket. Therefore your actual time was: '+str(avg))\n            outvar.set(outvarph)\n\n# Shift\ndef shift():\n    global t, t1, times, outvar\n    t = round(time.perf_counter()-t1,3)\n    times += t\n    outvarph = ('Gear Shift took '+str(t)+' seconds\\n')\n    outvar.set(outvarph)\n\n# Results (end of game and money dealt)\ndef results():\n    global money, avg\n    if avg < avgo:\n        prize = random.randint(100,1000)\n        money += prize\n        moneytext = '£'+str(money)\n        moneyvar.set(moneytext)\n        outvarph = ('You won by '+str(round(avgo-avg, 3))+' seconds.\\nCongratulations on the win. Here is £'+str(prize)+' as a reward.')\n        outvar.set(outvarph)\n    else:\n        outvarph = ('You lost by '+str(round(avg-avgo, 3))+' seconds unfortunately.\\nBetter luck next time.')\n        outvar.set(outvarph)\n\n### Program\ndef prog():\n    global oppdata, outvar, avg, avgo\n    \n    num = 1\n    \n    outvarph = '''Get ready to drag race...\n    Wait for the \"SHIFT NOW!\" signal and click the \n    \"SHIFT\" button to shift up a gear.'''\n    outvar.set(outvarph)\n    print('ready')\n\n    master.after(2000, findingopp)\n    master.after(5000, foundopp)\n    master.after(10000, startnow)\n\n    #################\n    #shiftcode()\n    #################\n    \n    # opptime = ('Your opponent clocked in at '+str(avgo)+' seconds.')\n\n    shbutton.config(state='disabled')\n    #build.config(state='normal')\n\n\n\n### BUTTONS ###\n\n# Build Button GUI\nbuild = Button(widframe, command=build, text='BUILD', bg='#3c3c3c', fg='yellow',activebackground='#2b2b2b',activeforeground='yellow')\nbuild.grid(row=3, column=1, sticky='news')\n\n# Race Button GUI\nrbuttonvar = StringVar(rbframe)\nrbuttonvar.set('START RACE')\nrbutton = Button(rbframe, text=rbuttonvar.get(), command=start, bg='#3c3c3c', fg='lime',activebackground='#2b2b2b',activeforeground='lime')\nrbutton.config(state='disabled')\nrbutton.pack(fill=BOTH, expand=1)\n\n# Shift Button GUI    \nshvar = IntVar()\nshbutton = Button(shframe, text='SHIFT', command=lambda: shvar.set(1), bg='#3c3c3c', fg='red',activebackground='#2b2b2b',activeforeground='red')\nshbutton.config(state='disabled')\nshbutton.pack(fill=BOTH, expand=1)\n\n\n#  Play Again code\n#    p = input('Race again? y or n:   ')\n#    if p == 'y':\n#        print('\\n\\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\\n\\n')\n#        prog()\n#    else:\n#        quit()\n\n# master.protocol('WM_DELETE_WINDOW',nothing()) #On exit event\n\n\nmaster.mainloop()\n\n\n","sub_path":"SPyDR GUI (code first) - v1.3.4.pyw","file_name":"SPyDR GUI (code first) - v1.3.4.pyw","file_ext":"pyw","file_size_in_byte":10210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"513587834","text":"import asyncio\nimport asynctest\nfrom unittest import mock\n\nimport katsdptelstate.aio\n\nimport kattelmod\nfrom kattelmod.component import Component, TelstateUpdatingComponent, KATCPComponent, MultiMethod\nfrom kattelmod.clock import get_clock\nfrom kattelmod.test.test_clock import WarpEventLoopTestCase\n\n\nclass DummyComponent(Component):\n    def __init__(self, speed: float) -> None:\n        super().__init__()\n        self._name = 'dummy'\n        self._initialise_attributes(locals())\n        self._add_dummy_methods('capture_start capture_stop')\n        self.temperature = 451.0\n        self.pressure = 1000.0\n\n\nclass DummyTelstateUpdatingComponent(TelstateUpdatingComponent):\n    def __init__(self, speed: float) -> None:\n        super().__init__()\n        self._name = 'dummy'\n        self._initialise_attributes(locals())\n        self.temperature = 451.0\n        self.pos_foo = 1000.0     # Will be rate limited by name\n\n\nclass TestComponent(WarpEventLoopTestCase):\n    def setUp(self):\n        self.comp = DummyComponent(88.0)\n\n    def test_type(self):\n        self.assertEqual(self.comp._type(), 'kattelmod.test.test_component.DummyComponent')\n\n    def test_repr(self):\n        self.assertRegex(\n            repr(self.comp),\n            r\"\")\n\n    def test_sensors(self):\n        self.assertEqual(self.comp._sensors, ['pressure', 'speed', 'temperature'])\n\n    async def test_dummy_methods(self):\n        # Just tests that it exists and runs without crashing\n        await self.comp.capture_stop()\n\n    def test_fake(self):\n        # Fake up the import so that it just returns this module again, instead\n        # of trying to go into kattelmod.systems. Note that this cannot be a\n        # decorator because 'kattelmod.test.test_component' is not defined at\n        # the time the module is being imported.\n        with mock.patch('kattelmod.component.import_module',\n                        return_value=kattelmod.test.test_component):\n            self.comp.temperature = 100.0\n            fake = self.comp._fake()\n            self.assertEqual(fake.temperature, 100.0)\n            self.assertEqual(fake.pressure, 1000.0)\n            self.assertEqual(fake.speed, 88.0)\n\n\nclass TestTelstateUpdatingComponent(WarpEventLoopTestCase):\n    async def setUp(self):\n        self.telstate = katsdptelstate.aio.TelescopeState()\n        self.comp = DummyTelstateUpdatingComponent(88.0)\n        self.comp._name = 'dummy'\n        self.comp._telstate = self.telstate\n        await self.comp._start()\n        # Some of the internal are based around whether there has been an update\n        # yet.\n        self.comp._update(self.START_TIME)\n\n    async def test_setattr(self):\n        \"\"\"Basic test that setting an attribute updates telstate\"\"\"\n        await self.comp._flush()\n        self.assertEqual(await self.telstate.get('dummy_speed'), 88.0)\n        self.assertEqual(await self.telstate.key_type('dummy_speed'),\n                         katsdptelstate.KeyType.IMMUTABLE)\n        # Initial value is pushed into the past\n        self.assertEqual(await self.telstate.get_range('dummy_temperature', st=0),\n                         [(451.0, self.START_TIME - 300.0)])\n        get_clock().advance(5)\n        self.comp.temperature = 100.0\n        await self.comp._flush()\n        self.assertEqual(await self.telstate.get_range('dummy_temperature', st=0),\n                         [(451.0, self.START_TIME - 300.0), (100.0, self.START_TIME + 5.0)])\n\n    async def test_updates(self):\n        \"\"\"Test interaction with _update and rate limiting.\n\n        Normally the attribute setting would be done in the _update callback,\n        but it's easier to put them in the test rather than in the dummy\n        class.\n        \"\"\"\n        for i in range(6):\n            get_clock().advance(0.25)\n            self.comp._update(get_clock().time())\n            self.comp.temperature += 1.0\n            self.comp.pos_foo += 1.0\n        await self.comp._flush()\n        self.assertEqual(\n            await self.telstate.get_range('dummy_temperature', st=0),\n            [(451.0, self.START_TIME - 300.0),\n             (452.0, self.START_TIME + 0.25),\n             (453.0, self.START_TIME + 0.5),\n             (454.0, self.START_TIME + 0.75),\n             (455.0, self.START_TIME + 1.0),\n             (456.0, self.START_TIME + 1.25),\n             (457.0, self.START_TIME + 1.5)])\n        self.assertEqual(\n            await self.telstate.get_range('dummy_pos_foo', st=0),\n            [(1000.0, self.START_TIME - 300.0),\n             (1002.0, self.START_TIME + 0.5),\n             (1004.0, self.START_TIME + 1.0),\n             (1006.0, self.START_TIME + 1.5)])\n\n    def test_updatable(self):\n        self.assertTrue(self.comp._updatable)\n\n    async def test_start_twice(self):\n        # Mostly just to get test coverage\n        await self.comp._start()\n\n\nclass TestKATCPComponent(asynctest.ClockedTestCase):\n    async def setUp(self) -> None:\n        self.server = await asyncio.start_server(self._client_cb, '127.0.0.1', 0)\n        self.endpoint = self.server.sockets[0].getsockname()[:2]\n        self.addCleanup(self.server.wait_closed)\n        self.addCleanup(self.server.close)\n        self.reader = self.loop.create_future()    # type: asyncio.Future[asyncio.StreamReader]\n        self.writer = self.loop.create_future()    # type: asyncio.Future[asyncio.StreamWriter]\n\n    def _client_cb(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:\n        self.reader.set_result(reader)\n        self.writer.set_result(writer)\n        self.addCleanup(writer.close)\n\n    def test_bad_endpoint(self):\n        with self.assertRaises(ValueError):\n            KATCPComponent('invalid.com')\n        with self.assertRaises(ValueError):\n            KATCPComponent('')\n\n    async def test_connect_timeout(self):\n        comp = KATCPComponent('{}:{}'.format(*self.endpoint))\n        task = asyncio.ensure_future(comp._start())\n        await self.advance(100)\n        with self.assertRaises(asyncio.TimeoutError):\n            await task\n\n    async def _interact(self):\n        reader = await self.reader\n        writer = await self.writer\n        writer.write(b'#version-connect katcp-protocol 5.0-MI\\n')\n        await writer.drain()\n        await reader.readline()\n        writer.write(b'!ping[1] ok hello\\n')\n        await writer.drain()\n\n    async def test_good(self):\n        task = self.loop.create_task(self._interact())\n        comp = KATCPComponent('{}:{}'.format(*self.endpoint))\n        await comp._start()\n        await comp._start()      # Check that it's idempotent\n        response = await comp._client.request('ping', 'hello')\n        self.assertEqual(response, ([b'hello'], []))\n        await comp._stop()\n        await comp._stop()       # Check that it's idempotent\n        await task\n\n\nclass SyncMethod:\n    def __init__(self):\n        self.called_with = None\n\n    def my_method(self, *args, **kwargs):\n        self.called_with = (args, kwargs)\n\n\nclass AsyncMethod:\n    def __init__(self):\n        self.called_with = None\n\n    async def my_method(self, *args, **kwargs):\n        await asyncio.sleep(0)\n        self.called_with = (args, kwargs)\n\n\nclass TestMultiMethod(asynctest.TestCase):\n    def setUp(self):\n        self.sync1 = SyncMethod()\n        self.sync2 = SyncMethod()\n        self.async1 = AsyncMethod()\n        self.async2 = AsyncMethod()\n\n    def test_sync(self):\n        mm = MultiMethod([self.sync1, self.sync2], 'my_method', 'help')\n        self.assertIsNone(self.sync1.called_with)\n        self.assertIsNone(self.sync2.called_with)\n        mm('a', 1, kw=2)\n        self.assertEqual(self.sync1.called_with, (('a', 1), {'kw': 2}))\n        self.assertEqual(self.sync2.called_with, (('a', 1), {'kw': 2}))\n\n    async def test_async(self):\n        mm = MultiMethod([self.async1, self.async2], 'my_method', 'help')\n        self.assertIsNone(self.async1.called_with)\n        self.assertIsNone(self.async2.called_with)\n        await mm('a', 1, kw=2)\n        self.assertEqual(self.async1.called_with, (('a', 1), {'kw': 2}))\n        self.assertEqual(self.async2.called_with, (('a', 1), {'kw': 2}))\n","sub_path":"kattelmod/test/test_component.py","file_name":"test_component.py","file_ext":"py","file_size_in_byte":8162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"157751643","text":"##############################################################################\n#\n# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.\n# \n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE\n# \n##############################################################################\n\nimport Globals\nfrom Acquisition import aq_base\n\nfrom AccessControl import ClassSecurityInfo\nfrom CMFCorePermissions import ModifyPortalContent\nfrom utils import getToolByName\n\n\nclass CMFCatalogAware:\n    \"\"\"Mix-in for notifying portal_catalog and portal_workflow\n    \"\"\"\n\n    security = ClassSecurityInfo()\n\n    # Cataloging methods\n    # ------------------\n\n    security.declareProtected(ModifyPortalContent, 'indexObject')\n    def indexObject(self):\n        catalog = getToolByName(self, 'portal_catalog', None)\n        if catalog is not None:\n            catalog.indexObject(self)\n\n    security.declareProtected(ModifyPortalContent, 'unindexObject')\n    def unindexObject(self):\n        catalog = getToolByName(self, 'portal_catalog', None)\n        if catalog is not None:\n            catalog.unindexObject(self)\n\n    security.declareProtected(ModifyPortalContent, 'reindexObject')\n    def reindexObject(self):\n        catalog = getToolByName(self, 'portal_catalog', None)\n        if catalog is not None:\n            catalog.reindexObject(self)\n        \n    def manage_afterAdd(self, item, container):\n        \"\"\"\n            Add self to the workflow and catalog.\n        \"\"\"\n        #\n        #   Are we being added (or moved)?\n        #\n        if aq_base(container) is not aq_base(self):\n            self.indexObject()\n\n    def manage_afterClone(self, item):\n        \"\"\"\n            Add self to workflow, as we have just been cloned.\n        \"\"\"\n        if aq_base(item) is aq_base(self):\n            wf = getToolByName(self, 'portal_workflow', None)\n            if wf is not None:\n                wf.notifyCreated(self)\n\n    def manage_beforeDelete(self, item, container):\n        \"\"\"\n            Remove self from the catalog.\n        \"\"\"\n        #\n        #   Are we going away?\n        #\n        if aq_base(container) is not aq_base(self):\n            self.unindexObject()\n            #\n            #   Now let our \"aspects\" know we are going away.\n            #\n            for item_id, subitem in self.objectItems():\n                # Carefully avoid implicit acquisition of the\n                # name \"manage_beforeDelete\"\n                if hasattr(aq_base(subitem), 'manage_beforeDelete'):\n                    subitem.manage_beforeDelete(item, container)\n\n\nGlobals.InitializeClass(CMFCatalogAware)\n\n","sub_path":"CMF/tags/CMF-1_3-abandoned-branch/CMFCore/CMFCatalogAware.py","file_name":"CMFCatalogAware.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"99656116","text":"\nclass Node:\n    def __init__(self,key,value):\n        self.key = key\n        self.value = value\n        self.next = None\n        self.prev = None\n\nclass DoublyLL:\n    def _init__(self,data):\n        self.head = None\n        self.tail = None\n\nclass cache:\n\n\n    def __init__(self):\n        self.capacity = 3\n        self.KVMap = {}\n        self.KVList = [0 for i in range(self.capacity)]\n        self.LL = DoublyLL()\n\n    def insert(self,k,v):\n        if len(self.KVMap) == self.capacity:\n            self.evict() # if reached capacity then remove the element\n        else:\n            reference = self.insertLL(key,value) # adjust pointers\n            self.KVMap[k] = reference\n\n    # create a reference and store that in map\n    def insertLL(self,key,value):\n        reference = Node(key,value)\n\n        if not self.LL.head: # first node\n            self.LL.head = self.LL.tail = reference\n        else:\n            reference.next = self.LL.head\n            self.LL.head.prev = reference\n            self.LL.head = reference\n\n        return reference\n\n\n    # get the tail and now set the tail to prev\n    def evict(self):\n        key = self.LL.tail.key\n        self.LL.tail = self.LL.tail.prev\n\n        self.KVMap.delete(key)\n\n    def getValueNSetHead (self,reference):\n        temp = reference.next\n        temp.prev =reference.prev\n\n        reference.next = self.LL.head\n        reference.prev = None\n        self.LL.head = reference\n        return reference.value\n\n\n    def get(self,k):\n        if (self.KVMap[k]):\n            reference = self.KVMap[k]\n            value = self.getValueNSetHead(reference)\n        else:\n            value = self.getFromDB(k)\n\n        return value\n\n    def getFromDB(self,k):\n        return \"value\"","sub_path":"Python/IK/LinkedListStackQueue/LRUCache.py","file_name":"LRUCache.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"188308490","text":"import eventlet\neventlet.monkey_patch()\n\nimport argparse\n\nimport redis\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--host\", default=\"localhost\")\nparser.add_argument(\"--port\", default=8080)\nparser.add_argument(\"--redisHost\", required=True)\nparser.add_argument(\"--redisChannel\", default=\"transcriptions\")\nparser.add_argument(\"--id\", default=\"Editor\")\nargs = parser.parse_args()\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\n# socketio = SocketIO(async_mode='threading')\nsocketio = SocketIO()\nrdb = redis.Redis(host=args.redisHost, port=6379, db=0)\np = rdb.pubsub()\nthread = None\n\n\n@app.route('/')\ndef index():\n  return render_template('index.html', async_mode=socketio.async_mode)\n\n\n@socketio.on('connect')\ndef connect():\n  print('%s socket connected!' % args.id)\n  # socketio.emit('message', 'acking your connect')\n  global thread\n  if thread is None:\n    print('starting new background task')\n    p.subscribe(args.redisChannel)\n    thread = socketio.start_background_task(target=start_listening)\n\n\ndef start_listening():\n  for msg in p.listen():\n    # print('Read pubsub msg:' + str(msg))\n    if 'subscribe' not in msg['type']:\n      payload = msg['data'].decode('utf-8')\n      socketio.emit('pubsubmsg', payload)\n    socketio.sleep(0.2)\n\n\n@socketio.on('disconnect')\ndef disconnect():\n  print('%s socket disconnected!' % args.id)\n\n\n@socketio.on('message')\ndef handle_message(message):\n  print('Ignoring received string message: ' + message)\n\n\nif __name__ == '__main__':\n  socketio.init_app(app)\n  socketio.run(app, host=args.host, port=args.port)\n","sub_path":"ui/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"64523418","text":"from avaiation_ellipsoid_calc_tools import vincenty_direct_solution\nfrom aviation_bearing_tools import MagVar, Bearing\nfrom aviation_coordinate_tools import CoordinatesPair\n\n\n# Parameters of WGS84 ellipsoid\n\nWGS84_A = 6378137.0  # semi-major axis of the WGS84 ellipsoid in m\nWGS84_B = 6356752.314245  # semi-minor axis of the WGS84 ellipsoid in m\nWGS84_F = 1 / 298.257223563  # flattening of the WGS84 ellipsoid\n\n\nclass LocalOriginPoint(CoordinatesPair):\n    def __init__(self, src_lat, src_lon, src_mag_var, origin_id='', origin_name=''):\n        CoordinatesPair.__init__(self, src_lat, src_lon)\n        self.mag_var = MagVar(src_mag_var)\n        self.origin_id = origin_id\n        self.origin_name = origin_name\n        self.check_init_data()\n\n    def check_init_data(self):\n        if self.mag_var.is_valid is False:\n            self.is_valid = False\n            self.err_msg += self.mag_var.err_msg\n\n\nclass LocalPolarEndPoint:\n    def __init__(self, origin_point: LocalOriginPoint, brng: Bearing, dist_m):\n        self.origin_point = origin_point\n        self.brng = brng\n        self.dist_m = dist_m\n        self._ep_lon_dd = None\n        self._ep_lat_dd = None\n        self.calc_ep()\n\n    def calc_ep(self):\n        self.brng.calc_tbrng(self.origin_point.mag_var.dd_value)\n        self.ep_lat_dd, self.ep_lon_dd = vincenty_direct_solution(self.origin_point.dd_lat,\n                                                                  self.origin_point.dd_lon,\n                                                                  self.brng.dd_tbrng,\n                                                                  self.dist_m,\n                                                                  WGS84_A, WGS84_B, WGS84_F)\n\n    @property\n    def ep_lat_dd(self):\n        return self._ep_lat_dd\n\n    @ep_lat_dd.setter\n    def ep_lat_dd(self, value):\n        self._ep_lat_dd = value\n\n    @property\n    def ep_lon_dd(self):\n        return self._ep_lon_dd\n\n    @ep_lon_dd.setter\n    def ep_lon_dd(self, value):\n        self._ep_lon_dd = value\n","sub_path":"aviation_local_coordinates_tools.py","file_name":"aviation_local_coordinates_tools.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"557419987","text":"import pygame\r\nimport random\r\nimport sys\r\nfrom time import sleep\r\n\r\nBLACK = (0, 0, 0)\r\nRED = (255, 0, 0)\r\npad_width = 800\r\npad_height = 700\r\nfighter_width = 80\r\nfighter_height = 80\r\nenemy_width = 70\r\nenemy_height = 70\r\nbackground_height = 640\r\n\r\n\r\ndef back( x, y):\r\n    global gamepad, background\r\n    gamepad.blit(background, (x, y))\r\n\r\n\r\ndef draw_score(count):\r\n    global gamepad\r\n    font = pygame.font.SysFont(None, 20)\r\n    text = font.render('Score: ' + str(count * 100), True, (255, 255, 255))\r\n    gamepad.blit(text, (0, 0))\r\n\r\n\r\ndef draw_passed(count):\r\n    global gamepad\r\n    font = pygame.font.SysFont(None, 20)\r\n    text = font.render('Left Life: ' + str(3 - count), True, (255, 255, 255))\r\n    gamepad.blit(text, (720, 0))\r\n\r\n\r\ndef disp_message(text):\r\n    global gamepad\r\n    textfont = pygame.font.Font('freesansbold.ttf', 80)\r\n    text = textfont.render(text, True, (255, 255, 000))\r\n    textpos = text.get_rect()\r\n    textpos.center = (pad_width / 2, pad_height / 2)\r\n    gamepad.blit(text, textpos)\r\n    pygame.display.update()\r\n    sleep(2)\r\n    run_game()\r\n\r\n\r\ndef crash():\r\n    global gamepad\r\n    disp_message('Crashed!')\r\n\r\n\r\ndef gameover():\r\n    global gamepad\r\n    disp_message('Game Over')\r\n\r\n\r\ndef draw_object(obj, x, y):\r\n    global gamepad\r\n    gamepad.blit(obj, (x, y))\r\n\r\n\r\ndef run_game():\r\n    global gamepad, clock, fighter, enemy, bullet, background, boom\r\n\r\n    isShot = False\r\n    shotcount = 0\r\n    enemypassed = 0\r\n    boomcount = 0\r\n\r\n    bullet_xy = []\r\n\r\n    x = pad_width * 0.45\r\n    y = pad_height * 0.8\r\n    x_change = 0\r\n\r\n    enemy_x = random.randrange(0, pad_width - enemy_width)\r\n    enemy_y = 0\r\n    enemy_speed = 1\r\n\r\n    ongame = False\r\n    while not ongame:\r\n        for event in pygame.event.get():\r\n            if event.type == pygame.QUIT:\r\n                pygame.quit()\r\n                sys.exit()\r\n\r\n            if event.type == pygame.KEYDOWN:\r\n                if event.key == pygame.K_LEFT:\r\n                    x_change -= 15\r\n\r\n                elif event.key == pygame.K_RIGHT:\r\n                    x_change += 15\r\n\r\n                elif event.key == pygame.K_SPACE:\r\n                    if len(bullet_xy) < 20:\r\n                        bullet_x = x + fighter_width / 2\r\n                        bullet_y = y - fighter_height / 4\r\n                        bullet_xy.append([bullet_x, bullet_y])\r\n\r\n            if event.type == pygame.KEYUP:\r\n                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n                    x_change = 0\r\n\r\n        gamepad.fill(BLACK)\r\n        back(0,0)\r\n\r\n        x += x_change\r\n        if x < 0:\r\n            x = 0\r\n        elif x > pad_width - fighter_width:\r\n            x = pad_width - fighter_width\r\n\r\n        if y < enemy_y + enemy_height:\r\n            if (enemy_x > x and enemy_x < x + fighter_width) or \\\r\n                    (enemy_x + enemy_width > x and enemy_x + enemy_width < x + fighter_width):\r\n                crash()\r\n        draw_object(fighter, x, y)\r\n\r\n        if len(bullet_xy) != 0:\r\n            for i, bxy in enumerate(bullet_xy):\r\n                bxy[1] -= 10\r\n                bullet_xy[i][1] = bxy[1]\r\n\r\n                if bxy[1] < enemy_y:\r\n                    if bxy[0] > enemy_x and bxy[0] < enemy_x + enemy_width:\r\n                        bullet_xy.remove(bxy)\r\n                        isShot = True\r\n                        shotcount += 1\r\n                    if bxy[1] <= 0:\r\n                        try:\r\n                            bullet_xy.remove(bxy)\r\n                        except:\r\n                            pass\r\n\r\n        if len(bullet_xy) != 0:\r\n            for bx, by in bullet_xy:\r\n                draw_object(bullet, bx, by)\r\n\r\n        draw_score(shotcount)\r\n\r\n        enemy_y += enemy_speed\r\n\r\n        if enemy_y > pad_height:\r\n            enemy_y = 0\r\n            enemy_x = random.randrange(0, pad_width - enemy_width)\r\n            enemypassed += 1\r\n\r\n        if enemypassed == 3:\r\n            gameover()\r\n\r\n        draw_passed(enemypassed)\r\n\r\n        if isShot:\r\n            draw_object(boom, enemy_x, enemy_y)\r\n            boomcount += 1\r\n            if boomcount > 5:\r\n                enemy_x = random.randrange(0, pad_width - enemy_width)\r\n                enemy_y = 0\r\n                isShot = False\r\n                boomcount = 0\r\n                enemy_speed += 0.5\r\n                if enemy_speed >= 10:\r\n                    enemy_speed = 10\r\n        else:\r\n            draw_object(enemy, enemy_x, enemy_y)\r\n\r\n        pygame.display.update()\r\n        clock.tick(60)\r\n\r\n    pygame.quit()\r\n    quit()\r\n\r\n\r\ndef init_game():\r\n    global gamepad, clock, fighter, enemy, bullet, background, boom\r\n\r\n    pygame.init()\r\n    gamepad = pygame.display.set_mode((pad_width, pad_height))\r\n    pygame.display.set_caption('Fight Bug (spoqa)')\r\n    fighter = pygame.image.load('pyicon.png')\r\n    enemy = pygame.image.load('bug.png')\r\n    bullet = pygame.image.load('bullet.png')\r\n    background = pygame.image.load('pythonistas.png')\r\n    boom = pygame.image.load('boom.png')\r\n    clock = pygame.time.Clock()\r\n\r\n\r\ninit_game()\r\nrun_game()\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"375096701","text":"\"\"\"\nCopyright (c) 2012, Thomas Recouvreux\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\nimport threading\nimport subprocess\nimport time\n\nfrom ..mypyirc import bridgebot\nfrom ..mypyirc.botlauncher import BridgeBotLauncher\n\n\n\n\nclass StandartioBot(bridgebot.BridgeBot):\n\tdef __init__(self, *, server_ip, server_port, nickname, channel, exec_name, exec_params, protocol_file, protocol_prefixe):\n\t\tsuper().__init__(server_ip=server_ip, server_port=server_port,\n\t\t\tnickname=nickname, channel=channel,\n\t\t\tprotocol_file=protocol_file, protocol_prefixe=protocol_prefixe)\n\t\tself.exec_name = exec_name\n\t\tself.exec_params = exec_params\n\t\tself.process = None\n\t\tself.lock_connect = threading.Lock()\n\t\tself.connect_exec()\n\t\t\n\n\tdef connect_exec(self):\n\t\tdef f():\n\t\t\twhile True:\n\t\t\t\ttry:\n\t\t\t\t\t# kill de l'ancien process\n\t\t\t\t\tif self.process:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself.process.terminate()\n\t\t\t\t\t\t\ttime.sleep(1)\n\t\t\t\t\t\t\tif not self.process.poll():\n\t\t\t\t\t\t\t\tself.process.terminate()\n\t\t\t\t\t\texcept Exception:\n\t\t\t\t\t\t\tself.process = None\n\t\t\t\t\tprint(\"Subprocess : \",self.exec_name, self.exec_params)\n\t\t\t\t\tself.process = subprocess.Popen([self.exec_name]+self.exec_params, stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n\t\t\t\texcept Exception as ex:\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"connection ok\")\n\t\t\t\t\tself.sendall(\"connection ok\")\n\t\t\t\t\tbreak\n\t\tif self.lock_connect.acquire(False):\n\t\t\tt = threading.Thread(target=f)\n\t\t\tt.setDaemon(True)\n\t\t\tt.start()\n\t\t\tself.lock_connect.release()\n\t\t\t\n\t\n\tdef write(self, msg):\n\t\t\"\"\" #écrit sur l'input standart \"\"\"\n\t\tif msg:\n\t\t\tprint(\"%s\" % msg.strip())\n\t\t\tmsg = bytes(msg.strip()+\"\\n\",\"utf-8\")\n\t\t\ttry:\n\t\t\t\tself.process.stdin.write(msg)\n\t\t\t\tself.process.stdin.flush()\n\t\t\texcept IOError:\n\t\t\t\tself.connect_exec()\n\t\t\t\treturn 'IOError'\n\n\tdef read(self):\n\t\ttry:\n\t\t\tself.process.stdout.flush()\n\t\t\tm = str(self.process.stdout.readline(),\"utf-8\")\n\t\texcept IOError:\n\t\t\tself.connect_exec()\n\t\t\treturn 'IOError'\n\t\telse:\n\t\t\treturn m\n\n\tdef cmd__setexe(self, exe, args, *, id_msg=42, **kwargs):\n\t\t\"\"\"\n\t\tchanger l'executable\n\t\t@param exe nom de l'executable\n\t\t@param args la liste des arguments, séparés par une virgule\n\t\t\"\"\"\n\t\tself.exec_name = exe\n\t\tself.exec_args = args[1:-1].split(',')\n\t\tself.connect_exec()\n\n\n\nclass StandartioBotLauncher(BridgeBotLauncher):\n\tdef __init__(self, *, exec_name=\"./test.py\", exec_params=[], **kwargs):\n\t\tsuper().__init__(bot_class=StandartioBot, **kwargs)\n\t\tself.parser.add_option(\"-e\", \"--exec-name\",\n\t\t\t\t\t\t\taction=\"store\", dest=\"exec_name\", default=exec_name,\n\t\t\t\t\t\t\thelp=\"nom de l'executable\")\n\t\tself.parser.add_option(\"-p\", \"--exec-params\",\n\t\t\t\t\t\t\taction=\"callback\", callback=self.cb_params,\n\t\t\t\t\t\t\tdest=\"exec_params\", default=exec_params,\n\t\t\t\t\t\t\thelp=\"paramètres de l'executable séparés par ','\")\n\n\tdef cb_params(self, option, opt, value, parser):\n\t\treturn value.split(',')\n\n\n\t\nif __name__ == \"__main__\":\n\tlauncher = StandartioBotLauncher()\n\tlauncher.run()\n\t\n","sub_path":"pyircclient/clients/standartiobot.py","file_name":"standartiobot.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"187694674","text":"import os\nfrom utils import StringDistance, extract_digit\n\n\nclass GenderCorrection:\n    \"\"\"Correct Religion based on input by comparing Levenshtein distance to\n    tongiao.txt\n    \"\"\"\n\n    def __init__(self, cost_dict_path=None, gender_path = None):\n        dir_path = os.path.dirname(os.path.realpath(__file__))\n        if cost_dict_path is None:\n            cost_dict_path = os.path.join(dir_path, 'data', 'cost_char_dict.txt')\n        if gender_path is None:\n            gender_path = os.path.join(dir_path, 'data', 'gioitinh.txt')\n        self.string_distance = StringDistance(cost_dict_path=cost_dict_path)\n        self.genders = []\n        with open(gender_path, 'r', encoding='utf-8') as f:\n            for line in f:\n                entity = line.strip()\n                if not entity:\n                    break\n                entity = entity.split('\\n')\n                self.genders.extend(entity)\n        self.genders = tuple(set(self.genders))\n\n\n    def correct(self, phrase, correct_phrases, nb_candidates=2, distance_threshold=40):\n        candidates = [(None, distance_threshold)] * nb_candidates\n        max_diff_length = distance_threshold\n        for correct_phrase in correct_phrases:\n            if abs(len(phrase) - len(correct_phrase)) >= max_diff_length:\n                continue\n            if extract_digit(correct_phrase) != extract_digit(phrase):\n                distance = 100\n            else:\n                distance = self.string_distance.distance(phrase, correct_phrase)\n            if distance < candidates[-1][1]:\n                candidates[-1] = (correct_phrase, distance)\n                candidates.sort(key=lambda x: x[1])\n        return candidates\n\n    def gender_correction(self, gender):\n        if not isinstance(gender, str):\n            raise ValueError(\"Only Str Input\")\n        gender = gender.replace('.', ' ')\n        result = self.correct(gender, self.genders, nb_candidates=1, distance_threshold=20)\n        if len(result) != 0:\n            return result[0][0], result[0][1]\n        else:\n            return gender, -1\n\n\nif __name__ == '__main__':\n    a = GenderCorrection()\n    print(a.gender_correction(\"nú\"))\n","sub_path":"VN-gender-correction/gender_correction.py","file_name":"gender_correction.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"322290829","text":"#!/bin/env python2.7\r\n#coding:utf-8\r\n##### code  by  mik ####\r\n##### qiangchuan.wu ####\r\nfrom comm import SendToServer\r\n\r\n\r\n\r\n\r\n@SendToServer\r\ndef load(arg01,arg02):\r\n    LinuxLoad={}\r\n    f = open(\"/proc/loadavg\") \r\n    con = f.read().split() \r\n    f.close() \r\n    LinuxLoad['lavg_1']=con[0] \r\n    LinuxLoad['lavg_5']=con[1] \r\n    LinuxLoad['lavg_15']=con[2] \r\n    \r\n    return LinuxLoad\r\n    ","sub_path":"plugin/LinuxLoad.py","file_name":"LinuxLoad.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"203203643","text":"# TASK SIX: CLASSES AND OBJECTS\n# 1.\tWrite a program that calculates and prints the value according to the given formula:\n# Q= Square root of [(2*C*D)/H]\n# Following are the fixed values of C and H:\n# C is 50. H is 30.\n# D is the variable whose values should be input to your program in a comma-separated sequence.\nimport math\n\nx=input(\"Enter numbers separeted by comma: \" )\nlist1=[int(num) for num in x.split(\",\")]\nprint(list1)\nC,H=50,30\n\nresult=map(lambda D:math.sqrt((2*C*D)/H),list1)\nprint(list(result))\n\n\n\n# 2.Define a class named Shape and its subclass Square. \n# The Square class has an init function which takes a length as argument. \n# Both classes have an area function which can print the area of the shape \n# where Shape’s area is 0 by default.\nclass Shape:\n    def __init__(self,length=0):\n        self.length=length\n\n    def area(self):\n        return \"The Shape area\", self.length\n\nclass Square(Shape):\n    def __init__(self,length):\n        self.length=length\n\n    def area(self):\n        return \"The Square area\", self.length\n\nshape=Shape()\nsquare=Square(12)\nprint(shape.area())\nprint(square.area())\n\n\n# 3.Create a class to find the three elements that sum to zero from a set of n real numbers.\n# Input array: [-25,-10,-7,-3,2,4,8,10]\n# Output: [[-10,2,8],[-7,-3,10]]\n\n\n \n# 4. What is the output of the following code? Explain your answer as well.\n# class Test:\n#     def __init__(self):\n#         self.x = 0\n# class Derived_Test(Test):\n#     def __init__(self):\n#         self.y = 1\n# def main():\n#     b = Derived_Test()\n#     print(b.x,b.y)\n# main()\n\n####AttributeError: 'Derived_Test' object has no attribute 'x'\n\n# class A:\n#     def __init__(self, x= 1):\n#         self.x = x\n# class der(A):\n#     def __init__(self,y = 2):\n#         super().__init__()\n#         self.y = y\n# def main():\n#     obj = der()\n#     print(obj.x, obj.y)\n# main())\n\n\n###SyntaxError: invalid syntax\n \n# class A:\n#     def __init__(self,x):\n#         self.x = x\n#     def count(self,x):\n#         self.x = self.x+1\n# class B(A):\n#     def __init__(self, y=0):\n#         A.__init__(self, 3)\n#         self.y = y\n#     def count(self):\n#         self.y += 1     \n# def main():\n#     obj = B()\n#     obj.count()\n#     print(obj.x, obj.y)\n# main()\n \n ###Answer: 3 1\n \n# class A:\n#     def __init__(self):\n#         self.multiply(15)\n#         print(self.i)\n \n#     def multiply(self, i):\n#         self.i = 4 * i;\n# class B(A):\n#     def __init__(self):\n#         super().__init__()\n \n#     def multiply(self, i):\n#         self.i = 2 * i;\n# obj = B()\n \n### Answer extra semicolons \n\n# 5.Create a Time class and initialize it with hours and minutes.\n# Make a method addTime which should take two time object and add them. \n# E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)\n# Make a method displayTime which should print the time.\n# Make a method DisplayMinute which should display the total minutes in the Time. \n# E.g.- (1 hr 2 min) should display 62 minute.\nfrom datetime import datetime,timedelta\n\n\nclass Time():\n    def __init__(self,hour=\"0\"):\n        hour=datetime.now().strftime('%H:%M')\n        self.hour = hour\n\n    #(2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)\n    def addTime(self,time1=(0,0),time2=(0,0)):\n        self.time1=timedelta(hours=time1[0],minutes=time1[1])\n        self.time2=timedelta(hours=time2[0],minutes=time2[1])\n        return self.time1+self.time2\n\n    # Make a method displayTime which should print the time.\n    def displayTime(self):\n        print(datetime.now().strftime('%H:%M:%S'))\n    \n    # Make a method DisplayMinute which should display the total minutes in the Time. \n    # E.g.- (1 hr 2 min) should display 62 minute.\n    def DisplayMinute(self,hour,minute=0):\n        self.time=timedelta(hours=hour,minutes=minute)\n        return self.time.total_seconds()/60\n\nobj=Time()\n\n\nprint(obj.hour)\nobj.displayTime()\nprint(obj.addTime((2,50),(1,20)))\nprint(obj.DisplayMinute(1,2))\n\n\n\n# 6.Write a Person class with an instance variable, and a constructor that takes an integer, as a parameter.\n# The constructor must assign  to  after confirming the argument passed as  is not negative; \n# if a negative argument is passed as ,\n# the constructor should set  to  and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods:\n# yearPasses() should increase the  instance variable by .\n# amIOld() should perform the following conditional actions:\n# If , print You are young..\n# If  and , print You are a teenager..\n# Otherwise, print You are old..\n# Sample Input:\n# 4\n# -1\n# 10\n# 16\n# 18\n# Sample Output:\n# Age is not valid, setting age to 0.\n# You are young.\n# You are young.\n \n# You are young.\n# You are a teenager.\n \n# You are a teenager.\n# You are old.\n \n# You are old.\n# You are old.\n \n\nclass Person():\n    def __init__(self,age):\n        if age < 0:\n            print(\"Age is not valid, setting age to 0.\")\n            self.age=0\n        else:\n            self.age=age\n    \n    def yearPasses(self):\n        self.age=self.age+1\n        return self.age\n\n    def amIOld(self):\n        if self.age<14:\n            print(\"You are young!\")\n        elif 14 <= self.age <= 20:\n            print(\"You are teenager\")\n        else:\n            print(\"You are old!\")\n\nperson=Person(12)\nprint(person.yearPasses())\nperson.amIOld()\n\nperson1=Person(-12)\nprint(person1.yearPasses())\nperson1.amIOld()","sub_path":"assignment6.py","file_name":"assignment6.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"506179633","text":"###     Iterables and Iterators\n\niterString = iter(\"String of Characters\")\nprint(\"First char: \", next(iterString))\nprint(\"Next char: \", next(iterString))\n\n\n# Custom Iterators\nclass HexaDecimal:\n    def __init__(self):\n        self.values = \"0123456789ABCDEF\"\n        self.index = -1\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self.index >= len(self.values)-1:\n            raise StopIteration\n        self.index += 1\n        return self.values[self.index]\n\n\nhex1 = HexaDecimal()\nobj1 = iter(hex1)\n\nprint(next(obj1))\nprint(next(obj1))\n\nfor h in obj1:\n    print(h)\n\n\n# Custom Iterators with different Iterable and Iterator classes\nclass HexaDecimalData:\n    def __init__(self):\n        self.values = \"0123456789ABCDEF\"\n\n\nclass Hex:\n    def __init__(self, Hx):\n        self.HD = Hx\n        self.index = -1\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self.index >= len(self.HD.values)-1:\n            raise StopIteration\n        self.index += 1\n        return self.HD.values[self.index]\n\n\nhexD = HexaDecimalData()\nprint(hexD.values)\nh1 = Hex(hexD)\n\nprint(next(h1))\nprint(next(h1))\n\nfor h in h1:\n    print(h)\n\n\n\n###     Generators\n\n# List creates all the values at once\n# i = [x for x in range(int(10e+300))]\n# print(i[0])\n\n# Generators doesn't create whole list, instead generates one value for each call\n# Generator comprehensions\neven_numbers = (x * 2 for x in range(int(10e+300)))\nprint(next(even_numbers))\nprint(next(even_numbers))\n\n\n# syntax looks like a tuple but its a generator\n# use explicit typecast to tuple to make it a tuple\nt = (x for x in range(10))\nprint(type(t))\n# if its a generator, get next value using next()\nprint(t)\n\n\ndef cube_gen(num):\n    for n in range(1, num):\n        yield n**3\n\no = cube_gen(10)\nprint(next(o))\nprint(next(o))\n\n#o2 = cube_gen(10)\nfor value in o:\n    print(value)\n\n\n### Practice: Create an iterable Employees class returning empID on each next() call\n    \n    ","sub_path":"Day2/20_IterablesAndGenerators.py","file_name":"20_IterablesAndGenerators.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"411239057","text":"\"\"\"\nGloabal settings and constants.\n\"\"\"\nimport os\n\n# max 2mb\nIMG_MAX_UPLOAD_SIZE = 2e+6\n\n# tf-serving url\nTF_SERVING_URL = os.environ.get(\"TF_SERVING_URL\",\n                                \"http://172.17.0.5:8501\")\nTF_SERVING_MODEL_NAME = \"mystique\"\nENABLE_TF_SERVING = os.environ.get(\"ENABLE_TF_SERVING\",\n                                   False)\nTF_FROZEN_MODEL_PATH = os.path.join(os.path.dirname(__file__),\n                                    \"../model/frozen_inference_graph.pb\")\nTF_LABEL_PATH = os.path.join(os.path.dirname(__file__),\n                             \"training/object-detection.pbtxt\")\n\n# Pytorch model settings.\nPTH_MODEL_PATH = os.path.join(\n    os.path.dirname(__file__),\n    \"../model/pth_models/faster-rcnn-2020-05-31-1590943544-epochs_25.pth\")\n\nDETR_MODEL_PATH = os.path.join(\n    os.path.dirname(__file__),\n    \"../model/pth_models/detr_trace.pt\")\n\n\n# image hosting max size and default image url\nIMG_MAX_HOSTING_SIZE = 1000000\nDEFAULT_IMG_HOSTING = \"https://lh3.googleusercontent.com/-snm-WznsB3k/XrAWKVCBC3I/AAAAAAAAB8Y/tR-2f8CzboQCmyTzrAfj9Xtvnbeh9PJ8QCK8BGAsYHg/s0/2020-05-04.png\" # noqa\n\n\n# Class labels\nID_TO_LABEL = {\n    0: 'background',\n    1: \"textbox\",\n    2: \"radiobutton\",\n    3: \"checkbox\",\n    4: \"actionset\",\n    5: \"image\",\n    6: \"rating\"\n}\n\n# image detection swtiching paramater\n# On True [ uses custom image pipeline for image objects]\n# On False [ uses RCNN model image obejcts ]\n# Default is False\n# USE_CUSTOM_IMAGE_PIPELINE = False\n\n# RCNN model confidence score cutoff\nMODEL_CONFIDENCE = 80.0\n\n# Extra textbox padding - 5px\nTEXTBOX_PADDING = 5\n\nMODEL_REGISTRY = {\n    \"tf_faster_rcnn\": \"mystique.detect_objects.ObjectDetection\",\n    \"tfs_faster_rcnn\": \"mystique.detect_objects.TfsObjectDetection\",\n    # \"pth_faster_rcnn\": \"mystique.obj_detect.PtObjectDetection\",\n    \"pth_detr\": \"mystique.obj_detect.DetrOD\",\n    \"pth_detr_cpp\": \"mystique.obj_detect.DetrCppOD\"\n}\n\nACTIVE_MODEL_NAME = os.environ.get(\"ACTIVE_MODEL_NAME\", \"tf_faster_rcnn\")\n\n# Noise objects removal IOU threshold\nIOU_THRESHOLD = 0.5\n\n# Threshold values of w,h ratio of each image object labels\nIMAGE_SIZE_RATIOS = {\n        (10.23, 11.92): \"Small\",\n        (19.99, 15.0): \"Medium\",\n        (24.51, 16.33): \"Large\"\n}\n# Threshold values of mid point distance between 2 design objects column with\n# labels\nCOLUMN_WIDTH_DISTANCE = {\n        (1.0, 46.63): \"auto\",\n        (1.0, 80.40): \"stretch\"\n}\n# Threshold values of the mid point distance for the last column in the columns\n# and the input image's width, height for the column width labels\nLAST_COLUMN_THRESHOLD = {\n        (1.0, 3.68): \"stretch\",\n        (1.0, 22.40): \"auto\"\n}\n# COLUMNSET GROUPING THRESHOLDS\nCOLUMNSET_GROUPING = {\n        \"ymin_difference\": 10.0,\n        \"ymax-ymin_difference\": 3,\n        \"xmax-xmin_difference\": 100\n}\n","sub_path":"source/pic2card/mystique/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"403000899","text":"import itertools\n\nfrom django.db import models\nfrom django.db.models import Count\nfrom django.db.models.functions import Sqrt\nfrom django.utils.translation import gettext_lazy as _\nfrom model_utils.fields import AutoCreatedField\nfrom submissions.models import Submission\n\n\nclass RankRequest(models.Model):\n\n    conference = models.OneToOneField(\n        \"conferences.Conference\", on_delete=models.CASCADE, verbose_name=_(\"conference\")\n    )\n\n    created = AutoCreatedField(_(\"created\"))\n\n    def __str__(self):\n        return (\n            f\"{self.conference.name} <{self.conference.code}>, \"\n            f\"created on {self.created}\"\n        )\n\n    def save(self, *args, **kwargs):\n        super(RankRequest, self).save(*args, **kwargs)\n\n        ranked_submissions = self.build_ranking(self.conference)\n\n        self.save_rank_submissions(ranked_submissions)\n\n    def build_ranking(self, conference):\n        \"\"\"Builds the ranking\n\n        P. S. maybe we should make some *Strategy* in order to have all\n        available and run different strategies...\n\n        :return: list of dictionary ordered by score descending\n        [{\n            \"submission_id\": submission.id,\n            \"submission__topic_id\": submission.topic_id,\n            \"score\": score\n        },\n        ...\n        ]\n        \"\"\"\n\n        return RankRequest.users_most_voted_based(conference)\n        # return RankRequest.simple_sum(conference)\n\n    @staticmethod\n    def users_most_voted_based(conference):\n        \"\"\"Builds the ranking based on the votes each user has gived\n        This algorithm rewards users who have given more votes. If a user\n        votes many submissions, it means that he cares about his choices so\n        he must be rewarded by weighing his votes more.\n\n        P. S. maybe we should make some *Strategy* in order to have all\n        available and run different strategies...\n\n        \"\"\"\n\n        from voting.models import Vote\n\n        submissions = Submission.objects.filter(conference=conference)\n        votes = Vote.objects.filter(submission__conference=conference)\n\n        users_weight = RankRequest.get_users_weights(votes)\n\n        ranking = []\n        for submission in submissions:\n            submission_votes = votes.filter(submission=submission)\n\n            if submission_votes:\n                vote_info = {}\n                for vote in submission_votes:\n                    vote_info[vote.id] = {\n                        \"normalised_vote\": vote.value * users_weight[vote.user.id],\n                        \"scale_factor\": users_weight[vote.user.id],\n                    }\n                score = sum([v[\"normalised_vote\"] for v in vote_info.values()]) / sum(\n                    [v[\"scale_factor\"] for v in vote_info.values()]\n                )\n            else:\n                score = 0\n            rank = {\n                \"submission_id\": submission.id,\n                \"submission__topic_id\": submission.topic_id,\n                \"score\": score,\n            }\n            ranking.append(rank)\n        return sorted(ranking, key=lambda k: k[\"score\"], reverse=True)\n\n    @staticmethod\n    def get_users_weights(votes):\n        queryset = votes.values(\"user_id\").annotate(weight=Sqrt(Count(\"submission_id\")))\n        return {weight[\"user_id\"]: weight[\"weight\"] for weight in queryset}\n\n    def save_rank_submissions(self, scored_submissions):\n        \"\"\"Save the list of ranked submissions calculating the rank position\n        from the score\n        \"\"\"\n\n        ranked_obj = {}\n        for index, rank in enumerate(scored_submissions):\n            rank_submission = RankSubmission(\n                rank_request=self,\n                submission=Submission.objects.get(pk=rank[\"submission_id\"]),\n                absolute_rank=index + 1,\n                absolute_score=rank[\"score\"],\n            )\n            ranked_obj[rank[\"submission_id\"]] = rank_submission\n\n        # group by topic to generate the relative ranking\n        def group_by(item):\n            return item[\"submission__topic_id\"]\n\n        scored_submissions = sorted(scored_submissions, key=group_by)\n\n        for k, g in itertools.groupby(scored_submissions, group_by):\n            for index, rank in enumerate(list(g)):\n                ranked_obj[rank[\"submission_id\"]].topic_rank = index + 1\n                ranked_obj[rank[\"submission_id\"]].save()\n\n\nclass RankSubmission(models.Model):\n\n    rank_request = models.ForeignKey(\n        RankRequest,\n        on_delete=models.CASCADE,\n        verbose_name=_(\"rank request\"),\n        related_name=\"rank_submissions\",\n    )\n\n    submission = models.ForeignKey(\n        \"submissions.Submission\", on_delete=models.CASCADE, verbose_name=_(\"submission\")\n    )\n\n    absolute_rank = models.PositiveIntegerField(_(\"absolute rank\"))\n    absolute_score = models.DecimalField(\n        _(\"absolute score\"), decimal_places=6, max_digits=9\n    )\n    topic_rank = models.PositiveIntegerField(_(\"topic rank\"))\n\n    def __str__(self):\n        return (\n            f\"<{self.rank_request.conference.code}>\"\n            f\" | {self.submission.title}\"\n            f\" | {self.absolute_rank}\"\n        )\n","sub_path":"backend/voting/models/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"204449595","text":"from __future__ import print_function\n\nimport csv\nimport re\nimport argparse\nimport os\nfrom datetime import date\nfrom cStringIO import StringIO\nfrom operator import add\nimport datetimes\nfrom pyspark import SparkContext, SparkConf\n\npu_datetime_index = 1\ndo_datetime_index = 2\npu_location_id_index = 7\ndo_location_id_index = 8\n\nparser = argparse.ArgumentParser(description='Taxi net traffic.')\nparser.add_argument('--input_dir', type=str, default='public/taxis/',\n                    help='location of csv files in HDFS.')\nparser.add_argument('--start_month', type=int, default=7, help='start month.')\nparser.add_argument('--end_month', type=int, default=12, help='end month.')\nparser.add_argument('--save_path', type=str, default='./net_traffic.csv',\n                    help='directory in HDFS to save files to.')\nparser.add_argument('--loglevel', type=str, default='WARN',\n                    help='log verbosity.')\nargs = parser.parse_args()\n\n\ndef csv_row_read(x):\n    '''Turns a CSV string (x) into a list of columns.'''\n    return next(csv.reader([x]))\n\n\ndef to_csv(l):\n    '''Turns a tuple into a CSV row.\n    Args:\n        l: list/tuple to turn into a CSV\n    Returns:\n        (str) input encoded as CSV'''\n    f = StringIO()\n    writer = csv.writer(f)\n    writer.writerow(l)\n    return f.getvalue().strip()\n\n\nSATURDAY = 5\ndef process_pair(columns, time_index, loc_id_index):\n    '''Processes either input date/pickup, or output date/pickup'''\n    date_str = columns[time_index]\n    loc_str = columns[loc_id_index]\n    d = datetimes.matches_date(date_str)\n    if d is None:\n        return None\n    try:\n        loc = int(loc_str)\n    except:\n        return None\n    if loc < 1 or loc > 263:\n        return None\n    is_weekend = date(d['year'], d['month'], d['day']).weekday() >= SATURDAY\n    return (d['hour'], d['minute'], loc, is_weekend)\n\n\ndef process(string):\n    '''Args:\n        string: Raw input from the textFile(s)\n    Returns:\n        [None], or tuple of\n            (key: (location, is_weekend, in/out, hour, minute), count: 1)\n        If 'string' is invalid, returns [None].'''\n    columns = csv_row_read(string)\n    if len(columns) < 10:\n        return [None]\n    try:\n        pu_hour, pu_minute, pu_loc, pu_weekend = process_pair(\n                columns, pu_datetime_index, pu_location_id_index)\n        do_hour, do_minute, do_loc, do_weekend = process_pair(\n                columns, do_datetime_index, do_location_id_index)\n    except:\n        return [None]\n    pu_key = (pu_loc, pu_weekend, pu_hour, pu_minute)\n    do_key = (do_loc, do_weekend, do_hour, do_minute)\n    # Feed to a flatMap.\n    return [(pu_key, (1, 0)), (do_key, (0, 1))]\n\n\ndef tuple_add(x, y):\n    x0, x1 = x\n    y0, y1 = y\n    return (x0 + y0, x1 + y1)\n\n\ndef format_add_result(pair):\n    key, (pu_count, do_count) = pair\n    row = list(key)\n    row.append(pu_count)\n    row.append(do_count)\n    return to_csv(row)\n\nfilepaths = [\n    os.path.join(\n        args.input_dir, 'yellow_tripdata_2016-{:02d}.csv'.format(month))\n    for month in range(args.start_month, args.end_month + 1)\n]\n\ndef main():\n    conf = SparkConf().setAppName('net_traffic')\n    sc = SparkContext()\n    sc.setLogLevel(args.loglevel)\n    sc.addPyFile('datetimes.py')\n\n    print('-'*80 + '\\n' + 'net traffic counter' + '\\n' + '-'*80)\n    for filepath in filepaths:\n        print(filepath)\n\n    print('Save to:', args.save_path)\n\n    not_null = lambda x: x is not None\n    all_data = sc.union([sc.textFile(x) for x in filepaths])\n    counts = all_data.flatMap(process).filter(not_null).reduceByKey(tuple_add)\n    counts\\\n        .sortByKey()\\\n        .map(format_add_result)\\\n        .saveAsTextFile(args.save_path)\n\nif __name__ == '__main__':\n    main()\n\n","sub_path":"deliverable1/net_traffic.py","file_name":"net_traffic.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"227335691","text":"\"\"\"\nCompute a topological ordering of a given directed acyclic graph (DAG) with n vertices and m edges.\n\"\"\"\n\n\ndef topological_sort(g):\n    \"\"\"\n    Returns tuple for a directed graph where:\n     - First element is a boolean that is set to True if graph contains a cycle\n     - Second element is an array of vertices in topological order if graph has no cycles,\n       or None otherwise\n    \"\"\"\n    visited = set()\n    removed = set()\n    result = []\n\n    def __remove_if_sink(x):\n        edges = g.get_edges(x)\n        if not edges or set(map(lambda e: e.end, edges)).issubset(removed):\n            result.append(x)\n            removed.add(x)\n            return True\n        return False\n\n    def __topological_sort(x):\n        if x in visited:\n            return True\n        visited.add(x)\n\n        for edge in g.get_edges(x):\n            if edge.end in removed:\n                continue\n            if __topological_sort(edge.end):\n                return True\n\n        __remove_if_sink(x)\n        return False\n\n    for v in g.get_vertices():\n        if v not in visited and v not in removed:\n            if __topological_sort(v):\n                return (True, None)\n    return (False, result)\n","sub_path":"python/src/topological_sort.py","file_name":"topological_sort.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"456191003","text":"import argparse\ndef preprocessing(data):\n    import joblib\n    import numpy as np\n    import pandas as pd\n    from math import sin, cos, sqrt, atan2, radians\n    from sklearn.preprocessing import LabelEncoder, StandardScaler\n    from sklearn.model_selection import train_test_split\n\n\n    df = joblib.load(data)\n    \n        # convert price to numeric value\n    df[\"price\"] = df[\"price\"].apply(lambda x: x.replace(\"$\", \"\")) # Remove dollar sign\n    df[\"price\"] = df[\"price\"].apply(lambda x: x.replace(\",\", \"\")) # Remove thousand seperator\n    df[\"price\"] = df[\"price\"].astype(\"float\") # Cast the column into type float\n    lowerbound = df[\"price\"].mean() - 3 * df[\"price\"].std()\n    upperbound = df[\"price\"].mean() + 3 * df[\"price\"].std()\n    df1 = df[(df[\"price\"] > lowerbound) & (df[\"price\"] < upperbound)]\n    df = df1.copy()\n\n    # create list for selected features\n    selected = []\n\n        # fill out the missing values in columns \"host_is_superhost\" and \"host_identity_verified\"\n    df[\"host_is_superhost\"] = df[\"host_is_superhost\"].replace(np.NAN, \"f\")\n    df[\"host_identity_verified\"] = df[\"host_identity_verified\"].replace(np.NAN, \"f\")\n    # add the two columns to the 'selected' list\n    selected.append('host_is_superhost')\n    selected.append('host_identity_verified')\n\n\n        # Calcuate the distance bwteen the listing and mianat tractions in Berlin\n    # Formula to calculate distances\n    def distance(lat1, lat2, lon1, lon2):\n        R = 6373.0\n        rlat1 = radians(lat1)\n        rlat2 = radians(lat2)\n        rlon1 = radians(lon1)\n        rlon2 = radians(lon2)\n        rdlon = rlon2 - rlon1\n        rdlat = rlat2 - rlat1\n        a = sin(rdlat / 2)**2 + cos(rlat1) * cos(rlat2) * sin(rdlon / 2)**2\n        c = 2 * atan2(sqrt(a), sqrt(1 - a))\n        distance = R * c\n        return distance\n\n    # Top locations in Berlin\n    toploc = {\"hbf\": [52.525293, 13.369359], \n              \"txl\": [52.558794, 13.288437], \n              \"btor\": [52.516497, 13.377683], \n              \"museum\": [52.517693, 13.402141], \n              \"reichstag\": [52.518770, 13.376166]}\n    toploc = pd.DataFrame.from_dict(toploc)\n    toploc_trans = toploc.transpose()\n    toploc_trans.columns = [\"latitude\", \"longitude\"]\n\n    # Construct distance columns\n    dist = []\n    for col in toploc.columns:\n        df[\"dist_\"+col] = df.apply(lambda x: distance(x.latitude, toploc[col][0], x.longitude, toploc[col][1]), axis=1)\n        dist.append(\"dist_\"+col)\n        \n    for col in dist:\n        df[col+\"_close\"] = (df[col] < df[col].median())\n\n    df[\"good_distance\"] = df.apply(lambda x: any([x.dist_hbf_close, x.dist_txl_close, x.dist_museum_close, x.dist_reichstag_close]), axis=1)\n\n    selected.append(\"good_distance\")\n\n    selected.append('room_type')\n\n    # Amenities\n    df[\"amenities\"] = df[\"amenities\"].apply(lambda x: x[1:-1].replace(\"\\'\", \"\").split(\",\"))\n    df[\"with_hair_dryer\"] = df[\"amenities\"].apply(lambda x: '\"Hair dryer\"' in x)\n    df[\"lap_friendly\"] = df[\"amenities\"].apply(lambda x: '\"Laptop friendly workspace\"' in x)\n    df[\"with_hanger\"] = df[\"amenities\"].apply(lambda x: \"Hangers\" in x)\n    for i in [\"with_hair_dryer\", \"lap_friendly\", \"with_hanger\"]:\n        selected.append(i)\n\n    # minimum nights\n    df[\"min_nights_greater_than_two\"] = df[\"minimum_nights\"] > 2\n    selected.append(\"min_nights_greater_than_two\")\n\n        # Cleaning fee\n    # Remove dollar sign\n    df[\"cleaning_fee\"][-df[\"cleaning_fee\"].isna()] = df[\"cleaning_fee\"][-df[\"cleaning_fee\"].isna()].apply(lambda x: x.replace(\"$\", \"\").replace(\",\", \"\"))\n    df[\"cleaning_fee\"] = df[\"cleaning_fee\"].astype(\"float\")\n    df['cleaning_fee'].fillna(method=\"pad\", inplace=True)\n    selected.append('cleaning_fee')\n\n    selected.append(\"accommodates\")\n    selected.append('cancellation_policy')\n    selected.append(\"instant_bookable\")\n\n    # Convert string variables into categorical variables\n    df[\"host_is_superhost\"] = df[\"host_is_superhost\"]==\"t\"\n    df[\"host_identity_verified\"] = df[\"host_identity_verified\"]==\"t\"\n\n    for col in df[selected].select_dtypes(\"bool\").columns:\n        df[col] = df[col].astype(\"int\")\n    \n    data = df[selected]\n\n    # Encode the categorical varibles  \n    le = LabelEncoder()\n      \n    data['room_type']= le.fit_transform(data['room_type'])\n    data['cancellation_policy']= le.fit_transform(data['cancellation_policy'])\n    data['instant_bookable'] = np.where(data['instant_bookable'] == 't', 1, 0)\n\n    #  Standardisation\n    sc = StandardScaler()\n    scaledFeatures = sc.fit_transform(data)\n\n    # split to training and test set\n    X = scaledFeatures\n    y = df[\"price\"]\n    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n    data_dic = {\"X_train\": X_train,\"X_test\": X_test, \"Y_train\": y_train, \"Y_test\": y_test}\n    \n    joblib.dump(data_dic, 'clean_data')\n    \nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--data')\n    args = parser.parse_args()\n    preprocessing(args.data)\n","sub_path":"Berlin Airbnb/pipeline components/preprocess/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"367282339","text":"'''\nThis script will read in NEW pandas datframe info,\nMake a prediction on it (probability that it is fraud),\nand then return a dataframe with that prediction on it.\n'''\n\nimport pandas as pd \nimport numpy as np \nimport pickle \n\nfrom src.clean_new_data import clean_new_data\n\n# from pymongo import MongoClient\n# client = MongoClient('localhost', 27017)\n# db = client['fraud']\n# table = db['events']\n\n\n# def load_clean_into_pandas(request_info):\n#     '''\n#     inputs\n#     ------\n#     request_info: json formatted info that will be formatted into \n#     '''\n#     df = clean_new_data(df)\n\n#     return df\n\n\ndef predict(request_info):\n    '''\n    inputs\n    ------\n    request_info: pandas dataframe \n    '''\n\n    # load request_info into a pandas dataframe and clean it using clean_new_data\n    # df = pd.read_json(request_info)\n    df_cleaned = clean_new_data(request_info)\n\n    # set x_test to the cleaned dataframe\n    X_test = np.array(df_cleaned)\n\n    # load saved pickled model\n    with open('models/grad_boost_model.p', 'rb') as mod:\n        model = pickle.load(mod)\n\n    # calcluate the fraud probability of the input data using the model's predict_proba method\n    # try the predict_proba. if it cannot be calculated, set it equal to 0.\n    try:\n        probs = model.predict_proba(X_test.reshape(1,-1))[:, 1]\n    except:\n        probs = [1,1]\n\n    # add the probs to the original dataframe\n    request_info['fraud_probability'] = np.around(probs[0], 3)\n    #print(request_info['fraud_probability'])\n\n    # return the dataframe with the predictions\n    return request_info\n    ","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"76414966","text":"#!/bin/python\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the minimumAbsoluteDifference function below.\ndef minimumAbsoluteDifference(arr):\n    m = 999999999\n    arr = sorted(arr)\n    for i in range(len(arr)-1):\n            s = abs(arr[i] - arr[i+1])\n            if s < m:\n                m = s\n            \n    return m\nif __name__ == '__main__':\n    # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n    n = int(input())\n\n    arr = list(map(int, input().rstrip().split()))\n\n    result = minimumAbsoluteDifference(arr)\n    print(result)\n    # fptr.write(str(result) + '\\n')\n\n    # fptr.close()","sub_path":"Greedy Algorithms/Minimum_Absolute_Difference_in_an_Array.py","file_name":"Minimum_Absolute_Difference_in_an_Array.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"400315746","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse \nfrom .models import *\nfrom .forms import *\nfrom django.db.models import Avg\n\ndef home(request):\n    query = request.GET.get(\"name\")\n    allBuinesses = None\n    if query:\n        allBusinesses = Business.objects.filter(name__icontains=query)\n    else:\n\n        allBusinesses = Business.objects.all() \n\n    context = {\n        \"businesses\": allBusinesses, \n    }\n    \n    return render(request,'main/index.html', context)\n    \n    \n#details page\ndef detail(request, id):\n    business = Business.objects.get(id=id) \n    reviews = Review.objects.filter(business=id)\n    average = reviews.aggregate(Avg(\"rating\"))[\"rating__avg\"]\n    if average == None:\n        average = 0\n    average = round(average, 2)\n    context = {\n        \"business\": business,\n        \"reviews\":reviews,\n        \"average\":average\n    }\n    return render(request, 'main/details.html', context)\n\n\ndef add_business(request):\n    if request.user.is_authenticated:\n        if request.method == \"POST\":\n            form = BusinessForm(request.POST or None)\n            if form.is_valid():\n                data = form.save(commit=False)\n                data.save()\n                return redirect(\"main:home\")\n        else:\n            form = BusinessForm()\n        return render(request, 'main/addbusiness.html', {\"form\": form, \"controller\": \"Add a business\"})\n    else:\n        return redirect(\"main:home\")\n\n\ndef edit_business(request, id):\n    if request.user.is_authenticated:\n        busines = Business.objects.get(id=id)\n    \n        if request.method == \"POST\":\n            form = BusinessForm(request.POST or None, instance=busines)\n        \n            if form.is_valid():\n                data = form.save(commit=False)\n                data.save()\n                return redirect(\"main:detail\", id)\n        else:\n            form = BusinessForm(instance=busines)\n        return render(request, 'main/addbusiness.html', {\"form\": form, \"controller\": \"Edit Business\"})\n    else:\n          return redirect(\"main:home\")\n\n\ndef delete_business(request, id):\n    if request.user.is_authenticated:\n        if request.user.is_superuser:\n            business = Business.objects.get(id=id)\n            business.delete()\n            return redirect('main:home')\n        else:\n            return redirect(\"main:home\")\n    return redirect(\"accounts:login\")\n\n\ndef add_review(request, id):\n    if request.user.is_authenticated:\n        business = Business.objects.get(id=id)\n        if request.method == \"POST\":\n            form = ReviewForm(request.POST or None)\n            if form.is_valid():\n                data = form.save(commit=False)\n                data.comment = request.POST[\"comment\"]\n                data.rating = request.POST[\"rating\"]\n                data.user = request.user\n                data.business = business\n                data.save()\n                return redirect(\"main:detail\", id)\n        else:\n            form = ReviewForm()\n        return render(request, 'main/detail.html', {\"form\": form})\n    else:\n        return redirect(\"accounts:login\")\n\n\ndef edit_review(request, business_id, review_id):\n    if request.user.is_authenticated:\n        business = Business.objects.get(id=business_id)\n        review = Review.objects.get(business=business, id=review_id)\n        if request.user == review.user:\n            if request.method ==\"POST\":\n                form = ReviewForm(request.POST, instance=review)\n                if form.is_valid():\n                    data = form.save(commit=False)\n                    if (data.rating > 10) or (data.rating < 0 ):\n                        error = \"out of range, please leave a rating between 0 and 10\"\n                        return render(request, 'main/editreview.html', {\"error\": error, \"form\":form})\n                    else:\n                        data.save()\n                        return redirect(\"main:detail\", business_id)\n            else:\n                form = ReviewForm(instance=review)\n            return render(request, 'main/editreview.html', {\"form\" : form})\n        else:\n            return redirect(\"main:detail\", business_id)\n    else:\n        return redirect(\"accounts:login\")\n\ndef delete_review(request, business_id, review_id):\n    if request.user.is_authenticated:\n        business = Business.objects.get(id=business_id)\n        review = Review.objects.get(business=business, id=review_id)\n        if request.user == review.user:\n            review.delete()\n            return redirect(\"main:detail\", business_id)\n    else:\n        return redirect(\"accounts:login\")\n\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"304716768","text":"# make a function to ask for input values\n\ndef main():\n    payment_period = int(input(\"Please specify the number of years you want to take the mortgage for: \"))*12\n    annual_interest_rate = float(input(\"What is the interest rate charged? \"))\n    loan_amount = float(input(\"What is the loan amount? \"))\n    amortization_func(loan_amount, payment_period, annual_interest_rate)\n\n# fucntion to calculate monthly installment\ndef pmt_func(loan_amount,payment_period,annual_interest_rate):\n    monthly_interest = annual_interest_rate/(100*12)\n    r = 1 + monthly_interest\n    monthly_payment_numerator = loan_amount * (monthly_interest *(r ** payment_period))\n    monthly_payment_denominator = (r ** payment_period)-1\n    monthly_payment = monthly_payment_numerator/monthly_payment_denominator\n    return monthly_payment, monthly_interest\n\n# make an amortization table\ndef amortization_func(loan_amount,payment_period,annual_interest_rate):\n    ''' calculates the amortization table and displays it to the user in a tabular form if asked by the user'''\n    monthly_payment, monthly_interest = pmt_func(loan_amount,payment_period,annual_interest_rate)\n    principal = loan_amount\n    width = 11\n    print(\"Pay_number | int_payment | pr_payment | pr_outstanding | principal\")\n    for i in range(payment_period):\n        interest_payment = principal * monthly_interest\n        principal_payment = monthly_payment - interest_payment\n        principal_outstanding = principal - principal_payment\n        principal = principal_outstanding\n        interest_payment_str = f'{interest_payment:.2f}'\n        principal_payment_str = f'{principal_payment:.2f}'\n        principal_outstanding_str = f'{principal_outstanding:.2f}'\n        principal_str = f'{principal:.2f}'\n        print(str(i+1).rjust(width)+ '|'+ interest_payment_str.rjust(width + 2) + '|'+ principal_payment_str.rjust(width+1)+ '|'+\n            principal_outstanding_str.rjust(width+5)+ '|'+principal_str.center(width))\n\n\nif __name__ == \"__main__\":\n    main()\n\n\n","sub_path":"amortization_calculator.py","file_name":"amortization_calculator.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"476800690","text":"import psycopg2\nimport traceback\nimport unittest\nimport uuid\n\nfrom monsquel import Monsquel\n\n\ndef createDatabase():\n    db = psycopg2.connect(database='postgres')\n    db.set_session(autocommit=True)\n    cur = db.cursor()\n    try:\n        cur.execute('DROP DATABASE unittest')\n    except:\n        pass\n    finally:\n        db.commit()\n    cur.execute('CREATE DATABASE unittest')\n    db.close()\n    db = psycopg2.connect(database='unittest')\n    cur = db.cursor()\n    cur.execute('CREATE EXTENSION cube')\n    cur.execute('CREATE EXTENSION earthdistance')\n    db.commit()\n\nglobal_init = False\n\n\nclass TestBase:\n\n    class Base(unittest.TestCase):\n\n        def setUp(self):\n            global global_init\n            if not global_init:\n                createDatabase()\n                global_init = True\n\n\nclass TestFindByID(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        doc = {'test': 'ok'}\n        doc_with_id = db.test.insert_one({'test': 'ok'})\n        self.assertTrue(isinstance(doc_with_id['_id'], uuid.UUID))\n        _id = doc_with_id.pop('_id')\n        self.assertEqual(doc, doc_with_id)\n        doc['_id'] = _id\n        new_doc = db.test.find({'_id': _id})\n        self.assertEqual(doc, new_doc)\n        db.drop()\n\n\nclass TestFind(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('name')\n        db.test.create_index('email')\n        name1 = db.test.insert_one({'name': 'name1', 'email': 'email1'})\n        name2 = db.test.insert_one({'name': 'name2', 'email': 'email2'})\n        docs = db.test.find({'name': 'name1'})\n        self.assertTrue(len(docs) == 1)\n        self.assertEqual(docs[0], name1)\n        docs = db.test.find({'name': 'name1', 'email': 'email1'})\n        self.assertTrue(len(docs) == 1)\n        self.assertEqual(docs[0], name1)\n        docs = db.test.find({'name': 'name1', 'email': 'email2'})\n        self.assertTrue(len(docs) == 0)\n        db.drop()\n\n\nclass TestFindOr(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('name')\n        db.test.create_index('email')\n        name1 = db.test.insert_one({'name': 'name1', 'email': 'email1'})\n        name2 = db.test.insert_one({'name': 'name2', 'email': 'email2'})\n        name3 = db.test.insert_one({'name': 'name3', 'email': 'email3'})\n        docs = db.test.find({'$or': [{'name': 'name1'}, {'name': 'name2'}]})\n        self.assertTrue(len(docs) == 2)\n        self.assertEqual([name1, name2], docs)\n        docs = db.test.find({'$or': [{'name': 'name1', 'email': 'email1'},\n                                     {'name': 'name2'}]})\n        self.assertTrue(len(docs) == 2)\n        self.assertEqual([name1, name2], docs)\n        db.drop()\n\n\nclass TestFindLike(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('title', fulltext=True)\n        doc1 = db.test.insert_one({'title': 'SomE lOng teXt'})\n        doc2 = db.test.insert_one({'title': 'other text'})\n        docs = db.test.find({'$like': {'title': '%long%'}})\n        self.assertTrue(len(docs) == 1)\n        self.assertEqual(docs[0], doc1)\n        db.drop()\n\n\nclass TestTransactions(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('name')\n        db.test.create_index('email')\n        db.begin()\n        name1 = db.test.insert_one({'name': 'name1', 'email': 'email1'})\n        name2 = db.test.insert_one({'name': 'name2', 'email': 'email2'})\n        db.rollback()\n        no_docs = db.test.find({'name': 'name1'})\n        self.assertTrue(len(no_docs) == 0)\n        no_doc = db.test.find(name1)\n        self.assertTrue(no_doc == None)\n        db.drop()\n\n\nclass TestConfigSave(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('name')\n        name1 = db.test.insert_one({'name': 'name1', 'email': 'email1'})\n        name2 = db.test.insert_one({'name': 'name2', 'email': 'email2'})\n        db = Monsquel(database='unittest')\n        doc = db.test.find(name1)\n        self.assertEqual(doc, name1)\n        db.drop()\n\n\nclass TestUpdate(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('name')\n        name1 = db.test.insert_one({'name': 'name1', 'email': 'email3'})\n        name1['email'] = 'email1'\n        db.test.insert_one(name1)\n        db = Monsquel(database='unittest')\n        doc = db.test.find(name1)\n        self.assertEqual(doc, name1)\n        db.drop()\n\n\nclass TestGeo(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('geo', geo=True)\n        db.test.create_index('name')\n        name1 = db.test.insert_one(\n            {'name': 'name1', 'geo': {'coordinates': [0, 50]}})\n        db.test.insert_one(name1)\n        docs = db.test.find({'name': 'name1', 'geo':\n                            {'$nearSphere':\n                             {'$geometry': {'coordinates': [22, 40]},\n                              '$maxDistance': 2000 * 1000}}})\n        self.assertTrue(len(docs) == 1)\n        self.assertEqual(name1, docs[0])\n        no_docs = db.test.find({'name': 'name1', 'geo':\n                                {'$nearSphere':\n                                 {'$geometry': {'coordinates': [22, 40]},\n                                  '$maxDistance': 1800 * 1000}}})\n        self.assertTrue(len(no_docs) == 0)\n        db.drop()\n\nclass TestArrays(TestBase.Base):\n\n    def runTest(self):\n        db = Monsquel(database='unittest')\n        db.test.create_index('arr', arr=True)\n        arr1 = db.test.insert_one({'arr': ['a', 'b', 'c']})\n        doc = db.test.find({'arr': ['a']})\n        self.assertTrue(len(doc) == 1)\n        self.assertEqual(arr1, doc[0])\n\nif __name__ == '__main__':\n    x = TestArrays()\n    x.setUp()\n    x.runTest()\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"138452256","text":"\"\"\"\nIn the United Kingdom the currency is made up of pound (£) and pence (p). There are eight coins in general circulation:\n\n1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).\nIt is possible to make £2 in the following way:\n\n1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p\nHow many different ways can £2 be made using any number of coins?\n\n1x200\n2x100\n4x50\n2x50 + 1x100\n8x20\n4x20 + 2x50\n4x20 + 1x100\n20x10\n10x10 + 5x20\n10x10 + 2x50\n10x10 + 1x100\n15x10 + 1x50\n\n5+2+1:\n40 (1)\n39 (2)\n38 +5+0\n38+0+10\n38+1+8\n38+2+\n\n\n\n2 + 1:\n100 posibilidades\n\n1:\n200 posibilidades\n\"\"\"\n\ndef get_coins(values, target):\n    if len(values) == 0:\n        return 0\n    if len(values) == 1:\n        coin = values[0]\n        n = int(target/coin)\n        print(f'{n} monedas de {values[0]} ({coin*n} pounds)')\n        return n\n    suma = 0\n    # Valor mas alto de moneda\n    coin = values[len(values)-1]\n    # Division entera\n    i = int(target/coin)\n    for n in range(i,0,-1):\n        suma += 1\n        n_monedas = target/(n*coin)\n        resto = target - n_monedas*coin\n        print(f'{n} monedas de {coin} ({coin*n} pounds)')\n        if resto != 0:\n            # Llama con una moneda menos para el resto\n            suma += get_coins(values[0:len(values)-2], resto)\n        else:\n            print(f'Sin resto')\n    \n    \n\n\n    return suma\n\n\n\n    \n\nvalues = [1,2,5,10,20,50,100,200]\ntarget = 200\n\nprint(get_coins(values[0:2],target))\n\n\"\"\"\npossibilities = 0\nfor i in range(0,2):\n    print(f'i: {i}')\n    for j in range(0,i+1):\n        print(f'j: {j}')\n        coin = values[i]\n        resto = 200\n        print(f'Coin: {coin}, resto: {resto}')\n        while resto != 0:\n            resto -= coin\n            possibilities += 1\n\nprint(possibilities)\n\"\"\"","sub_path":"Problem_031/problem_31.py","file_name":"problem_31.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"430395911","text":"from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.legacy.nn as nn2\nfrom torch.autograd import Variable\n\n\ndef weights_init(m):\n    classname = m.__class__.__name__\n    if classname.find('Conv') != -1:\n        m.weight.data.normal_(0.0, 0.02)\n        m.bias.data.fill_(0)\n    elif classname.find('BatchNorm') != -1:\n        m.weight.data.normal_(1.0, 0.02)\n        m.bias.data.fill_(0)\n\n# For input size input_nc x 256 x 256\nclass G(nn.Module):\n    def __init__(self, input_nc, output_nc, ngf):\n        super(G, self).__init__()\n        self.conv1 = nn2.SpatialDilatedConvolution(input_nc, ngf, 5, 5,        1 , 1, 2 , 2, 1, 1)\n        self.conv2 = nn2.SpatialDilatedConvolution(ngf, ngf*2, 5, 5,        1 , 1, 4 , 4  , 2, 2)\n        self.conv3 = nn2.SpatialDilatedConvolution(ngf*2, ngf*4, 5, 5,        1 , 1, 6 , 6, 3, 3)\n        self.conv4 = nn2.SpatialDilatedConvolution(ngf*4, 3, 5, 5,        1 , 1, 6 , 6, 3, 3)\n\n        \n        self.batch_norm = nn.BatchNorm2d(ngf)\n        self.batch_norm2 = nn.BatchNorm2d(ngf * 2)\n        self.batch_norm4 = nn.BatchNorm2d(ngf * 4)\n        self.batch_norm8 = nn.BatchNorm2d(ngf * 8)\n\n        self.leaky_relu = nn.LeakyReLU(0.2, True)\n        self.relu = nn.ReLU(True)\n\n        self.dropout = nn.Dropout(0.5)\n\n        self.tanh = nn.Tanh()\n\n    def forward(self, input):\n        # Encoder\n        # Convolution layers:\n        # input is (nc) x 256 x 256\n        '''\n        e1 = self.conv1.updateOutput(input.data.cpu())\n        e1=Variable(e1.cuda())\n        #print (e1.size())\n\n        v1=   self.leaky_relu(e1)\n        a1=self.conv2.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e2 = self.batch_norm2(   Variable(a1.cuda()) )\n\n        #e2=Variable(e2.cuda())\n        #print (e2.size())\n\n        \n        v1=   self.leaky_relu(e2)\n        a1=self.conv3.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e3 = self.batch_norm4(   Variable(a1.cuda()) )\n\n        #e2=Variable(e2.cuda())\n        #print (e3.size())\n        v1=   self.leaky_relu(e3)\n        a1=self.conv4.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e4 =  Variable(a1.cuda()) \n        #print (e3.size())\n\n        \n        \n\n        # state size is (ngf x 2) x 64 x 64\n        # state size is (ngf x 4) x 32 x 32\n        #print (e8)\n\n        output = self.tanh(e4)\n        #print (output.size())\n        return output\n        '''\n        e1 = self.conv1.updateOutput(input.data.cpu())\n        e1=Variable(e1)\n        #print (e1.size())\n\n        v1=   self.leaky_relu(e1)\n        a1=self.conv2.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e2 = self.batch_norm2(   Variable(a1  ) )\n\n        #e2=Variable(e2.cuda())\n        #print (e2.size())\n\n        \n        v1=   self.leaky_relu(e2)\n        a1=self.conv3.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e3 = self.batch_norm4(   Variable(a1) )\n\n        #e2=Variable(e2.cuda())\n        #print (e3.size())\n        v1=   self.leaky_relu(e3)\n        a1=self.conv4.updateOutput(  v1.data.cpu())\n        # state size is (ngf) x 128 x 128\n        e4 =  Variable(a1) \n        #print (e3.size())\n\n        \n        \n\n        # state size is (ngf x 2) x 64 x 64\n        # state size is (ngf x 4) x 32 x 32\n        #print (e8)\n\n        output = self.tanh(e4)\n        #print (output.size())\n        return output\n        \n\nclass D(nn.Module):\n    def __init__(self, input_nc, output_nc, ndf):\n        super(D, self).__init__()\n        self.conv1 = nn.Conv2d(input_nc + output_nc, ndf, 4, 2, 1)\n        self.conv2 = nn.Conv2d(ndf, ndf * 2, 4, 2, 1)\n        self.conv3 = nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1)\n        self.conv4 = nn.Conv2d(ndf * 4, ndf * 8, 4, 1, 1)\n        self.conv5 = nn.Conv2d(ndf * 8, 1, 4, 1, 1)\n\n        self.batch_norm2 = nn.BatchNorm2d(ndf * 2)\n        self.batch_norm4 = nn.BatchNorm2d(ndf * 4)\n        self.batch_norm8 = nn.BatchNorm2d(ndf * 8)\n\n        self.leaky_relu = nn.LeakyReLU(0.2, True)\n\n        self.sigmoid = nn.Sigmoid()\n\n    def forward(self, input):\n        # input is (nc x 2) x 256 x 256\n        h1 = self.conv1(input)\n        # state size is (ndf) x 128 x 128\n        h2 = self.batch_norm2(self.conv2(self.leaky_relu(h1)))\n        # state size is (ndf x 2) x 64 x 64\n        h3 = self.batch_norm4(self.conv3(self.leaky_relu(h2)))\n        # state size is (ndf x 4) x 32 x 32\n        h4 = self.batch_norm8(self.conv4(self.leaky_relu(h3)))\n        # state size is (ndf x 8) x 31 x 31\n        h5 = self.conv5(self.leaky_relu(h4))\n        # state size is (ndf) x 30 x 30, corresponds to 70 x 70 receptive\n        output = self.sigmoid(h5)\n        return output\n","sub_path":"Extras/models (3rd copy).py","file_name":"models (3rd copy).py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"2159596","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom _schon import ContinuousSIS\nimport horgg\nimport argparse\nimport json\nimport pickle\n\nparser = argparse.ArgumentParser(description='Solution using simulations')\nparser.add_argument('file',  type=str, help='Configuration file')\nargs = parser.parse_args()\n\n#import parameters\n#=================\nconfig_file = args.file\n\nwith open(config_file, 'r') as file:\n    config = json.load(file)\n\n#=======\n#unpack\n#=======\n#structure\nnmax = config['nmax']\nmmax = config['mmax']\nmmin = config['mmin']\nqm = np.array(config['qm'])\npn = np.array(config['pn'])\n\n#rate\npy_n = np.array(config['py_n'])\nymax = config['ymax']\nrate = np.array(config['rate'])\nmean_rate = config['mean_rate']\n\n#contagion\ninitial_infected_fraction = config['initial_density']\n# initial_infected_fraction = 0.0001\n\n#===============\n#random network\n#===============\n\n#generate sequences\n# np.random.seed(42) #optional, if nothing is given, it is seeded with time\nN = 200000 #number of groups\nn_list = horgg.utility.sequence_1(N, pn)\nm_list = horgg.utility.sequence_2(n_list, qm)\n\ngraph_generator = horgg.BCMS(m_list,n_list)\n# horgg.BCMS.seed(42) #optional, if nothing is given, it is seeded with time\n\n#mcmc steps are additional edge swaps to ensure uniformity, I recommend O(N)\nedge_list = graph_generator.get_random_graph(nb_steps=N)\n\n#===================\n#group transmission\n#===================\npdf = py_n[:,nmax]\ncum = np.cumsum(pdf)\ngroup_transmission_rate = []\nfor _ in range(N):\n    r = np.random.random()\n    ind = np.searchsorted(cum,r)\n    group_transmission_rate.append(rate[ind])\nprint(np.mean(group_transmission_rate))\n\n#infection parameter\nrecovery_rate = 1.\ninfection_rate = np.zeros((nmax+1,nmax+1))\nfor n in range(2,nmax+1):\n    for i in range(nmax+1):\n        infection_rate[n][i] = i\n\nsample_size = 10\nIlist = []\ni = 0\nwhile i < sample_size:\n    cont = ContinuousSIS(edge_list,recovery_rate,infection_rate,\n                            group_transmission_rate)\n    cont.measure_prevalence()\n\n    cont.infect_fraction(initial_infected_fraction)\n\n    #evolve and measure\n    dt = 100\n    dec_dt = 1\n    cont.evolve(dt,dec_dt,measure=True,quasistationary=False)\n\n    #print the result measure\n    for measure in cont.get_measure_vector():\n        name = measure.get_name()\n        if name == \"prevalence\":\n            I = [initial_infected_fraction] + list(measure.get_result())\n\n    if I[-1] > 0:\n        print(f\"sample {i+1}, final prevalence {I[-1]}\")\n        Ilist.append(I)\n        i += 1\n\nt = np.arange(0,dt,dec_dt)\n\nImean = np.mean(Ilist,axis=0)\nIstd = np.std(Ilist,axis=0)\n\nprint(len(t))\nprint(len(Imean))\n\nplt.errorbar(t,Imean,yerr=Istd/np.sqrt(sample_size))\nplt.yscale('log')\nplt.show()\n\n#save data\ndata = dict()\ndata['t'] = t\ndata['Ilist'] = Ilist\n\n# with open(config['sim_file'], 'wb') as file:\n    # pickle.dump(data,file)\n\n","sub_path":"time-evo-SIS/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"446937044","text":"import os\nimport time\nimport xml.etree.ElementTree as et\n\nfrom bs4 import BeautifulSoup as bs\nfrom colorama import init, Back, Fore\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Alignment\nfrom xml.etree.ElementTree import Element, ElementTree\n\nTO_CHOP_OFF = [' ', '\\n', '\\t', '\\r', '\\xa0']\nTO_DELETE = ['\\t', '\\r']\n\ndef normalize_text(text_to_normalize):\n    normalized_text = str(text_to_normalize)\n    \n    for symbol in TO_DELETE:\n        if str(symbol) in normalized_text:\n            normalized_text = normalized_text.replace(symbol, '')\n\n    while normalized_text:\n        if any(s == normalized_text[0] for s in TO_CHOP_OFF):\n            normalized_text = normalized_text[1:]\n        elif any(s == normalized_text[-1] for s in TO_CHOP_OFF):\n            normalized_text = normalized_text[:-1]\n        else:\n            break\n\n    return str(normalized_text)\n\ndef print_xml(element):\n    text = et.tostring(element, encoding = 'unicode')\n    text = remove_version_str(text)\n    text = bs(text, 'lxml')\n    text = text.prettify()\n    text = text.replace('', '')\n    text = text.replace('', '')\n    text = text.replace('', '')\n    text = text.replace('', '')\n    text = normalize_text(text)\n    while ':name' in text:\n        text = text.replace(':name', ':Name')\n    while ':code' in text:\n        text = text.replace(':code', ':Code')\n    while ':description' in text:\n        text = text.replace(':description', ':Description')\n    return text\n\ndef sortCode(et):\n    try:\n        tag = et.tag\n        tag = tag.split('}')[-1]\n        if tag.lower() == 'code':\n            tag = 'z' + tag\n        urn = et.get('urn')\n        value = et.get('value')\n        key = tag + '.' + value + '.' + str(urn)\n        return key\n    except:\n        urn = ''\n        value = ''\n        key = tag + '.' + value + '.' + str(urn)\n        return key\n\ndef openxml(filename):\n\n    with open(filename, 'r', errors = 'ignore') as f:\n        file = f.read()\n\n    register_namespaces(file)\n\n    root = et.parse(filename).getroot()\n    return root\n\ndef register_namespaces(file):\n    start = file.find('Structure') + 10\n    end = file[start:].find('>') + start\n    structure = file[start:end]\n    \n    namespaces = {}\n    start = structure.find('\"') + 1\n\n    while start != 0:\n        end = structure[start:].find('\"') + start\n\n        namespace_start = structure[:start].rfind(':') + 1\n        namespace_end = structure[namespace_start:].find('=') + namespace_start\n\n        namespace = structure[namespace_start:namespace_end]\n        uri = structure[start:end]\n        namespaces[namespace] = uri\n        \n        structure = structure[end+1:]        \n        start = structure.find('\"') + 1\n\n    del namespaces['schemaLocation']\n    for ns in namespaces:\n        et.register_namespace(ns, namespaces[ns])\n\ndef remove_version_str(urn):\n    try:\n        start = urn.rfind('(')\n        end = urn.rfind(')') + 1\n\n        _ = float(urn[start + 1:end - 1])\n\n        if start == -1 or end == -1:\n            return urn\n        else:\n            return urn[:start] + '(1.0)' + urn[end:]\n    except Exception:\n        return urn\n\ndef remove_version_et(obj):\n    try:\n        urn = remove_version_str(obj.attrib['urn'])\n        new_obj = obj\n        new_obj.attrib['urn'] = urn\n        return new_obj\n    except:\n        return obj\n","sub_path":"kodai/freg_funkcijos.py","file_name":"freg_funkcijos.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"166497627","text":"'''\n输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。\n要求不能创建任何新的结点,只能调整树中结点指针的指向。\n'''\n\n\nclass TreeNode:\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\n\ndef convert(pRootOfTree):\n    if not pRootOfTree:\n        return None\n    p_last = convert_nodes(pRootOfTree, None)\n    while p_last and p_last.left:  # 向头节点走\n        p_last = p_last.left\n    return p_last  # 返回链表的头节点\n\n\n'''\n# 回顾:\ndef inorder(self):  # 前序,中序和后序遍历都是深度优先遍历的特例\n    if self.leftChild:  # 左\n        self.leftChild.inorder()\n    print(self.key)  # 中间的处理\n    if self.rightChild:  # 右\n        self.rightChild.inorder()\n'''\n\n\n# 核心是中序遍历,先理解好中序遍历的递归过程再看下面代码会便于理解\ndef convert_nodes(pRootOfTree, last):\n    if not pRootOfTree:\n        return None\n\n    # 左\n    if pRootOfTree.left:\n        last = convert_nodes(pRootOfTree.left, last)\n\n    # 中间的处理\n    if last:  # 建立双向链接\n        last.right = pRootOfTree\n    pRootOfTree.left = last\n    last = pRootOfTree  # 跟着向后移动\n\n    # 右\n    if pRootOfTree.right:\n        last = convert_nodes(pRootOfTree.right, last)\n\n    return last\n\n\npNode1 = TreeNode(10)\npNode2 = TreeNode(6)\npNode3 = TreeNode(14)\npNode4 = TreeNode(4)\npNode5 = TreeNode(8)\npNode6 = TreeNode(12)\npNode7 = TreeNode(16)\n\npNode1.left = pNode2\npNode1.right = pNode3\npNode2.left = pNode4\npNode2.right = pNode5\npNode3.left = pNode6\npNode3.right = pNode7\n\nnewList = convert(pNode1)\nprint(newList.val)\n\n'''\ndef Convert(pRootOfTree):\n    if pRootOfTree is None:\n        return None\n    if not pRootOfTree.left and not pRootOfTree.right:\n        return pRootOfTree\n\n    # 处理左子树\n    Convert(pRootOfTree.left)\n    left = pRootOfTree.left\n\n    # 连接根与左子树最大结点\n    if left:\n        while left.right:\n            left = left.right\n        pRootOfTree.left, left.right = left, pRootOfTree\n\n    # 处理右子树\n    Convert(pRootOfTree.right)\n    right = pRootOfTree.right\n\n    # 连接根与右子树最小结点\n    if right:\n        while right.left:\n            right = right.left\n        pRootOfTree.right, right.left = right, pRootOfTree\n\n    while pRootOfTree.left:\n        pRootOfTree = pRootOfTree.left\n\n    return pRootOfTree\n'''\n","sub_path":"剑指Offer/第4章/二叉搜索树与双向链表27.py","file_name":"二叉搜索树与双向链表27.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"272391659","text":"import random    #start\n\nname = input(\"enter your name: \")\nprint(name)\n#saved user input in name\nprint(\"        following are the rules of the game\")\nprint(\"1> The word should be displayed  in encrypted form along with the hint then the user is asked whether he wants to guess the entire word or guess the letters in the word one by one.only fir the first time.\")\nprint(\"2> The initial score of the player will be 10 points.\")\nprint(\"3> If the user chooses to guess the entire word at once  then if he successfully makes the correct guess then display the word and 5 points will be awarded ,he wins the game so display the score and the game stops. But if he fails to make the correct guess then 3 points are deducted from the score and then he can make further guess for the entire word till the score greater than 0. The game gets over if the score becomes zero.\")\nprint(\"4> If the user chooses to guess the letter one by one then If the correct letter is guessed ,display the letter(with correct placement) and 3 points will be awarded else 2 points will be deducted for each wrong guess.\")\nprint(\"5> The user is allowed  to make further guesses only if the score is greater than 0.If the score is not greater than zero than the game is over and the player loses  the game.\")\n#described all the rules related to the game\n\nprint (\"welcome \" + name)\n\npoints = 10\n#initial point is 10\n\n\ndef get_club():\n    club=[\"EMOTICA\",\"AVC\",\"SOULS\",\"VIBRANZ\",\"PIXALS\"]\n    return random.choice(club).upper()\n\n\ndef check(club, guesses, guess):\n    status = ''\n    matches = 0\n    global points\n    for letter in club:\n        if letter in guesses:\n            status += letter\n        else:\n            status += '*'\n        if letter == guess:\n            matches += 1\n\n    if matches >= 1:\n        points = points + 3\n\t#here point variable point scored by the user\n        print('your score',points)\n        print('yes,the word you have to guess contains', matches, '\"' + guess + '\"' + 's')\n\t# if the user guessed the correct letter then the points will be increased by 3 points\n\n    else:\n        print('sorry,,the word doesn\\'t contain the letter \"' + guess + '\"')\n        points = points-2\n        print('your score',points)\n        # if points < 0:\n        # print('your prediction is wrong!')\n\t# if the guessed letter is not present in the supposed club name then the point will be decresed by 2\n\n    return status\n\n\ndef main():\n    club= get_club()\n    guesses=[] #this array stores guesses.\n    guessed = False\n    print('the word you have to guess contains', len(club), 'letters.')\n    global points\n    while points > 0:\n        print('please enter one letter or {}-lettered word directly'.format(len(club)))\n        guess = (input()).upper()\n\t#each letters in this guess variable are converted to capital letterl\n\t#this loop will be only executed when the points of the user is greater than 0\n\n        if guess in guesses:\n            print('you have already guessed the letter' + guess + '\"')\n            points = points - 2\n            #if user repeats the same letter again it will deduct its 2 points\n            print('your score is:' ,points)\n        elif len(guess) == len(club):\n            guesses.append(guess)\n\t    #append function is here used to add the letter at the end of guess variable\n            if guess == club:\n                guessed = True\n            else:\n                print('sorry,that is incorrect.')\n        elif len(guess) == 1:\n            guesses.append(guess)\n            result = check(club, guesses, guess)\n            if result == club:\n                guessed = True\n                break\n            else:\n                print(result)\n        else:\n            print('invalid entry.')\n    if points>0:\n        print('yes,the club name is', club + ' congratulations you have guessed the correct club name')\n    else:\n        print('NOO your input is wrong')\n\nmain()","sub_path":"Word guessing game.py","file_name":"Word guessing game.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"130419835","text":"\"\"\"测试登录功能  正确的用户名:18684720553\"\"\"\nimport time\nimport unittest\n\nimport ddt\nimport pytest\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\n\n\n# 1. 测试,预期结果和实际结果\n# 2. 投资,登录\n# Selenium 初始化的时候 Option, --headless\nfrom pages.index import IndexPage\nfrom pages.login import LoginPage\nfrom test_data.login import user_info_error, user_info_authorize\n\n\n@ddt.ddt\nclass TestLogin(unittest.TestCase):\n\n    @classmethod\n    def setUpClass(cls):\n        print(\"test begin\")\n        cls.driver = Chrome()\n        cls.login_page = LoginPage(cls.driver)\n\n    @classmethod\n    def tearDownClass(cls):\n        print(\"test end\")\n        cls.driver.quit()\n\n    def setUp(self):\n        # 浏览器初始化\n        print(\"test case begin\")\n        # self.driver = Chrome()\n        # 初始化登录页面\n\n    def tearDown(self):\n        print(\"test case end\")\n        # clear_user_info()\n\n    def test_login_2_success(self):\n        # 登录 login\n        self.login_page.login('18684720553', 'python')\n        # 5. 断言 首页的元素\n\n        # 获取用户信息 get_user_info()\n        # user_ele = driver.find_element_by_xpath(\"//a[@href='/Member/index.html']\")\n\n        user_ele = IndexPage(self.driver).get_user_info()\n\n        self.assertTrue(\"小蜜蜂96027921\" in user_ele.text)\n\n        time.sleep(2)\n\n    @pytest.mark.login\n    @ddt.data(*user_info_error)\n    def test_login_1_error(self, data):\n        \"\"\"请输入手机号\"\"\"\n        # 登录\n        self.login_page.login(data['username'], data['pwd'])\n        # 定位出错的信息的元素 get_flash_info()\n\n        # 清空用户数据clear_user_info() 侵犯攻击性\n\n        flash_ele = self.login_page.get_flash_info()\n        # 断言\n        self.assertTrue(data['expected'] == flash_ele.text)\n\n        # 关键点:数据不同\n\n\n        # 测试用例数据:1. Excel, 2:列表\n        # http_request(url, data, method)\n        # 数据 == 》 测试, page 页面\n\n    @ddt.data(*user_info_authorize)\n    def test_login_2_unauth(self, data):\n        \"\"\"请输入手机号\"\"\"\n        # 登录\n        self.login_page.login(data['username'], data['pwd'])\n        # 定位出错的信息的元素 get_flash_info()\n\n        # 清空用户数据clear_user_info() 侵犯攻击性\n\n        flash_ele = self.login_page.get_flash_info_1()\n        # 断言\n        self.assertTrue(data['expected'] == flash_ele.text)\n\n\nif __name__ == '__main__':\n    unittest.main()\n\n\n    # 随机测试\n    # 测试用例发现 add 自动发现\n    # 测试环境 fixture\n    # 测试报告,pip install pytest-allure\n    # 重运行机制\n\n\n\n","sub_path":"qianchengdai_v3/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"250346087","text":"import os\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef get_drawable_map(map, target_x = 200, target_y = 200):\n\n    color_unknown = -80\n    color_known = 0\n    color_obstacle = 150\n    color_target = 200\n\n    target_dim = 4\n    target_x_index = slice(target_x - (target_dim//2), target_x + (target_dim//2))\n    target_y_index = slice(target_y - (target_dim//2), target_y + (target_dim//2))\n\n    drawable_map = np.copy(map)\n    drawable_map[drawable_map == -1] = color_unknown # recoloring unknown\n    drawable_map[drawable_map == 0] = color_known # recoloring known\n    drawable_map[drawable_map == 100] = color_obstacle # recoloring obstacles\n    drawable_map[target_x_index,target_y_index] = color_target # recoloring target\n\n    return drawable_map\n\n\n\nnpy_name = 'indoor_1'\nscript_folder = os.path.dirname(os.path.realpath(__file__))\nmap_path = script_folder + '/' + npy_name\n\nmap = np.load(map_path + '.npy')\nprint('map shape: ', map.shape)\n# np.savetxt(map_path + '.txt', map, '%4.0f')\n\n\nplt.figure(figsize = (6,6))\nplt.imshow(get_drawable_map(map), interpolation='nearest', origin='lower')\nplt.pause(20)\n","sub_path":"tests/loadmap/loadmap.py","file_name":"loadmap.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"333462867","text":"# 消息内容处理接口,分割获得的聊天数据\n# 数据分割后包括:\n# \t聊天类型(私密/群消息): \n#\t聊天@情况(仅当群消息时获得):  \n#\t聊天@对象(仅当cq_status==True时获得): \n#\t聊天消息来源群ID(仅当群消息时获得): \n#\t聊天消息来源用户ID:\n#\t聊天消息来源昵称:\n#\t消息内容: \n#\t消息图像URL(当存在消息type==\"image\"时): \n#\t消息处理状态:  \n\n# 私密消息数据的几种情况:\n#\t1、私密消息\n#\t2、私密消息+图像信息\n#\t3、图像信息\n\n# 群消息数据的几种情况:\n#\t1、群消息\n#\t2、图像信息\n#\t3、@成员+群消息\n#\t4、@成员+群消息+图像信息\n#\t5、@成员+图像信息\n#\t6、@成员+无任何消息\n\n# 处理消息全局接口\ndef get_message(data):\n\n\t# 初始化数据默认值\n\tmessage_type=\"\"\n\tat_status=False\n\tat_id=[]\n\tgroup_id=\"\"\n\tuser_id=\"\"\n\tnickname=\"\"\n\tmessage=\"\"\n\timage_url=[]\n\tmessage_status=False\n\t\n\t# 获得全局聊天类型(私密/群消息)\n\tmessage_type=data.get(\"Type\")\n\n\t# 处理私密消息\n\tif (message_type==\"PrivateMsg\"):\n\t\tmessage_type=\"private\"\n\t\t(user_id,nickname,message,image_url,message_status)=private_message(data)\n\n\t# 处理群消息\n\telif (message_type==\"GroupMsg\"):\n\t\tmessage_type=\"group\"\n\t\t(at_status,at_id,group_id,user_id,nickname,message,image_url,message_status)=group_message(data)\n\n\t# 输出消息\n\t#print(\"收到一条%s消息:\" %message_type)\n\t#print(\"@类型:%s\\t@对象:%s\" %(at_status,at_id))\n\t#print(\"来自QQ:%s\\t昵称:%s\" %(user_id,nickname))\n\t#print(\"消息类型:%s\" %message_type)\n\t#print(\"消息内容:%s\" %message)\n\t#print(\"消息图像URL:%s\" %image_url)\n\t#print(\"消息处理状态:%s\\n\" %message_status)\n\n\t# 整合数据\n\tmessage={\n\t\t\"message_type\":message_type,\n\t\t\"at_status\":at_status,\n\t\t\"at_id\":at_id,\n\t\t\"group_id\":group_id,\n\t\t\"user_id\":user_id,\n\t\t\"nickname\":nickname,\n\t\t\"message\":message,\n\t\t\"image_url\":image_url,\n\t\t\"message_status\":message_status\n\t}\n\n\treturn message\n\n# 私密消息处理\ndef private_message(data):\n\timage_url=\"\"\n\tuser_id=data.get(\"FromQQ\").get(\"UIN\")\n\tnickname=data.get(\"FromQQ\").get(\"NickName\")\n\tmessage=data.get(\"Msg\").get(\"Text\")\n\n\t# Warning: For CoolQ, no longer useful\n\t#message=\"\"\n\t#image_url=[]\n\t#message_length=len(data.get(\"message\"))\n\t#for i in range(message_length):\n\t\t#if(data.get(\"message\")[i].get(\"type\")==\"text\"):\n\t\t\t#message=message+data.get(\"message\")[i].get(\"data\").get(\"text\")\n\t\t#elif(data.get(\"message\")[i].get(\"type\")==\"image\"):\n\t\t\t#image_url.append(data.get(\"message\")[i].get(\"data\").get(\"url\"))\n\n\tif message!=\"\":\n\t\tmessage_status=True\n\telse:\n\t\tmessage_status=False\n\t\n\treturn user_id,nickname,message,image_url,message_status\n\n# 群消息处理\ndef group_message(data):\n\tat_status=False\n\tat_id=[]\n\timage_url=\"\"\n\tgroup_id=data.get(\"FromGroup\").get(\"GIN\")\n\tuser_id=data.get(\"FromQQ\").get(\"UIN\")\n\tnickname=data.get(\"FromQQ\").get(\"Card\")\n\tmessage=data.get(\"Msg\").get(\"Text\")\n\n\t# Warning: For CoolQ, no longer useful\n\t#message=\"\"\n\t#image_url=[]\n\t#message_length=len(data.get(\"message\"))\n\t#for i in range(message_length):\n\t\t#if(data.get(\"message\")[i].get(\"type\")==\"text\"):\n\t\t\t#message=message+data.get(\"message\")[i].get(\"data\").get(\"text\")\n\t\t#elif(data.get(\"message\")[i].get(\"type\")==\"image\"):\n\t\t\t#image_url.append(data.get(\"message\")[i].get(\"data\").get(\"url\"))\n\t\t#elif(data.get(\"message\")[i].get(\"type\")==\"at\"):\n\t\t\t#cq_status=True\n\t\t\t#cq_id.append(data.get(\"message\")[i].get(\"data\").get(\"qq\"))\n\n\tif message!=\"\":\n\t\tmessage_status=True\n\telse:\n\t\tmessage_status=False\n\t\n\treturn at_status,at_id,group_id,user_id,nickname,message,image_url,message_status\n\t","sub_path":"message_operate.py","file_name":"message_operate.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"569523660","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:lichengbing\n\n# import fan1\n#\n# user_input = input('输入编号:')\n# if hasattr(fan1, user_input):\n#     func = getattr(fan1, user_input)\n#     func()\n# else:\n#     print('no module...')\n\nuser_input = input('请输入URL:')\nk, v = user_input.split('/')\nobj = __import__('lib.' + k, fromlist=True)\nif hasattr(obj, v):\n    func = getattr(obj, v)\n    func()\nelse:\n    print('no module...')\n\n","sub_path":"day6/test/fan2.py","file_name":"fan2.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"249091328","text":"# -*- coding: utf-8 -*-\n\nimport urllib\n\nfrom services import GameActiveInfoService\nfrom services import GameQuestionInfoService\nfrom services import GameActivePrizeInfoService\nfrom services import GameAnswerInfoService\n\nfrom services import UserInfoService\nfrom services import UserPlayOriginGameInfoService\nfrom services import UserPlayShareGameInfoService\nfrom services import UserShareInfoService\nfrom services import UserShareLimitInfoService\nfrom services import UserPrizeInfoService\n\n\nfrom h5game_backend import LOGGER\nfrom h5game_backend import app\nfrom models import BizStatusUtils\n\n#####主业务类\n\nclass GameBizService:\n\tdef __init__(self):\n\t\t#LOGGER.info(\"Init 1\")\n\t\tself._gameActiveInfoService = GameActiveInfoService.GameActiveInfoService()\n\t\tself._gameQuestionInfoService = GameQuestionInfoService.GameQuestionInfoService()\n\t\tself._gameActivePrizeInfoService = GameActivePrizeInfoService.GameActivePrizeInfoService()\n\t\tself._gameAnswerInfoService = GameAnswerInfoService.GameAnswerInfoService()\n\n\t\tself._userPrizedInfoService = UserPrizeInfoService.UserPrizeInfoService()\n\t\tself._userPlayOriginGameInfoService = UserPlayOriginGameInfoService.UserPlayOriginGameInfoService()\n\t\tself._userPlayShareGameInfoService = UserPlayShareGameInfoService.UserPlayShareGameInfoService()\n\t\tself._userShareInfoService = UserShareInfoService.UserShareInfoService()\n\t\tself._userShareLimitInfoService = UserShareLimitInfoService.UserShareLimitInfoService()\n\t\tself._userInfoService = UserInfoService.UserInfoService()\n\n\n#####获取此Url或signWord对应的activeId\n\tdef gameHomepageInfo(self, userId, signWord):\n\t\tactiveInfo = self._gameActiveInfoService.getInfoBySignWord(signWord)\t\t\n\t\tif not activeInfo:\n\t\t\treturn None\n\t\tprizes = self._gameActivePrizeInfoService.getInfosByActiveId(activeInfo['id'])\n\t\t###check user prized\n\t\t###是否中奖了\n\t\tprizeInfo = self._userPrizedInfoService.getUserPrizeInfo(userId, activeInfo['id'])\n\n\t\tif prizeInfo:\n\t\t\tLOGGER.debug(\"User prized info:\" + str(prizeInfo))\n\t\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\t\tLOGGER.info(\"Goto homepage.\")\n\t\treturn {'success': True, 'welcome': True, 'activeInfo': activeInfo, 'prizes': prizes}\n\n#self.gameBizService.afterShared(userId, shareCode, activeId)\n\tdef afterShared(self, userId, shareCode, activeId):\n\t\tself._userShareInfoService.modifyResult(userId, shareCode, activeId, BizStatusUtils.SHARED_SUCCESS)\n\n\tdef _handleIllegalResp(self, failedType = 'illegal', message=\"data access failed\"):\n\t\treturn {'success': False, 'failedType': failedType, 'message': message}\n#######\n\tdef playShareGame(self, userId, openId, activeId, shareCode):\n\t\t##用户权限检测\n\t\tactiveInfo = self._gameActiveInfoService.getInfo(activeId)\n\t\tif activeInfo is None:\n\t\t\treturn self._handleIllegalResp(message=\"no activeInfo info:\" + activeId)\n\t\t###是否中奖了\n\t\tactiveId = activeInfo['id']\n\t\tprizeInfo = self._userPrizedInfoService.getUserPrizeInfo(userId, activeId)\n\t\tif prizeInfo:\n\t\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\t\t###shareCode有效性检测\n\t\tshareInfo = self._userShareInfoService.getInfoByShareCode(shareCode)\n\t\tif shareInfo is None or int(shareInfo['activeId']) != int(activeId):\n\t\t\treturn self._handleIllegalResp(message=\"illegal info failed.\")\n\n\t\tsharePlayInfo = self._userPlayShareGameInfoService.getInfo(userId, activeId, shareCode)\n\t\tif sharePlayInfo is not None:\n\t\t\tplayInfoResult = int(sharePlayInfo['result'])\n\t\t\tif playInfoResult == BizStatusUtils.PLAY_RESULT_SUCCESS:\n\t\t\t\treturn self._gotoRecivePrize(userId, activeId)\n\t\t\telse:\n\t\t\t\treturn self._continuePlay(sharePlayInfo, activeInfo = activeInfo)\n\t\tfirstQuestion, randomQuestionIds = self._gameQuestionInfoService.randomAndGetUserFirstQuestion(activeId)\n\t\t#def addUserPlayInfo(self, userId, activeId, shareCode, randomQuestionIds, playQuestionId):\n\t\tplayInfo = self._userPlayShareGameInfoService.addUserPlayInfo(userId, activeId, shareCode, randomQuestionIds, firstQuestion['id'])\n\t\tif playInfo:\n\t\t\treturn self._continuePlay(playInfo, firstQuestion, activeInfo = activeInfo)\n\t\treturn self._handleIllegalResp(failedType=\"server\")\n\n\tdef playGame(self, userId, activeId):\n\t\t##用户权限检测\n\t\tactiveInfo = self._gameActiveInfoService.getInfo(activeId)\n\t\tif activeInfo is None:\n\t\t\tLOGGER.debug(\"No active info\")\n\t\t\treturn self._handleIllegalResp()\n\t\t###是否中奖了\t\t\n\t\tprizeInfo = self._userPrizedInfoService.getUserPrizeInfo(userId, activeId)\n\t\tif prizeInfo:\n\t\t\tLOGGER.debug(\"No prize info\")\n\t\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\n\t\t##用户上一次玩结束了吗\n\t\tplayInfo = self._userPlayOriginGameInfoService.getInfo(userId, activeId)\n\t\tif playInfo is None:\n\t\t\tLOGGER.debug(\"No playInfo info go to play origin game\")\n\t\t\treturn self._playOriginGame(userId, activeId)\n\t\t######用户有正在玩的记录\n\t\treturn self._continuePlay(playInfo)\n\n\tdef _playOriginGame(self, userId, activeId):###用户还能再玩\n\t\tfirstQuestion, randomQuestionIds = self._gameQuestionInfoService.randomAndGetUserFirstQuestion(activeId)\n\t\tLOGGER.debug(\"First question:\" + str(firstQuestion))\n\t\t# LOGGER.debug(\"Random question ids:\" + randomQuestionIds)\n\t\tplayInfo = self._userPlayOriginGameInfoService.addUserPlayInfo(userId, activeId, randomQuestionIds, firstQuestion['id'])\t\t\n\t\tif playInfo:\n\t\t\treturn self._continuePlay(playInfo, firstQuestion)\n\t\treturn self._handleIllegalResp(failedType=\"server\")\n\n\t#####开始在接口层面区分来自于共享的还是系统提供的游戏机会,此接口只供系统提供的游戏机会中调用\n\t#####resp=  {'sucess': True/False, 'failedType': 'illegal'|'server'|'limit', 'play':True, \\\n\t############'needShare': True, 'prized', 'activeInfo': activeInfo, 'playInfo': playInfo,  \\\n\t############'prizeInfo': prizeInfo, 'question': question, \"answers\": answers}\n\tdef originGameNext(self, userId, activeId, questionId, answerId):\n\t\tplayInfo = self._userPlayOriginGameInfoService.getInfo(userId, activeId)\n\t\tif playInfo is None:\n\t\t\treturn self._handleIllegalResp()\n\n\t\tif int(playInfo['playQuestionId']) != int(questionId):\n\t\t\t###用户当前玩的问题和数据库数据不对,可能是微信客户端里点后退了\n\t\t\tprizeInfo = self._userPrizedInfoService.getUserPrizeInfo(userId, activeId)\n\t\t\tif prizeInfo:\n\t\t\t\tactiveInfo = self._gameActiveInfoService.getInfo(activeId)\n\t\t\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\t\t\treturn self._continuePlay(playInfo)\n\t\trightAnswer = self._gameQuestionInfoService.checkAnswer(questionId, answerId)\n\t\tif rightAnswer:\n\t\t\treturn self._gotoNext(userId, activeId, questionId, playInfo)\n\t\telse:\n\t\t\tresp =  self._continuePlay(playInfo)\n\t\t\tresp['answerFailed'] = True\n\t\t\treturn resp\n\n\tdef shareGameNext(self, userId, activeId, shareCode, questionId, answerId):\n\t\tplayInfo = self._userPlayShareGameInfoService.getInfo(userId, activeId, shareCode)\n\t\tif playInfo is None:\n\t\t\treturn self._handleIllegalResp(message=\"No playInfo or the question id is wrong.\")\n\n\t\t###用户当前玩的问题和数据库数据不对,可能是微信客户端里点后退了\n\t\tif int(playInfo['playQuestionId']) != int(questionId):\n\t\t\tprizeInfo = self._userPrizedInfoService.getUserPrizeInfo(userId, activeId)\n\t\t\tif prizeInfo:\n\t\t\t\tactiveInfo = self._gameActiveInfoService.getInfo(activeId)\n\t\t\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\t\t\treturn self._continuePlay(playInfo)\n\t\trightAnswer = self._gameQuestionInfoService.checkAnswer(questionId, answerId)\n\t\tif rightAnswer:\n\t\t\treturn self._gotoSharedGameNext(userId, activeId, shareCode, questionId, playInfo)\n\t\telse:\n\t\t\tresp = self._continuePlay(playInfo)\n\t\t\tresp['answerFailed'] = True\n\t\t\treturn resp\n\n\tdef _initQuestionIds(self, questionIdsStr):\n\t\tquestionIds = questionIdsStr.split(\",\")\n\t\tquestionIdList = []\n\t\tfor questionId in questionIds:\n\t\t\tquestionId = questionId.strip()\n\t\t\tquestionIdList.append(questionId)\n\t\treturn questionIdList\n\t\n\t###在答题成功后,下一个题目\n\tdef _gotoNext(self, userId, activeId, preQuestionId, playInfo):\n\t\tquestionIdsStr = playInfo['questionIds']\n\t\tquestionIdList = self._initQuestionIds(questionIdsStr)\n\t\tpreIndex = -1\n\t\tfor index, value in enumerate(questionIdList):\n\t\t\tif int(value) == int(preQuestionId):\n\t\t\t\tpreIndex = index\n\t\t\t\tbreak\n\t\tif preIndex == -1:\n\t\t\treturn self._handleIllegalResp()\n\t\t###问题答完了\n\t\t###获取抽奖码\n\t\tif preIndex == len(questionIdList) - 1:\n\t\t\tself._userPlayOriginGameInfoService.modifyResult(playInfo['id'], userId, activeId, BizStatusUtils.PLAY_RESULT_SUCCESS)\n\t\t\treturn self._gotoRecivePrize(userId, activeId)\n\t\t#####下一个问题\n\t\tquestionId = questionIdList[preIndex + 1]\n\t\tquestion = self._gameQuestionInfoService.getInfo(questionId)\t\t\n\t\tif question is None:\n\t\t\treturn self._handleIllegalResp()\n\t\tself._userPlayOriginGameInfoService.modifyPlayQuestionId(playInfo['id'], userId, activeId, questionId)\n\t\tplayInfo = self._userPlayOriginGameInfoService.getInfo(userId, activeId)\n\t\treturn self._continuePlay(playInfo, question)\n\n\t###在答题成功后,下一个题目\n\tdef _gotoSharedGameNext(self, userId, activeId, shareCode, preQuestionId, playInfo):\n\t\tquestionIdsStr = playInfo['questionIds']\n\t\tquestionIdList = self._initQuestionIds(questionIdsStr)\n\t\tpreIndex = -1\n\t\tfor index, value in enumerate(questionIdList):\n\t\t\tif int(value) == int(preQuestionId):\n\t\t\t\tpreIndex = index\n\t\t\t\tbreak\n\t\tif preIndex == -1:\n\t\t\treturn self._handleIllegalResp()\n\t\t###问题答完了\n\t\t###获取抽奖码\n\t\tif preIndex == len(questionIdList) - 1:\n\t\t\tself._userPlayShareGameInfoService.modifyResult(playInfo['id'], userId, activeId, shareCode, BizStatusUtils.PLAY_RESULT_SUCCESS)\n\t\t\treturn self._gotoRecivePrize(userId, activeId)\n\t\t#####下一个问题\n\t\tquestionId = questionIdList[preIndex + 1]\n\t\tquestion = self._gameQuestionInfoService.getInfo(questionId)\t\t\n\t\tif question is None:\n\t\t\treturn self._handleIllegalResp()\n\t\tself._userPlayShareGameInfoService.modifyPlayQuestionId(playInfo['id'], userId, activeId, shareCode, questionId)\n\t\tplayInfo = self._userPlayShareGameInfoService.getInfo(userId, activeId, shareCode)\n\t\treturn self._continuePlay(playInfo, question)\n\n\n\t###用户领奖给用户生成抽奖码,并返回\n\tdef _gotoRecivePrize(self, userId, activeId):\n\t\tactiveInfo = self._gameActiveInfoService.getInfo(activeId)\n\t\tprizeInfo = self._userPrizedInfoService.genPrize(userId, activeId)\n\t\tif activeInfo is None or prizeInfo is None:\n\t\t\treturn self._handleIllegalResp()\n\t\treturn self._handlePrized(activeInfo, prizeInfo)\n\n\tdef _handlePrized(self, activeInfo, prizeInfo):\n\t\treturn {'success': True, 'prized': True, 'activeInfo': activeInfo, 'prizeInfo': prizeInfo}\n\n\tdef _initReturnQuestion(self, question, playInfo, activeInfo):\n\t\tif question is None or playInfo is None or activeInfo is None:\n\t\t\treturn self._handleIllegalResp()\n \t\t\n\t\tanswers = self._initQuestionPossibleAnswerInfo(question)\n\t\tif answers is None or not answers:\n\t\t\treturn self._handleIllegalResp()\n\n\t\tquestionIdsStr = playInfo['questionIds']\n\t\tquestionIdList = self._initQuestionIds(questionIdsStr)\n\t\tnumberIndex = -1\n\n\t\tfor i_id in questionIdList:\n\t\t\tnumberIndex = numberIndex + 1\n\t\t\tif str(i_id) == str(question['id']):\n\t\t\t\tbreak\n\t\tif 'shareCode' in playInfo:\n\t\t\treturn {'success': True, 'play': True, 'activeInfo': activeInfo, 'playInfo': playInfo, 'question': question, 'answers': answers, 'numberIndex': numberIndex, 'shareCode': playInfo['shareCode']}\n\t\telse:\n\t\t\treturn {'success': True, 'play': True, 'activeInfo': activeInfo, 'playInfo': playInfo, 'question': question, 'answers': answers, 'numberIndex': numberIndex}\n\n\t################originGame是否原生游戏#############\n\tdef _continuePlay(self, playInfo, question = None, activeInfo = None):\n\t\tif question is None:\n\t\t\tquestionId = playInfo['playQuestionId']\n\t\t\tquestion = self._gameQuestionInfoService.getInfo(questionId)\n\t\tif activeInfo is None:\n\t\t\tactiveInfo = self._gameActiveInfoService.getInfo(playInfo['activeId'])\n\t\treturn self._initReturnQuestion(question, playInfo, activeInfo)\n\n\tdef _initQuestionPossibleAnswerInfo(self, question):\n\t\tif question is None:\n\t\t\treturn self._handleIllegalResp()\n\t\tanswerIdsStr = question['possibleAnswerIds']\n\t\tanswerIds = answerIdsStr.split(\",\")\n\t\tanswerIdList = []\n\t\tfor answerId in answerIds:\n\t\t\tanswerId = answerId.strip()\n\t\t\tanswerIdList.append(answerId)\n\t\treturn self._gameAnswerInfoService.getInfos(answerIdList)\n\n\tdef _userId(self, openId):\n\t\treturn self._userInfoService.getUserId(openId)\n\n\tdef genUserShareContent(self, userId, openId, activeId, appId, signWord):\n\t\tshareInfo = self._userShareInfoService.getInfoByUserIdActiveId(userId, activeId)\n\t\tif shareInfo:\t\t\t\n\t\t\treturn shareInfo\n\t\tshareCode = self._userShareInfoService.buildShareCode(openId)\n\t\tshareUrl = self._getShareUrl(signWord, shareCode)\n\n\t\t##def genShareInfo(self, userId, openId, activeId, shareCode, shareUrl):\n\t\treturn self._userShareInfoService.genShareInfo(userId, openId, activeId, shareCode, shareUrl)\n\n\n\tdef _getShareUrl(self, signWord, shareCode):\n\t\treturn \"http://h5.yiketalks.com/game/redirect/\" + signWord + \"/\" + shareCode\n\n","sub_path":"h5game_backend/services/GameBizService.py","file_name":"GameBizService.py","file_ext":"py","file_size_in_byte":12947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"158232165","text":"class Solution:\n    def minPathSum(self, grid: List[List[int]]) -> int:\n        dp = grid.copy()\n        X, Y = len(grid), len(grid[0])\n        for x in range(X):\n            for y in range(Y):\n                if 0 < x and 0 < y:\n                    dp[x][y] += min([dp[x - 1][y], dp[x][y - 1]])\n                elif x == 0 and y != 0:\n                    dp[x][y] += dp[x][y - 1]\n                elif x != 0 and y == 0:\n                    dp[x][y] += dp[x - 1][y]\n                elif x == 0 and y == 0:\n                    continue\n        return dp[X - 1][Y - 1]\n","sub_path":"64_minimum-path-sum.py","file_name":"64_minimum-path-sum.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"340066257","text":"import histogram_v2\n\ndef moby_clean(file_name):\n    with open (file_name, 'r') as file:\n        words = [line.strip() for line in file.readlines()]\n        dict = histogram_v2.histogram(words)\n        list_dict = list(dict.items())\n        list_dict.sort(key=lambda x: x[1])\n        print(list_dict[:5])\n        print(list_dict[-5:])\n\nmoby_clean('moby_clean.txt')\n","sub_path":"104-moby_stat.py","file_name":"104-moby_stat.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"276919043","text":"class Solution:\n    def solve(self, board: List[List[str]]) -> None:\n        \"\"\"\n        Do not return anything, modify board in-place instead.\n        \"\"\"\n        if not board or len(board) == 0 or len(board[0]) == 0:\n            return\n        m, n = len(board), len(board[0])\n        for i in range(m):\n            if board[i][0] == 'O':\n                self.bfs(board, i, 0)\n            if board[i][n - 1] == 'O':\n                self.bfs(board, i, n - 1)\n        for j in range(n):\n            if board[0][j] == 'O':\n                self.bfs(board, 0, j)\n            if board[m - 1][j] == 'O':\n                self.bfs(board, m - 1, j)\n\n        for i in range(m):\n            for j in range(n):\n                if board[i][j] == 'Y':\n                    board[i][j] = 'O'\n                elif board[i][j] == 'O':\n                    board[i][j] = 'X'\n\n\n    def bfs(self, board, i, j):\n        dx, dy = [1, 0, 0, -1], [0, 1, -1, 0]\n        q = collections.deque([(i, j)])\n        board[i][j] = 'Y'\n        while q:\n            board_x, board_y = q.popleft()\n            for k in range(4):\n                x, y = board_x + dx[k], board_y + dy[k]\n                if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]):\n                    continue\n                if board[x][y] == 'O':\n                    board[x][y] = 'Y'\n                    q.append((x, y))\n\n\nclass Solution:\n    def solve(self, board: List[List[str]]) -> None:\n        \"\"\"\n        Do not return anything, modify board in-place instead.\n        \"\"\"\n        if not board or len(board) == 0 or len(board[0]) == 0:\n            return\n        m, n = len(board), len(board[0])\n        visited = set()\n        for i in range(m):\n            if board[i][0] == 'O':\n                self.dfs(board, i, 0, visited)\n            if board[i][n - 1] == 'O':\n                self.dfs(board, i, n - 1, visited)\n        for j in range(n):\n            if board[0][j] == 'O':\n                self.dfs(board, 0, j, visited)\n            if board[m - 1][j] == 'O':\n                self.dfs(board, m - 1, j, visited)\n\n        for i in range(m):\n            for j in range(n):\n                if board[i][j] == 'Y':\n                    board[i][j] = 'O'\n                elif board[i][j] == 'O':\n                    board[i][j] = 'X'\n\n\n    def dfs(self, board, i, j, visited):\n        dx, dy = [1, 0, 0, -1], [0, 1, -1, 0]\n        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or (i, j) in visited or board[i][j] != 'O':\n            return\n        board[i][j] = 'Y'\n        visited.add((i, j))\n        for k in range(4):\n            x, y = i + dx[k], j + dy[k]\n            self.dfs(board, x, y, visited)\n","sub_path":"python/130. Surrounded Regions.py","file_name":"130. Surrounded Regions.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"637936682","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('shop', '0006_auto_20150304_1527'),\n    ]\n\n    operations = [\n        migrations.AlterField(\n            model_name='goods',\n            name='price_list',\n            field=models.ForeignKey(null=True, verbose_name='Прайс-листы', blank=True, to='shop.PriceList'),\n        ),\n    ]\n","sub_path":"shop/migrations/0007_auto_20150304_1539.py","file_name":"0007_auto_20150304_1539.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"21527115","text":"from models.user import User\nfrom instagram_web.util.google_oauth import oauth\nfrom flask_login import login_user, login_required,logout_user\nfrom flask import Blueprint,url_for,render_template, flash, redirect, request\n\n# ----------------------------------------------------------------------------------------\nsessions_blueprint=Blueprint('sessions',\n                            __name__,\n                            template_folder='templates')\n# ----------------------------------------------------------------------------------------\n\n@sessions_blueprint.route('/login', methods=[\"GET\"])\ndef login():\n    return render_template('sessions/login.html')\n\n@sessions_blueprint.route('/auth', methods=[\"POST\"])\ndef authentication():\n    username = request.form['name']\n    password = request.form['password']\n\n    try:\n        user = User.get(name=username)\n    except:\n        flash('Username does not exist. Please try again.')\n        return redirect(url_for('sessions.login'))\n\n    login_user(user)\n    flash('Logged in successfully.')\n    return redirect(url_for('home'))\n\n@sessions_blueprint.route('/logout')\n@login_required\ndef logout():\n    logout_user()\n    flash('You have been logged out.')\n    return redirect(url_for('home'))\n\n# ----------------------------------------------------------------------------------------\n@sessions_blueprint.route('/google_login')\ndef google_login():\n    redirect_uri = url_for('sessions.authorize',_external=True)\n    return oauth.google.authorize_redirect(redirect_uri)\n\n@sessions_blueprint.route('/authorize/google')\ndef authorize():\n    oauth.google.authorize_access_token()\n    email = oauth.google.get('https://www.googleapis.com/oauth2/v2/userinfo').json()['email']\n    profile_photo = oauth.google.get('https://www.googleapis.com/oauth2/v2/userinfo').json()['email']\n    user = User.get_or_none(User.email==email)\n\n    if user:\n        login_user(user)\n        return redirect(url_for('home'))\n    else:\n        flash(\"User email not found in database. Please create an account first.\")\n        return redirect(url_for('users.new'))","sub_path":"instagram_web/blueprints/sessions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"472809137","text":"import json\nimport logging\nimport requests\nimport datetime\nimport traceback\nimport util.config as config\n\nclass TerrAvionAPI1User:\n    def __init__(self, access_token):\n        self.access_token = access_token\n        self.api1_domain = config.api1_domain\n        self.log = logging.getLogger(__name__)\n    def parse_response(self, r):\n        if r.status_code == 200:\n            self.log.debug('-----------------Response-------------------')\n            self.log.debug(json.dumps(r.json(), sort_keys=True, indent=2))\n            self.log.debug('------------------------------------')\n            result = r.json()\n            return result\n        else:\n            self.log.debug('error:' + str(r.status_code))\n            self.log.debug(r.text)\n            self.log.debug('-------------------------------------------------------')\n    def get_user(self, user_email):\n        q_url = self.api1_domain\n        q_url += 'users/' + user_email\n        q_url += '/?access_token=' + self.access_token\n        self.log.debug(q_url)\n        r = requests.get(q_url)\n        return self.parse_response(r)\n","sub_path":"geotiff_download/lib/api1/ta_user.py","file_name":"ta_user.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"461010848","text":"# no Liana solution\n\n\nfrom random import randint\n\n\nclass Solution(object):\n    def __init__(self, nums):\n        \"\"\"\n\n        :type nums: List[int]\n        :type numsSize: int\n        \"\"\"\n        self.nums = nums\n\n    def pick(self, target):\n        \"\"\"\n        :type target: int\n        :rtype: int\n        \"\"\"\n        res, total = None, 0\n        for i in xrange(len(self.nums)):\n            if self.nums[i] == target:\n                total += 1\n                if randint(1, total) == total:\n                    res = i\n        return res\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(nums)\n# param_1 = obj.pick(target)\n","sub_path":"398_random_pick_index/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"419617487","text":"# look for children in each node's children array recursively\n# look for children before brethren\n\n# O (V + E) complexity, O(V) for space\n\nclass Node:\n    def __init__(self, name):\n        self.children = []\n        self.name = name\n\n    def addChild(self, name):\n        self.children.append(Node(name))\n        return self\n\n     # is the array empty? \n    def depthFirstSearch(self, array):\n        # append to the array the node's name\n\t\n        array.append(self.name)\n\n        # call depthFirstSearch on all its children nodes. \n\n        for child in self.children:\n            child.depthFirstSearch(array)\n        \n        return array\n\n\n\n\n    def __str__(self) -> str:\n        if self.children:\n            for i in self.children:\n                print(i)\n\n        return self.name\n\nRoot = Node('A')\nRoot.addChild('B')\nRoot.addChild('C')\n\n# print(Root.children[1])\n\n# Root.depthFirstSearch()\n\nprint(Root)\n","sub_path":"AlgoExperts/Graphs/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"555426929","text":"# -*- coding: utf-8 -*-\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom .models import *\nfrom .forms import *\n\n# Create your views here.\ndef home(request):\n\tinfos = InformacionGeneral.objects.filter(categoria = \"IG\", activo = True).order_by(\"-prioridad\")\n\ttecnos = InformacionGeneral.objects.filter(categoria = \"TG\", activo = True).order_by(\"-prioridad\")\n\tlengs = InformacionGeneral.objects.filter(categoria = \"LG\", activo = True).order_by(\"-prioridad\")\n\texps = ExperienciaProfesional.objects.filter(activo = True).order_by(\"-desde\")\n\t\n\treturn render(request,\"index.html\",{\"infos\": infos, \"tecnos\":tecnos,\"lengs\":lengs,\"exps\":exps,})\n\ndef estudios(request):\n\testus = Estudio.objects.filter(activo = True).order_by(\"-fecha\")\n\t\n\treturn render(request,\"estudios.html\",{\"estus\":estus,})\n\ndef proyectos(request):\n\tproyes = Proyecto.objects.filter(activo = True).order_by(\"-fecha\")\n\t\n\treturn render(request,\"proyectos.html\",{\"proyes\":proyes,})\n\n\"\"\"\nsiempre estar pendiente de colocar el form como las variables que le pasas al template \ntambien de colocar la linea de encoding para utf8 en cada lugar donde vayas a usar acentos o caracteres epeciales\nimportar el form \n\"\"\"\ndef contactame(request):\n\tif request.is_ajax():\n\t    nombre = request.POST['name']\n\t    email = request.POST['email']\n\t    mensaje = request.POST['message']\n\n\t    msj = Mensaje(nombre=nombre, email=email,mensaje=mensaje)\n\t    msj.save()\n\n\t    return HttpResponse('Ok')\n\telse:\n\t\tform = ContactForm()\n\t\treturn render(request,\"contactame.html\",{\"form\": form})\n","sub_path":"administrador/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"380228857","text":"import os\nimport numpy as np\nfrom scipy import interpolate\nfrom scipy.spatial import Delaunay\nfrom netCDF4 import Dataset\nfrom ttide.t_getconsts import t_getconsts\nfrom ttide.t_vuf import t_vuf\nfrom matplotlib.tri import Triangulation\nfrom ttide.t_predic import t_predic\nfrom vcmq import regrid2d,create_grid,MV2,set_grid,griddata,grid2xy\n#from regrid import horizontal\nfrom vacumm.misc.grid.regridding import fill2d\nimport copy\nfrom scipy.interpolate import interp1d\n\ndef missing_interp(lon,lat,arr):\n\tgrid0 = create_grid(lon[0,:], lat[:,0])\n\tvarri = MV2.asarray(arr)\n\tvarri=set_grid(varri, grid0)\n\ttempf = fill2d(varri, method='carg')\n\tlon=np.ma.masked_where(tempf==tempf.fill_value, lon)\n\tlat=np.ma.masked_where(tempf==tempf.fill_value, lat)\n\tarri = griddata(lon.compressed(),lat.compressed(), tempf.compressed(), (lon[0,:], lat[:,0]), method='nat', ext=True, sub=10)\n\n\treturn arri\n\ndef extrapolate_amp(lon,lat,lonr, latr, maskr, arr):\n\tarr=missing_interp(lon,lat,arr)\n\tarri = grid2xy(arr,xo= lonr,yo=latr)\n\n\tif np.any(arri.mask):\n\t\ttmp=arri.getValue()[~arri.mask]\n\t\tpt=arri.mask.nonzero()[0]\n\t\tF=interp1d(np.arange(0,len(tmp)),tmp,'nearest',fill_value='extrapolate')\n\t\tarri[arri.mask]=F(pt)\n\n\n\n\n\n\treturn arri\ndef extrapolate_pha(lon,lat,lonr, latr, maskr, arr):\n\n\tcx, cy = np.cos(arr), np.sin(arr)\n\tcx=missing_interp(lon,lat,cx)\n\tcy=missing_interp(lon,lat,cy)\n\tcx = grid2xy(cx,xo= lonr,yo=latr)\n\tcy = grid2xy(cy,xo= lonr,yo=latr)\n\t\n\tif np.any(cx.mask):\n\t\ttmp=cx.getValue()[~cx.mask]\n\t\tpt=cx.mask.nonzero()[0]\n\t\tF=interp1d(np.arange(0,len(tmp)),tmp,'nearest',fill_value='extrapolate')\n\t\tcx[cx.mask]=F(pt)\n\n\t\ttmp=cy.getValue()[~cy.mask]\n\t\tpt=cy.mask.nonzero()[0]\n\t\tF=interp1d(np.arange(0,len(tmp)),tmp,'nearest',fill_value='extrapolate')\n\t\tcy[cy.mask]=F(pt)\n\n\tarr = np.arctan2(cy, cx)\n\treturn arr\n\ndef extract_HC(modfile,Vars, lon, lat, conlist=None, logger=None):\n\t\"\"\"\n\tExtract harmonic constituents and interpolate onto points in lon,lat\n\tset \"z\" to specifiy depth for transport to velocity conversion\n\tset \"constituents\" in conlist\n\tReturns:\n\t    u_re, u_im, v_re, v_im, h_re, h_im, omega, conlist\n\t\"\"\"\n\n\t###\n\tlon = np.asarray(lon)\n\tlat = np.asarray(lat)\n\n\t# Make sure the longitude is between 0 and 360\n\tlon = np.mod(lon,360.0)\n\n\t###\n\t# Read the filenames from the model file\n\tpathfile = os.path.split(modfile)\n\tpath = pathfile[0]\n\n\n\tf = Dataset(modfile,'r')\n\n\t###\n\t# Read the grid file\n\tX=f.variables['lon'][:]\n\tY=f.variables['lat'][:]\n\tif len(X.shape)==1:\n\t\tX, Y = np.meshgrid(X, Y)\n\n\tif 'dep' in f.variables:\n\t\tdepth=f.variables['dep'][:]\n\telse:\n\t\tdepth=np.zeros((X.shape))\n\n\t\n\t###\n\t# Check that the constituents are in the file\n\tconList = []\n\tconIDX=[]\n\tif conlist is not None:\n\t\tfor ncon in range(0,len(f.variables['cons'])):\n\t\t\tif f.variables['cons'][ncon][:] in conlist:\n\t\t\t\tx=''\n\t\t\t\tconList.append(''.join([x+n for n in f.variables['cons'][ncon]]))\n\t\t\t\tconIDX.append(ncon)\n\telse:\n\t\tfor ncon in range(0,len(f.variables['cons'])):\n\t\t\tx=''\n\t\t\tconList.append(''.join([x+n.decode('UTF-8') for n in f.variables['cons'][ncon].data]))\n\t\t\tconIDX.append(ncon)\n\n\tconst = t_getconsts(np.array([]))\n\tConst= [con.decode('UTF-8') for con in const[0]['name']] \n\tconsindex = [Const.index(con.ljust(4)) for con in conList]\n\n\ttfreq = (2*np.pi)*const[0]['freq'][consindex]/3600.\n\n\t###\n\t# Now go through and read the data for each\n\n\t\n\tmaskr = []\n\t\n\tVars=list(set([x.replace('_amp','').replace('_pha','') for x in Vars]))\n\tvar={}\n\t# interpolating to ROMS grid requires special care with phases!!\n\t#    this is subjected to parallelization via muitiprocessing.Process - do it!\n\t#    there is a sandbox in roms repo with a starting exercise\n\tfor var0 in Vars:\n\t\tvar[var0]=np.ones(shape=(len(tfreq),4,len(lon)))*-1e-8\n\t\tN=-1\n\n\t\tfor con,ncon in zip(const[0]['name'][consindex],conIDX):\n\t\t\tN=N+1\n\t\t\tcon=con.decode('UTF-8')\n\t\t\tlogger.info(\"Interpolating %s for %s\" %(var0, con))\t\t\n\t\t\tvar[var0][ncon,0,:] = extrapolate_amp(X, Y, lon, lat, maskr, f.variables[var0+\"_amp\"][ncon,:,:]) \n\t\t\tvar[var0][ncon,2,:] = extrapolate_pha(X, Y, lon, lat, maskr, f.variables[var0+\"_pha\"][ncon,:,:])*180./np.pi\n\n\n\n\treturn var,tfreq,consindex\n\ndef get_tide(ju,freq,tidecon0,t_time,lat0):\n\ttidecon=copy.deepcopy(tidecon0)\n\tnodes=tidecon.shape[2]\n\n\t\n\t#tidecon[:,0,:]=tidecon[:,0,:]+tidecon[:,0,:]*50/100\n\n\t#print('!!!!!!ADDING 50%!!!!!!!!!!!!!!')\n\n\n\n\n\tif t_time.dtype.name.startswith('datetime64') or t_time.dtype is np.dtype(\"O\"):\n\t\tt_time = tm.date2num(t_time)\n\n\tt_time = t_time.reshape(-1, 1)\n\n\n\n\tsnr = (tidecon[:, 0,0] / tidecon[:, 1,0]) ** 2\n\tI = snr > 2\n\n\t\n\ttidecon = tidecon[I, :]\n\tju = np.asarray(ju)[I]\n\tfreq = freq[I]\n\n\n\tap = np.multiply(tidecon[:, 0] / 2.0,np.exp(-1j * tidecon[:, 2] * np.pi / 180))\n\tam = np.conj(ap)\n\n\n\tjdmid = np.mean(t_time[0:((2 * int((max(t_time.shape) - 1) / 2)) + 1)])\n\n\tv, u, f = t_vuf('nodal', jdmid, ju, lat0)\n\n\tap = ap * np.kron(np.ones((ap.shape[1],1)),f * np.exp(+1j * 2 * np.pi * (u + v))).T\n\tam = am * np.kron(np.ones((ap.shape[1],1)),f * np.exp(-1j * 2 * np.pi * (u + v))).T\n\n\tt_time = t_time - jdmid\n\n\tn, m = t_time.shape\n\tyout = np.zeros([ap.shape[1], 1], dtype='complex128')\n\ttouter = np.outer(24 * 1j * 2 * np.pi * freq, t_time[0])\n\n\ttouter=np.kron(np.ones((1,ap.shape[1])),touter)\n\n\tyout[:,0]=np.sum(np.multiply(np.exp(touter), ap), axis=0)+np.sum(np.multiply(np.exp(-touter), am), axis=0)\n\n\ttide=np.real(yout)\n\n\n\treturn tide\n","sub_path":"pre-processing/core/tidal_tools_old.py","file_name":"tidal_tools_old.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"553365388","text":"from django.urls import path\nfrom . import views\n\napp_name = \"turniket\"\n\nurlpatterns = [\n    path('', views.index, name='index'),\n    path('filter/', views.filter, name='filter'),\n    path('addperm/', views.addperm, name='addperm'),\n    path('exportreport/', views.exportreport, name='exportreport'),\n    path('addshortday/', views.addshortday, name='addshortday'),\n]","sub_path":"turniket/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"22102490","text":"# **********************************************************************\n#\n# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.\n#\n# This copy of Ice is licensed to you under the terms described in the\n# ICE_LICENSE file included in this distribution.\n#\n# **********************************************************************\n#\n# Ice version 3.4.2\n#\n# \n#\n# Generated from file `FileInfo.ice'\n#\n# Warning: do not edit this file.\n#\n# \n#\n\nimport Ice, IcePy, __builtin__\nimport Ice_BuiltinSequences_ice\n\n# Included module Ice\n_M_Ice = Ice.openModule('Ice')\n\n# Start of module IcePatch2\n_M_IcePatch2 = Ice.openModule('IcePatch2')\n__name__ = 'IcePatch2'\n\nif not _M_IcePatch2.__dict__.has_key('FileInfo'):\n    _M_IcePatch2.FileInfo = Ice.createTempClass()\n    class FileInfo(object):\n        '''Basic information about a single file.'''\n        def __init__(self, path='', checksum=None, size=0, executable=False):\n            self.path = path\n            self.checksum = checksum\n            self.size = size\n            self.executable = executable\n\n        def __hash__(self):\n            _h = 0\n            _h = 5 * _h + __builtin__.hash(self.path)\n            if self.checksum:\n                for _i0 in self.checksum:\n                    _h = 5 * _h + __builtin__.hash(_i0)\n            _h = 5 * _h + __builtin__.hash(self.size)\n            _h = 5 * _h + __builtin__.hash(self.executable)\n            return _h % 0x7fffffff\n\n        def __lt__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path < other.path or self.checksum < other.checksum or self.size < other.size or self.executable < other.executable\n            elif other == None:\n                return False\n            return NotImplemented\n\n        def __le__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path <= other.path or self.checksum <= other.checksum or self.size <= other.size or self.executable <= other.executable\n            elif other == None:\n                return False\n            return NotImplemented\n\n        def __eq__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path == other.path and self.checksum == other.checksum and self.size == other.size and self.executable == other.executable\n            elif other == None:\n                return False\n            return NotImplemented\n\n        def __ne__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path != other.path or self.checksum != other.checksum or self.size != other.size or self.executable != other.executable\n            elif other == None:\n                return True\n            return NotImplemented\n\n        def __gt__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path > other.path or self.checksum > other.checksum or self.size > other.size or self.executable > other.executable\n            elif other == None:\n                return False\n            return NotImplemented\n\n        def __ge__(self, other):\n            if isinstance(other, _M_IcePatch2.FileInfo):\n                return self.path >= other.path or self.checksum >= other.checksum or self.size >= other.size or self.executable >= other.executable\n            elif other == None:\n                return False\n            return NotImplemented\n\n        def __str__(self):\n            return IcePy.stringify(self, _M_IcePatch2._t_FileInfo)\n\n        __repr__ = __str__\n\n    _M_IcePatch2._t_FileInfo = IcePy.defineStruct('::IcePatch2::FileInfo', FileInfo, (), (\n        ('path', (), IcePy._t_string),\n        ('checksum', (), _M_Ice._t_ByteSeq),\n        ('size', (), IcePy._t_int),\n        ('executable', (), IcePy._t_bool)\n    ))\n\n    _M_IcePatch2.FileInfo = FileInfo\n    del FileInfo\n\nif not _M_IcePatch2.__dict__.has_key('_t_FileInfoSeq'):\n    _M_IcePatch2._t_FileInfoSeq = IcePy.defineSequence('::IcePatch2::FileInfoSeq', (), _M_IcePatch2._t_FileInfo)\n\n# End of module IcePatch2\n\nIce.sliceChecksums[\"::IcePatch2::FileInfo\"] = \"4c71622889c19c7d3b5ef8210245\"\nIce.sliceChecksums[\"::IcePatch2::FileInfoSeq\"] = \"892945a7a7bfb532f6148c4be9889bd\"\n","sub_path":"python/Ice/IcePatch2_FileInfo_ice.py","file_name":"IcePatch2_FileInfo_ice.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"647353029","text":"\"\"\"\nProvides a Swagger (http://swagger.wordnik.com/) implementation\nfor flask-peewee rest apis.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport logging, peewee\nimport os\nfrom flask import jsonify, Blueprint, render_template\nfrom flask.globals import request\nfrom flask.ext.peewee_swagger import first\n\nlogger = logging.getLogger('flask_peewee_swagger')\ncurrent_dir = os.path.dirname(__file__)\n\nclass SwaggerUI(object):\n    \"\"\" Adds a flask blueprint for the swagger ajax UI. \"\"\"\n\n    def __init__(self, app, title='api docs', prefix='/api-docs'):\n        super(SwaggerUI, self).__init__()\n\n        self.app = app\n        self.title = title\n        self.url_prefix = prefix\n\n        self.blueprint = Blueprint('SwaggerUI', __name__,\n                                   static_folder=os.path.join(current_dir, 'static'),\n                                   template_folder=os.path.join(current_dir, 'templates'))\n\n    def setup(self):\n        self.blueprint.add_url_rule('/', 'index', self.index)\n        self.app.register_blueprint(self.blueprint, url_prefix=self.url_prefix)\n\n    def index(self):\n        return render_template('swagger.jinja2',\n                               static_dir='%s/static' % self.url_prefix,\n                               title=self.title)\n\n\nclass Swagger(object):\n    \"\"\" Adds a flask blueprint for the swagger meta json resources. \"\"\"\n\n    def __init__(self, api, name='Swagger'):\n        super(Swagger, self).__init__()\n\n        self.app = api.app\n        self.api = api\n\n        self.blueprint = Blueprint(name, __name__)\n\n    def setup(self):\n        self.configure_routes()\n        self.app.register_blueprint(self.blueprint,\n            url_prefix='%s/meta' % self.api.url_prefix)\n\n    def configure_routes(self):\n        self.blueprint.add_url_rule('/resources', 'model_resources', self.model_resources)\n        self.blueprint.add_url_rule('/resources/', 'model_resource', self.model_resource)\n\n    def base_uri(self):\n        base_uri = request.host_url\n        if base_uri.endswith('/'):\n            base_uri = base_uri[0:-1]\n        return base_uri\n\n    def model_resources(self):\n        \"\"\" Listing of all supported resources. \"\"\"\n\n        response = jsonify({\n            'apiVersion': '0.1',\n            'swaggerVersion': '1.1',\n            'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),\n            'apis': self.get_model_resources()\n        })\n\n        response.headers.add('Cache-Control', 'max-age=0')\n        return response\n\n    def get_model_resources(self):\n        resources = []\n\n        for type in sorted(self.api._registry.keys(),\n            key=lambda type: type.__name__):\n            resource = self.api._registry.get(type)\n            resources.append({\n                'path': '/meta/resources/%s' % resource.get_api_name(),\n                'description': 'Managed objects of type %s' % type.__name__\n            })\n\n        return resources\n\n    def model_resource(self, resource_name):\n        \"\"\" Details of a specific model resource. \"\"\"\n\n        resource = first(\n            [resource for resource in self.api._registry.values()\n             if resource.get_api_name() == resource_name])\n\n        data = {\n            'apiVersion': '0.1',\n            'swaggerVersion': '1.1',\n            'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),\n            'resourcePath': '/meta/%s' % resource.get_api_name(),\n            'apis': self.get_model_apis(resource),\n            'models': self.get_model(resource)\n        }\n        response = jsonify(data)\n        response.headers.add('Cache-Control', 'max-age=0')\n        return response\n\n    def get_model_apis(self, resource):\n        return (\n            self.get_listing_api(resource), \n            self.get_item_api(resource), \n            self.get_create_api(resource), \n            self.get_update_api(resource),\n            self.get_delete_api(resource)\n        )\n\n    def get_create_api(self, resource):\n        \"\"\" Generates the meta descriptor for the resource listing api. \"\"\"\n\n        create_api = {\n            'path': '/%s/' % resource.get_api_name(),\n            'description': 'Operations on %s' % resource.model.__name__,\n            'operations': [\n                {\n                    'httpMethod': 'POST',\n                    'nickname': 'create%ss' % resource.model\n                    .__name__,\n                    'summary': 'Create %ss' % resource.model.__name__,\n                    'parameters': [{\n                        'description': '%s object' % (resource.model.__name__),\n                        'paramType': 'body',\n                        'required': True,\n                        'allowMultiple': False,\n                        'dataType': resource.model.__name__\n                    }]\n                }\n            ]\n        }\n\n        return create_api\n\n    def get_update_api(self, resource):\n        \"\"\" Generates the meta descriptor for the resource listing api. \"\"\"\n\n        update_api = {\n            'path': '/%s/{id}/' % resource.get_api_name(),\n            'description': 'Operations on %s' % resource.model.__name__,\n            'operations': [\n                {\n                    'httpMethod': 'PUT',\n                    'nickname': 'update%ss' % resource.model\n                    .__name__,\n                    'summary': 'Update %ss' % resource.model.__name__,\n                    'parameters': [\n                        {\n                            'paramType': 'path', \n                            'name': 'id',\n                            'description': '%s id' % (resource.model.__name__),\n                            'dataType': 'int',\n                            'required': True,\n                            'allowMultiple': False,\n                        },\n                        {\n                            'description': '%s object' % (resource.model.__name__),\n                            'paramType': 'body',\n                            'required': True,\n                            'allowMultiple': False,\n                            'dataType': resource.model.__name__\n                        }\n                    ]\n                }\n            ]\n        }\n\n        return update_api\n\n    def get_listing_api(self, resource):\n        \"\"\" Generates the meta descriptor for the resource listing api. \"\"\"\n\n        get_all_params = self.get_listing_parameters(resource)\n\n        get_all_api = {\n            'path': '/%s/' % resource.get_api_name(),\n            'description': 'Operations on %s' % resource.model.__name__,\n            'operations': [\n                {\n                    'httpMethod': 'GET',\n                    'nickname': 'list%ss' % resource.model\n                    .__name__,\n                    'summary': 'Find %ss' % resource.model.__name__,\n                    'parameters': get_all_params,\n                }\n            ]\n        }\n\n        return get_all_api\n\n    def get_listing_parameters(self, resource):\n        params = []\n\n        for field_name in sorted(resource.model._meta.fields.keys()):\n            field = resource.model._meta.fields.get(field_name)\n            parameter = self.get_model_field_parameter(resource, field)\n            if parameter:\n                params.append(parameter)\n\n\n        params.append({\n            'paramType': 'query',\n            'name': 'limit',\n            'description': 'The number of items to return (defaults to %s)' % resource.paginate_by,\n            'dataType': 'int',\n            'required': False,\n            'allowMultiple': False,\n        })\n\n        params.append({\n            'paramType': 'query',\n            'name': 'page',\n            'description': 'The page number of the results to return. Used '\n                           'with limit.',\n            'dataType': 'int',\n            'required': False,\n            'allowMultiple': False,\n        })\n\n        return params\n\n    def get_model(self, resource):\n        properties = {}\n        for field_name in sorted(resource.model._meta.fields.keys()):\n            field = resource.model._meta.fields.get(field_name)\n            model_property = self.get_model_property(resource, field)\n            if model_property:\n                properties[field_name] = model_property\n\n        return {\n            resource.model.__name__:{\n                'id':resource.model.__name__,\n                'properties':properties\n            }\n        }\n\n    def get_model_property(self, resource, field):\n        data_type = 'int'\n        if isinstance(field, peewee.CharField):\n            data_type = 'string'\n        elif isinstance(field, peewee.DateTimeField):\n            data_type = 'Date'\n        elif isinstance(field, peewee.FloatField):\n            data_type = 'float'\n        elif isinstance(field, peewee.BooleanField):\n            data_type = 'boolean'\n        property = {\n            'type':data_type,\n        }\n        return property\n\n    def get_model_field_parameter(self, resource, field):\n        data_type = 'int'\n        if isinstance(field, peewee.CharField):\n            data_type = 'string'\n        elif isinstance(field, peewee.DateTimeField):\n            data_type = 'Date'\n        elif isinstance(field, peewee.FloatField):\n            data_type = 'float'\n        elif isinstance(field, peewee.BooleanField):\n            data_type = 'boolean'\n        parameter = {\n            'paramType': 'query', 'name': field.name,\n            'description': 'Filter by %s' % field.name,\n            'dataType': data_type, 'required': False,\n            'allowMultiple': False,\n        }\n        return parameter\n\n    def get_item_api(self, resource):\n        \"\"\" Generates the meta descriptor for the resource item api. \"\"\"\n\n        parameters = self.get_item_parameters(resource)\n\n        get_item_api = {\n            'path': '/%s/{id}' % resource.get_api_name(),\n            'description': 'Operations on %s' % resource.model.__name__,\n            'operations': [\n                {\n                    'httpMethod': 'GET',\n                    'nickname': 'get%s' % resource.model.__name__,\n                    'summary': 'Get %s by its unique ID' %\n                               resource.model.__name__,\n                    'parameters': parameters,\n                }\n            ]\n        }\n\n        return get_item_api\n\n    def get_item_parameters(self, resource):\n        return [{\n            'paramType': 'path',\n            'name': 'id',\n            'description': 'ID of %s to be fetched' % resource.model.__name__,\n            'dataType': 'int',\n            'required': True,\n            'allowMultiple': False,\n        }]\n\n    def get_delete_api(self, resource):\n        \"\"\" Generates the meta descriptor for the resource item api. \"\"\"\n\n        parameters = self.delete_item_parameters(resource)\n\n        get_item_api = {\n            'path': '/%s/{id}/' % resource.get_api_name(),\n            'description': 'Operations on %s' % resource.model.__name__,\n            \"responseClass\": \"void\",\n            'operations': [\n                {\n                    'httpMethod': 'DELETE',\n                    'nickname': 'delete%s' % resource.model.__name__,\n                    'summary': 'Delete %s by its unique ID' %\n                               resource.model.__name__,\n                    'parameters': parameters,\n                }\n            ]\n        }\n\n        return get_item_api\n\n    def delete_item_parameters(self, resource):\n        return [{\n            'paramType': 'path',\n            'name': 'id',\n            'description': 'ID of %s to be fetched' % resource.model.__name__,\n            'dataType': 'int',\n            'required': True,\n            'allowMultiple': False,\n        }]\n\n        return delete_item_api\n\n\n","sub_path":"flask_peewee_swagger/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":11718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"346472441","text":"import os\nimport sys\nimport time\nimport linecache\nfrom bisect import insort\nfrom collections import defaultdict, namedtuple\n\n\ndef find_utr_regions(trans_id, trans_sense, trans_exons, trans_cds):\n\n    if not trans_cds:\n        trans_5utr, trans_3utr, start_codon, stop_codon = [], [], tuple(), tuple()\n        return trans_5utr, trans_3utr, start_codon, stop_codon\n\n    if trans_sense not in {\"+\", \"-\"}:\n        print(f'WARNING: Strand error for transcript \"{trans_id}\" ({trans_sense})')\n        return None, None, None, None\n\n    flat = lambda l: [e for sub in l for e in sub]\n    group_by_pair = lambda l: [e for e in zip(l[::2], l[1::2])]\n\n    trans_exons = flat(trans_exons)\n    trans_exons_set = set(trans_exons)\n    trans_cds = flat(trans_cds)\n\n    if trans_sense == \"+\":\n        # 5' UTR for FORWARD strands\n        start = trans_cds[0]\n        exons_subset = [exon for exon in trans_exons if exon < start]\n        if exons_subset:\n            if start in trans_exons_set:\n                trans_5utr = exons_subset\n            else:\n                trans_5utr = exons_subset + [start-1]\n        else:\n            trans_5utr = []\n\n        if not len(trans_5utr) % 2 == 0:\n            trans_5utr = trans_5utr + [start-1]\n\n        # 3' UTR for FORWARD strands\n        stop = trans_cds[-1]\n        exons_subset = [exon for exon in trans_exons if exon > stop]\n        if exons_subset:\n            if stop in trans_exons_set:\n                trans_3utr = exons_subset\n            else:\n                trans_3utr = [stop+1] + exons_subset\n        else:\n            trans_3utr = []\n\n        if not len(trans_3utr) % 2 == 0:\n            trans_3utr = [stop+1] + trans_3utr\n\n        start_codon = (start, start + 2)\n        stop_codon = (stop - 2, stop)\n\n    elif trans_sense == \"-\":\n        # 5' UTR for REVERSE strands\n        start = trans_cds[-1]\n        exons_subset = [exon for exon in trans_exons if exon > start]\n        if exons_subset:\n            if start in trans_exons_set:\n                trans_5utr = exons_subset\n            else:\n                trans_5utr = [start+1] + exons_subset\n        else:\n            trans_5utr = []\n\n        if not len(trans_5utr) % 2 == 0:\n            trans_5utr = [start+1] + trans_5utr\n\n        # 3' UTR for REVERSE strands\n        stop = trans_cds[0]\n        exons_subset = [exon for exon in trans_exons if exon < stop]\n        if exons_subset:\n            if stop in trans_exons_set:\n                trans_3utr = exons_subset\n            else:\n                trans_3utr = exons_subset + [stop-1]\n        else:\n            trans_3utr = []\n\n        if not len(trans_3utr) % 2 == 0:\n            trans_3utr = trans_3utr + [stop-1]\n\n        start_codon = (start - 2, start)\n        stop_codon = (stop, stop + 2)\n\n    else:\n        print(f'Transcript \"{trans_id}\" does not present a valid strand (\"{trans_sense}\")')\n        return [], [], (), ()\n\n    # TODO, answer these questions:\n    #  Is it possible that a Start/Stop codon are formed after splicing, and thus its coordinates belong to 2 diff exons\n    #  If so, should I check that all 3 bp of codon are contained inside the same exon?\n\n    trans_5utr = group_by_pair(sorted(trans_5utr))\n    trans_3utr = group_by_pair(sorted(trans_3utr))\n\n    return trans_5utr, trans_3utr, start_codon, stop_codon\n\n\ndef get_id(gtf_line, tag):\n\n    # Warning messages can introduce too much noise in the output, thus we silence them for now\n    print_warning = False\n    if tag not in gtf_line:\n        if print_warning:\n            print(f'Warning! No instance of tag \"{tag}\" found on line:')\n            print(f\"{gtf_line}\")\n        return None\n\n    splitted = gtf_line.strip('\\n').split(tag)\n\n    # Some lines may contain multiple instances of the \"splitting tag\"; ex: it contains both \"gene_id\" AND \"ref_gene_id\"\n    # Generally, in the GTF files the desired tag is the first one (\"gene_id\" come always before \"ref_gene_id\")\n    if len(splitted) != 2:\n        if print_warning:\n            print(f'WARNING: Multiple matches of tag \"{tag}\" found on line:')\n            print(f\"{gtf_line}\")\n        pass\n\n    # This always seems to be the case\n    end_tag = '\";'\n\n    res_id = splitted[1].split(end_tag)[0]\n\n    # TODO quick fix of bug where \" character remains at the end of transcript_ids after RTD re-annotation step\n    res_id = res_id.replace('\"', '')\n\n    return res_id\n\n\ndef add_tag(gtf_line, tag=None):\n\n    # If no tag is given, return the gtf_line unchanged\n    # This is necessary when using the \"split_redundancy_removal\" method to avoid redundant re-tagging of GTF lines\n    if not tag:\n        return gtf_line\n\n    if 'gene_id \"' not in gtf_line or 'transcript_id \"' not in gtf_line:\n        return gtf_line\n\n    # Add \"_\" separator to tag if not present\n    if not tag.startswith(\"_\"):\n        tag = f\"_{tag}\"\n\n    # Avoid re-annotating a line that has already been tagged\n    try:\n        if tag in gtf_line:\n            return gtf_line\n    except TypeError:\n        # Previous check make this redundant, but better be safe than sorry\n        sys.exit(\"Tag cannot be 'None'\")\n\n    # Important: some lines have a \"ref_gene_id\" tag, this screw up the gene_id, this is handled by get_id method\n    gene_id = get_id(gtf_line, 'gene_id \"')\n    trans_id = get_id(gtf_line, 'transcript_id \"')\n\n    # Important: Replace only the first instance found! This is necessary to NOT re-annotate \"ref_gene_id\" IDs\n    temp_line = gtf_line.replace(f'gene_id \"{gene_id}', f'gene_id \"{gene_id + tag}', 1)\n    tagged_line = temp_line.replace(f'transcript_id \"{trans_id}', f'transcript_id \"{trans_id + tag}', 1)\n\n    return tagged_line\n\n\ndef parse_gtf(gtf_file, tag=None, verb=False):\n\n    with open(gtf_file) as fh:\n        for i, line in enumerate(fh):\n\n            # Some assemblies/annotations (Ex: stringtie, TAIR10) start with headers, ignore these lines\n            if not line or line.startswith(\"#\"):\n                continue\n\n            # If tag is not given (None), add_tag() return the line unchanged\n            line = add_tag(line, tag)\n\n            # TODO the current approach is to disregard the offending row, but it may be better to remove the transcript\n            if 'gene_id \"' not in line or 'transcript_id \"' not in line:\n                if verb:\n                    print(f'WARNING: Row {i} of {gtf_file} does not contain a gene or transcript ID')\n                    print(f\"{line}\")\n                continue\n\n            # GTF line format: seqname, source, feature, start, end, score, strand, frame, attr\n            gtf_row = line.strip('\\n').split('\\t')\n            if len(gtf_row) != 9:\n                if verb:\n                    print(f'WARNING: Row {i} of {gtf_file} does not contain a gene or transcript ID')\n                    print(f\"{line}\")\n                continue\n\n            yield gtf_row\n\n\ndef create_gtf_object(gtf_file, to_keep=None, tag=None, verb=False):\n\n    if verb:\n        print(time.asctime(), f'Uploading information from annotation file: {gtf_file}')\n\n    # TODO the parsing and creation of GTF_object can be slow for large GTF_files,\n    #  perhaps it can be faster with Cython or PyPY?\n\n    # Structure of the GTF object\n    GTF = namedtuple('GTF',\n                     'gtf_path '\n                     'chrom_gene_dt chrom_trans_dt '\n                     'gene_coords_dt gene_trans_dt gene_name_dt '\n                     'trans_chrom_dt trans_gene_dt trans_sense_dt '\n                     'trans_exons_dt trans_introns_dt trans_cds_dt trans_5utr_dt trans_3utr_dt '\n                     'trans_start_codon trans_stop_codon '\n                     'trans_gtf_lines_index')\n\n    # Initialize data structures to store relational-information of interest\n    chrom_gene_dt, chrom_trans_dt, gene_trans_dt = [defaultdict(set) for _ in range(3)]\n\n    trans_exons_dt, trans_introns_dt, trans_cds_dt, trans_5utr_dt, trans_3utr_dt, \\\n    trans_gtf_lines_index = [defaultdict(list) for _ in range(6)]\n\n    gene_name_dt = defaultdict(str)\n\n    gene_coords_dt, trans_chrom_dt, trans_gene_dt, \\\n    trans_sense_dt, trans_start_codon_dt, trans_stop_codon_dt = [{} for _ in range(6)]\n\n    # This create a Transcript_Id to row position in a file, so as to recover the relevant lines when necessary\n    # Important! As the row number must represent the number in the original file, this check must be done here\n    # as further ignore invalid rows (and thus the row number would be skipped)\n    with open(gtf_file) as fh:\n        for line_ix, line in enumerate(fh, 1):\n\n            # If tag is not given (None), add_tag() return the line unchanged\n            line = add_tag(line, tag)\n\n            if 'transcript_id \"' not in line:\n                continue\n            else:\n                trans_id = get_id(line, 'transcript_id \"')\n                trans_gtf_lines_index[trans_id].append(line_ix)\n\n    # As it is a generator, it is not convenient to put the print statement inside the method\n    if verb:\n        print(time.asctime(), f'Parsing annotation file: {gtf_file}')\n\n    # Line indexing must start from 1 for the linecache.getline() function\n    for line_obj in parse_gtf(gtf_file, tag):\n        # line_obj (GTF row) is a list with the following format:\n        seqname, source, feature, start, end, score, strand, frame, attr = line_obj\n\n        gene_id = get_id(attr, 'gene_id \"')\n        trans_id = get_id(attr, 'transcript_id \"')\n\n        # If there is a subset to keep, ignore the others\n        if to_keep:\n            if trans_id not in to_keep:\n                continue\n\n        # Uniquely ID each strand by pairing it to its scaffold. Ex: Chrom01+, Chrom01-, Chrom02+,  etc\n        genomic_strand = f'{seqname}{strand}'\n\n        # Get Gene Name and gene description (Note) if available\n        if 'gene_name \"' in attr:\n            gene_name = get_id(attr, 'gene_name \"')\n            gene_name_dt[gene_id] = gene_name\n        if 'Note \"' in attr:\n            gene_note = get_id(attr, 'Note \"')\n            gene_name_dt[gene_id] += \" \" + gene_note\n\n        gene_trans_dt[gene_id].add(trans_id)\n        chrom_gene_dt[genomic_strand].add(gene_id)\n        chrom_trans_dt[genomic_strand].add(trans_id)\n\n        trans_gene_dt[trans_id] = gene_id\n        trans_sense_dt[trans_id] = strand\n        trans_chrom_dt[trans_id] = genomic_strand\n\n        # Ensure that start/ end are in order (start < end)\n        start, end = int(start), int(end)\n        start, end = min(start, end), max(start, end)\n        coord_pair = (start, end)\n\n        # Many functions downstream assume these list of coordinates are sorted. Thus the use of insort to add elements\n        if feature == 'exon':\n            # Important! Newly assembled GTF may contain repeated lines/rows. Thus, check if info is already present!\n            if coord_pair not in trans_exons_dt[trans_id]:\n                insort(trans_exons_dt[trans_id], coord_pair)\n\n        if feature == 'CDS':\n            if coord_pair not in trans_cds_dt[trans_id]:\n                insort(trans_cds_dt[trans_id], coord_pair)\n\n        if feature == 'five_prime_utr':\n            if coord_pair not in trans_5utr_dt[trans_id]:\n                insort(trans_5utr_dt[trans_id], coord_pair)\n\n        if feature == 'three_prime_utr':\n            if coord_pair not in trans_3utr_dt[trans_id]:\n                insort(trans_3utr_dt[trans_id], coord_pair)\n\n        if feature == 'start_codon':\n            trans_start_codon_dt[trans_id] = coord_pair\n\n        if feature == 'stop_codon':\n            trans_stop_codon_dt[trans_id] = coord_pair\n\n    # Important! Some annotations may report only CDS coordinates of a transcript, and doesn't report them also as exons\n    # For the program to work, it is necessary to identify these coordinates both as CDS and exons!\n    for trans_id in trans_gene_dt.keys():\n        if not trans_exons_dt[trans_id] and trans_cds_dt[trans_id]:\n            trans_exons_dt[trans_id] = trans_cds_dt[trans_id]\n\n    # Generate missing feature information (Coordinates for: introns, 5'-3' UTR regions, start/stop codons)\n    get_introns = lambda exons: [(ex1[-1]+1, ex2[0]-1) for (ex1, ex2) in zip(exons[:-1], exons[1:])]\n\n    for trans_id, trans_exons in trans_exons_dt.items():\n        trans_sense = trans_sense_dt[trans_id]\n\n        # Generate Intron information\n        trans_introns = get_introns(trans_exons)\n        trans_introns_dt[trans_id] = trans_introns\n\n        # Generate UTR information if possible\n        trans_cds = trans_cds_dt[trans_id]\n        if trans_cds:\n            trans_5utr, trans_3utr, start_codon, stop_codon = \\\n                find_utr_regions(trans_id, trans_sense, trans_exons, trans_cds)\n\n            if not trans_5utr_dt[trans_id] and trans_5utr:\n                trans_5utr_dt[trans_id] = trans_5utr\n\n            if not trans_3utr_dt[trans_id] and trans_3utr:\n                trans_3utr_dt[trans_id] = trans_3utr\n\n            try:\n                trans_start = trans_start_codon_dt[trans_id]\n            except KeyError:\n                if start_codon:\n                    trans_start_codon_dt[trans_id] = start_codon\n                else:\n                    trans_start_codon_dt[trans_id] = tuple()\n\n            try:\n                trans_stop = trans_stop_codon_dt[trans_id]\n            except KeyError:\n                if stop_codon:\n                    trans_stop_codon_dt[trans_id] = stop_codon\n                else:\n                    trans_stop_codon_dt[trans_id] = tuple()\n\n    # It is posssible for incorrectly annotated transcriptomes to have transcript without any annotated exon-coordinates\n    missing_exons = set()\n    for t_id, t_exons in trans_exons_dt.items():\n        if not t_exons:\n            missing_exons.add(t_id)\n\n    if missing_exons:\n        if verb:\n            print(f'WARNING: File {os.path.basename(gtf_file)} contains \"{len(missing_exons)}\" '\n                  f'transcripts without annotated exon-coordinates. These models will be ignored.')\n\n        no_exons = os.path.join(os.path.dirname(gtf_file),\n                                os.path.basename(gtf_file).replace(\".gtf\", \"_missing_exons.csv\"))\n        with open(no_exons, \"a+\") as fh:\n            fh.write(f\"Transcript_ID\\n\")\n            for t_id in sorted(missing_exons):\n                fh.write(f\"{t_id}\\n\")\n\n    # Annotate Genes start/end Coordinates\n    flat = lambda l: [item for sublist in l for item in sublist]\n\n    for gene, trans_list in gene_trans_dt.items():\n        starts, ends = (set() for _ in range(2))\n        for t_id in trans_list:\n            trans_exons = flat(trans_exons_dt[t_id])\n\n            # If there are transcripts without exons, this method will run again ignoring those models,\n            # thus we skip this error on the current iteration to allow this method to continue on the first iteration\n            if not trans_exons:\n                continue\n\n            starts.add(trans_exons[0])\n            ends.add(trans_exons[-1])\n\n        if starts and ends:\n            gene_coords_dt[gene] = (min(starts), max(ends))\n\n    # Create a GTF object with the parsed and generated information\n    gtf_object = GTF(gtf_path=gtf_file,\n                     chrom_gene_dt=chrom_gene_dt, chrom_trans_dt=chrom_trans_dt,\n                     gene_coords_dt=gene_coords_dt, gene_trans_dt=gene_trans_dt, gene_name_dt=gene_name_dt,\n                     trans_chrom_dt=trans_chrom_dt, trans_gene_dt=trans_gene_dt, trans_sense_dt=trans_sense_dt,\n                     trans_exons_dt=trans_exons_dt, trans_introns_dt=trans_introns_dt, trans_cds_dt=trans_cds_dt,\n                     trans_5utr_dt=trans_5utr_dt, trans_3utr_dt=trans_3utr_dt,\n                     trans_start_codon=trans_start_codon_dt, trans_stop_codon=trans_stop_codon_dt,\n                     trans_gtf_lines_index=trans_gtf_lines_index)\n\n    # If there are incorrectly annotated transcripts without exons, run the method again while ignoring incorrect models\n    if missing_exons:\n        to_keep = set(gtf_object.trans_exons_dt.keys()) - missing_exons\n        gtf_object = create_gtf_object(gtf_file, to_keep=to_keep)\n\n    return gtf_object\n\n\ndef write_gtf(gtf_obj, transcripts, outfolder, outname, w_mode=\"w+\", all_t=False, verb=False):\n\n    # Create an output folder if it doesnt exist\n    if not os.path.isdir(outfolder):\n        os.makedirs(outfolder)\n\n    outfile = os.path.join(outfolder, outname)\n\n    # Sort transcripts by the key (Chrom, Gene_ID, Trans_ID, Leftmost_coordinate)\n    get_sort_key = lambda t_id: (gtf_obj.trans_chrom_dt[t_id], gtf_obj.trans_gene_dt[t_id], t_id,\n                                 gtf_obj.trans_exons_dt[t_id][0][0])\n\n    if all_t:\n        if verb:\n            print(time.asctime(), \"Including all transcripts from input annotation into the output file\")\n        transcripts = set(gtf_obj.trans_exons_dt.keys())\n\n    # TODO, writing large files is a bit slow, it could be due to sort or linecache, look how to speed up the process\n\n    sorted_transcripts = sorted(transcripts, key=lambda t_id: get_sort_key(t_id))\n\n    if verb:\n        print(time.asctime(), f'Writing output file: {outfile}')\n    with open(outfile, w_mode) as fh:\n        for trans_id in sorted_transcripts:\n            if trans_id in transcripts:\n                for line_ix in gtf_obj.trans_gtf_lines_index[trans_id]:\n                    line = linecache.getline(gtf_obj.gtf_path, line_ix)\n                    fh.write(line)\n\n    return outfile\n","sub_path":"RTDmaker/lib/parsing/gtf_object_tools.py","file_name":"gtf_object_tools.py","file_ext":"py","file_size_in_byte":17345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"194715942","text":"#!/usr/bin/env python\n \nimport os, csv\n\nhomePath = '/Users/swmo/data/'\n\nftrain = open(homePath + 'wp/wp_cbandit_train.tsv', 'w')\nfvalid = open(homePath + 'wp/wp_cbandit_valid.tsv', 'w')\n\nt0 = t1 = v0 = v1 = 0\nused_pid = []\nwith open(homePath + 'wp/wp_cbandit_unique_user.tsv') as tsv:\n\tfor line in csv.reader(tsv, delimiter='\\t'):\n\t\tnew_pid = int(line[1])\n\t\tif new_pid in used_pid: continue\n\t\t\n\t\ts = line[1] + '\\t' + line[0] + '\\t' + line[2] + '\\n'\n\t\t\n\t\tif int(line[2]) == 0:\n\t\t\tif t0 < 500:\n\t\t\t\tftrain.write(s)\n\t\t\t\tt0 = t0 + 1\n\t\t\telif v0 < 50:\n\t\t\t\tfvalid.write(s)\n\t\t\t\tv0 = v0 + 1\n\n\t\tif int(line[2]) == 1:\n\t\t\tif t1 < 500:\n\t\t\t\tftrain.write(s)\n\t\t\t\tt1 = t1 + 1\n\t\t\telif v1 < 50:\n\t\t\t\tfvalid.write(s)\n\t\t\t\tv1 = v1 + 1","sub_path":"make_data/cbandit_unique.py","file_name":"cbandit_unique.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"34884918","text":"import pymongo\nimport pandas as pd\nimport numpy as np\nimport json\nimport requests\n\nimport sqlite3\ncur = sqlite3.connect('database.sqlite').cursor()\n\ndef get_season_games(season):\n    wanted_match_df = pd.DataFrame(cur.execute(f\"\"\"SELECT HomeTeam, AwayTeam, Div AS league, Season, \n                                                        FTHG, FTAG, FTR, Date\n                                                    FROM matches\n                                                    WHERE season == {season} AND (league = 'E0' OR league = 'D1')\n                                                    \"\"\").fetchall())\n    wanted_match_df.columns = [x[0] for x in cur.description]\n    return wanted_match_df\n\ndef get_rainy(time):\n    api_key = json.load(open ('pwds.json'))\n    url = f'https://api.darksky.net/forecast/{api_key[\"api_key\"]}/52.5200,13.4050,{time}T12:00:00'\n    response = requests.get(url)\n    data = json.loads(response.text)\n    if 'daily' in data.keys():\n        if 'data' in data['daily'].keys():\n            if 'icon' in data['daily']['data'][0].keys():\n                return 'rain' in data['daily']['data'][0]['icon']\n    return False\n\ndef add_rainy(df):\n    rain_frame = df.copy()\n    rainy = []\n    for date in rain_frame['Date']:\n        rainy.append(get_rainy(date))\n    rain_frame['rainy'] = rainy\n    return rain_frame\n\ndef total_goals(team, dataframe):\n    home_goals = dataframe.loc[dataframe['HomeTeam'] == team]['FTHG'].sum()\n    away_goals = dataframe.loc[dataframe['AwayTeam'] == team]['FTAG'].sum() \n    return home_goals + away_goals\n\ndef total_wins(team, dataframe):\n    home_wins = len(dataframe.loc[dataframe['HomeTeam'] == team].loc[dataframe['FTR'] == 'H'])\n    away_wins = len(dataframe.loc[dataframe['AwayTeam'] == team].loc[dataframe['FTR'] == 'A'])\n    return home_wins + away_wins\n\ndef rain_percent(team, df):\n    home = df.loc[df['HomeTeam'] == team].loc[df['rainy'] == True]\n    away = df.loc[df['AwayTeam'] == team].loc[df['rainy'] == True]\n    wins = len(home.loc[home['FTR'] == 'H']) + len(away.loc[away['FTR'] == \"A\"])\n    total_games = len(home) + len(away)\n    if total_games == 0:\n        return 0\n    return wins / total_games\n\ndef get_stats(dataframe):\n    columns=['Team Name', 'League', 'Season', 'Wins', 'Goals', 'Win Percentage on Rainy Days']\n    df_list = []\n    for team in set(list(dataframe['HomeTeam']) + list(dataframe['AwayTeam'])):\n        league1 = dataframe.loc[dataframe['HomeTeam'] == team]\n        league2 = dataframe.loc[dataframe['AwayTeam'] == team]\n        league = pd.concat([league2, league1])\n        season = dataframe['Season'][0]\n        df_list.append([team, league['league'].iloc[0], season, total_wins(team, dataframe), total_goals(team, dataframe),\n                        rain_percent(team, dataframe)])\n    return pd.DataFrame(df_list, columns=columns)\n\ndef mongo_handler(stats_df):\n    password = json.load(open ('pwds.json'))\n    client = pymongo.MongoClient(f\"mongodb+srv://samthurman:{password['password']}@flatironcluster1-mfxlu.mongodb.net/test?retryWrites=true&w=majority\")\n    db = client.DarkskyLab\n    dictionary_list = []\n    for team in stats_df.values:\n        dictionary = dict(zip(list(stats_df.columns), team))\n        dictionary_list.append(dictionary)\n    db.teamResults.insert_many(dictionary_list)\n    return db.teamResults\n\ndef pipeline(season):\n    games = get_season_games(season)\n    print(\"got season games\")\n    with_rain = add_rainy(games)\n    print(\"got season games w rain\")\n    stats = get_stats(with_rain)\n    print(\"got stats\")\n    mongo_handler(stats)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"89063248","text":"# -*- coding: utf-8 -*-\nfrom enum import Enum\nimport numpy as np\nimport gdal\nimport os\nfrom matplotlib import pyplot as plt\nimport scipy\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Iterable\nfrom PIL import Image\n\n\"\"\" 最后需要根据求出来的指数进行分类,比如是遥感指数,地面指数之类的,现在只是存在一个类里面 \"\"\"\n\nclass JoBaseGeoProduct:\n    \"\"\" 传入和传出的参数一定要固定,提前定义好\n    所使用的函数放到一个大的目录下面,用xml 记录下来,不要把用到的文件全部放到基础地理产品的本地,\n    应该在一个特定的文件夹下面专门去测试,这边只是测试后能够执行的最终函数\"\"\"\n    @staticmethod\n    def cloud_index(red, hot_red):\n        \"\"\" 云指数,返回bool矩阵,有云的是 1\n        input : red(红) , hot_red(热红外)\n        \"\"\"\n        result = np.zeros(red.shape)\n\n        result[scipy.bitwise_or(hot_red < 278, red > 0.35)] = 1\n\n        return result\n\n    # ------------------------------------------------------\n\n    @staticmethod\n    def NDVI(r2, r3):\n        \"\"\"计算 NDVI \"\"\"\n        r2 = r2.astype(np.float)\n        r3 = r3.astype(np.float)\n        r4 = (r3 - r2).astype(np.float)\n        r5 = (r3 + r2).astype(np.float)\n        return r4 / r5\n\n    @staticmethod\n    def fc(NDVI):\n        \"\"\"计算地表覆盖度\"\"\"\n        NDVI = NDVI.astype(np.float)\n\n        temp_1 = (NDVI - 0.2).astype(np.float)\n        temp_2 = 0.3\n        fc = (temp_1 / temp_2).astype(np.float)\n\n        fc[NDVI < 0.2] = 0.001\n        fc[NDVI >= 0.5] = 1.0\n\n        return fc.astype(np.float)\n\n    @staticmethod\n    def albedo(r2, r3):\n        \"\"\"计算宽波段反照率\"\"\"\n        r2 = r2.astype(np.float)\n        r3 = r3.astype(np.float)\n        result = -0.3376 * r2 ** 2 - 0.2707 * r3 ** 2 + 0.7074 * r2 * r3 + 0.2915 * r2 + 0.5256 * r3\n        return result\n\n    @staticmethod\n    def emissivity(fc, NDVI):\n        \"\"\"计算地表发射率\"\"\"\n        fc = fc.astype(np.float)\n        NDVI = NDVI.astype(np.float)\n\n        F, s, v = 0.55, 0.97, 0.99\n        emissivity = np.ones(fc.shape)\n        emissivity = v * fc + s * (1 - fc) + (1 - s) * (1 - fc) * F * v\n        emissivity[NDVI < 0.2] = 0.97\n        emissivity[NDVI >= 0.5] = 0.99\n        return emissivity\n\n    @staticmethod\n    def hc(NDVI):\n        \"\"\"计算植被高度\"\"\"\n        NDVI = NDVI.astype(np.float)\n        hc = np.ones(NDVI.shape) * (0.0012 + ((2.5 - 0.0012) / (0.5 - 0.2)) * (NDVI - 0.2))\n        hc[NDVI < 0.2] = 0.0012\n        hc[NDVI >= 0.5] = 2.5   # 夏天是玉米,长得 2.5m 高\n        return hc\n\n    @staticmethod\n    def LAI(NDVI):\n        \"\"\"计算叶面指数\"\"\"\n        NDVI = NDVI.astype(np.float)\n        LAI = np.ones(NDVI.shape) * 0.0001\n        LAI[NDVI >= 0.2] = (2.4762 * NDVI + 2.1245)[NDVI >= 0.2]\n        return LAI\n\n    \"\"\" 待完善 \"\"\"\n    @staticmethod\n    def LST(TBB12, TBB13, fc, r2, NDVI):\n        \"\"\"计算地表温度, 这个好好看看,是有问题的\"\"\"\n        TBB12 = TBB12.astype(np.float)\n        TBB13 = TBB13.astype(np.float)\n        fc = fc.astype(np.float)\n        r2 = r2.astype(np.float)\n        NDVI = NDVI.astype(np.float)\n\n        LST = np.zeros(TBB12.shape)\n\n        def LST_0(cm, cd):\n            p = 1 + (0.15616 * (1 - cm) / cm) - 0.482 * (cd / (cm ** 2))\n            m = 6.26 + (3.98 * (1 - cm) / cm) - 38.33 * (cd / (cm ** 2))\n            LST = 1.274 + (p * (TBB12 + TBB13)) / 2 + (m * (TBB12 - TBB13)) / 2\n            return LST / 8\n\n        # ----------------------------------------------------------------------\n        c12 = 0.968 + 0.021 * fc\n        c13 = 0.974 + 0.015 * fc\n        cm = (c12 + c13) / 2\n        cd = (c12 - c13)\n        LST = LST_0(cm, cd)\n        # ----------------------------------------------------------------------\n        #     cm = 0.98 - 0.042*r2\n        #     cd = -0.003 - 0.029*r2\n        #     temp_2 = LST_0(cm, cd)\n        #     LST[ NDVI < 0.2 ] = temp_2[ NDVI < 0.2 ]\n        # ----------------------------------------------------------------------\n        cm = 0.989\n        cd = 0.0\n        temp_3 = LST_0(cm, cd)\n        LST[NDVI >= 0.5] = temp_3[NDVI >= 0.5]\n\n        return TBB12\n\n    @staticmethod\n    def AOD():\n        \"\"\" 气溶胶光学厚度 \"\"\"\n        pass\n\n    @staticmethod\n    def ATI():\n        \"\"\" 表观热惯量 \"\"\"\n        pass\n\n# 代码庞大的话这边只是一个函数调用方法,基础代码可以放在其他的地方\n# -------------------------------------------------- 地理产品测试 --------------------\n\nif __name__ == \"__main__\":\n\n\n    pass\n\n","sub_path":"utils/Operate/baseProduct.py","file_name":"baseProduct.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"453011901","text":"import datetime\nimport pprint\nimport numpy\nimport time\nimport datetime\n\nd = datetime.date(2018,1,1)\nzero = int(d.strftime(\"%s\"))\nnow = (time.time()) \n\n\nseconds = (now - zero) \n# print(\"zero = \" + str(zero))\n# print(\"now = \" + str(now))\n# print(\"seconds = \" + str(seconds))\n\nFILE = \"casy-etoro-6M.txt\"\nlines = open(FILE).read().split(\"\\n\")\n\ntime_array = numpy.zeros(int(seconds))\n\nfor idx,line in enumerate(lines):\n\tdat = datetime.datetime.strptime(line, \"%d/%m/%Y %H:%M:%S\")\n\ttime = int(dat.strftime(\"%s\"))\n\tif idx%2 == 0:\n\t\tstart_time = time\n\telse:\n\t\tend_time = time\n\t\ttime_array[start_time-zero:end_time-zero] += 1\n\n\nmaximum = numpy.argmax(time_array)\nprint(str(maximum))\nmaximum = numpy.amax(time_array)\nprint(str(maximum))\n\n\t\nhistogram = numpy.zeros(20)\ncasy_histogram = numpy.zeros(20)\n\nlast_x = 0\nfor x in time_array:\n\tcasy_histogram[int(x)] += 1\n\tif x != last_x:\n\t\thistogram[int(x)] += 1\n\t\tlast_x = x\npp = pprint.PrettyPrinter(depth=6)\npp.pprint(histogram)\nprint(numpy.sum(histogram[:]))\npp.pprint(casy_histogram)\n\n\n\n\n\n# isOverlapping =  ((A <= D) && (C <= B) );\n\n\n# A       B\n    # C      D\n\n# s = \"2010-01-01 18:48:14.631829\"\n# datetime.datetime.strptime(s, \"%Y-%m-%d %H:%M:%S.%f\")\n\n# 15/10/2018 12:03:48\n# datetime.datetime.strptime(s, \"%d/%m/%Y %H:%M:%S\")\n\n\n\n# A -> 1Start\n# B -> 1End\n# C -> 2Start\n# D -> 2End\n\n","sub_path":"overlaps_counter.py","file_name":"overlaps_counter.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"245973432","text":"# -*- coding: utf-8 -*-\nDESC = \"ssl-2019-12-05\"\nINFO = {\n  \"DescribeCertificateOperateLogs\": {\n    \"params\": [\n      {\n        \"name\": \"Offset\",\n        \"desc\": \"偏移量,默认为0。\"\n      },\n      {\n        \"name\": \"Limit\",\n        \"desc\": \"请求日志数量,默认为20。\"\n      },\n      {\n        \"name\": \"StartTime\",\n        \"desc\": \"开始时间,默认15天前。\"\n      },\n      {\n        \"name\": \"EndTime\",\n        \"desc\": \"结束时间,默认现在时间。\"\n      }\n    ],\n    \"desc\": \"获取用户账号下有关证书的操作日志。\"\n  },\n  \"DescribeCertificates\": {\n    \"params\": [\n      {\n        \"name\": \"Offset\",\n        \"desc\": \"分页偏移量,从0开始。\"\n      },\n      {\n        \"name\": \"Limit\",\n        \"desc\": \"每页数量,默认20。\"\n      },\n      {\n        \"name\": \"SearchKey\",\n        \"desc\": \"搜索关键词。\"\n      },\n      {\n        \"name\": \"CertificateType\",\n        \"desc\": \"证书类型:CA = 客户端证书,SVR = 服务器证书。\"\n      },\n      {\n        \"name\": \"ProjectId\",\n        \"desc\": \"项目 ID。\"\n      },\n      {\n        \"name\": \"ExpirationSort\",\n        \"desc\": \"按到期时间排序:DESC = 降序, ASC = 升序。\"\n      },\n      {\n        \"name\": \"CertificateStatus\",\n        \"desc\": \"证书状态。\"\n      },\n      {\n        \"name\": \"Deployable\",\n        \"desc\": \"是否可部署,可选值:1 = 可部署,0 =  不可部署。\"\n      }\n    ],\n    \"desc\": \"本接口(DescribeCertificates)用于获取证书列表。\"\n  },\n  \"DescribeCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"本接口(DescribeCertificate)用于获取证书信息。\"\n  },\n  \"CancelCertificateOrder\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"取消证书订单。\"\n  },\n  \"CommitCertificateInformation\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"提交证书订单。\"\n  },\n  \"DeleteCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"本接口(DeleteCertificate)用于删除证书。\"\n  },\n  \"DescribeCertificateDetail\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"获取证书详情。\"\n  },\n  \"UploadCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"CertificatePublicKey\",\n        \"desc\": \"证书公钥。\"\n      },\n      {\n        \"name\": \"CertificatePrivateKey\",\n        \"desc\": \"私钥内容,证书类型为 SVR 时必填,为 CA 时可不填。\"\n      },\n      {\n        \"name\": \"CertificateType\",\n        \"desc\": \"证书类型,默认 SVR。CA = 客户端证书,SVR = 服务器证书。\"\n      },\n      {\n        \"name\": \"Alias\",\n        \"desc\": \"备注名称。\"\n      },\n      {\n        \"name\": \"ProjectId\",\n        \"desc\": \"项目 ID。\"\n      }\n    ],\n    \"desc\": \"本接口(UploadCertificate)用于上传证书。\"\n  },\n  \"ReplaceCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      },\n      {\n        \"name\": \"ValidType\",\n        \"desc\": \"验证类型:DNS_AUTO = 自动DNS验证,DNS = 手动DNS验证,FILE = 文件验证。\"\n      },\n      {\n        \"name\": \"CsrType\",\n        \"desc\": \"类型,默认 Original。可选项:Original = 原证书 CSR,Upload = 手动上传,Online = 在线生成。\"\n      },\n      {\n        \"name\": \"CsrContent\",\n        \"desc\": \"CSR 内容。\"\n      },\n      {\n        \"name\": \"CsrkeyPassword\",\n        \"desc\": \"KEY 密码。\"\n      }\n    ],\n    \"desc\": \"本接口(ReplaceCertificate)用于重颁发证书。已申请的免费证书仅支持 RSA 算法、密钥对参数为2048的证书重颁发,并且目前仅支持1次重颁发。\"\n  },\n  \"ApplyCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"DvAuthMethod\",\n        \"desc\": \"验证方式:DNS_AUTO = 自动DNS验证,DNS = 手动DNS验证,FILE = 文件验证。\"\n      },\n      {\n        \"name\": \"DomainName\",\n        \"desc\": \"域名。\"\n      },\n      {\n        \"name\": \"ProjectId\",\n        \"desc\": \"项目 ID。\"\n      },\n      {\n        \"name\": \"PackageType\",\n        \"desc\": \"证书类型,目前仅支持类型2。2 = TrustAsia TLS RSA CA。\"\n      },\n      {\n        \"name\": \"ContactEmail\",\n        \"desc\": \"邮箱。\"\n      },\n      {\n        \"name\": \"ContactPhone\",\n        \"desc\": \"手机。\"\n      },\n      {\n        \"name\": \"ValidityPeriod\",\n        \"desc\": \"有效期,默认12个月,目前仅支持12个月。\"\n      },\n      {\n        \"name\": \"CsrEncryptAlgo\",\n        \"desc\": \"加密算法,仅支持 RSA。\"\n      },\n      {\n        \"name\": \"CsrKeyParameter\",\n        \"desc\": \"密钥对参数,仅支持2048。\"\n      },\n      {\n        \"name\": \"CsrKeyPassword\",\n        \"desc\": \"CSR 的加密密码。\"\n      },\n      {\n        \"name\": \"Alias\",\n        \"desc\": \"备注名称。\"\n      },\n      {\n        \"name\": \"OldCertificateId\",\n        \"desc\": \"原证书 ID,用于重新申请。\"\n      }\n    ],\n    \"desc\": \"本接口(ApplyCertificate)用于免费证书申请。\"\n  },\n  \"DownloadCertificate\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      }\n    ],\n    \"desc\": \"本接口(DownloadCertificate)用于下载证书。\"\n  },\n  \"SubmitCertificateInformation\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      },\n      {\n        \"name\": \"CsrType\",\n        \"desc\": \"CSR 生成方式:online = 在线生成, parse = 手动上传。\"\n      },\n      {\n        \"name\": \"CsrContent\",\n        \"desc\": \"上传的 CSR 内容。\"\n      },\n      {\n        \"name\": \"CertificateDomain\",\n        \"desc\": \"绑定证书的域名。\"\n      },\n      {\n        \"name\": \"DomainList\",\n        \"desc\": \"上传的域名数组(多域名证书可以上传)。\"\n      },\n      {\n        \"name\": \"KeyPassword\",\n        \"desc\": \"私钥密码。\"\n      },\n      {\n        \"name\": \"OrganizationName\",\n        \"desc\": \"公司名称。\"\n      },\n      {\n        \"name\": \"OrganizationDivision\",\n        \"desc\": \"部门名称。\"\n      },\n      {\n        \"name\": \"OrganizationAddress\",\n        \"desc\": \"公司详细地址。\"\n      },\n      {\n        \"name\": \"OrganizationCountry\",\n        \"desc\": \"国家名称,如中国:CN 。\"\n      },\n      {\n        \"name\": \"OrganizationCity\",\n        \"desc\": \"公司所在城市。\"\n      },\n      {\n        \"name\": \"OrganizationRegion\",\n        \"desc\": \"公司所在省份。\"\n      },\n      {\n        \"name\": \"PostalCode\",\n        \"desc\": \"公司邮编。\"\n      },\n      {\n        \"name\": \"PhoneAreaCode\",\n        \"desc\": \"公司座机区号。\"\n      },\n      {\n        \"name\": \"PhoneNumber\",\n        \"desc\": \"公司座机号码。\"\n      },\n      {\n        \"name\": \"VerifyType\",\n        \"desc\": \"证书验证方式。\"\n      },\n      {\n        \"name\": \"AdminFirstName\",\n        \"desc\": \"管理人姓。\"\n      },\n      {\n        \"name\": \"AdminLastName\",\n        \"desc\": \"管理人名。\"\n      },\n      {\n        \"name\": \"AdminPhoneNum\",\n        \"desc\": \"管理人手机号码。\"\n      },\n      {\n        \"name\": \"AdminEmail\",\n        \"desc\": \"管理人邮箱地址。\"\n      },\n      {\n        \"name\": \"AdminPosition\",\n        \"desc\": \"管理人职位。\"\n      },\n      {\n        \"name\": \"ContactFirstName\",\n        \"desc\": \"联系人姓。\"\n      },\n      {\n        \"name\": \"ContactLastName\",\n        \"desc\": \"联系人名。\"\n      },\n      {\n        \"name\": \"ContactEmail\",\n        \"desc\": \"联系人邮箱地址。\"\n      },\n      {\n        \"name\": \"ContactNumber\",\n        \"desc\": \"联系人手机号码。\"\n      },\n      {\n        \"name\": \"ContactPosition\",\n        \"desc\": \"联系人职位。\"\n      }\n    ],\n    \"desc\": \"提交证书资料。\"\n  },\n  \"ModifyCertificateProject\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateIdList\",\n        \"desc\": \"需要修改所属项目的证书 ID 集合,最多100个证书。\"\n      },\n      {\n        \"name\": \"ProjectId\",\n        \"desc\": \"项目 ID���\"\n      }\n    ],\n    \"desc\": \"批量修改证书所属项目。\"\n  },\n  \"ModifyCertificateAlias\": {\n    \"params\": [\n      {\n        \"name\": \"CertificateId\",\n        \"desc\": \"证书 ID。\"\n      },\n      {\n        \"name\": \"Alias\",\n        \"desc\": \"备注名称。\"\n      }\n    ],\n    \"desc\": \"用户传入证书id和备注来修改证书备注。\"\n  }\n}","sub_path":"tccli/services/ssl/v20191205/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"46384030","text":"import webbrowser\n\n\nclass Movie(object):\n    \"\"\"\n    Implementation of the Movie type\n\n    Attributes:\n    title: a string representing the title of the movie\n    storyline: a string representing\n    poster_art_url: a string\n    trailer_url: a string\n    running_time: a integer indicating the movie's running time in minutes.\n    director: a list containing the name of the director(s) of the movie.\n    \"\"\"\n    def __init__(self, movie_title, movie_storyline, poster_art_url,\n                 youtube_trailer_url, movie_running_time):\n        \"\"\"\n        Initialize Movie objects\n\n        Args:\n            movie_title(str): Movie's name.\n            movie_storyline(str): Brief description of the movie.\n            poster_art_url(str): URL for the movie poster.\n            youtube_trailer_url(str): URL for the movie trialer on youtube.\n            movie_running_time(int): Movie's running time in minutes.\n        \"\"\"\n        self.title = movie_title\n        self.storyline = movie_storyline\n        self.poster_art_url = poster_art_url\n        self.trailer_url = youtube_trailer_url\n        self.running_time = movie_running_time\n\n    def show_trailer(self):\n        \"\"\"\n        Open a modal that plays the trailer for the movie.\n        \"\"\"\n\n        webbrowser.open(self.trailer_url)\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"429384614","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import unicode_literals, absolute_import, print_function, division\nimport sopel.module\nimport sys\nimport os\nshareddir = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(shareddir)\nfrom SpicebotShared import *\n\nfishtypes = [\"Pike\",\"Carp\",\"Marlin\",\"Trout\",\"Cod\",\"Anchovy\",\"Venezuelan Beaverfish\",\"fish\",\"jellyfish\"]\nvowels = ('a','e','i','o','u','A','E','I','O','U')\n\n@sopel.module.commands('fish')\ndef mainfunction(bot, trigger):\n    enablestatus, triggerargsarray = spicebot_prerun(bot, trigger, trigger.group(1))\n    if not enablestatus:\n        execute_main(bot, trigger, triggerargsarray)\n    \ndef execute_main(bot, trigger, triggerargsarray):\n    target = get_trigger_arg(bot, triggerargsarray, 1)\n    reason = get_trigger_arg(bot, triggerargsarray, '2+')\n    message = \"Whoops, something went wrong.\"\n    fishtype = get_trigger_arg(bot,fishtypes,'random')\n    fishmsg = \"a \" + fishtype\n    # Vowel awareness\n    if fishtype.startswith(vowels):\n        fishmsg = \"an \" + fishtype\n        \n    # No target specified\n    if not target:\n        bot.say(\"Who/what would you like to slap with a fish?\")\n    \n    # Can't slap the bot\n    if target == bot.nick:\n        bot.say(\"I will not do that!!\")\n        \n    # Target is fine\n    else:\n        if not reason:\n            message = trigger.nick + \" slaps \" + target + \" with \" + fishmsg + \".\"\n        else:\n            if reason.startswith('for ') or reason.startswith('because ') or reason.startswith('cause '):\n                message = trigger.nick + \" slaps \" + target + \" with \" + fishmsg + \" \" + reason + \".\"\n            else:\n                message = trigger.nick + \" slaps \" + target + \" with \" + fishmsg + \" for \" + reason + \".\"\n        bot.say(message)\n        \n","sub_path":"modules/Memes/Slap_With_Fish.py","file_name":"Slap_With_Fish.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"577344187","text":"from read_raw_data import get_plotly_dfs\nfrom pymongo import MongoClient\ndef get_axis(name):\n    return [name + ', x', name + ', y']\ndef get_category(table):\n    categories = []\n    for col in table['chart_data']:\n        category = None\n        if 'type' in col:\n            category = col['type']\n        elif 'mode' in col:\n            category = col['mode']\n        if category:\n            if category not in types:\n                categories.append(category)\n    return categories\n\n\ndef process_line_chart(table):\n    axises = {}\n\n    for i, col in enumerate(table['chart_data']):\n        if col['mode'] != \"lines\":\n            continue\n        if col['yaxis'] in axises.keys():\n            axises[col['yaxis']].append(i)\n        else:\n            axises[col['yaxis']] = [i]\n    documents = []\n    for yaxis, ids in axises.items():\n        if len(ids) == 1:\n            i = ids[0]\n            column_x = table['df'].columns[2 * i]\n            column_y = table['df'].columns[2 * i + 1]\n            document = {\n                'dataset_id': table['dataset_id'],\n                'order': i,\n                'locator': table['locator'],\n                'type': 'singleseq',\n                'name': table['chart_data'][i]['name'],\n                'column_x': column_x,\n                'column_y': column_y,\n                'x': list(table['df'][column_x]),\n                'y': list(table['df'][column_y]),\n                'col': table['chart_data'][i]\n            }\n            documents.append(document)\n        else:\n            min_value = ids[0]\n            for i in ids:\n                if min_value > i:\n                    min_value = i\n            document = {\n                'dataset_id': table['dataset_id'],\n                'order': min_value,\n                'orders': ids,\n            }\n            data = []\n            for i in ids:\n                column_x = table['df'].columns[2 * i]\n                column_y = table['df'].columns[2 * i + 1]\n                data.append({\n                    'order': i,\n                    'column_x': column_x,\n                    'column_y': column_y,\n                    'x': list(table['df'][column_x]),\n                    'y': list(table['df'][column_y]),\n                    'col': table['chart_data'][i]\n                })\n            document['data'] = data\n            documents.append(document)\n\n\n\n\n\n\ntables = get_plotly_dfs(limit=1)\nline_count = 0\ncount = 0\ntypes = []\nclient = MongoClient()\ncollection = client['vis_data'].viznet\nfor i, table in enumerate(tables):\n    print(i)\n# try:\n#     for table in tables:\n#         categories = get_category(table)\n#         for col in table['chart_data']:\n#             category = None\n#             if 'type' in col:\n#                 category = col['type']\n#             elif 'mode' in col:\n#                 category = col['mode']\n#         if 'line' in categories:\n#             line_count += 1\n#         count += 1\n#         if count % 1000 == 0:\n#             print(\"finished: \", count)\n#         # table['df'][]\n#         # try:\n#         #     if table['chart_data'][0]['type'] == \"line\":\n#         #         count += 1\n#         # except:\n#         #     if table['chart_data'][0]['mode'] == \"line\":\n#         #         count += 1\n#         # print(table['chart_data'])\n# except:\n#     print(\"sa\")\n# print(count)\n# print(types)","sub_path":"characterization/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"67369993","text":"import os, sys\nimport pytest\nimport unittest\nimport subprocess\nimport shutil\nfrom sonLib.bioio import getTempDirectory, popenCatch, popen\n\nclass TestCase(unittest.TestCase):\n    def setUp(self):\n        self.tempDir = getTempDirectory(os.getcwd())\n        unittest.TestCase.setUp(self)\n        self.cromwell = False\n\n    def tearDown(self):\n        unittest.TestCase.tearDown(self)\n        if self.cromwell:\n            # try to catch some cromwell root mode directories that above missies\n            # see https://github.com/ComparativeGenomicsToolkit/cactus/issues/255\n            os.system(\"docker run --rm -it -v {}:/data evolvertestdocker/cactus:latest rm -rf {}\".format(\n                os.path.dirname(self.tempDir.rstrip('/')), os.path.join('/data', os.path.basename(self.tempDir))))\n        os.system(\"rm -rf %s || true\" % self.tempDir)\n\n    def _job_store(self, binariesMode):\n        return os.path.join(self.tempDir, 'js-{}'.format(binariesMode))\n\n    def _out_hal(self, binariesMode):\n        return os.path.join(self.tempDir, 'evovler-{}.hal'.format(binariesMode))\n\n    def _run_evolver(self, binariesMode):\n        \"\"\" Run the full evolver test, putting the jobstore and output in tempDir\n        \"\"\"\n        cmd = ['cactus', self._job_store(binariesMode), './examples/evolverMammals.txt', self._out_hal(binariesMode),\n                               '--binariesMode', binariesMode, '--logInfo', '--realTimeLogging', '--workDir', self.tempDir]\n        # todo: it'd be nice to have an interface for setting tag to something not latest or commit\n        if binariesMode == 'docker':\n            cmd += ['--latest']\n\n        sys.stderr.write('Running {}'.format(' '.format(cmd)))\n        subprocess.check_call(' '.join(cmd), shell=True)\n\n    def _run_evolver_decomposed(self, name):\n        \"\"\" Run the full evolver test, putting the jobstore and output in tempDir\n        but instead of doing in in one shot like above, use cactus-prepare, cactus-blast\n        and cactus-align to break it into different steps \"\"\"\n\n        out_dir = os.path.join(self.tempDir, 'output')\n        out_seqfile = os.path.join(out_dir, 'evolverMammalsOut.txt')\n        in_seqfile = './examples/evolverMammals.txt'\n        cmd = ['cactus-prepare', in_seqfile, '--outDir', out_dir, '--outSeqFile', out_seqfile, '--outHal', self._out_hal(name),\n               '--jobStore', self._job_store(name)]\n\n        job_plan = popenCatch(' '.join(cmd))\n\n        for line in job_plan.split('\\n'):\n            line = line.strip()\n            if len(line) > 0 and not line.startswith('#'):\n                # do Anc2 in binariesMode docker to broaden test coverage\n                if 'Anc2' in line and line.startswith('cactus-'):\n                    line += ' --binariesMode docker --latest'\n                sys.stderr.write('Running {}'.format(line))\n                subprocess.check_call(line, shell=True)\n\n    def _run_evolver_decomposed_wdl(self, name):\n        \"\"\" Run the full evolver test, putting the jobstore and output in tempDir\n        but instead of doing in in one shot, use cactus-prepare to make a wdl\n        script and run that locally through cromwell \"\"\"\n\n        # hack to use docker to remove filetree in teardown, as cromwell\n        # can leave root files hanging around there\n        self.cromwell = True\n        \n        out_seqfile = os.path.join(self.tempDir, 'evolverMammalsOut.txt')\n        in_seqfile = './examples/evolverMammals.txt'\n        out_wdl = os.path.join(self.tempDir, 'prepared.wdl')\n        cmd = ['cactus-prepare', in_seqfile, '--outHal', self._out_hal(name),\n               '--jobStore', self._job_store(name), '--wdl',\n               '--dockerImage', 'evolvertestdocker/cactus:latest',\n               '--preprocessCores', '2',\n               '--blastCores', '4',\n               '--alignCores', '4']\n\n        # specify an output directory\n        cw_optionsfile = os.path.join(self.tempDir, 'options.json')\n        cw_output = os.path.join(self.tempDir, 'cromwell-output')\n        with open(cw_optionsfile, 'w') as cw_opts:\n            cw_opts.write('{\\n')\n            cw_opts.write('    \\\"final_workflow_outputs_dir\\\": \\\"{}\\\",\\n'.format(cw_output))\n            cw_opts.write('    \\\"use_relative_output_paths\\\": true\\n')\n            cw_opts.write('}\\n')\n\n        # download cromwell\n        subprocess.check_call(['wget', '-q', 'https://github.com/broadinstitute/cromwell/releases/download/49/cromwell-49.jar'],\n                              cwd=self.tempDir)\n\n        # run cactus-prepare and write the output to a wdl file\n        popen(' '.join(cmd), out_wdl)\n\n        # run the wdl script in cromwell\n        subprocess.check_call(['java', '-jar', './cromwell-49.jar', 'run',\n                               out_wdl, '-o', cw_optionsfile], cwd=self.tempDir)\n\n        # fish the file out of cromwell\n        shutil.copyfile(os.path.join(cw_output, os.path.basename(self._out_hal(name))), self._out_hal(name))\n\n\n    def _run_evolver_decomposed_no_outgroup(self, binariesMode):\n        \"\"\" Run just the mouse-rat alignment.  Inspired by issues arising here\n        https://github.com/ComparativeGenomicsToolkit/cactus/pull/216\n        https://github.com/ComparativeGenomicsToolkit/cactus/pull/217 \"\"\"\n\n        out_dir = os.path.join(self.tempDir, 'output')\n        out_seqfile = os.path.join(out_dir, 'evolverMammalsOut.txt')\n        in_seqfile = os.path.join(self.tempDir, 'evolverMammalsIn.txt')\n        with open(in_seqfile, 'w') as inseq:\n            inseq.write('(simMouse_chr6:0.084509,simRat_chr6:0.091589);\\n')\n            inseq.write('simMouse_chr6 http://s3-us-west-2.amazonaws.com/jcarmstr-misc/testRegions/evolverMammals/simMouse.chr6\\n')\n            inseq.write('simRat_chr6 http://s3-us-west-2.amazonaws.com/jcarmstr-misc/testRegions/evolverMammals/simRat.chr6\\n')\n\n        cmd = ['cactus-prepare', in_seqfile, '--outDir', out_dir, '--outSeqFile', out_seqfile, '--outHal', self._out_hal(binariesMode),\n               '--jobStore', self._job_store(binariesMode)]\n        job_plan = popenCatch(' '.join(cmd))\n\n        for line in job_plan.split('\\n'):\n            line = line.strip()\n            if len(line) > 0 and not line.startswith('#'):\n                # todo interface in prepare\n                if line.startswith('cactus-'):\n                    line += ' --binariesMode {}'.format(binariesMode)\n                    if binariesMode == 'docker':\n                        line += ' --latest'\n                if line.startswith('cactus-align'):\n                    #Remove all the id prefixes to pretend the cigars came not cactus-blast\n                    subprocess.check_call('sed -i -e \\'s/id=[0,1]|//g\\' {}/Anc0.cigar*'.format(out_dir), shell=True)\n                    line += ' --nonBlastInput'\n                sys.stderr.write('Running {}'.format(line))\n                subprocess.check_call(line, shell=True)\n\n    def _csvstr_to_table(self, csvstr, header_fields):\n        \"\"\" Hacky csv parse \"\"\"\n        output_stats = {}\n        skip = True\n        # filter out everything but the csv stats from the halStats output\n        for line in csvstr.split('\\n'):\n            toks = [tok.strip() for tok in str(line).split(',')]\n            if skip:\n                if all([header in toks for header in header_fields]):\n                    skip = False\n            elif len(toks) > len(header_fields):\n                output_stats[toks[0]] = toks[1:]\n        return output_stats\n\n    def _subset_table(self, csvstr, subset={}):\n        \"\"\" Hack a truth table to a subset \"\"\"\n        if not subset:\n            return csvstr\n        lines=csvstr.split('\\n')\n        ret=''\n        for i, line in enumerate(lines):\n            if i == 0 or line.split(',')[0].strip() in subset:\n                ret += line + '\\n'\n        return ret\n\n    def _check_stats(self, halPath, delta_pct, subset={}):\n        \"\"\" Compare halStats otuput of given file to baseline\n        \"\"\"\n        # this is just pasted from a successful run.  it will be used to catch serious regressions\n        ground_truth = '''GenomeName, NumChildren, Length, NumSequences, NumTopSegments, NumBottomSegments\n        Anc0, 2, 545125, 9, 0, 14471\n        Anc1, 2, 569645, 6, 16862, 54019\n        simHuman_chr6, 0, 601863, 1, 53463, 0\n        mr, 2, 611571, 3, 52338, 55582\n        simMouse_chr6, 0, 636262, 1, 56172, 0\n        simRat_chr6, 0, 647215, 1, 55687, 0\n        Anc2, 2, 577109, 15, 17350, 57130\n        simCow_chr6, 0, 602619, 1, 56309, 0\n        simDog_chr6, 0, 593897, 1, 55990, 0'''\n\n        ground_truth = self._subset_table(ground_truth, subset)\n\n        # run halStats on the evolver output\n        proc = subprocess.Popen(['bin/halStats',  halPath], stdout=subprocess.PIPE)\n        output, errors = proc.communicate()\n        sts = proc.wait()\n        self.assertEqual(sts, 0)\n        sys.stderr.write(\"\\nComparing stats\\n{}\\nvs ground truth\\n{}\\n\".format(output.decode(\"utf-8\"), ground_truth))\n        output_table = self._csvstr_to_table(output.decode(\"utf-8\"), ['GenomeName', 'NumChildren'])\n        truth_table = self._csvstr_to_table(ground_truth, ['GenomeName', 'NumChildren'])\n\n        # make sure the stats are roughly the same\n        self.assertEqual(len(truth_table), len(output_table))\n        for key, val in truth_table.items():\n            self.assertTrue(key in output_table)\n            oval = output_table[key]\n            self.assertEqual(len(val), len(oval))\n            for i in range(len(val)):\n                is_leaf = key.startswith('sim')\n                # exact comparison for NumChildren and, for leaves, Lengh and NumSequences\n                exact_comp = i == 0 or (is_leaf and i in [1,2])\n                # no comparison for NumSequences in Ancestors as it seems to be all over the place\n                no_comp = i == 2 and not is_leaf\n                if exact_comp:\n                    self.assertEqual(int(oval[i]), int(val[i]))\n                elif not no_comp:\n                    delta = delta_pct * int(val[i])\n                    self.assertGreaterEqual(int(oval[i]), int(val[i]) - delta)\n                    self.assertLessEqual(int(oval[i]), int(val[i]) + delta)\n\n    def _check_coverage(self, halPath, delta_pct, subset={}, columns=3):\n        \"\"\" Compare halStats otuput of given file to baseline\n        \"\"\"\n        # this is just pasted from a successful run.  it will be used to catch serious regressions\n        ground_truth = '''Genome, sitesCovered1Times, sitesCovered2Times, sitesCovered3Times\n        simMouse_chr6, 636262, 24981, 567\n        simRat_chr6, 574916, 21476, 1328\n        simHuman_chr6, 459323, 3948, 0\n        simCow_chr6, 427278, 4610, 0\n        simDog_chr6, 433022, 2905, 0'''\n\n        ground_truth = self._subset_table(ground_truth, subset)\n\n        # run halCoverage on the evolver output\n        proc = subprocess.Popen(['bin/halStats',  halPath, '--coverage', 'simMouse_chr6', '--hdf5InMemory'], stdout=subprocess.PIPE)\n        output, errors = proc.communicate()\n        sts = proc.wait()\n        self.assertEqual(sts, 0)\n        sys.stderr.write(\"\\n\\nComparing coverage\\n{}\\nvs ground truth\\n{}\\n\".format(output.decode(\"utf-8\"), ground_truth))\n        output_table = self._csvstr_to_table(output.decode(\"utf-8\"), ['Genome', 'sitesCovered1Times'])\n        truth_table = self._csvstr_to_table(ground_truth, ['Genome', 'sitesCovered1Times'])\n\n        # make sure the stats are roughly the same\n        self.assertEqual(len(truth_table), len(output_table))\n        for key, val in truth_table.items():\n            self.assertTrue(key in output_table)\n            oval = output_table[key]\n            self.assertEqual(len(val[:columns]), len(oval[:columns]))\n            for i in range(columns):\n                delta = delta_pct * int(val[i])\n                self.assertGreaterEqual(int(oval[i]), int(val[i]) - delta)\n                self.assertLessEqual(int(oval[i]), int(val[i]) + delta)\n\n    def testEvolverLocal(self):\n        \"\"\" Check that the output of halStats on a hal file produced by running cactus with --binariesMode local is\n        is reasonable\n        \"\"\"\n        # run cactus directly, the old school way\n        name = \"local\"\n        self._run_evolver(name)\n\n        # check the output\n        self._check_stats(self._out_hal(name), delta_pct=0.25)\n        self._check_coverage(self._out_hal(name), delta_pct=0.20)\n\n    def testEvolverPrepareWDL(self):\n\n        # run cactus step by step via a WDL workflow made by cactus-prepare\n        self._run_evolver_decomposed_wdl(\"wdl\")\n\n        # check the output\n        self._check_stats(self._out_hal(\"wdl\"), delta_pct=0.25)\n        self._check_coverage(self._out_hal(\"wdl\"), delta_pct=0.20)\n\n    def testEvolverDecomposedLocal(self):\n        \"\"\" Check that the output of halStats on a hal file produced by running cactus with --binariesMode local is\n        is reasonable\n        \"\"\"\n        # run cactus step by step via the plan made by cactus-prepare\n        name = \"decomposed\"\n        self._run_evolver_decomposed(name)\n\n        # check the output\n        self._check_stats(self._out_hal(name), delta_pct=0.25)\n        self._check_coverage(self._out_hal(name), delta_pct=0.20)\n\n    def testEvolverDocker(self):\n        \"\"\" Check that the output of halStats on a hal file produced by running cactus with --binariesMode docker is\n        is reasonable.  Note: the local image being tested should be set up via CACTUS_DOCKER_ORG (with tag==latest)\n        \"\"\"\n        # run cactus\n        self._run_evolver(\"docker\")\n\n        # check the output\n        self._check_stats(self._out_hal(\"docker\"), delta_pct=0.25)\n        self._check_coverage(self._out_hal(\"docker\"), delta_pct=0.20)\n\n    def testEvolverPrepareNoOutgroupDocker(self):\n\n        # run cactus step by step via the plan made by cactus-prepare, hacking to apply --nonBlastInput option to cactus-align\n        self._run_evolver_decomposed_no_outgroup(\"docker\")\n\n        # check the output\n        self._check_stats(self._out_hal(\"docker\"), delta_pct=2.5, subset=['simMouse_chr6', 'simRat_chr6', 'Anc0'])\n        self._check_coverage(self._out_hal(\"docker\"), delta_pct=0.20, subset=['simMouse_chr6', 'simRat_chr6', 'Anc0'], columns=1)\n\n    def testEvolverPrepareNoOutgroupLocal(self):\n\n        # run cactus step by step via the plan made by cactus-prepare, hacking to apply --nonBlastInput option to cactus-align\n        self._run_evolver_decomposed_no_outgroup(\"local\")\n\n        # check the output\n        self._check_stats(self._out_hal(\"local\"), delta_pct=2.5, subset=['simMouse_chr6', 'simRat_chr6', 'Anc0'])\n        self._check_coverage(self._out_hal(\"local\"), delta_pct=0.20, subset=['simMouse_chr6', 'simRat_chr6', 'Anc0'], columns=1)\n\n\nif __name__ == '__main__':\n    unittest.main()\n","sub_path":"test/evolverTest.py","file_name":"evolverTest.py","file_ext":"py","file_size_in_byte":14702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"569262492","text":"# define generic quota per user\nMAX_CONTAINER_PER_USER = 5\nMAX_RAM_PER_USER = \"30G\"\nMAX_CPU_PER_USER = 10\nMAX_STORAGE_PER_USER = \"80G\"\n\n# define limit max experiments per page\nPAGE_SIZE_EXPERIMENTS = 7\n\n# 0: This would only allow Umbrella authentication. By default, the system does only allow Umbrella authentication.\n# 1: This would allow the user to show the form in order to authenticate locally\nALLOW_LOCAL_AUTHENTICATION = 1\n\n# Both volumes should be built dynamically, but root of both of them must be declared as settings variables\n# (e.g EXPERIMENTS_DATASETS_ROOT - for the read-only - and EXPERIMENTS_OUTPUT - for the results)--\nEXPERIMENTS_DATASETS_ROOT = \"/tmp/data\"\nEXPERIMENTS_OUTPUT = \"/tmp/results\"\n\n","sub_path":"calipsoplus/settings_calipso.py","file_name":"settings_calipso.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"14540902","text":"#!/usr/bin/env python3\n#-----------------------------------------------------------------------------\n# This file is part of the 'Camera link gateway'. It is subject to\n# the license terms in the LICENSE.txt file found in the top-level directory\n# of this distribution and at:\n#    https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.\n# No part of the 'Camera link gateway', including this file, may be\n# copied, modified, propagated, or distributed except according to the terms\n# contained in the LICENSE.txt file.\n#-----------------------------------------------------------------------------\nimport pyrogue as pr\n\nimport axipcie                                 as pcie\nimport l2si_drp\n\nclass DrpPgpTDet(pr.Device):\n    def __init__(self,\n                 numDmaLanes = 2,\n                 numTimingLanes = 1,\n                 numPgpLanes = 1,\n                 pgp3     = False,\n                 **kwargs):\n        super().__init__(**kwargs)\n\n        self.add(pcie.AxiPcieCore(\n            offset      = 0x0000_0000,\n            numDmaLanes = numDmaLanes,\n            expand      = False,\n        ))\n\n        self.add(l2si_drp.MigToPcieDma(\n            name     = 'MigToPcieDma',\n            offset    = 0x0080_0000,\n            numLanes  = numDmaLanes,\n            expand    = False,\n        ))\n\n        self.add(l2si_drp.TDetSemi(\n            name     = 'TDetSemi',\n            offset    = 0x00A0_0000,\n            numLanes  = numTimingLanes,\n            expand    = False,\n        ))\n\n        self.add(l2si_drp.PgpSemi(\n            name     = 'PgpSemi',\n            offset    = 0x00B0_0000,\n            numLanes  = numPgpLanes,\n            usePgp3   = False,\n            expand    = False,\n        ))\n\n        self.add(l2si_drp.TDetTiming(\n            name     = 'TDetTiming',\n            offset    = 0x00C0_0000,\n            numLanes  = numTimingLanes+numPgpLanes,\n            expand    = False,\n        ))\n\n        self.add(l2si_drp.I2CBus(\n            name     = 'I2CBus',\n            offset    = 0x00E0_0000,\n            expand    = False,\n        ))\n","sub_path":"firmware/python/l2si_drp/_DrpPgpTDet.py","file_name":"_DrpPgpTDet.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"643042800","text":"import tensorflow as tf\nfrom bayesdend.rec_model.upsampled_model_util import soma_network, spine_network\nfrom bayesdend.rec_model.spikes import *\nfrom tensorflow.contrib.distributions import Bernoulli\nfrom bayesdend.utils.tf_util import repeat_elements\nfrom keras.backend import binary_crossentropy\nfrom bayesdend.rec_model.upsampled_model_util import network_output, cut_upsample\n\nclass DendriteUpsampled(Spikes):\n    \"\"\"\n    Dendritic sample-based model.\n    \"\"\"\n\n    def __init__(self, Nb, temp, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.Nb = Nb\n\n    def log_prob(self, data_ph, prior, genparams):\n        \"\"\"\n        params genparams: a list of generative parameters\n        \"\"\"\n        if genparams is not None:\n            print(\"gene_params condictioning.\")\n            soma_gen_params = tf.stop_gradient(genparams['gen_soma'] / 10.0)\n            spine_gen_params = tf.stop_gradient(genparams['gen_spine'] / 10.0)\n        else:\n            spine_gen_params = None\n            soma_gen_params = None\n\n        # soma_output, spine_output\n        soma_output, spine_output = network_output(self.window_size, self.upsample)\n        upsample_adjust = cut_upsample(self.window_size, self.upsample, self.rec_model_cond)\n        soma_cut = (soma_output - spine_output) // 2 + upsample_adjust\n        spine_cut = upsample_adjust\n\n        with tf.variable_scope('recognition'):\n            with tf.variable_scope('soma'):\n                logit_soma = soma_network(data_ph['upsampled_traces'], self.window_size, self.upsample, self.Nc,\n                                          self.batch_size, self.sample_rate, self.conv_mode, soma_gen_params)\n                # feed in soma_samples, and soma_probability\n                gt = data_ph['gt_hr']\n                if not self.sup_test:\n                    soma_sample = tf.expand_dims(gt[:, :, 0:1], axis=0)\n                else:\n                    soma_sample = tf.cast(Bernoulli(logits=logit_soma).sample(self.Nb), tf.float32)\n\n\n            with tf.variable_scope('spine'):\n                logit_spine = spine_network(data_ph['upsampled_traces'], soma_sample, logit_soma, self.batch_size, self.window_size,\n                                            self.upsample, self.Nc-1, self.Nb, spine_output, self.sample_rate, spine_gen_params, self.conv_mode)\n                spine_sample = tf.cast(Bernoulli(logits=logit_spine).sample(), tf.float32)\n\n            if soma_cut != 0:\n                logit_soma = logit_soma[:, soma_cut:-soma_cut]\n            if spine_cut != 0:\n                logit_spine = logit_spine[:, :, spine_cut:-spine_cut]\n\n            if not self.sup_test:\n                soma_spine_logit = tf.concat([logit_soma, logit_spine[0]], -1)\n                self.Qsamp = tf.expand_dims(tf.sigmoid(soma_spine_logit), axis=0)\n            else:\n                logit_soma_repeat = repeat_elements(tf.expand_dims(logit_soma, axis=0), self.Nb, axis=0)\n                soma_spine_logit = tf.concat([logit_soma_repeat, logit_spine], -1)\n                if soma_cut != 0:\n                    soma_sample_cut = soma_sample[:, :, soma_cut:-soma_cut]\n                else:\n                    soma_sample_cut = soma_sample\n                if spine_cut != 0:\n                    spine_sample_cut = spine_sample[:, :, spine_cut:-spine_cut]\n                else:\n                    spine_sample_cut = spine_sample\n                self.Qsamp = tf.concat([soma_sample_cut, spine_sample_cut], axis=-1)\n\n            self.kl_divergence_sample = 0\n            self.kl_divergence_ana = 0\n\n            # some diagnostics\n            new_window_size = int(logit_soma.get_shape().as_list()[1]/self.upsample)\n            jitters = tf.reshape(tf.sigmoid(logit_soma), [self.batch_size, new_window_size, self.upsample, 1])\n            # normalize it by ground truth\n            self.jitters_ind = tf.reduce_mean(jitters, [0, 1, 3])\n\n            if soma_cut != 0:\n                gt_corr = gt[:, soma_cut:-soma_cut]\n            else:\n                gt_corr = gt\n\n            if not self.sup_test:\n                log_q = -binary_crossentropy(gt_corr, soma_spine_logit, from_logits=True)\n            else:\n                log_q = 0.0\n\n        return [0.0, log_q]\n\n    def get_latents(self):\n        latents = {}\n        latents['spikes'] = self.Qsamp\n        return latents\n\n    def get_expected_rate(self):\n        return tf.reduce_mean(self.Qsamp, 0)\n\n    def get_samples(self):\n        \"\"\"\n        Get samples: [Nb, batch_size, window_size, Nc]\n        \"\"\"\n        return self.Qsamp\n","sub_path":"bayesdend/rec_model/dend_upsampled.py","file_name":"dend_upsampled.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"154928519","text":"import argparse\nimport os\n\nimport numpy as np\nfrom bpemb import BPEmb\nfrom elmoformanylangs import Embedder\nfrom gensim.models import FastText as fText\n\n\n#####################################################################\n# Requirements: fasttext - install from github repo\n#               gensim - latest version (3.7)\n#               bpemb  - pip install\n#               allennlp - pip install\n#               https://github.com/HIT-SCIR/ELMoForManyLangs\n#####################################################################\n\ndef chunks(l, n):\n    # For item i in a range that is a length of l,\n    for i in range(0, len(l), n):\n        # Create an index range for l of n items:\n        yield l[i:i + n]\n\n\n### Util Functions ###\ndef ensure_dir(file_path):\n    directory = os.path.dirname(file_path)\n    if not os.path.exists(directory):\n        os.makedirs(directory)\n\n\n### Loading Embedding Functions ###\ndef loadfasttext(embfile):\n    \"\"\"\n    Load fasttext embeddings\n    :param embfile:\n    :return:\n    \"\"\"\n    model = fText.load_fasttext_format(embfile)\n    return model\n\n\ndef loadBPE(lang, vector_size):\n    \"\"\"\n    It automatically downloads the embedding file and loads it as a gensim keyed vector\n    :param lang: langauge is enough, no need for embedding file\n    :return:\n    \"\"\"\n    model = BPEmb(lang=lang, dim=vector_size)\n    return model\n\n\ndef loadElmo(embfile):\n    \"\"\"\n\n    :param embfile:\n    :return:\n    \"\"\"\n    model = Embedder(embfile)\n    return model\n\n\ndef loadw2v(embfile):\n    \"\"\"\n    To be filled\n    :param embfile:\n    :return:\n    \"\"\"\n    return None\n\n\ndef loadModel(infile, lang, w2vtype, vector_size):\n    \"\"\"\n    Load the embedding model\n    :param infile: Embedding file\n    :param lang: language\n    :param w2vtype: type of embeddings\n    :return:\n    \"\"\"\n    if w2vtype in ['fasttext', 'muse_supervised', 'muse_unsupervised']:\n        return loadfasttext(infile)\n    elif w2vtype == 'bpe':\n        return loadBPE(lang, vector_size)\n    elif w2vtype == 'elmo':\n        return loadElmo(infile)\n    elif w2vtype == 'w2v':\n        return loadw2v(infile)\n    else:\n        print(\"Should be one of w2v|fasttext|bpe|elmo\")\n        return None\n\n\ndef word_by_word_retr(sent, model):\n    \"\"\"\n    Util function for fasttext retrieval\n    :param sent: batch of words, just a list of words, don't have to be a sentence\n    :return: numpy matric BxD\n    \"\"\"\n    # check word by word\n    first_word = sent[0]\n\n    try:\n        batch_word_embed = model[first_word]\n    except:\n        batch_word_embed = model[u'']\n\n    # initialize batch_sent_emb with the first word's embedding\n    batch_sent_emb = batch_word_embed\n    for i in range(1, len(sent)):\n        word = sent[i]\n        try:\n            batch_word_embed = model[word]\n        except:\n            batch_word_embed = model[u'']\n        batch_sent_emb = np.vstack((batch_sent_emb, batch_word_embed))\n    return batch_sent_emb\n\n\ndef get_fasttext(model, words, batch_size):\n    \"\"\"\n    Get fasttext embeddings\n    :param model: fasttext model\n    :param words: words\n    :param batch_size: batch size\n    :return:\n    \"\"\"\n    # Make batches of words\n    sents = list(chunks(words, batch_size))\n    try:\n        batch_sent_embs = model[sents[0]]\n    except:\n        batch_sent_embs = word_by_word_retr(sents[0], model)\n\n    for i in range(1, len(sents)):\n        # print(i)\n        sent = sents[i]\n        try:\n            emb_for_sent = model[sent]\n        except:\n            emb_for_sent = word_by_word_retr(sent, model)\n        batch_sent_embs = np.concatenate((batch_sent_embs, emb_for_sent))\n\n    return batch_sent_embs\n\n\ndef get_bpe(model, words):\n    \"\"\"\n    Get BPE embeddings. It only works word by word!! Will be slow\n    :param model: bpe model\n    :param words: words\n    :param batch_size: batch size\n    :return:\n    \"\"\"\n    # Make batches of words\n    # check word by word\n    first_word = words[0]\n    batch_word_embed = np.mean(model.embed(first_word), axis=0)\n    batch_sent_emb = batch_word_embed\n\n    for i in range(1, len(words)):\n        word = words[i]\n        batch_word_embed = np.mean(model.embed(word), axis=0)\n        batch_sent_emb = np.vstack((batch_sent_emb, batch_word_embed))\n\n    return batch_sent_emb\n\n\ndef get_elmo(model, words, batch_size):\n    \"\"\"\n    Get fasttext embeddings\n    :param model: fasttext model\n    :param words: words\n    :param batch_size: batch size (should be 1)\n    :return:\n    \"\"\"\n    # Make batches of words - since it is contextual embeddings, make sentences of size 1\n    sents = list(chunks(words, batch_size))\n    batch_sent_embs = model.sents2elmo(sents)\n    batch_sent_embs = np.vstack(batch_sent_embs)\n    return batch_sent_embs\n\n\ndef get_w2v(model, words, batch_size):\n    \"\"\"\n    Get fasttext embeddings\n    :param model: fasttext model\n    :param words: words\n    :param batch_size: batch size\n    :return:\n    \"\"\"\n    # Make batches of words\n    sents = list(chunks(words, batch_size))\n    try:\n        batch_sent_embs = model[sents[0]]\n    except:\n        batch_sent_embs = word_by_word_retr(sents[0])\n\n    for i in range(1, len(sents)):\n        sent = sents[i]\n        try:\n            emb_for_sent = model[sent]\n        except:\n            emb_for_sent = word_by_word_retr(sent)\n\n        batch_sent_embs = np.concatenate((batch_sent_embs, emb_for_sent))\n\n    return batch_sent_embs\n\n\ndef generateEmbeds(model, infile, outfile, w2vtype, batch_size):\n    # Read the input file to a list\n    with open(infile) as f:\n        lines = f.read().splitlines()\n    f.close()\n\n    if w2vtype in ['fasttext', 'muse_supervised', 'muse_unsupervised']:\n        nparray = get_fasttext(model, lines, batch_size)\n    elif w2vtype == 'bpe':\n        nparray = get_bpe(model, lines)\n    elif w2vtype == 'elmo':\n        nparray = get_elmo(model, lines, 1)\n    elif w2vtype == 'w2v':\n        nparray = get_w2v(model, lines, batch_size)\n    else:\n        outlines = ''\n\n    # Create the output file\n    ensure_dir(outfile)\n    np.savetxt(outfile, nparray, delimiter=' ', fmt='%1.5f')  # X is an array\n    return\n\n\ndef main(args):\n    model = loadModel(args.embedding, args.lang, args.w2vtype, args.vector_size)\n    outfile = os.path.join(args.savedir, args.lang, args.w2vtype, \"embeds_\" + str(args.part) + \".vec\")\n    generateEmbeds(model, args.infile, outfile, args.w2vtype, args.batch_size)\n    return\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    # Prepare feature tests\n    parser.add_argument('--w2vtype', type=str, default='fasttext', help='')\n    parser.add_argument('--lang', type=str, default=\"tur\", help=\"\")\n    parser.add_argument('--embedding', type=str, default=\"./embeddings/wiki.tr/wiki.tr\")\n    parser.add_argument('--infile', type=str, default=\"./words/tur.txt\")\n    parser.add_argument('--savedir', type=str, default='./saved_embeddings')\n    parser.add_argument('--part', type=int, default=1)\n    parser.add_argument('--batch_size', type=int, default=100)\n    parser.add_argument('--vector_size', type=int, default=300)\n\n    args = parser.parse_args()\n    main(args)\n","sub_path":"data_util/extract_vectors.py","file_name":"extract_vectors.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"181006645","text":"class Humano:\r\n    contador = 0\r\n\r\n    def __init__(self,nome,idade,peso,altura):\r\n\r\n        self.id = Humano.contador + 1\r\n        self.nome = nome\r\n        self.idade = idade\r\n        self.peso = peso\r\n        self.altura = altura\r\n        Humano.contador = id\r\n\r\n    def profissao(self,forca,sabedoria,velocidade):\r\n\r\n        if 7 <= forca and 2 >= sabedoria and 3 >= velocidade:\r\n            return \"Bárbaro\"\r\n        elif 5 <= forca < 7 and 5 <= sabedoria <= 7 and velocidade >= 7:\r\n            return \"Ladino\"\r\n        elif  forca <= 2 and sabedoria >= 7 and velocidade <= 3:\r\n            return \"Feiticeiro\"\r\n        else:\r\n            return \"Rooker\"\r\n\r\njogador1 = Humano(\"Victor\",26,102,1.91)\r\n\r\n\r\nprint(jogador1.__dict__)\r\nprint(f\"{jogador1.nome} é da classe {jogador1.profissao(7,1,1)}\")\r\n","sub_path":"treinamento/rpgClasses.py","file_name":"rpgClasses.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"187468095","text":"'''\n주민번호는 다음과 같이 구성된다.\nXXXXXX-XXXXXXX\n앞의 6자리는 생년월일(yymmdd)이고 뒤 7자리는 성별, 지역, 오류검출코드이다.\n주민번호를 입력받아 형태를 바꿔 출력해보자.\n\nINPUT\n주민번호 앞 6자리와 뒷 7자리가 '-'로 구분되어 입력된다.\n(입력값은 가상의 주민번호이다.)\nex)110011-0000000\n\nOUTPUT\n'-'를 제외한 주민번호 13자리를 모두 붙여 출력한다.\n'''\nimport string\nfnumber, bnumber = input().split('-')\nrrnumber = fnumber+bnumber\nprint(rrnumber)","sub_path":"codeUp/codeUp100/1020.py","file_name":"1020.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"215201680","text":"from playground.network.packet import PacketType\nfrom playground.network.packet.fieldtypes import INT32,UINT32, STRING, BUFFER, BOOL\nclass RequestPacket(PacketType):\n\tDEFINITION_IDENTIFIER = \"lab2b.student_x1.MyPacket\"\n\tDEFINITION_VERSION = \"1.0\"\n\tFIELDS = [\n\t\t(\"Request\", STRING)\n\t\t]\nclass QTimeZonePacket(PacketType):\n\tDEFINITION_IDENTIFIER = \"lab2b.student_x2.MyPacket\"\n\tDEFINITION_VERSION = \"1.0\"\n\tFIELDS = [\n\t\t(\"Question\", STRING)\n\t]\nclass ATimeZonePacket(PacketType):\n\tDEFINITION_IDENTIFIER = \"lab2b.student_x3.MyPacket\"\n\tDEFINITION_VERSION = \"1.0\"\n\tFIELDS = [\n\t\t(\"Answer\", STRING)\n\t]\nclass DatePacket(PacketType):\n\tDEFINITION_IDENTIFIER = \"lab2b.student_x4.MyPacket\"\n\tDEFINITION_VERSION = \"1.0\"\n\tFIELDS = [\n\t\t(\"month\", INT32),\n\t\t(\"day\", INT32),\n\t\t(\"year\", INT32),\n\t\t(\"hour\", INT32),\n\t\t(\"minute\", INT32)\n\t]\nclass FinalPacket(PacketType):\n\tDEFINITION_IDENTIFIER = \"lab2b.student_x5.MyPacket\"\n\tDEFINITION_VERSION = \"1.0\"\n\tFIELDS = [\n\t\t(\"thx\", BUFFER)\n\t]\n\t\ndef basicUnitTest():\n\trequest=RequestPacket()\t\n\trequest.Request = \"true\"\n\t#print(\"The orginal request data is : {}\".format(request.Request))\n\tpacketBytes1 = request.__serialize__()\n\trequestRecv = PacketType.Deserialize(packetBytes1)\n\tprint(requestRecv.Request)\n\tif request == requestRecv:\n\t\tprint(\"The request packet is the same!\")\n\telse:\n\t\tprint(\"Error!\")\n\n\tqtimezone=QTimeZonePacket()\n\tqtimezone.Question = \"What's your time zone?\"\n\tpacketBytes2 = qtimezone.__serialize__()\n\tqtimezoneRecv = PacketType.Deserialize(packetBytes2)\n\tif qtimezone == qtimezoneRecv:\n\t\tprint(\"The qtimezone packet is the same!\")\n\telse:\n\t\tprint(\"Error!\")\n\n\tatimezone=ATimeZonePacket()\n\tatimezone.Answer = \"UTC-5\"\n\tpacketBytes3 = atimezone.__serialize__()\n\tatimezoneRecv = PacketType.Deserialize(packetBytes3)\n\tif atimezone == atimezoneRecv:\n\t\tprint(\"The atimezone packet is the same!\")\n\telse:\n\t\tprint(\"Error!\")\n\n\tdate=DatePacket()\n\tdate.month = 9\n\tdate.day = 6\n\tdate.year = 2017\n\tdate.hour = 22\n\tdate.minute = 0\n\tpacketBytes4 = date.__serialize__()\n\tdateRecv = PacketType.Deserialize(packetBytes4)\n\tif date == dateRecv:\n\t\tprint(\"The date packet is the same!\")\n\telse:\n\t\tprint(\"Error!\")\n\n\tfinal=FinalPacket()\n\tfinal.thx = b\"Thanks!\"\n\tpacketBytes5 = final.__serialize__()\n\tfinalRecv = PacketType.Deserialize(packetBytes5)\n\tif final == finalRecv:\n\t\tprint(\"The final packet is the same!\")\n\telse:\n\t\tprint(\"Error!\")\nif __name__==\"__main__\":\n\tbasicUnitTest()\n","sub_path":"submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"480864703","text":"class inventory:\n    \"\"\" inventory class for player\n\n    Arugments\n    items -- array of items, blank for no items (default = [])\n    \"\"\"\n    def __init__(self, items=[]):\n        self.items = items\n\n    def get(self, name):\n        for item in self.items:\n            if item.name == name:\n                return item\n\n    def remove(self, name):\n        for idx, item in enumerate(self.items):\n            if item.name == name:\n                del self.items[idx]\n                return True\n        return False\n\n    def give(self, item):\n        self.items.append(item)\n        self.sort()\n\n    def printInv(self):\n        text = 'Inventory:'\n        if len(self.items) == 0:\n            print('Inventory Empty')\n        else:\n            for item in self.items:\n                text += f'\\n-{item.name.title()}\\n\\t{item.desc}'\n        print(text)\n\n    def sort(self):\n        # Make new lists of the names of the items to sort\n        # put weapons in weaponNames and consumables in consumablesNames\n        weaponNames = []\n        consumablesNames = []\n        for item in self.items:\n            if (item.type == 'weapon'):\n                weaponNames.append(item.name)\n            else:\n                consumablesNames.append(item.name)\n        weaponNames.sort()\n        consumablesNames.sort()\n        # replace inventory with sorted items from both lists\n        sortedItems = []\n        for name in weaponNames:\n            sortedItems.append(self.get(name))\n        for name in consumablesNames:\n            sortedItems.append(self.get(name))\n\n        self.items = sortedItems\n","sub_path":"inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"318971553","text":"url = 'https://mobile.twitter.com/search-advanced?q=a&lang=en%20near%3A%22san%20francisco%22%20within%3A15m'\r\nimport gevent.monkey\r\ngevent.monkey.patch_all()\r\nimport pandas as pd\r\nimport numpy as np\r\nimport lxml.html\r\nimport requests\r\nimport grequests\r\nfrom bs4 import BeautifulSoup\r\nfrom time import time\r\nimport json\r\n\r\nstates = [\"Alabama\",\"Alaska\",\"Arizona\",\"Arkansas\",\"California\",\"Colorado\",\r\n  \"Connecticut\",\"Delaware\",\"Florida\",\"Georgia\",\"Hawaii\",\"Idaho\",\"Illinois\",\r\n  \"Indiana\",\"Iowa\",\"Kansas\",\"Kentucky\",\"Louisiana\",\"Maine\",\"Maryland\",\r\n  \"Massachusetts\",\"Michigan\",\"Minnesota\",\"Mississippi\",\"Missouri\",\"Montana\",\r\n  \"Nebraska\",\"Nevada\",\"New Hampshire\",\"New Jersey\",\"New Mexico\",\"New York\",\r\n  \"North Carolina\",\"North Dakota\",\"Ohio\",\"Oklahoma\",\"Oregon\",\"Pennsylvania\",\r\n  \"Rhode Island\",\"South Carolina\",\"South Dakota\",\"Tennessee\",\"Texas\",\"Utah\",\r\n  \"Vermont\",\"Virginia\",\"Washington\",\"West Virginia\",\"Wisconsin\",\"Wyoming\"]\r\nmyUa = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'\r\nHEADER = {'User-Agent': myUa}\r\n\r\ndef getUserNames(pageData):\r\n\tsubstr = 'data-screen-name=\\\"'\r\n\tunames = []\r\n\twhile True:\r\n\t\tf_cursor = pageData.find(substr)\r\n\t\tif f_cursor==-1: break\r\n\t\telse: f_cursor += len(substr)\r\n\t\tpageData = pageData[f_cursor:]\r\n\t\ts_cursor = pageData.find('\\\"')\r\n\t\tuname = pageData[:s_cursor]\r\n\t\tunames += [uname]\r\n\treturn unames\r\n\r\ndef makeUrlList(new_pos):\r\n\tglobal states\r\n\tsince = '2019-05-01'\r\n\tuntil = '2019-12-01'\r\n\turls = []\r\n\ti = 0\r\n\tfor state in states:\r\n\t\tstate_parsed = str(state).replace(' ','%20')\r\n\t\turl = f'https://twitter.com/i/search/timeline?f=tweets&vertical=default&q=in%20ORis%20ORyou%20ORthat%20ORit%20ORfor%20near%3A\"{state_parsed}\"%20within%3A15mi%20since%3A{since}%20until%3A{until}&src=typd&include_available_features=1&include_entities=1&lang=en&max_position={new_pos[i]}&reset_error_state=false'\r\n\t\turls += [url]\r\n\t\ti+=1\r\n\r\n\treturn urls\r\n\r\ndef makeDataFrame(total_users):\r\n\tnuser = []\r\n\ttotal_users = set(total_users)\r\n\tfor user in total_users:\r\n\t\tif len(user)>3: nuser += [user]\r\n\tdf = pd.DataFrame(nuser)\r\n\treturn df\r\n\r\n\r\nnew_pos = ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','', '','','','','','', '','','','','','','','','','','','']\r\nstart = time()\r\nfor i in range(7000):\r\n\ttotal_users = []\r\n\tprint(i)\r\n\turls = makeUrlList(new_pos)\r\n\r\n\trs = (grequests.get(u, headers=HEADER) for u in urls)\r\n\trespones = grequests.map(rs)\r\n\tres_c = 0\r\n\tfor response in respones:\r\n\t\ttry:\r\n\t\t\tpage = json.loads(response.text)\r\n\t\texcept: pass\r\n\t\telse:\r\n\t\t\tnew_pos[res_c] = page['min_position']\r\n\t\t\tdatas = page['items_html']\r\n\t\t\tusernames = getUserNames(datas)\r\n\t\t\ttotal_users += usernames\r\n\t\t\tres_c += 1\r\n\tdf = makeDataFrame(total_users)\r\n\twith open('twitter_usernames.csv', 'a', newline='') as f:\r\n\t\tdf.to_csv(f, header=False, index=False)\r\n\r\n\r\n\r\nprint('elapsed: ', time()-start)\r\n","sub_path":"twitterUSernameScraper.py","file_name":"twitterUSernameScraper.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"33757869","text":"class Solution:\n    def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n        maxIncrease = sum([sum(i) for i in grid])\n        rotedArr = list(zip(*grid))\n\n        for i in grid:\n            for j in rotedArr:\n                maxIncrease -= min(max(i), max(j))\n        \n        return maxIncrease*-1","sub_path":"LeetCode-solution/problems/max_increase_to_keep_city_skyline/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"406391869","text":"# coding=utf-8\n# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\n\"\"\"\nFILE: sample_export_import_project_async.py\n\nDESCRIPTION:\n    This sample demonstrates how to export and import a Qna project.\n\nUSAGE:\n    python sample_export_import_project_async.py\n\n    Set the environment variables with your own values before running the sample:\n    1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource.\n    2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key.\n\"\"\"\n\nimport asyncio\n\nasync def sample_export_import_project_async():\n    # [START export_import_project]\n    import os\n    from azure.core.credentials import AzureKeyCredential\n    from azure.ai.language.questionanswering.authoring.aio import AuthoringClient\n\n    # get service secrets\n    endpoint = os.environ[\"AZURE_QUESTIONANSWERING_ENDPOINT\"]\n    key = os.environ[\"AZURE_QUESTIONANSWERING_KEY\"]\n\n    # create client\n    client = AuthoringClient(endpoint, AzureKeyCredential(key))\n    async with client:\n\n        # create project\n        project_name = \"IssacNewton\"\n        await client.create_project(\n            project_name=project_name,\n            options={\n                \"description\": \"biography of Sir Issac Newton\",\n                \"language\": \"en\",\n                \"multilingualResource\": True,\n                \"settings\": {\n                    \"defaultAnswer\": \"no answer\"\n                }\n            })\n\n        # export\n        export_poller = await client.begin_export(\n            project_name=project_name,\n            file_format=\"json\"\n        )\n        export_result = await export_poller.result()\n        export_url = export_result[\"resultUrl\"]\n\n        # import project\n        project = {\n            \"Metadata\": {\n                \"ProjectName\": \"IssacNewton\",\n                \"Description\": \"biography of Sir Issac Newton\",\n                \"Language\": \"en\",\n                \"DefaultAnswer\": None,\n                \"MultilingualResource\": False,\n                \"CreatedDateTime\": \"2022-01-25T13:10:08Z\",\n                \"LastModifiedDateTime\": \"2022-01-25T13:10:08Z\",\n                \"LastDeployedDateTime\": None,\n                \"Settings\": {\n                    \"DefaultAnswer\": \"no answer\",\n                    \"EnableHierarchicalExtraction\": None,\n                    \"DefaultAnswerUsedForExtraction\": None\n                }\n            }\n        }\n        import_poller = await client.begin_import_assets(\n            project_name=project_name,\n            options=project\n        )\n        await import_poller.result()\n\n        # list projects\n        print(\"view all qna projects:\")\n        qna_projects = client.list_projects()\n        async for p in qna_projects:\n            if p[\"projectName\"] == project_name:\n                print(\"project: {}\".format(p[\"projectName\"]))\n                print(\"\\tlanguage: {}\".format(p[\"language\"]))\n                print(\"\\tdescription: {}\".format(p[\"description\"]))\n\n    # [END export_import_project]\n\nif __name__ == '__main__':\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(sample_export_import_project_async())\n","sub_path":"sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/async_samples/sample_export_import_project_async.py","file_name":"sample_export_import_project_async.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"155394088","text":"import cv2\nimport argparse\nfrom wand.image import Image\nimport PythonMagick\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-f\", \"--first\", required=True,\n\thelp=\"first input image\")\nap.add_argument(\"-s\", \"--second\", required=True,\n\thelp=\"second\")\nap.add_argument(\"-w\", \"--w\", required=True)\nap.add_argument(\"-he\", \"--h\", required=True)\nargs = vars(ap.parse_args())\nimgA=cv2.imread(args[\"first\"])\nimgB=cv2.imread(args[\"second\"])\nw=int(args[\"w\"])\nh=int(args[\"h\"])\ndim=(w,h)\npath1=\"C:/Users/GOUAIED/OneDrive/Bureau/springbootrestdemo/springbootrestdemo1/screenshots/compare/imgA.png\"\npath2=\"C:/Users/GOUAIED/OneDrive/Bureau/springbootrestdemo/springbootrestdemo1/screenshots/compare/imgB.png\"\npath3=\"C:/Users/GOUAIED/OneDrive/Bureau/springbootrestdemo/springbootrestdemo1/screenshots/compare/diff.png\"\nimg1=cv2.resize(imgA, dim, interpolation = cv2.INTER_AREA)\nimg2=cv2.resize(imgB, dim, interpolation = cv2.INTER_AREA)\ncv2.imwrite(path1,img1)\ncv2.imwrite(path2,img2)\nA=Image(filename=path1)\nB=Image(filename=path2)\nB.fuzz = B.quantum_range * 0.20 \nresult_image, result_metric = B.compare(A)\nprint(result_metric)\nresult_image.save(filename=path3)","sub_path":"BackEnd/target/classes/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"415858859","text":"#!/usr/bin/python\n\n\"\"\"\n   Degradome picture generator\n   Usage:\n   picgen.py -degr first.csv second.csv -annotated ann1.tab ann2.tab -length tr.len\n   -degr: PareSnip csv files\n   -annotated: my own tab delimited annotation files\n   -length: transcript length file created by infoseq\n   -depth: depth file from samtools depth\n\"\"\"\n\nimport sys\nimport Image\nimport ImageDraw\nimport os\n\nclass Sample:\n\tdef __init__(self, ctg, cp, abu, duplex):\n\t\tself.alignment = duplex\n\t\tself.mirid     = \"no_mirid\"\n\t\tself.seq       = \"\"\n\t\tself.clevage   = cp\n\t\tself.abundance = abu\n\t\tself.category  = ctg\n\t\tself.parseDuplex(duplex)\n\tdef parseDuplex(self, duplex):\n\t\tself.seq = duplex.split(\"\\n\")[0].split()[1].replace(\"-\",\"\")\n\nclass Degradome:\n\tdef __init__(self):\n\t\tself.trid       = \"\"\n\t\tself.annotation = \"\"\n\t\tself.length     = 0\n\t\tself.samples    = dict()\n\t\tself.datapoints = dict()\n\tdef update(self, fields, fn):\n\t\tbase = os.path.basename(fn)\n\t\t#samplename = base.replace(\"_degradome.csv\", \"\")\n\t\tsamplename = base.replace(\".csv\", \"\")\n\t\tself.trid = fields[1]\n\t\tif samplename not in self.samples:\n\t\t\tself.samples[samplename] = list()\n\t\tself.samples[samplename].append(Sample(fields[2], int(fields[3]), float(fields[5]), fields[8]))\n\tdef maxabu(self):\n\t\tmaxabu = 0\n\t\tfor sid in self.samples:\n\t\t\tfor s in self.samples[sid]:\n\t\t\t\tif s.abundance > maxabu:\n\t\t\t\t\tmaxabu = s.abundance\n\t\tfor sample in self.datapoints:\n\t\t\tfor point in self.datapoints[sample]:\n\t\t\t\tif point[1] > maxabu:\n\t\t\t\t\tmaxabu = point[1]\n\t\treturn maxabu\n\ndef readDegradome(filename, deg):\n\tf = open(filename)\n\tf.readline()\n\tcounter = 0\n\tline = \"\"\n\tfor i in f:\n\t\tline += i\n\t\tif counter % 3 == 2:\n\t\t\tfields = line.replace('\"', \"\").rstrip().split(\",\")\n\t\t\tfields[1] = fields[1].split()[0]\n\t\t\tif fields[1] not in deg:\n\t\t\t\tdeg[fields[1]] = Degradome()\n\t\t\tdeg[fields[1]].update(fields, filename)\n\t\t\tline = \"\"\n\t\tcounter += 1\n\tf.close()\n\ndef readAnnot(filename, deg):\n\tf = open(filename)\n\tf.readline()\n\t#sample = os.path.basename(filename).replace(\"_degradome.tab\", \"\")\n\tsample = os.path.basename(filename).replace(\".tab\", \"\")\n\tfor i in f:\n\t\tfields = i.rstrip().split(\"\\t\")\n\t\tfields[0] = fields[0].split()[0]\n\t\tdeg[fields[0]].annotation = fields[1]\n\t\tfor j in deg[fields[0]].samples[sample]:\n\t\t\tif j.seq == fields[9]:\n\t\t\t\tj.mirid = fields[8]\n\t\t\t\tbreak\n\tf.close()\n\ndef readLen(filename, deg):\n\tf = open(filename)\n\tf.readline()\n\tfor i in f:\n\t\tfields = i.rstrip().split(\"\\t\")\n\t\tfields[0] = fields[0].split()[0]\n\t\tif fields[0] in deg:\n\t\t\tdeg[fields[0]].length = int(fields[1])\n\tf.close()\n\ndef readDepth(filename, deg):\n\tf = open(filename)\n\tsample = os.path.basename(filename).replace(\".depth\", \"\")\n\tfor i in f:\n\t\tfields = i.rstrip().split()\n\t\tfields[0] = fields[0].split()[0]\n\t\tif fields[0] in deg:\n\t\t\tif sample not in deg[fields[0]].datapoints:\n\t\t\t\tdeg[fields[0]].datapoints[sample] = list()\n\t\t\tdeg[fields[0]].datapoints[sample].append( (int(fields[1]), int(fields[2])) )\n\tf.close()\n\ndef drawHRuler(c, m):\n\tc.line([(90,900),(960, 900)], fill=\"black\")\n\tfor i in range(100, 960, 43):\n\t\tnum = str(int(float(i - 100) / 860.0 * m))\n\t\tc.line([(i, 900), (i, 910)], fill=\"black\")\n\t\t(w,h) = c.textsize(num)\n\t\tc.text((i - (w / 2), 912), num, fill=\"black\")\n\tc.text((500, 950), \"POSITION\", fill=\"black\")\n\ndef datatoscreen(x, y, ma, l):\n\tox = int(float(x) / float(l) * 860.0 + 100.0)\n\toy = int(900.0 - float(y) / float(ma) * 800.0)\n\treturn ox,oy\n\ndef drawVRuler(c,m):\n\tc.line([(100, 100), (100, 910)], fill=\"black\")\n\tstep = int(m) / 10\n\tif step < 1:\n\t\tstep = 1\n\tfor i in range(0, int(m), step):\n\t\tx,y = datatoscreen(0, i, m, 200)\n\t\tc.line([(100, y),(90, y)], fill=\"black\")\n\t\t(w,h) = c.textsize(str(i))\n\t\tc.text((90 - w, y - h / 2), str(i), fill=\"black\")\n#\tfor i in range(900, 100, -40):\n#\t\tnum = (float(900 - i) / 810.0) * m\n#\t\tnum = \"%.4f\" % (num)\n#\t\tc.line([(100, i),(90, i)], fill=\"black\")\n#\t\t(w,h) = c.textsize(num)\n#\t\tc.text((90 - w, i - h / 2), num, fill=\"black\")\n\ndef drawTitle(c, tr):\n\ttitle = tr.trid + \" \" + tr.annotation\n\t(w, h) = c.textsize(title)\n\tc.text((640 - w / 2, 50 - h / 2), title, fill=\"black\")\n\ndef drawDataPoints(c, tr, ma):\n\tcolors = {\"germ1\":\"rgb(246, 47, 8)\", \"germ2\":\"rgb(246, 47, 8)\", \"root1\":\"rgb(246, 161, 8)\", \"root2\":\"rgb(246, 161, 8)\", \"leaf1\": \"rgb(249, 235, 8)\", \"leaf2\": \"rgb(249, 235, 8)\", \"stem1\":\"rgb(87, 249, 8)\",\"stem2\":\"rgb(87, 249, 8)\", \"flower1\":\"rgb(8, 87, 249)\", \"flower2\":\"rgb(8, 87, 249)\", \"bti_germ\": \"rgb(249, 8, 116)\", \"bti_leaf\":\"rgb(229, 8, 249)\"}\n\tfor sample in tr.datapoints:\n\t\tfor point in tr.datapoints[sample]:\n\t\t\tx,y = datatoscreen(point[0], point[1], ma, tr.length)\n\t\t\tc.ellipse((x - 2, y - 2, x + 2, y + 2), fill=\"blue\")\n\tfor s in tr.samples:\n\t\tfor sample in tr.samples[s]:\n\t\t\tx,y = datatoscreen(sample.clevage, sample.abundance, ma, tr.length)\n\t\t\tc.rectangle((x - 2, y - 2, x + 2, y + 2), fill=colors[s])\n\t\t\ndef drawLegend(c, x, y):\n\tcolors = [\"rgb(246, 47, 8)\", \"rgb(246, 161, 8)\", \"rgb(249, 235, 8)\", \"rgb(87, 249, 8)\", \"rgb(8, 87, 249)\", \"rgb(229, 8, 249)\", \"rgb(249, 8, 116)\"]\n\tlabels = [\"seedling\", \"root\", \"leaf\", \"stem\", \"flower\", \"BTI leaf\", \"BTI seedling\"]\n\t(w,h) = c.textsize(\"BTI leaf\")\n\n\tfor i in range(7):\n\t\typos = y + i * h\n\t\tc.rectangle((x, ypos + (h / 2) - 2, x + 4, ypos + (h / 2) + 2), fill=colors[i])\n\t\tc.text((x + 10, ypos), labels[i], fill=\"black\")\n\ndef drawAlignment(c, tr):\n\talignment = dict()\n\tfor s in tr.samples:\n\t\tfor sample in tr.samples[s]:\n\t\t\talignment[sample.mirid] = [sample.alignment, sample.category]\n\typos = 180\n\tfor a in alignment:\n\t\t#name = 'nbe-' + a[4:]\n\t\tname = a\n\t\tc.text((980, ypos), name, fill=\"black\")\n\t\t(w, h) = c.textsize(name)\n\t\tc.text((980 + w, ypos), \" \" + alignment[a][1] + \" category\", fill = \"black\")\n\t\typos += h\n\t\tfor lines in alignment[a][0].split(\"\\n\"):\n\t\t\tc.text((980, ypos), lines, fill=\"black\")\n\t\t\typos += c.textsize(lines)[1]\n\n###### MAIN ########\n\ndegradome = dict()\n\nfor param in sys.argv[1:]:\n\tif param.startswith('-'):        # command\n\t\tif param == '-degr':\n\t\t\tswitch = 1\n\t\telif param == '-annotated':\n\t\t\tswitch = 2\n\t\telif param == '-length':\n\t\t\tswitch = 3\n\t\telif param == '-depth':\n\t\t\tswitch = 4\n\t\telse:\n\t\t\tswitch = 0\n\telse:                            # filename\n\t\tif switch == 1:\n\t\t\treadDegradome(param, degradome)\n\t\telif switch == 2:\n\t\t\treadAnnot(param, degradome)\n\t\telif switch == 3:\n\t\t\treadLen(param, degradome)\n\t\telif switch == 4:\n\t\t\treadDepth(param, degradome)\n\n# remove non conserved miRNAs\nremove = set()\nfor tr in degradome:\n\tallzero = True\n\tremovesample = set()\n\tfor s in degradome[tr].samples:\n\t\tdegradome[tr].samples[s] = [x for x in degradome[tr].samples[s] if x.mirid != \"no_mirid\"]\n\t\tif len(degradome[tr].samples[s]) != 0:\n\t\t\tallzero = False\n\t\telse:\n\t\t\tremovesample.add(s)\n\tif allzero:\n\t\tremove.add(tr)\n\telse:\n\t\tfor r in removesample:\n\t\t\tdel degradome[tr].samples[r]\nfor r in remove:\n\tdel degradome[r]\n\t\t\t\t\n\t\nfor tr in degradome:\n\timg    = Image.new('RGB', (1280, 1024), color=\"white\")\n\tcanvas = ImageDraw.Draw(img)\n\n\tma = degradome[tr].maxabu()\n\tdrawHRuler(canvas, degradome[tr].length)\n\tdrawVRuler(canvas, ma)\n\tdrawTitle(canvas, degradome[tr])\n\tdrawDataPoints(canvas, degradome[tr], ma)\n\t#drawLegend(canvas, 980, 100)\n\tdrawAlignment(canvas, degradome[tr])\n\n\trot = img.transpose(Image.ROTATE_270)\n\tcanvas = ImageDraw.Draw(rot)\n\tcanvas.text((470, 30), \"ABUNDANCE\", fill=\"black\")\n\timg = rot.transpose(Image.ROTATE_90)\n\n\timg.save(tr.split()[0] + \".png\", 'png')\n","sub_path":"picgen.py","file_name":"picgen.py","file_ext":"py","file_size_in_byte":7322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"238661684","text":"import glob\nimport os\nfrom random import shuffle\nfrom nltk.tokenize import TreebankWordTokenizer\nfrom nlpia.loaders import get_data\nimport yaml\nimport numpy as np\nword_vectors = get_data('w2v', limit=200000)\n\nclasses = set()\n\ndef pre_process_data(filepath):\n    with open(filepath) as file:\n        documents = yaml.full_load(file)\n        intents = documents['nlu']\n        dataset = []\n        for intent in intents:\n            intent_name = intent['intent']\n            classes.add(intent_name)\n            for example in intent['examples']:\n                dataset.append((intent_name, example))\n        shuffle(dataset)\n        return dataset\n\ndataset = pre_process_data('mood.yml')\nclasses = list(classes)\n\n\ndef tokenize_and_vectorize(dataset):\n    tokenizer = TreebankWordTokenizer()\n    vectorized_data = []\n    expected = []\n    for sample in dataset:\n        tokens = tokenizer.tokenize(sample[1])\n        sample_vecs = []\n        for token in tokens:\n            try:\n                sample_vecs.append(word_vectors[token])\n            except KeyError:\n                pass\n        vectorized_data.append(sample_vecs)\n    return vectorized_data\n\n\ndef collect_expected(dataset):\n    expected = []\n    for sample in dataset:\n        one_hot = np.zeros(len(classes))\n        one_hot[classes.index(sample[0])] = 1\n        expected.append(one_hot)\n    return expected\n\n\n\nvectorized_data = tokenize_and_vectorize(dataset)\n\nexpected = collect_expected(dataset)\n\nsplit_point = int(len(vectorized_data) * .8)\nx_train = vectorized_data[:split_point]\ny_train = expected[:split_point]\nx_test = vectorized_data[split_point:]\ny_test = expected[split_point:]\n\n\nmaxlen = 400\nbatch_size = 32\nembedding_dims = 300\nepochs = 100\n\ndef pad_trunc(data, maxlen):\n    new_data = []\n    zero_vector = []\n    for _ in range(len(data[0][0])):\n        zero_vector.append(0.0)\n    for sample in data:\n        if len(sample) > maxlen:\n            temp = sample[:maxlen]\n        elif len(sample) < maxlen:\n            temp = sample\n            additional_elems = maxlen - len(sample)\n            for _ in range(additional_elems):\n                temp.append(zero_vector)\n        else:\n            temp = sample\n        new_data.append(temp)\n    return new_data\n\nx_train = pad_trunc(x_train, maxlen)\nx_test = pad_trunc(x_test, maxlen)\n\n\n\nx_train = np.reshape(x_train, (len(x_train), maxlen, embedding_dims))\ny_train = np.array(y_train)\nx_test = np.reshape(x_test, (len(x_test), maxlen, embedding_dims))\ny_test = np.array(y_test)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, LSTM, Activation\nnum_neurons = 50\nmodel = Sequential()\n\nmodel.add(LSTM(\n  num_neurons, return_sequences=True,\n  input_shape=(maxlen, embedding_dims)))\n\nmodel.add(Dropout(.2))\nmodel.add(Flatten())\nmodel.add(Dense(len(classes)))\nmodel.add(Activation('softmax'))\n\nmodel.compile('rmsprop', 'categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\nmodel.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))\n\n\n\n\n# ==============\nvec_list = tokenize_and_vectorize([('mood_baaah', 'I am not feeling too well')])\ntest_vec_list = pad_trunc(vec_list, maxlen)\n\ntest_vec = np.reshape(test_vec_list, (len(test_vec_list), maxlen, embedding_dims))\nmodel.predict(test_vec)\nclasses[np.argmax(model.predict(test_vec))]","sub_path":"lstm_multi.py","file_name":"lstm_multi.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"33801696","text":"\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport sys\nimport os\n\n\n\n\nk = int(sys.argv[1]) # kernel_size\nn = int(sys.argv[2]) # the number of layers\nfid = int(sys.argv[3]) # index contained in the name of features saved\nfoid = int(sys.argv[4]) # index of folder where the features will be saved to\ngpu_ = str(sys.argv[5]) # device id\n\n\nos.environ['CUDA_VISIBLE_DEVICES'] = gpu_\n\n\nw_init = tf.random_normal_initializer(mean=0, stddev=1) # kernel initialization\nb_init = tf.random_normal_initializer(mean=0, stddev=1) # bias initialization\n\n\ndef random_hp(data, kernel_size, num_layers, n):\n    # num_layers = 6\n\n    # kernel_size = 3\n\n    conv = tf.contrib.layers.conv2d(\n        inputs=data,\n        num_outputs=n,\n        kernel_size=kernel_size,\n        stride=1,\n        padding='VALID',\n        activation_fn=tf.sign,\n        weights_initializer=w_init,\n        biases_initializer=b_init,\n        data_format=\"NCHW\",\n    ) # typical convolutional kernel\n\n    for i in range(num_layers - 1):\n        var = tf.get_variable(str(i), [kernel_size, kernel_size, n, 1], initializer=w_init, dtype=tf.float32)\n        conv = tf.nn.depthwise_conv2d(conv, var, [1, 1, 1, 1], 'VALID', data_format='NCHW') # depthwise convolution\n        biases = tf.get_variable('bias_' + str(i), [n], initializer=b_init, dtype=tf.float32)\n        conv = tf.nn.bias_add(conv, biases, data_format='NCHW')\n        conv = tf.sign(conv)\n\n    global_pool = tf.reduce_mean(input_tensor=conv, axis=[2,3]) # global average\n\n    p = tf.contrib.layers.flatten(global_pool)\n\n    return p\n\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\nsess = tf.Session(config=config)\n\nx = tf.placeholder(tf.float32, shape=[None, 3, 96, 96])\n\nn_features = 2500 # the number of features you want to generate\nbatch_size = 20\n\nfeatures = random_hp(data=x, kernel_size=k, num_layers=n, n=n_features)\n\n\n# load data\ntrain_data = np.load('x_train.npy')\ntest_data = np.load('x_test.npy')\n\n# normalization on each images\ntrain_data = (train_data - train_data.mean(axis=(1, 2, 3), keepdims=True)) / train_data.std(axis=(1, 2, 3),\n                                                                                                keepdims=True)\ntest_data = (test_data - test_data.mean(axis=(1, 2, 3), keepdims=True)) / test_data.std(axis=(1, 2, 3),\n                                                                                            keepdims=True)\n\ndef save_features(index, folderid):\n    path = 'features%d/'%folderid\n    train_features = np.zeros(shape=(train_data.shape[0], n_features), dtype=np.float32)\n    for i in range(train_data.shape[0] // batch_size):\n        tmp = train_data[i * batch_size:(i + 1) * batch_size]\n        train_features[i * batch_size:(i + 1) * batch_size] = sess.run(features, feed_dict={x: tmp})\n\n    np.save(path+'train_data_%d.npy' % index, train_features)\n    del train_features\n\n    test_features = np.zeros(shape=(test_data.shape[0], n_features), dtype=np.float32)\n    for i in range(test_data.shape[0] // batch_size):\n        tmp = test_data[i * batch_size:(i + 1) * batch_size]\n        test_features[i * batch_size:(i + 1) * batch_size] = sess.run(features, feed_dict={x: tmp})\n\n    np.save(path+'test_data_%d.npy' % index, test_features)\n    del test_features\n\n\na = time.time()\n\nsess.run(tf.global_variables_initializer())\nsave_features(fid, foid)\n\nprint('Cost: %.3f' % (time.time() - a))\n","sub_path":"stl10/stack_features.py","file_name":"stack_features.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"460103173","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom . import views\nurlpatterns = [\n    url(r'^qq/authorization/$', views.OauthLoginView.as_view()),\n    url(r'^sina/authorization/$', views.SinaLoginView.as_view()),\n    url(r'^qq/user/$', views.OauthView.as_view()),\n    url(r'^sina/user/$', views.SinaView.as_view()),\n    url(r'^image_codes/(?P[\\d\\w-]+)/$', views.ImageVerify),\n]\n","sub_path":"meiduo_mall/meiduo_mall/apps/oauth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"476606841","text":"'''\n\tRaspberry Pi GPIO Status and Control\n\tadapted by Arnaldo Viana\n'''\nimport RPi.GPIO as GPIO\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n#define actuators GPIOs\nledRed = 2\nledYlw = 3\nledGrn = 4\nledRed1 = 17\nledYlw1 = 27\nledGrn1 = 22\n\n#initialize GPIO status variables\nledRedSts = 0\nledYlwSts = 0\nledGrnSts = 0\nledRedSts1 = 0\nledYlwSts1 = 0\nledGrnSts1 = 0\n\n# Define led pins as output\nGPIO.setup(ledRed, GPIO.OUT)   \nGPIO.setup(ledYlw, GPIO.OUT) \nGPIO.setup(ledGrn, GPIO.OUT)\nGPIO.setup(ledRed1, GPIO.OUT)   \nGPIO.setup(ledYlw1, GPIO.OUT) \nGPIO.setup(ledGrn1, GPIO.OUT) \n\n# turn leds OFF \nGPIO.output(ledRed, GPIO.LOW)\nGPIO.output(ledYlw, GPIO.LOW)\nGPIO.output(ledGrn, GPIO.LOW)\nGPIO.output(ledRed1, GPIO.LOW)\nGPIO.output(ledYlw1, GPIO.LOW)\nGPIO.output(ledGrn1, GPIO.LOW)\n\t\n@app.route(\"/\")\ndef index():\n\t# Read Sensors Status\n\tledRedSts = GPIO.input(ledRed)\n\tledYlwSts = GPIO.input(ledYlw)\n\tledGrnSts = GPIO.input(ledGrn)\n\tledRedSts1 = GPIO.input(ledRed1)\n\tledYlwSts1 = GPIO.input(ledYlw1)\n\tledGrnSts1 = GPIO.input(ledGrn1)\n\n\ttemplateData = {\n              'title' : 'GPIO output Status!',\n              'ledRed'  : ledRedSts,\n              'ledYlw'  : ledYlwSts,\n              'ledGrn'  : ledGrnSts,\n              'ledRed1'  : ledRedSts1,\n              'ledYlw1'  : ledYlwSts1,\n              'ledGrn1'  : ledGrnSts1,\n        }\n\treturn render_template('index.html', **templateData)\n\t\n@app.route(\"//\")\ndef action(deviceName, action):\n\tif deviceName == 'ledRed':\n\t\tactuator = ledRed\n\tif deviceName == 'ledYlw':\n\t\tactuator = ledYlw\n\tif deviceName == 'ledGrn':\n\t\tactuator = ledGrn\n\tif deviceName == 'ledRed1':\n\t\tactuator = ledRed1\n\tif deviceName == 'ledYlw1':\n\t\tactuator = ledYlw1\n\tif deviceName == 'ledGrn1':\n\t\tactuator = ledGrn1\n   \n\tif action == \"on\":\n\t\tGPIO.output(actuator, GPIO.HIGH)\n\tif action == \"off\":\n\t\tGPIO.output(actuator, GPIO.LOW)\n\t\t     \n\tledRedSts = GPIO.input(ledRed)\n\tledYlwSts = GPIO.input(ledYlw)\n\tledGrnSts = GPIO.input(ledGrn)\n\tledRedSts1 = GPIO.input(ledRed1)\n\tledYlwSts1 = GPIO.input(ledYlw1)\n\tledGrnSts1 = GPIO.input(ledGrn1)\n   \n\ttemplateData = {\n              'ledRed'  : ledRedSts,\n              'ledYlw'  : ledYlwSts,\n              'ledGrn'  : ledGrnSts,\n              'ledRed1'  : ledRedSts1,\n              'ledYlw1'  : ledYlwSts1,\n              'ledGrn1'  : ledGrnSts1,\n\t}\n\treturn render_template('index.html', **templateData)\n\nif __name__ == \"__main__\":\n   app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"rpiWebServer_ex3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"108597333","text":"from datetime import datetime\nimport io\nimport serial\n\n\nclass Thermometer(object):\n\n    def __init__(self):\n        \"\"\"\n        Initialise the thermometer\n        \"\"\"\n        self.ser = serial.Serial(\n            port='/dev/ttyUSB0', \n            baudrate=9600) \n        self.sio = io.TextIOWrapper(\n            io.BufferedRWPair(self.ser, self.ser, 1),\n            encoding='ascii', newline='\\r')\n        self.sio._CHUNK_SIZE = 1\n\n\n    def get_measurement(self):\n        \"\"\"\n        Returns tuple of (temperature, when)\n        temperature is float and when is datetime object\n        \"\"\"\n        datastring = self.sio.readline().strip()\n        temp = float(datastring[:6])\n        when = datetime.utcnow()\n        return (temp, when)\n\n\n    def close(self):\n        self.ser.close()\n","sub_path":"python/exercises/example_code/temperature_probe_object_oriented_example/thermometer.py","file_name":"thermometer.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"358420263","text":"#!/usr/bin/env python\n\nimport multiprocessing\nimport numpy as np\nimport os\nfrom pylab import *\nimport scipy\nimport scipy.stats\n\n# TODO use this style instead\n# date, rain, high, low = zip(*csv.reader(file(\"weather.csv\")))\n\nrep_titles = {\"grow\": \"Grow\", \"bubble_down\": \"Bubble-down\"}\ndist_titles = {\n    \"genotype\": \"Genotype\",\n    \"phenotype\": \"Phenotype\",\n    \"semantics\": \"Semantic\",\n    \"fitness\": \"Fitness\"\n    }\n\ndef gp_distances_boxplots(basedir):\n    print(r\"\\begin{tabular}{l|l|l|l|l}\")\n    print(r\" Representation & Distance & Random & Mutation & Crossover \\\\ \\hline\")\n    \n    reps = [\"grow\", \"bubble_down\"]\n    for rep in reps:\n        ops = [\"random\", \"mutation\", \"crossover\"]\n        process(basedir, ops, rep)\n        \n    print(r\"\\end{tabular}\")        \n\ndef process(basedir, ops, rep):\n    data = {}\n    dtypes = [\"genotype\", \"phenotype\", \"semantics\", \"fitness\"]\n    for op in ops:\n        filename = os.path.join(basedir, rep, op + \"_distances.dat\")\n        txt = open(filename).read()\n        _data = []\n        for line in txt.split(\"\\n\"):\n            if len(line) < 2: continue\n            parts = line.split()\n            g, p, s, f = parts\n            g = int(g)\n            p = int(p)\n            s = float(s)\n            f = float(f)\n            if g == 0: continue\n            _data.append((g, p, s, f))\n        _data = np.array(_data)\n        _data = _data.transpose()\n        data[op] = _data\n    \n    for i, d in enumerate(dtypes):\n        bpdata = [data[op][i] for op in ops]\n        # make_boxplot(basedir, ops, rep, d, bpdata)\n        print_data(rep, d, bpdata)\n        \ndef make_boxplot(basedir, ops, rep, dist, bpdata):\n    codename = rep + \"_\" + dist\n    fig = figure(figsize=(6, 4))\n    ax = fig.add_subplot(111)\n    ax.boxplot(bpdata)\n    if rep in [\"semantics\", \"fitness\"]:\n        ax.set_yscale('log')\n    ax.set_xticklabels(ops)\n    ax.set_ylabel(dist + \" distance\")\n    outfilename = os.path.join(basedir, codename + \".pdf\")\n    print(\"saving to \" + outfilename)\n    fig.savefig(outfilename)\n    close()\n\ndef print_data(rep, dist, bpdata):\n    # we use Mann-Whitney non-parametric test\n    # because fitness values have many, huge outliers\n    \n    # random v mutation\n    mu, mp = scipy.stats.mannwhitneyu(bpdata[0], bpdata[1])\n    # multiply by 2 for two-sided \n    mp *= 2.0\n    # random v crossover\n    cu, cp = scipy.stats.mannwhitneyu(bpdata[0], bpdata[2])\n    # multiply by 2 for two-sided \n    cp *= 2.0\n\n    if mp < 0.01:\n        mps = r\"{\\bf *}\"\n    else:\n        mps = \"\"\n    if cp < 0.01:\n        cps = r\"{\\bf *}\"\n    else:\n        cps = \"\"\n    \n    rmean = np.mean(bpdata[0])\n    rmedian = np.median(bpdata[0])\n    rstddev = np.std(bpdata[0])\n    mmean = np.mean(bpdata[1])\n    mmedian = np.median(bpdata[1])\n    mstddev = np.std(bpdata[1])\n    cmean = np.mean(bpdata[2])\n    cmedian = np.median(bpdata[2])\n    cstddev = np.std(bpdata[2])\n\n    print(rep)\n    print(dist)\n    print(\"random v mutation\", mu, mp)\n    print(\"random v crossover\", cu, cp)\n    print(\"random\", rmean, rstddev, rmedian)\n    print(\"mutation\", mmean, mstddev, mmedian)\n    print(\"crossover\", cmean, cstddev, cmedian)\n\n    print(r\" %s & %s & %.2g & %.2g \\hfill %s & %.2g \\hfill %s \\\\\" % (\n            rep_titles[rep],\n            dist_titles[dist],\n            rmedian, \n            mmedian, mps,\n            cmedian, cps))\n\n    # print(r\"\\begin{tabular}{l|ll|lll|lll}\")\n    # print(r\"         & Random      &      & Mutation       &       & Crossover       &       \\\\\")\n    # print(r\"Distance & mean (sd)   & med  & mean (sd)      & med   & mean (sd)       & med   \\\\ \\hline\")\n    # print(r\" %s      & %.1g (%.1g) & %.1g & %.1g (%.1g) %s & %.1g  & %.1g (%.1g) %s  & %.1g  \\\\\" % (\n    #         dist,\n    #         rmean, rstddev, rmedian, \n    #         mmean, mstddev, mps, mmedian,\n    #         cmean, cstddev, cps, cmedian))\n    # print(r\"\\end{tabular}\")        \n                \nif __name__ == \"__main__\":\n    gp_distances_boxplots(sys.argv[1])\n","sub_path":"src/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"324997789","text":"from tkinter import *\nimport tkinter as tk\n\nroot = tk.Tk()\n\nroot.title(\"Sleep Calculator\")\n\nroot.geometry(\"600x450\")\n\nroot.configure(bg=\"#001245\")\n\n\nnameQuestion = tk.Label(root, text=\"What is your name?\", font = ('Avenir',15), bg=\"#001245\", fg=\"#0068f0\").grid(row=0, padx=(80, 50))\n\ne1 = Entry(root)\ne1.grid(row=0, column=1)\n\ndef getName ():  \n    name = e1.get()\n    print(name)\n\nbutton1 = tk.Button(text=\"Submit\", command=getName)\nbutton1.grid(row=0,column=2)\n    \n\n\n\n\nage = tk.Label(root, text=\"How old are you?\", font = ('Avenir',15), bg=\"#001245\", fg=\"#0068f0\").grid(row=1, pady=10, padx=(80, 50))\n\nagevariable = StringVar(root)\nagevariable.set(\"8\") # default value\n\nageDropdown = OptionMenu(root, agevariable, \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\")\nageDropdown.grid(row=1, column=1)\n\n\ndef getAge ():  \n    age = agevariable.get()\n    print(age)\n\nbutton2 = tk.Button(text=\"Submit\", command=getAge)\nbutton2.grid(row=1,column=2)\n\n\n\n\n\n\nroot.mainloop()","sub_path":"Unit 1 Project/SleepCalc2.py","file_name":"SleepCalc2.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"288880175","text":"# coding=utf-8\nimport itchat\nimport time\nimport random\nfrom itchat.content import *\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nitchat.auto_login(True)\nroom_name_class = '府小六年级二班'\nroom_id_class = itchat.search_chatrooms(name=room_name_class)[0].get('UserName')\nroom_name_family = '有家有爱'\nroom_id_family = itchat.search_chatrooms(name=room_name_family)[0].get('UserName')\n\n\nscheduler = BackgroundScheduler()\n\n\ndef send_message_to_room():\n    print('ok.......')\n    itchat.send('杨老师您好,没有新增情况。', toUserName=room_id_class)\n\n\nscheduler.add_job(send_message_to_room, 'cron', hour=7, minute=0, second=0, args=())\nscheduler.start()\n\n\n@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)\ndef text_reply(msg):\n    if msg.User['NickName'] == room_name_class:\n        if msg['ActualNickName'] == '数学老师' or msg['ActualNickName'] == '英语周老师' or msg['ActualNickName'] == '白兰鸽' or ('语文' in msg['ActualNickName']):\n            if msg['Type'] == 'Video' or msg['Type'] == 'Picture' or msg['Type'] == 'Recording' or msg['Type'] == 'Attachment':\n                msg['Text'](msg['FileName'])\n                itchat.send(msg['ActualNickName'] + '老师发布的:', toUserName=room_id_family)\n                itchat.send('@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']), toUserName=room_id_family)\n\n            if msg['Type'] == 'Text':\n                time.sleep(random.uniform(0.1, 2.5))\n                # itchat.send(msg['ActualNickName'] + '老师说的:', toUserName=room_id_family)\n                itchat.send(msg['ActualNickName'] + '说:\\n' + msg['Content'], toUserName=room_id_family)\n\n\nitchat.run()\n","sub_path":"微信机器人0215/wechat_robot_1.py","file_name":"wechat_robot_1.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"336491796","text":"\"\"\"\nClass for retrieving data from several datasets\n\"\"\"\nimport importlib\nimport os.path\nfrom .metadatareader.xray_image_metadata import XRayImageMetadata\n\nclass DatasetBaseInterface: #pylint: disable=too-few-public-methods\n    \"\"\"\n    Interface for Dataset Reader Classes\n    \"\"\"\n    dataset = None\n\n    def get_data(self):\n        \"\"\"\n        Get images and metadata from a dataset\n        \"\"\"\n        raise NotImplementedError\n\n\n\nclass DatasetBase(DatasetBaseInterface): #pylint: disable=too-few-public-methods\n    \"\"\"\n     Store the path where the files are saved so that the data can be read.\n    \"\"\"\n    dataset = None\n    metadata_folder = None\n    images_folder = None\n\n    def __init__(self, **kwargs):\n        self.path = kwargs.get(\"path\")\n        self.metadata_path = os.path.join(self.path,\n                                          self.metadata_folder)\n        self.images_path = os.path.join(self.path,\n                                        self.images_folder)\n\n    def get_data(self):\n        metadata_reader = importlib.import_module(\n                f\"xrayreader.metadatareader.{self.dataset}\").Reader\n        images_reader = importlib.import_module(\n                f\"xrayreader.images.{self.dataset}\").Reader\n\n        data = {\"data\": {}}\n        data['data']['dataset'] = self.dataset\n        if self.images_folder:\n            data['data']['images'] = images_reader(path=self.images_path).get_images()\n        if self.metadata_folder:\n            data['data']['metadata'] = metadata_reader(path=self.metadata_path).parse_files()\n        return data\n\n\nclass ChinaDataset(DatasetBase):#pylint: disable=too-few-public-methods\n    \"\"\"\n    Get metadata and images from China.\n    \"\"\"\n    dataset = 'china'\n    metadata_folder = 'ClinicalReadings'\n    images_folder = 'CXR_png'\n\n\nclass MontgomeryDataset(DatasetBase): #pylint: disable=too-few-public-methods\n    \"\"\"\n    Get metadata and images from Montgomery.\n    \"\"\"\n    dataset = 'montgomery'\n    metadata_folder = 'ClinicalReadings'\n    images_folder = 'CXR_png'\n\n\nclass IndiaDataset(DatasetBaseInterface):\n    \"\"\"\n    Get information from India.\n    \"\"\"\n    dataset = 'india'\n\n    def __init__(self, **kwargs):\n        self.path = kwargs.get(\"path\")\n        self.images_folder = kwargs.get(\"folder\", \"DatasetA\")\n\n\n    @staticmethod\n    def get_metadata(imagename, filename):\n        \"\"\"\n        Return the name of the file and indicate\n        whether the patient from India has tb.\n\n        :param: imagename\n        :type: string\n        :return: list with the filenames and `True` if the patient has tb, `False` otherwise\n        :rtype: list\n        \"\"\"\n        return (imagename, XRayImageMetadata(\n                filename=filename,\n                check_normality=imagename[0] == 'p'\n        ))\n\n\n    def get_image_reader_module(self):\n        \"\"\"\n        Returns the path where the images are saved\n        and the dataset where this images are from.\n        \"\"\"\n        images_reader = importlib.import_module(\n                f\"xrayreader.images.{self.dataset}\").Reader\n        return images_reader(path=self.path,\n                             dataset=self.images_folder)\n\n    def get_data(self):\n        data = {\"data\": {}}\n        data['data']['dataset'] = self.dataset\n        if self.images_folder:\n            images = self.get_image_reader_module().get_images()\n            data['data']['images'] = images\n            data['data']['metadata'] = dict([\n                self.get_metadata(imagename, img.filename)\n                for imagename, img in images.items()\n            ])\n        return data\n\n\nclass Dataset: #pylint: disable=too-few-public-methods\n    \"\"\"\n    Return the data from a specific dataset,\n    India, China, or Montgomery.\n    \"\"\"\n    _datasets = {\n        \"india\": IndiaDataset,\n        \"montgomery\": MontgomeryDataset,\n        \"china\": ChinaDataset\n    }\n\n    def __init__(self, name, path):\n        self.name = name\n        self.path = path\n\n    def _get_dataset(self):\n        \"\"\"\n        Return the name and the path of the dataset.\n\n        :return: name of the dataset and it's path\n        :rtype: string\n        \"\"\"\n        if self.name not in self._datasets:\n            raise ValueError(\"Dataset not found\")\n        return self._datasets.get(self.name)(path=self.path)\n\n    def get_data(self):\n        \"\"\"\n        Return the data from the dataset.\n\n        :return: list with the metadata of the dataset\n        :rtype: list\n        \"\"\"\n        dataset = self._get_dataset()\n        return dataset.get_data()\n","sub_path":"xrayreader/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"641707435","text":"import asyncio\nimport logging\nimport random\n\nimport alphabot.bot\n\n# Actual bot instance. Will be available because this file should only be\n# invoked inside of a script-discovery code of the bot itself!\nbot = alphabot.bot.get_instance()\nlog = logging.getLogger(__name__)\n\n\n@bot.on_schedule(minute='0')\nasync def still_here():\n    channel = bot.get_channel(name='alphabot-debug')\n    if channel:\n        await channel.send('I am still here!')\n\n\n@bot.add_command('button-example')\nasync def button_example(message):\n    action = await message.button_prompt(\n        'Is this a good button example?',\n        ['No', 'Yes'])\n\n    await message.reply('Got \"%s\" from the button.' % action)\n\n\n@bot.on(type='message', message='acknowledge')\nasync def acknowledge(event):\n    message = bot.event_to_chat(event)\n    await message.reply('Tadaa!')\n    log.info('Attached to a message!')\n\n\n@bot.add_command('lunch')\nasync def lunch_suggestion(message):\n    await message.reply(\"How about Chipotle?\")\n\n    if bot.engine == 'slack':\n        await message.react('burrito')\n\n\n@bot.add_command('hi')\nasync def conversation(message):\n    log.info('Starting a conversation')\n    await message.reply(\"How are you?\")\n\n    response = await message.listen_for('(.*)')\n\n    await message.reply(\"%s? Me too!\" % response.text)\n\n\n@bot.add_command('random number')\n@bot.learn(\n    ['Give me a random number',\n     'roll the dice',\n     'generatet a random number'])\nasync def random_number(message):\n    last_r = await bot.memory.get('random_number')\n    r = random.randint(1, 10)\n    await bot.memory.save('random_number', r)\n\n    await message.reply(\"Random number is %s\" % r)\n    if last_r is not None:\n        await asyncio.sleep(1)\n        await message.reply(\"But last time I said it was %s\" % last_r)\n","sub_path":"alphabot/sample-scripts/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"101337654","text":"#coding:utf8\n'''\nPornhub Downloader\n'''\nfrom __future__ import division, print_function, unicode_literals\nfrom io import BytesIO\nimport os\nimport downloader\nimport ree as re\nfrom utils import (Downloader, Soup, try_n, LazyUrl, urljoin, get_print,\n                   Session, get_max_range, filter_range, get_ext,\n                   lock, format_filename, clean_title, get_resolution)\nimport clf2\nimport utils\nfrom m3u8_tools import playlist2stream, M3u8_stream\nimport errors\nimport json\nimport functools\nimport operator\n\n\n\nclass File(object):\n    '''\n    File\n    '''\n\n    def __init__(self, id_, title, url, url_thumb):\n        self.id_ = id_\n        self.title = clean_title('{}'.format(title))\n        self.url = url\n        \n        ext = get_ext(self.url)\n        if ext.lower() == '.m3u8':\n            try:\n                self.url = playlist2stream(self.url, n_thread=4)\n            except:\n                self.url = M3u8_stream(self.url, n_thread=4)\n            \n        self.url_thumb = url_thumb\n        self.thumb = BytesIO()\n        downloader.download(self.url_thumb, buffer=self.thumb)\n        \n        if ext.lower() == '.m3u8':\n            ext = '.mp4'\n        self.filename = format_filename(self.title, self.id_, ext)\n        print('filename:', self.filename)\n\n\nclass Video(object):\n    '''\n    Video\n    '''\n    _url = None\n    filename = None\n    thumb = None\n\n    def __init__(self, url, cw, session):\n        url = Downloader_pornhub.fix_url(url)\n        self.url = LazyUrl(url, self.get, self)\n        self.cw = cw\n        self.session = session\n\n    @try_n(2)\n    def get(self, url):\n        '''\n        get\n        '''\n        cw = self.cw\n        session = self.session\n        print_ = get_print(cw)\n        if self._url:\n            return self._url\n\n        id_ = re.find(r'viewkey=(\\w+)', url, re.IGNORECASE) or \\\n              re.find(r'/embed/(\\w+)', url, re.IGNORECASE, err='no id')\n        print_('id: {}'.format(id_))\n        if 'viewkey=' not in url.lower() and '/gif/' not in url.lower():\n            url = urljoin(url, '/view_video.php?viewkey={}'.format(id_))\n\n        url_test = url.replace('pornhubpremium.com', 'pornhub.com')\n        try:\n            html = downloader.read_html(url_test, session=session)\n            soup = Soup(html)\n            if soup.find('div', id='lockedPlayer'):\n                print_('Locked player')\n                raise Exception('Locked player')\n            url = url_test\n        except: #3511\n            url = url.replace('pornhub.com', 'pornhubpremium.com')\n            html = downloader.read_html(url, session=session)\n            \n        soup = Soup(html)\n        soup = fix_soup(soup, url, session, cw)\n        html = soup.html\n\n        # removed\n        if soup.find('div', class_='removed'):\n            raise Exception('removed')\n\n        gif = soup.find('div', {'id': 'gifImageSection'})\n        if gif:\n            print_('GIF')\n            id_ = url.split('/gif/')[1]\n            id_ = re.findall('[0-9a-zA-Z]+', id_)[0]\n            \n            jss = list(gif.children)\n            for js in jss:\n                if 'data-mp4' in getattr(js, 'attrs', {}):\n                    break\n            else:\n                raise Exception('gif mp4 url not found')\n\n            title = js['data-gif-title']\n            url = js['data-mp4']\n            url_thumb = re.find(r'https?://.+?.phncdn.com/pics/gifs/.+?\\.jpg', html, err='no thumb')\n            file = File('gif_{}'.format(id_), title, url, url_thumb)\n        else:\n            if id_ is None:\n                raise Exception('no id')\n\n            print_('Video')\n\n            # 1968\n            #title = j['video_title']\n            title = soup.find('h1', class_='title').text.strip()\n\n            video_urls = []\n            video_urls_set = set()\n\n            def int_or_none(s):\n                try:\n                    return int(s)\n                except:\n                    return None\n\n            def url_or_none(url):\n                if not url or not isinstance(url, str):\n                    return None\n                url = url.strip()\n                return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None\n            \n            flashvars  = json.loads(re.find(r'var\\s+flashvars_\\d+\\s*=\\s*({.+?});', html, err='no flashvars'))\n            url_thumb = flashvars.get('image_url')\n            media_definitions = flashvars.get('mediaDefinitions')\n            if isinstance(media_definitions, list):\n                for definition in media_definitions:\n                    if not isinstance(definition, dict):\n                        continue\n                    video_url = definition.get('videoUrl')\n                    if not video_url or not isinstance(video_url, str):\n                        continue\n                    if video_url in video_urls_set:\n                        continue\n                    video_urls_set.add(video_url)\n                    video_urls.append(\n                        (video_url, int_or_none(definition.get('quality'))))\n\n            def extract_js_vars(webpage, pattern, default=object()):\n                assignments = re.find(pattern, webpage, default=default)\n                if not assignments:\n                    return {}\n\n                assignments = assignments.split(';')\n\n                js_vars = {}\n\n                def remove_quotes(s):\n                    if s is None or len(s) < 2:\n                        return s\n                    for quote in ('\"', \"'\", ):\n                        if s[0] == quote and s[-1] == quote:\n                            return s[1:-1]\n                    return s\n\n                def parse_js_value(inp):\n                    inp = re.sub(r'/\\*(?:(?!\\*/).)*?\\*/', '', inp)\n                    if '+' in inp:\n                        inps = inp.split('+')\n                        return functools.reduce(\n                            operator.concat, map(parse_js_value, inps))\n                    inp = inp.strip()\n                    if inp in js_vars:\n                        return js_vars[inp]\n                    return remove_quotes(inp)\n\n                for assn in assignments:\n                    assn = assn.strip()\n                    if not assn:\n                        continue\n                    assn = re.sub(r'var\\s+', '', assn)\n                    vname, value = assn.split('=', 1)\n                    js_vars[vname] = parse_js_value(value)\n                return js_vars\n\n            def add_video_url(video_url):\n                v_url = url_or_none(video_url)\n                if not v_url:\n                    return\n                if v_url in video_urls_set:\n                    return\n                video_urls.append((v_url, None))\n                video_urls_set.add(v_url)\n\n            def parse_quality_items(quality_items):\n                q_items = json.loads(quality_items)\n                if not isinstance(q_items, list):\n                    return\n                for item in q_items:\n                    if isinstance(item, dict):\n                        add_video_url(item.get('url'))\n\n            if not video_urls:\n                print_('# extract video_urls 2')\n                FORMAT_PREFIXES = ('media', 'quality', 'qualityItems')\n                js_vars = extract_js_vars(\n                    html, r'(var\\s+(?:%s)_.+)' % '|'.join(FORMAT_PREFIXES),\n                    default=None)\n                if js_vars:\n                    for key, format_url in js_vars.items():\n                        if key.startswith(FORMAT_PREFIXES[-1]):\n                            parse_quality_items(format_url)\n                        elif any(key.startswith(p) for p in FORMAT_PREFIXES[:2]):\n                            add_video_url(format_url)\n                if not video_urls and re.search(\n                        r'<[^>]+\\bid=[\"\\']lockedPlayer', html):\n                    raise Exception('Video is locked')\n\n##            if not video_urls:\n##                print_('# extract video_urls 3')\n##                js_vars = extract_js_vars(\n##                    dl_webpage('tv'), r'(var.+?mediastring.+?)')\n##                add_video_url(js_vars['mediastring'])\n\n            for mobj in re.finditer(\n                    r']+\\bclass=[\"\\']downloadBtn\\b[^>]+\\bhref=([\"\\'])(?P(?:(?!\\1).)+)\\1',\n                    html):\n                video_url = mobj.group('url')\n                if video_url not in video_urls_set:\n                    video_urls.append((video_url, None))\n                    video_urls_set.add(video_url)\n\n            video_urls_ = video_urls\n            video_urls = []\n            for video_url, height in video_urls_:\n                if '/video/get_media' in video_url:\n                    print_(video_url)\n                    medias = downloader.read_json(video_url, session=session)\n                    if isinstance(medias, list):\n                        for media in medias:\n                            if not isinstance(media, dict):\n                                continue\n                            video_url = url_or_none(media.get('videoUrl'))\n                            if not video_url:\n                                continue\n                            height = int_or_none(media.get('quality'))\n                            video_urls.append((video_url, height))\n                    continue\n                video_urls.append((video_url, height))\n                \n\n            videos = []\n            for video_url, height in video_urls:\n                video = {}\n                video['height'] = height or int_or_none(re.find(r'(?P\\d+)[pP]?_\\d+[kK]', video_url))\n                video['quality'] = video['height'] or 0\n                video['videoUrl'] = video_url\n                ext = get_ext(video_url)\n                video['ext'] = ext\n                if ext.lower() == '.m3u8':\n                    video['quality'] -= 1\n                print_('[{}p] {} {}'.format(video['height'], video['ext'], video['videoUrl']))\n                videos.append(video)\n\n            if not videos:\n                raise Exception('No videos')\n\n            videos = sorted(videos, key=lambda video: video['quality'])\n\n            res = get_resolution()\n\n            videos_good = [video for video in videos if video['quality'] <= res]\n            if videos_good:\n                video = videos_good[-1]\n            else:\n                video = videos[0]\n            print_('\\n[{}p] {} {}'.format(video['height'], video['ext'], video['videoUrl']))\n\n            file = File(id_, title, video['videoUrl'].strip(), url_thumb)\n        \n        self._url = file.url\n        self.title = file.title\n        self.filename = file.filename\n        self.thumb = file.thumb\n        return self._url\n\n\ndef is_login(session, cw=None, n=2):\n    '''\n    is_login\n    '''\n    print_ = get_print(cw)\n    print_('is_login {}'.format(n))\n    if n <= 0:\n        return False\n    url = 'https://www.pornhubpremium.com'\n    soup = downloader.read_soup(url, session=session)\n    soup = fix_soup(soup, url, session, cw)\n    html = str(soup)\n    if soup.find('ul', id='profileMenuDropdown'):\n        return True\n    return is_login(session, cw, n-1)\n\n\n\n@Downloader.register\nclass Downloader_pornhub(Downloader):\n    '''\n    Downloader\n    '''\n    type = 'pornhub'\n    single = True\n    strip_header = False\n    URLS = ['pornhub.com', 'pornhubpremium.com', 'pornhubthbh7ap3u.onion']\n\n    def init(self):\n        self.session = Session() # 1791\n        if 'pornhubpremium.com' in self.url.lower() and\\\n           not is_login(self.session, self.cw):\n            raise errors.LoginRequired()\n\n    @classmethod\n    def fix_url(cls, url):\n        if 'pornhub_gif_' in url:\n            url = 'https://www.pornhub.com/gif/{}'.format(\n                url.replace('pornhub_gif_', ''))\n        elif 'pornhub_album_' in url:\n            url = 'https://www.pornhub.com/album/{}'.format(\n                url.replace('pornhub_album_', ''))\n        elif 'pornhub_' in url:\n            url = 'https://www.pornhub.com/view_video.php?viewkey={}'\\\n                       .format(url.replace('pornhub_', ''))\n        if '/authenticate/goToLoggedIn' in url:\n            qs = utils.query_url(url)\n            url = urljoin(url, qs['url'][0])\n        url = url.replace('pornhubthbh7ap3u.onion', 'pornhub.com')\n        return url\n\n    @classmethod\n    def key_id(cls, url):\n        for domain in cls.URLS:\n            if domain in url:\n                id_ = domain + url.split(domain)[1]\n                break\n        else:\n            raise Exception('no id')\n        return id_.split('#')[0]\n\n    def read(self):\n        cw = self.cw\n        session = self.session\n\n        videos = []\n        tab = ''.join(self.url.replace('pornhubpremium.com', 'pornhub.com', 1).split('?')[0].split('#')[0].split('pornhub.com/')[-1].split('/')[2:3])\n\n        if '/album/' in self.url:\n            self.print_('Album')\n            info = read_album(self.url, session=session)\n            self.single = False\n            for photo in info['photos']:\n                self.urls.append(photo.url)\n\n            self.title = clean_title(info['title'])\n        elif '/photo/' in self.url:\n            self.print_('Photo')\n            info = read_photo(self.url, session=session)\n            for photo in info['photos']:\n                self.urls.append(photo.url)\n\n            self.title = info['title']\n        elif tab not in ['', 'videos']:\n            raise NotImplementedError(tab)\n        elif 'viewkey=' not in self.url.lower() and\\\n             '/embed/' not in self.url.lower() and\\\n             '/gif/' not in self.url.lower():\n            self.print_('videos')\n            info = get_videos(self.url, cw)\n            hrefs = info['hrefs']\n            self.print_('videos: {}'.format(len(hrefs)))\n\n            if not hrefs:\n                raise Exception('no hrefs')\n\n            videos = [Video(href, cw, session) for href in hrefs]\n            video = self.process_playlist(info['title'], videos)\n            self.setIcon(video.thumb)\n            self.enableSegment()\n        else:\n            video = Video(self.url, cw, session)\n            video.url()\n            self.urls.append(video.url)\n            self.setIcon(video.thumb)\n            self.title = video.title\n            self.enableSegment()\n\n\n\ndef fix_soup(soup, url, session=None, cw=None):\n    '''\n    fix_soup\n    '''\n    print_ = get_print(cw)\n    if soup.find('div', class_='logo'):\n        return soup\n    print_('invalid soup: {}'.format(url))\n\n    res = clf2.solve(url, session=session, cw=cw)\n\n    return Soup(res['html'])\n\n\n\nclass Photo(object):\n    '''\n    Photo\n    '''\n\n    def __init__(self, id_, url, referer):\n        self.id_ = id_\n        self.url = LazyUrl(referer, lambda x: url, self)\n        ext = os.path.splitext(url.split('?')[0])[1]\n        self.filename = '{}{}'.format(id_, ext)\n\n\n@try_n(8)\ndef read_album(url, session=None):\n    '''\n    read_album\n    '''\n    soup = downloader.read_soup(url, session=session)\n    id_album = re.find('/album/([0-9]+)', url, err='no album id')\n    url_json = 'https://www.pornhub.com/album/show_album_json?album={}'.format(id_album)\n    data = downloader.read_json(url_json, url, session=session)\n    block = soup.find('div', class_='photoAlbumListBlock')\n    href = block.a.attrs['href']\n    id_ = re.find('/photo/([0-9]+)', href, err='no photo id')\n    ids = [id_]\n    while True:\n        item = data[id_]\n        id_ = item['next']\n        if id_ in ids:\n            break\n        ids.append(id_)\n\n    photos = []\n    for id_ in ids:\n        item = data[id_]\n        img = item['img_large']\n        referer = 'https://www.pornhub.com/photo/{}'.format(id_)\n        photo = Photo(id_, img, referer)\n        photos.append(photo)\n\n    info = {}\n    title = clean_title(soup.find('h1', class_='photoAlbumTitleV2').text)\n    info['title'] = format_filename(title, 'album_{}'.format(id_album))\n    info['photos'] = photos\n    return info\n\n\n@try_n(8)\ndef read_photo(url, session=None):\n    '''\n    read_photo\n    '''\n    id_ = re.find('/photo/([0-9]+)', url, err='no photo id')\n    soup = downloader.read_soup(url, session=session)\n    div = soup.find('div', id='thumbSlider')\n    href = urljoin(url, div.find('a').attrs['href'])\n    info = read_album(href)\n    photos = []\n    for photo in info['photos']:\n        if str(photo.id_) == id_:\n            photos.append(photo)\n\n    info['photos'] = photos\n    info['title'] = '{} - {}'.format(info['title'], photos[0].filename)\n    return info\n\n\n@try_n(4)\ndef get_videos(url, cw=None):\n    '''\n    get_videos\n    '''\n    print_ = get_print(cw)\n\n    if '/users/' in url:\n        mode = 'users'\n        username = url.split('/users/')[1].split('/')[0]\n    elif '/pornstar/' in url:\n        mode = 'pornstar'\n        username = url.split('/pornstar/')[1].split('/')[0]\n    elif '/model/' in url:\n        mode = 'model'\n        username = url.split('/model/')[1].split('/')[0]\n    elif '/channels/' in url:\n        mode = 'channels'\n        username = url.split('/channels/')[1].split('/')[0]\n    elif '/playlist/' in url:\n        mode = 'playlist'\n        username = url.split('/playlist/')[1].split('/')[0]\n    else:\n        raise Exception('Not supported url')\n    username = username.split('?')[0].split('#')[0]\n\n    session = Session()\n\n    domain = utils.domain(url)\n\n    if mode in ['pornstar']:\n        url_main = 'https://{}/{}/{}'.format(domain, mode, username)\n        html = downloader.read_html(url_main, session=session)\n        soup = Soup(html)\n        soup = fix_soup(soup, url_main, session, cw)\n        for a in soup.findAll('a'):\n            if '/{}/{}/videos/upload'.format(mode, username) in a.attrs.get('href', ''):\n                free = True\n                break\n        else:\n            free = False\n        print_('free: {}'.format(free))\n\n    # Range\n    max_pid = get_max_range(cw, 500)\n    max_pid = min(max_pid, 2000)#\n\n    html = downloader.read_html(url, session=session)\n    soup = fix_soup(Soup(html), url, session, cw)\n\n    info = {}\n\n    # get title\n    h1 = soup.find('h1')\n    if h1:\n        header = 'Playlist'\n        title = h1.find(id='watchPlaylist')\n    else:\n        title = None\n    if not title:\n        header = 'Channel'\n        profile = soup.find('div', class_='profileUserName')\n        wrapper = soup.find('div', class_='titleWrapper')\n        bio = soup.find('div', class_='withBio')\n        title = soup.find('h1', {'itemprop':'name'})\n        if not title and profile:\n            title = profile.a\n        if not title and wrapper:\n            title = wrapper.h1\n        if not title and bio:\n            title = bio.h1\n    if not title:\n        raise Exception('No title')\n    #print(title)\n    info['title'] = '[{}] {}'.format(header, title.text.strip())\n    token = re.find('''token *= *['\"](.*?)['\"]''', html)\n    print_('token: {}'.format(token))\n\n    # get links\n    hrefs = []\n    fail = 0\n    for p in range(1, 1+100):\n        try:\n            if mode in ['users', 'model']:\n                if mode == 'users':\n                    url_api = 'https://{}/users/{}/videos/public/'\\\n                              'ajax?o=mr&page={}'.format(domain, username, p)\n                elif mode == 'model':\n                    url_api = 'https://{}/model/{}/videos/upload/'\\\n                              'ajax?o=mr&page={}'.format(domain, username, p)\n                r = session.post(url_api)\n                soup = Soup(r.text)\n                if soup.find('h1'):\n                    print('break: h1')\n                    break\n            elif mode in ['pornstar']:\n                if free:\n                    url_api = 'https://{}/{}/{}/videos/upload'\\\n                              '?page={}'.format(domain, mode, username, p)\n                    soup = downloader.read_soup(url_api, session=session)\n                    soup = fix_soup(soup, url_api, session, cw)\n                    soup = soup.find('div', class_='videoUList')\n                else:\n                    url_api = 'https://{}/{}/{}?page={}'.format(domain, mode, username, p)\n                    soup = downloader.read_soup(url_api, session=session)\n                    soup = fix_soup(soup, url_api, session, cw)\n                    soup = soup.find('ul', class_='pornstarsVideos')\n            elif mode in ['channels']:\n                url_api = 'https://{}/{}/{}/videos?page={}'.format(domain, mode, username, p)\n                soup = downloader.read_soup(url_api, session=session)\n                soup = fix_soup(soup, url_api, session, cw)\n                try:\n                    soup = soup.find('div', {'id': 'channelsBody'}).find('div', class_='rightSide')\n                except:\n                    break\n            elif mode in ['playlist']:\n                #url_api = 'https://{}/playlist/viewChunked?id={}&offset={}&itemsPerPage=40'.format(domain, username, len(hrefs))\n                if token is None:\n                    raise Exception('no token')\n                url_api = 'https://{}/playlist/viewChunked?id={}&token={}&page={}'.format(domain, username, token, p)\n                soup = downloader.read_soup(url_api, session=session)\n            else:\n                raise NotImplementedError(mode)\n            fail = 0\n        except Exception as e:\n            print_(e)\n            fail += 1\n            if fail < 2:\n                continue\n            else:\n                break\n        finally:\n            print_('{}  ({})'.format(url_api, len(hrefs)))\n\n        if cw and not cw.alive:\n            return\n\n        lis = soup.findAll('li', class_='videoblock')\n        if not lis:\n            print_('break: no lis')\n            break\n\n        if getattr(soup.find('title'), 'text', '').strip() == 'Page Not Found':\n            print_('Page Not Found')\n            break\n\n        c = 0\n        for li in lis:\n            a = li.find('a')\n            href = a.attrs['href']\n            href = urljoin(url, href)\n            if href in hrefs:\n                continue\n            c += 1\n            if href.startswith('javascript:'): # Remove Pornhub Premium\n                print(href)\n                continue\n            hrefs.append(href)\n        if c == 0:\n            print('c==0')\n            break\n        print(c) # 1320\n\n        if len(hrefs) >= max_pid:\n            break\n\n    if cw:\n        hrefs = filter_range(hrefs, cw.range)\n\n    info['hrefs'] = hrefs\n\n    return info\n","sub_path":"src/extractor/pornhub_downloader.py","file_name":"pornhub_downloader.py","file_ext":"py","file_size_in_byte":22424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"170771338","text":"def max_even_seq(n):\n    strn = str(n)\n    trutheven = []\n    for digit in strn:\n        if int(digit) % 2 == 0:\n            trutheven.append('+')\n        else:\n            trutheven.append('-')\n    count = 0\n    seqlist = []\n    for value in trutheven:\n        if value == '-':\n            count = count * 0\n            seqlist.append(count)\n        else:\n            count = count + 1\n            seqlist.append(count)\n    max_even_seq1 = max(seqlist)\n    return max_even_seq1\n\n\n\n\n #Testing Q6\n","sub_path":"max_even_seq/subs/2017B/161.py","file_name":"161.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"161270737","text":"\"\"\"Example of tracking.get_estimates usage\"\"\"\nimport json\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nfrom tracking.get_estimates import get_estimates\n\n\ndef draw_estimated_positions(calculated_estimates: dict) -> None:\n    \"\"\"\n    Draws calculated estimates with a pyplot.\n    :param calculated_estimates: dict with estimated positions\n    {\"index_number\": {\"frame_number\": [x_position, y_position]}}\n    :return: None\n    \"\"\"\n    for index in calculated_estimates:\n        x_pos = [calculated_estimates[index][frame_index][0]\n                 for frame_index in calculated_estimates[index]]\n        y_pos = [calculated_estimates[index][frame_index][1]\n                 for frame_index in calculated_estimates[index]]\n        plt.plot(x_pos, y_pos)\n\n    plt.xlabel('width [px]')\n    plt.ylabel('height [px]')\n    plt.title('Estimated positions')\n    plt.grid()\n    plt.gca().invert_yaxis()\n    plt.show()\n\n\nwith open('example_detections/A3_first_2000_frames.json', 'r') as fp:\n    DATA = json.load(fp)['detections']\n\nESTIMATES = get_estimates(DATA,\n                          max_estimate_detection_assignment_cost=40,\n                          max_detection_assignment_cost=30,\n                          consecutive_detection_frames=5,\n                          max_strike_count=20)\n\ndraw_estimated_positions(ESTIMATES)\n\nif __name__ == '__main__':\n    pass\n","sub_path":"usage_example_1.py","file_name":"usage_example_1.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"403301557","text":"\"\"\"\nASGI config for website project.\n\nIt exposes the ASGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/howto/deployment/asgi/\n\"\"\"\n\nimport os\nfrom socket import gethostbyname, gethostname\n\nfrom django.core.asgi import get_asgi_application\n\nipaddress = gethostbyname(gethostname())\nif ipaddress.startswith('127.0'):\n    os.environ.setdefault(\n        'DJANGO_SETTINGS_MODULE',\n        'website.settings.development'\n    )\nelse:\n    os.environ.setdefault(\n        'DJANGO_SETTINGS_MODULE',\n        'website.settings.production'\n    )\n\napplication = get_asgi_application()\n","sub_path":"website/asgi.py","file_name":"asgi.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"474680904","text":"from time import *\r\nimport string\r\ntimes = perf_counter()\r\ntext = open('HW.txt')\r\nletters = string.ascii_lowercase\r\nfor i in text:\r\n  text_lower = i.lower()\r\n  text_nospace = text_lower.replace(\" \", \"\")\r\n  text_nopunctuation = text_nospace.strip(string.punctuation)\r\n  for a in letters:\r\n    if a in text_nopunctuation:\r\n      num = text_nopunctuation.count(a)\r\n      print(a, num)\r\nprint(perf_counter() - times)\r\n","sub_path":"all/letter coun ter.py","file_name":"letter coun ter.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"394788987","text":"import random\r\nstages = ['''\r\n  +---+\r\n  |   |\r\n  O   |\r\n /|\\  |\r\n / \\  |\r\n      |\r\n=========\r\n''', '''\r\n  +---+\r\n  |   |\r\n  O   |\r\n /|\\  |\r\n /    |\r\n      |\r\n=========\r\n''', '''\r\n  +---+\r\n  |   |\r\n  O   |\r\n /|\\  |\r\n      |\r\n      |\r\n=========\r\n''', '''\r\n  +---+\r\n  |   |\r\n  O   |\r\n /|   |\r\n      |\r\n      |\r\n=========''', '''\r\n  +---+\r\n  |   |\r\n  O   |\r\n  |   |\r\n      |\r\n      |\r\n=========\r\n''', '''\r\n  +---+\r\n  |   |\r\n  O   |\r\n      |\r\n      |\r\n      |\r\n=========\r\n''', '''\r\n  +---+\r\n  |   |\r\n      |\r\n      |\r\n      |\r\n      |\r\n=========\r\n''']\r\nword_list = ['dolap','perde','deve','eşşek']\r\nchosen_word = random.choice(word_list)\r\nword_length = len(chosen_word)\r\n\r\nprint(f'Psst, the solution: {chosen_word}')\r\n      \r\ndisplay = []\r\n\r\nfor _ in range(word_length):\r\n      display +='_'\r\nlives = 6\r\n\r\n    \r\n\r\nend_of_game = False\r\nwhile not end_of_game:\r\n    guess = input(\"Guess a letter: \").lower()\r\n\r\n    #Check guessed letter\r\n    for position in range(word_length):\r\n        letter = chosen_word[position]\r\n      \r\n        if letter == guess:\r\n            display[position] = letter\r\n\r\n    if guess not in chosen_word:\r\n        lives -= 1\r\n        if lives==0:\r\n            end_of_game =True\r\n            print('You lose')   \r\n            \r\n            \r\n            \r\n\r\n    print(f\"{' '.join(display)}\")\r\n\r\n    #Check if there are no more \"_\" left in 'display'. Then all letters have been guessed.\r\n    if \"_\" not in display:\r\n        end_of_game = True   \r\n        \r\n        print(\"You win.\")        \r\n        \r\n    print(stages[lives])\r\n           \r\n","sub_path":"Python-Hangman.py","file_name":"Python-Hangman.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"140054975","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 12 13:22:39 2016\n\n@author: Moe\n\"\"\"\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.rcParams['xtick.direction'] = 'out'\nmatplotlib.rcParams['ytick.direction'] = 'out'\n\ndef func_rd(t_vals, d):\n    \"\"\"Compute the periodic rectangular function R_d(t) on all given t values.\n    \n    t_vals -- All t values to compute R_d(t) for.\n    d -- The d param.\n    \"\"\"\n    return np.mod(np.floor(t_vals / d), 2)\n    np.mod\n    \nt_range = (-10, 10)\nt_values = np.linspace(t_range[0], t_range[1], num=199, endpoint=False)\nsampling_rate = 1\nsample_times = np.arange(t_range[0], t_range[1], sampling_rate)\nd_vals = [.3, .5, 1.0, 2.0, 3.3, 4.5]\n\nfor d in d_vals:\n    rd = func_rd(t_values, d)\n    sampled_rd = func_rd(sample_times, d)\n    fig = plt.figure()\n    ax = fig.add_subplot(1,1,1)\n    plt.plot(t_values, rd, c='b')\n    plt.stem(sample_times, sampled_rd, linefmt=' ', markerfmt='ro', basefmt=' ')\n    plt.xlabel(r'$t$')\n    plt.ylabel(r'$R_d(t)$')\n    plt.ylim((-0.2, 1.2))\n    plt.xlim(t_range)\n    plt.title(r'Sampling of $R_d(t)$ with $d=' + str(d) + r'$')\n    ax.get_xaxis().tick_bottom()\n    ax.get_yaxis().tick_left()\n\n    plt.show()","sub_path":"Uebung08/a3_aliasing.py","file_name":"a3_aliasing.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"31983803","text":"import numpy as np\nfrom copy import deepcopy\nfrom random import shuffle\n\n# Mängulaua suurus\nboardSize = 8\nboard = [np.zeros(boardSize, dtype=int) for i in range(boardSize)]\n\nplayers = [\".\", \"X\", \"O\"] # Mängijad\n# player = 1  # Käiku tegev mängija (alustab 1 ehk must)\n\n# Tehisintellekti vastu mängimine (True või False)\nplayAI = True\n# Kas AI mängib mustade (1) või valgete (2) nuppudega (alati alustavad mustad)\nAIPlayer = 1\n\nallRows = []\nfor i in range(boardSize):\n    cRow = []\n    for j in range(boardSize):\n        cRow.append([i, j])\n    allRows.append(cRow)\n\nallCols = []\nfor i in range(boardSize):\n    col = []\n    for j in range(boardSize):\n        col.append([j, i])\n    allCols.append(col)\n\nrightDiagonals = []\nfor i in range(boardSize - 4):\n    diagonal = []\n    k = i\n    for j in range(boardSize-i):\n        diagonal.append([k, j])\n        k += 1\n    rightDiagonals.append(diagonal)\nfor i in range(1, boardSize - 4):\n    diagonal = []\n    k = i\n    for j in range(boardSize-i):\n        diagonal.append([j, k])\n        k += 1\n    rightDiagonals.append(diagonal)\n\nleftDiagonals = []\nfor i in range(boardSize - 1, 3, -1):\n    diagonal = []\n    k = i\n    for j in range(boardSize-(boardSize-(i+1))):\n        diagonal.append([j, k])\n        k -= 1\n    leftDiagonals.append(diagonal)\nfor i in range(1, boardSize - 4):\n    diagonal = []\n    k = i\n    for j in range(boardSize - 1, -1 + i, -1):\n        diagonal.append([k, j])\n        k += 1\n    leftDiagonals.append(diagonal)\n\nallDirections = []\nfor directions in [allRows, allCols, rightDiagonals, leftDiagonals]:\n    for direction in directions:\n        allDirections.append(direction)\n\n# Funktsioonid ======================================================================================================\n\n# Kontrollib, kas sinna võib käia\ndef legalMove(move):\n    if any([m not in range(0, boardSize) for m in move]):\n        return False\n    if board[move[0]][move[1]] == 0:\n        return True\n    return False\n\n\ndef isNextTo(space1, space2):\n    if space1[0] != space2[0] and space1[1] != space2[1]:\n        if space1[0] == space2[0] or space1[0] == space2[0] + 1 or space1[0] == space2[0] - 1:\n            if space1[1] == space2[1] or space1[1] == space2[1] + 1 or space1[1] == space2[1] - 1:\n                return True\n    return False\n\ndef find_combinations(row, pl):\n    combinations = []\n    current_combination = []\n    for i in range(len(row)):\n        if row[i][0] == pl:\n            current_combination.append(row[i][1])\n        elif len(current_combination) != 0:\n            if len(current_combination) > 1:\n                combinations.append(current_combination)\n            current_combination = []\n    if len(current_combination) > 1:\n        combinations.append(current_combination)\n    return combinations\n\ndef checkCombinations(pl, board):\n    board_with_coordinates = []\n    for i in range(len(board)):\n        row = board[i]\n        board_with_coordinates.append([])\n        for j in range(len(row)):\n            board_with_coordinates[i].append([board[i][j], [i, j]])\n\n    max_col = len(board_with_coordinates[0])\n    max_row = len(board_with_coordinates)\n    cols = [[] for _ in range(max_col)]\n    rows = [[] for _ in range(max_row)]\n    fdiag = [[] for _ in range(max_row + max_col - 1)]\n    bdiag = [[] for _ in range(len(fdiag))]\n    min_bdiag = -max_row + 1\n\n    for x in range(max_col):\n        for y in range(max_row):\n            cols[x].append(board_with_coordinates[y][x])\n            rows[y].append(board_with_coordinates[y][x])\n            fdiag[x + y].append(board_with_coordinates[y][x])\n            bdiag[x - y - min_bdiag].append(board_with_coordinates[y][x])\n\n    combinations = []\n    for row in rows + cols + fdiag + bdiag:\n        combinations += find_combinations(row, pl)\n    return combinations\n\ndef square_blocked(board, x, y, player):\n    return not (0 <= x < boardSize) or not (0 <= y < boardSize) or board[x][y] == 3 - player\n\ndef both_blocked(combination, board):\n    if len(combination) <= 1:\n        return False\n    x_move = combination[1][0] - combination[0][0]\n    y_move = combination[1][1] - combination[0][1]\n    player = board[combination[0][0]][combination[0][1]]\n    blocked_before = square_blocked(board, combination[0][0] - x_move, combination[0][1] - y_move, player)\n    blocked_after = square_blocked(board, combination[-1][0] + x_move, combination[-1][1] + y_move, player)\n    return blocked_before and blocked_after\n\ndef isBlocked(combination, board):\n    x_move = combination[1][0] - combination[0][0]\n    y_move = combination[1][1] - combination[0][1]\n    player = board[combination[0][0]][combination[0][1]]\n    if square_blocked(board, combination[0][0] - x_move, combination[0][1] - y_move, player):\n        return True\n    if square_blocked(board, combination[-1][0] + x_move, combination[-1][1] + y_move, player):\n        return True\n\n    return False\n\n# Tagastab mängija nupu võimalike käikude listi\n# Kui võimalikud käigud puuduvad, tagastab tühja listi\ndef getPossMoves(bd):\n    possMoves = []\n    for rownr, row in enumerate(bd):\n        for colnr, value in enumerate(row):\n            if value == 0:\n                if legalMove((rownr, colnr)):\n                    possMoves.append((rownr, colnr))\n    return possMoves\n\n\n# Kontrolli, kas reas on täpselt viis sama värvi nuppu järjest\n# gomoku - 5 nupu järjend\n# row - rida, milles seda otsitakse\ndef checkRow(gomoku, row):\n    n = len(gomoku)\n    # Eeldame, et kõik õiged väärtused\n    # value = player\n    value = gomoku[0]\n    matches = [i for i in range(len(row) - n + 1) if np.array_equal(gomoku, row[i:i + n])]\n    # Viisik on olemas\n    if len(matches) > 0:\n        # Kontrolli, ega tegu pole kuuikuga\n        rokumoku = gomoku + [value]\n        for match in matches:\n            if (not np.array_equal(row[match - 1:match + n], rokumoku)) \\\n                    and (not np.array_equal(row[match:match + n + 1], rokumoku)):\n                return True\n    return False\n\n\n# Kontroll, kas mäng on lõppenud\ndef isEnd():\n    answer = False\n    winner = 0\n    # Raske uskuda, aga mängulaud on täis\n    if len(getPossMoves(board)) == 0:\n        return True\n    # Kellelgi on täpselt viis järjest ehk gomoku\n    # Kontrolli seda mõlema mängija kohta\n    # Eeldame, et mõlemad korraga ei saa gomokuni jõuda\n    for pl in [1, 2]:\n        gomoku = [pl for i in range(5)]\n        x = boardSize - len(gomoku) + 1  # milliseid diagonaale kontrolida\n        # read\n        # veerud\n        # langevad diagonaalid\n        # tõusvad diagonaalid\n        if any([checkRow(gomoku, row) for row in board]) or \\\n                any([checkRow(gomoku, row) for row in np.transpose(board)]) or \\\n                any([checkRow(gomoku, row) for row in [np.diagonal(board, i) for i in range(-x, x)]]) or \\\n                any([checkRow(gomoku, row) for row in [np.diagonal(np.fliplr(board), i) for i in range(-x, x)]]):\n            answer = True\n            winner = pl\n    return answer, winner\n\n\ndef getRate(player, board):\n    playerCombinations = checkCombinations(player, board)\n    enemyCombinations = checkCombinations(3-player, board)\n\n    longestPlayerCombination = []\n    longestEnemyCombination = []\n\n    for combination in playerCombinations:\n        if len(combination) > len(longestPlayerCombination) and (len(combination) >= 5 or not both_blocked(combination, board)):\n            longestPlayerCombination = combination\n\n    for combination in enemyCombinations:\n        if len(combination) > len(longestEnemyCombination) and (len(combination) >= 5 or not both_blocked(combination, board)):\n            longestEnemyCombination = combination\n\n    rate = 4\n\n    if len(longestPlayerCombination) == 5:\n        rate = 8\n        return rate\n    if len(longestEnemyCombination) == 4 and not isBlocked(longestEnemyCombination, board):\n        rate = 1\n        return rate\n    if len(longestEnemyCombination) == 4 and isBlocked(longestEnemyCombination, board) or (\n            len(longestEnemyCombination) == 3 and not isBlocked(longestEnemyCombination, board)):\n        rate = 2\n        return rate\n    if len(longestPlayerCombination) == 4:\n        rate = 7\n        return rate\n    if len(longestPlayerCombination) == 4 and isBlocked(longestPlayerCombination, board) or (\n            len(longestPlayerCombination) == 3 and not isBlocked(longestPlayerCombination, board)):\n        rate = 6\n        return rate\n    if len(longestEnemyCombination) == 3 and isBlocked(longestEnemyCombination, board) or (\n            len(longestEnemyCombination) == 2 and not isBlocked(longestEnemyCombination, board)):\n        rate = 3\n        return rate\n    if len(longestPlayerCombination) == 3 and isBlocked(longestPlayerCombination, board) or (\n                len(longestPlayerCombination) == 2 and not isBlocked(longestPlayerCombination, board)):\n        rate = 5\n        return rate\n    return rate\n\n\ndef minimax(board, depth, player):\n    # player - momendil käigul olija, algoritmi väljakutsuja\n    # move - variantide katsetamisel võimaliku käigu tegija\n    allturns = getPossMoves(board)\n    if (depth >= 0) and depth < len(allturns):\n        bestturn, bestrate = maximizer(board, allturns, depth, player)\n    return bestturn, bestrate\n\n\n# Mängija käik, maksimeeri tulemust\ndef maximizer(board, allturns, depth, player):\n    bestturn = (-1, -1)\n    bestrate = 0\n    # Kui pole veel soovitud sügavus saavutatud ning mängu lõpuni on veel piisavalt käike\n    for turn in allturns:\n        b = deepcopy(board)\n        b[turn[0]][turn[1]] = player\n        if depth > 1:\n            _turn, rate = minimizer(b, getPossMoves(board), depth - 1, 3 - player)\n        else:\n            rate = getRate(player, b)\n        if rate > bestrate:\n            bestrate = rate\n            bestturn = turn\n    # print(\"maximizer(\" + str(depth) + \", \" + str(player) + \"): \" + str(bestturn) + \", \" + str(bestrate))\n    return bestturn, bestrate\n\n\n# Vastasmängija käik, minimeeri meie kahjusid\ndef minimizer(board, allturns, depth, player):\n    bestturn = (-1, -1)\n    bestrate = 10\n\n    for turn in allturns:\n        b = deepcopy(board)\n        b[turn[0]][turn[1]] = player\n        if depth > 1:\n            _turn, rate = maximizer(b, getPossMoves(board), depth - 1, 3 - player)\n        else:\n            rate = 8 - getRate(player, b)\n        if rate < bestrate:\n            bestrate = rate\n            bestturn = turn\n    # print(\"minimizer(\" + str(depth) + \", \" + str(player) + \"): \" + str(bestturn) + \", \" + str(bestrate))\n    return bestturn, bestrate\n\n\ndef getTurn(board, player):\n    print(player)\n    depth = 3\n    if len(getPossMoves(board)) < depth:\n        depth = len(getPossMoves(board))\n    move, rate = minimax(board, depth, player)\n    return move\n","sub_path":"gomoku_ai.py","file_name":"gomoku_ai.py","file_ext":"py","file_size_in_byte":10760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"611704032","text":"from itertools import permutations as perm\nfrom functools import reduce\n\ndef solve(n):\n    answer = 0\n    visited = set()\n    start = n // 3 + 1\n    for pi in perm(range(1, n + 1)):\n        for i in range(start, min(2 * start, n - 1)):\n            m = int(reduce(lambda x, y: str(x) + str(y), pi[:i]))\n            if m in visited:\n                continue\n            elif i > n - i:\n                break\n            for j in range(i + 1, n):\n                a = int(reduce(lambda x, y: str(x) + str(y), pi[i:j]))\n                b = int(reduce(lambda x, y: str(x) + str(y), pi[j:]))\n                if a * b in visited:\n                    continue\n                if m == a * b:\n                    visited.add(m)\n                    answer += m\n    return answer\n\ndef main():\n    print(solve(int(input())))\n    #print(is_n_pan_digital(4, 12, {1,2,3,4}))\n\nif __name__ == '__main__':\n    main()","sub_path":"competitions/old_competitions/project_euler/euler_032/pandigital_products_permutations.py","file_name":"pandigital_products_permutations.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"551024446","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2010 - 2023, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.\n# All rights reserved.\n#\n# SPDX-License-Identifier: BSD-3-Clause\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n#    list of conditions and the following disclaimer.\n#\n# 2. 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# 3. Neither the name of the copyright holder nor the names of its\n#    contributors may be used to endorse or promote products derived from\n#    this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# We kindly request you to use one or more of the following phrases to refer to\n# foxBMS in your hardware, software, documentation or advertising materials:\n#\n# - \"This product uses parts of foxBMS®\"\n# - \"This product includes parts of foxBMS®\"\n# - \"This product is derived from foxBMS®\"\n\n\"\"\"Various helper functions used in the foxBMS waf toolchain\n\"\"\"\n\nimport pathlib\nimport json\nimport jsonschema\n\nfrom waflib.Configure import conf\nfrom waflib import Utils\n\n\n@conf\ndef f_validator(\n    ctx,  # pylint: disable=unused-argument\n    schema_path,\n    validator_version=jsonschema.Draft7Validator,\n):\n    \"\"\"Returns a validator with resolved relative references\"\"\"\n    schema_path = pathlib.Path(schema_path).resolve().as_posix()\n    with open(schema_path, mode=\"r\", encoding=\"utf-8\") as filepointer:\n        schema = json.load(filepointer)\n    if Utils.is_win32:\n        uri_template = \"file:///{0}\"\n    else:\n        uri_template = \"file:{0}\"\n    base_uri = uri_template.format(schema_path)\n    validator_version.check_schema(schema)\n    resolver = jsonschema.RefResolver(\n        base_uri=base_uri,\n        referrer=schema,\n    )\n    validator = validator_version(schema, resolver=resolver, format_checker=None)\n    return validator\n","sub_path":"tools/waf-tools/f_helpers.py","file_name":"f_helpers.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"129270355","text":"#  Copyright 2015 Observable Networks\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\");\n#  you may not use this file except in compliance with the License.\n#  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# python builtins\nimport json\nimport logging\nfrom tempfile import NamedTemporaryFile\nfrom vendor.libnmap.process import NmapProcess\nfrom vendor.libnmap.parser import NmapParser, NmapParserException\n\n# local\nfrom service import Service\nfrom utils import utc\n\nOBSERVATION_TYPE = 'scan_observation_v1'\nSCAN_TARGETS = 'scan-config'\nSCAN_INTERVAL_SECONDS = 60 * 60  # Hourly.\nDEFAULT_NMAP_ARGS = ['nmap', '-oG', '-']\nMAX_SIMULTANEOUS_TARGETS = 10\n\n\ndef _run_scan(ips, now):\n    nmap = NmapProcess(ips)\n    rc = nmap.run()\n    if rc != 0:\n        logging.error(\"nmap failed with error {}\".format(rc))\n        return\n\n    try:\n        report = NmapParser.parse(nmap.stdout)\n    except NmapParserException as e:\n        logging.error(\"nmap parsing error? \" + str(e))\n        return\n\n    for host in report.hosts:\n        ports = ['{}/{}'.format(s.port, s.state)\n                 for s in host.services]\n        yield {\n            'observation_type': OBSERVATION_TYPE,\n            'time': now.isoformat(),\n            'source': host.address,\n            'ports': ', '.join(ports),\n            'info_type': 'services',\n            'result': '',\n        }\n\n\nclass NmapperService(Service):\n    def __init__(self, *args, **kwargs):\n        kwargs.update({\n            'poll_seconds': SCAN_INTERVAL_SECONDS,\n        })\n        super(NmapperService, self).__init__(*args, **kwargs)\n\n    def _get_target_ips(self):\n        json_resp = self.api.get_data(SCAN_TARGETS).json()\n        objects = json_resp.get('objects', [])\n        if not objects:\n            return []\n\n        is_enabled = objects[0].get('is_enabled', True)\n        if not is_enabled:\n            return []\n\n        target_ips = objects[0].get('scan_targets', [])\n        return target_ips\n\n    def _upload_results(self, filename, now):\n        path = self.api.send_file('logs', filename, now, suffix='nmap')\n        data = {\n            'path': path,\n            'log_type': 'observations',\n        }\n        self.api.send_signal('logs', data)\n\n    def execute(self, now=None):\n        logging.info('getting target ips')\n        target_ips = self._get_target_ips()\n        logging.info('got {} target ips'.format(len(target_ips)))\n\n        # timezoneify now\n        if now:\n            now = now.replace(tzinfo=utc)\n\n        while target_ips:\n            ips = target_ips[0:MAX_SIMULTANEOUS_TARGETS]\n            target_ips = target_ips[MAX_SIMULTANEOUS_TARGETS:]\n\n            results = _run_scan(ips, now)\n            with NamedTemporaryFile() as f:\n                if not results:\n                    continue\n                for r in results:\n                    f.write(json.dumps(r) + '\\n')\n\n                f.seek(0)\n                self._upload_results(f.name, now)\n\n\nif __name__ == '__main__':\n    scanner = NmapperService()\n    scanner.run()\n","sub_path":"src/scripts/ona_service/nmapper.py","file_name":"nmapper.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"53002984","text":"import pandas as pd\n\n\n#  create Dataframe fealds\nflds = {'Model': ['Model name'],\n          'Predict by': ['features'],\n          'AUC-ROC': [0.0],\n          'Accuracy': [0.0],\n          'Precision': [0.0],\n          'Recall': [0.0],\n          'F1': [0.0]\n         }\ndf = pd.DataFrame(data=flds)\ndf.to_csv('Resaulst.csv', index=False)","sub_path":"AllSINEs/TableCreation.py","file_name":"TableCreation.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"197520682","text":"from flask import Flask, render_template\napp = Flask(__name__)\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\nengine = create_engine('sqlite:///restaurantMenu.db')\nBase.metadata.bind=engine\nDBSession = sessionmaker(bind = engine)\nsession = DBSession()\n\n@app.route('/')\n@app.route('/restaurants//')\ndef RestaurantMenu(restaurant_id):\n\trestaurant = session.query(Restaurant).first()\n\titems = session.query(MenuItem).filter_by(restaurant_id = \n\t\trestaurant.id)\n\treturn render_template('menu.html', restaurant=restaurant, items = items)\n\n@app.route('/')\n@app.route('/restaurants///edit/')\ndef EditMenu(restaurant_id, menu_id):\n\trestaurant = session.query(Restaurant).first()\n\titems = session.query(MenuItem).filter_by(restaurant_id = \n\t\trestaurant.id)\n\treturn render_template('menu.html', restaurant=restaurant, items = items)\n\nif __name__ == '__main__':\n\tapp.debug = True\n\tapp.run(host = '0.0.0.0', port = 5000)","sub_path":"vagrant/menu/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"266401774","text":"#!/usr/bin/env python\n#coding=utf-8\nimport sys\n\nprint(\"生成器函数 - 斐波那契\")\n# 生成器函数 - 斐波那契\ndef fibonacci(n):\n    a,b,counter=0,1,0\n    while True:\n        if(counter > n):\n            return\n        yield a\n        a,b=b,a+b\n        counter +=1\nf = fibonacci(10) # f 是一个迭代器,由生成器返回生成\n\nwhile True:\n    try:\n        print(next(f),end=\" \")\n    except StopIteration:\n        sys.exit()","sub_path":"Other/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"227683088","text":"from django.urls import path, re_path\nfrom . import views\n\napp_name = 'accounts'\n\nurlpatterns = [\n    path('signup/', views.signup_view, name=\"signup\"),\n    path('login/', views.login_view, name=\"login\"),\n    path('logout/', views.logout_view, name=\"logout\"),\n    path('/profile/', views.profile_view, name=\"profile\"),\n    path('/movielist/', views.movielist_view, name=\"list\"),\n    path('/movielist/add', views.addmovie_view, name=\"addmovie\"),\n]","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"309372044","text":"vector = ((0, 1), (1, 0), (0, -1), (-1, 0))\n\n\ndef solve():\n    pos = (0, 0)\n    vid = 0\n    for no in range(1, n * n + 1):\n        y, x = pos\n        grid[y][x] = no\n\n        v = vector[vid]\n        y, x = y + v[0], x + v[1]\n        if not (0 <= y < n and 0 <= x < n) or grid[y][x] != 0:\n            vid = (vid + 1) % 4\n            v = vector[vid]\n            y, x = pos\n            y, x = y + v[0], x + v[1]\n\n        pos = (y, x)\n\n    for line in grid:\n        print(*line)\n\n\nfor tno in range(1, int(input()) + 1):\n    n = int(input())\n    grid = [[0 for _ in range(n)] for _ in range(n)]\n    print(f'#{tno}')\n    solve()\n","sub_path":"풀이/swea/recommends/1954_o.py","file_name":"1954_o.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"192889413","text":"class Animal:\n  def __init__(self, name, weight = 0, age = 0, health = 0, happiness = 0):\n    self.name = name\n    self.weight = weight\n    self.age = age\n    self.health = health\n    self.happiness = happiness\n\n  def feed(self, val):\n    self.weight += 10\n    self.health += val\n    return self\n      \n  def play(self, val):\n    self.happiness += val\n    return self\n\n  def display(self):\n    print(\"Name:{} Weight:{} Age:{} Health:{} Happiness:{} \". format(self.name, self.weight, self.age, self.health, self.happiness))\n\nclass Tigers(Animal):\n  def __init__(self, name, weight = 0, age = 0, health = 0, happiness = 0):\n    super().__init__(name, weight, age, health, happiness)\n  def feed_tiger(self, val):\n    if val == \"rabbit\":\n      val = 100\n    else:\n      val = 10\n    super().feed(val)\n    return self\n  def play_tiger(self, val):\n    if val == \"ball\":\n      val = 100\n    else:\n      val = 10\n    super().play(val)\n    return self\n\nclass Lions(Animal):\n  def __init__(self, name, weight = 0, age = 0, health = 0, happiness = 0):\n    super().__init__(name, weight, age, health, happiness)\n  def feed_lion(self, val):\n    if val == \"beef\":\n      val = 100\n    else:\n      val = 10\n    super().feed(val)\n    return self\n  def play_lion(self, val):\n    if val == \"water\":\n      val = 100\n    else:\n      val = 10\n    super().play(val)\n    return self\n\nclass Bears(Animal):\n  def __init__(self, name,  weight = 0, age = 0, health = 0, happiness = 0):\n    super().__init__(name, weight, age, health, happiness)\n  def feed_bear(self, val):\n    if val == \"honey\":\n      val = 100\n    else:\n      val = 10\n    super().feed(val)\n    return self\n  def play_bear(self, val):\n    if val == \"piglet\":\n      val = 100\n    else:\n      val = 10\n    super().play(val)\n    return self\n\n# tiger1 = Tigers(\"TT\", 1, 10)\n# lion1 = Lions(\"Simba\", 10, 1, 10, 10)\n# bear1 = Bears(\"Winnie\", 10, 1, 10, 10)\n\n# tiger1.feed(\"something\").play(\"something\").display()","sub_path":"Python/OOP/zoo/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"9985126","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('tickets', '0002_auto_20150612_2233'),\n    ]\n\n    operations = [\n        migrations.AlterModelOptions(\n            name='tickettype',\n            options={'ordering': ['-preferred', '-active', 'event', 'name']},\n        ),\n        migrations.RenameField(\n            model_name='tickettype',\n            old_name='description',\n            new_name='name',\n        ),\n    ]\n","sub_path":"tickets/migrations/0003_auto_20150612_2235.py","file_name":"0003_auto_20150612_2235.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"56468576","text":"# encoding:utf-8\r\n\"\"\"\r\n关于图片的一些操作:\r\n①图片转化为数组并存为二进制文件;\r\n②从二进制文件中读取数据并重新恢复为图片\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport PIL.Image as Image\r\nimport pickle\r\nimport matplotlib.image as plimg\r\nclass Imageconversion(object):\r\n    image_base_path = \"C:/image/cifar10/picture/\"\r\n    data_base_path = \"C:/image/cifar10/datasets/cifar-10-batches/\"\r\n\r\n    def image_to_array(self, filenames):\r\n        \"\"\"\r\n        图片转化为数组并存为二进制文件;\r\n        :param filenames:文件列表\r\n        :return:\r\n        \"\"\"\r\n        n = filenames.__len__()  # 获取图片的个数\r\n        result = np.array([])  # 创建一个空的一维数组\r\n        image = np.array([])\r\n\r\n        print(u\"开始将图片转为数组\")\r\n        for i in range(n):\r\n            image = Image.open(self.image_base_path + filenames[i])\r\n            image = image.resize((32, 32),Image.ANTIALIAS)            \r\n            r, g, b = image.split()  # rgb通道分离\r\n            # 注意:下面一定要reshpae(1024)使其变为一维数组,否则拼接的数据会出现错误,导致无法恢复图片\r\n            #将PILLOW图像转成数组\r\n            r_arr = plimg.pil_to_array(r)\r\n            g_arr = plimg.pil_to_array(g)\r\n            b_arr = plimg.pil_to_array(b)\r\n            r_arr = np.array(r).reshape(1024)\r\n            g_arr = np.array(g).reshape(1024)\r\n            b_arr = np.array(b).reshape(1024)\r\n            # 行拼接,类似于接火车;最终结果:共n行,一行3072列,为一张图片的rgb值\r\n            image_arr = np.concatenate((r_arr, g_arr, b_arr))\r\n            result = np.concatenate((result, image_arr))            \r\n\r\n        print(u\"转为数组成功,开始保存到文件\")  \r\n        # 构造字典,所有的图像诗句都在arr数组里,我这里是个以为数组,目前并没有存label\r\n        contact = {'labels':10,'data':result}\r\n        file_path = self.data_base_path + \"data_batch_6\"\r\n        with open(file_path, mode='wb') as f:\r\n#            p.dump(result, f)\r\n             pickle.dump(contact, f)#把字典存到文本中去\r\n        print(u\"保存文件成功\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    imgbin = Imageconversion()\r\n    images = []\r\n    for j in range(2):\r\n        images.append('img'+str(j) + \".jpg\")\r\n    imgbin.image_to_array(images)\r\n\r\n","sub_path":"image/cifar10/imgtobin.py","file_name":"imgtobin.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"214138139","text":"# 백준[9466번]\nimport sys\nsys.setrecursionlimit(111111)\n\ndef dfs(x):\n  global result\n  visited[x]=1\n  cycle.append(x)\n  number=num[x]\n\n  if visited[number]:\n    if number in cycle:\n      result+=cycle[cycle.index(number):]\n    return\n  else:\n    dfs(number)\n\n\nt=int(input())\n\nfor _ in range(t):\n  n=int(input())\n  num=[0]+list(map(int,input().split()))\n  visited=[1]+[0]*n\n  result=[]\n\n  for i in range(1,n+1):\n    if visited[i]==0:\n      cycle=[]\n      dfs(i)\n  print(n-len(result))\n  \n","sub_path":"baekjoon9466.py","file_name":"baekjoon9466.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"170170539","text":"from flask import Flask, render_template, request\nimport mysql.connector, os\nimport connection\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\napp = Flask(__name__)\n\ndb = connection.DBConnection()\n\n@app.route('/')\ndef index():\n  return 'Flask app running'\n\n\n@app.route('/dashboard')\ndef dashboard():\n  r = db.getUrlList('SELECT * FROM endpoints WHERE urlEnabled = 1')\n  return render_template('dashboard.html', urls=r)\n\n\n@app.route('/update/', methods=['GET', 'POST'])\ndef update(id):\n  if(request.method == 'GET'):\n    r = db.getById(id)\n    return render_template('update.html', u=r)\n  \n  if(request.method == 'POST'):\n    return \"return method is post\"\n","sub_path":"nocflask.py","file_name":"nocflask.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"208605457","text":"import pandas as pd\nimport pickle5 as pickle\n\n# file = open(\"model/One_Hot_Encoder.pkl\", \"rb\")\n\none_hot = pickle.load(open(\"model/One_Hot_Encoder.pkl\", \"rb\"))\n\n\ndef process_input(input_data):\n    \"\"\"\n    Function which One Hot Encodes input from API.\n    :param input_data: sent to API by the user\n    :return: input data, encoded features\n    \"\"\"\n    try:\n        dataframe = pd.DataFrame.from_dict(input_data, orient=\"index\").T\n        dataframe[[\"year\", \"rating\", \"metascore\", \"total_votes\"]] = dataframe[\n            [\"year\", \"rating\", \"metascore\", \"total_votes\"]\n        ].astype(float)\n        encoded_features = one_hot.transform(dataframe)\n\n        return input_data, encoded_features\n    except:\n        print(\"here is a problem with processing input function\")\n","sub_path":"src/data_processing/processing_input.py","file_name":"processing_input.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"54465947","text":"\"\"\"\r\nGeneral Purpose Stats\r\r\n=====================\r\r\n\r\r\nSome plots visualize a transformation of the original data set. Use a\r\r\nstat parameter to choose a common transformation to visualize.\r\r\n\r\r\nEach stat creates additional variables to map aesthetics to. These\r\r\nvariables use a common ..name.. syntax.\r\r\n\r\r\nLook at the examples of the most general stats below.\r\r\n\r\n\"\"\"\r\n\r\n# sphinx_gallery_thumbnail_path = \"gallery_py\\_stats\\_general_purpose_stats.png\"\r\n\r\nimport pandas as pd\r\n\r\nfrom lets_plot import *\r\nLetsPlot.setup_html()\r\n\r\n# %%\r\n\r\ndf = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv')\r\ndf.head()\r\n\r\n# %%\r\n\r\n# %% [markdown]\r\n#\r\n# Identity Stat\r\r\n# ~~~~~~~~~~~~~\r\r\n\r\n# %%\r\n\r\nw, h = 400, 300\r\np = ggplot() + ggsize(w, h)\r\n\r\np1 = p + geom_bar(aes(x='fl'), data=df) + \\\r\n         ggtitle('Default geom_bar() Stat - Count')\r\n\r\ndf2 = df.groupby('fl').median().iloc[:, 0].sort_values().to_frame('median').reset_index()\r\np2 = p + geom_bar(aes(x='fl', y='median'), data=df2, stat='identity') + \\\r\n         ggtitle('Identity Stat for Calculated Median')\r\n\r\np3 = p + geom_bin2d(aes('cty', 'hwy'), data=df) + \\\r\n         ggtitle('Default geom_bin2d() Stat - Count')\r\n\r\ndf4 = df.groupby(['cty', 'hwy']).median().iloc[:, 0].to_frame('median').reset_index()\r\np4 = p + geom_raster(aes(x='cty', y='hwy', fill='median'), data=df4, stat='identity') + \\\r\n         ggtitle('Identity Stat for Calculated Median')\r\n\r\nbunch = GGBunch()\r\nbunch.add_plot(p1, 0, 0)\r\nbunch.add_plot(p2, w, 0)\r\nbunch.add_plot(p3, 0, h)\r\nbunch.add_plot(p4, w, h)\r\nbunch","sub_path":"docs/_downloads/63a857408cdf733e41fa18d20874dc49/plot__general_purpose_stats.py","file_name":"plot__general_purpose_stats.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"654246164","text":"\"\"\"\nname: Hayam Abdalla\ntraffic.py\n\nproblem: Practice accumulations and nested loops\n\ncertification of authenticity:\nI certify that this assignment is entirely my own work.\n\"\"\"\n\n\ndef main():\n    total_numbers_vehicles = 0\n    road_numbers = eval(input(\"How many roads were surveyed? \"))\n    for i in range(road_numbers):\n        total_cars = 0\n        days_numbers = eval(input(\"how many days was road \" + str(i+1) + \"surveyed\"))\n        for day in range(days_numbers):\n            cars_traveled = eval(input(\"how many cars traveled on day \" + str(day + 1) + \"?\"))\n            total_cars = total_cars + cars_traveled\n        average_number_cars= round(total_cars/days_numbers, 2)\n        print(\"Road\" + str(i + 1) + \"average vehicles per day:\", average_number_cars)\n        total_numbers_vehicles = total_numbers_vehicles + total_cars\n    print(\"total number of vehicles traveled on all roads:\", total_numbers_vehicles)\n    average_number_vehicles = total_numbers_vehicles / road_numbers\n    print(\"average number of vehicles per road:\", round(average_number_vehicles, 2))\n","sub_path":"assignments/hw4/traffic.py","file_name":"traffic.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"162516006","text":"from .. import export\nfrom suitcase.tiff_series.tests.tests import create_expected\nfrom numpy.testing import assert_array_equal\nimport os\nimport tifffile\n\n\ndef test_export(tmp_path, example_data):\n    '''Runs a test using the plan that is passed through to it.\n\n    ..note::\n\n        Due to the `example_data` `pytest.fixture` this will run multiple tests\n        each with a range of detectors and a range of event_types. See\n        `suitcase.utils.conftest` for more info.\n\n    '''\n\n    collector = example_data()\n    artifacts = export(collector, tmp_path, file_prefix='')\n    expected = create_expected(collector, stack_images=True)\n\n    for filename in artifacts.get('stream_data', []):\n        actual = tifffile.imread(str(filename))\n        streamname = os.path.basename(filename).split('-')[0]\n        assert_array_equal(actual, expected[streamname])\n\n\ndef test_file_prefix_formatting(file_prefix_list, example_data, tmp_path):\n    '''Runs a test of the ``file_prefix`` formatting.\n\n    ..note::\n\n        Due to the `file_prefix_list` and `example_data` `pytest.fixture`'s\n        this will run multiple tests each with a range of file_prefixes,\n        detectors and event_types. See `suitcase.utils.conftest` for more info.\n\n    '''\n    collector = example_data()\n    file_prefix = file_prefix_list()\n    artifacts = export(collector, tmp_path, file_prefix=file_prefix)\n\n    for name, doc in collector:\n        if name == 'start':\n            templated_file_prefix = file_prefix.format(**doc).partition('-')[0]\n            break\n\n    if artifacts:\n        unique_actual = set(str(artifact).split('/')[-1].partition('-')[0]\n                            for artifact in artifacts['stream_data'])\n        assert unique_actual == set([templated_file_prefix])\n","sub_path":"suitcase/tiff_stack/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"522110381","text":"\n#disable or enable this if you have oom problems\nimport tensorflow\nconfig = tensorflow.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tensorflow.Session(config=config)\n\n\nimport os.path\nimport mask_rcnn_additional\nimport kutils\nimport numpy\nimport cv2\nimport sys\nimport os\nimport skimage.morphology\nimport json\nimport matplotlib\nmatplotlib.use('TkAgg')\n\n\nclass Segmentation:\n    __mModel = None\n    __mConfig = None\n    __mModelDir = \"\"\n    __mModelPath = \"\"\n    __mLastMaxDim = mask_rcnn_additional.NucleiConfig().IMAGE_MAX_DIM\n    __mConfidence = 0.5\n    __NMSThreshold = 0.35\n\n    '''\n    @param pModelDir clustering Mask_RCNN model path\n    '''\n    def __init__(self, pModelPath, pConfidence=0.5, pNMSThreshold = 0.35, pMaxDetNum=512):\n        if not os.path.isfile(pModelPath):\n            raise ValueError(\"Invalid model path: \" + pModelPath)\n\n        self.__mConfidence = pConfidence\n        self.__NMSThreshold = pNMSThreshold\n        self.__mModelPath = pModelPath\n        self.__mModelDir = os.path.dirname(pModelPath)\n        self.__mMaxDetNum=pMaxDetNum\n\n    def Segment(self, pImage, pPaddingRatio=0.0, pDilationSElem=None, pCavityFilling=False, pPredictSize=None):\n\n        rebuild = self.__mModel is None\n\n        if pPredictSize is not None:\n            maxdim = pPredictSize\n            temp = maxdim / 2 ** 6\n            if temp != int(temp):\n                maxdim = (int(temp) + 1) * 2 ** 6\n\n            if maxdim != self.__mLastMaxDim:\n                self.__mLastMaxDim = maxdim\n                rebuild = True\n\n        if rebuild:\n            import model\n            import keras.backend\n            keras.backend.clear_session()\n            print(\"Max dim changed (\",str(self.__mLastMaxDim),\"), rebuilding model\")\n\n            self.__mConfig = mask_rcnn_additional.NucleiConfig()\n            self.__mConfig.DETECTION_MIN_CONFIDENCE = self.__mConfidence\n            self.__mConfig.DETECTION_NMS_THRESHOLD = self.__NMSThreshold\n            self.__mConfig.IMAGE_MAX_DIM = self.__mLastMaxDim\n            self.__mConfig.IMAGE_MIN_DIM = self.__mLastMaxDim\n            self.__mConfig.DETECTION_MAX_INSTANCES=self.__mMaxDetNum\n            self.__mConfig.__init__()\n\n            self.__mModel = model.MaskRCNN(mode=\"inference\", config=self.__mConfig, model_dir=self.__mModelDir)\n            self.__mModel.load_weights(self.__mModelPath, by_name=True)\n\n        image = kutils.RCNNConvertInputImage(pImage)\n        offsetX = 0\n        offsetY = 0\n        width = image.shape[1]\n        height = image.shape[0]\n\n        if pPaddingRatio > 0.0:\n            image, (offsetX, offsetY) = kutils.PadImageR(image, pPaddingRatio)\n\n        results = self.__mModel.detect([image], verbose=0)\n\n        r = results[0]\n        masks = r['masks']\n        scores = r['scores']\n\n        if masks.shape[0] != image.shape[0] or masks.shape[1] != image.shape[1]:\n            print(\"Invalid prediction\")\n            return numpy.zeros((height, width), numpy.uint16), \\\n                   numpy.zeros((height, width, 0), numpy.uint8),\\\n                   numpy.zeros(0, numpy.float)\n\n\n        count = masks.shape[2]\n        if count < 1:\n            return numpy.zeros((height, width), numpy.uint16), \\\n                   numpy.zeros((height, width, 0), numpy.uint8),\\\n                   numpy.zeros(0, numpy.float)\n\n        if pPaddingRatio > 0.0:\n            newMasks = numpy.zeros((height, width, count), numpy.uint8)\n\n            for i in range(count):\n                newMasks[:, :, i] = masks[offsetY: (offsetY + height), offsetX: (offsetX + width), i]\n\n            masks = newMasks\n\n        if pDilationSElem is not None:\n            for i in range(count):\n                masks[:, :, i] = cv2.dilate(masks[:, :, i], kernel=pDilationSElem)\n\n        if pCavityFilling:\n            for i in range(count):\n                temp = cv2.bitwise_not(masks[:, :, i])\n                temp, _, _ = cv2.findContours(temp, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n                masks[:, :, i] = cv2.bitwise_not(temp)\n#            for i in range(count):\n#                masks[:, :, i] = scipy.ndimage.binary_fill_holes(masks[:, :, i])\n\n        for i in range(count):\n            masks[:, :, i] = numpy.where(masks[:, :, i] == 0, 0, 255)\n\n        return kutils.MergeMasks(masks), masks, scores\n\n\nprint(\"Usage: \" + sys.argv[0] + \" settings.json\")\n\ninputDir = \"\"\noutputDir = \"\"\nmodelPath = \"\"\nseparate = False\npadding = 0.0\ndilate = 0\ncavityFill = False\nconfidence = 0.5\nscaleFilePath = None\nnmsThresh = 0.35\nscoreDir = None\ndefaultSize = None\nshowOutputs = False\n\njsn = json.load(open(sys.argv[1]))\nparams = jsn[\"segmentation_params\"]\ninputDir = os.path.join(os.curdir, params[\"input_dir\"])\noutputDir = os.path.join(os.curdir, params[\"output_dir\"])\nmodelPath = os.path.join(os.curdir, params[\"model\"])\n\nif \"detection_nms_threshold\" in params:\n    nmsThresh = float(params[\"detection_nms_threshold\"])\nif \"default_image_size\" in params:\n    defaultSize = int(params[\"default_image_size\"])\nif \"separate_masks\" in params:\n    separate = params[\"separate_masks\"] == \"true\"\nif \"padding\" in params:\n    padding = float(params[\"padding\"])\nif \"dilation\" in params:\n    dilate = int(params[\"dilation\"])\nif \"cavity_filling\" in params:\n    cavityFill = params[\"cavity_filling\"] == \"true\"\nif \"detection_confidence\" in params:\n    confidence = float(params[\"detection_confidence\"])\nif \"scale_file\" in params:\n    scaleFilePath = params[\"scale_file\"]\nif \"scores_dir\" in params:\n    scoreDir = params[\"scores_dir\"]\nif \"show\" in params:\n    showOutputs = params[\"show\"] == \"true\"\nif \"detection_max_instances\" in params:\n    maxDetNum=int(params[\"detection_max_instances\"])\n\nimagesDir = os.path.join(inputDir,\"images\")\nimageFiles = [f for f in os.listdir(imagesDir) if os.path.isfile(os.path.join(imagesDir, f))]\n\nmethod = Segmentation(pModelPath=modelPath, pConfidence=confidence, pNMSThreshold=nmsThresh, pMaxDetNum=maxDetNum)\n\n# parsing scale file if present\nscales = {}\nif scaleFilePath is not None:\n    scaleFile = open(scaleFilePath, \"r\")\n    for line in scaleFile:\n        elems = line.split()\n        scales[elems[0]] = float(elems[1])\n    scaleFile.close()\n\nif len(scales) < 1:\n    imageFiles = sorted(imageFiles)\n\nelse:\n    for imageFile in imageFiles:\n        baseName = os.path.splitext(os.path.basename(imageFile))[0]\n        if baseName not in scales:\n            if defaultSize is not None:\n                scales[baseName] = defaultSize\n            else:\n                print(\"Missing scaling entry for\", baseName, \", skipping\")\n\n    # sorting scales\n    import operator\n    scales = sorted(scales.items(), key=operator.itemgetter(1))\n    imageFiles = []\n    for file, _ in scales:\n        imageFiles.append(file + \".png\")\n\n    scales = dict(scales)\n\nos.makedirs(name=outputDir, exist_ok=True)\nif scoreDir is not None:\n    os.makedirs(name=scoreDir, exist_ok=True)\n\nimcount = len(imageFiles)\nfor index, imageFile in enumerate(imageFiles):\n    print(\"Image:\", str(index + 1), \"/\", str(imcount), \"(\", imageFile, \")\")\n\n    baseName = os.path.splitext(os.path.basename(imageFile))[0]\n    imagePath = os.path.join(imagesDir, imageFile)\n    if \".DS_Store\" in imagePath:\n        continue\n    image = skimage.io.imread(imagePath)\n\n    dilationStruct = None\n    if dilate > 0:\n        dilationStruct = skimage.morphology.disk(dilate)\n\n    maxdim = None\n    if baseName in scales:\n        maxdim = int(scales[baseName])\n    else:\n        maxdim = defaultSize\n\n    mask, masks, scores = method.Segment(pImage=image, pPaddingRatio=padding, pCavityFilling=cavityFill, pDilationSElem=dilationStruct, pPredictSize=maxdim)\n\n    count = masks.shape[2]\n    print(\"  Nuclei (including cropped):\", str(count))\n\n    skimage.io.imsave(os.path.join(outputDir, baseName + \".tiff\"), mask)\n\n    if count < 1:\n        continue\n\n    if separate:\n        masksDir = os.path.join(outputDir, baseName, \"masks\")\n        os.makedirs(name=masksDir, exist_ok=True)\n        for m in range(count):\n            skimage.io.imsave(os.path.join(masksDir, str(m) + \".png\"), masks[:, :, m])\n\n    if scoreDir is not None:\n        scoreFile = open(os.path.join(scoreDir, baseName + \".tsv\"),\"w\")\n        scoreFile.write(\"label\\tscore\\r\\n\")\n        for s in range(count):\n            scoreFile.write(str(s+1) + \"\\t\" + str(scores[s])+ \"\\r\\n\")\n        scoreFile.close()\n","sub_path":"nucleAIzer/biomagdsb/FinalModel/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"392469807","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/fabien/.virtualenvs/scrapy3/lib/python3.6/site-packages/scrapoxy/downloadmiddlewares/proxy.py\n# Compiled at: 2017-12-15 11:20:18\n# Size of source mod 2**32: 1288 bytes\n\"\"\"\nAn extension to use Scrapoxy as a proxy for Scrapy.\n\nYou must fill PROXY in settings:\nPROXY = 'http://127.0.0.1:8888/?noconnect'\n\nDon't forget the ?noconnect to use HTTPS over HTTP.\n\"\"\"\nfrom __future__ import unicode_literals\nimport base64, re\n\nclass ProxyMiddleware(object):\n\n    def __init__(self, crawler):\n        proxy = crawler.settings.get('PROXY')\n        if proxy:\n            parts = re.match('(\\\\w+://)(\\\\w+:\\\\w+@)?(.+)', proxy)\n            if parts.group(2):\n                proxy_auth = parts.group(2)[:-1].encode().decode().strip()\n                self._proxy_auth = 'Basic {}'.format(base64.b64encode(proxy_auth.encode('ascii')).decode('ascii'))\n                print(self._proxy_auth)\n            self._proxy = parts.group(1) + parts.group(3)\n\n    @classmethod\n    def from_crawler(cls, crawler):\n        return cls(crawler)\n\n    def process_request(self, request, spider):\n        if request.meta.get('no-proxy'):\n            return\n        if hasattr(self, '_proxy'):\n            request.meta['proxy'] = self._proxy\n            if hasattr(self, '_proxy_auth'):\n                request.headers['proxy-authorization'] = self._proxy_auth","sub_path":"pycfiles/scrapoxy-1.11.tar/proxy.cpython-36.py","file_name":"proxy.cpython-36.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"536367066","text":"import greengrasssdk\nimport time\nimport json\nimport boto3\nimport datetime\nimport itertools\nimport threading\n\nfrom threading import Timer\nfrom influxdb import InfluxDBClient\n\n\n# Creating a ggc and influxdb clients\ngg_client = greengrasssdk.client('iot-data')\ndb_client = InfluxDBClient('localhost', 8086, 'root', 'root', 'postal_service')\n\n\n# Define lambda globals\nFORWARD_MQ_CHANNEL = 'postal/telemetry/stream/forward'\n\nGGC_BTN_B_SHADOW_NAME = 'GG_BTN_BLUE'\nGGC_BTN_Y_SHADOW_NAME = 'GG_BTN_YELLOW'\nGGC_LED_Y_SHADOW_NAME = 'GG_LED_YELLOW'\nGGC_LED_B_SHADOW_NAME = 'GG_LED_BLUE'\n\nSHADOW_NAMES = [\n    GGC_BTN_B_SHADOW_NAME,\n    GGC_BTN_Y_SHADOW_NAME,\n    GGC_LED_Y_SHADOW_NAME,\n    GGC_LED_B_SHADOW_NAME\n]\n\n\nclass PostalThread(threading.Thread):\n\n    def __init__(self, threadID, name):\n        threading.Thread.__init__(self)\n\n        self.threadID = threadID\n        self.name     = name\n\n    def run(self):\n\n        while True:\n\n            telemetry_query = \"SELECT * FROM {} WHERE time > now() - 15s;\".format(\n                \", \".join(SHADOW_NAMES))\n\n            results = db_client.query(telemetry_query)\n\n            payload = {d: list(results.get_points(d)) for d in SHADOW_NAMES}\n            JSONPayload = json.dumps(payload).encode()\n\n            gg_client.publish(\n                topic=FORWARD_MQ_CHANNEL,\n                payload=JSONPayload\n            )\n\n            time.sleep(15)\n\n\npostal_thread = PostalThread(1, 'Postal-Thread')\npostal_thread.start()\n\n\ndef function_handler(event, context):\n    pass\n","sub_path":"greengrass/ggc_groups_ste/lambda/sample_zero/ggcPostalServiceForward/ggcPostalServiceForward.py","file_name":"ggcPostalServiceForward.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"340565606","text":"from Exercise import *\n\nfrom git_ignore import config\nimport talking\nimport time\nclass User:\n    primary_id = -1\n    id = -1\n    current_training = 0\n    current_exercise = 0\n    full_name = \"\"\n    nickname = \"\"\n    check_time = 0.0\n    status = \"\"\n    trainings = []\n\n    def __init__(self, _tuple = (), _primary_id = -1, _id = -1, _full_name = \"\", _nickname = \"\", _current_training = 0, _current_exercise = 0, _status = \"Sleeping\", _check_time = 0):\n        if _tuple:\n            self.primary_id = _tuple[0]\n            self.id = _tuple[1]\n            self.full_name = _tuple[2]\n            self.nickname = _tuple[3]\n            self.current_training = _tuple[4]\n            self.current_exercise = _tuple[5]\n            self.status = _tuple[6]\n            self.check_time = _tuple[7]\n        else:\n            self.primary_id = _primary_id\n            self.id = _id\n            self.full_name = _full_name\n            self.nickname = _nickname\n            self.current_training = _current_training\n            self.current_exercise = _current_exercise\n            self.status = _status\n            self.check_time = _check_time\n\n\n    def encode_to_json(self):\n        encoded_trainings = []\n        for train in self.trainings:\n            encoded_train = train.encode_to_json()\n            encoded_trainings.append(encoded_train)\n        return {\"id\": str(self.id), \"current_training\":  str(self.current_training),\n                \"current_exercise\": str(self.current_exercise), \"full_name\": self.full_name,\n                \"nickname\": self.nickname, \"check_time\": str(self.check_time),\n                \"status\": self.status, \"trainings\": encoded_trainings}\n\n    def decode_from_json(self, json_group):\n        self.id = int(json_group[\"id\"])\n        self.current_training = int(json_group[\"current_training\"])\n        self.full_name = json_group[\"full_name\"]\n        self.nickname = json_group[\"nickname\"]\n        self.check_time =  float(json_group[\"check_time\"])\n        self.status = json_group[\"status\"]\n        \n        encoded_trainings = json_group[\"trainings\"]\n        for encoded_train in encoded_trainings:\n            new_train = Training()\n            new_train.decode_from_json(encoded_train)\n            self.trainings.append(new_train)\n\n\n    def timeout(self):\n        return ((not self.status == \"Waiting\") and float(self.check_time) < time.time())\n\n    def finished(self):\n        return self.current_training >= len(self.trainings)\n\n    def get_exercise(self):\n        if self.current_exercise >= len(self.trainings[self.current_training].exercises):\n            return talking.last_exercise\n        else:\n            return self.trainings[self.current_training].exercises[self.current_exercise].to_message()\n\n    def let_go(self):\n        self.status = \"Sleeping\"\n        self.check_time = time.time() + config.TWO_DAYS\n        self.current_exercise = 0\n","sub_path":"User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"375484055","text":"#\n# Copyright 2014 iXsystems, Inc.\n# All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted providing that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n#    notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n#    notice, this list of conditions and the following disclaimer in the\n#    documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#####################################################################\n\nfrom freenas.utils import exclude\n\n\ndef restore_collection(ds, dump):\n    metadata = dump['metadata']\n    data = dump['data']\n    name = metadata['name']\n    integer = metadata['pkey-type'] in ('integer', 'serial')\n\n    ds.collection_delete(name)\n    ds.collection_create(name, metadata['pkey-type'], metadata['attributes'])\n    configstore = metadata['attributes'].get('configstore', False)\n\n    for key, row in list(data.items()):\n        pkey = int(key) if integer else key\n        ds.insert(name, row, pkey=pkey, config=configstore)\n\n\ndef restore_db(ds, dump, types=None, progress_callback=None):\n    for i in dump:\n        metadata = i['metadata']\n        attrs = metadata['attributes']\n        if types and 'type' in attrs.keys() and attrs['type'] not in types:\n            continue\n\n        restore_collection(ds, i)\n        if progress_callback:\n            progress_callback(metadata['name'])\n\n\ndef dump_collection(ds, name):\n    metadata = {\n        'name': name,\n        'pkey-type': ds.collection_get_pkey_type(name),\n        'attributes': ds.collection_get_attrs(name),\n        'migration': ds.collection_get_migration_policy(name),\n        'migrations': ds.collection_get_migrations(name)\n    }\n\n    configstore = metadata['attributes'].get('configstore', False)\n\n    def collect():\n        return {x['id']: exclude(x, 'id') for x in ds.query(name)}\n\n    def collect_configstore():\n        return {x['id']: x['value'] for x in ds.query(name)}\n\n    return {\n        'metadata': metadata,\n        'data': collect_configstore() if configstore else collect()\n    }\n","sub_path":"src/datastore/datastore/restore.py","file_name":"restore.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"145902636","text":"# import the necessary packages\nfrom face_recognition import db,app\nfrom face_recognition.WebCam_Face_Recognition import modules\nfrom datetime import datetime\nimport numpy as np\nfrom PIL import Image\nfrom numpy import asarray\nimport imutils\nimport cv2\nimport traceback\nimport pytz\n\n# get the standard UTC time\nUTC = pytz.utc\nIST = pytz.timezone('Asia/Kolkata')\n\ndef get_detections(caffe_model,frame):\n\t# image preprocessing like mean substraction to pass it in neural networks\n\tblob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\n\t# blob.shape = (1, 3, 300, 300)\n\t# pass the blob through the network and obtain the detections and\n\t# predictions\n\tcaffe_model.setInput(blob)\n\tdetections = caffe_model.forward()\n\t# detection.shape =  (1, 1, 200, 7)\n\t'''\n    7 columns:\n    3rd column = confidence of pizel\n    4th column = (startX)/width\n    5th column = (startY)/height\n    6th column = (endX)/width\n    7th column = (endY)/height\n    '''\n\n\treturn detections\n\n\ndef get_box(detection, dims):\n\tw = dims['w']\n\th = dims['h']\n\tbox = detection * np.array([w, h, w, h])\n\treturn box.astype(\"int\")\n\n\ndef draw_box(frame, dims):\n\t'''\n    draw a box on face\n    '''\n\tstartX, startY, endX, endY = dims\n\t# draw the bounding box of the face along with the associated\n\t# probability\n\tcv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)\n\n\ndef crop_image(frame, dims,required_size):\n\t'''\n    returns face as a array\n    '''\n\tstartX, startY, endX, endY = dims\n\t# crop face from image array\n\tcrop = frame[startY:endY, startX:endX]\n\t# convert array into image\n\tcrop_img = Image.fromarray(crop)\n\t# resize face to (160,160,3)\n\tcrop_img = crop_img.resize(required_size)\n\t# convert face image into array\n\tface = asarray(crop_img)\n\treturn face\n\n\ndef predict_label(embs, svm_model,label_encoder):\n\t'''\n    returns label name & prediction probability using (128,1) embeddings\n    '''\n\t# to normalize face pixels\n\tencoder = modules.Normalizer()\n\tembs = encoder.transform(modules.expand_dims(embs, axis=0))\n\n\t# predict class lebel in numeric data type\n\tclass_val = svm_model.predict(embs)\n\t# convert numeric label into string i.e. 0 -> karm\n\tclass_name = label_encoder.inverse_transform(class_val)[0]\n\t# confidence to recognize\n\tclass_probability = max(svm_model.predict_proba(embs)[0])\n\n\treturn (class_name, class_probability)\n\n\ndef write_text(frame, data, dims,h):\n\t'''\n    write label name on face\n    '''\n\tstartX, startY, endX, endY= dims\n\ttext = str(data[\"class_name\"]) + \"-\" + str(round(data[\"class_probability\"] * 100, 2)) + \"%\"\n\ttext_face = \"face = \" + str(round(data[\"detection_conf\"], 2))\n\t# put text above rectangle\n\t# fix y position,where we have to put text\n\ty = startY - 10 if startY - 10 > 10 else endY + 10\n\ty_f = endY + 10 if endY + 10 < h else startY - 10\n\tcv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 0, 0), 2)\n\tcv2.putText(frame, text_face, (startX, y_f), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)\n\ndef camera():\n\n\t#for face detection\n\tconfidence_threshold = 0.5\n\n\t#for face recognition\n\tprediction_threshold = 0.5\n\n\t#for frame count to decide attendance\n\tframe_count_threshold = 5\n\trequired_size = (160, 160)\n\n\t#get models\n\tfacenet_model = app.config['FACENET_MODEL']\n\tcaffe_model = app.config['CAFFE_MODEL']\n\tsvm_model = app.config['SVM_MODEL']\n\tlabel_encoder = app.config['LABEL_ENCODER']\n\n\t# loop over the frames from the video stream\n\tprint(\"starting video stream...\")\n\t# capture from PC's Camera\n\t# vs = VideoStream(src=0).start()\n\n\t# Capture from Phone's Camera\n\t# url = \"http://192.168.0.104:8080/video\"\n\tvs = cv2.VideoCapture(0)\n\tif not vs:\n\t\tprint(\"camera can not capture frame!\")\n\n\t# loop over the frames from the video stream\n\tframe_count = 0\n\tattendance_marked = {}\n\tattendance_started = {}\n\twhile True:\n\t\tframe_count = (frame_count + 1) % 1000\n\t\t# grab the frame from the threaded video stream and resize it\n\t\t# to have a maximum width of 400 pixels\n\n\t\t# for mobile camera\n\t\th, frame = vs.read()\n\t\tframe = imutils.resize(frame, width=360)\n\t\t#for pc camera\n\t\t#frame = vs.read()\n\t\t#frame = imutils.resize(frame, width=720)\n\t\t# grab the frame dimensions and convert it to a blob\n\t\t(h, w) = frame.shape[:2]\n\t\tdetections = get_detections(caffe_model,frame)\n\t\t# loop over the detections\n\t\t# for each in detections:\n\t\tfor i in range(0, detections.shape[2]):\n\n\t\t\t# extract the confidence (i.e., probability) associated with the prediction\n\t\t\tconfidence = detections[0, 0, i, 2]\n\t\t\t# confidence = each['confidence']\n\n\t\t\t# filter out weak detections by ensuring the `confidence` is\n\t\t\t# greater than the minimum confidence\n\n\t\t\tif confidence < confidence_threshold:\n\t\t\t\tcontinue\n\n\t\t\t# compute the (x, y)-coordinates of the bounding box for the\n\t\t\t# object\n\t\t\tdims = get_box(detections[0, 0, i, 3:7], {\"h\": h, \"w\": w})\n\t\t\tstartX, startY, endX, endY = dims\n\n\t\t\t# draw rectangle on face\n\t\t\tdraw_box(frame, dims)\n\n\t\t\ttry:\n\t\t\t\t# crop face from image\n\t\t\t\tface = crop_image(frame, dims,required_size)\n\n\t\t\t\t# get embeddings from image\n\t\t\t\tembs = modules.get_embeddings(facenet_model, face)\n\n\t\t\t\t# predict label\n\t\t\t\tclass_name, class_probability = predict_label(embs, svm_model,label_encoder)\n\n\t\t\t\tif class_probability < prediction_threshold:\n\t\t\t\t\tclass_name = \"unknown\"\n\n\t\t\t\tif class_name not in attendance_marked and class_name != \"unknown\":\n\t\t\t\t\ttry:\n\t\t\t\t\t\tattendance_started[class_name][\"count\"] += 1\n\t\t\t\t\t\tattendance_started[class_name][\"confidence\"] += class_probability\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(class_name, \" recognized!\")\n\t\t\t\t\t\tattendance_started[class_name] = {\"count\": 1, \"confidence\": class_probability}\n\t\t\t\t\tif attendance_started[class_name][\"count\"] >= frame_count_threshold:\n\t\t\t\t\t\tprint(class_name, \" Attendance marked!\")\n\t\t\t\t\t\ttrue_count = attendance_started[class_name][\"count\"]\n\n\t\t\t\t\t\tattendance_marked[class_name] = {\"frame_count\":true_count,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"confidence\":round(attendance_started[class_name][\"confidence\"] / true_count, 2),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"time\":str(datetime.now(IST).time())}\n\t\t\t\t# print(attendance_started)\n\t\t\t\t# print(frame_count)\n\t\t\t\tdata = {\"class_name\":class_name,\"class_probability\":class_probability,\"detection_conf\":confidence}\n\n\t\t\t\t#write the label of person\n\t\t\t\twrite_text(frame, data, dims,h)\n\t\t\texcept Exception:\n\t\t\t\ttraceback.print_exc()\n\t\t\t\t# print(\"title outside\")\n\t\t\t\tpass\n\n\t\t#print(frame_count, end='\\r')\n\n\t\t# show the output frame\n\t\tcv2.imshow(\"Frame\", frame)\n\t\tkey = cv2.waitKey(1)\n\n\t\t# if the `q` key was pressed, break from the loop\n\t\tif key == ord(\"q\"):\n\t\t\tbreak\n\n\t# do a bit of cleanup\n\tcv2.destroyAllWindows()\n\n\t# for pc camera\n\t# vs.stop()\n\tprint(attendance_started)\n\tprint(attendance_marked)\n\t# & 0xFF\n\t#for mobile camera\n\tvs.release()\n\tprint(\"camera stopped\")\n\treturn attendance_marked\n\t#& 0xFF\n","sub_path":"face_recognition/WebCam_Face_Recognition/LiveFaceRecognition.py","file_name":"LiveFaceRecognition.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"19617716","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, ingredients):\n  batches = {}\n\n  for ingredient in list(recipe.keys()):\n    if ingredient not in list(ingredients.keys()):\n      return 0\n  \n  for ingredient in ingredients:\n    batches[ingredient] = ingredients[ingredient] // recipe[ingredient]\n\n  min_batches = batches[ingredient]\n  for ingredient in batches:\n    if batches[ingredient] < min_batches:\n      min_batches = batches[ingredient]\n      \n  return min_batches\n\nif __name__ == '__main__':\n  # Change the entries of these dictionaries to test \n  # your implementation with different inputs\n  recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n  ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n  print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"448121423","text":"\"\"\"\nThe Lab Manager utility module\n\"\"\"\nimport httplib\n\n##from xml.sax import make_parser, SAXException\n##from xml.sax.handler import feature_namespaces\nimport logging\n\n\ndef funcListConfigurations(strLmIp=\"10.201.16.10\"):\n    \"\"\"\n    To list Lab Manager Configuration\n    @type strLmIp: the Lab Manager IP\n    \"\"\"\n    logging.info('LabManger >> funcListConfigurations')\n\n    strSoapTemplate = \"\"\"\n   \n      \n         \n         Titanium_auto\n         \n         Titanium@2009\n         \n         \n      \n   \n   \n      \n         1\n      \n   \n\"\"\"\n\n    logging.info('LabManger >> funcListConfigurations >> SoapMessage:')\n    logging.info(strSoapTemplate)\n\n    #print SoapMessage\n    webservice = httplib.HTTPS(strLmIp)\n    webservice.putrequest(\"POST\", \"/LabManager/SOAP/LabManager.asmx\")\n    webservice.putheader(\"Host\", strLmIp)\n    webservice.putheader(\"User-Agent\", \"Python Post\")\n    webservice.putheader(\"Content-type\", \"text/xml; charset=\\\"UTF-8\\\"\")\n    webservice.putheader(\"Content-length\", \"%d\" % len(strSoapTemplate))\n    webservice.putheader(\"SOAPAction\",\n                         \"\\\"http://vmware.com/labmanager/funcListConfigurations\\\"\")\n    webservice.endheaders()\n    webservice.send(strSoapTemplate)\n\n    # get the response\n\n    logging.info('LabManger >> funcListConfigurations >> Get response:')\n    lstReplyHeader = webservice.getreply()\n    logging.info(lstReplyHeader)\n\n    logging.info('LabManger >> funcListConfigurations >> Get file:')\n    objReplyContent = webservice.getfile()\n    logging.info(objReplyContent.next())\n\n\ndef funcGetMachineId(strVmName, strLmIp=\"10.201.16.10\"):\n    \"\"\"\n    To get lab manager machine id for operation.\n    \"\"\"\n    strSoapTemplate1 = \"\"\"\n   \n      \n         \n         Titanium_auto\n         \n         Titanium@2009\n         \n         \n      \n   \n   \n      \n         989\n         %s\n      \n   \n\"\"\"\n\n    logging.info('LabManger >> funcListConfigurations >> SoapMessage:')\n    strSoapTemplate1 = strSoapTemplate1 % (strVmName)\n    logging.info(strSoapTemplate1)\n\n    #print SoapMessage\n    webservice = httplib.HTTPS(strLmIp)\n    webservice.putrequest(\"POST\", \"/LabManager/SOAP/LabManager.asmx\")\n    webservice.putheader(\"Host\", strLmIp)\n    webservice.putheader(\"User-Agent\", \"Python Post\")\n    webservice.putheader(\"Content-type\", \"text/xml; charset=\\\"UTF-8\\\"\")\n    webservice.putheader(\"Content-length\", \"%d\" % len(strSoapTemplate1))\n    webservice.putheader(\n        \"SOAPAction\", \"\\\"http://vmware.com/labmanager/GetMachineByName\\\"\")\n    webservice.endheaders()\n    webservice.send(strSoapTemplate1)\n\n    # get the response\n\n    logging.info('LabManger >> funcListConfigurations >> Get response:')\n    lstReplyHeader = webservice.getreply()\n    logging.info(lstReplyHeader)\n\n    if lstReplyHeader[1] == 'OK':\n        logging.info('LabManger >> funcListConfigurations >> Get file:')\n        objReplyContent = webservice.getfile()\n        logging.info(objReplyContent.next())\n\n#===============================================================================\n# 1 XPower On. Turns on a machine.\n# 2 XPower Off. Turns off a machine. Nothing is saved.\n# 3 XSuspend. Freezes a machine CPU and state.\n# 4 XResume. Resumes a suspended machine.\n# 5 XReset. Reboots a machine.\n# 6 XSnapshot. Save a machine state at a specific point in time.\n# 7 XRevert. Returns a machine to a snapshot state.\n# 8 XShutdown. Shuts down a machine before turning off.\n#===============================================================================\n\n\ndef funcMachineActionTemplate(intMachineID, intActionID,\n                              strLmIp=\"10.201.16.10\",\n                              strLmUserName=\"Titanium_auto\",\n                              strLmPassword=\"Titanium@2009\"):\n    \"\"\"\n    Do lab manager action by input machine id and action id\n    @type strLmIp: String\n    @param strLmIp: the Lab Manager IP\n    @type strLmUserName: String\n    @param strLmUserName: the Lab Manager User Account\n    @type strLmPassword: String\n    @param strLmPassword: the Lab Manager User Password\n    @return: the Lab Manager execute result code. For example 200 means OK\n    \"\"\"\n    logging.info('LabManger >> funcMachinePerformActionTemplate')\n    logMessage = 'intMachineID=%d, intActionID=%d' % (\n        intMachineID, intActionID)\n    logging.info(logMessage)\n\n    strSoapTemplate = \"\"\"\n   \n      \n         \n         %s\n         \n         %s\n         \n         \n      \n   \n   \n      \n         %d\n         %d\n      \n   \n\"\"\"\n\n    strSoapMessage = strSoapTemplate % (strLmUserName, strLmPassword,\n                                        intMachineID, intActionID)\n\n    logging.info('LabManger >> funcMachinePerformActionTemplate'\n                 ' >> SoapMessage:')\n    logging.info(strSoapMessage)\n\n    #print SoapMessage\n    webservice = httplib.HTTPS(strLmIp)\n    webservice.putrequest(\"POST\", \"/LabManager/SOAP/LabManager.asmx\")\n    webservice.putheader(\"Host\", strLmIp)\n    webservice.putheader(\"User-Agent\", \"Python Post\")\n    webservice.putheader(\"Content-type\", \"text/xml; charset=\\\"UTF-8\\\"\")\n    webservice.putheader(\"Content-length\", \"%d\" % len(strSoapMessage))\n    webservice.putheader(\"SOAPAction\",\n                         \"\\\"http://vmware.com/labmanager/MachinePerformAction\\\"\")\n    webservice.endheaders()\n    webservice.send(strSoapMessage)\n\n    # get the response\n\n    logging.info('LabManger >> funcMachinePerformActionTemplate >>'\n                 ' Get response:')\n    lstReplyHeader = webservice.getreply()\n    logging.info(lstReplyHeader)\n    return lstReplyHeader[0]\n\n#===============================================================================\n# 1 XPower On. Turns on a machine.\n# 2 XPower Off. Turns off a machine. Nothing is saved.\n# 3 XSuspend. Freezes a machine CPU and state.\n# 4 XResume. Resumes a suspended machine.\n# 5 XReset. Reboots a machine.\n# 6 XSnapshot. Save a machine state at a specific point in time.\n# 7 XRevert. Returns a machine to a snapshot state.\n# 8 XShutdown. Shuts down a machine before turning off.\n#===============================================================================\n\n\ndef funcPowerOn(intMachineID):\n    \"\"\"\n    Do power on\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 1)\n\n\ndef funcPowerOff(intMachineID):\n    \"\"\"\n    Do power off\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 2)\n\n\ndef funcSuspend(intMachineID):\n    \"\"\"\n    Do suspend\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 3)\n\n\ndef funcResume(intMachineID):\n    \"\"\"\n    Do resume\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 4)\n\n\ndef funcReset(intMachineID):\n    \"\"\"\n    Do reset\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 5)\n\n\ndef funcSnapshot(intMachineID):\n    \"\"\"\n    Do snapshot\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 6)\n\n\ndef funcRevert(intMachineID, strLmIp, strLmUserName, strLmPassword):\n    \"\"\"\n    Do revert Lab Manager VM\n    @type intMachineID: Integer\n    @param intMachineID: the VM id for identify action target\n    @type strLmIp: String\n    @param strLmIp: the Lab Manager IP\n    @type strLmUserName: String\n    @param strLmUserName: the Lab Manager User Account\n    @type strLmPassword: String\n    @param strLmPassword: the Lab Manager User Password\n    @return: the Lab Manager execute result message\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 7, strLmIp, strLmUserName, strLmPassword)\n\n\ndef funcShutdown(intMachineID):\n    \"\"\"\n    Do shutdown\n    @param intMachineID: machine id\n    \"\"\"\n    return funcMachineActionTemplate(intMachineID, 8)\n\n#===============================================================================\n#Machine1 = 10.201.173.211,Ti_STAF_V322,x86,Vista SP2,1931\n#Machine2 = 10.201.173.212,Ti_STAF_XP,x86,XP Professional SP3,1894\n#Machine3 = 10.201.173.213,Ti_STAF_V641,x64,Vista SP1,1996\nif __name__ == '__main__':\n    #funcListConfigurations()\n    #funcGetMachineId('VaHPS264_RU')\n    funcRevert(2624)\n    ##Reset(1894)\n    ##time.sleep(60)\n    ##Revert(1894)\n    ##Reset(1931)\n    ##time.sleep(60)\n    ##Revert(1931)\n    #Reset(2010)\n    #time.sleep(60)\n    #Revert(2010)\n    #Snapshot(1996)\n    #Reset(1996)\n    #time.sleep(60)\n    #Revert(1996)\n    #Snapshot(1996)\n#===============================================================================\n","sub_path":"lib/python/crossPlatform/labManager.py","file_name":"labManager.py","file_ext":"py","file_size_in_byte":9944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"451176274","text":"# -*- coding: utf-8 -*-\n'''\nTools for working with paths and files.\n'''\n\n# Standard library imports\nfrom fnmatch import fnmatch\nimport os\nimport shutil\nimport stat\nimport zipfile\n\n\ndef normalize(*parts):\n    '''Join, expand, and normalize a filepath.'''\n\n    path = os.path.expanduser(os.path.expandvars(os.path.join(*parts)))\n    return os.path.abspath(path).replace('\\\\', '/')\n\n\ndef parent(path):\n    '''Get a file paths parent directory'''\n    return normalize(os.path.dirname(path))\n\n\ndef ensure_path_exists(path, *args):\n    '''Like os.makedirs but keeps quiet if path already exists'''\n\n    if os.path.exists(path):\n        return\n\n    os.makedirs(path, *args)\n\n\ndef rmtree(path):\n    '''Safely remove directory and all of it's contents.'''\n\n    def onerror(func, path, _):\n        os.chmod(path, stat.S_IWRITE)\n        func(path)\n\n    shutil.rmtree(path, onerror=onerror)\n\n\ndef walk_up(start_dir, depth=20):\n    '''Like os.walk but walks up a tree.'''\n\n    root = start_dir\n\n    for i in range(depth):\n        contents = os.listdir(root)\n        subdirs, files = [], []\n        for f in contents:\n            if os.path.isdir(os.path.join(root, f)):\n                subdirs.append(f)\n            else:\n                files.append(f)\n\n        yield root, subdirs, files\n\n        parent = os.path.dirname(root)\n        if parent and not parent == root:\n            root = parent\n        else:\n            break\n\n\ndef touch(filepath):\n    '''Touch the given filepath'''\n\n    with open(filepath, 'a'):\n        os.utime(filepath, None)\n\n\ndef format_size(bytesize):\n    '''Human readable size.'''\n\n    value = bytesize\n    for unit in ['b', 'kb', 'mb', 'gb', 'tb', 'pb', 'zi']:\n        if value < 1024.0:\n            return \"{:.0f} {}\".format(value, unit)\n        value /= 1024.0\n    return \"{:.0f} {}\".format(value, unit)\n\n\ndef get_file_count(folder):\n    '''Get the number of files in a folder.'''\n\n    count = 0\n    for _, _, files in exclusive_walk(folder):\n        count += len(files)\n    return count\n\n\ndef get_folder_size(folder):\n    '''Get the size of a folder in bytes.'''\n\n    size = 0\n    for root, _, files in exclusive_walk(folder):\n        for file in files:\n            file_path = os.path.join(root, file)\n            if not os.path.islink(file_path):\n                size += os.path.getsize(file_path)\n    return size\n\n\ndef is_excluded(value, exclude, exclude_patterns):\n    '''Check if a string value matches exclude values and glob patterns'''\n\n    return (\n        value in exclude\n        or any([fnmatch(value, p) for p in exclude_patterns])\n    )\n\n\ndef exclusive_walk(folder, exclude=None, exclude_patterns=None):\n    '''Like os.walk but exclude files by value or glob pattern.'''\n\n    exclude = exclude or ['__pycache__', '.git', 'thumbs.db', '.venv', 'venv']\n    exclude_patterns = exclude_patterns or ['*.pyc', '*.egg-info']\n\n    for root, subdirs, files in os.walk(folder):\n        if is_excluded(os.path.basename(root), exclude, exclude_patterns):\n            subdirs[:] = []\n            continue\n\n        included = []\n        for file in files:\n            if is_excluded(file, exclude, exclude_patterns):\n                continue\n            included.append(file)\n\n        yield root, subdirs, included\n\n\ndef zip_folder(folder, where):\n    '''Zip the contents of a folder.'''\n\n    parent = os.path.dirname(where)\n    if not os.path.isdir(parent):\n        os.makedirs(parent)\n\n    # TODO: Count files first so we can report progress of building zip.\n\n    with zipfile.ZipFile(where, 'w', zipfile.ZIP_DEFLATED) as zip_file:\n        for root, subdirs, files in exclusive_walk(folder):\n            rel_root = os.path.relpath(root, folder)\n            for file in files:\n                zip_file.write(\n                    os.path.join(root, file),\n                    arcname=os.path.join(rel_root, file)\n                )\n","sub_path":"packages/cpenv/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"27754305","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef ao_simulation_filter(wsn, run, scenario):\n\n    totalPkSentCount = []\n    totalPkReceivedCount = []\n    packetLoss = []\n    consumedPower = []\n    latencyMean = []\n    jitterMean = []\n\n    for i in range(1, 11):\n        packetSentCount = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-2')) & (wsn.type=='scalar') & \n        (wsn.module.str.startswith(\"Sc\"+scenario+\".ss\")) & (wsn.module.str.endswith(\"udp\")) & \n        (wsn.name=='packetSent:count')]   \n\n        packetReceivedCount = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-2'))& (wsn.type=='scalar') & \n        (wsn.module.str.startswith('Sc'+scenario+'.sink')) & \n         (wsn.module.str.endswith(\"udp\")) & (wsn.name=='packetReceived:count')]\n\n        totalPkSentCount.append(sum(packetSentCount.value))\n        totalPkReceivedCount.append(sum(packetReceivedCount.value))\n        packetLoss.append((totalPkSentCount[i-1] - totalPkReceivedCount[i-1]) * 100 / totalPkSentCount[i-1])\n\n\n        residualEnergy = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-2')) & (wsn.type=='scalar') & \n        (wsn.name=='residualEnergyCapacity:last') & \n        (wsn.module.str.endswith('energyStorage'))] \n\n        if(int(scenario) == 1):\n            spentEnergyJ = 3000 - sum(residualEnergy.value)\n        elif(int(scenario) == 2):\n            spentEnergyJ = 9000 - sum(residualEnergy.value)\n        elif(int(scenario) == 3):\n            spentEnergyJ = 15000 - sum(residualEnergy.value)\n            \n        consumedPower.append(spentEnergyJ / 240)\n\n        latency = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-2')) & (wsn.type=='histogram') & \n        (wsn.name=='endToEndDelay:histogram')] \n\n        latencyMean.append(latency[\"mean\"].mean())\n     \n        jitter = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-2')) & (wsn.type=='histogram') & \n        (wsn.name=='jitter:histogram')] \n        \n        jitterMean.append(jitter[\"mean\"].mean())   \n\n    return [totalPkSentCount, totalPkReceivedCount, packetLoss, jitterMean, latencyMean, consumedPower];\n\n\n\ndef ro_simulation_filter(wsn, run, scenario):\n    totalPkSentCountRO = []\n    totalPkReceivedCountRO = []\n    packetLossRO = []\n    consumedPowerRO = []\n    latencyMeanRO = []\n    jitterMeanRO = []\n\n    for i in range(1, 11):\n        packetSentCountRO = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-1')) & (wsn.type=='scalar') & \n        (wsn.module.str.startswith('Sc'+scenario+'.ss')) & (wsn.module.str.endswith(\"udp\")) & \n        (wsn.name=='packetSent:count')]   \n\n        packetReceivedCountRO = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-1'))& (wsn.type=='scalar') & \n        (wsn.module.str.startswith('Sc'+scenario+'.sink')) & \n        (wsn.module.str.endswith(\"udp\")) & (wsn.name=='packetReceived:count')]\n\n        totalPkSentCountRO.append(sum(packetSentCountRO.value))\n        totalPkReceivedCountRO.append(sum(packetReceivedCountRO.value))\n        packetLossRO.append((totalPkSentCountRO[i-1] - totalPkReceivedCountRO[i-1]) * 100 / totalPkSentCountRO[i-1])\n\n        residualEnergyRO = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-1')) & (wsn.type=='scalar') & \n        (wsn.name=='residualEnergyCapacity:last') & \n        (wsn.module.str.endswith('energyStorage'))] \n\n        if(int(scenario) == 1):\n            spentEnergyJRO = 3000 - sum(residualEnergyRO.value)\n        elif(int(scenario) == 2):\n            spentEnergyJRO = 9000 - sum(residualEnergyRO.value)\n        elif(int(scenario) == 3):\n            spentEnergyJRO = 15000 - sum(residualEnergyRO.value)\n        consumedPowerRO.append(spentEnergyJRO / 240)\n\n        latencyRO = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-1')) & (wsn.type=='histogram') & \n        (wsn.name=='endToEndDelay:histogram')] \n\n        latencyMeanRO.append(latencyRO[\"mean\"].mean())\n        \n        jitterRO = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-1')) & (wsn.type=='histogram') & \n        (wsn.name=='jitter:histogram')] \n        \n        jitterMeanRO.append(jitterRO[\"mean\"].mean())\n\n    return [totalPkSentCountRO, totalPkReceivedCountRO, packetLossRO, jitterMeanRO, latencyMeanRO, consumedPowerRO];\n\n\ndef flc_simulation_filter(wsn, run, scenario):\n\n    totalPkSentCountFLC = []\n    totalPkReceivedCountFLC = []\n    packetLossFLC = []\n    consumedPowerFLC = []\n    latencyMeanFLC = []\n    jitterMeanFLC = []\n\n    for i in range(1, 11):\n        packetSentCountFLC = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-0')) & (wsn.type=='scalar') & \n        (wsn.module.str.startswith('Sc'+scenario+'.ss')) & \n        (wsn.module.str.endswith(\"udp\")) & (wsn.name=='packetSent:count')] \n\n        packetReceivedCountFLC = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-0'))& (wsn.type=='scalar') & \n        (wsn.module.str.startswith('Sc'+scenario+'.sink')) & \n        (wsn.module.str.endswith(\"udp\")) & (wsn.name=='packetReceived:count')]\n\n        totalPkSentCountFLC.append(sum(packetSentCountFLC.value))\n        totalPkReceivedCountFLC.append(sum(packetReceivedCountFLC.value))\n        packetLossFLC.append((totalPkSentCountFLC[i-1] - totalPkReceivedCountFLC[i-1]) * 100 / totalPkSentCountFLC[i-1])\n\n\n        residualEnergyFLC = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-0')) & (wsn.type=='scalar') & \n        (wsn.name=='residualEnergyCapacity:last') & \n        (wsn.module.str.endswith('energyStorage'))] \n\n        if(int(scenario) == 1):\n            spentEnergyJFLC = 3000 - sum(residualEnergyFLC.value)\n        elif(int(scenario) == 2):\n            spentEnergyJFLC = 9000 - sum(residualEnergyFLC.value)\n        elif(int(scenario) == 3):\n            spentEnergyJFLC = 15000 - sum(residualEnergyFLC.value)\n        consumedPowerFLC.append(spentEnergyJFLC / 240)\n\n        latencyFLC = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-0')) & (wsn.type=='histogram') & \n        (wsn.name=='endToEndDelay:histogram')] \n\n        latencyMeanFLC.append(latencyFLC[\"mean\"].mean())\n\n        jitterFLC = wsn[(wsn.run.str.startswith('wsnSc'+scenario+'T'+str(i)+'-0')) & \n        (wsn.type=='histogram') & (wsn.name=='jitter:histogram')] \n\n        jitterMeanFLC.append(jitterFLC[\"mean\"].mean()) \n\n    return [totalPkSentCountFLC, totalPkReceivedCountFLC, packetLossFLC, jitterMeanFLC, latencyMeanFLC, consumedPowerFLC];\n","sub_path":"OmnetPart/WSN/src/networktopology/results/Filters.py","file_name":"Filters.py","file_ext":"py","file_size_in_byte":6399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"259018797","text":"##9. Kullanıcıdan bir input alan ve bu inputun içindeki\n##büyük ve küçük harf sayılarının veren bir fonksiyon yazınız.\nbuyukharfler=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','W','V','Y','Z','X']\nkucukharfler=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','w','y','z','x']\nbuyuk_harfler=[]\nkucuk_harfler=[]\ndiger=[]\ndef harf_sayisi():\n    kul=input(\"Bir metin giriniz : \")\n    global buyuk_harfler\n    global kucuk_harfler\n    for i in kul:\n        if i in buyukharfler:\n            buyuk_harfler += [str(i)]\n        if i in kucukharfler:\n            kucuk_harfler += [str(i)]\n    print(\"Buyuk harf sayisi : \",len(buyuk_harfler), \"\\n\" ,\"Kucuk harf sayisi : \" ,len(kucuk_harfler),sep=\"\")\nharf_sayisi()                \n \n## global ile fonksiyon icerisindeki degiskenlerin global alanda kullanilmasini sagladik\n","sub_path":"9.odev buyuk-kucuk harf.py","file_name":"9.odev buyuk-kucuk harf.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"198856358","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n\n#   http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nNot an example, just helper functions for the other examples.\n\"\"\"\nimport os\nimport subprocess\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nimport webtraversallibrary as wtl\n\n\ndef start_server() -> str:\n    my_env = os.environ.copy()\n    my_env[\"FLASK_APP\"] = \"tests/site/flask_app.py\"\n    subprocess.Popen(\"python3 -m flask run\".split(), env=my_env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n    return \"http://localhost:5000\"\n\n\ndef parse_cli_args() -> ArgumentParser:\n    \"\"\"\n    Parses CLI flags relevant for examples.\n    \"\"\"\n    parser = ArgumentParser()\n\n    group = parser.add_argument_group(\"Run parameters\")\n    group.add_argument(\"--url\", type=str, default=\"DEFAULT\", help=\"URL to run the workflow on.\")\n    group.add_argument(\n        \"--output\",\n        type=Path,\n        help=\"Where to save the result locally. If save, remember to also add save flag for config.\",\n        default=None,\n    )\n    group.add_argument(\n        \"--windows\",\n        type=str,\n        nargs=\"*\",\n        default=[wtl.Workflow.SINGLE_TAB],\n        help=\"Tab names (comma-separated). Use space separation for multiple windows.\",\n    )\n    group.add_argument(\n        \"--config\",\n        type=str,\n        nargs=\"*\",\n        default=[],\n        required=False,\n        help=\"Names of config files in config/, such as \" '\"iphone_x_mobile\", or key=value pairs.',\n    )\n\n    cli_args = parser.parse_args()\n    cli_args.config.insert(0, \"default\")\n\n    if cli_args.url == \"DEFAULT\":\n        cli_args.url = start_server()\n\n    return cli_args\n","sub_path":"examples/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"366594068","text":"\"\"\"empty message\n\nRevision ID: 61eae234080\nRevises: None\nCreate Date: 2014-02-27 23:50:34.431578\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '61eae234080'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n    ### commands auto generated by Alembic - please adjust! ###\n    op.create_table('location',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('location', sa.String(length=20), nullable=True),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('location')\n    )\n    op.create_table('area',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('area', sa.String(length=20), nullable=True),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('area')\n    )\n    op.create_table('baseline',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('date', sa.Date(), nullable=True),\n    sa.Column('early', sa.Integer(), nullable=True),\n    sa.Column('late', sa.Integer(), nullable=True),\n    sa.PrimaryKeyConstraint('id')\n    )\n    op.create_table('bimlink',\n    sa.Column('revit_id', sa.Integer(), nullable=False),\n    sa.Column('excel_id', sa.String(length=60), nullable=True),\n    sa.PrimaryKeyConstraint('revit_id'),\n    sa.UniqueConstraint('excel_id')\n    )\n    op.create_table('shift',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('shift', sa.String(length=1), nullable=True),\n    sa.Column('start', sa.Integer(), nullable=True),\n    sa.Column('end', sa.Integer(), nullable=True),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('shift')\n    )\n    op.create_table('material',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('material', sa.String(length=20), nullable=True),\n    sa.Column('unit', sa.String(length=20), nullable=True),\n    sa.PrimaryKeyConstraint('id'),\n    sa.UniqueConstraint('material')\n    )\n    op.create_table('report',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('bimimg_filename', sa.String(length=200), nullable=True),\n    sa.Column('siteimg_filename', sa.String(length=200), nullable=True),\n    sa.Column('site_caption', sa.String(length=200), nullable=True),\n    sa.Column('date', sa.Date(), nullable=True),\n    sa.Column('note', sa.String(length=500), nullable=True),\n    sa.Column('summary', sa.String(length=500), nullable=True),\n    sa.PrimaryKeyConstraint('id')\n    )\n    op.create_table('track',\n    sa.Column('id', sa.Integer(), nullable=False),\n    sa.Column('date', sa.Date(), nullable=True),\n    sa.Column('station_start', sa.Float(), nullable=True),\n    sa.Column('station_end', sa.Float(), nullable=True),\n    sa.Column('quantity', sa.Float(), nullable=True),\n    sa.Column('img', sa.String(length=200), nullable=True),\n    sa.Column('caption', sa.String(length=200), nullable=True),\n    sa.Column('area_id', sa.Integer(), nullable=True),\n    sa.Column('location_id', sa.Integer(), nullable=True),\n    sa.Column('shift_id', sa.Integer(), nullable=True),\n    sa.Column('material_id', sa.Integer(), nullable=True),\n    sa.ForeignKeyConstraint(['area_id'], ['area.id'], ),\n    sa.ForeignKeyConstraint(['location_id'], ['location.id'], ),\n    sa.ForeignKeyConstraint(['material_id'], ['material.id'], ),\n    sa.ForeignKeyConstraint(['shift_id'], ['shift.id'], ),\n    sa.PrimaryKeyConstraint('id')\n    )\n    ### end Alembic commands ###\n\n\ndef downgrade():\n    ### commands auto generated by Alembic - please adjust! ###\n    op.drop_table('track')\n    op.drop_table('report')\n    op.drop_table('material')\n    op.drop_table('shift')\n    op.drop_table('bimlink')\n    op.drop_table('baseline')\n    op.drop_table('area')\n    op.drop_table('location')\n    ### end Alembic commands ###\n","sub_path":"migrations/versions/61eae234080_.py","file_name":"61eae234080_.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"484882772","text":"from sentry.conf.server import *\nimport os.path\n\nCONF_ROOT = os.path.dirname(__file__)\n\nDATABASES = {\n    'default': {\n        # You can swap out the engine for MySQL easily by changing this value\n        # to ``django.db.backends.mysql`` or to PostgreSQL with\n        # ``django.db.backends.postgresql_psycopg2``\n        'ENGINE': 'django.db.backends.mysql',\n        'NAME': 'sentry_server',\n        'USER': 'sentry',\n        'PASSWORD': '****',\n        'HOST': '',\n        'PORT': '',\n        'OPTIONS': {\n            'init_command': 'SET storage_engine=INNODB',\n        }\n    }\n}\n\nSENTRY_KEY = '***********'\n\n# Set this to false to require authentication\nSENTRY_PUBLIC = False\n\n# You should configure the absolute URI to Sentry. It will attempt to guess it if you don't\n# but proxies may interfere with this.\n# SENTRY_URL_PREFIX = 'http://sentry.example.com'  # No trailing slash!\nSENTRY_URL_PREFIX = 'http://sentry.sistemas.pdg.com.br'\n\nSENTRY_WEB_HOST = '0.0.0.0'\nSENTRY_WEB_PORT = 9000\nSENTRY_WEB_OPTIONS = {\n    'workers': 3,  # the number of gunicorn workers\n    # 'worker_class': 'gevent',\n}\n\n# Mail server configuration\n\n# For more information check Django's documentation:\n#  https://docs.djangoproject.com/en/1.3/topics/email/?from=olddocs#e-mail-backends\n\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\nEMAIL_HOST = '192.168.4.71'\nEMAIL_HOST_USER = ''  # 'sistemas'\nEMAIL_HOST_PASSWORD = ''  # '***'\nEMAIL_PORT = 25\nEMAIL_USE_TLS = True\nSENTRY_EMAIL_SUBJECT_PREFIX = '[Sentry] '\nimport logging\nSENTRY_MAIL_LEVEL = logging.DEBUG\n\n\nADMINS=()\nSENTRY_ADMINS=('felipe.rafael@pdg.com.br')\nSENTRY_SERVER_EMAIL='sistemas@pdg.com.br'\n\n\nBROKER_HOST = \"127.0.0.1\"\nBROKER_PORT = 5672\nBROKER_VHOST = \"sentry\"\nBROKER_USER = \"sentry\"\nBROKER_PASSWORD = \"****\"\n\nSENTRY_USE_QUEUE = (\n    'sentry.tasks.cleanup.cleanup',\n    'sentry.tasks.post_process.post_process_group',\n    'sentry.tasks.process_buffer.process_incr',\n)\n\nSENTRY_BUFFER = 'sentry.buffer.base.Buffer'\nSENTRY_BUFFER_OPTIONS = {\n    'hosts': {\n        0: {\n            'host': 'localhost',\n            'port': 6379\n        }\n    }\n}\n\nCACHES = {\n    'default': {\n        'BACKEND': 'django_pylibmc.memcached.CacheClass',\n        'LOCATION': '127.0.0.1:11211'\n    }\n}\nSENTRY_CACHE_BACKEND = 'default'\n\nDEBUG=True\n\n\nLOGGING = {\n    'version': 1,\n    'disable_existing_loggers': True,\n    'root': {\n        'level': 'DEBUG',\n        'handlers': ['sentry'],\n    },\n    'handlers': {\n        'sentry': {\n            'level': 'DEBUG',\n            'class': 'raven.contrib.django.handlers.SentryHandler',\n        },\n        'mail_admins': {\n            'level': 'DEBUG',\n            'class': 'django.utils.log.AdminEmailHandler',\n        }\n    },\n    'loggers': {\n        'django.request': {\n            'handlers': ['mail_admins'],\n            'level': 'DEBUG',\n            'propagate': True,\n        },\n    }\n}\n","sub_path":"dockerized-gists/3975990/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"545731210","text":"irc = None\r\n\r\n# simple google lookup\r\n\r\nimport urllib2\r\nfrom urllib import quote_plus\r\nimport re\r\nimport lxml.html\r\n\r\ndef init(bot):\r\n    global irc\r\n    irc = bot\r\n    bot.cmd.events['PRIVMSG'].subscribe(handle_privmsg)\r\n\r\ndef handle_privmsg(sender, args):\r\n    global irc\r\n\r\n    target = args[2]\r\n\r\n    argv = args[0].split(' ')\r\n\r\n    if not argv:\r\n        return\r\n    \r\n    if len(argv[0]) == 0 or argv[0].isspace():\r\n        return\r\n\r\n    if argv[0] == \"!google\":\r\n        if len(argv) > 1:\r\n            _, query = args[0].split(None, 1)\r\n            query = quote_plus(query)\r\n            my_url = \"http://www.google.com/search?q=%s&btnI=\" % (query)\r\n\r\n            try:\r\n                opener = urllib2.build_opener()\r\n                opener.addheaders = [('User-agent', 'Mozilla/5.0')]\r\n                page = opener.open(my_url)\r\n                page_url = page.geturl()\r\n                p = lxml.html.parse(page)\r\n                title = p.find(\".//title\").text\r\n                clean_title = title.encode('ascii', 'ignore')\r\n            \r\n                irc.privmsg(args[2], \"%s - %s\" % (clean_title, page_url))\r\n            except:\r\n                irc.privmsg(args[2], \"Failed\")\r\n    pass\r\n","sub_path":"plugin/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"29970528","text":"import sys\nimport os\nimport json\nfrom textblob import TextBlob\nimport pandas as pd\nfrom candidate_dictionary import candidates\nfrom handle_file_dict import handle_dict\n\ndef get_text(tweet):\n\ttext = tweet.get('text', [])\n\treturn text\n\ndef text_extract(file_name):\n\troot = \"timelines/older_timelines/\"\n\tpath = os.path.join(root + file_name)\n\tprint(path)\n\twith open(path, 'r') as f:\n\t\ttweet_text = []\n\t\tfor line in f:\n\t\t\ttweet = json.loads(line)\n\t\t\ttext = get_text(tweet)\n\t\t\ttweet_text.append(text)\n\treturn tweet_text\n\nif __name__ == \"__main__\":\n\tfile_name = \"user_timeline_sensanders.json\"\n\tmeow = text_extract(file_name)\n\tprint(meow[0])\n\tprint('finished')","sub_path":"original_files/file_check.py","file_name":"file_check.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"397788324","text":"from django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView, CreateView, DetailView\nfrom .models import Author, Category, Post\n\nclass PostListView(ListView):\n\tmodel = Post\n\tpaginate_by = 5\n\ttemplate_name = 'blog/post_list.html'\n\n\tdef get_queryset(self):\n\t\tqueryset = Post.objects.order_by(\"-creation_date\")\n\t\treturn queryset\n\nclass PostDetailView(DetailView):\n\tmodel = Post\n\t","sub_path":"deploytest/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"627151543","text":"from stdlib.__stdlib import *\nfrom stdlib._setup import isetup\nfrom stdlib.checksum import bank_card,id_card,org_code,czbank_ac\nfrom stdlib.version import get_version,upgrade_version\nfrom stdlib.tz_util import now,utc,Local,dt_tz\n__all__=['read_file','write_file','join','Linux','decode',\n        'smart_copy','leap_year','end_of_month',\n        'year_frac','first_of_month',\n        'date_add','delta','read_shell','write_shell',\n        'exec_shell','wlen','parse_args','encrypt',\n        'decrypt','ensure_path','tmpfile',\n        'bank_card','id_card','org_code','get_pinyin',\n        'get_version','upgrade_version','is_installed',\n        'logger','is_test','POSIX','WINDOWS','abspath',\n        'utctime','localtime','now','utc','Local','dt_tz',\n        'fileext','czbank_ac'\n        ]\n","sub_path":"stdlib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"410339481","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov  5 12:18:10 2020\n\n\"\"\"\nimport gdal\nimport os\nimport numpy as np\nimport re\nimport time\n\ndef absoluteFilePaths(directory, ext = 'tif'): \n   result = []\n   for dirpath,_,filenames in os.walk(directory):\n       for f in filenames:\n           if f.endswith(ext):\n               result.append(os.path.abspath(os.path.join(dirpath, f)))\n   return result\n\ndef get_all_values(filePaths):\n    \n    ds = gdal.Open(filePaths[0])\n    band = ds.GetRasterBand(1)\n    array = band.ReadAsArray()\n\n    results = [[[] for x in range(len(array[1]))] for y in range(len(array))]\n\n    for filename in filePaths:\n        \n        ds = gdal.Open(filename)\n        band = ds.GetRasterBand(1)\n        array = band.ReadAsArray()\n        \n        for i in range(len(array)):\n            for j in range(len(array[i])):\n                results[i][j].append(array[i][j])\n    \n    return results\n\n##############################################################################\n##                                M A I N                                   ##\n##############################################################################\n\nOPERA_path = '/thesis/data_analysis/opera/3tiff_p_d/2015'\nDWD_path = '/thesis/data_analysis/dwd/7alignOPERA/2015'\n#DWD_path = '/thesis/data_analysis/dwd/6alignIMERG/2015'\n#OPERA_path = '/thesis/data_analysis/imerg/4dail/2015/precipitationCal'\n\nfilePaths_OPERA = absoluteFilePaths(OPERA_path)\nfilePaths_DWD = absoluteFilePaths(DWD_path)\n\nshared_DWD = []\n\nfor filename in filePaths_OPERA:\n    \n    date_string = re.search('RATE_[\\d]{8}', filename).group()[5:]\n    #date_string = re.search('MERG.[\\d]{8}', filename).group()[5:]\n    date_time = time.strptime(date_string, '%Y%m%d')\n\n    for filename_DWD in filePaths_DWD:\n        \n        if date_string in filename_DWD:\n            \n            shared_DWD.append(filename_DWD)\n\nfilePaths_OPERA = sorted(filePaths_OPERA)\nfilePaths_DWD = sorted(shared_DWD)\n\nall_OPERA_values = get_all_values(filePaths_OPERA)\nall_DWD_values = get_all_values(filePaths_DWD)\n\ncleaned_pairs = [[[] for x in range(len(all_OPERA_values[1]))] for y in range(len(all_OPERA_values))]\n\nfor i in range(len(all_OPERA_values)):\n    for j in range(len(all_OPERA_values[i])):\n\n        cleaned_list_DWD = []\n        cleaned_list_OPERA = []        \n\n        for k in range(len(all_OPERA_values[i][j])):\n            \n            if all_DWD_values[i][j][k] != -9999000 and all_OPERA_values[i][j][k] != -9999000:    \n                cleaned_pairs[i][j].append((all_DWD_values[i][j][k], all_OPERA_values[i][j][k]))\n\ncorrelations = [[-9999000 for x in range(len(all_OPERA_values[1]))] for y in range(len(all_OPERA_values))]\n\nfor i in range(len(correlations)):\n    for j in range(len(correlations[i])):\n\n        if len(cleaned_pairs[i][j]) >= 10:\n\n            DWD_values = [DWD_value for DWD_value, OPERA_value in cleaned_pairs[i][j]] \n            OPERA_values = [OPERA_value for DWD_value, OPERA_value in cleaned_pairs[i][j]] \n\n            correlations[i][j] = np.corrcoef(DWD_values, OPERA_values)[0][1]\n\nds = gdal.Open(filePaths_DWD[0])\ncorr_array = np.array(correlations)\n\n#save\noutput_fn = '/thesis/data_analysis/correlation/correlation_OPERA_yearly.tif'\ndriver = gdal.GetDriverByName('GTiff')\ndst_ds = driver.CreateCopy(output_fn, ds)\n\ndst_band = dst_ds.GetRasterBand(1)\ndst_band.WriteArray(corr_array) # mx.filled() to prevent weird nodata stuff and smash the mask onto the data\ndst_band.ComputeStatistics(True)\n\nds.FlushCache()\ndst_ds.FlushCache()\n","sub_path":"scripts/opera/OPERA_map.py","file_name":"OPERA_map.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"29329404","text":"import os\nfrom gym_idsgame.config.runner_mode import RunnerMode\nfrom gym_idsgame.agents.dao.agent_type import AgentType\nfrom gym_idsgame.config.client_config import ClientConfig\nfrom gym_idsgame.agents.training_agents.policy_gradient.pg_agent_config import PolicyGradientAgentConfig\nfrom gym_idsgame.runnner import Runner\nfrom experiments.util import util\nfrom gym_idsgame.agents.training_agents.common.opponent_pool_config import OpponentPoolConfig\n\ndef default_output_dir() -> str:\n    \"\"\"\n    :return: the default output dir\n    \"\"\"\n    script_dir = os.path.dirname(__file__)\n    return script_dir\n\n\ndef default_config_path() -> str:\n    \"\"\"\n    :return: the default path to configuration file\n    \"\"\"\n    config_path = os.path.join(default_output_dir(), './config.json')\n    return config_path\n\n\ndef default_config() -> ClientConfig:\n    \"\"\"\n    :return: Default configuration for the experiment\n    \"\"\"\n    env_name = \"idsgame-v19\"\n    opponent_pool_config = OpponentPoolConfig(pool_maxsize=100000,\n                                              pool_increment_period=50,\n                                              head_to_head_period=1,\n                                              quality_scores=True,\n                                              quality_score_eta=0.01,\n                                              initial_quality=1000,\n                                              pool_prob=0.5)\n    pg_agent_config = PolicyGradientAgentConfig(gamma=1, alpha_attacker=0.00001, epsilon=1, render=False,\n                                                alpha_defender=0.0001,\n                                                eval_sleep=0.9,\n                                                min_epsilon=0.01, eval_episodes=100, train_log_frequency=1,\n                                                epsilon_decay=0.9999, video=True, eval_log_frequency=1,\n                                                video_fps=5, video_dir=default_output_dir() + \"/results/videos\",\n                                                num_episodes=100000000,\n                                                eval_render=False, gifs=True,\n                                                gif_dir=default_output_dir() + \"/results/gifs\",\n                                                eval_frequency=100000, attacker=True, defender=False,\n                                                video_frequency=101,\n                                                save_dir=default_output_dir() + \"/results/data\",\n                                                checkpoint_freq=5000,\n                                                input_dim_attacker=(4 + 2) * 2,\n                                                output_dim_attacker=(4+1) * 2,\n                                                input_dim_defender=(4 + 2) * 3,\n                                                output_dim_defender=5 * 3,\n                                                hidden_dim=64,\n                                                num_hidden_layers=4, batch_size=2000,\n                                                gpu=False, tensorboard=True,\n                                                tensorboard_dir=default_output_dir() + \"/results/tensorboard\",\n                                                optimizer=\"Adam\", lr_exp_decay=False, lr_decay_rate=0.999,\n                                                state_length=1, normalize_features=False, merged_ad_features=True,\n                                                zero_mean_features=False, gpu_id=0, lstm_network=False,\n                                                lstm_seq_length=4, num_lstm_layers=2, optimization_iterations=10,\n                                                eps_clip=0.2, max_gradient_norm=0.5, gae_lambda=0.95,\n                                                cnn_feature_extractor=False, features_dim=512,\n                                                flatten_feature_planes=False,\n                                                attacker_load_path=\"/home/kim/storage/workspace/gym-idsgame/experiments/manual_play/v19/minimal_defense/manual_vs_openai_ppo/v4/1591164917.874881_attacker_policy_network.zip\",\n                                                ar_policy=True, attacker_node_input_dim=((4 + 2) * 4),\n                                                attacker_at_net_input_dim=(4 + 2), attacker_at_net_output_dim=(4 + 1),\n                                                attacker_node_net_output_dim=4\n                                                )\n    client_config = ClientConfig(env_name=env_name, attacker_type=AgentType.PPO_OPENAI_AGENT.value,\n                                 mode=RunnerMode.MANUAL_DEFENDER.value, output_dir=default_output_dir(),\n                                 title=\"OpenAI PPO vs ManualDefender\", pg_agent_config=pg_agent_config,\n                                 bot_attacker=True)\n    return client_config\n\n\ndef write_default_config(path:str = None) -> None:\n    \"\"\"\n    Writes the default configuration to a json file\n\n    :param path: the path to write the configuration to\n    :return: None\n    \"\"\"\n    if path is None:\n        path = default_config_path()\n    config = default_config()\n    util.write_config_file(config, path)\n\n\n# Program entrypoint\nif __name__ == '__main__':\n    args = util.parse_args(default_config_path())\n    if args.configpath is not None:\n        if not os.path.exists(args.configpath):\n            write_default_config()\n        config = util.read_config(args.configpath)\n    else:\n        config = default_config()\n    util.create_artefact_dirs(config.output_dir, 0)\n    Runner.run(config)\n\n\n\n","sub_path":"experiments/manual_play/v19/minimal_defense/manual_vs_openai_ppo/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"74531198","text":"import sys\nimport os\nimport dlib\nimport glob\nimport cv2\nfrom PIL import Image\nimport time\n##from multiprocessing import Process, Lock\nfrom multiprocessing import Pool\n\n\npredictor_path = \"./shape_predictor_68_face_landmarks.dat\"\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(predictor_path)\n\n\n##win = dlib.image_window()\n\n\ndef landmarkGenerate(f):\n    try:\n        print(\"Processing file: {}\".format(f))\n        img = dlib.load_rgb_image(f)\n\n        ##    win.clear_overlay()\n        ##    win.set_image(img)\n\n        # Ask the detector to find the bounding boxes of each face. The 1 in the\n        # second argument indicates that we should upsample the image 1 time. This\n        # will make everything bigger and allow us to detect more faces.\n        dets = detector(img, 1)\n        print(\"Number of faces detected: {}\".format(len(dets)))\n        for k, d in enumerate(dets):\n            # print(enumerate(dets.indexof(k,d))\n            print(\"Detection {}: Left: {} Top: {} Right: {} Bottom: {}\".format(\n                k, d.left(), d.top(), d.right(), d.bottom()))\n            # Get the landmarks/parts for the face in box d.\n            shape = predictor(img, d)\n\n            print(\"Part 0: {}, Part 1: {} ...\".format(shape.part(0),\n                                                      shape.part(1)))\n            # print(\"shape \"+str(shape))\n\n            ##        lock.acquire()\n\n            im = Image.open(f)\n            width, height = im.size\n\n            file = open(f + \".txt\", \"w\")\n            for s in range(68):\n                if int(shape.part(s).x) < 0:\n                    file.write(0)\n                elif int(shape.part(s).x) > width:\n                    file.write(width)\n                else:\n                    file.write(str(shape.part(s).x))\n                file.write(\",\")\n                if int(shape.part(s).y) < 0:\n                    file.write(0)\n                elif int(shape.part(s).y) > height:\n                    file.write(height)\n                else:\n                    file.write(str(shape.part(s).y))\n\n                file.write(\"\\n\")\n\n            # width, height = cv2.GetSize(img)\n\n            # print(\"image.width \"+str(width))\n            # print(\"image.height \"+str(height))\n    ##                file.write(\"0,0\\n\")\n    ##                file.write(str(int(width/2))+\",0\\n\")\n    ##                file.write(str(width-1)+\",0\\n\")\n    ##                file.write(\"0,\"+str(int(height/2))+\"\\n\")\n    ##                file.write(str(width-1)+\",\"+str(int(height/2))+\"\\n\")\n    ##                file.write(\"0,\"+str(height-1)+\"\\n\")\n    ##                file.write(str(int(width/2))+\",\"+str(height-1)+\"\\n\")\n    ##                file.write(str(width-1)+\",\"+str(height-1)+\"\\n\")\n\n    ##        lock.release()\n\n    # Draw the face landmarks on the screen.\n    ##        win.add_overlay(shape)\n\n    ##    win.add_overlay(dets)\n    ##    time.sleep(2)\n    # dlib.hit_enter_to_continue()\n    except:\n        pass\n\n\nif __name__ == '__main__':\n    folder='C:\\\\Users\\\\cscwhui\\\\Desktop\\\\python\\\\computed\\\\ProposalEnhanced\\\\morphedImageWithoutCorner'\n    ##    lock = Lock()\n    i = os.listdir(folder)\n    print(i)\n    for j in i:\n        p = Pool()\n        p.map_async(landmarkGenerate,(glob.glob(os.path.join(folder+\"\\\\\"+j, \"*.jpg\"))))\n        # p.map_async(landmarkGenerate, (glob.glob(os.path.join(faces_folder_path, \"*.jpg\"))))\n        p.close()\n        p.join()\n##    for f in glob.glob(os.path.join(faces_folder_path, \"*.jpg\")):\n##        Process(target=landmarkGenerate,args=(lock,f)).start()\n\n\n","sub_path":"landmarkFolder.py","file_name":"landmarkFolder.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"185995170","text":"import threading\nimport queue\nimport time\nimport logging\nimport random\nimport sys\nimport os\n\n\nread_file = 'C:/temp/temp1/simplified.txt'\nlog1 = open('C:/temp/temp1/simplified_log1.txt', \"a+\")\n\nlogging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',)\n\nBUF_SIZE = 10\nq = queue.Queue(BUF_SIZE)\n\nclass ProducerThread(threading.Thread):\n    def __init__(self, name):\n        super(ProducerThread,self).__init__()\n        self.name = name\n\n    def run(self):\n        with open(read_file, 'r') as f:\n            for line in f:\n                stripped = line.strip('\\n\\r')\n                value1,value2,value3,value4,value5 = stripped.split(',')\n                float_value1 = float(value1)\n                if not q.full():\n                    q.put(float_value1)\n                    logging.debug('Putting ' + str(float_value1) + ' : ' + str(q.qsize()) + ' items in queue')\n                    time.sleep(random.random())\n        return\n\nclass ConsumerThread(threading.Thread):\n    def __init__(self, name):\n        super(ConsumerThread,self).__init__()\n        self.name = name\n        return\n\n    def run(self):\n        while not q.empty():\n            float_value1 = q.get()\n            sqr_value1 = float_value1 * float_value1\n            log1.write(\"The square of \" + str(float_value1) + \" is \" + str(sqr_value1))\n            logging.debug('Getting ' + str(float_value1) + ' : ' + str(q.qsize()) + ' items in queue')\n            time.sleep(random.random())\n        return\n\nif __name__ == '__main__':\n\n    p = ProducerThread(name='producer')\n    c = ConsumerThread(name='consumer')\n\n    p.start()\n    time.sleep(2)\n    c.start()\n    time.sleep(2)\n\n    # https://stackoverflow.com/questions/54489332/python-multithreading-producer-consumer-pattern\n","sub_path":"python/threads/python-multithreading-producer-consumer-pattern.py","file_name":"python-multithreading-producer-consumer-pattern.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"132542263","text":"import itertools as it\nimport logging\nimport sys\nimport copy\nfrom qiskit.chemistry import FermionicOperator\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\ndef quicksortL(arr):\n    #quick sort just for arrays\n    if len(arr) <= 1:\n        return arr\n    pivot = arr[len(arr) // 2]\n    left = [x for x in arr if x < pivot ]\n    middle = [x for x in arr if x == pivot]\n    right = [x for x in arr if pivot < x]\n    return quicksortL(left) + middle + quicksortL(right)\n\ndef order(b):\n    count = 0\n    ideal = np.array(quicksortL(b))\n    temp = b\n    \n    DoOrder = True\n    \n    while DoOrder==True:\n        if np.array_equal(ideal,np.array(temp))==True:\n            DoOrder = False\n\n        for i in range(len(temp)-1):\n            if temp[i]>temp[i+1]:\n                tmp = temp[i]\n                temp[i] = temp[i+1]\n                temp[i+1] = tmp\n                count +=1\n                break\n    return count\n\nclass term:\n    coef = None\n    oper = [] \n    stat = None\n    \n    def __init__(self,c=0,o=[],s=None):\n        self.coef = c\n        self.oper = o\n        if(s=='fermi'): self.stat = -1\n        else:           self.stat =  1\n\n    def Print(self,message=''):\n        s=message+' '+str(self.coef)+' * '\n        for op in self.oper:\n            if len(op)==2:\n                s+=op[0]+'('+op[1]+')'\n            elif len(op)==3:\n                s+=op[0]+'('+op[1]+op[2]+')'\n            else:\n                s+='ErrorOp'\n        print(s)\n\n    def Copy(self):\n        Y = term()\n        Y.coef    = self.coef\n        Y.oper    = [ok for ok in self.oper]\n        Y.stat    = self.stat\n        return Y        \n        \n    def Ordered(self):\n        #Check if the term is Totally ordered\n        expr  = [x[0] for x in self.oper]\n        coefC  = [x[1] for x in self.oper if x[0]=='C']\n        coefD  = [x[1] for x in self.oper if x[0]=='D']\n        coefI  = [x[1] for x in self.oper if x[0]=='I']\n        idenOD = [x[1]<=x[2] for x in self.oper if x[0]=='I']\n        if (quicksortL(expr)==expr)and(quicksortL(coefC)==coefC)and(quicksortL(coefD)==coefD)and(quicksortL(coefI)==coefI)and(np.array(idenOD).all()==True):\n            return True\n        else:\n            return False\n    \n    def CDIndexList(self):\n        #gives a list of indicies for adag and a operators\n        ls = ''\n        for x in self.oper:\n            if (x[0]=='C')or(x[0]=='D'):\n                ls +=x[1]\n        return ls\n    def Normal_Ordered(self):\n        expr = [x[0] for x in self.oper if (x[0]=='C')or(x[0]=='D')]\n        if (quicksortL(expr)==expr):\n            return True\n        else:\n            return False\n    \n    def IntOrder(self):\n        Y = self.Copy()\n        if (self.Normal_Ordered()==True)and(self.Ordered()==False):\n\n            listC = [x[1] for x in self.oper if x[0]=='C']\n            listD = [x[1] for x in self.oper if x[0]=='D']\n            listI = [quicksortL([x[1],x[2]]) for x in self.oper if x[0]=='I']\n            powerC = order(listC)\n            listC  = quicksortL(listC)\n\n            powerD = order(listD)\n            listD  = quicksortL(listD)\n            \n            listI1 = [x[0] for x in listI]\n            listI2 = quicksortL(listI1)\n            listIden = []\n            for x in listI2:\n                listIden.append('I'+x+listI[listI1.index(x)][1])\n    \n            listCD = []\n            for x in listC:\n                listCD.append('C'+x)\n            for x in listD:\n                listCD.append('D'+x)\n            Y.coef *=(Y.stat)**(powerC+powerD)\n            Y.oper = listCD+listIden\n            return Y.IntOrder()\n        else:\n            return Y\n    def Power(self):\n        coefC  = [x[1] for x in self.oper if x[0]=='C']        \n        return len(coefC)\n    def IdenTail(self):\n        Y = self.Copy()\n        listCD = [x for x in self.oper if (x[0]=='C')or(x[0]=='D')]\n        listId = [x for x in self.oper if x[0]=='I']\n        Y.oper = listCD+listId\n        return Y\n    def OpertoStr(self):\n        res= ''\n        for x in self.oper:\n            res +=x\n        return res\n    \n    def Product(self,O2,s):\n        Y = term()\n        Y.coef = self.coef*O2.coef*s\n        Y.oper = self.oper+O2.oper\n        Y.stat = self.stat\n        return Y\n    \nclass term_list:\n\n    nop = 0\n    eta = []\n\n    def __init__(self,lst=[]):\n        self.eta = lst\n        self.nop = len(lst)\n        \n    def Remove_Zeros(self):\n        self.nop = len(self.eta)\n        idx      = [ i for i in range(self.nop) if self.eta[i].coef==0 ]\n        for i in idx[::-1]:\n            del self.eta[i]\n        self.nop = len(self.eta)\n    def Print(self):\n        print(\"operator number \",self.nop)\n        for x in self.eta:\n            x.Print()\n    def CDSimplify(self):\n        self.Remove_Zeros()\n        Done = (np.array([f.Normal_Ordered() for f in self.eta]).all()==True)\n        if Done==True:\n            return self\n        elif Done==False:\n            for i in range(self.nop):\n                if self.eta[i].Normal_Ordered()==False:\n                    x = self.eta[i].IdenTail()\n                    for ind in range(len(x.oper)-1):\n                        if (x.oper[ind][0]=='D')and(x.oper[ind+1][0]=='C'):\n                            y  = x.Copy()\n                            o1 = x.oper[ind]\n                            o2 = x.oper[ind+1]\n                            x.oper[ind]   = o2\n                            x.oper[ind+1] = o1\n                            x.coef *= x.stat\n                        \n                            y.oper.pop(ind+1)\n                            y.oper.pop(ind)\n                            y.oper.append('I'+o1[1]+o2[1])\n                            break\n                    self.eta[i] = x\n                    self.eta.append(y)\n                    self.nop = len(self.eta)\n                    break\n            return self.CDSimplify()\n        \n    def Simplify(self):\n        #adag-a ordering\n        self.CDSimplify()\n        #internal ordering\n        for i in range(self.nop):\n            self.eta[i] = self.eta[i].IntOrder()\n        #coef simplification\n        OperLstSet = set([x.OpertoStr() for x in self.eta])\n        if len(OperLstSet)c; all a,b,c should be terms    \n    ina = a.CDIndexList()\n    inb = b.CDIndexList()\n    out = c.CDIndexList()\n    listIden = [x for x in c.oper if x[0]=='I']\n    for x in listIden:\n        ina = ina.replace(x[2],x[1])\n        inb = inb.replace(x[2],x[1])        \n    #rl = ina+','+inb+'->'+out\n    #coef = c.coef\n    #powr = c.Power()\n    return rules(c.coef,ina+','+inb+'->'+out,c.Power())\n\ndef ComRules(o1,o2):\n    #input: 2 terms; output : list of class-rule objects for np.einsum\n    res= []\n    l1   = term_list([o1])\n    l2   = term_list([o2])\n    lout = l1.Commutator(l2)\n    for ind in range(lout.nop):\n        res.append(make_rule(o1,o2,lout.eta[ind]))\n    return res\n\ndef toPhys(h):\n    #convert h-matrix from chemistry notations to physics one\n    #now working only for 1 & 2 body terms\n    if len(h.shape)==2:\n        return h\n    elif len(h.shape)==4:\n        return np.einsum('ijkm->ikmj', h)\n    else:\n        return h\n\ndef toChem(h):\n    #convert h-matrix from physics notations to chemistry one\n    # now working only for 1 & 2 body terms\n    if len(h.shape)==2:\n        return h\n    elif len(h.shape)==4:\n        return np.einsum('ikmj->ijkm', h)\n    else:\n        return h\n\ndef hComPhys(ha,hb, stat = 'fermi', threshold=1e-12):\n    #function which calculates commutator of two h-matricies\n    res = []\n    #latin alphabet for set of indicies\n    alfa = 'abcdefghijklmnopqrstuvwxyz'\n    # need to create two class-term  objects for each h-matrix\n    dim_a = len(ha.shape)\n    dim_b = len(hb.shape)\n    \n    oper_a = []\n    oper_b = []\n    \n    for x in range(dim_a//2):\n        oper_a.append('C'+alfa[0])\n        alfa = alfa[1:]\n    for x in range(dim_a//2):\n        oper_a.append('D'+alfa[0])\n        alfa = alfa[1:]\n    for x in range(dim_b//2):\n        oper_b.append('C'+alfa[0])\n        alfa = alfa[1:]\n    for x in range(dim_b//2):\n        oper_b.append('D'+alfa[0])\n        alfa = alfa[1:]\n        \n    term_a = term(1,oper_a,stat)\n    term_b = term(1,oper_b,stat)\n    \n    CR = ComRules(term_a,term_b)\n    \n    PowList = set([x.power for x in CR])\n    \n    #-------------------#    \n    for PW in PowList:\n        #create empty tensor\n        nferm = ha.shape[0]\n        dim   = 2*PW\n        cur   = np.zeros(np.full(dim,nferm))\n        for x in CR:\n            if x.power==PW:\n                cur +=x.coef*np.einsum(x.rule,ha,hb,optimize=True)\n        if np.abs(cur).max()>threshold:\n            res.append(cur)\n    return res\n\ndef hSimplify(h, stat = 'fermi', threshold=1e-12):\n\n    print(\"I AM IN hSimplify\")\n    print(\"H in \",h.shape)\n    res = np.zeros_like(h)\n    if stat == 'fermi':\n        eta = -1\n    else:\n        eta = +1\n    \n\n    print(\"RES \",res.shape)\n\n    dim = len(h.shape)//2\n    nferm = h.shape[0]\n\n    print(\"I AM TRYING TO LOOP OVER \")\n    print(len(list(it.combinations(np.arange(nferm), dim))))\n    print(\"TWICE\")\n\n    # 1 -- ACCELERATE hSimplify REMOVING FOR LOOPS!\n    \n    for xL in it.combinations(np.arange(nferm), dim):\n        for xR in it.combinations(np.arange(nferm), dim):\n            val = 0\n            for yL in it.permutations(xL):\n                for yR in it.permutations(xR):\n                    coef = eta**(order(np.array(yR))+order(np.array(yL)))\n                    ind = list(yL)+list(yR)\n                    val += coef*h[tuple(ind)]\n            if np.abs(val)>threshold:\n                res[tuple(list(xL)+list(xR))] = val\n    return res\n\ndef mat_list_simplify(lst,nf=0,threshold=1e-12):\n    res = [y for x in lst for y in x]\n    if len(res)==0:\n        return []\n    else:\n        PowList = set([len(x.shape) for x in res])\n        res2 = []\n        for PW in PowList:\n            mt = np.zeros(np.full(PW,nf))\n            for elem in res:\n                if len(elem.shape)==PW:\n                    mt +=elem\n            if np.abs(mt).max()>threshold:\n                res2.append(mt)\n        return res2\n    \ndef ten_commutator(fop_a, fop_b, fop_c=None, stat = 'fermi', Chem=True, threshold=1e-12):\n    # fop_a, fop_b, fop_c - Fermionic Operators\n    # if fop_c ==0 => return = [a,b] ([X,Y]=X*Y-Y*X)\n    # if fop_c !=0 => return = 0.5*([[a,b],c]+[a,[b,c]])\n    \n    ha_list = []\n    if np.all(fop_a.h1)!=0:\n        ha_list.append(fop_a.h1)\n    if np.all(fop_a.h2)!=0:\n        ha_list.append(fop_a.h2)\n    \n    hb_list = []\n    if np.all(fop_b.h1)!=0:\n        hb_list.append(fop_b.h1)\n    if np.all(fop_b.h2)!=0:\n        hb_list.append(fop_b.h2)\n    \n    hc_list = []\n    if fop_c is not None:\n        if np.all(fop_c.h1)!=0:\n            hc_list.append(fop_c.h1)\n        if np.all(fop_c.h2)!=0:\n            hc_list.append(fop_c.h2)\n\n    ha_phys_list = []\n    hb_phys_list = []\n    hc_phys_list = []\n    \n    if Chem==True:\n        for x in ha_list:\n            ha_phys_list.append(toPhys(x))\n        for x in hb_list:\n            hb_phys_list.append(toPhys(x))\n        for x in hc_list:\n            hc_phys_list.append(toPhys(x))\n\n    if len(ha_phys_list)!=0:\n        nf = ha_phys_list[0].shape[0]\n    else:\n        nf = hb_phys_list[0].shape[0]\n            \n    if fop_c is None:\n        #just [A,B]\n        res = []\n        for x in ha_phys_list:\n            for y in hb_phys_list:\n                res.append(hComPhys(x,y, stat, threshold))\n        \n        res = mat_list_simplify(res,nf,threshold)\n        \n        if len(res)==0:\n            #return empty fermionic operator\n            return FermionicOperator(np.zeros((nf,nf)))\n        else:\n            h1out = np.zeros((nf,nf))\n            h2out = np.zeros((nf,nf,nf,nf))\n\n            for x in res:\n                if len(x.shape)==2:\n                    h1out = hSimplify(x, stat, threshold)\n                if len(x.shape)==4:\n                    h2out = hSimplify(x, stat, threshold)\n            if Chem==True:\n                return FermionicOperator(toChem(h1out),toChem(h2out))\n            else:\n                return FermionicOperator(h1out,h2out)                    \n    else:\n        #([[A,B],C]+[A,[B,C]])/2\n        comAB = []\n        for x in ha_phys_list:\n            for y in hb_phys_list:\n                comAB.append(hComPhys(x,y, stat, threshold))\n        comAB = mat_list_simplify(comAB,nf,threshold)\n        if len(comAB)==0:\n            comAB_C = []\n        else:\n            comAB_C = []\n            for x in comAB:\n                for y in hc_phys_list:\n                    comAB_C.append(hComPhys(x,y, stat, threshold))\n        \n        comBC = []\n        for x in hb_phys_list:\n            for y in hc_phys_list:\n                comBC.append(hComPhys(x,y, stat, threshold))\n        comBC = mat_list_simplify(comBC,nf,threshold)\n        if len(comBC)==0:\n            comA_BC = []\n        else:\n            comA_BC = []\n            for x in ha_phys_list:\n                for y in comBC:\n                    comA_BC.append(hComPhys(x,y, stat, threshold))\n        \n        comABC = mat_list_simplify(comAB_C+comA_BC,nf,threshold)\n\n        if len(comABC)==0:\n            #return empty fermionic operator\n            return FermionicOperator(np.zeros((nf,nf)))\n        else:\n            h1out = np.zeros((nf,nf))\n            h2out = np.zeros((nf,nf,nf,nf))\n\n            for x in comABC:\n                if len(x.shape)==2:\n                    h1out = 0.5*hSimplify(x, stat, threshold)\n                if len(x.shape)==4:\n                    h2out = 0.5*hSimplify(x, stat, threshold)\n            if Chem==True:\n                return FermionicOperator(toChem(h1out),toChem(h2out))\n            else:\n                return FermionicOperator(h1out,h2out)\n","sub_path":"TensorAnalyticFermionicCommutator.py","file_name":"TensorAnalyticFermionicCommutator.py","file_ext":"py","file_size_in_byte":14962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"58036555","text":"import os\nimport random\nimport string\nimport numpy as np\n\n###\n# data processing\n###\n\ndef create_dictionary():\n    \"\"\"\n    create char2id, id2char and vocab_size\n    from printable ascii characters.\n    \"\"\"\n    chars = sorted(ch for ch in string.printable if ch not in (\"\\x0b\", \"\\x0c\", \"\\r\"))\n    char2id = dict((ch, i + 1) for i, ch in enumerate(chars))\n    char2id.update({\"\": 0})\n    id2char = dict((char2id[ch], ch) for ch in char2id)\n    vocab_size = len(char2id)\n    return char2id, id2char, vocab_size\n\nCHAR2ID, ID2CHAR, VOCAB_SIZE = create_dictionary()\n\n\ndef encode_text(text, char2id=CHAR2ID):\n    \"\"\"\n    encode text to array of integers with CHAR2ID\n    \"\"\"\n    return np.fromiter((char2id.get(ch, 0) for ch in text), int)\n\n\ndef decode_text(int_array, id2char=ID2CHAR):\n    \"\"\"\n    decode array of integers to text with ID2CHAR\n    \"\"\"\n    return \"\".join((id2char[ch] for ch in int_array))\n\n\ndef one_hot_encode(indices, num_classes):\n    \"\"\"\n    one-hot encoding\n    \"\"\"\n    return np.eye(num_classes)[indices]\n\n# NOTE: there is no rolling in this generator, so RNN states must be\n# reset after each Epoch\ndef io_batch_generator(text_path, max_bytes_in_ram=1000000, batch_size=64, seq_len=64, one_hot_features=False, one_hot_labels=False):\n    \"\"\"\n    batch generator for sequence\n    ensures that batches generated are continuous along axis 1\n    so that hidden states can be kept across batches and epochs\n    \"\"\"\n\n    total_bytes = os.path.getsize(text_path)\n    effective_file_end = total_bytes - total_bytes % max_bytes_in_ram\n    \n    print('total_bytes: {}'.format(total_bytes))\n    print('max_bytes_in_ram: {}'.format(max_bytes_in_ram))\n    print('effective_file_end: {}'.format(effective_file_end))\n\n    with open(text_path, 'r') as file:\n        epoch = 0\n        while True:\n\n            # once we are back at the beginning of the file we have \n            # entered a new epoch. Epoch is also initialized to zero so\n            # that it will be set to one here at the beginning.\n            if file.tell() == 0: \n                epoch += 1\n                print('debug: now in epoch {}'.format(epoch))\n\n            # load max_bytes_in_ram into ram\n            io_batch = file.read(max_bytes_in_ram)\n            print('debug: new io_batch of {} bytes'.format(max_bytes_in_ram))\n            \n            # if we are within max_bytes_in_ram of the effecitive\n            # end of the file, set the file read playhead back to\n            # the beginning, which will increase the epoch next loop\n            if file.tell() + max_bytes_in_ram > effective_file_end:\n                file.seek(0)\n\n            # print('debug: encoding {} bytes of text from io_batch'.format(len(io_batch)))\n            # encode this batch of text\n            encoded = encode_text(io_batch)\n\n            # the number of data batches for this io batch of bytes in RAM\n            num_batches = (len(encoded) - 1) // (batch_size * seq_len)\n            \n            if num_batches == 0:\n                raise ValueError(\"No batches created. Use smaller batch_size or seq_len or larger value for max_bytes_in_ram.\")\n            \n            # print(\"debug: number of batches in io_batch: {}\".format(num_batches))\n            \n            rounded_len = num_batches * batch_size * seq_len\n            # print(\"debug: effective text length in io_batch: {}\".format(rounded_len))\n\n            x = np.reshape(encoded[: rounded_len], [batch_size, num_batches * seq_len])\n            if one_hot_features:\n                x = one_hot_encode(x, VOCAB_SIZE)\n            # print(\"debug: x shape: {}\".format(x.shape))\n\n            y = np.reshape(encoded[1: rounded_len + 1], [batch_size, num_batches * seq_len])\n            if one_hot_labels:\n                y = one_hot_encode(y, VOCAB_SIZE)\n            # print(\"debug: y shape: {}\".format(y.shape))\n\n            x_batches = np.split(x, num_batches, axis=1)\n            y_batches = np.split(y, num_batches, axis=1)\n\n            for batch in range(num_batches):\n                yield x_batches[batch], y_batches[batch], epoch\n            \n            # free the mem\n            del x\n            del y\n            del x_batches\n            del y_batches\n            del encoded\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"543955606","text":"\"\"\"General knowledge about Achaea.\"\"\"\n\np = None\n\ndef init(processor):\n    assert processor is not None\n    global p\n    p = processor\n    \nknown_potions = ['health', 'mana']\nknown_elixirs = ['immunity', 'frost', 'venom', 'speed', 'levitation']\nknown_herbs = ['bayberry', 'bellwort', 'bloodroot', 'cohosh', 'echinacea',\n               'ginger', 'ginseng', 'goldenseal', 'hawthorn', 'irid', 'moss',\n               'kelp', 'kola', 'kuzu', 'slipper', 'lobelia', 'myrrh', 'ash',\n               'pear', 'sileris', 'skullcap', 'elm', 'valerian']\nknown_salves = ['caloric', 'mass', 'epidermal', 'restoration', 'mending']\n\n\nelementalism_elements = ['earth', 'air', 'fire', 'water']\nhealing_elements = ['earth', 'air', 'fire', 'water', 'spirit']\n\n","sub_path":"mudwyrm_users/admin/achaea/scripts/achaea.py","file_name":"achaea.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"560626301","text":"from flask import Flask, request, abort\nimport time\n\nfrom json_handler import Json_handler\n\n\nconfig = Json_handler()\napp = Flask(__name__)\n\n\ndef event(type_:str, user_id:int, **kwargs):\n\tcurrent_time = time.time()\n\te = {\"type\": type_, \"user_id\": user_id, \"time\": current_time}\n\te.update(kwargs)\n\n\treturn e\n\n\n@app.route(\"/\", methods=['POST', 'GET'])\ndef main_page():\n\t\"\"\"\n\t-> JSON {\n\t\t\"key\": int,\n\t}\n\t:return: JSON {\n\t\t\"ok\": bool\n\t}\n\t\"\"\"\n\n\tkey = request.json[\"key\"]\n\n\tif key == \"_scream_\":\n\t\treturn {\"ok\": True}\n\telse:\n\t\treturn {\"ok\": False}\n\n\n@app.route(\"/user.getUsernames\", methods=['GET'])\ndef get_nicknames():\n\t\"\"\"\n\t:return: JSON {\n\t\t\"usernames\": list\n\t}\n\t\"\"\"\n\n\tusernames = []\n\n\tfor user in config.read_field(\"users\"):\n\t\tusernames.append(list(user.values())[0])\n\n\treturn {\"usernames\": usernames}\n\n\n@app.route(\"/user.check\", methods=['POST'])\ndef check_id():\n\t\"\"\"\n\t-> JSON {\n\t\t\"user_id\": int\n\t}\n\t:return: JSON {\n\t\t\"check\": true,\n\t\t\"confirmed\": bool,\n\t\t\"user_id\": int\n\t}\n\t\"\"\"\n\n\tuser_id = request.json[\"user_id\"]\n\n\tif user_id >= 0 and user_id <= config.most_user_id:\n\t\treturn {\"user.check\": True, \"confirmed\": True, \"user_id\": user_id}\n\telse:\n\t\treturn {\"user.check\": True, \"confirmed\": False, \"user_id\": user_id}\n\n\n@app.route(\"/user.getid\", methods=['POST'])\ndef get_id():\n\t\"\"\"\n\t-> JSON {\n\t\t\"nickname\": str,\n\t}\n\t:return: JSON {\n\t\t\"user.getid\": true,\n\t\t\"user_id\": int\n\t}\n\t\"\"\"\n\n\tn = config.most_user_id\n\tnickname = request.json[\"nickname\"]\n\n\tconfig.write_user(n, nickname)\n\n\treturn {\"user.getid\": True, \"user_id\": n}\n\n\n@app.route(\"/messages.send\", methods=['POST'])\ndef send_message():\n\t\"\"\"\n\t-> JSON {\n\t\t\"user_id\": int,\n\t\t\"message\": str,\n\t\t\"color\": str\n\t}\n\t:return: JSON {'ok': true}\n\t\"\"\"\n\n\tr = request.json\n\tuser_id = r[\"user_id\"]\n\tmessage = r[\"message\"]\n\tcolor = r[\"color\"]\n\n\tconfig.write_event(event(type_=\"messages.send\", user_id=user_id, message=message, username=config.read_username(user_id), color=color))\n\n\treturn {\"ok\": True}\n\n\n@app.route(\"/user.connect\", methods=['POST'])\ndef connect():\n\t\"\"\"\n\t-> JSON {\n\t\t\"user_id\": int\n\t}\n\t:return: {'ok': true}\n\t\"\"\"\n\n\tuser_id = request.json[\"user_id\"]\n\tconfig.write_event(event(type_=\"user.connect\", user_id=user_id, username=config.read_username(user_id)))\n\n\treturn {'ok': True}\n\n\n@app.route(\"/user.disconnect\", methods=['POST'])\ndef disconnect():\n\t\"\"\"\n\t-> JSON {\n\t\t\"user_id\": int\n\t}\n\t:return: {'ok': true}\n\t\"\"\"\n\n\tuser_id = request.json[\"user_id\"]\n\tconfig.write_event(event(type_=\"user.disconnect\", user_id=user_id, username=config.read_username(user_id)))\n\n\treturn {'ok': True}\n\n\n@app.route(\"/user.rename\", methods=['POST'])\ndef nick_change():\n\t\"\"\"\n\t-> JSON {\n\t\t\"id\": int,\n\t\t\"nickname\": str\n\t}\n\t:return: JSON {\n\t\t\"ok\": true\n\t}\n\t\"\"\"\n\n\tuser_id = request.json[\"id\"]\n\tnickname = request.json[\"nickname\"]\n\n\tconfig.write_event(\n\t\tevent(\n\t\t\ttype_=\"user.rename\", user_id=user_id,\n\t\t\tconfirmed=True,\n\t\t\told_name=config.read_username(user_id), \n\t\t\tnew_name=nickname))\n\n\tconfig.change_user_nickname(user_id, nickname)\n\n\treturn {\"ok\": True}\n\n\n@app.route(\"/events.get\", methods=['POST'])\ndef get_events():\n\t\"\"\"\n\t-> JSON {\n\t\t\"after\": float\n\t}\n\t:return: JSON {\n\t\t\"events\": [\n\t\t\t{ \"type\": str, \"user_id\": str, \"message\": str, \"time\": float }\n\t\t\t...\n\t\t]\n\t}\n\t\"\"\"\n\n\tafter = request.json[\"after\"]\n\tfiltered_events = [\n\t\tevent for event in config.read_field(\"events\") if event['time'] > after\n\t\t]\n\n\treturn {\n\t\t'events': filtered_events\n\t}\n\n\n@app.route(\"/events.getAll\", methods=['POST', 'GET'])\ndef get_all_events():\n\t\"\"\"\n\t:return: JSON {\n\t\t\"allEvents\": [\n\t\t\t{ \"type\": str, \"user_id\": str, \"message\": str, \"time\": float }\n\t\t\t...\n\t\t]\n\t}\n\t\"\"\"\n\n\treturn {\n\t\t'allEvents': config.read_field(\"events\")\n\t}\n\n\nif __name__ == \"__main__\":\n\tapp.run()\n\tconfig.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"440785561","text":"from __future__ import division\nimport logging\nimport time\nfrom UI_test_utils.UI_test_utils import get_lazyTsb_values\n\nLATENCY_SECONDS_TO_START_TSB = 0.5\nLATENCY_SECONDS_UNTIL_POSITION_INCREMENTING = 2\n\nlogger = logging.getLogger(__name__)\n\n\ndef add_position_incrementing_latency(selenium):\n    tune_started_time = selenium.get_last_keyevent()['time'] / 1000.0\n    tune_completed_time = time.time()\n    start_delay = get_lazyTsb_values(selenium)\n    logger.info(\"Tune initiated {0} tune completed {1} time to tsb start {2}\".format(tune_started_time, tune_completed_time, start_delay))\n    if start_delay > 0:\n        tsb_started_time = tune_completed_time + start_delay + LATENCY_SECONDS_TO_START_TSB\n        if tsb_started_time > tune_completed_time:\n            logger.info(\"Sleeping for %s secs\" % (tsb_started_time - tune_completed_time))  # start TSB takes more than 5 seconds most of the time, adding 5 seconds\n            time.sleep(tsb_started_time - tune_completed_time)\n    # Allow time for system to settle down\n    time.sleep(LATENCY_SECONDS_UNTIL_POSITION_INCREMENTING)\n","sub_path":"Learning/PCT/test_code/engineering_tests/infinitehome/pytest/vgw_tests/stb_tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"211388301","text":"class Responses(object):\n    def __init__(self, pairs=[]):\n        if not isinstance(pairs, list):\n            pairs = list(pairs)\n\n        assert all([isinstance(p, tuple) and len(p) == 2 for p in pairs])\n\n        # self._pairs is a list of tuples, where each tuple is\n        #   (prompt, response, usage count)\n        self._pairs = [(k, v, 0) for k, v in pairs]\n\n    def find_response(self, string):\n        \"\"\"Pick the first valid (prompt is in string) response\n        that has the lowest usage count\n        \"\"\"\n\n        valid_responses = [(k, v, count) for k, v, count in self._pairs\n                           if k in string]\n\n        if not valid_responses:\n            return None\n\n        return min(valid_responses, key=lambda p: p[2])\n\n    def update_response(self, string, response):\n        instance = self.find_response(string)\n        if instance:\n            return (instance[1], instance)\n        else:\n            return (None, response)\n\n    def use(self, instance):\n        self._pairs = [(k, v, count + 1 if (k == instance[0] and\n                                            v == instance[1]) else count)\n                       for k, v, count in self._pairs]\n","sub_path":"pynomator/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"303272920","text":"#!/usr/bin/env python\n\nimport rospy\nimport random\n\nfrom pkg.msg import complex\n\n\npub = rospy.Publisher('topic', complex, queue_size=10)\nrospy.init_node('node1', anonymous=True)\nrate = rospy.Rate(1)\n\nwhile not rospy.is_shutdown():\n    Com_num = complex()\n    Com_num.real = int(10*random.random())\n    Com_num.imaginary = int(10*random.random())\n    rospy.loginfo(Com_num)\n    pub.publish(Com_num)\n    rate.sleep()\n","sub_path":"Day4/tasksWS/src/pkg/scripts/pub_complex.py","file_name":"pub_complex.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"424202773","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n    path('', views.home, name='home'),\n    path('about/', views.about, name='about'),\n    path('snakes/', views.snakes_index, name='index'),\n    path('snakes/', views.snakes_detail, name='detail'),\n    path('snakes/create/', views.SnakeCreate.as_view(), name='snakes_create'),\n    path('snakes//update/', views.SnakeUpdate.as_view(), name='snakes_update'),\n    path('snakes//delete/', views.SnakeDelete.as_view(), name='snakes_delete'),\n    path('snakes//add_feeding/', views.add_feeding, name='add_feeding'),\n    path('snakes//add_photo/', views.add_photo, name='add_photo'),\n    path('snakes//assoc_toy//', views.assoc_toy, name='assoc_toy'),\n    path('toys//delete/', views.ToyDelete.as_view(), name='toys_delete'),\n    path('toys/', views.ToyList.as_view(), name='toys_index'),\n    path('toys//', views.ToyDetail.as_view(), name='toys_detail'),\n    path('toys/create/', views.ToyCreate.as_view(), name='toys_create'),\n    path('toys//update/', views.ToyUpdate.as_view(), name='toys_update'),\n    path('toys//delete/', views.ToyDelete.as_view(), name='toys_delete'),    \n]\n\n","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"169651590","text":"VK_LINK = 'https://vk.com/id'\n\nGOSHA_ID = 184541442\n\nCOMMANDS = {'commandant':    [\"КОМЕНДА\", \"МИЛЕНА\", \"КОМЕНДАНТ\", \"МИЛЕНЫ\", \"КОМЕНДЫ\"],                            # 0\n            'castellan':     [\"БЕЛЬЕ\", \"КАСТЕЛЯНША\", \"МАРГАРИТА\", \"БЕЛЬЯ\"],                                      # 1\n            'gym':           [\"ТРЕНАЖЕРНЫЙ ЗАЛ\", \"СПОРТИВНЫЙ ЗАЛ\", \"СПОРТЗАЛ\", \"ЗАПИСЬ В СПОРТЗАЛ\", \"ЗАЛ\"],      # 2\n            'study_room':    [\"УЧЕБНАЯ КОМНАТА\", \"УЧЕБКА\", \"ЗАПИСЬ В УЧЕБКУ\"],                                   # 3\n            'guests':        [\"ГОСТИ\", \"ГОСТЕЙ\", \"ГОСТЯМИ\"],                                                     # 4\n            'shower':        [\"ДУШ\", \"МЫТЬСЯ\", \"ДУШЕВАЯ\"],                                                       # 5\n            'laundry':       [\"СТИРК\", \"ПРАЧК\", \"ПОСТИРОЧН\", \"СТИРАТЬ\"],                                         # 6\n            'duty':          [\"ДЕЖУРСТВО\", \"УБОРКА\", \"КУХНЯ\"],                                                   # 7\n            'question':      [\"ВОПРОС\", \"СТУДСОВЕТ\", \"ПОДСКАЖИ\"],                                                # 8\n            'greeting':      [\"ПРИВЕТ\", \"ПРИВ\", \"ХАЙ\", \"ШАЛОМ\", \"ЗДАРОВА\", \"ДРАТУТИ\", \"НАЧАТЬ\", \"START\"],        # 9\n            'parting':       [\"ПОКА\", \"ПРОЩАЙ\", \"ГУДБАЙ\", \"ЧМОКИ\", \"ПОКЕДОВА\"],                                  # 10\n            'gratitude':     [\"СПАСИБО\", \"THX\", \"THANKS\", \"THANK YOU\", \"СПАСИБКИ\", \"СПС\"],                       # 11\n            'opportunities': [\"УМЕЕШЬ\", \"ВОЗМОЖНОСТИ\", \"МОЖЕШЬ\", \"ИНФО\", \"ТЫ КТО?\", \"ИНФОРМАЦИЯ\"],               # 12\n            'rude_command':  [\"СУКА\", \"БЛЯТЬ\", \"ПИЗ\", \"ФАК\", \"ХУЙ\", \"ПИДОР\", \"СОСАТЬ\", \"СОСИ\", \"ЖОПА\"],          # 13\n            'invoice':       ['ЧЕК', \"ОПЛАТА\"],                                                                  # 14\n            'topical':       ['АКТУАЛЬНОЕ'],\n            }\n","sub_path":"config/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"417409917","text":"# W H X Y Player\n\n# 20 10 5 0 3\n\nfrom sys import stdin\n'''\n#inputList = map(str, stdin.read().split())\nwhile True:\n    try:\n        lists = input().split()\n    except EOFError:\n        break\n'''\n\n\ndef solution(inputList):\n    # W H X Y Player\n\n    # 20 10 5 0 3\n\n    width = inputList[0]\n    height = inputList[1]\n    xaxis = inputList[2]\n    yaxis = inputList[3]\n    numPlayers = inputList[4]\n\n    def circleCheck(x, y):\n        return 0\n\n    def squareCheck(x, y):\n        #global width\n        #global height\n        if x >= xaxis and x <= (width+xaxis):\n            if y >= yaxis and y <= (yaxis+height):\n                return 1\n        return 0\n    squareCheck(1, 2)\n    # for\n\n\nsolution([20, 10, 5, 0, 3])\n","sub_path":"kakao/1358.py","file_name":"1358.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"570608323","text":"# coding=utf-8\n#\n# Created by junn, on 16/12/16\n#\n\n###########################################################\n# ##                短信与邮件设置\n###########################################################\n\n\n# 短信验证码开关, 测试阶段可设为False\nSMS_CODE_REQUIRED = True\n\nSMS_CONF = {\n    'code_len':     4,          # 短信验证默认长度, 4位数字\n    'code_max_limit': 6,        # 同一手机号当天可请求的短信验证码最大条数\n    'code_err_limit': 5,        # 同一手机号可允许的验证码最大输入错误次数\n    'code_expiry':   10,        # 验证码超时时间, 单位分钟\n}\n\n# 用户与账号相关配置\nLOGIN_AFTER_SIGNUP = False  # 注册后直接登录\n\n# 邮件配置\nFROM_EMAIL_ALIAS = u'NMIS'\nCHANGE_NOTIFICATIONS_MIN_INTERVAL = 300     # seconds\n\n\n# aliyun email setup\nALIYUN_EMAIL = {\n    'api_base_url':     \"http://dm.aliyuncs.com\",\n    'access_key_id':    \"xxxx\",\n    'access_key_secret': 'xxxx'\n}\n\nFROM_EMAIL_LIST = [  # 发件Email列表, 多个以备用\n    'team@{{cookiecutter.project_slug}}.com',\n]\n\nMAIL_FUNC_TYPE = 'async'    # 邮件发送类型: async-异步, sync-同步\n\n# 所��的邮件服务\nEMAIL_SERVICE = 'aliyun'\nFROM_EMAIL_ACCOUNT = FROM_EMAIL_LIST[0] if EMAIL_SERVICE == 'aliyun' else FROM_EMAIL_LIST[1]\n","sub_path":"{{cookiecutter.project_slug}}-back/apps/settings/subs/email_conf.py","file_name":"email_conf.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"283357911","text":"'''\nCreated on Mar 22, 2015\n\n@author: hijungshin\n'''\n\nimport cv2\nimport numpy as np\nimport util\n\ndef label_objs(list_of_objs, list_of_labels):    \n    list_of_imgobjs = list_of_objs + list_of_labels\n    img = util.groupimages(list_of_imgobjs)\n#     util.showimages([img])\n    return img\n\ndef getlabelimg(text):\n    \"\"\"put text in image and return image\"\"\"\n    fontface = cv2.FONT_HERSHEY_COMPLEX\n    fontscale = 0.7\n    thickness = 1\n    fontcolor=(0,0,0)\n    size, baseline = cv2.getTextSize(text, fontface, fontscale, thickness)\n    img = np.ones((size[1]+2*baseline, size[0], 3), dtype=np.uint8)*255\n    cv2.putText(img, text, (0, 2*baseline + size[1]/2), fontface, fontscale, fontcolor, thickness=thickness)\n#     util.showimages([img], text)\n    return img\n    \ndef getlabels(start_i, nlabels):\n    list_of_labels = []\n    for i in range(0, nlabels):\n        ltxt = '(' + chr(ord('a') + start_i+i) + ')'\n        img = getlabelimg(ltxt)\n        label = Label(img, (0,0))\n        list_of_labels.append(label)\n    return list_of_labels\n\n\nclass Label:\n    def __init__(self, img, pos):\n        self.img = img\n        self.pos = pos\n        h, w = img.shape[0:2]\n        self.tlx = pos[0] - w/2\n        self.tly = pos[1] - h/2\n        self.brx = self.tlx + w\n        self.bry = self.tly + h       \n        \n    def changepos(self, pos):\n        self.pos = pos\n        h, w = self.img.shape[0:2]\n        self.tlx = pos[0] - w/2\n        self.tly = pos[1] - h/2\n        self.brx = self.tlx + w\n        self.bry = self.tly + h    ","sub_path":"Scripts/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"442366932","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom uuid import uuid4\n\nclass ProjectTask(models.Model):\n    _inherit = ['project.task']\n\n    task_validated_by_customer = fields.Boolean(string=\"Task Validated By Customer\")\n    \n    project_need_task_validation = fields.Boolean(related=\"project_id.tasks_need_validation\")\n    \n    access_token_for_rfc_validation = fields.Char(string=\"Access Token for RFC Validation\")\n    \n    analysis_time_estimation = fields.Float(string=\"Analysis Time Estimation\")\n    development_time_estimation = fields.Float(string=\"Development Time Estimation\")\n    test_time_estimation = fields.Float(string=\"Test Time Estimation\")\n    release_time_estimation = fields.Float(string=\"Release Time Estimation\")\n    total_time_estimation = fields.Float(string=\"Total Time Estimation\", compute='_compute_total_time_estimation')\n    \n    @api.depends('analysis_time_estimation', 'development_time_estimation', 'test_time_estimation', 'release_time_estimation')\n    def _compute_total_time_estimation(self):\n        for task in self:\n            task.total_time_estimation = task.analysis_time_estimation + task.development_time_estimation + task.test_time_estimation + task.release_time_estimation\n            \n    def action_validate_rfc(self):\n        self.ensure_one()\n        self.write({'task_validated_by_customer': True})\n    \n    @api.multi\n    def action_send_rfc(self):    \n        self.ensure_one()\n        ir_model_data = self.env['ir.model.data']\n        try:\n            template_id = ir_model_data.get_object_reference('project_rfc_validation', 'email_template_rfc_validation')[1]\n        except ValueError:\n            template_id = False\n        try:\n            compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]\n        except ValueError:\n            compose_form_id = False\n        \n        self.access_token_for_rfc_validation = uuid4()\n\n        ctx = {\n            'default_model': 'project.task',\n            'default_res_id': self.ids[0],\n            'default_use_template': bool(template_id),\n            'default_template_id': template_id,\n            'default_composition_mode': 'comment',\n            'access_token': self.access_token_for_rfc_validation\n        }\n\n        return {\n            'name': _('Compose Email'),\n            'type': 'ir.actions.act_window',\n            'view_type': 'form',\n            'view_mode': 'form',\n            'res_model': 'mail.compose.message',\n            'views': [(compose_form_id, 'form')],\n            'view_id': compose_form_id,\n            'target': 'new',\n            'context': ctx,\n        }","sub_path":"project_rfc_validation/models/project_task.py","file_name":"project_task.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"589885063","text":"#!/usr/bin/env python\n# _*_coding:utf-8_*_\n\n\nfrom AppTest.Common import *\n\n\nclass MyTestCase(unittest.TestCase):\n    @classmethod\n    def setUp(self):\n        self.case_name = os.path.basename(__file__)\n        browse = BrowserEngine(self)\n        self.web_driver = browse.open_browser(self, url=WebControlServer.web_url)\n\n    @classmethod\n    def tearDown(self):\n        Common.report_screen_shot(self, self.case_name)\n        Common.del_app_entity_by_name(self, \"%app_name%\")\n        Common.quit(self)\n\n    def test_step(self):\n        u\"\"\"应用列表查询支持模糊查询\"\"\"\n        logger.info(\"web端登录\")\n        Common.login_web_portal(self, Content.register_count, Content.login_password)\n\n        logger.info(\"判断是否登陆成功\")\n        get_login_result = Common.check_if_class_name_exist(self, ClassName.ivu_icon_log_out, \"i\")\n        self.assertTrue(get_login_result)\n\n        logger.info(\"点击应用管理\")\n        Common.touch_text_by_class_name(self, ClassName.ivu_menu_item, \"应用管理\", \"li\")\n\n        logger.info(\"进入应用列表界面\")\n        Common.touch_text_by_class_name(self, ClassName.layout_text, \"应用管理\", \"span\")\n        Common.touch_text_by_class_name(self, ClassName.layout_text, \"应用列表\", \"span\")\n\n        logger.info(\"点击添加应用\")\n        Common.touch_text_by_class_name(self, ClassName.ivu_btn_primary, \"添加应用\", \"button\")\n\n        logger.info(\"上传图片\")\n        Common.upload_file(self, ClassName.ivu_upload_input, \"icon\", \"icon.jpg\")\n\n        logger.info(\"输入应用名称\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"请输入应用名称\", \"app_name\")\n\n        logger.info(\"选择行业所属\")\n        Common.touch_by_class_name_and_palceholder(self, ClassName.ivu_select_input, \"请选择所属行业\")\n        result = Common.get_element_by_class_name_and_text(self, \"div\", ClassName.ivu_form_item_required, \"选择所属行业\")\n        item = Common.get_class_name_elements_by_element_blank(self, result, \"li\", ClassName.ivu_select_item)\n        Common.touch_by_element(self, item[0])\n\n        logger.info(\"选择付费方式-免费\")\n        Common.touch_text_by_class_name(self, ClassName.ivu_radio_wrapper_group_item, \"免费开通\", \"label\")\n\n        logger.info(\"输入产品负责人\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"请输入产品负责人\", \"zhangsen\")\n\n        logger.info(\"输入产品负责人联系方式\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"请输入负责人联系方式\", \"12345678901\")\n\n        logger.info(\"选择应用开发商\")\n        Common.touch_by_class_name_and_palceholder(self, ClassName.ivu_select_input, \"请选择应用开发商\")\n        result = Common.get_element_by_class_name_and_text(self, \"div\", ClassName.ivu_form_item_required, \"应用开发商\")\n        item = Common.get_class_name_elements_by_element_blank(self, result, \"li\", ClassName.ivu_select_item)\n        Common.touch_by_element(self, item[0])\n\n        logger.info(\"输入应用连接\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"请输入应用链接\", \"http://www.baidu.com\")\n\n        logger.info(\"输入应用连接详情\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"请输入应用详情链接\", \"http://www.baidu.com\")\n\n        logger.info(\"点击保存\")\n        Common.touch_text_by_class_name(self, ClassName.ivu_btn_primary, \"提交审核\", \"button\")\n\n        logger.info(\"通过搜索检测是否创建成功\")\n        Common.send_text_by_class_name_and_palceholder(self, ClassName.ivu_input, \"输入应用名称、ISV名称进行搜索\", \"p_nam\")\n        Common.touch_search_by_placeholder(self, \"输入应用名称、ISV名称进行搜索\")\n        search_result = Common.get_results_by_class_name_blank(self, \"tr\", ClassName.ivu_table_row)\n        self.assertEqual(len(search_result), 1)\n\n\n","sub_path":"AppTest/testCase/Sprint3/case_Sprint3_portal_0039.py","file_name":"case_Sprint3_portal_0039.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"322913508","text":"def get_input():\n    for i in range(0,20):\n        grades.append(input('Enter the grade of student {}: '.format(i+1)))\n    return grades\n\ndef occurrences(grades, letters):\n    _output = [0,0,0,0,0,0]\n    for grade in grades:\n        for letter in letters:\n            if letter == grade:\n                _output[letters.index(letter)] += 1\n    return _output\n\ndef display(_output, letters):\n    for i in range(0,len(_output)):\n        print('{}\\'s: {}'.format(letters[i], _output[i])) \n\ngrades = []\nletters = ['A','B','C','D','E','F']\ndisplay(occurrences(get_input(), letters),letters)\n","sub_path":"schoolwork/higher/grades_count_occurrence.py","file_name":"grades_count_occurrence.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"329938737","text":"from django.shortcuts import render, get_list_or_404, get_object_or_404\nfrom django.core.urlresolvers import reverse_lazy\nfrom shop.views import summ_in_cart, get_query\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.template import loader\nfrom shop.models import Client, Product, Category, Cart, CartElement, Order, Photo\nimport datetime\nfrom django.http import QueryDict\nfrom django.contrib.auth.decorators import login_required\n\n\n# @login_required(login_url='/accounts/login/')\ndef menu(request, cat=\"0\"):\n    template = loader.get_template('bshop/in_catalog.html')\n    for_cat_menu = Category.objects.all()\n    name_ = ''\n    for_content = {}\n\n    for i in for_cat_menu:\n        # str = i.get_absolute_url()\n        if int(cat) == int(i.id):\n            name_ = i.name\n            for_content = Product.objects.filter(product__category=i.id)\n    if not name_:\n        return HttpResponseRedirect(reverse_lazy('index'))\n\n    if request.method == 'GET':\n        params_ = request.GET\n        p = QueryDict('')\n        if params_:\n            p = params_.copy()\n        if 'q' in p:\n            # print(\"Search\", request.GET['q'])\n            query_string = p.get('q')\n            entry_query = get_query(query_string, ['product__name', 'product__description', ])\n            for_content = for_content.filter(entry_query)\n            query_string = 'Результат поиска - ' + str(p.get('q'))\n        else:\n            query_string = name_\n\n        f_ispreorder = p.get('ispreorder')\n        if f_ispreorder == 'True' or f_ispreorder == 'False':\n            for_content = for_content.filter(is_preorder=f_ispreorder)\n\n        if 'sort' in p:\n            sort_ = p.get('sort')\n            if sort_ == 'PRICEUP':\n                for_content = for_content.order_by('cost')\n            if sort_ == 'PRICEDOWN':\n                for_content = for_content.order_by('-cost')\n            if sort_ == 'AVIALABLE':\n                for_content = for_content.order_by('is_preorder')\n\n    if not request.user.is_authenticated():\n        if 'key' not in request.session:\n            request.session['last_date'] = str(datetime.datetime.now())\n            request.session.save()\n            request.session['key'] = request.session.session_key\n        for_cart = CartElement.objects.filter(cart__key=request.session['key'], cart__status=True)\n    else:\n        for_cart = CartElement.objects.filter(cart__owner__user__username=request.user.username, cart__status=True)\n    l = len(for_cart)\n    category_ = get_object_or_404(Category, id=cat)\n    photos_ = get_list_or_404(Photo, product_in_time__category=category_.id, is_alpha=True)[0:4]\n\n    # photos_ = Photo.objects.all()[0:4]\n    context = {'menu': for_cat_menu, 'path': request.path, 'content': for_content, 'name': name_, 'catalog_id': cat,\n               'session': request.session, 'cart_length': l, 'summ_in_cart': summ_in_cart(for_cart),\n               'query_string': query_string,'photos': photos_, 'p': p, 'sort': Product.by_sort}\n    return HttpResponse(template.render(context, request))","sub_path":"shop/views_/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"641625630","text":"import os\nos.chdir('python')\n\nclass Athlete:\n    def __init__(self, a_name, a_dob=None, a_times=[]):\n        self.name = a_name\n        self.dob = a_dob\n        self.times = a_times\n\n    def top3(self):\n        return(sorted(set([sanitize(t) for t in self.times]))[0:3])\n\n    def add_time(self, time_value):\n        self.times.append(time_value)\n\n    def add_times(self, list_of_times):\n        self.times.extend(list_of_times)\n\ndef sanitize(time_string):\n    if '_' in time_string:\n        splitter = '_'\n    elif ':' in time_string:\n        splitter = ':'\n    elif '-' in time_string:\n        splitter = '-'\n    else:\n        return(time_string)\n\n    (mins, sec) = time_string.split(splitter)\n    return(mins+ ':' +sec)\n\ndef get_coach_data(filename):\n    try:\n        with open(filename) as f:                   #step1:打开文件\n            data = f.readline()                     #step2:读出文件\n        templ=data.strip().split(',')               #step3:分割文件\n        return(Athlete(templ.pop(0),templ.pop(0),templ))\n    \n    except IOError as ioerr:\n        print('File error:' + str(ioerr))\n        return(None)\n\nsarah = get_coach_data('sarah2.txt')\nsarah.add_time('1.2')\nprint(sarah.name+\"'s fastest times are\" + str(sarah.top3()))\n","sub_path":"headfirstpython/150509/150509test2.py","file_name":"150509test2.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"481564778","text":"# -*- coding: utf-8 -*-\nfrom module import pool_parallel as po\nfrom module import argorism as arg\nimport time\n\n# 100000\npool_time = time.time()\nmax_num = 100\nresult = po.pool_pal(arg.coin, 4, max_num)\nend_pool_time = time.time() - pool_time\nnum0 = result.count(0)\nprobability = num0 / max_num * 100\n\n#po.pool_pal(ras.dice, 4, 10)\n\ntime_no = time.time()\ncoin_num = []\nfor i in range(max_num):\n    coin_num.append(arg.coin(i))\nend_time = time.time() - time_no\n\nprint (\"並列化あり(pool):{0}\".format(end_pool_time) + \"[sec]\")\nprint (\"並列化なし:{0}\".format(end_time) + \"[sec]\")\nprint(\"表が出る確率:{0}\".format(probability))","sub_path":"code/main_sample.py","file_name":"main_sample.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"604105078","text":"# Primeiro devemos testar se o numero é primo\n# Caso ele não for devemos pegar o proximo numero primo depois dele\n# Se ele for, retornamos ele mesmo\n\ndef primo(x):\n    primo = True\n    aux = x\n    cont = 2\n    while primo and cont <= aux:\n        if cont != aux and aux % cont == 0:\n            primo = False\n        else:\n          cont += 1\n          primo = True\n    return primo\n\ndef maior_primo(x):\n\n    while not primo(x):\n        x = x + 1\n    return x\n\n\nnumero = int(input('Digite um Numero: '))\n\nif primo(numero):\n    print(numero)\nelse:\n    print(maior_primo(numero))\n","sub_path":"Semana 5/maior_numero_primo.py","file_name":"maior_numero_primo.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"568281132","text":"from django.contrib import admin\n\n# Register your models here.\n# vim: set fileencoding=utf-8 :\nfrom django.contrib import admin\n\nfrom . import models\n\n\nclass SpecialiteAdmin(admin.ModelAdmin):\n\n    list_display = ('id', 'titre', 'statut', 'date_add', 'date_upd')\n    list_filter = (\n        'statut',\n        'date_add',\n    )\n    search_fields = ('titre',)\n\nclass CategorieAdmin(admin.ModelAdmin):\n\n    list_display = ('id', 'titre', 'statut', 'date_add', 'date_upd')\n    list_filter = (\n        'statut',\n        'date_add',\n        'date_upd',\n    )\n    actions = ('active', 'deactive')\n    def active(self, request, queryset):\n        queryset.update(statut=False)\n        self.message_user(request, 'La selection a été deactivé avec succès')\n\n    active.short_description = 'Desactiver'\n\n    def deactive(self, request, queryset):\n        queryset.update(statut=True)\n        self.message_user(request, 'La selection a été activé avec succès')\n\n    deactive.short_description = 'Activer'\n    \nclass MenuAdmin(admin.ModelAdmin):\n\n    list_display = (\n        'id',\n        'jour',\n        'position',\n        'statut',\n        'date_add',\n        'date_upd',\n    )\n    list_filter = (\n        'statut',\n        'date_add',\n        'date_upd',\n    )\n\n\nclass PlatAdmin(admin.ModelAdmin):\n\n    list_display = (\n        'id',\n        'specialite',\n        'categorie',\n        'titre',\n        'prix',\n        'ingredient',\n        'image_menu',\n        'image_special',\n        'statut',\n    )\n    list_filter = (\n        'specialite',\n        'categorie',\n        'statut',\n        'date_add',\n        'date_upd',\n    )\n    search_fields = ('titre',)\n    #date_hierarchy = ('date_add',)\n    filter_horizontal = ('menu',)\n\ndef _register(model, admin_class):\n    admin.site.register(model, admin_class)\n\n\n_register(models.Specialite, SpecialiteAdmin)\n_register(models.Categorie, CategorieAdmin)\n_register(models.Menu, MenuAdmin)\n_register(models.Plat, PlatAdmin)\n","sub_path":"apirestio/myappi/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"232720481","text":"import urllib.request\nfrom knock60 import load_vectors\nfrom pprint import pprint\nfrom tqdm import tqdm\n    \ndef download_file():\n    url = \"http://download.tensorflow.org/data/questions-words.txt\"\n    urllib.request.urlretrieve(url, f\"data/questions-words.txt\")\n    \ndef knock64():\n    download_file()\n    progress_bar = tqdm(total = 19558)\n    word_vectors = load_vectors()\n    with open(\"data/questions-words.txt\", \"r\") as f1,\\\n         open(\"data/result_knock64.txt\", \"w\") as f2:\n        for line in f1:\n            progress_bar.update(1)\n            line = line.strip()\n            words = line.split(\" \")\n            if len(words) != 4:\n                f2.write(f\"{line}\\n\")\n                continue\n            sim_word = word_vectors.most_similar(positive = [words[1], words[2]], negative = [words[0]], topn = 1)[0]\n            f2.write(f\"{line} {sim_word[0]} {sim_word[1]}\\n\")\n    \nif __name__ == \"__main__\":\n    knock64()","sub_path":"kazuma/chapter07/knock64.py","file_name":"knock64.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"644537399","text":"import numpy as np\n# Setting the random seed, feel free to change it and see different solutions.\nnp.random.seed(42)\n\ndef stepFunction(t):\n    if t >= 0:\n        return 1\n    return 0\n\ndef prediction(X, W, b):\n    return stepFunction((np.matmul(X,W)+b)[0])\n\n# The code below implements the perceptron trick.\n# The function receives as inputs the data X (X[i][0],X[i][1]), the labels y,\n# the weights W (as an array), and the bias b.\n# We update the weights and bias W, b, according to the perceptron algorithm,\n# and return W and b.\ndef perceptronStep(X, y, W, b, learn_rate = 0.01):\n    for i in range(len(X)):\n        # y_hat = step(w1*x1+w2*x2+b)\n        y_hat = prediction(X[i],W,b)\n        # If the point is classified positive(y_hat), but it has a negative label(y[i]), \n        # subtract α*x[i][0],α*x[i][1], and α to w_1, w_2 and b respectively.\n        if y[i]==0 and y_hat==1:\n            W[0] -= X[i][0]*learn_rate\n            W[1] -= X[i][1]*learn_rate\n            b -= learn_rate\n        # If the point is classified negative(y_hat), but it has a positive label(y[i]), \n        # add α*x[i][0],α*x[i][1], and α to w_1, w_2 and b respectively.\n        elif y[i]==1 and y_hat==0:\n            W[0] += X[i][0]*learn_rate\n            W[1] += X[i][1]*learn_rate\n            b += learn_rate\n    return W, b\n    \n# This function runs the perceptron algorithm repeatedly on the dataset,\n# and returns a few of the boundary lines obtained in the iterations,\n# for plotting purposes.\n# Applying the learning rule to each example in a dataset is called an epoch. If we have a small number of epochs in your training, it would be poor and you would realize the effects of underfitting. \n# On the other hand, if we train the network too much, it would 'memorize' the desired outputs for the training inputs (supposing a supervised learning).\ndef trainPerceptronAlgorithm(X, y, learn_rate = 0.01, num_epochs = 30):\n    x_min, x_max = min(X.T[0]), max(X.T[0])\n    y_min, y_max = min(X.T[1]), max(X.T[1])\n    W = np.array(np.random.rand(2,1))\n    b = np.random.rand(1)[0] + x_max\n    # These are the solution lines that get plotted below.\n    boundary_lines = []\n    for i in range(num_epochs):\n        # In each epoch, we apply the perceptron step.\n        W, b = perceptronStep(X, y, W, b, learn_rate)\n        boundary_lines.append((-W[0]/W[1], -b/W[1]))\n    return boundary_lines\n","sub_path":"Lesson_2_Introduction_to_Neural_Networks/10. Perceptron Algorithm/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"482932829","text":"# Bithumb에서 코인 이름과 가격 가져오기\n\nimport bs4\nimport requests\n\na = requests.get(\"https://www.bithumb.com/\").text\ndoc = bs4.BeautifulSoup(a, 'html.parser')\n\nresult = doc.select('.coin_list tr td p a strong')\nresult2 = doc.select('.sort_real')\n\nfor i in range(len(result)):\n    print(result[i].text + result2[i].text)","sub_path":"day2/bithumb.py","file_name":"bithumb.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"514447297","text":"import sys\nimport torch\nimport numpy as np\nfrom torchvision.models import vgg16, resnet50\nfrom model.region_proposal_network import RegionProposalNetwork\nfrom model.faster_rcnn import FasterRCNN\nfrom model.roi_module import RoIPooling2D\nfrom roi_align.functions.roi_align import RoIAlignFunction\nfrom utils.config import opt\nfrom utils import array_tool\nfrom torch.nn import functional\nfrom model.fpn import FPN\n\ndef decom_vgg16():\n    model = vgg16(not opt.load_path)\n\n    C2 = list(model.features)[:16]\n    C3 = list(model.features)[16:23]\n    C4 = list(model.features)[23:30]\n\n    classifier = model.classifier  \n    classifier = list(classifier)\n    del classifier[6] \n    if not opt.use_dropout:\n        del classifier[5]\n        del classifier[2]\n    classifier = torch.nn.Sequential(*classifier)\n\n    return torch.nn.Sequential(*C2), torch.nn.Sequential(*C3), torch.nn.Sequential(*C4), classifier\n\n\nclass FasterRCNNVGG16FPN(FasterRCNN):\n\n    def __init__(self,\n                 n_fg_class= opt.class_num,\n                 ratios=[0.5, 1, 2],\n                 anchor_scales=[8, 16],\n                 feat_stride=[4, 8, 16, 32]):\n        C2, C3, C4, classifier = decom_vgg16()\n\n        fpn = FPN(\n            out_channels=512\n        )\n\n        rpn = RegionProposalNetwork(\n            512, 512,\n            ratios=ratios,\n            anchor_scales=anchor_scales,\n            feat_stride=feat_stride,\n        )\n\n        head = VGG16RoIHead(\n            n_class=n_fg_class + 1,\n            roi_size=7,\n            feat_stride=[4, 8, 16, 32],\n            classifier=classifier,\n        )\n\n        super(FasterRCNNVGG16FPN, self).__init__(\n            C2, C3, C4,\n            fpn,\n            rpn,\n            head,\n        )\n\nclass VGG16RoIHead(torch.nn.Module):\n    def __init__(self, n_class, roi_size, feat_stride, classifier):\n        super(VGG16RoIHead, self).__init__()\n\n        self.classifier = classifier\n        self.cls_loc = torch.nn.Linear(4096, n_class * 4)\n        self.score = torch.nn.Linear(4096, n_class)\n        normal_init(self.cls_loc, 0, 0.01)\n        normal_init(self.score, 0, 0.01)\n\n        self.n_class = n_class\n        self.roi_size = roi_size\n        self.feat_stride = feat_stride\n        self.spatial_scale = [1. / i for i in feat_stride]\n\n    def forward(self, features_maps, rois, roi_indices):\n        roi_indices = array_tool.totensor(roi_indices).float()\n        rois = array_tool.totensor(rois).float()\n        roi_level = self._PyramidRoI_Feat(rois)\n        indices_and_rois = torch.cat([roi_indices[:, None], rois], dim=1)\n        xy_indices_and_rois = indices_and_rois[:, [0, 2, 1, 4, 3]]  \n        indices_and_rois = xy_indices_and_rois.contiguous()  \n\n        roi_pool_feats = []\n        roi_to_levels = []\n\n        for i, l in enumerate(range(2, 5)):\n            if (roi_level == l).sum() == 0:\n                continue\n            idx_l = (roi_level == l).nonzero()\n            roi_to_levels.append(idx_l)\n\n            keep_indices_and_rois = indices_and_rois[idx_l]\n            keep_indices_and_rois = keep_indices_and_rois.view(-1, 5)\n            #roi_pooling = RoIPooling2D(self.roi_size, self.roi_size, self.spatial_scale[i])\n            roi_align = RoIAlignFunction(self.roi_size, self.roi_size, self.spatial_scale[i])\n            #pool = roi_pooling(features_maps[i], keep_indices_and_rois)   #通过roi_pooling\n            pool = roi_align(features_maps[i], keep_indices_and_rois)\n            roi_pool_feats.append(pool)\n        roi_pool_feats = torch.cat(roi_pool_feats, 0)\n        roi_to_levels = torch.cat(roi_to_levels, 0)\n        roi_to_levels = roi_to_levels.squeeze()\n        idx_sorted, order = torch.sort(roi_to_levels)\n        roi_pool_feats = roi_pool_feats[order]\n\n        pool = roi_pool_feats.view(roi_pool_feats.size(0), -1)\n\n        fc7 = self.classifier(pool)\n        roi_cls_locs = self.cls_loc(fc7) \n        roi_scores = self.score(fc7) \n\n        return roi_cls_locs, roi_scores\n\n    def _PyramidRoI_Feat(self, rois):\n        roi_h = rois[:, 2] - rois[:, 0] + 1\n        roi_w = rois[:, 3] - rois[:, 1] + 1\n        roi_level = torch.log(torch.sqrt(roi_h*roi_w)/224.0) /np.log(2)\n        roi_level = torch.round(roi_level + 4)\n        roi_level[roi_level < 2] = 2\n        roi_level[roi_level > 4] = 4\n        return roi_level\n\n\ndef normal_init(m, mean, stddev, truncated=False):\n    if truncated:\n        m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) \n    else:\n        m.weight.data.normal_(mean, stddev)  \n        m.bias.data.zero_()\n\ndef weights_init(m, mean, stddev, truncated=False):\n    classname = m.__class__.__name__\n    if classname.find('Conv') != -1:\n        m.weight.data.normal_(0.0, 0.02)\n        m.bias.data.fill_(0)\n    elif classname.find('BatchNorm') != -1:\n        m.weight.data.normal_(1.0, 0.02)\n        m.bias.data.fill_(0)\n\n\n\n","sub_path":"rcnn/simple-faster-rcnn-pytorch/model/faster_rcnn_vgg16_fpn.py","file_name":"faster_rcnn_vgg16_fpn.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"368553792","text":"from collections import Counter\ntext='''The Zen of Python, by Tim Peters\nBeautiful is better than ugly.\n Explicit is better than implicit.\n Simple is better than complex.\n Complex is better than complicated.\n Flat is better than nested.\n Sparse is better than dense.\n Readability counts.\n Special cases aren't special enough to break the rules.\n Although practicality beats purity.\n Errors should never pass silently.\n Unless explicitly silenced.\n In the face of ambxiguity, refuse the temptation to guess.\n There should be one-- and preferably only one --obvious way to do it.\n Although that way may not be obvious at first unless you're Dutch.\n Now is better than never.\n Although never is often better than *right* now.\n If the implementation is hard to explain, it's a bad idea.\n If the implementation is easy to explain, it may be a good idea.\n Namespaces are one honking great idea -- let's do more ofte'''\n\ndef stats_text_en(text,count):\n    if not isinstance(text, str):\n        raise ValueError('参数应当为str类型')\n    a=text.split()\n    symbols='。,;--*'\n    words=[]\n    for a1 in a:\n        for symbol in symbols:\n            b=a1.replace(symbol,'')\n            words.append(b)\n    return Counter(words).most_common(count)\n\n\n        \n\ntext2='''函数的执行会引入一个用于函数局部变量的新符号表。\n更确切地说,函数中所有��变量赋值都将存储在局部符号表中;而变量引用会首先在局部符号表中查找,\n然后是外层函数的局部符号表,最后是内置名称表。\n因此,全局变量和外层函数的变量不能在函数内部直接赋值.'''\ndef stats_text_cn(text,count):\n    if not isinstance(text, str):\n        raise ValueError('参数应当为str类型')\n    CN=[]\n    for CN1 in text2:\n        if '\\u4e00'<=CN1<='\\u9ffff':\n            CN.append(CN1)\n    return Counter(CN).most_common(count)\n\ndef stats_text(text,count):\n    if not isinstance(text,str):\n        raise ValueError('参数必须为str类型')\n    return stats_text_cn(text,count) + stats_text_en(text,count)","sub_path":"exercises/1901110001/d09/mymodule/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"263769376","text":"class Solution(object):\n    def missingNumber(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        max_nums = max(nums)\n        nums = list(sorted(nums))\n        list_nums = [i for i in range(max_nums+1)]\n        print(list_nums, nums)\n        for i in range(min(len(nums), len(nums))):\n            if nums[i] != list_nums[i]:\n                return list_nums[i]\n        return max_nums + 1","sub_path":"Solutions/Q268_missing_number.py","file_name":"Q268_missing_number.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"43614977","text":"##############################################################################\n\n#  SHADOW REMOVAL WITH SUBREGION MATCHING AND ILLUMINATION TRANSFER\n\n#  DONE BY:\n#  BHARATH KUMAR \n#  CHOCKALINGAM\n#  DC VIVEK \n#  HARINATH GOBI\n\n##############################################################################\n\nimport cv2\nimport numpy as np\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport sys\nfrom skimage import segmentation\nimport torch.nn.init\nimport scipy\n\nuse_cuda = torch.cuda.is_available()\n\n############################# SEGMENTATION VARIABLES #########################\n\nnChannel = 100\nmaxIter = 100\nminLabels = 3\nlr = 0.1\nnConv = 2\nnum_superpixels = 10000\ncompactness = 100\nvisualize = 1\ninput_file = 'shadow.jpg'\n\n##############################################################################\n\nimg = cv2.imread(input_file)\nshadow_removed_img = cv2.imread(input_file)\ngray = cv2.imread(input_file, 0)\nblur = cv2.bilateralFilter(img,9,75,75)\n\n#############################    HSI CONVERSION    ###########################\n\nblur = np.divide(blur, 255.0)\n\nhsi = np.zeros((blur.shape[0],blur.shape[1],blur.shape[2]),dtype=np.float)\nratio_map = np.zeros((blur.shape[0],blur.shape[1]),dtype=np.uint8)\n\nfor i in range(blur.shape[0]):\n    for j in range(blur.shape[1]):\n        hsi[i][j][2] = (blur[i][j][0]+blur[i][j][1]+blur[i][j][2])/3\n        hsi[i][j][0] = math.acos(((blur[i][j][2]-blur[i][j][1])*(blur[i][j][2]-blur[i][j][0]))/(2*math.sqrt((blur[i][j][2]-blur[i][j][1])*(blur[i][j][2]-blur[i][j][1])+(blur[i][j][2]-blur[i][j][0])*(blur[i][j][1]-blur[i][j][0]))))\n        hsi[i][j][1] = 1 - 3*min(blur[i][j][0],blur[i][j][1],blur[i][j][2])/hsi[i][j][2]\n        ratio_map[i][j] = hsi[i][j][0]/(hsi[i][j][2]+0.01)                    \n\n###############################################################################\n \n#########################    SHADOW DETECTION   ###############################\n\nhist = np.histogram(ratio_map.ravel(),256,[0,256])\nret,th = cv2.threshold(ratio_map,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\nret,inv_th = cv2.threshold(ratio_map,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\nbin_thresh = cv2.medianBlur(th,15)\nbin_inv_thresh = cv2.medianBlur(inv_th,15)\n\n###############################################################################\n\nshadow_region = cv2.bitwise_and(img,img,mask = th)\nbackground_region = cv2.bitwise_and(img,img,mask = inv_th)\n\n##############################  SEGMENTATION  #################################\n\n# CNN model\nclass MyNet(nn.Module):\n    def __init__(self,input_dim):\n        super(MyNet, self).__init__()\n        self.conv1 = nn.Conv2d(input_dim, nChannel, kernel_size=3, stride=1, padding=1 )\n        self.bn1 = nn.BatchNorm2d(nChannel)\n        self.conv2 = []\n        self.bn2 = []\n        for i in range(nConv-1):\n            self.conv2.append( nn.Conv2d(nChannel, nChannel, kernel_size=3, stride=1, padding=1 ) )\n            self.bn2.append( nn.BatchNorm2d(nChannel) )\n        self.conv3 = nn.Conv2d(nChannel, nChannel, kernel_size=1, stride=1, padding=0 )\n        self.bn3 = nn.BatchNorm2d(nChannel)\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = F.relu( x )\n        x = self.bn1(x)\n        for i in range(nConv-1):\n            x = self.conv2[i](x)\n            x = F.relu( x )\n            x = self.bn2[i](x)\n        x = self.conv3(x)\n        x = self.bn3(x)\n        return x\n\ndef segment(im):\n    data = torch.from_numpy( np.array([im.transpose( (2, 0, 1) ).astype('float32')/255.]) )\n    if use_cuda:\n        data = data.cuda()\n    data = Variable(data)\n\n    # slic\n    labels = segmentation.slic(im, compactness=compactness, n_segments=num_superpixels)\n    labels = labels.reshape(im.shape[0]*im.shape[1])\n    u_labels = np.unique(labels)\n    l_inds = []\n    for i in range(len(u_labels)):\n        l_inds.append( np.where( labels == u_labels[ i ] )[ 0 ] )\n\n    # train\n    model = MyNet( data.size(1) )\n    if use_cuda:\n        model.cuda()\n        for i in range(nConv-1):\n            model.conv2[i].cuda()\n            model.bn2[i].cuda()\n    model.train()\n    loss_fn = torch.nn.CrossEntropyLoss()\n    optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n    label_colours = np.random.randint(255,size=(100,3))\n    for batch_idx in range(maxIter):\n        # forwarding\n        optimizer.zero_grad()\n        output = model( data )[ 0 ]\n        output = output.permute( 1, 2, 0 ).contiguous().view( -1, nChannel )\n        ignore, target = torch.max( output, 1 )\n        im_target = target.data.cpu().numpy()\n        nLabels = len(np.unique(im_target))\n        if visualize:\n            im_target_rgb = np.array([label_colours[ c % 100 ] for c in im_target])\n            im_target_rgb = im_target_rgb.reshape( im.shape ).astype( np.uint8 )\n            cv2.imshow( \"output\", im_target_rgb )\n            cv2.waitKey(1)\n\n        # superpixel refinement\n        for i in range(len(l_inds)):\n            labels_per_sp = im_target[ l_inds[ i ] ]\n            u_labels_per_sp = np.unique( labels_per_sp )\n            hist = np.zeros( len(u_labels_per_sp) )\n            for j in range(len(hist)):\n                hist[ j ] = len( np.where( labels_per_sp == u_labels_per_sp[ j ] )[ 0 ] )\n            im_target[ l_inds[ i ] ] = u_labels_per_sp[ np.argmax( hist ) ]\n        target = torch.from_numpy( im_target )\n        if use_cuda:\n            target = target.cuda()\n        target = Variable( target )\n        loss = loss_fn(output, target)\n        loss.backward()\n        optimizer.step()\n\n        print (batch_idx, '/', maxIter, ':', nLabels, loss.data[0])\n        if nLabels <= minLabels:\n            print (\"nLabels\", nLabels, \"reached minLabels\", minLabels, \".\")\n            break  \n    return im_target_rgb        \n\nshadow_region = segment(shadow_region)\nshadow_region = cv2.bitwise_and(shadow_region,shadow_region,mask = th)\nbackground_region = segment(background_region)\nbackground_region = cv2.bitwise_and(background_region,background_region,mask = inv_th)\n\n###############################################################################\n\n############################  SUBREGION MATCHING  #############################\n\nshadow_region_colors = list(np.unique(shadow_region.reshape(-1, shadow_region.shape[2]), axis=0))\nbackground_region_colors = list(np.unique(background_region.reshape(-1, background_region.shape[2]), axis=0))\n\nshadow_subregions = []\nbackground_subregions = []\n\nfor i in range(len(shadow_region_colors)):\n    shadow_subregions.append([])\n    for x in range(shadow_region.shape[0]):\n        for y in range(shadow_region.shape[1]):\n            if (shadow_region[x][y] == shadow_region_colors[i]).all():\n                shadow_subregions[i].append([x,y])           \n\nfor i in range(len(background_region_colors)):\n    background_subregions.append([])\n    for x in range(background_region.shape[0]):\n        for y in range(background_region.shape[1]):\n            if (background_region[x][y] == background_region_colors[i]).all():\n                background_subregions[i].append([x,y])           \n\nshadow_region_colors.pop(0)\nbackground_region_colors.pop(0)\nshadow_region_colors = np.array(shadow_region_colors)\nbackground_region_colors = np.array(background_region_colors)\n\nshadow_subregions.pop(0)\nbackground_subregions.pop(0)\n\n#print(background_region_colors)\n#print(shadow_region_colors)\n#print(len(shadow_subregions))\n#print(len(shadow_subregions[0]),len(shadow_subregions[1]),len(shadow_subregions[2]))\n\nfeature_vector = []\nkernel_vector = []\nscales = 4\norientation = 6\n\nfor s in range(scales):\n    for o in range(orientation):\n        g_kernel = cv2.getGaborKernel((21, 21), (4.0+s*2), (np.pi*o)/6, 10.0, 0.5, 0, ktype=cv2.CV_32F)\n        filtered_img = cv2.filter2D(gray, cv2.CV_8UC3, g_kernel)\n        kernel_vector.append(g_kernel)\n        feature_vector.append(filtered_img)\n\nshadow_subregion_feature_vector = []\nbackground_subregion_feature_vector = []\n\nshadow_region_coord_mean = []\nbackground_region_coord_mean = []\n\nfeature_vector_mean = [np.mean(vector) for vector in feature_vector]\nfeature_vector_std = [np.std(vector) for vector in feature_vector]\n\niterator = 0\n\nfor vector in feature_vector:\n    shadow_region_coord_mean.append([])\n    shadow_subregion_feature_vector.append([])\n    background_region_coord_mean.append([])\n    background_subregion_feature_vector.append([])\n\n    for region in shadow_subregions:\n        mean = 0\n        std = 0\n        x_mean = 0\n        y_mean = 0\n        for x,y in region:\n            mean = mean + vector[x][y]\n            x_mean = x_mean + x\n            y_mean = y_mean + y\n        mean = mean/(vector.shape[0]*vector.shape[1])    \n        for x,y in region:\n            std = std + abs((vector[x][y]-mean)*(vector[x][y]-mean))   \n        shadow_subregion_feature_vector[iterator].append([mean,math.sqrt(std/(vector.shape[0]*vector.shape[1]))]) \n        shadow_region_coord_mean[iterator].append([x_mean/(len(region)),y_mean/(len(region))])\n        \n    for region in background_subregions:\n        mean = 0\n        std = 0\n        x_mean = 0\n        y_mean = 0\n        for x,y in region:\n            mean = mean + vector[x][y]\n            x_mean = x_mean + x\n            y_mean = y_mean + y\n        mean = mean/(vector.shape[0]*vector.shape[1])    \n        for x,y in region:\n            std = std + abs((vector[x][y]-mean)*(vector[x][y]-mean))    \n        background_subregion_feature_vector[iterator].append([mean,math.sqrt(std/(vector.shape[0]*vector.shape[1]))]) \n        background_region_coord_mean[iterator].append([x_mean/(len(region)),y_mean/(len(region))])\n    iterator = iterator + 1\n\n#print(len(background_subregions),len(shadow_subregions),len(shadow_subregion_feature_vector),len(shadow_region_coord_mean))        \n#print(len(background_region_coord_mean),len(background_subregion_feature_vector),len(background_region_coord_mean[0]),len(background_subregion_feature_vector[0]),len(background_subregion_feature_vector[0][0]),len(background_region_coord_mean[0][0]))\n#print(shadow_region_coord_mean[0],shadow_region_coord_mean[1])\n#print(shadow_subregion_feature_vector[0],shadow_subregion_feature_vector[1],shadow_subregion_feature_vector[2])\n\ndist_texture = []\ndist_space = []\nindex = 0\ndist = 0\ntext = 0\niterator = 0\n_iterator = 0\n\n#for s in range(scales):\n#    for o in range(orientation):\n#        dist_texture.append([])\n#        index = (orientation*s)+o \n#        for shadow_reg in range(len(shadow_subregion_feature_vector[index])):\n#            dist_texture[index].append([])\n#            for background_reg in range(len(background_subregion_feature_vector[index])):\n#                text = text + abs((shadow_subregion_feature_vector[index][shadow_reg][0]-background_subregion_feature_vector[index][shadow_reg][0])/feature_vector_mean[index][0]) + abs((shadow_subregion_feature_vector[index][shadow_reg][1]-background_subregion_feature_vector[index][shadow_reg][1])/feature_vector_mean[index][1])        \n#                dist_texture[index][iterator].append(text)    \n#            iterator = iterator + 1\n\n#print(feature_vector_mean[0],shadow_subregion_feature_vector[0],background_subregion_feature_vector[0])\n\nfor shadow_reg in range(len(shadow_subregion_feature_vector[index])):\n    dist_texture.append({})\n    _iterator = 0\n    for background_reg in range(len(background_subregion_feature_vector[index])):\n        text = 0\n        for s in range(scales):\n            for o in range(orientation):\n                index = (orientation*s)+o\n                text = text + abs((shadow_subregion_feature_vector[index][shadow_reg][0]-background_subregion_feature_vector[index][shadow_reg][0])/feature_vector_mean[index]) + abs((shadow_subregion_feature_vector[index][shadow_reg][1]-background_subregion_feature_vector[index][shadow_reg][1])/feature_vector_mean[index])        \n        dist_texture[iterator][_iterator] = text\n        _iterator = _iterator + 1    \n    iterator = iterator + 1\n\niterator = 0\n_iterator = 0   \n\nfor shadow_reg in range(len(shadow_subregion_feature_vector[index])):\n    dist_space.append({})\n    _iterator = 0\n    for background_reg in range(len(background_subregion_feature_vector[index])):\n        dist = math.sqrt((shadow_region_coord_mean[0][shadow_reg][0]-background_region_coord_mean[0][background_reg][0])*(shadow_region_coord_mean[0][shadow_reg][0]-background_region_coord_mean[0][background_reg][0])+(shadow_region_coord_mean[0][shadow_reg][1]-background_region_coord_mean[0][background_reg][1])*(shadow_region_coord_mean[0][shadow_reg][1]-background_region_coord_mean[0][background_reg][1]))        \n        dist_space[iterator][_iterator] = dist\n        _iterator = _iterator + 1\n    iterator = iterator + 1\n\n#print(dist_texture,dist_space)\n\nfor i in range(len(dist_texture)):\n    dist_texture[i] = sorted(dist_texture[i].items(), key=lambda kv: kv[1])\n    dist_space[i] = sorted(dist_space[i].items(), key=lambda kv: kv[1])\n\nmatch = []\n\nfor i in range(len(dist_texture)):\n    min = len(dist_texture[0])+len(dist_space[0])\n    minimum = 0\n    for j in range(len(dist_texture[0])):\n        for k in range(len(dist_space[0])):\n            if dist_texture[i][j][0] == dist_space[i][k][0]:\n                if j+k < min:\n                    min = j+k\n                    minimum = dist_texture[i][j][0]\n    match.append(minimum)                                                          \n\n#print(match)\n###############################################################################\n\n############################    SHADOW REMOVAL    #############################\n\nluminance = np.zeros((img.shape[0],img.shape[1]))\n#shadow_removed_image = np.zeros((img.shape[0],img.shape[1],img.shape[2]))\n#sigma_shadow = [1]*len(shadow_subregion_feature_vector[0])\n#sigma_background = [1]*len(background_subregion_feature_vector[0])\n\nfor x in range(img.shape[0]):\n    for y in range(img.shape[1]):\n        luminance[x][y] = img[x][y][2]*0.2126 + img[x][y][1]*0.7152 + img[x][y][0]*0.0722\n \niterator_ = 0\n\nshad_reg_mean = []\nback_reg_mean = []\n\nfor region in shadow_subregions:\n    r = 0\n    g = 0\n    b = 0\n    for x,y in region:\n        b = b + img[x][y][0]\n        g = g + img[x][y][1]\n        r = r + img[x][y][2]\n    b = b/len(region)\n    g = g/len(region)\n    r = r/len(region)\n    shad_reg_mean.append([b,g,r])\n        \nfor region in background_subregions:\n    r = 0\n    g = 0\n    b = 0\n    for x,y in region:\n        b = b + img[x][y][0]\n        g = g + img[x][y][1]\n        r = r + img[x][y][2]\n    b = b/len(region)\n    g = g/len(region)\n    r = r/len(region)\n    back_reg_mean.append([b,g,r])\n\nluminance_shad_std = []\nluminance_back_std = []\n\nfor region in shadow_subregions:\n    std = 0\n    mean = 0\n    for x,y in region:\n        mean = mean + luminance[x][y]\n    mean = mean/len(region)\n    for x,y in region:\n        std = std + abs((luminance[x][y]-mean)*(luminance[x][y]-mean))\n    luminance_shad_std.append(math.sqrt(std/len(region)))\n\n\nfor region in background_subregions:\n    std = 0\n    mean = 0\n    for x,y in region:\n        mean = mean + luminance[x][y]\n    mean = mean/len(region)\n    for x,y in region:\n        std = std + abs((luminance[x][y]-mean)*(luminance[x][y]-mean))\n    luminance_back_std.append(math.sqrt(std/len(region)))\n\n#match = [0,1,2]\n_iterator_ = 0\nfor region in shadow_subregions:\n    for x,y in region:\n        shadow_removed_img[x][y][0] = back_reg_mean[match[_iterator_]][0] + (luminance_back_std[match[_iterator_]]/luminance_shad_std[_iterator_])*(img[x][y][0]-shad_reg_mean[_iterator_][0])\n        shadow_removed_img[x][y][1] = back_reg_mean[match[_iterator_]][1] + (luminance_back_std[match[_iterator_]]/luminance_shad_std[_iterator_])*(img[x][y][1]-shad_reg_mean[_iterator_][1])\n        shadow_removed_img[x][y][2] = back_reg_mean[match[_iterator_]][2] + (luminance_back_std[match[_iterator_]]/luminance_shad_std[_iterator_])*(img[x][y][2]-shad_reg_mean[_iterator_][2])\n    _iterator_ = _iterator_ + 1    \n\n#print(luminance_back_std,luminance_shad_std,back_reg_mean,shad_reg_mean)\nprint(match)\n\n###############################################################################\n\ncv2.imshow(\"original_image\",img)\ncv2.imshow(\"detected_shadow\",bin_thresh)\ncv2.imshow(\"shadow_region\",shadow_region)\ncv2.imshow(\"background_region\",background_region)\ncv2.imshow(\"shadow_removed_image\",shadow_removed_img)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows(0)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"469842468","text":"MAX = 999999\n\nT = int(input())\n\nfor tc in range(1, T + 1):\n    N = int(input())\n\n    # 지도를 N보다 사이즈가 1씩 큰 2차원 리스트로 생성한다.\n    maze = [[MAX for i in range(N + 1)] for j in range(N + 1)]\n\n    for i in range(N):\n        # 지도를 한행씩 입력받는다.\n        temp = list(map(int, input().split()))\n        maze[i] = temp\n\n        # 우측 패딩값을 999999로 설정한다.\n        maze[i].append(MAX)\n\n    for i in maze:\n        print(i)\n\n    # 지도를 패딩을 제외하고 가장 우측하단 도착지부터 왼쪽으로 순회한다.\n    for i in range(N - 1, -1, -1):\n        for j in range(N - 1, -1, -1):\n            # 도착지는 스킵한다.\n            if i == N - 1 and j == N - 1:\n                continue\n\n            # 현재 위치에서 오른쪽과 아래를 비교해 더 빠른 경로를 찾는다.\n            # 더 빠른경로의 값을 현재 위치에 더해 갱신한다.\n            # 이렇게 하면 자연스레 모든 리스트의 값은 해당 위치에서 도착지까지의 최단경로값 형성되게 된다.\n            if maze[i][j + 1] < maze[i + 1][j]:\n                maze[i][j] = maze[i][j] + maze[i][j + 1]\n            else:\n                maze[i][j] = maze[i][j] + maze[i + 1][j]\n\n    # 출발지 인덱스의 값을 출력한다.\n","sub_path":"SWEA/tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"478056896","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\ndiciembre 2017\n\n@author: Rafael Ernesto Perez\n\n\"\"\"\n\n#from numpy import loadtxt, zeros, ones, array, linspace, logspace\n#from pylab import scatter, show, title, xlabel, ylabel, plot, contour\nimport numpy as np\nfrom scipy import optimize\nimport math,random,os\n\nclass RedNeuronal(object):\n    def __init__(self):\n        #Definimos los parametros generales\n        self.numeroNeuronasEntrada = 6\n        self.numeroNeuronasSalida = 1\n        self.numeroNeuronasEscondidas1 = 6\n        self.numeroNeuronasEscondidas2 = 6\n        #se definen los pesos de manera aleatoria\n        #los pesos w1 estanentre la capa de entrada y la escondida con randn es posible\n        # generar una matriz de valores aleatorios\n        # entre 0 y 1 de tamao esperado\n        #Primerparametros filas seundo columans\n\n        self.W1 = np.random.randn(self.numeroNeuronasEntrada, self.numeroNeuronasEscondidas1)\n        #Los pesos w2 estan entre la nerona escondida y la de salida\n        self.W2 = np.random.randn(self.numeroNeuronasEscondidas1, self.numeroNeuronasEscondidas2)\n        self.W3 = np.random.randn(self.numeroNeuronasEscondidas2, self.numeroNeuronasSalida)\n\n\n        # X es la matriz de entraada\n        # W es la matriz de pesos\n        # Z sera el resultado de la actividad neuronal(filas como nerornas oculta tenga ycolumas como ...\n    def avanzar(self,x):\n        #Entrgaremos muchos parametros en forma de matriz\n        #dot permite multiplicar matrices\n\n        #Primero calculamos Z2 (paso a)\n        self.Z2 = np.dot(x, self.W1)\n\n        #Calculamos las activacionesde la capa2 (paso b)\n        self.A2 = self.sigmoide(self.Z2)\n\n        #Calculamos Z3 (paso c)\n        self.Z3 = np.dot(self.A2, self.W2)\n\n        self.A3 = self.sigmoide(self.Z3)\n\n        # Calculamos Z4 (paso c)\n        self.Z4 = np.dot(self.A3, self.W3)\n\n        ySombrero = self.sigmoide(self.Z4)\n\n        return ySombrero\n\n    def sigmoide(self, z):\n        #Aplica funcion sigmoide sobre una matiz\n        return 1 / (1 + np.exp(-z))\n    #Es necesariominimizar el coste del error provocado porlos pesos,\n    #para esto es necesario corregirlos mediante<<<<<<\n# Brief: \n# data\nimport os\n\nlabel_dict = {\"0\": 0,\n              \"1\": 1,\n              \"2\": 2,\n              \"3\": 3,\n              }\n\nis_pos = False\ntrain_path = \"data/train_sample.txt\"\ntest_path = \"data/test_sample.txt\"\ntrain_seg_path = \"data/train_seg_sample.txt\"  # segment of train file\ntest_seg_path = \"data/test_seg_sample.txt\"  # segment of test file\n\nsentence_symbol_path = 'data/sentence_symbol.txt'\nstop_words_path = 'data/stop_words.txt'\n\n# one of \"logistic_regression, random_forest, bayes, decision_tree, svm, knn, xgboost, xgboost_lr, mlp, ensemble, stack, cnn\"\nmodel_type = \"logistic_regression\"\n# one of \"tfidf_char, tfidf_word, language, tfidf_char_language\", ignore when model_type=\"cnn\"\nfeature_type = 'tfidf_char'\noutput_dir = \"output\"\n\npr_figure_path = output_dir + \"/R_P.png\"  # precision recall figure\nmodel_save_path = output_dir + \"/model_\" + feature_type + \"_\" + model_type + \".pkl\"  # save model path\nvectorizer_path = output_dir + \"/vectorizer_\" + feature_type + \".pkl\"\n\n# xgboost_lr model\nxgblr_xgb_model_path = output_dir + \"/xgblr_xgb.pkl\"\nxgblr_lr_model_path = output_dir + \"/xgblr_lr.pkl\"\nfeature_encoder_path = output_dir + \"/xgblr_encoder.pkl\"\n\npred_save_path = output_dir + \"/pred_result.txt\"  # infer data result\ncol_sep = '\\t'  # separate label and content of train data\npred_thresholds = 0.5\nnum_classes = len(label_dict)  # num of data label classes\n\n# --- build_w2v.py ---\n# path of train sentence, if this file does not exist,\n# it will be built from train_seg_path data by train_w2v_model.py train\n# word2vec bin path\nsentence_w2v_bin_path = output_dir + \"/sentence_w2v.bin\"\n# sentence w2v vocab saved path\nsentence_w2v_path = output_dir + \"/sentence_w2v.pkl\"\nsentence_path = output_dir + '/sentences.txt'\n\n# --- train ---\nword_vocab_path = output_dir + \"/word_vocab.txt\"\npos_vocab_path = output_dir + \"/pos_vocab.txt\"\nlabel_vocab_path = output_dir + \"/label_vocab.txt\"\nword_vocab_start = 2\npos_vocab_start = 1\n\n# embedding\nw2v_path = output_dir + \"/w2v.pkl\"\np2v_path = output_dir + \"/p2v.pkl\"  # pos vector path\nw2v_dim = 256\npos_dim = 64\n\n# param\nmax_len = 400  # max len words of sentence\nmin_count = 10  # word will not be added to dictionary if it's frequency is less than min_count\nbatch_size = 128\nnb_epoch = 5\nkeep_prob = 0.5\nword_keep_prob = 0.9\npos_keep_prob = 0.9\n\n# directory to save the trained model\n# create a new directory if the dir does not exist\nmodel_save_temp_dir = output_dir + \"/save_model\"\nbest_result_path = output_dir + \"/best_result.csv\"\n\nif not os.path.exists(output_dir):\n    os.makedirs(output_dir)\nif not os.path.exists(model_save_temp_dir):\n    os.mkdir(model_save_temp_dir)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"596350153","text":"import os\nimport math\nfrom datetime import datetime, timedelta\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\nfrom sql import sql_oracle\nfrom time_tool import Time_tool\ntry:\n    from WindPy import w\n    w.start()\nexcept:\n    w = None\n\n# 季度标签\nclass SeasonLabel(object):\n    def __init__(self):\n        self.cu_wind = sql_oracle.cu\n        self.cu_pra = sql_oracle.cu_pra_sel\n        self.time_tool = Time_tool()\n        self.init_funcs()\n        self.market = pd.DataFrame()\n        self.gen_market()\n\n    def init_funcs(self):\n        '''初始化各种外挂方法'''\n        classes = [LeverageRatio, StandardDeviation, MaxDrawDown, IntervalProfit, AlphaCategroy, SharpRation, DownStd]\n        for class_ in classes:\n            class_(self).add_func()\n\n    def gen_time_list(self, start_date, end_date, s_type='daily', pre_flag=True):\n        '''生成交易日序列\n        s_type: daily, 日频; weekly, 周频\n        pre_flag: True, 需要计算收益率的标签在取样时需要往前多取一个交易日\n        attention: 算法不需要用前一交易日信息,但需要用前一日净值信息来替代, \n        '''\n        t_list = []\n        if s_type == 'daily':\n            t_df = self.time_tool.get_trade_days(start_date, end_date)\n            t_list = list(t_df.iloc[:, 0])\n            if pre_flag == True:\n                pre_day = self.time_tool.get_pre_trade_day(start_date)\n                t_list.insert(0, pre_day)\n        if s_type == 'weekly':\n            t_df = self.time_tool.get_week_trade_days(start_date, end_date)\n            t_list = list(t_df.iloc[:, 0])\n            if pre_flag == True:\n                pre_day = self.time_tool.get_pre_week_trade_day(start_date)\n                t_list.insert(0, pre_day)\n        return t_list\n\n    def get_fund_price(self, code, start_date='', end_date='', time_list=[]):\n        '''计算波动和回测时用到的sql查询方法'''\n        if time_list:\n            start_date = time_list[0]\n            end_date = time_list[-1]\n        sql = '''\n        select\n        f13_1101 as 截止日期, f21_1101 as 复权单位净值 \n        from\n        wind.tb_object_1101\n        left join wind.tb_object_1090\n        on f2_1090 = f14_1101\n        where \n        F16_1090= '%(code)s'\n        and\n        F13_1101 >= '%(start_date)s'\n        and\n        f13_1101 <= '%(end_date)s'\n        order by f13_1101\n        ''' % {'end_date': end_date, 'code': code, 'start_date': start_date}\n        fund_price = pd.DataFrame(self.cu_wind.execute(sql).fetchall(), columns=['日期', '复权单位净值'])\n        fund_price.set_index('日期', inplace=True)\n        if fund_price.empty:\n            raise Exception('lact of fund value')\n        if time_list:\n            # 基金净值数据是按照周频发布\n            # 基金成立在时间段中间,导致获取净值数据不足\n            # if len(time_list) - fund_price.shape[0] > len(time_list) * 0.1:\n            time_list_dt = pd.DataFrame(time_list, columns=['日期'])\n            fund_price = pd.merge(time_list_dt, fund_price, on=['日期'], how='outer')\n            if fund_price.shape[0] / len(time_list) < 0.9:\n                raise Exception('lack of data, timelist>>fund_price.shape[0]')\n            fund_price.fillna(method='ffill', inplace=True)\n            fund_price = pd.merge(time_list_dt, fund_price, on=['日期'], how='left')\n            fund_price.set_index(['日期'], inplace=True)\n            # fund_price = fund_price.reindex(time_list)\n        return fund_price\n\n    def get_fund_price_biwi(self, code, start_date='', end_date='', time_list=[]):\n        if time_list:\n            t1, t2 = time_list[0], time_list[-1]\n        else:\n            t1, t2 = start_date, end_date\n        sql_code = code + 'BI.WI'\n        sql_week_close_bibw = f\"\"\"\n        select  trade_dt,s_dq_close from wind.chinamutualfundbenchmarkeod \n        where s_info_windcode = '{sql_code}' and (trade_dt >= '{t1}' and trade_dt <='{t2}')\n        order by trade_dt \n        \"\"\"\n        sql_res = self.cu_wind.execute(sql_week_close_bibw).fetchall()\n        assert sql_res, f'{code}基准查询结果为空,请改变基准'\n        df = pd.DataFrame(sql_res, columns=['日期', '收盘价'])\n        if df.empty:\n            raise Exception('基金基准查询结果为空')\n        df.set_index('日期', inplace=True)\n        df = df.reindex(time_list)\n        return df\n\n    def get_ejfl_type(self, code, start_date, end_date):\n        '''获取区间内第一个匹配的二级分类类型'''\n        sql_string = f'''\n        select * from (\n            select ejfl from t_fund_classify_his\n            where rptdate <= {end_date}\n            and cpdm = {code}\n            order by rptdate\n        )\n        where rownum=1 \n        '''\n        ejfl_type = self.cu_pra.execute(sql_string).fetchall()\n        if ejfl_type:\n            rst = ejfl_type[0][0]\n        else:\n            rst = None\n        return rst\n\n    def get_market(self, fund_type, time_list):\n        \"\"\"获取同类基准\n         \"\"\"\n        if self.market.empty:\n            self.gen_market()\n        time_list_dt = pd.DataFrame(time_list, columns=['日期'])\n        market_tmp = pd.merge(time_list_dt, self.market, on=['日期'], how='outer')\n        market_tmp.fillna(method='ffill', inplace=True)\n        market_tmp = pd.merge(time_list_dt, market_tmp, on=['日期'], how='left')\n        market_all = pd.DataFrame()\n        for i in ['中证800','中证国债','恒生指数','中证综合债','中证短债','中证可转债','MSCI']:\n            market_all[str(i)+'收益率'] = market_tmp[str(i)].pct_change()\n        if fund_type =='股票型':\n            market_type  = market_all['中证800收益率']\n        elif fund_type == '激进配置型':\n            market_type = market_all['中证800收益率']*0.8+market_all['中证国债收益率']*0.2\n        elif fund_type =='标准配置型':\n            market_type = market_all['中证800收益率']*0.6+market_all['中证国债收益率']*0.4\n        elif fund_type == '保守配置型':\n            market_type = market_all['中证800收益率'] * 0.2 + market_all['中证国债收益率'] * 0.8\n        elif fund_type == '灵活配置型':\n            market_type = market_all['中证800收益率'] * 0.5 + market_all['中证国债收益率'] * 0.5\n        elif fund_type == '沪港深股票型':\n            market_type = market_all['中证800收益率'] * 0.45 + market_all['中证国债收益率'] * 0.1+market_all['恒生指数收益率']*0.45\n        elif fund_type == '沪港深配置型':\n            market_type = market_all['中证800收益率'] * 0.35 + market_all['中证国债收益率'] * 0.3 + market_all['恒生指数收益率'] * 0.35\n        elif fund_type =='纯债型':\n            market_type = market_all['中证综合债收益率']\n        elif fund_type == '普通债券型':\n            market_type = market_all['中证综合债收益率']*0.9+market_all['中证800收益率'] * 0.1\n        elif fund_type == '激进债券型':\n            market_type = market_all['中证综合债收益率']*0.8+market_all['中证800收益率'] * 0.2\n        elif fund_type =='短债型':\n            market_type = market_all['中证短债收益率']\n        elif fund_type =='可转债型':\n            market_type = market_all['中证可转债收益率']\n        elif fund_type =='环球股票':\n            market_type = market_all['MSCI收益率']\n        market_type.name = '市场组合收益率'\n        return  pd.DataFrame(market_type)\n\n    def gen_market(self):\n        '''计算同类基准\n        中证800收益率, 中证国债收益率, 恒生指数收益率, 中证综合债收益率, 中证短债收益率\n        MSCI收益率\n        没有用到 中证可转债\n        '''\n        # 中证800\n        market2 = self.market_fetch('000906')\n        market1 = self.market_fetch('000001')\n        market1 = market1[market1.index < '20050105']\n        a = market2[market2.index == '20050104'].iloc[0, 0] / market1[market1.index== '20050104'].iloc[-1, 0]\n        market1['000906'] = market1['000001'] * a\n        index = market1[market1.index == '20050104'].index.tolist()[0]\n        market_800 = pd.concat([market1[['000906']] , market2], axis=0).drop([index])\n\n        # 中证国债\n        m_country = self.market_fetch('h11006')\n        # 恒生指数\n        HSI  = self.get_market_wind('HSI.HI')\n        #中证综合债\n        m_bond = self.market_fetch('h11009')\n        # 中证短债\n        market_short = self.market_fetch('h11015')\n        # 中证可转债\n        market_tran = self.market_fetch('000832')\n        # MSCI\n        MSCI = self.get_market_wind(\"892400.MI\")\n        self.market = market_800.join([m_country,HSI,m_bond,market_short,market_tran,MSCI])\n        self.market.columns = ['中证800','中证国债','恒生指数','中证综合债','中证短债','中证可转债','MSCI']\n        return \n\n    def market_fetch(self, stock_index):\n        '''获取所有交易日指数数据'''\n        sql1 = '''\n        SELECT\n          T0.F2_1425 日期,\n          T0.F7_1425 AS 复权收盘价\n          FROM\n            wind.TB_OBJECT_1425 T0\n          LEFT JOIN wind.TB_OBJECT_1090 T1 ON T1.F2_1090 = T0.F1_1425\n          WHERE\n            T1.F16_1090 = '%(index_code)s'\n          AND T1.F4_1090 = 'S'\n          ORDER BY\n            T0.F2_1425\n        ''' % {'index_code': stock_index}\n        market = pd.DataFrame(self.cu_wind.execute(sql1).fetchall(), columns=['日期', '指数收盘价'])\n        market.index = market['日期']\n        del market['日期']\n        market.columns = [stock_index]\n        # market = market.pct_change()\n        return market\n\n    def get_market_wind(slef, code, index_start_date='19900101', end_date='20190331'):\n        try:\n            df = w.wsd(code, \"close\", index_start_date, end_date, \"\",\"Currency=CNY\", usedf=True)[1]\n            #df = w.wsd(code, \"close\", \"2015-01-01\", end_date, \"\",\"Currency=CNY\", usedf=True)[1]\n            df.index = pd.Series(df.index).apply(lambda x: str(x)[:4] + str(x)[5:7] + str(x)[8:10])\n            df.columns = [code]\n        except:\n            df = pd.DataFrame(columns=[code])\n        return df\n\n    def get_fund_price_fof(self, code, start_date='', end_date='', time_list=[]):\n        '''fof 基金计算波动和回测时用到的sql查询方法'''\n        if time_list:\n            start_date = time_list[0]\n            end_date = time_list[-1]\n        sql = '''\n        select\n        tradedate, closeprice\n        from\n        t_fof_value_info \n        where \n        fundid = '%(code)s'\n        and\n        tradedate >= '%(start_date)s'\n        and\n        tradedate <= '%(end_date)s'\n        ''' % {'end_date': end_date, 'code': code, 'start_date': start_date}\n        fund_price = pd.DataFrame(self.cu_pra.execute(sql).fetchall(), columns=['日期', '复权单位净值'])\n        fund_price.set_index('日期', inplace=True)\n        if fund_price.empty:\n            raise Exception('lact of fund value')\n        if time_list:\n            if len(time_list) - fund_price.shape[0] > 30:\n                raise Exception('lack of data')\n            fund_price = fund_price.reindex(time_list)\n        return fund_price\n\n    def get_fund_price_index(self, code, start_date='', end_date='', time_list=[]):\n        '''获取指数的净值数据'''\n        if time_list:\n            start_date = time_list[0]\n            end_date = time_list[-1]\n        sql =f'''\n        select f2_1425,f7_1425 from wind.tb_object_1425  left join wind.tb_object_1090  on f1_1425 = f2_1090\n        where f16_1090 = '{code}'\n        and (f2_1425 >='{start_date}' and f2_1425 <= '{end_date}')\n        and f4_1090 = 'S'\n        order by f2_1425\n        '''\n        fund_price = pd.DataFrame(self.cu_wind.execute(sql).fetchall(), columns=['日期', '复权单位净值'])\n        fund_price.set_index('日期', inplace=True)\n        if fund_price.empty:\n            raise Exception('lact of fund value')\n        if time_list:\n            if len(time_list) - fund_price.shape[0] > 30:\n                raise Exception('lack of data')\n            fund_price = fund_price.reindex(time_list)\n        return fund_price\n\n# 杠杆率标签\nclass LeverageRatio(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n        self.cu_wind = season_lable.cu_wind\n        self.cu_pra = season_lable.cu_pra\n\n    def add_func(self):\n        self.season_lable.leverage_ratio = self.leverage_ratio\n\n    def leverage_ratio(self, codes, start_date='', end_date=''):\n        '''计算杠杆率\n        codes: 用来取特定代码的杠杆率,现在是统一求出来, 后面再加处理\n        '''\n        holded_kind = self.get_data_from_sql(codes, start_date, end_date)\n        lev_mean = holded_kind.groupby('基金代码').mean()\n        lev_mean.reset_index(inplace=True)\n        rst_df = lev_mean[['基金代码', '杠杆率']]\n        return rst_df\n\n    def get_data_from_sql(self, codes, start_date, end_date):\n        '''get lvereage ratio info\n        wind.TB_OBJECT_1104 是按半年度更新\n        '''\n        if not codes:\n            raise Exception('invalid imput code')\n        if type(codes) != list:\n            codes = [codes]\n        codes_str = '(' + ','.join([\"'\" + str(i) + \"'\" for i in codes]) + ')'\n        sql_kind='''\n        select F16_1090 as 基金代码,\n        F14_1104 as 截止时间,\n        F5_1104 as 股票占比,\n        F11_1104 as 现金占比,\n        F13_1104 as 其他资产占比,\n        F32_1104 as 债券市值占比,\n        F45_1104 as 权证占比,\n        F52_1104 as 基金占比,\n        F55_1104 as 货币市场工具占比\n        from wind.TB_OBJECT_1090 left join wind.TB_OBJECT_1104\n        on F15_1104 = F2_1090\n        where\n        F14_1104 >= %(start_date)s\n        and F14_1104 <= %(end_date)s\n        and F16_1090 in %(codes_str)s\n        '''%{'start_date': start_date, 'end_date': end_date, 'codes_str': codes_str}\n        sql_res = self.cu_wind.execute(sql_kind).fetchall()\n        res = pd.DataFrame(sql_res,\n                           columns=['基金代码','报告期','股票%','现金%','其他资产%','债券%','权证%','基金%','货币市场工具%']\n              ).sort_values(by='基金代码', ascending=True).reset_index(drop=True)\n        res = res.fillna(0)\n        res['杠杆率'] = res['股票%']+res['现金%']+res['其他资产%']+res['债券%']+res['权证%']+res['基金%']+res['货币市场工具%']\n        return res\n\n# 波动率标签\nclass StandardDeviation(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n        self.get_fund_price_fof = season_lable.get_fund_price_fof\n        self.get_fund_price = season_lable.get_fund_price\n\n    def add_func(self):\n        self.season_lable.standard_deviation = self.standard_deviation\n        self.season_lable.compute_standard_deviation = self.compute_standard_deviation\n\n    def standard_deviation(self, code, start_date, end_date, fof=False):\n        '''计算波动率, 判断是否为fof基金走两个分支'''\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='daily', pre_flag=False)\n        if not fof:\n            # fund_price = self.get_fund_price(code, start_date, end_date)\n            fund_price = self.get_fund_price(code, time_list=time_list)\n        else:\n            fund_price = self.get_fund_price_fof(code, time_list=time_list)\n\n        zhou_bodong = self.compute_standard_deviation(fund_price)\n        return zhou_bodong\n\n    def compute_standard_deviation(self, df):\n        ''' 计算波动率,dataframe.columnes=['日期', '复权单位净值’], 返回numpy.float64'''\n        df2 = df.sort_values(by=['日期']).reset_index(drop=True)\n        df2['fund_return'] = df2.复权单位净值.diff() / df2.复权单位净值.shift(1)\n        df2.dropna(axis=0, inplace=True)\n        df2.reset_index(drop=True, inplace=True)\n        bodong = df2.fund_return.std() * (math.sqrt(250))\n        return bodong\n\n# 最大回撤标签\nclass MaxDrawDown(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n        self.get_fund_price_fof = season_lable.get_fund_price_fof\n        self.get_fund_price = season_lable.get_fund_price\n        self.get_fund_price_index = season_lable.get_fund_price_index\n\n    def add_func(self):\n        '''将接口暴露给上一级对象'''\n        # 计算基金最大回撤\n        self.season_lable.max_draw_down = self.max_draw_down\n        # 批量计算接口\n        self.season_lable.compute_max_draw_down = self.compute_max_draw_down\n        # 计算指数最大回撤\n        self.season_lable.max_draw_down_index = self.max_draw_down_index\n        return\n\n    def max_draw_down(self, code, start_date, end_date, fof=False):\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='daily', pre_flag=False)\n        if not fof:\n            # fund_price = self.get_fund_price(code, start_date, end_date)\n            fund_price = self.get_fund_price(code, time_list=time_list)\n        else:\n            fund_price = self.get_fund_price_fof(code, time_list=time_list)\n        mdd = self.compute_max_draw_down(fund_price)\n        return mdd\n\n    def max_draw_down_index(self, code, start_date, end_date):\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='daily', pre_flag=False)\n        fund_price = self.get_fund_price_index(code, time_list=time_list)\n        mdd = self.compute_max_draw_down(fund_price)\n        return mdd\n    def compute_max_draw_down(self, df):\n        df2 = df.sort_values(by=['日期']).reset_index(drop=True)\n        df.columns = ['复权单位净值']\n        price_list = df2['复权单位净值'].tolist()\n        i = np.argmax((np.maximum.accumulate(price_list) - price_list) / np.maximum.accumulate(price_list))  # 结束位置\n        if i == 0:\n            max_down_value = 0\n        else:\n            j = np.argmax(price_list[:i])  # 开始位置\n            max_down_value = (price_list[j] - price_list[i]) / (price_list[j])\n        return -max_down_value\n\n# 区间收益标签\nclass IntervalProfit(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n        self.get_fund_price = season_lable.get_fund_price\n        self.get_fund_price_fof = season_lable.get_fund_price_fof\n\n    def add_func(self):\n        self.season_lable.interval_profit = self.interval_profit\n        self.season_lable.interval_profit_index = self.interval_profit_index\n        return\n\n    def interval_profit(self, code, start_date, end_date, fof=False):\n        # start_date 如果不是交易日,向前取一天作为替代\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='daily', pre_flag=True)\n        start_date = start_date if time_list[1] == start_date else time_list[0]\n        end_date = time_list[-1]\n        if not fof:\n            s_price_dt = self.get_fund_price(code, start_date, start_date, [])\n            e_price_dt = self.get_fund_price(code, end_date, end_date, [])\n        else:\n            s_price_dt = self.get_fund_price_fof(code, start_date, start_date, [])\n            e_price_dt = self.get_fund_price_fof(code, end_date, end_date, [])\n        s_price = s_price_dt.iat[0, 0]\n        e_price = e_price_dt.iat[0, 0]\n        pft, annual_pft = self.compute_interva_profit(s_price, e_price, len(time_list))\n        return pft, annual_pft\n\n    def interval_profit_index(self, code, start_date, end_date):\n        \"\"\"计算指标的绝对收益率\"\"\"\n        # 找出[起始,终止] 前闭后闭 的所有交易日,如果pre_flag为True 会自动往前去一个交易日\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='daily', pre_flag=True)\n        # 重新定义起始时间\n        start_date = start_date if time_list[1] == start_date else time_list[0]\n\n        sql =f\"\"\"\n        select f2_1425,f7_1425 from wind.tb_object_1425  left join wind.tb_object_1090  on f1_1425 = f2_1090\n        where f16_1090 = '{code}'\n        and (f2_1425 >='{start_date}' and f2_1425 <= '{end_date}')\n        and f4_1090 = 'S'\n        order by f2_1425\n        \"\"\"\n        sql_res = self.season_lable.cu_wind.execute(sql).fetchall()\n\n        s_close = sql_res[0][1]\n        e_close = sql_res[-1][1]\n\n        pft, annual_pft = self.compute_interva_profit(s_close, e_close, len(time_list))\n        return pft,annual_pft\n\n    def compute_interva_profit(self, s_price, e_price, day_cnt):\n        '''计算收益率,返回年化和非年化两种结果'''\n        itv_pft = e_price / s_price - 1\n        annualized_itv_pft = itv_pft / day_cnt * math.sqrt(250)\n        return itv_pft, annualized_itv_pft\n\n# 超额收益alpha\nclass AlphaCategroy(object):\n    '''提供3种接口进行计算,目前实现两种\n    type=2 基金基准进行计算 基金基准不存在改取同类基准\n    type=0 同类基准\n    type=1 同类平均基准(未实现)\n    '''\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n\n    def add_func(self):\n        self.season_lable.compute_alpha_categroy = self.compute_alpha_categroy\n        return\n\n    def compute_alpha_categroy(self, code, start_date, end_date, run_type=2, fof=False):\n        ''' mainly process\n        '''\n        time_list = self.season_lable.gen_time_list(start_date, end_date, s_type='weekly', pre_flag=True)\n        if run_type == 2:\n            fund_value = self.season_lable.get_fund_price(code, time_list=time_list)\n            # 取不到 基金标准 换用同类标准\n            try:\n                fund_index_value = self.season_lable.get_fund_price_biwi(code, time_list=time_list)\n                fund_index_rate = fund_index_value.pct_change()\n                assert False\n            except Exception as err:\n                print(err)\n                ejfl_type = self.season_lable.get_ejfl_type(code, start_date, end_date)\n                print('type: {}'.format(ejfl_type))\n                fund_index_rate = self.season_lable.get_market(ejfl_type, time_list)\n        elif run_type == 0:\n            pass\n        print(fund_value)\n        print(fund_index_value)\n        fund_rate = fund_value.pct_change()\n        fund_rate.reset_index(drop=True, inplace=True)\n        market = fund_rate.join(fund_index_rate)\n        market.columns = ['基金收益率', '市场组合收益率']\n        market = market.dropna(axis=0, how='any')\n        rst = self.compute_alpha(market)\n        print(rst)\n        return rst\n\n    def compute_alpha(self, df):\n        '''\n        计算超额收益,取算数平均,返回年化结果\n        '''\n        df['超额收益'] = df['基金收益率'] - df['市场组合收益率']\n        temp = df['超额收益'].sum() / df['超额收益'].size\n        ### todo 将week_return 里数据移植过来,添加fund_value与index_value对比\n        return temp * 52\n\n#计算夏普比率\nclass SharpRation(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n\n    def add_func(self):\n        # 对外接口\n        self.season_lable.sharp_ratio = self.sharp_ratio\n        return\n\n    def get_periodic_interest_rate(self, time_list):\n        r = w.edb(\"M0043808\", index_start_date, end_date,usedf=True)[1]\n        r = r.reset_index(drop=True)\n        r.index = pd.Series(r['时间']).apply(lambda x: str(x)[:4] + str(x)[5:7] + str(x)[8:10])\n        r.columns = ['一年定存利率','时间']\n        return\n\n    def get_week_fund_value(self, code, time_list):\n        '''获取净值接口,后续添加其他方式'''\n        fund_value_df = season_lable.get_fund_price(code, time_list)\n        return fund_value_df\n\n    def sharp_ratio(self, code, start_date, end_date):\n        time_list = season_lable.gen_time_list(start_date, end_date, s_type='weekly', pre_flag=True)\n        week_fund_value = self.get_week_fund_value(code, time_list)\n        periodic_interest = self.get_periodic_interest_rate(time_list)\n        return\n\n    def compute_sharp_raitio(self):\n        dates.columns = ['基金收益率']\n        stv = dates['基金收益率'].std() * np.sqrt(52)\n        rst = ((dates['基金收益率'].mean() - interest) / stv) * 52\n        return rst\n\n# 计算下行波动率\nclass DownStd(object):\n    def __init__(self, season_lable: SeasonLabel):\n        self.season_lable = season_lable\n        self.offset = 5\n\n    def add_func(self):\n        # 对外接口\n        self.season_lable.down_std= self.down_std\n        self.season_lable.down_std_from_excel = self.down_std_from_excel\n        return\n\n    def down_std_get_fund_value(self, code, time_list):\n        '''获取净值入口,数据来源变化在这里修改'''\n        fund_value = self.season_lable.get_fund_price(code, time_list=time_list) \n        return fund_value\n\n    def get_value_from_excel(self, excel_path, start_date, end_date):\n        ex_df = pd.read_excel(excel_path)\n        time_ser = ex_df['日期'].dt.strftime('%Y%m%d')\n        ex_df['日期'] = time_ser\n        ex_df = ex_df[['日期', '复权单位净值']]\n        if start_date:\n            ex_df = ex_df[ex_df.日期 >= start_date]\n        if end_date:\n            ex_df = ex_df[ex_df.日期 <= end_date]\n        ex_df = ex_df.set_index(['日期'])\n        return ex_df\n\n    def down_std(self, code, start_date, end_date):\n        start_dt = datetime.strptime(start_date, '%Y%m%d')\n        start_new = start_dt - timedelta(weeks=self.offset)\n        start_str = start_new.strftime('%Y%m%d')\n        time_list = self.season_lable.gen_time_list(start_str, end_date, s_type='daily', pre_flag=True)\n        fund_value = self.down_std_get_fund_value(code, time_list)\n        fund_value = fund_value.loc[fund_value.index >= start_date][:]\n        fund_rate = fund_value.pct_change()\n        down_stv = self.compute_down_std(fund_rate)\n        return down_stv\n\n    def down_std_from_excel(self, excel_path, start_date='', end_date=''):\n        if not os.path.exists(excel_path):\n            err = 'input error, file not exists {}'.format(excel_path)\n        fund_value = self.get_value_from_excel(excel_path, start_date, end_date)\n        fund_rate = fund_value.pct_change()\n        down_stv = self.compute_down_std(fund_rate)\n        return down_stv\n\n    def compute_down_std(self, df):\n        df.columns = ['基金收益率']\n        net_np = np.array(df['基金收益率'].dropna(axis=0, how='any'))\n        down_net = np.array(np.delete(net_np, np.where(net_np >= 0)[0]))\n        down_stv = pow(np.power(down_net, 2).sum() / (len(df)-1), 1 / 2) * np.sqrt(52)\n        return down_stv\n\ntmp_local_season_label = SeasonLabel()\n# 获取杠杆率数据\nleverage_ratio = tmp_local_season_label.leverage_ratio\n\n# 获取波动率数据\nstandard_deviation = tmp_local_season_label.standard_deviation\n\n# 计算最大回撤\nmax_draw_down = tmp_local_season_label.max_draw_down\nmax_draw_down_index = tmp_local_season_label.max_draw_down_index\n\n# 计算区间收益\ninterval_profit = tmp_local_season_label.interval_profit\n# 计算指标的区间收益\ninterval_profit_index = tmp_local_season_label.interval_profit_index\n\n# 计算超额收益\ncompute_alpha_categroy = tmp_local_season_label.compute_alpha_categroy\n\n# 计算下行波动率\ndown_std = tmp_local_season_label.down_std\ndown_std_from_excel = tmp_local_season_label.down_std_from_excel\n\n\nif __name__ == '__main__':\n    print('hello world')\n","sub_path":"other/cj_project/Pra_tools/season_label.py","file_name":"season_label.py","file_ext":"py","file_size_in_byte":27597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"266370636","text":"import lab as B\n\nfrom matrix import Diagonal, Kronecker\n\n\ndef test_kronecker_formatting():\n    left = Diagonal(B.ones(2))\n    right = Diagonal(B.ones(3))\n    assert (\n        str(Kronecker(left, right)) == \"\"\n        \"\"\n    )\n    assert (\n        repr(Kronecker(left, right)) == \"\"\n        \"\\n\"\n        \" right=>\"\n    )\n\n\ndef test_kronecker_attributes():\n    left = Diagonal(B.ones(2))\n    right = Diagonal(B.ones(3))\n    kron = Kronecker(left, right)\n    assert kron.left is left\n    assert kron.right is right\n","sub_path":"tests/test_kronecker.py","file_name":"test_kronecker.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"530986890","text":"import rpy2.robjects as robjects\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects import IntVector, StrVector, BoolVector, Formula, r\n\nbase      = importr(\"base\")\nutils     = importr(\"utils\")\nstats     = importr(\"stats\")\nalgdesign = importr(\"AlgDesign\")\ncar       = importr(\"car\")\n\ndef isclose(a, b, rel_tol = 1e-09, abs_tol = 0.0):\n    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\n\ndef opt_federov(design_formula, data, trials):\n    output = algdesign.optFederov(Formula(design_formula),\n                                  data,\n                                  maxIteration = 1000,\n                                  nTrials = trials)\n    return output\n\ndef transform_lm(design, lm_formula):\n    print(\"Power Transform Step:\")\n    response = lm_formula.split(\"~\")[0].strip()\n    variables = lm_formula.split(\"~\")[1].strip()\n    r_snippet = \"\"\"boxcox_t <- powerTransform(%s, data = %s)\n    regression <- lm(bcPower(%s, boxcox_t$lambda) ~ %s, data = %s)\n    regression\"\"\" %(lm_formula, design.r_repr(), response, variables, design.r_repr())\n    transformed_lm = robjects.r(r_snippet)\n\n    return transformed_lm\n\ndef anova(design, formula):\n    regression = stats.lm(Formula(formula), data = design)\n    heteroscedasticity_test = car.ncvTest(regression)\n    print(\"Heteroscedasticity Test p-value:\")\n    print(heteroscedasticity_test.rx(\"p\")[0][0])\n\n    if heteroscedasticity_test.rx(\"p\")[0][0] < 0.05:\n        regression = transform_lm(design, formula)\n        heteroscedasticity_test = car.ncvTest(regression)\n        print(\"Heteroscedasticity Test p-value:\")\n        print(heteroscedasticity_test.rx(\"p\")[0][0])\n\n    summary_regression = stats.summary_aov(regression)\n    print(\"Regression Step:\")\n    print(summary_regression)\n\n    prf_values = {}\n\n    for k, v in zip(base.rownames(summary_regression[0]), summary_regression[0][4]):\n        if k.strip() != \"Residuals\":\n            prf_values[k.strip()] = v\n\n    return regression, prf_values\n\ndef predict_best(regression, data):\n    print(\"Predicting Best\")\n    predicted = stats.predict(regression, data)\n\n    predicted_min = min(predicted)\n    identical_predictions = 0\n\n    for k in range(len(predicted)):\n        if isclose(predicted[k], predicted_min, rel_tol = 1e-5):\n            identical_predictions += 1\n\n    print(\"Identical predictions (tol = 1e-5): {0}\".format(identical_predictions))\n    return data.rx(predicted.ro == base.min(predicted), True)\n\ndef prune_data(data, predicted_best, fixed_variables):\n    print(\"Pruning Data\")\n    conditions = []\n\n    for k, v in fixed_variables.items():\n        if conditions == []:\n            conditions = data.rx2(str(k)).ro == predicted_best.rx2(str(k))\n        else:\n            conditions = conditions.ro & (data.rx2(str(k)).ro == predicted_best.rx2(str(k)))\n\n    pruned_data = data.rx(conditions, True)\n\n    print(\"Dimensions of Pruned Data: \" + str(base.dim(pruned_data)).strip())\n    return pruned_data\n\ndef get_fixed_variables(predicted_best, ordered_prf_keys, fixed_factors, threshold = 2):\n    print(\"Getting fixed variables\")\n    variables = ordered_prf_keys\n    variables = [v.strip(\"I)(/1 \") for v in variables]\n\n    unique_variables = []\n\n    for v in variables:\n        if v not in unique_variables:\n            unique_variables.append(v)\n        if len(unique_variables) >= threshold:\n            break\n\n    fixed_variables = fixed_factors\n    for v in unique_variables:\n        fixed_variables[v] = predicted_best.rx2(str(v))[0]\n\n    print(\"Fixed Variables: \" + str(fixed_variables))\n    return fixed_variables\n\ndef prune_model(factors, inverse_factors, ordered_prf_keys, threshold = 2):\n    print(\"Pruning Model\")\n    variables = ordered_prf_keys\n    variables = [v.strip(\"I)(/1 \") for v in variables]\n\n    unique_variables = []\n\n    for v in variables:\n        if v not in unique_variables:\n            unique_variables.append(v)\n        if len(unique_variables) >= threshold:\n            break\n\n    pruned_factors = [f for f in factors if not f in unique_variables]\n    pruned_inverse_factors = [f for f in inverse_factors if not f in unique_variables]\n\n    return pruned_factors, pruned_inverse_factors\n\ndef dopt_anova_step(response, factors, inverse_factors, data, step_data, fixed_factors, budget):\n    full_model     = \"\".join([\" ~ \",\n                              \" + \".join(factors)])\n\n    if len(inverse_factors) > 0:\n        full_model += \" + \" + \" + \".join([\"I(1 / {0})\".format(f) for f in\n            inverse_factors])\n\n    design_formula = full_model\n    lm_formula     = response[0] + full_model\n    trials         = round(2 * (len(factors) + len(inverse_factors) + 1))\n\n    fixed_variables = fixed_factors\n\n    if budget - len(step_data[0]) < 0:\n        print(\"Full data does not fit on budget\")\n        if trials < len(step_data[0]):\n            print(\"Computing D-Optimal Design\")\n            output = opt_federov(design_formula, step_data, trials)\n            design = output.rx(\"design\")[0]\n        else:\n            print(\"Too few data points for a D-Optimal design\")\n            design = step_data\n\n        used_experiments = len(design[0])\n        regression, prf_values = anova(design, lm_formula)\n        ordered_prf_keys       = sorted(prf_values, key = prf_values.get)\n        predicted_best         = predict_best(regression, step_data)\n        fixed_variables        = get_fixed_variables(predicted_best, ordered_prf_keys,\n                                                     fixed_factors)\n        pruned_data            = prune_data(data, predicted_best, fixed_variables)\n\n        pruned_factors, pruned_inverse_factors = prune_model(factors, inverse_factors,\n                                                             ordered_prf_keys)\n    else:\n        print(\"Full data fits on budget, picking best value\")\n        used_experiments = len(step_data[0])\n        prf_values = []\n        ordered_prf_keys = []\n        pruned_data = []\n        pruned_factors = []\n        pruned_inverse_factors = []\n        predicted_best = step_data.rx((step_data.rx2(response[0]).ro == min(step_data.rx(response[0])[0])),\n                                  True)\n\n    return {\"prf_values\": prf_values,\n            \"ordered_prf_keys\": ordered_prf_keys,\n            \"predicted_best\": predicted_best,\n            \"pruned_data\": pruned_data,\n            \"pruned_factors\": pruned_factors,\n            \"pruned_inverse_factors\": pruned_inverse_factors,\n            \"fixed_factors\": fixed_variables,\n            \"used_experiments\": used_experiments}\n\ndef dopt_anova():\n    data = utils.read_csv(\"../data/search_space.csv\", header = True)\n\n    initial_factors = [\"elements_number\", \"y_component_number\",\n                       \"vector_length\", \"temporary_size\",\n                       \"load_overlap\", \"threads_number\", \"lws_y\"]\n\n    initial_inverse_factors = [\"y_component_number\", \"lws_y\",\n                               \"elements_number\", \"threads_number\"]\n\n    response = [\"time_per_pixel\"]\n\n    data = data.rx(StrVector(initial_factors + response))\n    data_best = data.rx((data.rx2(response[0]).ro == min(data.rx(response[0])[0])),\n                        True)\n\n    step_factors = initial_factors\n    step_inverse_factors = initial_inverse_factors\n    step_space = data\n\n    fixed_factors = {}\n\n    initial_budget = 54\n    budget = initial_budget\n    used_experiments = 0\n    iterations = 4\n\n    for i in range(iterations):\n        print(\"Step {0}\".format(i))\n        if step_space == []:\n            break\n\n        step_data = dopt_anova_step(response,\n                                    step_factors,\n                                    step_inverse_factors,\n                                    data,\n                                    step_space,\n                                    fixed_factors,\n                                    budget)\n\n        step_space = step_data[\"pruned_data\"]\n        step_factors = step_data[\"pruned_factors\"]\n        step_inverse_factors = step_data[\"pruned_inverse_factors\"]\n        budget -= step_data[\"used_experiments\"]\n        used_experiments += step_data[\"used_experiments\"]\n        fixed_factors = step_data[\"fixed_factors\"]\n\n        print(\"Fixed Factors: \" + str(fixed_factors))\n\n        if step_space != []:\n            step_best = step_space.rx((step_space.rx2(response[0]).ro ==\n                min(step_space.rx(response[0])[0])), True)\n\n            print(\"Best Step Slowdown: \" +\n                    str(step_best.rx(response[0])[0][0] /\n                        data_best.rx(response[0])[0][0]))\n\n        print(\"Slowdown: \" +\n                str(step_data[\"predicted_best\"].rx(response[0])[0][0] /\n                    data_best.rx(response[0])[0][0]))\n        print(\"Budget: {0}/{1}\".format(used_experiments, initial_budget))\n\ndopt_anova()\n","sub_path":"src/dopt_anova_transform.py","file_name":"dopt_anova_transform.py","file_ext":"py","file_size_in_byte":8757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"414220248","text":"import unittest\nfrom mock import MagicMock, patch\n\nfrom seismograph.ext.selenium.proxy.tools import WebElementToObject, WebElementCssToObject\n\nclass WebElemenToObjectTest(unittest.TestCase):\n    TEST_ATTR = 'css'\n\n    def setUp(self):\n        self.proxy = MagicMock()\n        self.proxy.parent = MagicMock()\n        self.proxy._wrapped = MagicMock()\n        self.proxy.parent.execute_script = MagicMock()\n        self.proxy.get_attribute = MagicMock(return_value = self.TEST_ATTR)\n       \n        self.el = WebElementToObject(self.proxy)\n \n    def test_get_attr(self):\n        self.assertEqual(self.el.css, self.TEST_ATTR)\n         \n    def test_get_attr_alert(self):\n        err = None\n        self.proxy.get_attribute = MagicMock(return_value = None)\n        try:\n            css = self.el.css\n        except AttributeError as e:\n            err = e.args[0]\n        self.assertEqual(err, self.TEST_ATTR)\n   \n    def test_set_attr(self):\n        self.el.css = 'css'\n        assert self.proxy.parent.execute_script.call_count == 1\n\nclass WebElemenCSSToObjectTest(unittest.TestCase):\n    TEST_ATTR = 'css'\n\n    def setUp(self):\n        self.proxy = MagicMock()\n        self.proxy.parent = MagicMock()\n        self.proxy._wrapped = MagicMock()\n        self.proxy.parent.execute_script = MagicMock()\n        self.proxy.value_of_css_property = MagicMock(return_value = self.TEST_ATTR)\n\n        self.el = WebElementCssToObject(self.proxy)\n\n    def test_get_attr(self):\n        self.assertEqual(self.el.css, self.TEST_ATTR)\n\n\n    def test_set_attr(self):\n        self.el.css = 'css'\n        assert self.proxy.parent.execute_script.call_count == 1\n\nif __name__ == '__main__':\n    unittest.main()\n","sub_path":"tests/tools_test.py","file_name":"tools_test.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"231881219","text":"user_name = input(\"What's your name? \")\nuser_age = input(\"And how old are you? \")\n\ntry:\n    our_age = int(user_age)\nexcept:\n    our_age = float(user_age)\n\ndays_old = our_age*52*7\n\nif not \".\" in user_age:\n    print(\"{} is {} days old. Wow!\".format(user_name, days_old))\nelse:\n    ratio = round(float(user_age)*our_age)\n    print(\"{} is {} days old. Wow!\".format(user_name, days_old))\n","sub_path":"python-basics/days_alive2.py","file_name":"days_alive2.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"597411724","text":"__author__ = 'Dennis'\r\nfrom phBot import *\r\nimport QtBind\r\n\r\ngui = QtBind.init(__name__, 'vSro exploits')\r\n\r\nlog ('[%s] Loaded' % __name__)\r\n\r\nInvisible = QtBind.createButton(gui, 'button_invisible', 'Invisible', 10, 50)\r\n\r\ndef button_invisible():\r\n    inject_joymax(0x70a7, b'\\x04', False)\r\n    log('Becoming invisible!')\r\n\r\n","sub_path":"Invisible.py","file_name":"Invisible.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"318487613","text":"# @Time    : 2019/10/9 14:38\n# @Author  : MosesPan\n# @Email   : 269258169@qq.com\n# @File    : huxiu_spider.py\n# @Software: PyCharm\n\nfrom coolscrapy.items import  HuxiuItem\nimport scrapy\nclass HuxiuSpider(scrapy.Spider):\n    name = \"huxiu\"\n    web_url = \"https://www.huxiu.com\"\n    allowed_domains = [\"huxiu.com\"]\n    start_urls=[\"https://www.huxiu.com/index.php\"]\n\n    def parse(self, response):\n        for sel in response.xpath('//div[@class=\"mob-ctt index-article-list-yh\"]'):\n            item = HuxiuItem()\n            item['title'] = sel.xpath('h2/a/text()').extract_first()\n            item['link']  = sel.xpath('h2/a/@href')[0].extract()\n            # url = response.urljoin(\"https://www.huxiu.com\"+item['link'])\n            url = response.urljoin(item['link'])\n            item['desc'] = sel.xpath('div[@class=\"mob-sub\"]/text()')[0].extract()\n            # print(item['title'], item['link'], url,item['desc'])\n            yield scrapy.Request(url, callback=self.parse_article)\n\n    def parse_article(self, response):\n        detail = response.xpath('//div[@class=\"article__bottom-content__right fl\"]')\n        item = HuxiuItem()\n        item['title'] = detail.xpath('div/h1/text()')[0].extract()\n        item['link'] = response.url\n        item['posttime'] = detail.xpath('div/span[@class=\"article__time\"]/text()')[0].extract()\n        print(item['title'], item['link'], item['posttime'])\n        yield item","sub_path":"coolscrapy/spiders/huxiu_spider.py","file_name":"huxiu_spider.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"285282960","text":"def binary_search(arr, target):\n    mid = len(arr) // 2\n    low = 0\n    high = len(arr) - 1\n    while low <= high and arr[mid] != target:\n        if target > arr[mid]:\n            low = mid + 1\n        else:\n            high = mid - 1\n        mid = (low + high) // 2\n    if target == arr[mid]:\n        return mid\n    else:\n        return None\n\n\narr = []\narr.sort()\nwhile True:\n    try:\n        n = int(input())\n        if n:\n            arr.append(n)\n    except:\n        break\n\n\n\n","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"348362303","text":"#  CASA Next Generation Infrastructure\n#  Copyright (C) 2021 AUI, Inc. Washington DC, USA\n#\n#  This program is free software: you can redistribute it and/or modify\n#  it under the terms of the GNU General Public License as published by\n#  the Free Software Foundation, either version 3 of the License, or\n#  (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program.  If not, see .\n\n#################################\n# Helper File\n#\n# Not exposed in API\n#\n#################################\n\n\ndef selectedchannels(chans=None, shapeLength=64):\n    \"\"\"\n        This method returns all the selected zero-based channel numbers from the specified string within the image.\n\n        Parameters\n        ----------\n        chans : the specified string defined chans\n            input string\n        length :\n            input int\n\n        Returns\n        -------\n        This method returns all the selected zero-based channel numbers from the specified string within the image.\n\n        Examples\n        chans = \"3~8, 54~60\"\n\n        \"\"\"\n    import re\n    import numpy as np\n\n    x = []\n    #split string into substrings\n    if(chans.find(',') != -1):\n        n1 = re.split(r',', chans)\n    elif(chans.find(';') != -1):\n        n1 = re.split(r';', chans)\n    else:\n        n1=[chans]\n\n    for s in n1:\n        n2 = re.findall(\"\\d+\", s)\n        if ( s.find('~') != -1):\n            x += [i for i in range(max(0,int(n2[0])), min(int(n2[1])+1, shapeLength))]\n        elif (s.find('>') != -1):\n            x += [i for i in range(max(0,int(n2[0])+1), shapeLength)]\n        elif (s.find('<') != -1):\n            x += [i for i in range(0, min(int(n2[0]),shapeLength))]\n        else:\n            x += [int(n2[0])]\n\n    return x\n","sub_path":"cngi/_utils/_image_utility.py","file_name":"_image_utility.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"141200205","text":"import sys\nimport re\n\ndef tokenize(chars):\n    return chars.lower().replace('(',' ( ').replace(')', ' ) ').split()\n\ndef parse(chars):\n    return read_from_tokens(tokenize(chars))\n\ndef read_from_tokens(tokens):\n    if(tokens) == 0:\n        raise SyntaxError()\n    token = tokens.pop(0)\n    if '(' == token:\n        L = []\n        while tokens[0] != ')':\n            L.append(read_from_tokens(tokens))\n        tokens.pop(0)\n        return L\n    elif ')' == token:\n        raise SyntaxError()\n    else:\n        return token\n\ndef read_by_line(filename):\n    res = \"\"\n    for line in open(filename):\n        if not line.startswith(\";;\"):\n            res += line\n    return res\n        \n\ndef find(key,sexp):\n    for item in sexp:\n        if len(item) > 1 and item[0] == key:\n            return item[1:]\n\ndef extract_pos(string):\n    t = re.search(\"pos-([0-9]+)-([0-9]+)\",string)\n    j = int(t.group(1)); i = int(t.group(2))\n    return (i,j)\n\nif __name__ == '__main__':\n    input_file = read_by_line(sys.argv[1])\n    parsed = parse(input_file)\n    init = find(\":init\",parsed)\n    M = 0;N = 0\n    clear = {}\n    is_goal = {}\n    at_player = {}\n    at_stone = {}\n    for item in init:\n        if(item[0] == \"clear\"):\n            i,j  = extract_pos(item[1])\n            clear[(i,j)] = True\n        elif(item[0] == \"is-goal\"):\n            i,j  = extract_pos(item[1])\n            is_goal[(i,j)] = True\n            M = max(M,i); N = max(N,j)\n        elif(item[0] == \"is-nongoal\"):\n            i,j  = extract_pos(item[1])\n            M = max(M,i); N = max(N,j)\n        elif(item[0] == \"at\"):\n            if(item[1].startswith(\"player\")):\n                t1 = re.search(\"player-([0-9]+)\",item[1])\n                i,j = extract_pos(item[2])\n                p = t1.group(1)\n                at_player[(i,j)] = int(p)\n            else:\n                t1 = re.search(\"stone-([0-9]+)\",item[1])\n                i,j = extract_pos(item[2])\n                s = t1.group(1)\n                at_stone[(i,j)] = int(s)\n\n    for i in range(1,M+1):\n        line = \"\"\n        for j in range(1,N+1):\n            if (i,j) in is_goal and (i,j) in at_stone:\n                line += \"*\"\n            elif (i,j) in is_goal:\n                line += \".\"\n            elif (i,j) in at_player:\n                line += str(at_player[(i,j)])\n            elif (i,j) in at_stone:\n                line += \"$\"\n            elif not (i,j) in clear:\n                line += \"#\"\n            else:\n                line += \" \"\n        line = line.rstrip()\n        print(line)\n    \n","sub_path":"instance_to_map.py","file_name":"instance_to_map.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"84372311","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@File    :   03.py\n@Time    :   2019/03/28 23:32:01\n@Author  :   waleslau \n@Version :   1.0\n@Contact :   waleslau@hotmail.com\n'''\n\n#统计每个字母出现次数,忽略大小写\n\nstr_input = input(r\"任意输入一串字符\")\n\nbig = [chr(i) for i in range(65,91)]#所有大写字母\nsmall = [chr(i) for i in range(97,123)]#所有小写字母\nthe_dict = {}\nfor i in str_input:\n    if i in big or small:\n        the_dict[i.lower()] = str_input.count(i.upper())+str_input.count(i.lower())\nprint(the_dict)","sub_path":"python/test-classroom/list-tuple-dict-test/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"527891339","text":"# /usr/bin/python3.6\n# -*- coding:utf-8 -*-\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\n\nclass Solution(object):\n    flag = True\n    old = 0\n\n    def traverse(self, root):\n        if root and self.flag:\n            if root.val != self.old:\n                self.flag = False\n                return\n            else:\n                self.traverse(root.left)\n                self.traverse(root.right)\n\n    def isUnivalTree(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: bool\n        \"\"\"\n        self.flag = True\n        self.old = root.val\n        self.traverse(root)\n        return self.flag\n\ndef main():\n    s = Solution()\n\n\nif __name__ == \"__main__\":\n    main()\n","sub_path":"python/leetcode_bak/965_Univalued_Binary_Tree.py","file_name":"965_Univalued_Binary_Tree.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"566939981","text":"#!/usr/bin/env python3\n\nimport random\nimport sys\n\ndef D1():\n    random.seed()\n    R1 = random.randrange(1,7,1)\n    R1 = str(R1)\n    return R1\n\ndef D2():\n    random.seed()\n    R2 = random.randrange(1,7,1)\n    R2 = str(R2)\n    return R2\n\ndef roller():\n    RList = []\n    RList.append(D1())\n    RList.append(D2())\n    Low = min(RList)\n    High = max(RList)\n    return [Low, High]\n\ndef ATBAT(rolls):\n\n    if rolls == ['1','1']:\n        return 'HOME_RUN'\n    elif rolls == ['1','2']:\n        return 'DOUBLE'\n    elif rolls == ['1','3']:\n        return 'SINGLE'\n    elif rolls == ['1','4']:\n        return 'POP_OUT'\n    elif rolls == ['1','5']: # DOUBLE PLAY IF AVAILABLE; to be added\n        return 'GROUND_OUT'\n    elif rolls == ['1','6']:\n        return 'STRIKEOUT'\n    elif rolls == ['2','2']:\n        return 'SINGLE'\n    elif rolls == ['2','3']:\n        return 'POP_OUT'\n    elif rolls == ['2','4']:\n        return 'GROUND_OUT'\n    elif rolls == ['2','5']:\n        return 'STRIKEOUT'\n    elif rolls == ['2','6']:\n        return 'GROUND_OUT'\n    elif rolls == ['3','3']:\n        return 'SINGLE'\n    elif rolls == ['3','4']:\n        return 'STRIKEOUT'\n    elif rolls == ['3','5']:\n        return 'GROUND_OUT'\n    elif rolls == ['3','6']:\n        return 'FLY_OUT'\n    elif rolls == ['4','4']:\n        return 'WALK'\n    elif rolls == ['4','5']:\n        return 'FLY_OUT'\n    elif rolls == ['4','6']:\n        return 'FLY_OUT'\n    elif rolls == ['5','5']:\n        return 'BASE_ON_ERROR'\n    elif rolls == ['5','6']:\n        return 'SINGLE'\n    elif rolls == ['6','6']:\n        return 'TRIPLE'\n\n\n# GAMPLAY\n\ndef VHalfInning(VR, VH):\n\n    # To be used for individual inning stats\n    H = 0\n    Outs = 0\n    OnBase = 0\n    Runs = 0\n    LOB = 0\n    PO = 0\n    GO = 0\n    K = 0\n    BB  = 0\n    FO = 0\n    E = 0\n\n    while Outs < 3:\n\n        rolls = roller()\n        AB = ATBAT(rolls)\n        #print(rolls)\n        #print(AB)\n\n        if AB == 'HOME_RUN':\n            H += 1\n            Runs += 1 + OnBase\n            OnBase = 0\n\n        elif AB == 'SINGLE':\n            H += 1\n            if OnBase < 3:\n                OnBase +=1\n            else:\n                Runs += 1\n                OnBase = 3\n\n        elif AB == 'DOUBLE':\n            H += 1\n            if OnBase < 2:\n                OnBase += 1\n            elif OnBase == 2:\n                Runs += 1\n                OnBase = 2\n            else:\n                Runs += 2\n                OnBase = 2\n\n        elif AB == 'TRIPLE':\n            H += 1\n            if OnBase == 1:\n                Runs += 1\n                OnBase = 1\n            elif OnBase == 2:\n                Runs += 2\n                OnBase = 1\n            elif OnBase == 3:\n                Runs += 3\n                OnBase == 1\n            else:\n                Runs += 1\n                OnBase = 1\n\n        elif AB == 'WALK':\n            if OnBase < 3:\n                OnBase +=1\n            else:\n                Runs += 1\n                OnBase = 3\n\n        elif AB == 'BASE_ON_ERROR':\n            if OnBase < 3:\n                OnBase +=1\n                #HEgame += 1        # Unable to calculate full game errors\n            else:\n                Runs += 1\n                OnBase = 3\n                #HEgame += 1        # Re: line 166\n\n        elif AB == 'POP_OUT':\n            Outs += 1\n\n        elif AB == 'GROUND_OUT':\n            Outs += 1\n\n        #elif AB == 'GROUND_OUT' and\n\n        elif AB == 'STRIKEOUT':\n            Outs += 1\n\n        elif AB == 'FLY_OUT':\n            Outs += 1\n\n    VR.append(Runs)\n    VH.append(H)\n    '''                                 # Prints Half Inning Summary\n    print('\\n')\n    print('visitor Inning Summary:')\n    print('Runs: ', Runs)\n    print('Hits: ', H)\n    print('Outs: ', Outs)\n    print('LOB:  ', OnBase)\n    print('\\n')\n    '''\n    return(VR, VH)\n\ndef HHalfInning(HR, HH):\n\n    # To be used for individual inning stats\n    H = 0\n    Outs = 0\n    OnBase = 0\n    Runs = 0\n    LOB = 0\n    PO = 0\n    GO = 0\n    K = 0\n    BB  = 0\n    FO = 0\n    E = 0\n\n    while Outs < 3:\n\n        rolls = roller()\n        AB = ATBAT(rolls)\n        #print(rolls)           # Dice roll\n        #print(AB)              # AB Value (single, etc.)\n\n        if AB == 'HOME_RUN':\n            H += 1\n            Runs += 1 + OnBase\n            OnBase = 0\n\n        elif AB == 'SINGLE':\n            H += 1\n            if OnBase < 3:\n                OnBase +=1\n            else:\n                Runs += 1\n                OnBase = 3\n\n        elif AB == 'DOUBLE':\n            H += 1\n            if OnBase < 2:\n                OnBase += 1\n            elif OnBase == 2:\n                Runs += 1\n                OnBase = 2\n            else:\n                Runs += 2\n                OnBase = 2\n\n        elif AB == 'TRIPLE':\n            H += 1\n            if OnBase == 1:\n                Runs += 1\n                OnBase = 1\n            elif OnBase == 2:\n                Runs += 2\n                OnBase = 1\n            elif OnBase == 3:\n                Runs += 3\n                OnBase == 1\n            else:\n                Runs += 1\n                OnBase = 1\n\n        elif AB == 'WALK':\n            if OnBase < 3:\n                OnBase +=1\n            else:\n                Runs += 1\n                OnBase = 3\n\n        elif AB == 'BASE_ON_ERROR':\n            if OnBase < 3:\n                OnBase +=1\n                #VEgame += 1            # Re: line 166\n\n            else:\n                Runs += 1\n                OnBase = 3\n                #VEgameE += 1           # Re: line 166\n\n        elif AB == 'POP_OUT':\n            Outs += 1\n\n        elif AB == 'GROUND_OUT':\n            Outs += 1\n\n        elif AB == 'STRIKEOUT':\n            Outs += 1\n\n        elif AB == 'FLY_OUT':\n            Outs += 1\n\n    HR.append(Runs)\n    HH.append(H)\n    '''             ### Prints Half Inning Summary\n    print('\\n')\n    print('Home Inning Summary:')\n    print('Runs: ', Runs)\n    print('Hits: ', H)\n    print('Outs: ', Outs)\n    print('LOB:  ', OnBase)\n    print('\\n')\n    '''\n    return HR,HH\n\ndef Visitor(VR, VH):\n    InningCount = 1\n    while InningCount < 10:\n        VR, VH = VHalfInning(VR, VH)\n        InningCount += 1\n\ndef Home(HR, HH, VR):\n    InningCount = 1\n    while InningCount < 9:\n        HR, HH = HHalfInning(HR, HH)\n        InningCount += 1\n    if sum(VR) >= sum(HR):\n        HR, HH = HHalfInning(HR, HH)\n        InningCount += 1\n    elif sum(VR) < sum(HR):\n        HR.append(0)\n\ndef VExtra(VR, VH):\n    return(VHalfInning(VR, VH))\n\ndef HExtra(HR, HH):\n    return(HHalfInning(HR, HH))\n\ndef season():\n    # To be used for total game stats\n    H = 0\n    Outs = 0\n    OnBase = 0\n    Runs = 0\n    LOB = 0\n    VPOgame = 0\n    VGOgame = 0\n    VKgame = 0\n    VBBgame  = 0\n    VFOgame = 0\n    VEgame = 0\n    VR = []\n    VH = []\n    HR = []\n    HH = []\n\n    counter = 1\n    while counter <= 162:\n        Visitor(VR, VH)\n        Home(HR, HH, VR)\n\n        while sum(VR) == sum(HR):\n            VR, VH = VExtra(VR, VH)\n            HR, HH = HExtra(HR, HH)\n\n        print('\\n')\n        print('Game # {}'.format(counter))\n        #print('          1 2 3 4 5 6 7 8 9    R   H')\n        print('Visitor:', VR, sum(VR), sum(VH))\n        print('Home:   ', HR, sum(HR), sum(HH))\n        print('\\n')\n        VR.clear()\n        HR.clear()\n        VH.clear()\n        HH.clear()\n        counter += 1\n\nTOne = ['1','2','3','4','5','6','7','8','9']\nTTwo = ['A','B','C','D','E','F','G','H','I']\nHPOgame = 0\nHGOgame = 0\nHKgame = 0\nHBBgame  = 0\nHFOgame = 0\nHEgame = 0\n\nseason()\n","sub_path":"DiceBaseball.py","file_name":"DiceBaseball.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"525059778","text":"# https://www.youtube.com/watch?v=LJdu68ro-rU&ab_channel=GeekCode\n\nimport requests\n\nfrom config import TG_TOKEN\n\nMAIN_URL = f'https://api.telegram.org/bot{TG_TOKEN}'\n\npayload = {\n    'chat_id': 354310062,\n    'text': 'Nice to see you again!',\n    'reply_to_message_id': 68\n}\n\nr = requests.get(f'{MAIN_URL}/getUpdates')  # получение сообщения\n# r = requests.post(f'{MAIN_URL}/sendMessage', data=payload)  # отсылка сообщения\nprint(r)\n\nprint(r.json())\n\n","sub_path":"bot_request.py","file_name":"bot_request.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"420424536","text":"golden_retriver = {'name' : 'golden retriver',\r\n    'master' : 'matt',\r\n    'type' : 'dog'}\r\ngreat_dane = {'name' : 'great dane',\r\n    'master' : 'diana',\r\n    'type' : 'dog'}\r\nlabrador_dog = {'name' : 'labrador dog',\r\n    'master' : 'dean',\r\n    'type' : 'dog'}\r\nborder_collie ={'name' : 'border collie',\r\n    'master' : 'ani',\r\n    'type' : 'dog'}\r\npets = [golden_retriver, great_dane, labrador_dog, border_collie]\r\n\r\nfor pet in pets:\r\n    print(\"Dog Name: \" + pet['name'].title())\r\n    print(\"\\tmaster: \" + pet['master'].title())\r\n    print(\"\\ttype: \" + pet['type'].title())\r\n","sub_path":"dictionary/pet.py","file_name":"pet.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"286442169","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport shutil\n\nfrom dmriqcpy.io.report import Report\nfrom dmriqcpy.io.utils import add_overwrite_arg, assert_inputs_exist,\\\n                              assert_outputs_exist\n\nDESCRIPTION = \"\"\"\nCompute the screenshot report in HTML format.\n\"\"\"\n\n\ndef _build_arg_parser():\n    p = argparse.ArgumentParser(description=DESCRIPTION,\n                                formatter_class=argparse.RawTextHelpFormatter)\n\n    p.add_argument('output_report',\n                   help='HTML report')\n\n    p.add_argument('data', nargs='+',\n                   help='Screenshot folders')\n\n    p.add_argument('--sym_link', action=\"store_true\",\n                   help='Use symlink instead of copy')\n\n    add_overwrite_arg(p)\n\n    return p\n\n\ndef main():\n    parser = _build_arg_parser()\n    args = parser.parse_args()\n\n    assert_inputs_exist(parser, args.data, are_directories=True)\n    assert_outputs_exist(parser, args, [args.output_report, \"data\", \"libs\"])\n\n    nb_subjects = len(os.listdir(args.data[0]))\n    for folder in args.data[1:]:\n        nb_subjects += len(os.listdir(folder))\n\n    if os.path.exists(\"data\"):\n        shutil.rmtree(\"data\")\n    os.makedirs(\"data\")\n\n    if os.path.exists(\"libs\"):\n        shutil.rmtree(\"libs\")\n\n    metrics_dict = {}\n    types = \"\"\n    for folder in args.data:\n        files = os.listdir(folder)\n        name = os.path.basename(os.path.normpath(folder))\n        subjects_dict = {}\n        for subj_screenshot in files:\n            if args.sym_link:\n                os.symlink(os.path.abspath(folder) + \"/\" + subj_screenshot,\n                           \"data/\" + subj_screenshot)\n            else:\n                shutil.copyfile(folder + \"/\" + subj_screenshot,\n                                \"data/\" + subj_screenshot)\n            subjects_dict[subj_screenshot] = {}\n            subjects_dict[subj_screenshot]['screenshot'] =\\\n                \"data/\" + subj_screenshot\n        metrics_dict[name] = subjects_dict\n        types += \" {0}\".format(name)\n\n    report = Report(args.output_report)\n    report.generate(title=\"Quality Assurance\" + types,\n                    nb_subjects=nb_subjects, metrics_dict=metrics_dict)\n\n\nif __name__ == '__main__':\n    main()\n","sub_path":"scripts/dmriqc_from_screenshot.py","file_name":"dmriqc_from_screenshot.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"258491615","text":"import math\n\nimport cairo\nimport gtk\n\nimport MouseManager\nfrom Helpers import PatternRepository\nfrom Helpers.Drawing import *\nfrom Helpers.TilesPolygon import TilesPolygon\nfrom Helpers.Internationalization import _\nfrom Selection import Selection\nfrom Board.GameItemTypes import GameItemTypes\nGameItemTypes = GameItemTypes.Instance()\n\nclass MapView( gtk.HBox ):\n    __pixelPerUnit = 2.5 # 2.5 means 5 pixels per Tile (a tile is two units)\n\n    def __init__( self, board, primaryObjectFamilies, secondaryObjectFamilies, primarySurfaceFamilies, secondarySurfaceFamilies ):\n        gtk.HBox.__init__( self, False, 0 )\n\n        self.board = board\n        self.board.registerView( self )\n        self.selection = Selection( self )\n        self.mouseManager = MouseManager.MouseManager( self )\n        for family in primaryObjectFamilies:\n            self.selection.addObjects( family )\n        for family in primarySurfaceFamilies:\n            self.selection.addSurfaces( family )\n        self.__scale = MapView.__pixelPerUnit * 4\n        self.__translateX = 0\n        self.__translateY = 0\n        self.__sisterViews = list()\n\n        self.drawingArea = gtk.DrawingArea()\n        self.drawingArea.connect( \"expose-event\", self.__onExposeEvent )\n        self.drawingArea.set_events(\n            gtk.gdk.EXPOSURE_MASK |\n            gtk.gdk.LEAVE_NOTIFY_MASK |\n            gtk.gdk.BUTTON_PRESS_MASK |\n            gtk.gdk.BUTTON_RELEASE_MASK |\n            gtk.gdk.POINTER_MOTION_MASK |\n            gtk.gdk.POINTER_MOTION_HINT_MASK\n        )\n        self.drawingArea.show()\n\n        toolBar = gtk.Toolbar()\n        toolBar.set_orientation( gtk.ORIENTATION_VERTICAL )\n\n        self.__objectFamilies = primaryObjectFamilies + secondaryObjectFamilies\n        self.__surfaces = list()\n        for family in secondarySurfaceFamilies + primarySurfaceFamilies:\n            for surface in GameItemTypes.surfaces[ family ]:\n                self.__surfaces.append( surface )\n\n        toolBar.append_item( _( \"Select/Move\" ), \"\", \"\", None, lambda widget: self.resetMouseManager() )\n\n        for family in primarySurfaceFamilies:\n            for surface in GameItemTypes.surfaces[ family ]:\n                if GameItemTypes.attributes[ surface ][ \"BuiltByLengths\" ]:\n                    menu = gtk.Menu()\n                    item = gtk.MenuItem( _( \"Length\" ) )\n                    menu.append( item )\n                    item.connect( \"activate\", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceLength() ), surface )\n                    item.show()\n                    item = gtk.MenuItem( _( \"Rectangle\" ) )\n                    menu.append( item )\n                    item.connect( \"activate\", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface )\n                    item.show()\n                    toolBar.append_item( _( surface ), \"\", \"\", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu )\n                else:\n                    toolBar.append_item( _( surface ), \"\", \"\", None, lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface )\n\n        for family in primaryObjectFamilies:\n            for category, subCategories in GameItemTypes.objects[ family ].iteritems():\n                menu = gtk.Menu()\n                for subCategory, buildingTypes in subCategories.iteritems():\n                    for buildingType in buildingTypes:\n                        item = gtk.MenuItem( _( buildingType ) )\n                        menu.append( item )\n                        item.connect( \"activate\", lambda widget, buildingType: self.mouseManager.setState( MouseManager.InsertingObject, buildingType ), buildingType )\n                        if not self.board.isAvailable( buildingType ):\n                            item.set_sensitive( False )\n                        item.show()\n                toolBar.append_item( _( category ), \"\", \"\", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu )\n        toolBar.show()\n\n        self.pack_end( toolBar, False, False, 2 )\n        self.pack_start( self.drawingArea, True, True, 2 )\n\n    def __onExposeEvent( self, widget, event ):\n        self.ctx = self.drawingArea.window.cairo_create()\n        self.__applyTranscale()\n        self.__drawboard()\n        self.__drawGrid()\n        self.mouseManager.draw()\n\n    def __drawboard( self ):\n        self.ctx.save()\n        self.ctx.set_source_rgb( 0.9, 0.9, 1 )\n        self.ctx.paint()\n        self.__drawSurfaces()\n        self.__drawObjects()\n        self.__drawSelection()\n        self.__drawService()\n        self.ctx.restore()\n\n    def __drawSurfaces( self ):\n        for surface in self.__surfaces:\n            self.__drawSurface( surface )\n\n    def __drawSurface( self, surface ):\n        self.__drawPolygons( self.board.getSurface( surface ).polygons, *GameItemTypes.getSurfaceColor( surface ) )\n\n    def __drawPolygons( self, polygons, r, g, b, a ):\n        self.ctx.save()\n        self.ctx.set_source_rgba( r, g, b, a )\n        pathPolygons( self.ctx, polygons )\n        self.ctx.fill()\n        self.ctx.restore()\n\n    def __drawObjects( self ):\n        for objectFamily in self.__objectFamilies:\n            self.__drawObjectFamily( objectFamily )\n\n    def __drawObjectFamily( self, family ):\n        self.ctx.save()\n        for o in self.board.getObjectsByFamily( family ):\n            self.__drawObject( o )\n        self.ctx.restore()\n\n    def __drawObject( self, o ):\n        self.drawObjectInPolygon( o.type, o.polygon, o.rotation )\n        if o.hasProblem:\n            pathPolygons( self.ctx, o.polygon.polygons )\n            self.ctx.set_source_rgba( 1, 0, 0, 0.5 )\n            self.ctx.fill()\n\n    def drawObjectInPolygon( self, resourceType, polygon, rotation ):\n        matrix = cairo.Matrix()\n        matrix.scale( MapView.__pixelPerUnit, MapView.__pixelPerUnit )\n        x, y = polygon.center\n        width, height = GameItemTypes.getObjectSize( resourceType )\n        matrix.translate( width, height )\n        matrix.rotate( -rotation * math.pi / 4 )\n        matrix.translate( -x, -y )\n        pattern = PatternRepository.getPattern( \"buildings\", resourceType )\n        pattern.set_matrix( matrix )\n        self.ctx.set_source( pattern )\n        self.ctx.paint()\n\n    def drawObjectNeeds( self, o ):\n        self.ctx.save()\n        self.ctx.set_font_size( 15 )\n        maxWidth = 0\n        \n        self.ctx.save()\n        self.ctx.identity_matrix()\n        texts = dict()\n        for surface, ( needs, interaction, check ) in o.needs.iteritems():\n            if needs == check:\n                color = ( 0, 0, 0 )\n            elif needs:\n                color = ( 0.6, 0, 0 )\n            else:\n                color = ( 0, 0.5, 0 )\n            if needs:\n                needsLikes = \"Needs\"\n            else:\n                needsLikes = \"Likes\"\n            text = _( needsLikes + \".\" + surface + \".\" + str( interaction ) )\n            x_bearing, y_bearing, width, height, x_advance, y_advance = self.ctx.text_extents( text )\n            maxWidth = max( maxWidth, width )\n            texts[ text ] = color\n        self.ctx.restore()\n        \n        x, y = o.polygon.center\n        \n        self.ctx.save()\n        self.ctx.translate( x, y )\n        self.ctx.scale( 1. / self.__scale, 1. / self.__scale )\n        self.ctx.set_source_rgb( 1, 1, 0.6 )\n        self.ctx.rectangle( -5, -2, maxWidth + 10, len( texts ) * 15 + 10 )\n        self.ctx.identity_matrix()\n        self.ctx.fill_preserve()\n        self.ctx.set_source_rgba( 0, 0, 0, 1 )\n        self.ctx.stroke()\n        self.ctx.restore()\n        \n        i = 0\n        for text in sorted( texts.keys() ):\n            i += 15\n            color = texts[ text ]\n            self.ctx.set_source_rgb( *color )\n            self.ctx.move_to( x, y )\n            self.ctx.save()\n            self.ctx.identity_matrix()\n            self.ctx.rel_move_to( 0, i )\n            self.ctx.show_text( text )\n            self.ctx.restore()\n        self.ctx.restore()\n\n    def __drawSelection( self ):\n        self.ctx.save()\n        pathPolygons( self.ctx, self.selection.getPolygons() )\n        self.ctx.identity_matrix()\n        self.ctx.set_source_rgb( 0, 0, 0 )\n        self.ctx.set_line_width( 4 )\n        self.ctx.stroke()\n        self.ctx.restore()\n\n    def __drawService( self ):\n        self.ctx.save()\n        wall = self.selection.getSurface( \"Wall\" ).tiles\n        if len( self.selection.objects ) == 1 and len( wall ) == 0:\n            ( o, ) = self.selection.objects\n            if \"Service.Name\" in o.attributes:\n                self.__drawSurface( \"Service.\" + o.attributes[ \"Service.Name\" ] )\n        if len( wall ) != 0 and len( self.selection.objects ) == 0:\n            self.__drawSurface( \"Security\" )\n        water = self.selection.getSurface( \"Water\" ).tiles\n        if len( water ) != 0:\n            self.__drawSurface( \"Shoreline\" )\n        self.ctx.restore()\n\n    def __drawGrid( self ):\n        self.ctx.save()\n        upperBound = 2 * self.board.size\n        self.ctx.rectangle( 0, 0, upperBound, upperBound )\n        if self.__scale > self.__pixelPerUnit * 2:\n            for i in range( 0, upperBound + 1, 2 ):\n                self.ctx.move_to( 0, i )\n                self.ctx.line_to( upperBound, i )\n                self.ctx.move_to( i, 0 )\n                self.ctx.line_to( i, upperBound )\n        self.ctx.set_source_rgba( 0.2, 0.2, 0.2, 0.5 )\n        self.ctx.identity_matrix()\n        self.ctx.stroke()\n        self.ctx.restore()\n\n    def __applyTranscale( self ):\n        self.ctx.scale( self.__scale, self.__scale )\n        self.ctx.translate( -self.__translateX, -self.__translateY )\n        # pixelX == self.__scale * ( logicX - self.__translateX )\n        # self.__scale == pixelX / ( logicX - self.__translateX )\n        # logicX == pixelX / self.__scale + self.__translateX\n\n    def transcalePoint( self, pixelX, pixelY ):\n        logicX = pixelX / self.__scale + self.__translateX\n        logicY = pixelY / self.__scale + self.__translateY\n        return logicX, logicY\n\n    def translate( self, dx, dy ):\n        self.__translateX -= dx / self.__scale\n        self.__translateY -= dy / self.__scale\n        self.queue_draw()\n        self.__transcaleSisterViews()\n\n    def zoomIn( self, x, y ):\n        self.__rescale( x, y, math.sqrt( 2.0 ) )\n\n    def zoomOut( self, x, y ):\n        self.__rescale( x, y, math.sqrt( 0.5 ) )\n\n    def __rescale( self, x, y, scale ):\n        oldScale = self.__scale\n        oldTransX = self.__translateX\n        oldTransY = self.__translateY\n        # x == oldScale * ( logicX - oldTransX )\n        # x == newScale * ( logicX - newTransX )\n        # => newScale * ( logicX - newTransX ) == oldScale * ( logicX - oldTransX )\n        # => logicX - newTransX == oldScale * ( logicX - oldTransX ) / newScale\n        # => newTransX == oldScale * ( oldTransX - logicX ) / newScale + logicX\n        logicX = x / self.__scale + oldTransX\n        logicY = y / self.__scale + oldTransY\n        newScale = max( self.__pixelPerUnit, oldScale * scale )\n        newTransX = oldScale * ( oldTransX - logicX ) / newScale + logicX\n        newTransY = oldScale * ( oldTransY - logicY ) / newScale + logicY\n        self.__scale = newScale\n        self.__translateX = newTransX\n        self.__translateY = newTransY\n        self.queue_draw()\n        self.__transcaleSisterViews()\n\n    def __transcaleSisterViews( self ):\n        for view in self.__sisterViews:\n            view.__translateX = self.__translateX\n            view.__translateY = self.__translateY\n            view.__scale = self.__scale\n            view.queue_draw()\n\n    def notifyView( self ):\n        self.queue_draw()\n\n    def resetMouseManager( self ):\n        self.mouseManager.reset()\n        self.queue_draw()\n\n    def addSisterView( self, view ):\n        self.__sisterViews.append( view )\n","sub_path":"src/MapView/MapView.py","file_name":"MapView.py","file_ext":"py","file_size_in_byte":12049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"32999321","text":"from __future__ import absolute_import, print_function\r\nimport torch\r\nfrom torch import nn\r\nimport math\r\nfrom torch.nn.parameter import Parameter\r\nfrom torch.nn import functional as F\r\nimport numpy as np\r\n\r\n\r\n#\r\nclass MemoryUnit(nn.Module):\r\n    def __init__(self, ptt_num, num_cls, part_num,fea_dim, shrink_thres=0.0025):\r\n        super(MemoryUnit, self).__init__()\r\n        '''\r\n        the instance PTT is divided into cls_number x ptt_number per cls x part number per ptt\r\n        '''\r\n        self.num_cls = num_cls\r\n        self.ptt_num = ptt_num\r\n        self.part_num = part_num\r\n        \r\n        self.mem_dim = ptt_num * num_cls * part_num # M\r\n        self.fea_dim = fea_dim # C\r\n        self.weight = Parameter(torch.Tensor(self.mem_dim, self.fea_dim))  # M x C\r\n        #self.sem_weight = Parameter(torch.Tensor(self.num_cls, self.fea_dim)) # N x C\r\n        self.bias = None\r\n        self.shrink_thres= shrink_thres\r\n        # self.hard_sparse_shrink_opt = nn.Hardshrink(lambd=shrink_thres)\r\n\r\n        self.avgpool = nn.AdaptiveAvgPool1d(1)\r\n\r\n        self.reset_parameters()\r\n\r\n    def reset_parameters(self):\r\n        stdv = 1. / math.sqrt(self.weight.size(1))\r\n        self.weight.data.uniform_(-stdv, stdv)\r\n        if self.bias is not None:\r\n            self.bias.data.uniform_(-stdv, stdv)\r\n\r\n    def get_update_query(self, mem, max_indices, score, query):\r\n        m, d = mem.size()\r\n\r\n        query_update = torch.zeros((m,d)).cuda()\r\n        #random_update = torch.zeros((m,d)).cuda()\r\n        for i in range(m):\r\n            idx = torch.nonzero(max_indices.squeeze(1)==i)\r\n            a, _ = idx.size()\r\n            #ex = update_indices[0][i]\r\n            if a != 0:\r\n                #random_idx = torch.randperm(a)[0]\r\n                #idx = idx[idx != ex]\r\n#                     query_update[i] = torch.sum(query[idx].squeeze(1), dim=0)\r\n                query_update[i] = torch.sum(((score[idx,i] / torch.max(score[:,i])) *query[idx].squeeze(1)), dim=0)\r\n                #random_update[i] = query[random_idx] * (score[random_idx,i] / torch.max(score[:,i]))\r\n            else:\r\n                query_update[i] = 0 \r\n                #random_update[i] = 0\r\n    \r\n    \r\n        return query_update        \r\n\r\n    def forward(self, input, residual=False):\r\n        '''\r\n        this is a bottom-up hierarchical stastic and summaration module\r\n        all steps in main flow follow  part -> prototype -> cls\r\n        input = NHW x C\r\n        total PTT M =  num_cls (L) x ptt_num (T) x part_num (P)\r\n        dimension C = fea_dim\r\n        '''\r\n        ### for global part-unware instance PTT, act as sub flow\r\n        att_weight = F.linear(input, self.weight)  # we doesn't split the part dimension, there it is part-unaware NHW x M\r\n        att_weight = F.softmax(att_weight, dim=1)  # NHW x M\r\n        ### update ###\r\n        #_, gather_indice = torch.topk(att_weight, 1, dim=1)\r\n        #ins_mem_sample_driven = self.get_update_query(self.weight, gather_indice, att_weight,input)\r\n        #self.weight.data = F.normalize(ins_mem_sample_driven+ self.weight, dim=1)\r\n\r\n        if self.shrink_thres >0:\r\n            att_weight = hard_shrink_relu(att_weight, lambd=self.shrink_thres)\r\n            att_weight = F.normalize(att_weight, p=1, dim=1)\r\n\r\n        mem_trans = self.weight.permute(1, 0)  # Mem^T, MxC\r\n        output = F.linear(att_weight, mem_trans)  # AttWeight x Mem^T^T = AW x Mem, (TxM) x (MxC) = TxC\r\n\r\n\r\n\r\n        #return {'output': output, 'att': att_weight}  # output, att_weight\r\n        return {'output': output, 'att': None,'sem_attn': self.weight}\r\n        \r\n\r\n    def extra_repr(self):\r\n        return 'mem_dim={}, fea_dim={}'.format(\r\n            self.mem_dim, self.fea_dim is not None\r\n        )\r\n\r\n\r\n# NxCxHxW -> (NxHxW)xC -> addressing Mem, (NxHxW)xC -> NxCxHxW\r\nclass MemModule(nn.Module):\r\n    def __init__(self, ptt_num, num_cls, part_num, fea_dim, shrink_thres=0.0025, device='cuda'):\r\n        super(MemModule, self).__init__()\r\n        self.ptt_num = ptt_num\r\n        self.num_cls = num_cls\r\n        self.part_num = part_num\r\n        ins_mem= False\r\n        if ins_mem:\r\n            self.mem_dim = ptt_num * num_cls * part_num# part-level instance\r\n        else:\r\n            self.mem_dim = num_cls# global semantic\r\n        self.fea_dim = fea_dim\r\n        self.shrink_thres = shrink_thres\r\n        self.memory = MemoryUnit(self.ptt_num, self.num_cls, self.part_num, self.fea_dim, self.shrink_thres)\r\n\r\n    def forward(self, input):\r\n        s = input.data.shape\r\n        l = len(s)\r\n\r\n        if l == 3:\r\n            x = input.permute(0, 2, 1)\r\n        elif l == 4:\r\n            x = input.permute(0, 2, 3, 1)\r\n        elif l == 5:\r\n            x = input.permute(0, 2, 3, 4, 1)\r\n        else:\r\n            x = []\r\n            print('wrong feature map size')\r\n        x = x.contiguous()\r\n        x = x.view(-1, s[1])\r\n        #\r\n        y_and = self.memory(x)\r\n        #\r\n        y = y_and['output']\r\n        att = y_and['att']\r\n\r\n        if l == 3:\r\n            y = y.view(s[0], s[2], s[1])\r\n            y = y.permute(0, 2, 1)\r\n            att = att.view(s[0], s[2], self.mem_dim)\r\n            att = att.permute(0, 2, 1)\r\n        elif l == 4:\r\n            y = y.view(s[0], s[2], s[3], s[1])\r\n            y = y.permute(0, 3, 1, 2)\r\n            #att = att.view(s[0], s[2], s[3], self.mem_dim)\r\n            #att = att.permute(0, 3, 1, 2)\r\n        elif l == 5:\r\n            y = y.view(s[0], s[2], s[3], s[4], s[1])\r\n            y = y.permute(0, 4, 1, 2, 3)\r\n            att = att.view(s[0], s[2], s[3], s[4], self.mem_dim)\r\n            att = att.permute(0, 4, 1, 2, 3)\r\n        else:\r\n            y = x\r\n            att = att\r\n            print('wrong feature map size')\r\n        return y, y_and['sem_attn']\r\n\r\n# relu based hard shrinkage function, only works for positive values\r\ndef hard_shrink_relu(input, lambd=0, epsilon=1e-12):\r\n    output = (F.relu(input-lambd) * input) / (torch.abs(input - lambd) + epsilon)\r\n    return output\r\n\r\n","sub_path":"memory_SGMRA.py","file_name":"memory_SGMRA.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"42440532","text":"import spacy\nfrom .parallel import *\nimport re\nimport functools\n#from .topicmodel import TopicModel\n\n''' This class parses data according to the MFD format. Available are the empath, mft and mft2.0 dictionaries.\n\nFor further information about the format of the dictionary files, see Haidt et al.'s example:\n\nhttp://www.moralfoundations.org/sites/default/files/files/downloads/moral%20foundations%20dictionary.dic\n\n'''\n\nclass DictionaryParser(object):\n\n    ### VVVVVVVVVVVV SKLEARN STUFF VVVVVVVVVVVVVV ###\n    def __init__(self, **params):\n        self.set_params(**params)\n        \n    def get_params(self, deep):\n        return self.params\n    \n    def set_params(self, **params):\n        self.params = params\n        self.dictfile = params['dictfile'] # required: dict file\n        self.workers = params['workers'] if 'workers' in params.keys() else 1\n        self.verb = params['verbose'] if 'verbose' in params.keys() else False\n        self.nlp = spacy.load(params['lang']) if 'lang' in params.keys() else spacy.load('en')\n        \n    def fit(self, X, y):\n        # pretending to be sklearn library\n        return self\n    \n    \n    ### ^^^^^^^^^^^^ SKLEARN STUFF ^^^^^^^^^^^^^^ ###\n\n    def __init__(self, **params):\n        ''' Sets self.dictionary (word:category) and self.dictionary_regex (word:regex_pattern) '''\n\n        self.set_params(**params)\n        \n        # read dict file (sometimes .dic): automatically reads nummap and values\n        self.nummap = dict()\n        self.dictionary = dict()\n        self.dictionary_regex = dict()\n        wordmode = True\n        with open(self.dictfile, 'r') as f:\n            for line in f.readlines():\n\n                ent = line.strip().split()\n                if line[0] == '%':\n                    wordmode = not wordmode\n                elif len(ent) > 0:\n                    if wordmode:\n                        wordkey = ''.join([e for e in ent if e not in self.nummap.keys()])\n                        self.dictionary[wordkey] = [self.nummap[e] for e in ent if e in self.nummap.keys()]\n                    else:\n                        self.nummap[ent[0]] = ent[1]\n        \n        self.category_words = {c:list() for c in self.nummap.values()}\n        for w,cats in self.dictionary.items():\n            for cat in cats:\n                self.category_words[cat].append(w)\n\n        # convenient class members\n        self.categories = list(self.nummap.values())\n    \n    def score_categories(self, X, categories=None, summed=False):\n        '''X is a list of bow (bow in list/set format) (used traditional ml notation)'''\n        \n        def worker(x, dat=None):\n            ''' Worker thread. dat includes either None (in single core mode) or dictionary, \n            dictionary_regex, and found (for multicore). '''\n            \n            # parallel/nonparallel details\n            if dat is None:\n                dat = x[1]\n                x = x[0]\n                \n            # unpack static data\n            dictionary, dictionary_regex, categories = dat['dictionary'], dat['dictionary_regex'], dat['cats']\n            \n            # score foundations\n            dist = {c:0 for c in categories}\n            for w,value_cats in dictionary.items(): # dict words\n                if w in x: # substring check: faster than regex\n                    for cat in value_cats:\n                        if cat in categories: # do I really need this?\n                            dist[cat] += 1\n                            \n            return dist\n        \n        if categories is None:\n            categories = self.categories\n        \n        #if self.verb: print('using spacy to parse for prediction')\n        #X = [[w.text for w in x] for x in self.nlp.pipe(X, disable=['ner', 'textcat', 'parser'], n_threads=self.workers)]\n        \n        dat = {'dictionary':self.dictionary, 'dictionary_regex':self.dictionary_regex, 'cats':categories}\n        if self.workers > 1:\n            if self.verb: print('Running prediction with', self.workers, 'cores.')\n            dists = parmap(worker, X, dat, workers=self.workers)\n        else:\n            if self.verb: print('Running prediction on single core.')\n            dists = list(map(worker, [(x,dat) for x in X]))\n        \n        if summed: # sum up counts across all inputs\n            combine = lambda x,y: {k:x[k]+y[k] for k in x.keys()}\n            catsum = functools.reduce(combine, dists)\n            return catsum\n        else:\n            return dists\n    \n    '''\n    def predict(self, X):\n        \n        yhat = list()    \n        for score in scores:\n            mftvalues = {c:0 for c in self.basenames.values()}\n            for c in self.basenames.keys():\n                if c != 'MoralityGeneral':\n                    #print('shitter', self.basenames[c])\n                    mftvalues[self.basenames[c]] += score[c]\n            \n            fscores = [(k,v) for k,v in mftvalues.items()]\n            sortbf = list(sorted(fscores, key=lambda x:x[1], reverse=True))\n            \n            yhat.append( [f[0] for f in sortbf if f[1] == sortbf[0][1] and f[1] > 0])\n\n        #scores = parmap(scores, mft_base_old)\n        \n        return yhat\n    \n    \n    def score(self, X, y):\n        y = list(y) # avoid weird indexing things if y is series/df\n        yhat = self.predict(X)\n        \n        # currently set to check prediction level\n        return np.mean([(1 if y[i] in yh else 0) for i,yh in enumerate(yhat)])\n    '''\n","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"393935723","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx1 = np.linspace(0,4,50)\nx2 = 12 - 3*x1\n\nplt.annotate(r'$3x_1 + x_2 <= 12$',xy = (1.5,8),xycoords = 'data',\n             xytext=(+30,-30),textcoords = 'offset points',fontsize = 12\n             ,arrowprops = dict(arrowstyle='->',\n                                connectionstyle=\"arc3,rad=.2\"))\n\nplt.plot(x1, x2, color = 'red', label=r'$max z=3x_1+x2$')\n\nx1 = np.linspace(0,5,50)\nx2 = 5-x1\nplt.annotate(r'$x_1 + x_2 <= 5$',xy = (0.5,5),xycoords = 'data',\n             xytext=(+30,0),textcoords = 'offset points',fontsize = 12\n             ,arrowprops = dict(arrowstyle='->',\n                                connectionstyle=\"arc3,rad=.2\"))\nplt.plot(x1, x2, color = 'red')\n\ny1 = np.linspace(0,1)\ny2 = 2-3*y1\n\nplt.annotate(r'$3y_1 + y_2 >= 2$',xy = (0.2,1.2),xycoords = 'data',\n             xytext=(+30,+30),textcoords = 'offset points',fontsize = 12\n             ,arrowprops = dict(arrowstyle='->',\n                                connectionstyle=\"arc3,rad=.2\"))\n\nplt.plot(y1, y2, color = 'blue', linewidth=1.0, linestyle='--', label=r'$min z=y1+y2$')\n\ny1 = np.linspace(0,1)\ny2 = 1-y1\nplt.annotate(r'$y_1 + y_2 >= 1$',xy = (1,0.2),xycoords = 'data',\n             xytext=(+30,0),textcoords = 'offset points',fontsize = 12\n             ,arrowprops = dict(arrowstyle='->',\n                                connectionstyle=\"arc3,rad=.2\"))\n\nplt.plot(y1, y2, color = 'b', linewidth=1.0, linestyle='--')\nlegend = plt.legend(loc = 'upper right', shadow = True)\nframe = legend.get_frame()\nframe.set_facecolor('y')\nplt.xlim(0, 5)\nplt.ylim(0,12)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nplt.scatter([3.5],[1.5],s = 50,color='r')\nplt.scatter([0.5],[0.5],s = 50,color='b')\n\nplt.show()\n","sub_path":"math/pymath/plot03.py","file_name":"plot03.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"153128939","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n线程池:\n需求:\n线程池是一个容器,可设置最大个数-----对列\n从线程池中获取线程,取一个少一个\n线程池中没有线程了,就等待\n任务执行完毕,交还线程\n'''\n\nimport queue\nimport threading\nimport time\n\n\nclass ThreadPool:\n    \"\"\"\n    自定义线程池\n    \"\"\"\n    def __init__(self,maxsize=5):\n        self.maxsize = maxsize   # 线程最大数\n        self._q = queue.Queue(maxsize)   # 创建一个队列用来存放线程\n        # 初始化线程池,存放最大线程数的threading.Thread类\n        for i in range(maxsize):\n            self._q.put(threading.Thread)\n\n    def get_thread(self):\n        \"\"\"\n        从线程池中取线程,线程池中没有线程了就等待\n        :return:\n        \"\"\"\n        return self._q.get()\n\n    def add_thread(self):\n        \"\"\"\n        任务执行完毕,交还线程,向线程池中添加新的threading.Thread类\n        :return:\n        \"\"\"\n        self._q.put(threading.Thread)\n\n\ndef task(args, p):\n    print(args)\n    time.sleep(1)\n\n    p.add_thread()   #任务执行完毕,交还线程\n\nif __name__ == '__main__':\n    pool = ThreadPool(5)   # 创建一个线程池对象\n\n    for i in range(100):\n        t = pool.get_thread()   # 获取一个线程类\n        obj = t(target=task, args=(i,pool))  # 创建一个线程对象\n        obj.start()   # 启动线程\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day11/8-自定义线程池1.py","file_name":"8-自定义线程池1.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"378612184","text":"from django.urls import reverse\n\nfrom core import constants\n\n\ndef test_contribution(self):\n    response = self.client.post(\n        reverse(\"api:contribution-list\"),\n        data={\"text\": \"du texte\", \"description\": \"une description\", \"type\": constants.CONTRIBUTION_TYPE_LIST[0]},\n    )\n    self.assertEqual(response.status_code, 201)\n    self.assertIsInstance(response.data, dict)\n","sub_path":"backend/api/contributions/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}
+{"seq_id":"438012858","text":"import logging\nimport re\nfrom PyQt5 import uic, QtWidgets\n\n\nclass Window(QtWidgets.QWidget):\n    def __init__(self, parent=None):\n        QtWidgets.QWidget.__init__(self, parent)\n        uic.loadUi('windows/window.ui', self)\n\n        self.original_text.textChanged.connect(self.seatch_hlus)\n        self.number_of_words_box.valueChanged.connect(self.seatch_hlus)\n        self.difference_box.valueChanged.connect(self.seatch_hlus)\n        self.repeat_in_center_box.valueChanged.connect(self.seatch_hlus)\n        self.delimiters_text.textChanged.connect(self.seatch_hlus)\n\n        self.list_regexps = [\"*?n?*\", \"o*\", \"*o\"]\n        self.regexps = {\n            \"*?n?*\": r\"[{any}]+{center}[{any}+]\",\n            \"o*\": r\"^[{start}]+[{any}]*\",\n            \"*o\": r\"[{any}]*[{end}]+$\"\n        }\n\n    def distance(self, a, b):\n        n, m = len(a), len(b)\n        if n > m:\n            a, b = b, a\n            n, m = m, n\n\n        current_row = range(n+1)\n        for i in range(1, m+1):\n            previous_row, current_row = current_row, [i]+[0]*n\n            for j in range(1, n+1):\n                add, delete, change = previous_row[j]+1, current_row[j-1]+1, previous_row[j-1]\n                if a[j-1] != b[i-1]:\n                    change += 1\n                current_row[j] = min(add, delete, change)\n\n        return current_row[n]\n\n    def doubles(self, s):\n        result = []\n        count = self.repeat_in_center_box.value()\n        if len(s) >= count+2:\n            new_s = s[1:-1]\n            l = len(new_s)\n            for i in range(l-count+1):\n                result.append(new_s[i:i+count])\n        return result\n\n    def parsing(self, text):\n        list_of_text = re.split(self.delimiters_text.text(), text)\n        number_of_nearest_words = self.number_of_words_box.value()\n        letters = \"\".join(set(text))\n\n        result = []\n        list_to_replace = []\n\n        for position, word in enumerate(list_of_text):\n            end = position+number_of_nearest_words\n            new_words = list_of_text[position+1:(len(list_of_text) if end > len(list_of_text) else end)]\n            centers_of_word = self.doubles(word)\n\n            logging.debug(\"CENTERS:\", centers_of_word)\n            for i, new_word in enumerate(new_words[:-1]):\n                if len(max(word, new_word)) <= len(min(word, new_word))*self.difference_box.value():\n                    res = None\n                    for regexp in self.list_regexps:\n                        if 'center' in self.regexps[regexp]:\n                            for c in centers_of_word:\n                                r = self.regexps[regexp].format(any=letters, center=c)\n                                res = re.search(r, new_word[1:-1])\n                                if res is not None:\n                                    break\n                        else:\n                            r = self.regexps[regexp].format(start=word[0], end=word[-1], any=letters)\n                            res = re.search(r, new_word)\n\n                        if res is not None:\n                            logging.debug(\"RES: \", res)\n                            list_to_replace.append([word, new_word, position, position+i])\n                            logging.debug(regexp)\n                            logging.debug(\"START:{start} END:{end}\".format(start=word[0], end=word[-1]))\n                            logging.debug(\"{}\\n{}\\n\\n\".format(word, new_word))\n                            result.append([word, new_word, regexp])\n                            break\n        return result\n\n    def seatch_hlus(self):\n        text = self.original_text.toPlainText()\n\n        self.new_text.clear()\n        result = self.parsing(text)\n        output = text\n        print(\"\\n\\n\\nRESULT: \", result)\n        for i, (first_word, second_word, r) in enumerate(result):\n            if r == \"*o\":\n                p = \"f\"\n            elif r == \"o*\":\n                p = \"s\"\n            elif r == \"*?n?*\":\n                p = \"c\"\n            else:\n                p = \"hlus\"\n\n            pos = output.find(first_word)\n            l = len(first_word)\n            output = output[:pos] + \"
\" + output[pos:pos+l] + \\\n \"[{}|{}]\".format(p, i) + output[pos+l:]\n\n pos = output.find(second_word, pos)\n l = len(second_word)\n output = output[:pos] + \"
\" + output[pos:pos+l] + \\\n \"[{}|{}]\".format(p, i) + output[pos+l:]\n\n for i in range(2, 20):\n output.replace(\"
\"*i, \"
\")\n print(\"\\n\\n\" in output)\n self.new_text.appendHtml(output)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n window = Window()\n window.show()\n app.exec()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"120110312","text":"\"\"\" Board is a class that displays cards on Canvas\n if Board.cardlist populated, it displays cards in one row\n if Board.pyramid_hands populated, it plays all six hands and\n displays them with showdown points by hand and total\n\n\"\"\"\n\n\nfrom create_card_images import create_card_images\nfrom PlaySixHands25 import *\nfrom display_points import *\n\n\nclass DisplayBoard():\n def __init__(self):\n self.player_win_points = [[[] for i in range(7)] for i in range(7)] #initialize 7x7 list of []\n self.player_names = [\"Pete\", \"John\", \"Ming\", \"Tony\", \"Ed\", \"Phil\"]\n self.Y_GAP = 95\n self.X_GAP = 72\n self.CANVAS_H = 7 * self.Y_GAP\n self.CANVAS_W = 25 * self.X_GAP\n self.X_OFFSET = 10\n self.Y_OFFSET = 10\n self.pyramid_hands = [[] for i in range[7]]\n\n def display_cardlist(self):\n print (\"running display_cardlist\")\n window1 = tk.Tk()\n\n window_label = tk.Label(window1, text = \"window1\")\n window_label.place(x = 25, y = 25)\n window_label.pack()\n hand_separation = 1.04\n X_GAP_factor = .8\n self.CANVAS_W = 25 * self.X_GAP * X_GAP_factor * hand_separation + 25\n self.X_GAP = 72 * X_GAP_factor\n self.CANVAS_H = 8.2 * self.Y_GAP + 25\n self.Y_OFFSET = 2.2 * self.Y_GAP\n image_dict = create_card_images()\n w2 = tk.Canvas(window1, height=self.CANVAS_H, width=self.CANVAS_W, bg=\"light blue\")\n xloc = self.X_OFFSET\n yloc = self.Y_OFFSET\n for card in self.cardlist:\n print(card, image_dict[card],xloc, yloc)\n w2.create_image(xloc, yloc, image=image_dict[card], anchor=\"nw\", tags=(\"card\"))\n xloc += self.X_GAP\n if xloc >= self.CANVAS_W:\n yloc = yloc + self.Y_GAP\n xloc = self.X_OFFSET\n w2.pack()\n w2.mainloop()\n\n def display_6hands(self):\n print (\"running display_6hands\")\n window2 = tk.Tk()\n\n hand_separation = 1.04\n X_GAP_factor = .8\n self.CANVAS_W = 30 * self.X_GAP * X_GAP_factor * hand_separation + 25\n self.X_GAP = 72 * .8\n self.CANVAS_H = 8.2 * self.Y_GAP + 25\n self.Y_OFFSET = 2.2 * self.Y_GAP\n card_image_dict = create_card_images()\n\n w = tk.Canvas(window2, height=self.CANVAS_H, width=self.CANVAS_W, bg=\"light blue\")\n xloc = round(self.X_OFFSET)\n # print (\"right before entering first for loop\")\n # print (len(self.handslist))\n for handx in self.pyramid_hands:\n yloc = round(self.Y_OFFSET)\n # print (handx)\n for i in range(1, 7):\n xloc_start = xloc\n if handx != []:\n X_GAP_Factor = 1\n if len(handx[i]) > 5:\n X_GAP_Factor = 5/len(handx[i])\n for card in handx[i]:\n # print(card, xloc, yloc)\n w.create_image(xloc, yloc, image=card_image_dict[card], anchor=\"nw\", tags=(\"card\"))\n xloc += self.X_GAP * X_GAP_Factor\n xloc = xloc_start\n yloc = yloc + self.Y_GAP\n xloc = xloc_start + 5 * self.X_GAP * hand_separation\n \n # show player_win_points using grid method\n xloc = self.X_OFFSET\n yloc = 30\n player_win_points = self.player_win_points\n\n # points display parameters\n color = \"white\"\n label_width = 4\n line_height = 24\n font_size = 16\n for i in range(6):\n total_points = 0\n for j in range(6):\n total_points += player_win_points[i][j][0]\n # printing row labels\n tk.Label(window2, text=\"H1\", font=font_size, bg=color, width=label_width).place(x=xloc, y=yloc)\n tk.Label(window2, text=\"H2\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+1*line_height)\n tk.Label(window2, text=\"H3\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+2*line_height)\n tk.Label(window2, text=\"H4\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+3*line_height)\n tk.Label(window2, text=\"H5\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+4*line_height)\n tk.Label(window2, text=\"H6\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+5*line_height)\n tk.Label(window2, text=\"Tot\", font=font_size, bg=color, width = label_width).place(x=xloc, y=yloc+6*line_height)\n for j in range(6):\n player = self.player_names[j]\n xloc = xloc + 38\n if i == j:\n player_win_points[i][j][1] = \"-\"\n player_win_points[i][j][2] = \"-\"\n player_win_points[i][j][3] = \"-\"\n player_win_points[i][j][4] = \"-\"\n player_win_points[i][j][5] = \"-\"\n player_win_points[i][j][6] = \"-\"\n player_win_points[i][j][0] = \"-\"\n # displaying player name for player j on row 1\n tk.Label(window2, text=player, font=(\"Arial 10 bold\"), bg=color, width = label_width, anchor=\"e\").place(x=xloc+2, y=yloc-1*line_height)\n # displaying column of points for player j on rows 2-7\n tk.Label(window2, text=str(player_win_points[i][j][1]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+0*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][2]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+1*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][3]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+2*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][4]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+3*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][5]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+4*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][6]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+5*line_height)\n tk.Label(window2, text=str(player_win_points[i][j][0]), font=font_size, bg=color, width = label_width, anchor=\"e\").place(x=xloc, y=yloc+6*line_height)\n # displaying total points on row 8\n tk.Label(window2, text=str(total_points),\n font=font_size, bg=color, anchor=\"e\", width=label_width).place(x=xloc, y=yloc+7*line_height)\n xloc = xloc + hand_separation * 70\n w.pack()\n w.mainloop()\n\n\n# using Deck2 deal which is much a simpler class\n# board2 = Board()\n# board2.cardlist = Deck2.deal()[0]\n# board2.display_cardlist()\n\n# testing Board.display_6hands\n\n","sub_path":"src/DisplayBoard.py","file_name":"DisplayBoard.py","file_ext":"py","file_size_in_byte":6989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"202136093","text":"import os\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport obspy\nimport pandas as pd\nfrom obspy import UTCDateTime\nfrom tqdm import tqdm\nfrom scipy import signal\n\n\ndef obspy_detrend(data):\n # based on obspys detrend (\"simple\") function\n if not np.issubdtype(data.dtype, np.floating):\n data = np.require(data, dtype=np.float64)\n ndat = len(data)\n x1, x2 = data[0], data[-1]\n data -= x1 + np.arange(ndat) * (x2 - x1) / float(ndat - 1)\n return data\n\n\ndef normalize_stream(stream, global_max=False):\n stream_max = np.abs(stream).max()\n if global_max is True:\n stream /= stream_max\n else:\n i = 0\n for tr in stream:\n ma_tr = np.abs(tr).max()\n if ma_tr == 0:\n i += 1\n else:\n tr /= ma_tr\n if i == 3:\n print(\"Der gesamte Stream ist 0\")\n return stream, stream_max\n\n\n# cp = \"/home/viola/WS2021/Code/Daten/Chile_small/new_catalog_sensitivity.csv\"\nwp = \"/home/viola/WS2021/Code/Daten/Chile_small/mseedJan07/\"\n# hp = \"/home/viola/WS2021/Code/Daten/Chile_small/hdf5_dataset_sensitivity.h5\"\n# mp = \"/home/viola/WS2021/Code/Models\"\n# chp = \"/home/viola/WS2021/Code/tb_logs/distance/version_47/checkpoints/epoch=19-step=319.ckpt\"\n# hf = \"/home/viola/WS2021/Code/tb_logs/distance/version_47/hparams.yaml\",\nip = \"/home/viola/WS2021/Code/Daten/Chile_small/inventory.xml\"\n# cp = \"../new_catalogue_sensitivity.csv\"\n\n\n\ncp = \"../new_catalogue_sensitivity.csv\"\nwp = \"../../data/earthquake/waveforms_long_full/\"\nwpa =\"../../data/earthquake/waveforms_long_additional/\"\nhp = \"../new_h5data_sensitivity.h5\"\nip = \"../inventory.xml\"\nfp = \"../highpass_filters.csv\"\nlfilt = signal.butter(2, 35, btype=\"lowpass\", fs=100, output=\"sos\")\n\n\ndef formulate(x, train_catalog,inv,filters):\n #print(x)\n # load train catalog\n # catalog_path = cp\n # hdf5_path = hp\n waveform_path = wp\n waveform_path_add = wpa\n\n # split_key = \"train_files\"\n # file_path = hdf5_path\n # h5data = h5py.File(file_path, \"r\").get(split_key)\n\n # for every item in catalog\n # locate 4 seconds after p Pick --> this is clear as its 3000-3003\n # compute peak displacement\n # load catalog with random test event\n\n event, station, p_pick, distance, magnitude = train_catalog[\n [\"EVENT\", \"STATION\", \"P_PICK\", \"DIST\", \"MA\"]\n ]\n #print(event,station)\n #print(filters)\n # print(filters[\"EVENT\"])\n filters = filters[filters[\"EVENT\"] == event]\n filters = filters[filters[\"STATION\"]==station]\n filterfreq = np.array(filters[\"HIGHPASS_FREQ\"])[0]\n \n # print(idx)\n # load hdf5 waveform\n # raw_waveform = np.array(h5data.get(event + \"/\" + station))\n # seq_len = 4 * 100 # 4seconds *sampling rate\n # p_pick_array = 3000 # ist bei 3000 weil obspy null indiziert arbeitet, also die Startzeit beginnt bei array 0\n\n # load obpsy waveforms\n if os.path.getsize(os.path.join(waveform_path_add, f\"{event}.mseed\")) > 0:\n o_raw_waveform = obspy.read(\n os.path.join(waveform_path, f\"{event}.mseed\")\n ) + obspy.read(os.path.join(waveform_path_add, f\"{event}.mseed\"))\n else:\n o_raw_waveform = obspy.read(os.path.join(waveform_path, f\"{event}.mseed\"))\n\n o_waveform = o_raw_waveform.select(station=station, channel=\"HHZ\")\n o_station_stream = o_waveform.slice(\n starttime=UTCDateTime(p_pick), #\n endtime=UTCDateTime(p_pick) + 3.99,\n ) # -0.01 deletes the last item, therefore enforcing array indexing\n\n # load inventory\n inv_selection = inv.select(station=station, channel=\"HHZ\")\n\n new_stream_w30 = o_station_stream.copy()\n #print(new_stream_w30)\n new_stream_w30[0].data = obspy_detrend(new_stream_w30[0].data)\n \n if filterfreq >0:\n # set high pass filter\n filt = signal.butter(2, filterfreq, btype=\"highpass\", fs=100, output=\"sos\")\n\n new_stream_w30[0].data = signal.sosfilt(filt, new_stream_w30[0].data, axis=-1).astype(np.float32)\n\n new_stream_w30[0].data = signal.sosfilt(lfilt, new_stream_w30[0].data, axis=-1).astype(np.float32)\n \n \n disp_w30 = new_stream_w30.remove_response(\n inventory=inv_selection, pre_filt=None, output=\"DISP\", water_level=30\n )\n # disp_w30.plot()\n m = np.max(np.abs(disp_w30)) # already returns absolute maximum amplitude\n # print(m*100)\n # assert(m>=0)\n return (m * 100, distance, magnitude)\n\n\npool = Pool(35)\ncatalog_path = cp\ncatalog = pd.read_csv(catalog_path)\ntrain_catalog = catalog[catalog[\"SPLIT\"] == \"TRAIN\"]\n#train_catalog = train_catalog[train_catalog[\"EVENT\"] == \"2007_01_01_01_42_45_080000\"]\n#print(train_catalog)\ninv = obspy.read_inventory(ip)\nfilters = pd.read_csv(fp)\nprint(len(train_catalog), len(filters))\n#filters = filters[filters[\"EVENT\"] == \"2007_01_01_01_42_45_080000\"]\n#print(filters)\n\nlen_train = len(train_catalog)\nresults = [\n pool.apply_async(formulate, args=(x, train_catalog.iloc[x],inv,filters))\n for x in tqdm(np.arange(0, len_train))\n]\noutput = [p.get() for p in tqdm(results)]\nprint(output)\nnp.save(\"outputfilters.npy\", output)\n","sub_path":"dataset_formula.py","file_name":"dataset_formula.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"249708604","text":"import socket\nimport re\nimport boto3\nimport urllib3\nimport argparse\nimport time\nfrom datetime import datetime\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dns')\nparser.add_argument('--id')\nargs = parser.parse_args()\n\n\ndnsname = args.dns\nzoneid = args.id\n\n\nnow = datetime.now()\n\nurl = 'http://ipecho.net/plain'\n\n\nhttp = urllib3.PoolManager()\nr = http.request('GET', url)\n\nnew_ip = re.sub(\"(b|')\", \"\", str(r.data))\n\nclient = boto3.client('route53')\n\nzone = client.list_resource_record_sets(\n HostedZoneId=zoneid,\n StartRecordName=dnsname\n)\n\nrrs = zone['ResourceRecordSets']\ncurrent_ip = rrs[0]['ResourceRecords'][0]['Value']\n\n\nprint(str(now) + ': DNS recored: ' + str(dnsname))\nprint(str(now) + ': ZONE ID: ' + str(zoneid))\nprint(str(now) + ': Current IP Address is ' + str(current_ip))\n\nprint(str(now) + ': Checking if IP address has changed')\n\nif current_ip != new_ip:\n print(str(now) + ': IP address has changed. Now Changing dns recorded ' +\n str(dnsname) + ' to ' + str(new_ip))\n\n client.change_resource_record_sets(\n HostedZoneId=zoneid,\n ChangeBatch={\n \"Comment\": \"Update record to reflect new IP Public address\",\n \"Changes\": [\n {\n \"Action\": \"UPSERT\",\n \"ResourceRecordSet\": {\n \"Name\": dnsname,\n \"Type\": \"A\",\n \"TTL\": 60,\n \"ResourceRecords\": [\n {\n \"Value\": new_ip\n }\n ]\n }\n }\n ]\n }\n )\n \n","sub_path":"aws-dyndns.py","file_name":"aws-dyndns.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"400065631","text":"@client.command(pass_context = True)\nasync def group(ctx, *arg):\n \"\"\" *(WIP)* gathers everyone to channel \"name_here\" and plays \"audio.mp3\" \"\"\"\n if ctx.message.author.server_permissions.move_members:\n server = ctx.message.server\n all_members = server.members\n channel = get_channel(server, \"name_here\")\n voice = await client.join_voice_channel(channel)\n player = voice.create_ffmpeg_player(filename = 'audio.mp3')\n members_to_move = set()\n if (arg[0] == 'ALL'):\n for member1 in all_members:\n if(member1.voice_channel != None and not member1.is_afk):\n await client.move_member(member1, channel)\n else:\n names = [name.lower() for name in arg]\n if names != []:\n for member in all_members:\n if member.voice != None:\n for name in names:\n remove = False\n if name in member.name.lower():\n members_to_move.add(member)\n remove = True\n if member.nick != None and name in member.nick.lower():\n members_to_move.add(member)\n remove = True\n if remove:\n names.remove(name)\n for member in members_to_move:\n await client.move_member(member, channel) #use asyncio.gather(*members_to_move) instead for concurrency?\n player.start()\n \n#working fine, removed to develop new reaction-mass-move\nasync def on_reaction_add(reaction, user):\n # code to clear messages by emjois\n # note to JT: Available messages in bot's cache only persist until bot restart. Furthermore, if a message is sent while the bot is offline, the bot cannot access that message.\n \n if(user.server_permissions.manage_messages):\n channel = reaction.message.channel\n msg1 = reaction.message\n if(reaction.emoji == '🆑'):\n #await client.send_message(channel, user.name + \" Set Marker at message '\" + msg1.content + \"' Please select second marker using \" + '🔴')\n res = await client.wait_for_reaction(emoji = '🔴')\n msg2 = res.reaction.message\n if(msg1.timestamp < msg2.timestamp):\n first = msg2\n second = msg1\n else:\n first = msg1\n second = msg2\n dlist = [first]\n async for message in client.logs_from(channel, before=first):#after vs bfore switch #use client.purge_from instead\n #await client.delete_message(message)\n dlist.append(message)\n if(message.timestamp == second.timestamp):\n #print(\"AT MSG 2: \" + message.content)\n break\n #await client.delete_message(first)\n await client.delete_messages(dlist)\n\n","sub_path":"WIP.py","file_name":"WIP.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"462417445","text":"# -*- coding: utf-8 -*-\n\n#猫眼top100数据爬取\nimport requests\nimport re\nimport json\nimport time\nfrom requests.exceptions import RequestException\nimport random\n\ndef get_one_page(url):\n\ttry:\n\t\theaders = {\n\t\t\t'User-Agent': 'Mozilla/5.0(Macintosh;Inter Mac OS X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)'\n\t\t\t\t\t\t 'Chorme/52.0.2743.116 Safari/537.36'\n\t\t}\n\t\tr = requests.get(url,headers = headers)\n\t\tif r.status_code == 200:\n\t\t\treturn r.text\n\t\treturn\n\texcept RequestException as e:\n\t\treturn None\n\ndef parse_one_page(html):\n\tpattern= re.compile('
.*?board-index.*?>(\\d+).*?data-src=\"(.*?)\".*?name\">(.*?).*?star\">(.*?)

.*?releasetime\">(.*?)

'\n\t\t\t\t\t\t + '.*?integer\">(.*?).*?fraction\">(.*?).*?
',re.S)\n\titems =re.findall(pattern,html)\n\titems = list(items)\n\tfor item in items:\n\t\tyield{\n\t\t\t'index':item[0],\n\t\t\t'image':item[1],\n\t\t\t'title':item[2].strip(),\n\t\t\t'actor':item[3].strip()[3:] if len(item[3]) > 3 else '',\n\t\t\t'time':item[4].strip()[5:] if len(item[4]) > 5 else '',\n\t\t\t'score':item[5].strip() + item[6].strip()\n\t\t}\n\ndef write_to_file(content):\n\twith open('result.txt','a',encoding='utf-8') as f:\n\t\tprint(type(json.dumps(content)))\n\t\tf.write(json.dumps(content,ensure_ascii = False)+'\\n')\n\ndef main(offset):\n\turl = 'http://maoyan.com/board/4?offset='+str(offset)\n\thtml = get_one_page(url)\n\tfor item in parse_one_page(html):\n\t\tprint(item)\n\t\twrite_to_file(item)\n\nif __name__ == '__main__':\n\tfor i in range(10):\n\t\tmain(offset =i *10)\n\t\ttime.sleep(3)\n\n\n\n","sub_path":"maoyan_requests.py","file_name":"maoyan_requests.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"405988767","text":"# Find All Duplicates in an Array\n'''\n\nGiven an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.\n\nFind all the elements that appear twice in this array.\n\nCould you do it without extra space and in O(n) runtime?\n\nExample:\nInput:\n[4,3,2,7,8,2,3,1]\n\nOutput:\n[2,3]\n\n'''\nclass Solution:\n def findDuplicates(self, arr: List[int]) -> List[int]:\n res = []\n for i, num in enumerate(arr):\n if arr[abs(num)-1]<0:\n res.append(abs(num))\n else:\n arr[abs(num)-1] = -1*abs(arr[abs(num)-1])\n return res","sub_path":"August/Week1/Find All Duplicates in an Array.py","file_name":"Find All Duplicates in an Array.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"94551899","text":"\"\"\"\nThis file initializes application and brings together all components.\n\"\"\"\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Extensions\ndb = SQLAlchemy()\n\n\ndef create_app(config_file='config.py'):\n app = Flask(__name__, instance_relative_config=True)\n\n app.config.from_pyfile(config_file)\n db.init_app(app)\n\n # Register all blueprints\n from .account import account\n app.register_blueprint(account)\n from .error import error\n app.register_blueprint(error)\n from .home import home\n app.register_blueprint(home)\n\n # Logging configuration\n if not app.debug:\n import os\n import logging\n from logging.handlers import SMTPHandler, RotatingFileHandler\n\n # Send email if an error occurred\n if app.config['MAIL_SERVER']:\n auth = None\n if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:\n auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])\n secure = None\n if app.config['MAIL_USE_TLS']:\n secure = ()\n mail_handler = SMTPHandler(\n mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),\n fromaddr='no-reply@' + app.config['MAIL_SERVER'],\n toaddrs=app.config['ADMINS'], subject='SmartHome Failure',\n credentials=auth, secure=secure\n )\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n\n # Logging to a file\n if not os.path.exists('logs'):\n os.mkdir('logs')\n file_handler = RotatingFileHandler('logs/smarthome.log',\n maxBytes=10240,\n backupCount=10)\n file_handler.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n\n app.logger.setLevel(logging.INFO)\n app.logger.info('SmartHome startup')\n\n return app\n\n# Import all models\nfrom .account import models as account_models\nfrom .home import models as home_models\n","sub_path":"smart_home/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"446876436","text":"# leetcode hard problem https://leetcode.com/problems/dungeon-game/\r\n\r\nclass Solution:\r\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\r\n d = collections.defaultdict(lambda : 100000000)\r\n d[(len(dungeon)-1,len(dungeon[0]))] = 1\r\n d[(len(dungeon),len(dungeon[0])-1)] = 1\r\n for i in range(len(dungeon)-1,-1,-1):\r\n for j in range(len(dungeon[0])-1,-1,-1):\r\n mx = dungeon[i][j] - min(d[(i+1,j)],d[(i,j+1)]) + 1\r\n if mx > 0:\r\n d[(i,j)] = 1\r\n else:\r\n d[(i,j)] = abs(mx) + 1\r\n \r\n print(d[(0,0)])\r\n ans = d[(0,0)] if d[(0,0)] > 0 else abs(d[(0,0)]) + 1 \r\n return ans","sub_path":"Program's_Contributed_By_Contributors/Python_Programs/Dungeon_Game.py","file_name":"Dungeon_Game.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"526532819","text":"import socket\n\n\ndef sendMsg(udpSocket):\n '''\n send message function\n :param udpSocket:\n :return:\n '''\n message = input('Please Input What You Want To Send: ')\n destIp = input('Please input dest IP:')\n destPort = input('Please Input dest port: ')\n udpSocket.sendto(message.encode('utf-8'), (destIp, int(destPort)))\n\n\ndef recvMsg(udpSocket: socket):\n recvData = udpSocket.recvfrom(2048)\n print('%s %s' % (str(recvData[1]), recvData[0].decode('utf-8')))\n\n\ndef main():\n udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udpSocket.bind(('127.0.0.1', 7788))\n print('------ Listening At 127.0.0.1:7788 ------')\n\n print('0: exit')\n print('1: send message')\n print('2: receive message')\n while True:\n print('-----------------------------------------')\n option = input('Please input your action number: ')\n if option == '1':\n sendMsg(udpSocket)\n elif option == '2':\n recvMsg(udpSocket)\n elif option == '0':\n break\n else:\n print('Please input [0, 2, 3]!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/case01/UDPServer.py","file_name":"UDPServer.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"312035427","text":"from datetime import timedelta, date\n\nfrom app.models import Client, Order, Tour\n\n\ndef get_tours(filters):\n if filters:\n str_from_price = filters.get('from_price', None)\n str_by_price = filters.get('by_price', None)\n\n if not str_by_price:\n str_by_price = 10e10\n\n if not str_from_price:\n str_from_price = '0'\n\n from_price = float(str_from_price) - 1\n by_price = float(str_by_price) + 1\n\n if from_price and by_price:\n tours = Tour.query.filter(Tour.day_cost > int(from_price)).filter(by_price > Tour.day_cost)\n elif from_price:\n tours = Tour.query.filter(Tour.day_cost >= from_price)\n elif by_price:\n tours = Tour.query.filter(by_price >= Tour.day_cost)\n else:\n tours = Tour.query.all()\n else:\n tours = Tour.query.all()\n\n return list(tours)\n\n\ndef get_orders(filters):\n if filters:\n s_from_date = filters.get('tour_date_from', None)\n s_by_date = filters.get('tour_date_by', None)\n\n if s_from_date and s_by_date:\n from_date = date.fromisoformat(s_from_date)\n by_date = date.fromisoformat(s_by_date)\n\n by_date += timedelta(days=1)\n from_date -= timedelta(days=1)\n\n print(from_date, by_date)\n orders = Order.query.filter(Order.tour_date > from_date).filter(by_date > Order.tour_date)\n elif s_from_date:\n from_date = date.fromisoformat(s_from_date)\n from_date -= timedelta(days=1)\n\n orders = Order.query.filter(Order.tour_date >= from_date)\n elif s_by_date:\n by_date = date.fromisoformat(s_by_date)\n by_date += timedelta(days=1)\n\n orders = Order.query.filter(by_date >= Order.tour_date)\n else:\n orders = Order.query.all()\n else:\n orders = Order.query.all()\n\n return list(orders)\n\n\ndef get_clients(filters):\n if filters:\n sort_by = filters.get('sort-input', False)\n desc = filters.get('desc', False)\n\n if sort_by == 'first_name':\n if desc:\n clients = list(Client.query.order_by(Client.first_name))\n clients.reverse()\n else:\n clients = Client.query.order_by(Client.first_name)\n elif sort_by == 'last_name':\n if desc:\n clients = list(Client.query.order_by(Client.last_name))\n clients.reverse()\n else:\n clients = Client.query.order_by(Client.last_name)\n elif sort_by == 'num_orders':\n if desc:\n clients = list(Client.query.all())\n clients.sort(key=lambda c: c.number_of_orders, reverse=True)\n else:\n clients = list(Client.query.all())\n clients.sort(key=lambda c: c.number_of_orders)\n else:\n clients = Client.query.all()\n else:\n clients = Client.query.all()\n\n return list(clients)\n\n","sub_path":"PROJECT/app/service/READ_operators.py","file_name":"READ_operators.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"623908737","text":"''' \nFeed System \nCopyright (C) 2020 RPL at UCSB \nAuthor: Sebastian Vargas\n\nThe purpose of this code is to calculate the time required to pressurize our Methane tank. \n\nFirst assumption: it is very easy for the helium to initially fill the eulage volume and takes little time. Therefore, I will consider the time \nit takes to pressurize from that point. Second assumption: At the very first instant that the helium fills the eulage volume, it still maintains \nits initial temperature, so I will update the temperature after this point. Important notes: I am going to be tracking moles inside the eulage volume, \nusing PV= nRT I will update the pressure as a function of moles and the temperature of the gas, the temperature will be updated by using the equation from BETE.\nI will run the simulation based on a while loop influenced by the pressure difference, and it will stop once the tanks reach the desired pressure. \n\n''' \nfrom polyfit_diffuser import q_of_p\nfrom materials import Helium \nimport matplotlib.pyplot as plt\nimport numpy as np\n\npressurant = Helium(540,100)\n\n\ncv = 0.01593484\n\ngallons_to_liters = 3.78541; # [L/gal] This will be used to convert flow rate into liters per minute \nhelium_density_eul = pressurant.get_density() ; # [g/L] This will be used for a conversion from flow rate into grams/s\ngrams_to_moles = 4.003 ; # [mol/g] This converts our flowrate from grams/s to mol/s \nv_eul = 25 ; # [L] Fixed quantity throughout pressurization \nP_reg = 540 ; # [psi] This is a fixed inlet pressure from the regulator \nP_eul = 14.7 ; # [psi} This is the INITIAL gauge pressure inside the tank, ambient pressure\npsi_to_atm = 0.068046 ; # [psi/atm] This converts our gauge pressure of psi to atm when we use PV=nrt, but remember to add 1 atm because we are using gauge pressures; \n\nP_diff = P_reg - P_eul ; # [psi] This is the pressure difference that influences flow rate across our diffuser \n\nTi = 310.928 ; # [K] Ambient room temperature \nTf = 111.7 ; # [K] Methane Cryogenic temperature, this is once pressurant reaches thermal equilibrium \nT = Ti ; # [K] Setting up the initial temperature of our pressurant, it is at ambient temperature (assumption) \nt = 0 ; # [s] Setting up euler time step problem\ndt = 0.001 ; # [s] Setting up time step \nR = 0.08205 ; # [L atm/mol k]\nmoles = P_eul*v_eul/(R*T) ; # [mol] Initial moles in the tank of pressurant \nlamb = 1.6667; \n\np_eul_array = []\np_f_array = []\nmoles_array = [] \n\ndef T_gas(P_f,P_i): \n return (P_f/P_i)*T*((P_f/P_i-1)/lamb + 1)**(-1)\n\ndef converging_temp_pressure(moles,T,P_eul): \n for x in range(30): \n new_press = (moles*R*T/v_eul)/psi_to_atm\n #T = (T * moles + T_gas(new_press, P_eul) * mdot * dt)/moles\n T = T_gas(new_press, P_eul)\n P_eul = new_press \n \n return T, new_press\n\nwhile P_diff > 1:\n p_eul_array.append(P_eul)\n p_f_array.append(T)\n moles_array.append(moles)\n #helium_density_eul = Helium(P_eul,T).get_density()\n mdot = q_of_p(P_diff)*gallons_to_liters*helium_density_eul*grams_to_moles/60 # [mol/s] Based on the curve fit as a function of pressure difference from the company \n moles = moles + mdot * dt\n new_press = (moles*R*T/v_eul)/psi_to_atm\n T = (T * (moles - mdot * dt) + T_gas(new_press, P_eul) * mdot * dt)/moles #[K] Temperature averaging\n #T = T_gas(new_press, P_eul)\n P_eul = new_press \n temp_pressure_var = converging_temp_pressure(moles,T,P_eul) # [mol/s] This updates our moles inside the eulage volume and prepares for pv=nrt \n #T = temp_pressure_var[0]\n #P_eul = temp_pressure_var[1]\n P_diff = P_reg - P_eul # [psi] Preparation to update mdot # [k] Use the function inside of the BETE pdf to update the temperature inside the tank as a function of the eulage pressure\n t = t + dt # [s] updating the time step \n \n\nfig, ax = plt.subplots()\nplt.plot(np.arange(0,dt * len(p_eul_array), dt),p_eul_array)\nplt.plot(np.arange(0,dt * len(p_eul_array), dt),p_f_array)\nplt.plot(np.arange(0,dt*len(p_eul_array),dt),moles_array)\nax.legend([\"Eulage Press (psi)\", \"Temp\", \"Moles\"])\nprint(t) \nplt.show()","sub_path":"Copy_Pressurization (Adam 7-10).py","file_name":"Copy_Pressurization (Adam 7-10).py","file_ext":"py","file_size_in_byte":4443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394117034","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n4.3 データセットの分割\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\n\n# データセットの準備\ndf_wine = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\", header=None)\nX, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values\n\n# データセットの分割\nX_train, X_test, y_train, y_test = \\\n train_test_split(X, y, test_size=0.3, random_state=0)\n\n# スケーリング\nstdsc = StandardScaler()\nX_train_std = stdsc.fit_transform(X_train)\nX_test_std = stdsc.transform(X_test)\n\n# L1正則化\nlr = LogisticRegression(penalty='l1', C=0.1)\nlr.fit(X_train_std, y_train)\n\nprint(\"Training Accuracy: {}\".format(lr.score(X_train_std, y_train))) #=> 0.9838709677419355\nprint(\"Test Accuracy: {}\".format(lr.score(X_test_std, y_test))) #=> 0.9814814814814815\n\n# 切片の表示\nprint(lr.intercept_)\n# class1 class2 class3\n#=> [-0.38380229 -0.15807151 -0.70038964]\n\n# 重み係数(=偏回帰係数)の表示\nprint(lr.coef_.shape) #=> (3, 13)\nprint(np.round(lr.coef_, 3))\n#=> [[ 0.28 0. 0. -0.028 0. 0. 0.71 0. 0. 0. 0. 0. 1.236]\n# [-0.644 -0.069 -0.057 0. 0. 0. 0. 0. 0. -0.927 0.06 0. -0.371]\n# [ 0. 0.062 0. 0. 0. 0. -0.636 0. 0. 0.498 -0.358 -0.571 0. ]]\n\n# 正則化の強さに対する特徴量の重み(=偏回帰係数/重み係数)の可視化\nfig = plt.figure()\nax = plt.subplot(111)\n\ncolors = ['blue', 'green', 'red', 'cyan', \n 'magenta', 'yellow', 'black', \n 'pink', 'lightgreen', 'lightblue', \n 'gray', 'indigo', 'orange']\n\nweights, params = [], []\n\n\n# 逆正則化パラメータ(C=1/$\\lambda$)の値ごとに処理\nprint(\"-------------------------\")\nfor c in range(-4, 6):\n lr = LogisticRegression(\n penalty='l1', # L1正則化\n C=10**c, # 逆正則化パラメータ(Cが小さいほど正則化が強い)\n random_state=0\n )\n lr.fit(X_train_std, y_train)\n weights.append(lr.coef_[1])\n params.append(10**c)\n\n# 重み係数をプロット\nweights = np.array(weights)\n\n# for column, color in zip(range(weights.shape[1]), colors):\n# # 横軸: 逆正則化パラメータ\n# # 縦軸: 重み係数\n# plt.plot(params, weights[:, column], label=df_wine.columns[column+1], color=color)\n\n\n# y = 0 の破線\n\nfor column, color in zip(range(weights.shape[1]), colors):\n plt.plot(params, weights[:, column],\n label=df_wine.columns[column + 1],\n color=color)\nplt.axhline(0, color='black', linestyle='--', linewidth=3)\nplt.xlim([10**(-5), 10**5])\nplt.ylabel('weight coefficient')\nplt.xlabel('C')\nplt.xscale('log')\nplt.legend(loc='upper left')\nax.legend(loc='upper center', \n bbox_to_anchor=(1.38, 1.03),\n ncol=1, fancybox=True)\nplt.show()","sub_path":"04/4-5-1.py","file_name":"4-5-1.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"417992727","text":"from flask_restful import Api\nfrom flask import Flask\nfrom flask import make_response\nfrom flask import jsonify\nimport logging\n\nfrom data import db_session, images_resource, rooms_resource, users_resource\nimport config\nfrom werkzeug import exceptions\n\nlogging.basicConfig(\n filename='logs.log',\n format='%(asctime)s %(levelname)s %(name)s %(message)s',\n level=logging.INFO\n)\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = config.KEY\napi = Api(app)\n\n\ndef main():\n api.add_resource(users_resource.UsersListResource, '/api/users')\n api.add_resource(users_resource.UsersResource, '/api/users/')\n api.add_resource(rooms_resource.RoomsListResource, '/api/rooms')\n api.add_resource(rooms_resource.RoomsResource, '/api/rooms/')\n api.add_resource(images_resource.ImagesListResource, '/api/images')\n api.add_resource(images_resource.ImagesResource, '/api/images/')\n try:\n db_session.global_init(\"db/data.sqlite\")\n except Exception as e:\n logging.fatal(f'Error in database connection! Error: {e}')\n exit(-1)\n app.run()\n\n\nif __name__ == \"__main__\": # убери на сервере\n main()\n","sub_path":"api/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"59382174","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 11 02:24:25 2016\r\n\r\n@author: msun\r\n\"\"\"\r\n\r\n#### CSE 231 Project 01 ######\r\n\r\n#### Part 1: calculate WCT #######\r\nT=15.0\r\nV=10.0\r\nWCT=35.74+0.6215*T-35.75*(V**0.16)+0.4275*T*(V**0.16)\r\nprint(\"The WCT index is\", WCT)\r\n\r\nT=0.0\r\nV=20.0\r\nWCT=35.74+0.6215*T-35.75*(V**0.16)+0.4275*T*(V**0.16)\r\nprint(\"The WCT index is\", WCT)\r\n\r\nT=-15.0\r\nV=30.0\r\nWCT=35.74+0.6215*T-35.75*(V**0.16)+0.4275*T*(V**0.16)\r\nprint(\"The WCT index is\", WCT)\r\n\r\n\r\n\r\n#### Part 2: Write a program for user-selected values #######\r\nT_str=input(\"please enter a temperature in Fahrenheit scale :\" )\r\nT_float=float(T_str)\r\n\r\nV_str=input(\"please enter a wind speed in MPH:\" )\r\nV_float=float(V_str)\r\n\r\nWCT=35.74+0.6215*T_float-35.75*(V_float**0.16)+0.4275*T_float*(V_float**0.16)\r\n\r\nprint(\"Temperature (degrees F): \", T_float)\r\nprint( \"Wind speed (MPH): \", V_float)\r\nprint(\"Wind Chill Temperature Index: \", WCT)\r\n\r\n\r\n############### End of Project 01 ###################\r\n\r\n\r\n","sub_path":"proj01/proj01.py","file_name":"proj01.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"178134670","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author: Yonglin Wang\n# Date: 2021/1/29\n\"\"\"Constants used in scripts. Crucially, to prevent circular import, this script does not import relative modules.\"\"\"\n\nfrom collections import OrderedDict\n\nRANDOM_SEED = 2020\n\n# -----\n# Feature extraction Constants\n# -----\n# names to save each column under, original data if no \"calculated\" or \"normalized\" specified in file path\n# In principle,if the directory is not tampered, the following arrays should all have shape (n, [sampling_rate])\nCOL_PATHS = OrderedDict({\"velocity\": \"velocity.npy\", # training, (n_sample, sampling_rate)\n \"velocity_cal\": \"velocity_calculated.npy\", # training, (n_sample, sampling_rate)\n \"position\": \"position.npy\", # training, (n_sample, sampling_rate)\n \"joystick\": \"joystick_deflection.npy\", # training, (n_sample, sampling_rate)\n \"destabilizing\": \"destabilizing_deflection.npy\", # training, (n_sample, sampling_rate)\n \"trial_key\": \"corresponding_peopleTrialKey.npy\", # for output reference only (n_samples,)\n \"start_seconds\": \"entry_start_seconds.npy\", # can be added as feature? (n_samples.)\n \"end_seconds\": \"entry_end_seconds.npy\", # can be added as feature? (n_samples,)\n \"label\": \"label.npy\", # truth label. 1=crash, 0=noncrash (n_sample,)\n })\n\n# lists of initial feature columns generated by generate_feature_files\nINIT_FEATURES = {\"velocity\", \"velocity_cal\", \"position\", \"joystick\", \"trial_key\", \"start_seconds\", \"end_seconds\", \"label\"}\n\n# argparser value checker\nMIN_STEP = 0.04\n\n# crash event criteria\nMIN_ENTRIES_IN_WINDOW = 2 # minimum # of entries between two crash events (i.e. in a window)\n\n# paths for saving output\nDEBUG_FORMAT = \"debug_{}ahead_{}window.csv\"\n\n# columns we will use for interpolation\nCOLS_TO_INTERPOLATE = ('currentVelRoll', 'currentPosRoll', 'calculated_vel', 'joystickX')\n\n# -----\n# DataLoader Constants\n# -----\n\n# velocity mode tag\nCALCULATED = \"calc\"\nORIGINAL = \"orig\"\n\n# paths for saving output\nDATA_OUT_DIR_FORMAT = \"data/{}window_{}ahead_{}rolling/\"\nEXP_OUT_DIR_FORMAT = \"exp/{}window_{}ahead_{}rolling/\"\n\n# path to pickle dataloader, saved under expriment\nLOADER_BASENAME = \"dataloader.pkl\"\n\n# Unique IDs for X Y data preprocessing configuration\nCONFIG_IDS = {1, 2, 3}\n\n# train test split config constants\nTEST_SIZE = 0.2\nUSED_COL_FORMAT = \"{}_InTrain\"\n\n# configuration specific details\nCONFIG_1_2_SPECS = {\"y_enc_path\": \"config1_y_enc.pkl\"}\n\n# -----\n# Model Constants\n# -----\n\n# list of available models\nAVAILABLE_MODELS = [\"lstm\"]\n\n# path to save model (to be joined with\n\n\n","sub_path":"src/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"532657416","text":"class FirstOrderZone(object):\n\n def __init__(self):\n self.c1 = []\n self.c2 = []\n self.c3 = []\n self.c = 0\n self.name = \"FirstOrderZone\"\n\n def getT(self, tpre, oat, on, index):\n T = tpre + (oat-tpre)*self.c1[index]+ self.c*self.c2[index]*on+self.c3[index]\n return T\n","sub_path":"350/pnnl/models/rtusimple.py","file_name":"rtusimple.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"368020176","text":"import Bio.Seq as Seq\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import spearmanr\nfrom scipy.stats.mstats import rankdata\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.linear_model.coordinate_descent import ElasticNet\n\nfrom .load_data import combine_organisms\n\n\ndef get_thirty_one_mer_data():\n \"\"\"\n Load up our processed data file for all of V1 and V2, make a 31mer so that\n we can use the SSC trained model to compare to\n Assumes we call this from the analysis subdirectory\n \"\"\"\n myfile = r\"..\\data\\FC_plus_RES_withPredictions.csv\"\n # was originally FC_RES_5304.csv but that isn't present\n newfile = r\"..\\data\\FC_plus_RES_withPredictions_w_31mer.csv\"\n data = pd.read_csv(myfile)\n thirty_one_mer = []\n for i in range(data.shape[0]):\n thirty_one_mer.append(\n convert_to_thirty_one(\n data.iloc[i][\"30mer\"], data.iloc[i][\"Target\"], data.iloc[i][\"Strand\"]\n )\n )\n data[\"31mer\"] = thirty_one_mer\n data.to_csv(newfile)\n\n\ndef convert_to_thirty_one(guide_seq, gene, strand):\n \"\"\"\n Given a guide sequence, a gene name, and strand (e.g. \"sense\"),\n return a 31mer string which is our 30mer,\n plus one more at the end.\n \"\"\"\n guide_seq = Seq.Seq(guide_seq)\n gene_seq = Seq.Seq(get_gene_sequence(gene)).reverse_complement()\n if strand == \"sense\":\n guide_seq = guide_seq.reverse_complement()\n ind = gene_seq.find(guide_seq)\n if ind == -1:\n print(\n f\"returning sequence+'A', could not find guide {guide_seq} in gene {gene}\"\n )\n return gene_seq + \"A\"\n if gene_seq[ind : (ind + len(guide_seq))] != guide_seq:\n raise AssertionError(\"match not right\")\n new_mer = gene_seq[(ind - 1) : (ind + len(guide_seq))]\n # this actually tacks on an extra one at the end for some reason\n if strand == \"sense\":\n new_mer = new_mer.reverse_complement()\n return str(new_mer)\n\n\ndef concatenate_feature_sets(feature_sets, keys=None):\n \"\"\"\n Given a dictionary of sets of features, each in a pd.DataFrame,\n concatenate them together to form one big np.array, and get the dimension\n of each set\n Returns: inputs, dim\n \"\"\"\n if feature_sets == {}:\n raise AssertionError(\"no feature sets present\")\n if keys is None:\n keys = list(feature_sets.keys())\n\n F = feature_sets[keys[0]].shape[0]\n for assemblage in feature_sets:\n F2 = feature_sets[assemblage].shape[0]\n if F != F2:\n raise AssertionError(\n f\"not same # individuals for features {keys[0]} and {assemblage}\"\n )\n\n N = feature_sets[keys[0]].shape[0]\n inputs = np.zeros((N, 0))\n feature_names = []\n dim = {}\n dimsum = 0\n for assemblage in keys:\n inputs_set = feature_sets[assemblage].values\n dim[assemblage] = inputs_set.shape[1]\n dimsum = dimsum + dim[assemblage]\n inputs = np.hstack((inputs, inputs_set))\n feature_names.extend(feature_sets[assemblage].columns.tolist())\n\n return inputs, dim, dimsum, feature_names\n\n\ndef spearmanr_nonan(x, y):\n \"\"\"\n same as scipy.stats.spearmanr, but if all values are equal, returns 0 instead of nan\n (Output: rho, pval)\n \"\"\"\n r, p = spearmanr(x, y)\n r = np.nan_to_num(r)\n p = np.nan_to_num(p)\n return r, p\n\n\ndef impute_gene_position(gene_position):\n \"\"\"\n Some amino acid cut position and percent peptide are blank because of stop codons, but\n we still want a number for these, so just set them to 101 as a proxy\n \"\"\"\n\n gene_position[\"Percent Peptide\"] = gene_position[\"Percent Peptide\"].fillna(101.00)\n\n if \"Amino Acid Cut position\" in gene_position.columns:\n gene_position[\"Amino Acid Cut position\"] = gene_position[\n \"Amino Acid Cut position\"\n ].fillna(gene_position[\"Amino Acid Cut position\"].mean())\n\n return gene_position\n\n\ndef get_gene_sequence(gene_name):\n try:\n gene_file = f\"../../gene_sequences/{gene_name}_sequence.txt\"\n with open(gene_file, \"rb\") as f:\n seq = f.read()\n seq = seq.replace(\"\\r\\n\", \"\")\n except ValueError:\n print(\n f\"could not find gene sequence file {gene_file}, \"\n f\"please see examples and generate one for your gene \"\n f\"as needed, with this filename\"\n )\n\n return seq\n\n\ndef get_ranks(y, thresh=0.8, prefix=\"\", flip=False):\n \"\"\"\n y should be a DataFrame with one column\n thresh is the threshold at which to call it a knock-down or not\n col_name = 'score' is only for V2 data\n flip should be FALSE for both V1 and V2!\n \"\"\"\n\n if prefix is not None:\n prefix = prefix + \"_\"\n\n # y_rank = y.apply(ranktrafo)\n y_rank = y.apply(rankdata)\n y_rank /= y_rank.max()\n\n if flip:\n y_rank = (\n 1.0 - y_rank\n ) # before this line, 1-labels where associated with low ranks, this flips it around\n # (hence the y_rank > thresh below)\n # we should NOT flip (V2), see README.txt in ./data\n\n y_rank.columns = [prefix + \"rank\"]\n y_threshold = (y_rank > thresh) * 1\n\n y_threshold.columns = [prefix + \"threshold\"]\n\n # JL: undo the log2 transform (not sure this matters?)\n y_rank_raw = (2 ** y).apply(rankdata)\n y_rank_raw /= y_rank_raw.max()\n if flip:\n y_rank_raw = 1.0 - y_rank_raw\n y_rank_raw.columns = [prefix + \"rank raw\"]\n if np.any(np.isnan(y_rank)):\n raise AssertionError(\"found NaN in ranks\")\n\n y_quantized = y_threshold.copy()\n y_quantized.columns = [prefix + \"quantized\"]\n\n return y_rank, y_rank_raw, y_threshold, y_quantized\n\n\ndef get_data(data, y_names, organism=\"human\", target_gene=None):\n \"\"\"\n this is called once for each gene (aggregating across cell types)\n y_names are cell types\n e.g. call: X_CD13, Y_CD13 = get_data(cd13, y_names=['NB4 CD13', 'TF1 CD13'])\n \"\"\"\n outputs = pd.DataFrame()\n # generate ranks for each cell type before aggregating to match what is in Doench et al\n thresh = 0.8\n for y_name in y_names: # for each cell type\n y = pd.DataFrame(data[y_name])\n # these thresholds/quantils are not used:\n y_rank, y_rank_raw, y_threshold, _ = get_ranks(y, thresh=thresh, flip=False)\n y_rank.columns = [y_name + \" rank\"]\n y_rank_raw.columns = [y_name + \" rank raw\"]\n y_threshold.columns = [y_name + \" threshold\"]\n\n outputs = pd.concat([outputs, y, y_rank, y_threshold, y_rank_raw], axis=1)\n\n # aggregated rank across cell types\n average_activity = pd.DataFrame(outputs[[y_name for y_name in y_names]].mean(1))\n average_activity.columns = [\"average activity\"]\n\n average_rank_from_avg_activity = get_ranks(\n average_activity, thresh=thresh, flip=False\n )[0]\n average_rank_from_avg_activity.columns = [\"average_rank_from_avg_activity\"]\n average_threshold_from_avg_activity = (average_rank_from_avg_activity > thresh) * 1\n average_threshold_from_avg_activity.columns = [\n \"average_threshold_from_avg_activity\"\n ]\n\n average_rank = pd.DataFrame(\n outputs[[y_name + \" rank\" for y_name in y_names]].mean(1)\n )\n average_rank.columns = [\"average rank\"]\n # higher ranks are better (when flip=False as it should be)\n average_threshold = (average_rank > thresh) * 1\n average_threshold.columns = [\"average threshold\"]\n\n # undo the log2 trafo on the reads per million, apply rank trafo right away\n average_rank_raw = pd.DataFrame(\n outputs[[y_name + \" rank raw\" for y_name in y_names]].mean(1)\n )\n average_rank_raw.columns = [\"average rank raw\"]\n outputs = pd.concat(\n [\n outputs,\n average_rank,\n average_threshold,\n average_activity,\n average_rank_raw,\n average_rank_from_avg_activity,\n average_threshold_from_avg_activity,\n ],\n axis=1,\n )\n\n # import pdb; pdb.set_trace()\n\n # sequence-specific computations\n # features = featurize_data(data)\n # strip out featurization to later\n features = pd.DataFrame(data[\"30mer\"])\n\n if organism == \"human\":\n target_gene = y_names[0].split(\" \")[1]\n\n outputs[\"Target gene\"] = target_gene\n outputs[\"Organism\"] = organism\n\n features[\"Target gene\"] = target_gene\n features[\"Organism\"] = organism\n features[\"Strand\"] = pd.DataFrame(data[\"Strand\"])\n\n return features, outputs\n\n\ndef extract_feature_from_model(method, results, split):\n model_type = results[method][3][split]\n if isinstance(model_type, ElasticNet):\n tmp_imp = results[method][3][split].coef_[:, None]\n elif isinstance(model_type, GradientBoostingRegressor):\n tmp_imp = results[method][3][split].feature_importances_[:, None]\n else:\n raise Exception(f\"need to add model {model_type} to feature extraction\")\n return tmp_imp\n\n\ndef extract_feature_from_model_sum(method, results, split, indexes):\n model_type = results[method][3][split]\n if isinstance(model_type, ElasticNet):\n tmp_imp = np.sum(results[method][3][split].coef_[indexes])\n elif isinstance(model_type, GradientBoostingRegressor):\n tmp_imp = np.sum(results[method][3][split].feature_importances_[indexes])\n else:\n raise Exception(f\"need to add model {model_type} to feature extraction\")\n return tmp_imp\n\n\ndef feature_importances(results):\n for method in results:\n feature_names = results[method][6]\n\n seen = set()\n uniq = []\n for ft in feature_names:\n if ft not in seen:\n uniq.append(ft)\n else:\n seen.add(ft)\n if seen:\n raise Exception(f\"feature name appears more than once: {seen}\")\n\n pd_order1, pi_order1, pd_order2, pi_order2, nggx = [], [], [], [], []\n for i, s in enumerate(feature_names):\n if \"False\" in s:\n continue\n elif \"_\" in s:\n nucl, _ = s.split(\"_\")\n if len(nucl) == 1:\n pd_order1.append(i)\n elif len(nucl) == 2:\n pd_order2.append(i)\n elif \"NGGX_pd.Order2\" in s:\n nggx.append(i)\n else:\n nucl = s\n if len(nucl) == 1:\n pi_order1.append(i)\n elif len(nucl) == 2:\n pi_order2.append(i)\n\n grouped_feat = {\n \"pd_order2\": pd_order2,\n \"pi_order2\": pi_order2,\n \"pd_order1\": pd_order1,\n \"pi_order1\": pi_order1,\n \"NGGX_pd.Order2\": nggx,\n }\n\n grouped_feat_ind = [grouped_feat[a] for a in grouped_feat]\n remaining_features_ind = set.difference(\n set(range(len(feature_names))), set(grouped_feat_ind)\n )\n\n for i in remaining_features_ind:\n grouped_feat[feature_names[i]] = [i]\n\n feature_importances_grouped = {}\n for k in grouped_feat:\n if not grouped_feat[k]:\n continue\n else:\n for split in results[method][3]:\n split_feat_importance = extract_feature_from_model_sum(\n method, results, split, grouped_feat[k]\n )\n if k not in feature_importances_grouped:\n feature_importances_grouped[k] = [split_feat_importance]\n else:\n feature_importances_grouped[k].append(split_feat_importance)\n\n all_split_importances = None\n for split in results[method][3]:\n\n split_feat_importance = extract_feature_from_model(method, results, split)\n\n if all_split_importances is None:\n all_split_importances = split_feat_importance.copy()\n else:\n all_split_importances = np.append(\n all_split_importances, split_feat_importance, axis=1\n )\n\n avg_importance = np.mean(all_split_importances, axis=1)[:, None]\n std_importance = np.std(all_split_importances, axis=1)[:, None]\n imp_array = np.concatenate(\n (np.array(feature_names)[:, None], avg_importance, std_importance), axis=1\n )\n\n df = pd.DataFrame(\n data=imp_array,\n columns=[\"Feature name\", \"Mean feature importance\", \"Std. Dev.\"],\n )\n df = df.convert_objects(convert_numeric=True)\n\n feature_dictionary = {\n \"pd_order2\": \"position dep. order 2 \",\n \"pd_order1\": \"position dep. order 1 \",\n \"pi_order1\": \"position ind. order 1 \",\n \"pi_order2\": \"position ind. order 2 \",\n \"5mer_end_False\": \"Tm (5mer end)\",\n \"5mer_start_False\": \"Tm (5mer start)\",\n \"Amino Acid Cut position\": \"amino acid cut position \",\n \"8mer_middle_False\": \"Tm (8mer middle)\",\n \"NGGX_pd.Order2\": \"NGGN interaction \",\n \"Tm global_False\": \"Tm (30mer)\",\n \"Percent Peptide\": \"percent peptide \",\n }\n\n for i in range(df.shape[0]):\n thisfeat = df[\"Feature name\"].iloc[i]\n if thisfeat in feature_dictionary:\n df[\"Feature name\"].iloc[i] = feature_dictionary[thisfeat]\n\n return df\n\n\nif __name__ == \"__main__\":\n # get_thirty_one_mer_data()\n\n V = \"1\"\n if V == \"1\":\n HUMAN_DATA = pd.read_excel(\"data/V1_data.xlsx\", sheetname=0, index_col=[0, 1])\n MOUSE_DATA = pd.read_excel(\"data/V1_data.xlsx\", sheetname=1, index_col=[0, 1])\n X, Y = combine_organisms(HUMAN_DATA, MOUSE_DATA)\n X.to_pickle(\"../data/X.pd\") # sequence features (i.e. inputs to prediction)\n Y.to_pickle(\n \"../data/Y.pd\"\n ) # cell-averaged ranks, plus more (i.e. possible targets for prediction)\n print(\"done writing to file\")\n elif V == \"2\":\n # this is now all in predict.py\n pass\n elif V == \"0\":\n pass\n","sub_path":"gRNAScores/azimuth/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":13961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"476640660","text":"#import the test libs to simulate the cast server\nfrom flask import Flask\nimport json\nimport time\nimport random\nfrom copy import deepcopy\n\nmode = 'normal' #normal, lowhash, online0, samehash, rejected, crash\nhashThreshold = 5850*1000\nhashrate = hashThreshold + 200000\nnumGPU = 3\n\ndata = json.loads('''{\n \"total_hash_rate\": 3718861,\n \"total_hash_rate_avg\": 3850839,\n \"pool\": {\n \"server\": \"cryptonight.usa.nicehash.com:3355\",\n \"status\": \"connected\",\n \"online\": 589,\n \"offline\": 0,\n \"reconnects\": 0,\n \"time_connected\": \"2018-03-25 21:11:17\",\n \"time_disconnected\": \"2018-03-25 21:11:17\"\n },\n \"job\": {\n \"job_number\": 10,\n \"difficulty\": 200007,\n \"running\": 26,\n \"job_time_avg\": 62.44\n },\n \"shares\": {\n \"num_accepted\": 18,\n \"num_rejected\": 0,\n \"num_invalid\": 0,\n \"num_network_fail\": 0,\n \"num_outdated\": 0,\n \"search_time_avg\": 32.56\n },\n \"devices\": [\n ]\n}''')\n\n\nstart = time.time()\n\n# Setup Flask app and app.config\napp = Flask(__name__)\n\ndef startGPUs():\n for x in range(numGPU):\n #build gpu data\n GPU = {\"device\": \"GPU\" + str(x),\n \"device_id\": str(x),\n \"hash_rate\": 1905402,\n \"hash_rate_avg\": 2044244,\n \"gpu_temperature\": 59,\n \"gpu_fan_rpm\": 3881}\n\n data['devices'].append(GPU)\n\ndef updateGPUs(crashedGPU = None):\n for x in range(numGPU):\n if x != crashedGPU:\n GPU = data['devices'][x]\n GPU['hash_rate'] = (hashrate + random.randint(-50000, 50000))/numGPU\n GPU['hash_rate_avg'] = (hashrate + random.randint(-5000, 5000))/numGPU\n\n@app.route('/')\ndef castSim():\n if mode == 'crash':\n updateGPUs(crashedGPU=numGPU-1)\n else:\n updateGPUs()\n\n if mode == 'normal' or mode == 'crash':\n #normal operation: online increases, hashrate is above minimum\n online = time.time() - start\n data['pool']['online'] = int(online)\n data['total_hash_rate'] = hashrate + random.randint(-50000, 50000)\n data['total_hash_rate_avg'] = hashrate + random.randint(-5000, 5000)\n\n elif mode == 'lowhash':\n #simulate low hashrate\n online = time.time() - start\n data['pool']['online'] = int(online)\n data['total_hash_rate'] = hashThreshold + random.randint(-50000, 50000)\n data['total_hash_rate_avg'] = hashThreshold + random.randint(-5000, 5000)\n\n elif mode == 'online0':\n #simulate online time of zero\n data['pool']['online'] = 0\n data['total_hash_rate'] = hashrate + random.randint(-50000, 50000)\n data['total_hash_rate_avg'] = hashrate + random.randint(-5000, 5000)\n\n elif mode == 'samehash':\n #simulate identical hashrates\n online = time.time() - start\n data['pool']['online'] = int(online)\n data['total_hash_rate'] = hashrate\n data['total_hash_rate_avg'] = hashrate\n \n elif mode == 'rejected':\n #simulate rejected shares\n num_invalid = data['shares']['num_invalid'] + 1\n online = time.time() - start\n data['pool']['online'] = int(online)\n data['total_hash_rate'] = hashrate + random.randint(-50000, 50000)\n data['total_hash_rate_avg'] = hashrate + random.randint(-5000, 5000)\n\n return json.dumps(data)\n\nstartGPUs()\napp.run(host='0.0.0.0', port=7777, debug=True)","sub_path":"castSim.py","file_name":"castSim.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"521189736","text":"from types import IntType, LongType\n\nfrom Structure import Structure\n\nclass IntegerStructure(Structure):\n\tsizes = {\n\t\t8: ('b', 'B', None), \n\t\t16: ('h', 'H', 'n'),\n\t\t32: ('i', 'I', 'j'),\n\t\t64: ('q', 'Q', 'p'),\n\t}\n\t\n\tdef __init__(self, *args, **kw):\n\t\tStructure.__init__(self, *args, **kw)\n\n\t\tif kw.has_key('size'):\n\t\t\tsize = kw['size']\n\t\telse:\n\t\t\tsize = 32\n\t\t\n\t\tif kw.has_key('type'):\n\t\t\ttype = kw['type']\n\t\telse:\n\t\t\ttype = 'signed'\n\t\t\n\t\tif not size in self.sizes.keys():\n\t\t\traise ValueError(\"Only supported sizes are %r not %i\" % (self.sizes.keys(),size))\n\t\tself.size = size\n\n\t\tif not type in (\"signed\", \"unsigned\", \"semisigned\"):\n\t\t\traise ValueError(\"Type can only be signed, unsigned or semisigned\")\n\t\tself.type = type\n\n\tdef check(self, value):\n\t\tif not isinstance(value, (IntType, LongType)):\n\t\t\traise ValueError(\"Value (%r) must be a number\" % value)\n\n\t\t# Do a bounds check now\n\t\tif self.type == \"signed\":\n\t\t\tmax = 2**(self.size-1)-1\n\t\t\tmin = -2**(self.size-1)\n\t\telif self.type == \"unsigned\":\n\t\t\tmax = 2**self.size-1\n\t\t\tmin = 0\n\t\telif self.type == \"semisigned\":\n\t\t\tmax = 2**self.size-2\n\t\t\tmin = -1\n\n\t\tif value < min:\n\t\t\traise ValueError(\"Value is too small! Must be bigger then %i\" % min)\n\t\t\n\t\tif value > max:\n\t\t\traise ValueError(\"Value is too big! Must be smaller then %i\" % max)\n\t\t\n\t\treturn True\n\t\t\n\tdef length(self, value):\n\t\treturn self.size / 8\n\n\tdef xstruct(self):\n\t\tif self.type == \"signed\":\n\t\t\txstruct = self.sizes[self.size][0]\n\t\telif self.type == \"unsigned\":\n\t\t\txstruct = self.sizes[self.size][1]\n\t\telif self.type == \"semisigned\":\n\t\t\txstruct = self.sizes[self.size][2]\n\t\treturn xstruct\n\txstruct = property(xstruct)\n\n","sub_path":"tp/netlib/structures/Integer.py","file_name":"Integer.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"73212526","text":"# Copyright 2016 VMware, Inc.\n#\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron.api.rpc.callbacks import events as callbacks_events\nfrom neutron import context as n_context\nfrom neutron import manager\nfrom neutron.objects.qos import policy as qos_policy\nfrom neutron.objects.qos import rule as rule_object\nfrom neutron.plugins.common import constants\n\nfrom oslo_log import log as logging\n\nfrom vmware_nsx.db import db as nsx_db\n\nLOG = logging.getLogger(__name__)\n\n\nclass NsxVQosRule(object):\n\n def __init__(self, context=None, qos_policy_id=None):\n super(NsxVQosRule, self).__init__()\n\n self._qos_plugin = None\n\n # Data structure to hold the NSX-V representation\n # of the neutron QoS Bandwidth rule\n self.bandwidthEnabled = False\n self.averageBandwidth = 0\n self.peakBandwidth = 0\n self.burstSize = 0\n\n # And data for the DSCP marking rule\n self.dscpMarkEnabled = False\n self.dscpMarkValue = 0\n\n if qos_policy_id is not None:\n self._init_from_policy_id(context, qos_policy_id)\n\n def _get_qos_plugin(self):\n if not self._qos_plugin:\n loaded_plugins = manager.NeutronManager.get_service_plugins()\n self._qos_plugin = loaded_plugins[constants.QOS]\n return self._qos_plugin\n\n # init the nsx_v qos data (outShapingPolicy) from a neutron qos policy\n def _init_from_policy_id(self, context, qos_policy_id):\n self.bandwidthEnabled = False\n self.dscpMarkEnabled = False\n\n # read the neutron policy restrictions\n if qos_policy_id is not None:\n plugin = self._get_qos_plugin()\n rules_obj = plugin.get_policies(\n context, qos_policy_id)\n if rules_obj is not None and len(rules_obj) > 0:\n for rule_obj in rules_obj:\n if isinstance(rule_obj, rule_object.QosBandwidthLimitRule):\n self.bandwidthEnabled = True\n # averageBandwidth: kbps (neutron) -> bps (nsxv)\n self.averageBandwidth = rule_obj['max_kbps'] * 1024\n # peakBandwidth: the same as the average value\n # because the neutron qos configuration supports\n # only 1 value\n self.peakBandwidth = self.averageBandwidth\n # burstSize: kbps (neutron) -> Bytes (nsxv)\n self.burstSize = rule_obj['max_burst_kbps'] * 128\n elif isinstance(rule_obj, rule_object.QosDscpMarkingRule):\n self.dscpMarkEnabled = True\n self.dscpMarkValue = rule_obj['dscp_mark']\n\n return self\n\n\ndef handle_qos_notification(policy_obj, event_type, dvs):\n # Check if QoS policy rule was created/deleted/updated\n # Only if the policy rule was updated, we need to update the dvs\n if (event_type == callbacks_events.UPDATED and\n hasattr(policy_obj, \"rules\")):\n\n # Reload the policy as admin so we will have a context\n context = n_context.get_admin_context()\n admin_policy = qos_policy.QosPolicy.get_object(\n context, id=policy_obj.id)\n # get all the bound networks of this policy\n networks = admin_policy.get_bound_networks()\n qos_rule = NsxVQosRule(context=context,\n qos_policy_id=policy_obj.id)\n\n for net_id in networks:\n # update the new bw limitations for this network\n net_morefs = nsx_db.get_nsx_switch_ids(context.session, net_id)\n for moref in net_morefs:\n # update the qos restrictions of the network\n dvs.update_port_groups_config(\n net_id,\n moref,\n dvs.update_port_group_spec_qos,\n qos_rule)\n","sub_path":"vmware_nsx/services/qos/nsx_v/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"440734454","text":"from dataclasses import dataclass, field\nfrom typing import Optional\n\n__NAMESPACE__ = \"http://autosar.org/schema/r4.0\"\n\n\n@dataclass\nclass AnyServiceInstanceId:\n \"\"\"This is a positive integer or the literal ALL (the value ANY is technically\n supported but deprecated) which can be denoted in decimal, octal and\n hexadecimal.\n\n The value is between 0 and 4294967295.\n\n :ivar value:\n :ivar s: Checksum calculated by the user's tool environment for an\n ArObject. May be used in an own tool environment to determine if\n an ArObject has changed. The checksum has no semantic meaning\n for an AUTOSAR model and there is no requirement for AUTOSAR\n tools to manage the checksum.\n :ivar t: Timestamp calculated by the user's tool environment for an\n ArObject. May be used in an own tool environment to determine\n the last change of an ArObject. The timestamp has no semantic\n meaning for an AUTOSAR model and there is no requirement for\n AUTOSAR tools to manage the timestamp.\n \"\"\"\n class Meta:\n name = \"ANY-SERVICE-INSTANCE-ID\"\n\n value: str = field(\n default=\"\",\n metadata={\n \"required\": True,\n \"pattern\": r\"[1-9][0-9]*|0[xX][0-9a-fA-F]+|0[0-7]*|0[bB][0-1]+|ANY|ALL\",\n }\n )\n s: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"S\",\n \"type\": \"Attribute\",\n }\n )\n t: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"T\",\n \"type\": \"Attribute\",\n \"pattern\": r\"([0-9]{4}-[0-9]{2}-[0-9]{2})(T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|([+\\-][0-9]{2}:[0-9]{2})))?\",\n }\n )\n","sub_path":"autosar/models/any_service_instance_id.py","file_name":"any_service_instance_id.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"381415431","text":"#OOD 面向对象对设计\nfrom random import randint\nimport time\n\nclass Tiger:\n # 静态属性\n classname = 'tiger'\n # 实例属性\n def __init__(self, weight = 200, asknum = 0,eatnum1 = 0, eatnum2 = 0):\n self.weight = weight\n self.asknum = asknum\n self.eatnum1 = eatnum1\n self.eatnum2 = eatnum2\n # 实例方法\n def roar(self):\n print('我是老虎')\n self.weight -= 5\n self.asknum += 1\n def eat(self,a):\n if a == 'meet':\n self.weight += 10\n self.eatnum1 += 1\n print('喂养成功!!!')\n elif a == 'grass':\n self.weight -= 10\n self.eatnum2 +=1\n print('我不吃草')\n else:\n print('无法识别食物,进入下一个房间')\n\nclass Sheep:\n classname = 'shee'\n def __init__(self, weight = 100, asknum = 0,eatnum1 =0, eatnum2=0):\n self.weight = weight\n self.asknum = asknum\n self.eatnum1 = eatnum1\n self.eatnum2 = eatnum2\n def roar(self):\n print('我是羊')\n self.asknum += 1\n self.weight -= 5\n def eat(self,a):\n if a == 'meet':\n self.weight -= 10\n self.eatnum1 += 1\n print('我不吃肉')\n elif a == 'grass':\n self.weight += 10\n self.eatnum2 += 1\n print('喂养成功!!!')\n else:\n print('无法识别食物,进入下一个房间')\n\n\nclass Room:\n def __init__(self,num,animal):\n self.num = num\n self.animal = animal\n\n\n\n# 开始游戏\nprint('''【游戏规则:\n每个房间随机分配一只动物(老虎或羊)\n每个房间每轮次仅可操作一次\n游戏过程中可询问房间内的动物,每询问一次,该房间动物的体重减少5斤\n输入食物进行投喂,老虎吃meet,羊吃grass\n喂养正确,则该房间动物的体重增加10斤\n喂养错误,则该房间动物的体重减少10斤\n游戏过程中:\n输入:a,效果:查询该房间的动物\n输入:n,效果:结束游戏\n输入其他内容,效果:喂养动物】\n''')\nc = True\na = input('是否开始游戏(y开始游戏,n结束游戏):')\nif a.lower() == 'y':\n print('.............游戏开始!!!............')\n # 设置倒计时\n a = int(time.time()) # 开始游戏前的时间戳(秒)\n b = 5 # 倒计时长(秒)\n print(f'倒计时{b}秒开始')\n # 分配动物\n rooms = []\n for i in range(1, 11):\n if randint(0, 1):\n animal = Tiger()\n else:\n animal = Sheep()\n room = Room(i, animal)\n rooms.append(room)\n # 进入游戏\n while c:\n for room in rooms:\n x =int(time.time()) #进入每一个房间时的时间戳(秒)\n if x >= a + b:\n print('\\n时间到')\n c = False\n break\n print(f'\\n喂养房间{room.num}的动物')\n ask = input('输入a查询该房间的动物,输入食物进行喂养(meet or grass),输入n结束游戏。\\n请输入:')\n if ask.lower() == 'a':\n room.animal.roar()\n elif ask.lower()=='n':\n c = False\n break\n else:\n room.animal.eat(ask.lower())#给动物喂食\n print('.............游戏结束!!!............')\n # 输出喂养结果\n for room in rooms:\n print(f'房间{room.num:>2}是:{room.animal.classname:<5},体重:{room.animal.weight:4}\\\n \\t询问次数:{room.animal.asknum:<2}\\t喂肉次数:{room.animal.eatnum1:<2}\\t喂草次数:{room.animal.eatnum2:<2}')\nelse:\n print('未进行游戏')\n\n\n\n\n\n","sub_path":"learnPython/tmp/songqin/game01.py","file_name":"game01.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"465815892","text":"import logging\nimport sys\nfrom logging.handlers import RotatingFileHandler\n\nimport dispatch.exceptions as exceptions\n\n\n\n# Configure logging\nlog_format = logging.Formatter(\"%(asctime)s [%(name)s.%(funcName)s():%(lineno)d]\\n\\t%(levelname)8s: %(message)s\\n\")\n\nlogger = logging.getLogger(\"dispatch\")\n\nstderr_handler = logging.StreamHandler()\nstderr_handler.setLevel(logging.DEBUG)\nstderr_handler.setFormatter(log_format)\nlogger.addHandler(stderr_handler)\n\nfile_handler = RotatingFileHandler(\"dispatch.log\", maxBytes=10000, backupCount=2)\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(log_format)\nlogger.addHandler(file_handler)\n\nlogger.setLevel(logging.DEBUG)\n\nlogger.info(\"Logging Configured at Level {}\".format(logger.getEffectiveLevel()))\n\n\ndef parse_arguments():\n \"\"\"Examples:\n $ dispatch ([host:]hostname | [hostfile:]file_path)+ [action:](get|set|create|delete) ([parameter:]parameter[=set_value])+ [option+]\n $ dispatch switch01 get ntp.client.skew\n $ dispatch switch01 switch02 get ntp.client.skew --output=json\n $ dispatch switch01 get interfaces.name network.interface.description network.interface.name\n -- switch01\n network.interface.description = \"Connected to the WAN\"\n network.interface.name = \"Ethernet1/1\"\n \"\"\"\n\n def find_action_word(args):\n pattern = \"^(?:action:)?(get|set|create|delete)$\"\n import re\n for i, word in enumerate(args):\n if re.match(pattern, word, re.IGNORECASE):\n return i\n\n n = find_action_word(sys.argv)\n if n is None:\n raise exceptions.DispatchSyntaxException(\"Could not find any action word: get, set, create, delete\")\n hosts = sys.argv[1:n] # Get the host list before the action word.\n parameters_and_options = sys.argv[n:] # Get the list of parameters after the action word.\n\n\n\n\n\n\n","sub_path":"dispatch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"6232840","text":"import chainer\nfrom chainer import cuda, Variable\nimport chainer.functions as F\nimport chainer.links as L\nimport numpy as np\n\nimport utils\n\nclass RNNLM(chainer.Chain):\n\n def __init__(self, vocab, word_dim, state_dim, BOS, EOS):\n \"\"\"\n :type vocab: {str: int}\n :type word_dim: int\n :type state_dim: int\n :type BOS: str\n :type EOS: str\n \"\"\"\n self.vocab = vocab\n self.vocab_size = len(self.vocab)\n self.ivocab = {i:w for w,i in self.vocab.items()}\n self.word_dim = word_dim\n self.state_dim = state_dim\n self.BOS = BOS\n self.EOS = EOS\n self.BOS_ID = self.vocab[self.BOS]\n self.EOS_ID = self.vocab[self.EOS]\n\n links = {}\n # Word embedding\n links[\"embed\"] = L.EmbedID(self.vocab_size, self.word_dim, ignore_label=-1)\n # RNN\n links[\"W_upd\"] = L.Linear(self.word_dim, self.state_dim)\n links[\"U_upd\"] = L.Linear(self.state_dim, self.state_dim, nobias=True)\n # Output\n links[\"W_out\"] = L.Linear(self.state_dim, self.vocab_size)\n super(RNNLM, self).__init__(**links)\n\n def preprocess(self, batch_words):\n \"\"\"\n :type batch_words: list of list of str\n :rtype: list of Variable(shape=(batch_size,), dtype=np.int32)\n \"\"\"\n batch_words = [[self.vocab[w] for w in words] for words in batch_words] # list of list of int\n batch_words = utils.padding(batch_words, head=True, with_mask=False) # (batch_size, max_length)\n seq_batch_word = utils.convert_ndarray_to_variable(batch_words, seq=True) # max_length * (batch_size,)\n return seq_batch_word\n\n def forward(self, seq_batch_word):\n \"\"\"\n :type seq_batch_word: list of Variable(shape=(batch_size,), dtype=np.int32)\n :rtype: list of Variable(batch_size, vocab_size)\n \"\"\"\n batch_size = seq_batch_word[0].shape[0]\n\n # Initialization\n hidden_state, bos = self.make_initial_variables(batch_size=batch_size) # (batch_size, state_dim), (batch_size, 1)\n\n # Recurret computation\n seq_batch_logits = [] # list of Variable(shape=(batch_size, vocab_size), dtype=np.float32)\n seq_batch_inputword = [bos] + seq_batch_word[:-1] # max_length * (batch_size,)\n for batch_inputword in seq_batch_inputword:\n hidden_state = self.update_state(batch_inputword, hidden_state) # (batch_size, state_dim)\n batch_logits = self.predict_next_word(hidden_state) # (batch_size, vocab_size)\n seq_batch_logits.append(batch_logits)\n\n return seq_batch_logits\n\n def generate_sentence(self, initial_words):\n \"\"\"\n :type initial_words: list of str\n :rtype: list of str\n \"\"\"\n assert len(initial_words) > 0\n initial_words = self.preprocess([initial_words]) # 2 * (1,)\n\n # Initialization\n hidden_state, bos = self.make_initial_variables(batch_size=1) # (1, state_dim), (1, 1)\n\n seq_outputword = [] # list of str\n\n inputword = bos # (1,)\n for step in range(len(initial_words)):\n # Predict the next word\n hidden_state = self.update_state(inputword, hidden_state) # (1, state_dim)\n # NOTE that, in this loop, we are interested in only updating hidden states and ignore the predicted words.\n outputword = initial_words[step] # NOTE Variable(shape=(1,), dtype=np.int32)\n # Recode\n seq_outputword.append(int(cuda.to_cpu(outputword.data)))\n # Prepare for the next step\n inputword = outputword # (1,)\n\n for _ in range(50):\n # Predict the next word\n hidden_state = self.update_state(inputword, hidden_state) # (1, state_dim)\n logits = self.predict_next_word(hidden_state) # (1, vocab_size)\n logits = cuda.to_cpu(logits.data) # (1, vocab_size)\n outputword = np.argmax(logits, axis=1) # NOTE numpy.ndarray(shape=(1,), dtype=np.int32)\n # Recode\n seq_outputword.append(int(outputword))\n # Prepare for the next step\n inputword = utils.convert_ndarray_to_variable(outputword, seq=False) # (1,)\n\n if outputword[0] == self.EOS_ID:\n break\n\n seq_outputword = [self.ivocab[w] for w in seq_outputword]\n return seq_outputword\n\n def make_initial_variables(self, batch_size):\n \"\"\"\n :type batch_size: int\n :rtype: Variable(shape=(batch_size, state_dim), dtype=np.float32), Variable(shape=(batch_size,1), dtype=np.int32)\n \"\"\"\n hidden_state = Variable(cuda.cupy.zeros((batch_size, self.state_dim), dtype=np.float32)) # (batch_size, state_dim)\n bos = Variable(cuda.cupy.full((batch_size,1), self.BOS_ID, dtype=np.int32)) # (batch_size, 1)\n return hidden_state, bos\n\n def update_state(self, inputwords, hidden_state):\n \"\"\"\n :type inputwords: Variable(shape=(batch_size,), dtype=np.int32)\n :type hidden_state: Variable(shape=(batch_size, state_dim), dtype=np.float32)\n :rtype: Variable(shape=(batch_size, state_dim), dtype=np.float32)\n \"\"\"\n word_vectors = self.embed(inputwords) # (batch_size, word_dim)\n hidden_state = F.tanh(self.W_upd(word_vectors) + self.U_upd(hidden_state)) # (batch_size, state_dim)\n return hidden_state\n\n def predict_next_word(self, hidden_state):\n \"\"\"\n :type hidden_state: Variable(shape=(batch_size, state_dim), dtype=np.float32)\n :rtype: Variable(shape=(batch_size, vocab_size), dtype=np.float32)\n \"\"\"\n logits = self.W_out(hidden_state)\n return logits\n","sub_path":"models/rnnlm.py","file_name":"rnnlm.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"333638902","text":"\"\"\"\n @Author:DarknessFor9\n @DateTime:7/8/19 5:04 PM\n\"\"\"\nfrom re import match\n\"\"\"\n1-5.根据读者当地的格式,匹配街道地址(使你的正则表达式足够通用,来匹配任意数量的街道单词,包括类型名称).例如,美国街道地址使用如下格式:1180\nBordeauxDrive.使你的正则表达式足够灵活,以支持多单词的街道名称,如3120 De La Cruz Boulevard.\n\"\"\"\npattern = r'\\d{4}(\\s\\w+)+'\n\ncontent = {\n \"3120 De La Cruz Boulevard\",\n \"251 john cruz boston\",\n \"5210 jio jo django python\"\n}\n\nfor i in content:\n result = match(pattern, i)\n if result is not None:\n print(result.group())\n","sub_path":"code/ReModule/practice/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"46070903","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport time\nimport os\nfrom pathlib import Path\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n\n\n\ndef weight_variable(shape,astype):\n initial = tf.truncated_normal(shape, stddev=0.01, dtype = astype)\n return tf.Variable(initial, dtype = astype)\n\ndef bias_variable(shape,astype):\n initial = tf.constant(0.0, shape=shape, dtype = astype)\n return tf.Variable(initial, dtype = astype)\n\ndef nn_example(e, b, data_type):\n learning_rate = 0.5\n epochs = e\n batch_size = b\n input_feature_count = 784\n out_classes = 10\n data_type = data_type\n\n # Neural network hidden layer variables\n h1 = 50\n h2 = 20\n\n # declare the training data placeholders\n # input x - for 28 x 28 pixels = 784\n x = tf.placeholder(data_type, [None, input_feature_count])\n # now declare the output data placeholder - 10 digits\n y = tf.placeholder(data_type, [None, out_classes])\n\n # build the network\n keep_prob_input = tf.placeholder(data_type)\n x_drop = tf.nn.dropout(x, keep_prob=keep_prob_input)\n\n W_fc1 = weight_variable([input_feature_count, h1], data_type)\n b_fc1 = bias_variable([h1], data_type)\n h_fc1 = tf.nn.relu(tf.matmul(x_drop, W_fc1) + b_fc1)\n\n keep_prob = tf.placeholder(data_type)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n W_fc2 = weight_variable([h1, h2],data_type)\n b_fc2 = bias_variable([h2], data_type)\n h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob)\n\n W_fc3 = weight_variable([h2, out_classes],data_type)\n b_fc3 = bias_variable([out_classes], data_type)\n\n # now calculate the hidden layer output - in this case, let's use a softmax activated\n # output layer\n y_ = tf.nn.softmax(tf.matmul(h_fc2_drop, W_fc3) + b_fc3)\n\n # now let's define the cost function which we are going to train the model on\n y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)\n cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped)\n + (1 - y) * tf.log(1 - y_clipped), axis=1))\n\n # add an optimiser\n optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)\n\n # finally setup the initialisation operator\n init_op = tf.global_variables_initializer()\n\n # define an accuracy assessment operation\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, data_type))\n\n # add a summary to store the accuracy\n accuracy_sum = tf.summary.scalar('accuracy', accuracy)\n\n saver = tf.train.Saver()\n\n merged = tf.summary.merge([accuracy_sum])\n writer = tf.summary.FileWriter(r'C:\\Users\\anant\\dev\\repos\\HPA')\n\n test_accuracy = 0\n # start the session\n with tf.Session() as sess:\n # initialise the variables\n sess.run(init_op)\n total_batch = int(len(mnist.train.labels) / batch_size)\n start_time = time.time()\n for epoch in range(max(epochs)+1):\n avg_cost = 0\n train_acc = 0\n for i in range(total_batch):\n batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)\n train_acc,_, c = sess.run([accuracy, optimiser, cross_entropy], feed_dict={x: batch_x, y: batch_y, keep_prob_input: 1.0, keep_prob: 1.0})\n avg_cost += c / total_batch\n arr_accuracy = [];\n time_elapsed = [];\n nw_size = [];\n if(epoch in epochs):\n elapsed = time.time() - start_time\n filepath = \"D:\\\\UCI\\\\HPA_Project\\\\weights_data\\\\epoch_\"+ str(epoch)+ '_batch_' +str(batch_size)\n save_path = saver.save(sess, filepath)\n mfilepath = filepath + \".data-00000-of-00001\"\n file = Path(mfilepath)\n size = file.stat().st_size\n test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob_input: 1.0, keep_prob: 1.0})\n arr_accuracy.append(test_accuracy)\n time_elapsed.append(elapsed)\n nw_size.append(size)\n print(epoch, b, test_accuracy, elapsed)\n return arr_accuracy, time_elapsed, nw_size\n\nif __name__ == \"__main__\":\n data_type = tf.float32\n batch_size = [50, 100, 200, 500, 1000]\n epochs = [5,10, 15, 20] #, 30, 50] #, 80, 100, 150, 200, 300, 500, 700, 1000]\n num_epochs = len(epochs)\n num_bsize = len(batch_size)\n accuracy_mat = [[] for i in range(num_bsize)]\n elapsed_time = [[] for i in range(num_bsize)]\n size_mat = [[] for i in range(num_bsize)]\n for j, b in enumerate(batch_size):\n accuracy_mat[j], elapsed_time[j], size_mat[j] = nn_example(epochs, b, data_type)\n print()\n","sub_path":"HPA_final.py","file_name":"HPA_final.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"7374401","text":"'''\r\nCreated on Jul 26, 2018\r\n\r\n@author: yiz\r\n'''\r\nfrom com.config.config_core import toDict\r\nfrom random import randint\r\n\r\n_global_conf = {\r\n 'storage': 'c:\\\\rgs_ _workFlow',\r\n \r\n# 'prot': 'http',\r\n# 'ip': '127.0.0.1',\r\n# 'port': '8980',\r\n# 'webapp': '/ ',\r\n \r\n# 'prot': 'https',\r\n# 'ip': '127.0.0.1',\r\n# 'port': '6443',\r\n# 'webapp': '',\r\n \r\n 'prot': 'http',\r\n 'ip': ' ',\r\n 'port': '37042',\r\n 'webapp': '/ ',\r\n \r\n 'use_proxy': False, \r\n 'softwareId': '200 ', \r\n 'uniqueid' : 'F001- 7',\r\n 'BetPerPattern': '1',\r\n 'PatternsBet': '75',\r\n 'browser': 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s',\r\n 'ant_path': 'C:\\\\ \\\\tools\\\\apache-ant-1.9.2\\\\bin\\\\ant.bat',\r\n 'tomcat': 'C:\\\\green-install\\\\tomcat-RGSserver-7.0.78-3\\\\', \r\n #'tomcat- -workable\\\\',\r\n 'tomcat_start': 'startup.bat',\r\n 'tomcat_stop': 'shutdown.bat',\r\n 'ant_build_dir': 'D:\\\\ \\\\build\\\\',\r\n 'ant_build_social': 'D:\\\\ \\\\ \\\\',\r\n 'paytable_dir': ' ',\r\n 'histo_ids': [\"200- -001\"],\r\n 'histo_times': '100000000',\r\n 'histo_cpus': '10'\r\n }\r\n\r\n_picker_conf = {\r\n 'pickerStages':\r\n [\r\n {\r\n 'stageName': 'FreeSpinPicker',\r\n 'cells': [\"L0C0R0\", \"L0C1R0\", \"L0C2R0\", \"L0C3R0\", \"L0C4R0\"],\r\n 'start_idx': randint(0, 4)\r\n }, \r\n {\r\n 'stageName': 'MlpPicker',\r\n 'cells': [\"L0C0R0\", \"L0C1R0\", \"L0C2R0\", \"L0C3R0\", \"L0C4R0\", \"L0C5R0\", \"L0C6R0\", \"L0C7R0\", \"L0C8R0\", \"L0C9R0\", \"L0C10R0\", \"L0C11R0\"],\r\n 'start_idx': randint(0, 11) \r\n }\r\n ]\r\n }\r\n\r\nglobal_conf = toDict(_global_conf)\r\npicker_conf = toDict(_picker_conf)\r\n\r\nif __name__ == \"__main__\":\r\n print(picker_conf)\r\n","sub_path":"com/config/config_global.py","file_name":"config_global.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"246618963","text":"# untie执行用例列表\r\n\r\n# shop执行用例列表\r\ndef case_list():\r\n alltestnames = [\r\n '场景一-奶茶店模式.air',\r\n '场景二-反结账.air',\r\n '场景二-反结账-继续点餐.air',\r\n '场景三-点餐-下单-退单.air',\r\n '场景三-点餐-单品调价.air',\r\n '场景三-点餐-整单折扣.air',\r\n '场景四-正餐-移台-结账-清台.air',\r\n '场景五-现金-找零.air',\r\n '场景六-混合支付.air',\r\n '场景八-正餐-复制桌台.air',\r\n '会员-充值-退款.air',\r\n '会员-物理卡注册-注销.air',\r\n '会员-会员价.air',\r\n '场景九-属性打折开启.air',\r\n '场景九-属性打折开启-点餐-单品调价.air',\r\n '场景九-属性打折开启-点餐-整单折扣.air',\r\n '场景九-属性打折关闭.air',\r\n '场景十-商品临时改价开启.air',\r\n '场景十-商品临时改价开启-点餐-临时改价.air',\r\n '场景十-商品临时改价关闭.air',\r\n '场景十一-自动抹零开启.air',\r\n '场景十一-自动抹零-现金-找零.air',\r\n '场景十一-自动抹零关闭.air',\r\n '场景十二-支持交接班开启.air',\r\n '场景十二-支持交接班关闭.air',\r\n '场景十三-预结即锁桌开启.air',\r\n '场景十三-预结即锁桌开启-正餐-预结锁桌台.air',\r\n '场景十三-预结即锁桌关闭.air',\r\n '场景十四-自动清台开启.air',\r\n '场景十四-自动清台-正餐-下单.air',\r\n '场景十四-自动清台关闭.air',\r\n '报表统计.air',\r\n # '场景七-正餐循环点餐.air',\r\n # 'test.air',\r\n ]\r\n return alltestnames\r\n\r\n\r\n# 目前存在问题alltestnames有一个用例,设置循环多次会报错,进程被占用\r\ndef loop_num():\r\n loop_num = 1\r\n return loop_num\r\n","sub_path":"AirtestCase/SmartPOS-New/allcase_list.py","file_name":"allcase_list.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"473982589","text":"# Définition d'un client réseau rudimentaire\n# Ce client dialogue avec un serveur ad hoc\n \nimport socket, sys\n \n#HOST = socket.gethostbyname(socket.gethostname())\nHOST = \"127.0.0.1\"\nPORT = 50001\n\n\n# 1) création du socket \nmySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n# 2) envoi d'une requête de connexion au serveur \ntry:\n mySocket.connect((HOST, PORT))\nexcept socket.error:\n print(\"La connexion a échoué.\")\n sys.exit()\nprint(\"Connexion établie avec le serveur.\")\n \n# 3) Dialogue avec le serveur :\n \nwhile 1:\n\n msgServeur = mySocket.recv(1024).decode(\"Utf8\")\n print(\"S > {}\".format(msgServeur))\n\n msgClient = input(\"Vous > \")\n\n if msgClient.upper() == \"FIN\":\n break\n\n mySocket.sendall(msgClient.encode(\"Utf8\"))\n \n# 4) Fermeture de la connexion :\nprint(\"Connexion interrompue.\")\nmySocket.close()","sub_path":"Internet et Bases de Données/client_1.py","file_name":"client_1.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"167946862","text":"from scrapy import Spider\nfrom scrapy.http import Request\n\nfrom firmware.items import FirmwareImage\nfrom firmware.loader import FirmwareLoader\n\nimport urllib.request, urllib.parse, urllib.error\n\n\nclass FoscamSpider(Spider):\n name = \"foscam\"\n allowed_domains = [\"foscam.com\"]\n start_urls = [\n \"http://www.foscam.com/downloads/firmware_details.html\"]\n\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url, cookies={'loginEmail': \"@.com\"}, dont_filter=True)\n\n def parse(self, response):\n # bit ugly but it works :-)\n if \"pid\" not in response.meta:\n for pid in range(0, 1000):\n yield Request(\n url=urllib.parse.urljoin(response.url, \"firmware_details.html?id=%s\" % pid),\n meta={\"pid\": pid},\n headers={\"Referer\": response.url,\n \"X-Requested-With\": \"XMLHttpRequest\"},\n callback=self.parse)\n else:\n for product in response.xpath(\"//div[@class='download_list_icon']/span/text()\").extract():\n prods = response.xpath(\"//table[@class='down_table']//tr\")\n # print(prods)\n # skip the table header\n for p in [x for x in prods[1:]]:\n version = p.xpath('td[1]//text()').extract_first()\n # skip partial versions\n if '_p' in version:\n continue\n item = FirmwareLoader(item=FirmwareImage(), response=response)\n item.add_value(\"version\", version)\n item.add_value(\"url\", 'https://www.foscam.com' + p.xpath('td[6]//a/@href').extract_first())\n item.add_value(\"product\", product)\n item.add_value(\"vendor\", self.name)\n yield item.load_item()\n","sub_path":"firmware/spiders/foscam.py","file_name":"foscam.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"163605208","text":"from autobahn.asyncio.wamp import ApplicationRunner, ApplicationSession\nimport requests\nimport asyncio\nimport json\nimport logging\nfrom autobahn.wamp.types import RegisterOptions\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\nimport os\nimport uuid\n\nclass SessionSet(OrderedDict):\n def __init__(self, engine):\n self._engine = engine\n\n def add(self):\n session = self._engine.make_session()\n\n ssn = session.__enter__()\n ssn['__context__'] = session\n\n self[ssn['name']] = ssn\n\n return ssn\n\n def __enter__(self):\n return self\n\n def __exit__(self, exctyp, excval, exctbk):\n exceptions = []\n for session in self.values():\n try:\n session['__context__'].__exit__(exctyp, excval, exctbk)\n except Exception as e:\n exceptions.append(e)\n\n if exceptions:\n raise RuntimeError(exceptions)\n\ndef make_session_set(engine):\n sessions = SessionSet(engine)\n try:\n yield sessions\n finally:\n sessions.clear()\n\nclass ProcessorResource():\n def __init__(self, engine, config):\n self._engine = engine\n self._config = config\n\n async def post(self, modules, metadata, session):\n processors = {}\n for module, content in modules.items():\n processors[module] = content.encode('utf-8')\n\n logging.warn(metadata)\n\n return self._engine.add_processor(processors, metadata, session)\n\nclass DataResource():\n def __init__(self, engine, config):\n self._engine = engine\n self._config = config\n\n async def post(self, filename, content, redirect, session=None):\n logging.warn(_(\"Data posted\"))\n logging.warn(redirect)\n if redirect:\n r = requests.get(content, stream=True)\n if r.status_code != 200:\n raise RuntimeError(_(\"Could not retrieve supplementary data: %d\") % r.status_code)\n\n logging.warn(_(\"Downloading %s\") % content)\n content = ''\n for chunk in r.iter_content(chunk_size=1024):\n content += chunk.decode('utf-8')\n\n return self._engine.add_data(filename, content.encode('utf-8'), redirect, session)\n\nclass ReportResource():\n def __init__(self, engine, config):\n self._engine = engine\n self._config = config\n\n async def get(self, session):\n await session['monitor_output']\n\n results = await self._engine.get_output(session)\n result_string = json.dumps(results)\n\n if len(result_string) > self._config['report']['max-length-chars']:\n raise RuntimeError(_(\"Report is too long: %d characters\") % len(results))\n\n return result_string\n\nclass DoorstepComponent(ApplicationSession):\n def __init__(self, engine, sessions, config, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._id = 'ltlwc-%s' % str(uuid.uuid4())\n self._engine = engine\n self._sessions = sessions\n self._config = config\n\n self._resource_processor = ProcessorResource(self._engine, self._config)\n self._resource_data = DataResource(self._engine, self._config)\n self._resource_report = ReportResource(self._engine, self._config)\n\n def get_session(self, name):\n return self._sessions[name]\n\n def make_session(self):\n return self._sessions.add()\n\n async def wrap_register(self, endpoint, callback):\n uri = 'com.ltldoorstep.{server}.{endpoint}'.format(server=self._id, endpoint=endpoint)\n\n async def _routine(session, *args, **kwargs):\n return await callback(*args, session=self.get_session(session), **kwargs)\n\n return await self.register(_routine, uri)\n\n async def onJoin(self, details):\n async def get_session_pair():\n session = self.make_session()\n print(_(\"Engaging for session %s\") % session['name'])\n\n # Kick off observer coro\n __, monitor_output = await self._engine.monitor_pipeline(session)\n monitor_output = asyncio.ensure_future(monitor_output)\n\n def output_results(output):\n logging.warn('outputting')\n return self.publish(\n 'com.ltldoorstep.event_result',\n self._id,\n session['name']\n )\n\n monitor_output.add_done_callback(output_results)\n\n session['monitor_output'] = monitor_output\n\n return (self._id, session['name'])\n\n await self.register(\n get_session_pair,\n 'com.ltldoorstep.engage',\n RegisterOptions(invoke='roundrobin')\n )\n await self.wrap_register('processor.post', self._resource_processor.post)\n await self.wrap_register('data.post', self._resource_data.post)\n await self.wrap_register('report.get', self._resource_report.get)\n\n def onDisconnect(self):\n logging.error(_(\"Disconnected from WAMP router\"))\n asyncio.get_event_loop().stop()\n\n\ndef launch_wamp(engine, router='localhost:8080', config={}):\n runner = ApplicationRunner(url=('ws://%s/ws' % router), realm='realm1')\n\n with SessionSet(engine) as sessions:\n runner.run(lambda *args, **kwargs: DoorstepComponent(engine, sessions, config, *args, **kwargs))\n","sub_path":"src/ltldoorstep/wamp_server.py","file_name":"wamp_server.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"591873680","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 9 19:13:11 2016\n\n@author: huisu\n\"\"\"\n\ndef solution(n):\n numset = set([])\n if n == 0:\n return 'INSOMNIA'\n count = 1\n while len(numset)!=10:\n strn = str(n*count)\n for i in strn:\n if i not in numset:\n numset.add(i) \n count += 1\n return strn\n\nif __name__ == '__main__':\n fp = open('A-large.in')\n n = fp.readline()\n f = open(\"output\", 'w+') \n for i in range(int(n)):\n line = fp.readline()\n f.write(\"Case #\"+str(i+1)+\": \"+str(solution(int(line)))+'\\n')\n fp.close()\n f.close()\n \n \n ","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_diandiansu_Couting Sheep.py","file_name":"16_0_1_diandiansu_Couting Sheep.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"301508084","text":"#!/usr/bin/env python3\nimport time\nfrom multiprocessing import Value, Process, Lock\n\ndef func(val, lock):\n for i in range(50):\n with lock:\n val.value += 1\n time.sleep(0.01)\n\nif __name__ == '__main__':\n val = Value('i', 0)\n lock = Lock()\n procs = [Process(target = func, args = (val, lock)) for i in range(10)]\n for p in procs:\n p.start()\n for p in procs:\n p.join()\n print(val.value)\n","sub_path":"w1/basic/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"222017174","text":"from os.path import dirname, realpath, join\n\nfrom eme.entities import load_settings\nfrom eme.websocket import WebsocketApp\nfrom wsapp.services import auth, startup\n\n\n\nclass MyWebsocketServer(WebsocketApp):\n\n def __init__(self):\n # eme/examples/simple_website is the working directory.\n script_path = dirname(realpath(__file__))\n conf = load_settings(join(script_path, 'config.ini'))\n\n super().__init__(conf, script_path)\n\n startup.init(self)\n auth.init(self, conf['auth'])\n\n\nif __name__ == \"__main__\":\n app = MyWebsocketServer()\n app.start()\n","sub_path":"bundle/wsapp/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"460692312","text":"import asyncio\nfrom Utils import *\nfrom Models import BitField\nfrom asyncio import Queue\nfrom Controllers.FileReader import FileReader\n\n\nclass ClientConnection:\n\n def __init__(self, host, port, torrent, request_queue):\n self.host = host\n self.port = port\n self.torrent = torrent\n self.request_queue = request_queue\n self.writer = None\n self.reader = None\n self.bitfield = None\n self.send_queue = Queue()\n\n self.am_choking = True\n self.am_interested = False\n self.peer_choking = True\n self.peer_interested = False\n\n self.required_index = None\n self.request_queue.register_peer(self)\n\n async def connect(self):\n \"\"\" start a connection with peer \"\"\"\n\n self.reader, self.writer = await asyncio.open_connection(\n host=self.host,\n port=self.port\n )\n\n await self.send_handshake()\n await self.reader.read(68)\n await self.send_unchoke()\n\n while True:\n await self._receive_socket()\n await self._send_socket()\n if not self.peer_choking and self.bitfield and self.am_interested:\n await self.send_request()\n\n async def _receive_socket(self):\n\n try:\n length_data = await asyncio.wait_for(\n self.reader.read(4), timeout=0.5\n )\n if length_data == b'':\n return await self.gracefully_shutdown()\n length = unpack_length(length_data)\n if length == 0:\n return\n\n buff = b''\n while len(buff) < length:\n buff += await self.reader.read(length - len(buff))\n\n await self._process(length, buff[0:1], buff[1:])\n\n except asyncio.TimeoutError:\n pass\n\n async def send_unchoke(self):\n await self._send(pack_protocol_int(1) + pack_id(1))\n self.am_choking = False\n\n async def _send_socket(self):\n\n try:\n message = self.send_queue.get_nowait()\n await self._send(message)\n except asyncio.QueueEmpty:\n pass\n\n async def queue_available(self, piece_handler):\n\n index = piece_handler.piece\n id = pack_id(4)\n piece = pack_protocol_int(index)\n data = id + piece\n length = pack_protocol_int(len(data))\n self.send_queue.put_nowait(length + data)\n\n async def send_handshake(self):\n \"\"\" send handshake to peer \"\"\"\n\n pstr_length = pack_id(19)\n pstr = 'BitTorrent protocol'.encode()\n reserved = (8 * chr(0)).encode()\n info_hash = self.torrent.get_info_hash()\n peer_id = self.torrent.peer_id().encode()\n\n await self._send(\n pstr_length + pstr + reserved + info_hash + peer_id\n )\n\n async def send_request(self):\n\n if self.required_index is None:\n self.required_index = self.request_queue.get_request(self.bitfield)\n if self.required_index is None:\n return\n\n if self.required_index.is_complete():\n await self.request_queue.confirm_download(self.required_index)\n # write piece to file\n self.required_index = None\n return await self.send_request()\n\n piece_data = self.required_index.next_piece()\n while piece_data is not None:\n\n piece, offset, length = piece_data\n\n id = pack_id(6)\n index = pack_protocol_int(piece)\n begin = pack_protocol_int(offset)\n length = pack_protocol_int(length)\n\n data = id + index + begin + length\n data = pack_length(len(data)) + data\n\n await self._send(data)\n piece_data = self.required_index.next_piece()\n\n async def send_interested(self):\n\n data = pack_length(1) + pack_id(2)\n await self._send(data)\n\n async def _process(self, length, id, data):\n \"\"\" process each incoming message \"\"\"\n\n handlers = {\n 0: self._handle_choke,\n 1: self._handle_un_choke,\n 2: self._handle_interested,\n 3: self._handle_not_interested,\n 4: self._handle_have,\n 5: self._handle_bitfield,\n 6: self._handle_request,\n 7: self._handle_piece,\n 8: self._handle_cancel,\n 9: self._handle_port\n }\n\n id = ord(id)\n if id not in handlers:\n return\n\n # print('got', id, handlers.get(id).__name__)\n await handlers.get(id)(length, data)\n\n async def _handle_choke(self, length, data):\n self.peer_choking = True\n print('peer choking')\n await self.gracefully_shutdown()\n\n async def _handle_un_choke(self, length, data):\n self.peer_choking = False\n\n async def _handle_interested(self, length, data):\n self.peer_interested = True\n\n async def _handle_not_interested(self, length, data):\n self.peer_interested = False\n\n async def _handle_have(self, length, data):\n pass\n\n async def _handle_bitfield(self, length, data):\n \"\"\" process bitfield \"\"\"\n self.bitfield = BitField(data)\n await self.send_interested()\n\n async def _handle_request(self, length, data):\n\n index_data = data[0:4]\n begin_data = data[4:8]\n length_data = data[8:12]\n\n index = unpack_protocol_int(index_data)\n begin = unpack_protocol_int(begin_data)\n length = unpack_protocol_int(length_data)\n\n block = await FileReader.read(index, begin, length)\n if block is None:\n return print('block is none')\n data = pack_id(7) + index_data + begin_data + block\n await self._send(pack_length(len(data)) + data)\n\n async def _handle_piece(self, length, data):\n \"\"\" process download response \"\"\"\n\n index_data = data[0:4]\n begin_data = data[4:8]\n block = data[8:]\n\n index = unpack_protocol_int(index_data)\n begin = unpack_protocol_int(begin_data)\n\n self.required_index.received(index, begin, block)\n\n async def _handle_cancel(self, length, data):\n pass\n\n async def _handle_port(self, length, data):\n pass\n\n async def _send(self, data):\n \"\"\" send message to peer \"\"\"\n self.writer.write(data)\n await self.writer.drain()\n\n async def gracefully_shutdown(self):\n # print('shutting down peer')\n if self.required_index is not None:\n self.request_queue.cancel_piece(self.request_queue)\n\n if self.writer is not None:\n try:\n await self.writer.wait_closed()\n except:\n pass\n\n if self.request_queue is not None:\n self.request_queue.remove_peer(self)\n self.request_queue = None\n","sub_path":"Controllers/ClientConnection.py","file_name":"ClientConnection.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"123501198","text":"def qsort(array: list):\n \"\"\"Алгоритм быстрой сортировки\"\"\"\n if len(array) < 2:\n return array\n else:\n pivot = array[0]\n less = [i for i in array[1:] if i <= pivot]\n greater = [i for i in array[1:] if i > pivot]\n return qsort(less) + [pivot] + qsort(greater)\n\n\nprint(qsort([2, 9, 4, 6, 99, 44, 33, 44]))\n","sub_path":"Chapter_4_БыстраяСортировка/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"22777681","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pytest\n\n\npytestmark = pytest.mark.django_db\n\n\ndef test_urls(client):\n\turl = '/admin'\n\tresponse = client.get(url, follow=True)\n\tassert response.status_code == 200\t","sub_path":"tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"513508313","text":"paragraph = open(\"text.txt\", \"r\")\nlist = []\nlist = paragraph.read()\ncount = dict()\nwords = list.split()\n\nfor word in words:\n if word in count:\n count[word] += 1\n else:\n count[word] = 1\nprint(\"Total word frequency\")\nprint(count)\nparagraph.close()\n","sub_path":"exercise_1.py","file_name":"exercise_1.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"626792395","text":"#%% code imports\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Input\nfrom keras.callbacks import EarlyStopping\nfrom keras.regularizers import l2\n\n\n#%% functions definition\ndef build_encoder(x_train, x_model_val, configs):\n '''function to build the encoder network for feature engineering stage\n\n Parameters\n ----------\n x_train : numpy ndarray\n x_model_val : numpy ndarray\n configs : list of booleans\n\n Returns\n -------\n encoder : TF model\n '''\n use_encoder = bool(configs[0])\n factor = 0.5 if bool(configs[1]) else 0.75\n if(use_encoder):\n # build the network\n input_layer = Input(shape=(int(x_train.shape[1]),))\n encoded = Dense(max(int(x_train.shape[1]*factor), 1), activation='relu')(input_layer)\n encoded = Dense(max(int(x_train.shape[1]*factor**2), 1), activation='relu')(encoded)\n encoded = Dense(max(int(x_train.shape[1]*factor**3), 1), activation='relu')(encoded)\n decoded = Dense(max(int(x_train.shape[1]*factor**2), 1), activation='relu')(encoded)\n decoded = Dense(max(int(x_train.shape[1]*factor), 1), activation='relu')(decoded)\n decoded = Dense(int(x_train.shape[1]), activation='linear')(decoded)\n autoencoder = Model(input_layer, decoded)\n encoder = Model(input_layer, encoded)\n # set the optimizer and loss\n autoencoder.compile(optimizer='Adam', loss='mean_squared_error')\n # specify the callback for early stopping and selecting the best model\n call_back = EarlyStopping(monitor='val_loss',\n min_delta=0.0000000000001, \n patience=10, \n mode='min',\n restore_best_weights=True)\n # start the training process\n autoencoder.fit(x_train, x_train, epochs=100,\n batch_size=32, shuffle=True,\n validation_data=(x_model_val, x_model_val),\n callbacks=[call_back],\n verbose=0)\n # function return\n return(encoder)\n else:\n return(None)\n\n","sub_path":"auto_design/feature_engineering/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"614187007","text":"import sys\nimport re\nimport random\n\ndef histogram(source_text):\n histogram = {}\n for word in source_text.split():\n word = re.sub('[.,:;!-[]?', '', word)\n\n if word in histogram:\n histogram[word] += 1\n else:\n histogram[word] = 1\n\n return histogram\n\ndef random_word(histogram):\n probability = 0\n rand_index = random.randint(1, sum(histogram.values()))\n # Algorithm 1\n # for (key, value) in histogram.items():\n # for num in range(1, value + 1):\n # if probability == rand_index:\n # if key in outcome_gram:\n # outcome_gram[key] += 1\n # else:\n # outcome_gram[key] = 1\n # # return outcome_gram\n # return key\n # else:\n # probability += 1\n # Algorithm 2\n for word in histogram:\n probability += histogram[word]\n if probability >= rand_index:\n if word in outcome_gram:\n outcome_gram[word] += 1\n else:\n outcome_gram[word] = 1\n return word\n\nif __name__ == \"__main__\":\n outcome_gram = {}\n dict = open('/Users/alexaaronpena/Github Repositories/Tweet-Generator/class_1/fish.txt', 'r')\n text = dict.read()\n dict.close()\n\n hist_dict = histogram(text)\n for number in range(1, 100000):\n random_word(hist_dict)\n\n print(\"If this were a perfect algorithm, the number of fish would be 50000, but my actual value is \" + str(outcome_gram[\"fish\"]))\n # for word, expected_count in hist_dict.items():\n print(\"The percent error is \" + str(abs(outcome_gram[\"fish\"] - 50000.0) / 50000.0 * 100.0) + \"%\")\n # outcome_gram[\"fish\"] = abs(outcome_gram[\"fish\"] - 5000.0) / 5000.0 * 100.0\n","sub_path":"class_1/stochastic_sampling.py","file_name":"stochastic_sampling.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"27928082","text":"\"\"\"Controller for the /nodes namespace.\"\"\"\n\nfrom typing import List\nfrom socketio import AsyncNamespace\nfrom config import Config\nfrom models.node import Node\nfrom models.acknowledgment import Acknowledgment\nfrom api.validate import Validate\nfrom protocol.master import ClusterMaster\n\n\nclass NodesController(AsyncNamespace):\n \"\"\"Controller for the /nodes namespace.\"\"\"\n\n def __init__(self, config: Config, cluster_master: ClusterMaster):\n super().__init__(namespace='/nodes')\n self.config: Config = config\n self.cluster_master: ClusterMaster = cluster_master\n\n # add node repository change listener\n config.node_repository.register_listener(self.send_nodes)\n\n async def send_nodes(self, sid: str = None) -> None:\n \"\"\"Sends the current nodes to all clients or only a specific one.\n\n :param str sid: If specified, nodes will only be sent to this session id. Otherwise, all\n clients will receive the nodes.\n \"\"\"\n await self.emit('get', self.config.node_repository.to_json(), room=sid)\n\n def validate(self, data: dict, create: bool) -> Acknowledgment:\n \"\"\"Validates the input data.\n\n :param dict data: Input data\n :param bool create: If a new node will be created from this data or an existing updated.\n :returns: Acknowledgment with the status and possible error messages.\n :rtype: models.acknowledgment.Acknowledgment\n \"\"\"\n ack = Acknowledgment()\n validate = Validate(ack)\n node_id = data.get('id')\n name = data.get('name')\n detector = data.get('detector')\n\n validate.string(name, label='Name', min_value=1, max_value=50)\n\n if self.config.balance:\n ack.add_error('No configuration changes can be made when balancing is active')\n\n if detector is not None:\n validate.string(detector, label='Detection Algorithm', min_value=3, max_value=8)\n\n if data.get('room') is None or isinstance(data.get('room'), dict) is False:\n ack.add_error('Room id must not be empty')\n elif validate.integer(data.get('room').get('id'), label='Room id', min_value=1):\n if self.config.room_repository.get_room(data.get('room').get('id')) is None:\n ack.add_error('A room with this id does not exist')\n\n if create:\n if self.config.node_repository.get_node_by_name(name) is not None:\n ack.add_error('A node with this name already exists')\n elif validate.integer(node_id, label='Node id', min_value=1):\n existing_name = self.config.node_repository.get_node_by_name(name)\n\n if self.config.node_repository.get_node(node_id) is None:\n ack.add_error('Node with this id does not exist')\n elif existing_name and existing_name.node_id != node_id:\n ack.add_error('A node with this name already exists')\n\n return ack\n\n async def on_get(self, _: str) -> List[Node]:\n \"\"\"Returns the current nodes.\n\n :param str sid: Session id\n :param dict data: Event data\n \"\"\"\n return self.config.node_repository.to_json()\n\n async def on_update(self, _: str, data: dict) -> dict:\n \"\"\"Updates a node.\n\n :param str sid: Session id\n :param dict data: Event data\n \"\"\"\n # validate\n ack = self.validate(data, False)\n\n # update the node\n if ack.successful:\n room = self.config.room_repository.get_room(data.get('room').get('id'))\n node = self.config.node_repository.get_node(data.get('id'))\n\n node.name = data.get('name')\n\n if data.get('detector') is not None:\n node.detector = data.get('detector')\n if node.acquired and node.online:\n self.cluster_master.send_service_update(node.ip_address)\n\n # update room reference if necessary\n if node.room is None or node.room.room_id != room.room_id:\n if node.room is not None:\n node.room.nodes.remove(node)\n\n # force re-calibration of the old room\n node.room.force_recalibration()\n\n node.room = room\n node.room.nodes.append(node)\n\n # force re-calibration of the new room\n node.room.force_recalibration()\n\n # store the update and send the new state to all clients\n await self.config.node_repository.call_listeners()\n await self.config.room_repository.call_listeners()\n\n return ack.to_json()\n\n async def on_delete(self, _: str, node_id: int) -> dict:\n \"\"\"Deletes a node.\n\n :param str sid: Session id\n :param int node_id: Node id\n \"\"\"\n ack = Acknowledgment()\n\n if self.config.balance:\n ack.add_error('No configuration changes can be made when balancing is active')\n\n node = self.config.node_repository.get_node(node_id)\n if node is None:\n ack.add_error('A node with this id does not exist')\n\n if ack.successful and node.room is not None:\n node.room.nodes.remove(node)\n node.room.force_recalibration()\n node.room = None\n\n # store the update and send the new state to all clients\n await self.config.node_repository.call_listeners()\n await self.config.room_repository.call_listeners()\n\n return ack.to_json()\n","sub_path":"backend/src/api/controllers/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"598848787","text":"import requests\nimport time\nimport json\n\nclass NotFound(Exception):\n def __init__(self, message):\n # Call the base class constructor with the parameters it needs\n super().__init__(message,[])\n\n\nclass Metadata:\n # Metadata about scopus response\n total = 0\n per_page = 10\n index = 0\n links = []\n # Each facet belongs to a key which holds specified data\n facets = {}\n\n @property\n def total_pages(self):\n return int(round((self.total / self.per_page),0))\n @property\n def current_page(self):\n return int((self.total / self.per_page) - (self.total - (self.index+self.per_page) / self.per_page))\n\nclass ScopusResponse:\n # TODO: implement a universal message statuses\n status_message = ''\n metadata = Metadata()\n data = []\n\nclass ScopusAuthor:\n id = 0\n raw = ''\n name = ''\n documents = 0\n cited_by = 0\n country = ''\n city = ''\n affiliation_id = 0\n affiliation = ''\n subject_areas = []\n h_index = 0\n coauthors = []\n request = None\n\n def get_coauthors(self):\n params = {\n 'co-author': self.id,\n 'count': 25,\n 'start': 0\n }\n url = \"https://api.elsevier.com/content/search/author\"\n req = requests.get(url, params=params, headers=self.request.headers)\n data = req.json()\n data = data['search-results']\n\n total = int(data['opensearch:totalResults'])\n per_page = int(data['opensearch:itemsPerPage'])\n\n for author in data['entry']:\n self.save_coauthor(author)\n\n for page in range(1, int(round((total / per_page),0))+1):\n params = {\n 'co-author': self.id,\n 'count': 25,\n 'start': per_page*page\n }\n url = \"https://api.elsevier.com/content/search/author\"\n req = self.request.get(url, params=params)\n data = req.json()\n data = data['search-results']\n\n if data.get('entry') and isinstance(data.get('entry'), list):\n for author in data['entry']:\n self.save_coauthor(author)\n\n return self.coauthors\n\n def save_coauthor(self, data):\n author = ScopusAuthor()\n \n if data.get('dc:identifier'):\n author.id = int((data.get('dc:identifier').split('AUTHOR_ID:'))[1])\n if data.get('document-count'):\n author.documents = int(data.get('document-count'))\n if data.get('cited-by-count'):\n author.cited_by = int(data.get('cited-by-count'))\n if data.get('h-index'):\n author.h_index = data.get('h-index')\n\n affiliation = data.get('affiliation-current')\n if affiliation:\n author.country = affiliation.get('affiliation-country')\n author.city = affiliation.get('affiliation-city')\n if affiliation.get('@id'):\n author.affiliation_id = int(affiliation.get('@id'))\n author.affiliation = affiliation.get('affiliation-name')\n \n if data.get('subject-area') and isinstance(data.get('subject-area'), list):\n author.subject_areas = [\n { 'name': sa.get('@abbrev'), 'freq': sa.get('@frequency')} \n for sa in data.get('subject-area')\n ]\n # else:\n # # TODO: Log none response\n # raise NotFound('Author basic data could not be received!')\n\n\n self.coauthors.append(author)\n\nclass Scopus:\n # Track time between requests\n last_request_time = time.time()\n min_request_interval = 0\n response = ScopusResponse()\n search_cursor = None\n request = requests.Session()\n \n def __init__(self, api_key=None, min_request_interval=0.25):\n if not api_key:\n raise Exception(\"Set api for Scopus requests!\")\n\n self.request.headers.update({\n 'Accept': 'application/json',\n 'X-ELS-APIKey': api_key ,\n 'User-Agent': 'elsapi-v4.',\n })\n self.min_request_interval = min_request_interval\n\n def search(self, query, facets=[], sortby=None, date='', subject=None, per_page=100, start=None, fields=[]):\n ## Wait between requests, scopus API has a cooldown period\n interval = time.time() - self.last_request_time\n if (interval < self.min_request_interval):\n time.sleep(self.min_request_interval - interval)\n \n # Create search params specific to Scopus article retrival\n params = {\n 'query': query,\n 'subj': subject,\n 'sort': sortby,\n 'count': per_page,\n 'start': start,\n 'date': date,\n 'field': ','.join(fields),\n 'facets': ';'.join(facets)\n }\n # Filter for none params\n params = {k:v for k,v in params.items() if v is not None}\n url = \"https://api.elsevier.com/content/search/scopus\"\n req = self.request.get(url, params=params)\n self.last_request_time = time.time()\n \n # Check for successfully requests or throw error\n if req.status_code == 200:\n self.parse_response(req, type='scopus')\n return self\n else:\n raise requests.HTTPError(json.loads(req.text),req.headers)\n\n def search_authors(self, query, facets=[], sortby=None, date='', subject=None, per_page=100, start=None, fields=[]):\n ## Wait between requests, scopus API has a cooldown period\n interval = time.time() - self.last_request_time\n if (interval < self.min_request_interval):\n time.sleep(self.min_request_interval - interval)\n \n # Create search params specific to Scopus article retrival\n params = {\n 'query': query,\n 'subj': subject,\n 'sort': sortby,\n 'count': per_page,\n 'start': start,\n 'date': date,\n 'field': ','.join(fields),\n 'facets': ';'.join(facets)\n }\n # Filter for none params\n params = {k:v for k,v in params.items() if v is not None}\n url = \"https://api.elsevier.com/content/search/author\"\n req = self.request.get(url, params=params)\n self.last_request_time = time.time()\n \n # Check for successfully requests or throw error\n if req.status_code == 200:\n self.parse_response(req, type='scopus')\n return self\n else:\n raise requests.HTTPError(json.loads(req.text),req.headers)\n\n\n def author_detail(self, id, view='LIGHT', fields=[]):\n ## Wait between requests, scopus API has a cooldown period\n interval = time.time() - self.last_request_time\n if (interval < self.min_request_interval):\n time.sleep(self.min_request_interval - interval)\n\n # Create search params specific to Scopus article retrival\n params = {\n 'view': view,\n 'field': ','.join(fields)\n }\n # Filter for none params\n params = {k:v for k,v in params.items() if v is not None}\n url = \"https://api.elsevier.com/content/author/author_id/{}\".format(id)\n req = self.request.get(url, params=params)\n self.last_request_time = time.time()\n \n # Check for successfully requests or throw error\n if req.status_code == 200:\n self.parse_author(req)\n return self\n else:\n raise requests.HTTPError(json.loads(req.text),req.headers)\n\n def parse_response(self, req, type='search'):\n data = req.json()\n # TODO: Switch case per response type\n data = data['search-results']\n self.response.metadata.total = int(data['opensearch:totalResults'])\n self.response.metadata.per_page = int(data['opensearch:itemsPerPage'])\n self.response.metadata.index = int(data['opensearch:startIndex'])\n self.response.data = data['entry']\n \n facets = data.get('facet')\n if isinstance(facets,dict):\n self.response.metadata.facets[facets['name']] = facets['category']\n \n if isinstance(facets,list):\n for facet in facets:\n self.response.metadata.facets[facet['name']] = facet['category']\n\n def parse_author(self, req):\n data = req.json()\n r_type = '{}'.format(type)\n data = data['author-retrieval-response'][0]\n author = ScopusAuthor()\n author.raw = data\n # Use same instance to requst further data from scopus API\n author.request = self.request\n \n coredata = data.get('coredata')\n if coredata:\n author.id = int((coredata.get('dc:identifier').split('AUTHOR_ID:'))[1])\n author.name = ''\n author.documents = int(coredata.get('document-count'))\n author.cited_by = int(coredata.get('cited-by-count'))\n author.h_index = data.get('h-index')\n\n affiliation = data.get('affiliation-current')\n if affiliation:\n author.country = affiliation.get('affiliation-country')\n author.city = affiliation.get('affiliation-city')\n author.affiliation_id = affiliation.get('@id')\n author.affiliation = affiliation.get('affiliation-name')\n author.subject_areas = []\n else:\n raise NotFound('Author basic data could not be received!')\n \n self.response.data = author\n\n # def parse_facets(self, facets)\n\n # def search_cursor(query, facets='', limit=100, count=100):","sub_path":"analysis/scopus.py","file_name":"scopus.py","file_ext":"py","file_size_in_byte":9550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"451512512","text":"from pwn import *\n\nelf = context.binary = ELF(\"./chainblock\")\nlibc = ELF('./libc.so.6')\n\nif args.GDB:\n\t# p = gdb.debug(elf.path)\n\tp = gdb.debug(elf.path, '\\n'.join([\n\t\t\"b *verify\",\n\t\t\"c\"\n\t]), env={'LD_PRELOAD': \"./libc.so.6\"})\nelif args.REMOTE:\n\tp = remote(\"pwn.be.ax\", 5000)\nelse:\n\tp = process(elf.path, env={'LD_PRELOAD': \"./libc.so.6\"}) \n\n\nOFFSET = 0x108\n\npayload = b'A' * OFFSET\n\n# 0x0000000000401493 : pop rdi ; ret\n# 0x000000000040101a : ret\npayload += p64(0x000000000040101a)\npayload += p64(0x0000000000401493)\npayload += p64(elf.got['printf'])\npayload += p64(elf.symbols['printf'])\npayload += p64(0x000000000040101a)\npayload += p64(elf.symbols['verify'])\n\np.sendline(payload)\n\np.recvuntil(b'KYC failed, wrong identity!')\np.recvline()\nleak = p.recvuntil(\"Please\")\nleak = leak.replace(b'Please', b'')\n\nlibc_printf = u64(leak.ljust(8, b'\\x00'))\nprint(hex(libc_printf))\n\nlibc.address = libc_printf - libc.symbols['printf']\n\nprint(f\"[+] libc base {hex(libc.address)}\")\n\nBINSH = next(libc.search(b\"/bin/sh\"))\nSYSTEM = libc.symbols[\"system\"]\n\npayload = b'A' * OFFSET\npayload += p64(0x000000000040101a)\npayload += p64(0x0000000000401493)\npayload += p64(BINSH)\npayload += p64(SYSTEM)\np.sendline(payload)\n\np.interactive()\n","sub_path":"corctf_2021/chainblock/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"495470629","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 24 03:51:15 2020\n\n@author: Muntabir Choudhury \n\"\"\"\nfrom nltk.tokenize import sent_tokenize\nimport re\nimport glob\nimport csv\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\npath = r\"C:\\Users\\Muntabir\\Documents\\Graduate School_ODU\\RA\\MIT_Sample\\etd_metadata_xml\"\n\n#file sorting\nnumbers = re.compile(r'(\\d+)')\ndef numericalSort(value):\n parts = numbers.split(value)\n parts[1::2] = map(int, parts[1::2])\n return parts\n\nfiles = sorted(glob.glob(\"*.xml\"), key=numericalSort)\ndegree = ''\nprefix_map = {\"dim\": \"http://www.dspace.org/xmlns/dspace/dim\"}\n\ncsvfile = open('degree_xml.csv', 'w')\ncsv_writer = csv.writer(csvfile)\n\nfor filename in files:\n with open(filename, 'r', encoding=\"utf-8\") as content:\n tree = ET.parse(content)\n doc_root = tree.getroot()\n \n degree_data=[]\n md_node = doc_root.find(\".//dim:field[@element='description'][@qualifier='degree']\", prefix_map)\n if md_node is not None:\n degree = md_node.text\n #tokenize the sentence\n sent_tokens = sent_tokenize(degree)\n #normalize the sentence\n sent_tokens = [sent.lower() for sent in sent_tokens]\n print(sent_tokens)\n \n #degree_data.append(sent_tokens)\n #print(degree_data)\n \n csv_writer.writerow(sent_tokens)\n\ncsvfile.close()\n\n#dfList=[]\n#colname=['metadata_author']\n#df=pd.read_csv('author-names_xml.csv', header = None)\n#dfList.append(df)\n#concatDf=pd.concat(dfList, axis=1)\n#concatDf.columns=colname\n#concatDf.to_csv('author-names_xml_modified.csv', index=None)\n \n\n","sub_path":"src/metadata_parser/mit/xmlparsing_degree.py","file_name":"xmlparsing_degree.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"44021041","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QCursor\nfrom PyQt5.QtWidgets import *\nimport modules.constant as CONSTANT\n\nclass AboutWidget(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.index = {\n '1. Introduction': ['1-1. Background', '1-2. Motivation', '1-3. About \"MonkeySapnner\"'],\n '2. What is Artifact Prototype?': ['2-1. Definition of Artifact Prototype', '2-2. Methodology'],\n '3. Prototype': [\n \"3-1. {}\".format(CONSTANT.ADOBE_READER_KEYWORD),\n \"3-2. {}\".format(CONSTANT.ADOBE_FLASH_PLAYER_KEYWORD),\n \"3-3. {}\".format(CONSTANT.EDGE_KEYWORD),\n \"3-4. {}\".format(CONSTANT.HWP_KEYWORD),\n \"3-5. {}\".format(CONSTANT.IE_KEYWORD),\n \"3-6. {}\".format(CONSTANT.OFFICE_KEYWORD),\n \"3-7. {}\".format(CONSTANT.LPE_KEYWORD),\n ],\n }\n self.presentPage = 0\n self.contentsText = {\n '1': '\"MonkeySpanner\" was made by a project manager, \\n'\n 'Eunjin, Kwon, in the team, \"Eunjin with MonkeySpanner\".\\n'\n 'Our team had performed research about security.\\n'\n 'Our topic is \"Precise Analysis of attacker\\'s behavior\\n'\n 'through Offensive Research\". '\n 'But, our project scope is only to exploit vulnerabilities of software in Windows.\\n\\n'\n '# Next page explain contents as below.\\n'\n ' (1) What our direction was\\n'\n ' (2) What purpose we approached as\\n'\n ' (3) Which expected effect many people can get \\n'\n ' by using this tool, and contacting with our research.\\n',\n '1-1': 'A software fundamentally behaves by being executed commands of assembly unit from CPU.\\n'\n 'In Digital Forensic, `Artifact` means data created \\n'\n 'automatically by system or software.\\n'\n 'Creating data automatically is to execute the commands \\n'\n 'when do some behavior or satisfy some conditions. \\n'\n 'Like Event Log, Prefetch, Registry, ... and vice versa.\\n'\n '(above artifacts from Operating System, artifacts created from each software can exists.)\\n\\n'\n 'So, Let Think about `Artifact Created When an Error Occurs`\\n\\n'\n 'This is because a exception code of are executed \\n'\n 'when error inside sw or system occurs.\\n'\n '(some exception code can’t create artifacts)\\n\\n'\n 'In fact, all software can’t create such artifacts, but\\n'\n 'if it is popular, it\\'ll handle exception, and deal with it for user to find cause of error.\\n'\n 'This is why popular softwares are able to create some artifacts when an error occurs.',\n '1-2': 'We needed to research popular software (like MS-Office, IE, Chrome, … etc) in Windows.\\n\\n'\n 'Also, we want to check on the following curiosity.\\n'\n ' (1) When exploit code executed, which artifact is left?\\n'\n ' (2) Is this treated as the artifact created when an error\\n'\n ' occurs ?\\n'\n ' (3) Such artifacts are different when not same\\n'\n ' vulnerability ?\\n\\n'\n 'In case (3), If such artifacts are similar,\\n'\n 'Are these common for every exploit in the software only?\\n\\n'\n 'So, we determined to find out `common artifacts set` for popular software when error occurs in Windows.\\n\\n'\n 'Our research is meaningful historically, but we worried about practicality (is this useful?)\\n\\n'\n '\"What about Incident Response ?\"\\n\\n'\n 'Fundamentally, it’s important to prevent from propagating malicious program after incident occurs.'\n 'So, we thought that our finding, common artifacts set will be artifacts occurred during malicious program spread.\\n\\n'\n '# Direction: To define common artifacts set for target software.\\n\\n'\n '# Goal: Our research reports seems to be used as logical grounds for precisely analyzing and classifying attacker’s behavior in Incident Response or Analysis',\n '1-3': 'The tool MonkeySapnner aims to be used to precisely classify and analyze attacker\\'s behavior '\n 'in the process of responding to and analyzing the incident.\\n'\n 'Today, the many forensic tools that add convenience are unfortunately '\n 'not in the process of extracting the associations of artifacts.\\n'\n '(There is, of course, such a tool.)\\n\\n'\n 'However, analysts are inconvenienced because this process requires a lot of time to invest in analysis.\\n'\n 'Our tools will help you relieve this discomfort.\\n\\n'\n 'With the Monkey Spanner, you will be able to see artifacts grouped by software, '\n 'and you will be able to quickly identify actual inflows and respond quickly to infringement.',\n '2': 'We called the artifacts grouped by specified software \"Artifact Prototype\".\\n(It is just simple reason)',\n '2-1': 'When you actually run malicious code, you may or may not have a variety of artifacts. \\n'\n 'We do not always think that our defined artifact prototype is complete because we always consider that there is not.'\n 'It just started from the idea that it could be grouped and used as an indicator of an intrusion. \\n\\n'\n 'When there are various artifacts left in normal execution, they may remain redundant. '\n 'In this case, it\\'s hard to see it as a significant artifact. '\n 'What we want to do is to help us identify the infringement, or to handle the error. \\n\\n'\n 'To summarize, we have defined the artifact prototype as a set of meaningful artifacts '\n 'that can be used to identify infringement of an infected malware by attacking certain software.',\n '2-2': 'Based on artifacts created time, if classfy exploit code,\\n\\n'\n '0.1 process execute\\n'\n ' 1.1 just got crash\\n'\n ' 2.1 run to shellcode\\n'\n '\\t 2.2 dll injection / file create\\n'\n '\\t 2.3 file delete / downloader\\n\\n'\n 'We thought it was the most significant artifact in terms of artifacts that could distinguish each step.'\n 'In fact, what I wanted most was to find artifacts due to errors, but in the Windows environment, '\n 'not all software left these artifacts.\\n\\n'\n 'Usually the first stage was a prefetch, a jump list, a web artifact, '\n 'and the second stage was an event log, a temporary file, or a deleted file. '\n 'To confirm this fact, we analyzed vulnerabilities exploited in exploit-kits with high attack success rates. '\n 'The artifacts for each CVE number were grouped and excluded if not significant. '\n 'As the process repeats, more and more artifact prototypes of certain software have been completed.',\n\n '3': \"3 TEST\",\n '3-1': \"3-1\"*20,\n '3-2': \"3-2\"*20,\n '3-3': \"3-3\"*20,\n '3-4': \"3-4\"*20,\n '3-5': \"3-5\"*20,\n '3-6': \"3-6\"*20,\n '3-7': \"3-7\"*20,\n }\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(\"About\")\n self.setFixedSize(self.width(), self.height()-150)\n self.layout = QVBoxLayout(self)\n self.splitter = QSplitter(Qt.Horizontal)\n self.layout.addWidget(self.splitter)\n\n # Table of Contents\n self.indexTree = QTreeWidget(self)\n self.indexTree.setFixedWidth(265)\n self.indexTree.setHeaderLabel(\"Table Of Contents\")\n self.indexTree.itemClicked.connect(self.indexItemClicked)\n\n self.treeWidgetItems = []\n for p_text in self.index.keys():\n parent = QTreeWidgetItem(self.indexTree)\n parent.setText(0, p_text)\n parent.setExpanded(True)\n self.treeWidgetItems.append(parent)\n for c_text in self.index[p_text]:\n child = QTreeWidgetItem(parent)\n child.setText(0, c_text)\n self.treeWidgetItems.append(child)\n\n\n # Contents\n self.contents = QTextEdit('', self)\n self.contents.setText(self.contentsText['1'])\n self.contents.setContentsMargins(10, 5, 5, 10)\n self.contents.setReadOnly(True)\n\n self.splitter.addWidget(self.indexTree)\n self.splitter.addWidget(self.contents)\n self.show()\n\n def indexItemClicked(self, item, p_int):\n idx = item.text(0).split('.')[0]\n self.contents.setText(self.contentsText[idx])\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n w = AboutWidget()\n sys.exit(app.exec_())","sub_path":"modules/UI/AboutWidget.py","file_name":"AboutWidget.py","file_ext":"py","file_size_in_byte":9308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"217753248","text":"# import sys when runing from the batch code\n\nimport sys\n\nimport os\n\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),\"../../../..\"))\n\nimport pandas as pd\n\nimport numpy as np\n\nfrom datetime import datetime\n\n# visualisation packages\n\nimport math\n\nimport matplotlib.dates as mdates\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nimport collections\n\nfrom matplotlib.font_manager import FontProperties\n\n \n\nimport current_version.production_ver.Analytics.abstract_sig_econ_dashboard as abs_sig\n\nimport time\n\nfrom current_version.production_ver.backtesting_utils.cache import cache_response, clear_cache\n\nfrom current_version.production_ver.Analytics.miniEDB import miniEDB\n\nfrom current_version.production_ver.signals.DATA_NGDP_LOC.NGDP_ALL import signal3 as DATA_NGDP_LOC_sig\n\nfrom old_versions.version2.zzz_NC_signal.ECON_SLACK.ECON_SLACK import signal3 as ECON_SLACK_sig\n\nfrom current_version.production_ver.signals.RATES_LVL_GROWmPOT.GROW_VS_POT import signal3 as RATES_LVL_GROWmPOT_sig\n\nfrom old_versions.version2.zzz_NC_signal.ECON_FX_RES.ECON_FX_RES import signal3 as ECON_FX_RES_sig\n\nfrom old_versions.version2.zzz_NC_signal.ECON_Market_Major.ECON_MARKET_MAJOR import signal3 as ECON_Market_Major_sig\n\nfrom current_version.production_ver.signals.DATA_MATRIX.GENERIC_DATA import signal3 as GENERIC_DATA_sig\n\n \n\n# part of the utilities\n\ndateparse = lambda x: pd.datetime.strptime(x, '%d/%m/%Y')\n\ndateparse2 = lambda x: pd.datetime.strptime(x, '%Y-%m-%d')\n\n \n\nclass signal3(abs_sig.sig_ECON_dashboard):\n\n def __init__(self):\n\n # in this case, both Econ and csv file data are used\n\n super(signal3, self).__init__()\n\n \n\n @cache_response('ECON_GROWTH', 'disk_8h',skip_first_arg=True)\n\n def get_data_dict(self,*args,**kwargs):\n\n self.add_sig_info()\n\n self.add_dir_info(**kwargs)\n\n self.pre_run_result = self.pre_run(**kwargs)\n\n self.raw_data_new_fmt = {}\n\n data_short_kw = {'dummy': 0, 'get_or_set_market_data': 'get'}\n\n data_short_kw.update((k, kwargs[k]) for k in data_short_kw.keys() & kwargs.keys())\n\n self.raw_data_new_fmt = GENERIC_DATA_sig().get_data_dict(**data_short_kw)['raw_data_new_fmt']\n\n self.raw_data_new_fmt.update(self.pre_run_result)\n\n self.clean_data()\n\n self.raw_data_new_fmt.update(self.run_mini_EDB_trans(miniEDB_parse_dict_list=self.miniEDB_parse_dict_list(),**kwargs))\n\n self.run_step1(**kwargs)\n\n return {'raw_data_new_fmt':self.raw_data_new_fmt}\n\n \n\n def add_sig_info(self):\n\n self.signal_ID = 'JY_dashboard_005'\n\n self.Short_Name = 'ECON_GROWTH'\n\n self.Description = '''\n\n Emerging FX reserve flow (BOP)\n\n '''\n\n self.override_master_input_dir=r'E:\\_CODE\\JYang\\JY_Project\\old_versions\\version2\\zzz_NC_input\\ECON_VIS.xlsx'\n\n self.exec_path = __file__\n\n \n\n def pre_run(self,**kwargs):\n\n '''\n\n :return: dictionary of pre-processing data from all pre-running result\n\n '''\n\n result_dict = {}\n\n result_dict.update(DATA_NGDP_LOC_sig().get_data_dict(**kwargs)['raw_data_new_fmt'])\n\n # print (ECON_SLACK_sig().get_data_dict(**kwargs)['raw_data_new_fmt'].keys())\n\n result_dict.update(ECON_SLACK_sig().get_data_dict(**kwargs)['raw_data_new_fmt'])\n\n result_dict.update(ECON_FX_RES_sig().get_data_dict(**kwargs)['raw_data_new_fmt'])\n\n result_dict.update(ECON_Market_Major_sig().get_data_dict(**kwargs)['raw_data_new_fmt'])\n\n result_dict.update(RATES_LVL_GROWmPOT_sig().get_data_dict(**kwargs)['econ_vis_format'])\n\n return result_dict\n\n \n\n def miniEDB_parse_dict_list(self):\n\n return [{'Short_Name': self.Short_Name, 'xls_dir': self.MASTER_INPUT_DIR, 'sheet_name': self.Short_Name},\n\n ]\n\n \n\n def run_mini_EDB_trans(self,miniEDB_parse_dict_list,**kwargs):\n\n result_dict = collections.OrderedDict()\n\n miniEDB1 = miniEDB()\n\n for p in miniEDB_parse_dict_list:\n\n print('running...', p)\n\n miniEDB1.add_spread_sheet_info(spread_sht_parse_dict=p, **kwargs)\n\n miniEDB1.add_dir_info(spread_sht_parse_dict=p, **kwargs)\n\n miniEDB1.raw_data_new_fmt = self.raw_data_new_fmt\n\n result_dict.update(miniEDB1.perform_transformation(miniEDB1.parse_input_table()))\n\n return result_dict\n\n \n\n def run_step1(self,**kwargs):\n\n self.raw_data_new_fmt.update(self.rename_col_to_key(self.raw_data_new_fmt))\n\n \n\n def clean_data(self):\n\n self.raw_data_new_fmt['IDN_WAGES_AVG_LOC_NSA'] = self.SU.conversion_to_q(self.raw_data_new_fmt['IDN_WAGES_AVG_LOC_NSA'])\n\n \n\nif __name__ == \"__main__\":\n\n # clear_cache('ECON_GROWTH', 'disk_8h')\n\n reporting_to = sys.argv[1] if len(sys.argv)>1.01 else None if len(sys.argv)>1.01 else None\n\n kw = {'reporting_to':reporting_to,'dummy':0}\n\n signal3().run_reporting(**kw)\n\n print (signal3().get_data_dict(**kw)['raw_data_new_fmt']['ARG_FXRES_NGDP(6m)'].dropna())","sub_path":"Caxton/JY_Completed/old_versions/version2/zzz_NC_signal/ECON_GROWTH/ECON_GROWTH.py","file_name":"ECON_GROWTH.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"173891297","text":"# coding: utf-8\n\nimport os\nimport os.path\nimport numpy as np\n\nimport torch\nimport torch.utils.data\nimport torch.utils.data as data\nfrom PIL import Image\n\nimport torchvision\nimport torchvision.models\nimport torchvision.transforms\n\nimport transforms\n\n\nIMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']\n\n\ndef is_image_file(filename):\n \"\"\"Checks if a file is an image.\n Args:\n filename (string): path to a file\n Returns:\n bool: True if the filename ends with a known image extension\n \"\"\"\n filename_lower = filename.lower()\n return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)\n\n\ndef find_classes(dir):\n classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n classes.sort()\n class_to_idx = {classes[i]: i for i in range(len(classes))}\n return classes, class_to_idx\n\n\ndef make_dataset(dir, class_to_idx):\n images = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n if not os.path.isdir(d):\n continue\n\n for root, _, fnames in sorted(os.walk(d)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n path = os.path.join(root, fname)\n item = (path, class_to_idx[target])\n images.append(item)\n\n return images\n\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n\ndef accimage_loader(path):\n import accimage\n try:\n return accimage.Image(path)\n except IOError:\n # Potentially a decoding problem, fall back to PIL.Image\n return pil_loader(path)\n\n\ndef default_loader(path):\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader(path)\n else:\n return pil_loader(path)\n\n\nclass ImageFolder(data.Dataset):\n\n def __init__(self, root, train=True, test_style='apple',\n transform=None, target_transform=None,\n loader=default_loader):\n classes, class_to_idx = find_classes(root)\n\n imgs = make_dataset(root, class_to_idx)\n if len(imgs) == 0:\n raise(RuntimeError(\"Found 0 images in subfolders of: \" + root + \"\\n\"\n \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n\n test_style = test_style.lower()\n if test_style not in ['apple', 'google', 'facebook', 'emoji-one', 'samsung', 'microsoft', 'lg', 'htc',\n 'whatsapp', 'messenger', 'twitter', 'emojidex', 'mozilla']:\n raise(RuntimeError(\"Need valid test_style name\"))\n\n if train is True:\n imgs = [x for x in imgs if test_style not in x[0]]\n else:\n imgs = [x for x in imgs if test_style in x[0]]\n\n self.root = root\n self.train = train\n self.test_style = test_style\n self.imgs = imgs\n self.classes = classes\n self.class_to_idx = class_to_idx\n self.transform = transform\n self.target_transform = target_transform\n self.loader = loader\n\n def __getitem__(self, index):\n\n path, target = self.imgs[index]\n img = self.loader(path)\n if self.transform is not None:\n img = self.transform(img)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self):\n return len(self.imgs)\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n fmt_str += ' Root Location: {}\\n'.format(self.root)\n tmp = ' Transforms (if any): '\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n tmp = ' Target Transforms (if any): '\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n return fmt_str\n\n\nclass Dataset(object):\n def __init__(self, config, dataset_dir=None):\n self.config = config\n if dataset_dir is None:\n self.dataset_dir = os.path.join('~/.torchvision/datasets',\n config['dataset'])\n else:\n self.dataset_dir = dataset_dir\n\n self.use_cutout = (\n 'use_cutout' in config.keys()) and config['use_cutout']\n\n self.use_random_erasing = ('use_random_erasing' in config.keys()\n ) and config['use_random_erasing']\n\n def get_datasets(self, icons=False):\n if icons is True:\n train_dataset = ImageFolder(\n self.dataset_dir, train=True, test_style=self.config['test_style'], transform=self.train_transform)\n test_dataset = ImageFolder(\n self.dataset_dir, train=False, test_style=self.config['test_style'], transform=self.test_transform)\n\n return train_dataset, test_dataset\n\n def _get_random_erasing_train_transform(self):\n raise NotImplementedError\n\n def _get_cutout_train_transform(self):\n raise NotImplementedError\n\n def _get_default_train_transform(self):\n raise NotImplementedError\n\n def _get_train_transform(self):\n if self.use_random_erasing:\n return self._get_random_erasing_train_transform()\n elif self.use_cutout:\n return self._get_cutout_train_transform()\n else:\n return self._get_default_train_transform()\n\n\nclass CIFAR(Dataset):\n def __init__(self, config):\n super(CIFAR, self).__init__(config)\n\n if config['dataset'] == 'CIFAR10':\n self.mean = np.array([0.4914, 0.4822, 0.4465])\n self.std = np.array([0.2470, 0.2435, 0.2616])\n elif config['dataset'] == 'CIFAR100':\n self.mean = np.array([0.5071, 0.4865, 0.4409])\n self.std = np.array([0.2673, 0.2564, 0.2762])\n\n self.train_transform = self._get_train_transform()\n self.test_transform = self._get_test_transform()\n\n def _get_random_erasing_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.random_erasing(\n self.config['random_erasing_prob'],\n self.config['random_erasing_area_ratio_range'],\n self.config['random_erasing_min_aspect_ratio'],\n self.config['random_erasing_max_attempt']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_cutout_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.cutout(self.config['cutout_size'],\n self.config['cutout_prob'],\n self.config['cutout_inside']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_default_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n def _get_test_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n\nclass Icons(Dataset):\n def __init__(self, config, dataset_dir):\n super(Icons, self).__init__(config, dataset_dir)\n\n self.mean = np.array([0.5, 0.5, 0.5])\n self.std = np.array([0.25, 0.25, 0.25])\n\n self.train_transform = self._get_train_transform()\n self.test_transform = self._get_test_transform()\n\n def _get_random_erasing_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize((32,32)),\n torchvision.transforms.ColorJitter(0.1,0.1,0.1),\n # torchvision.transforms.RandomRotation(15),\n # RandomAffine(degrees=15,scale=(0.8,1.2),shear=15),\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.random_erasing(\n self.config['random_erasing_prob'],\n self.config['random_erasing_area_ratio_range'],\n self.config['random_erasing_min_aspect_ratio'],\n self.config['random_erasing_max_attempt']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_cutout_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize((32,32)),\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.cutout(self.config['cutout_size'],\n self.config['cutout_prob'],\n self.config['cutout_inside']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_default_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize((32,32)),\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n def _get_test_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize((32,32)),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n\nclass MNIST(Dataset):\n def __init__(self, config):\n super(MNIST, self).__init__(config)\n\n self.mean = np.array([0.1307])\n self.std = np.array([0.3081])\n\n self.train_transform = self._get_train_transform()\n self.test_transform = self._get_default_transform()\n\n def _get_random_erasing_train_transform(self):\n transform = torchvision.transforms.Compose([\n transforms.normalize(self.mean, self.std),\n transforms.random_erasing(\n self.config['random_erasing_prob'],\n self.config['random_erasing_area_ratio_range'],\n self.config['random_erasing_min_aspect_ratio'],\n self.config['random_erasing_max_attempt']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_cutout_train_transform(self):\n transform = torchvision.transforms.Compose([\n transforms.normalize(self.mean, self.std),\n transforms.cutout(self.config['cutout_size'],\n self.config['cutout_prob'],\n self.config['cutout_inside']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_default_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n def _get_default_train_transform(self):\n return self._get_default_transform()\n\n def _get_default_test_transform(self):\n return self._get_default_transform()\n\n\nclass FashionMNIST(Dataset):\n def __init__(self, config):\n super(FashionMNIST, self).__init__(config)\n\n self.mean = np.array([0.2860])\n self.std = np.array([0.3530])\n\n self.train_transform = self._get_train_transform()\n self.test_transform = self._get_default_transform()\n\n def _get_random_erasing_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(28, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.random_erasing(\n self.config['random_erasing_prob'],\n self.config['random_erasing_area_ratio_range'],\n self.config['random_erasing_min_aspect_ratio'],\n self.config['random_erasing_max_attempt']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_cutout_train_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(28, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n transforms.normalize(self.mean, self.std),\n transforms.cutout(self.config['cutout_size'],\n self.config['cutout_prob'],\n self.config['cutout_inside']),\n transforms.to_tensor(),\n ])\n return transform\n\n def _get_default_transform(self):\n transform = torchvision.transforms.Compose([\n torchvision.transforms.RandomCrop(32, padding=4),\n torchvision.transforms.RandomHorizontalFlip(),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(self.mean, self.std),\n ])\n return transform\n\n def _get_default_train_transform(self):\n return self._get_default_transform()\n\n def _get_default_test_transform(self):\n return self._get_default_transform()\n\n\ndef get_loader(config):\n batch_size = config['batch_size']\n num_workers = config['num_workers']\n use_gpu = config['use_gpu']\n\n dataset_name = config['dataset']\n assert dataset_name in ['Icons', 'CIFAR10', 'CIFAR100', 'MNIST', 'FashionMNIST']\n\n if dataset_name in ['CIFAR10', 'CIFAR100']:\n dataset = CIFAR(config)\n elif dataset_name == 'MNIST':\n dataset = MNIST(config)\n elif dataset_name == 'FashionMNIST':\n dataset = FashionMNIST(config)\n\n # train_dataset, test_dataset = dataset.get_datasets()\n\n elif dataset_name == 'Icons':\n dataset = Icons(config, dataset_dir=\"/share/data/vision-greg/DistortedImageNet/Icons-50\")\n train_dataset, test_dataset = dataset.get_datasets(icons=True)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_workers,\n pin_memory=use_gpu,\n drop_last=True,\n )\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=False,\n pin_memory=use_gpu,\n drop_last=False,\n )\n return train_loader, test_loader\n","sub_path":"Icons-50/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":15366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"582494835","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport cv2\nimport numpy as np\nurl=\"http://192.168.1.3:8080/video\"\n\n\n# In[2]:\n\n\ncp=cv2.VideoCapture(url)\n\n\n# In[3]:\n\n\nwhile(True):\n ret,frame=cp.read()\n if frame is not None:\n cv2.imshow(\"frame\",frame)\n q=cv2.waitKey(1)\n if q==ord(\"q\"):\n break\ncv2.destroyAllWindows()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"video_capture.py","file_name":"video_capture.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"162362745","text":"from turtle import Turtle, Screen\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nfrom scoreboard import Scoreboard\r\nimport time\r\n\r\n# Create the screen\r\n\r\nscreen = Screen()\r\nscreen.setup(width=800, height=600)\r\nscreen.bgcolor(\"black\")\r\nscreen.title(\"Pong\")\r\nscreen.tracer(0)\r\n\r\n# Create and move a paddle\r\nr_paddle = Paddle((375, 0))\r\nl_paddle = Paddle((-380, 0))\r\nball = Ball()\r\nscoreboard = Scoreboard()\r\nscoreboard.update_scoreboard()\r\n\r\n\r\n\r\nscreen.listen()\r\nscreen.onkey(r_paddle.go_up, \"Up\")\r\nscreen.onkey(r_paddle.go_down, \"Down\")\r\nscreen.onkey(l_paddle.go_up, \"w\")\r\nscreen.onkey(l_paddle.go_down, \"s\")\r\n\r\n\r\ngame_is_on = True\r\nwhile game_is_on:\r\n time.sleep(ball.move_speed)\r\n screen.update()\r\n ball.move()\r\n# Create another paddle\r\n# Create the ball and make it move\r\n # Detect collision with wall and bounce\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce_y()\r\n\r\n # Detect collision with the left and the right paddle\r\n if ball.distance(r_paddle) < 50 and ball.xcor() > 340 or ball.distance(l_paddle) < 50 and ball.xcor() < -340:\r\n ball.bounce_x()\r\n\r\n # Detect when right paddle misses\r\n if ball.xcor() > 395:\r\n ball.reset_position()\r\n scoreboard.l_point()\r\n scoreboard.update_scoreboard()\r\n\r\n # Detect when left paddle misses\r\n if ball.xcor() < -400:\r\n ball.reset_position()\r\n scoreboard.r_point()\r\n scoreboard.update_scoreboard()\r\n\r\n# Keep score\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nscreen.exitonclick()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"211750510","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nimport scrapy\nfrom scrapy import Selector\nfrom scrapy.loader import ItemLoader\nfrom itemloaders.processors import MapCompose, TakeFirst\n\nfrom exchanges.taifex.items import FutureCodeItem\n\n\nclass FutureCodeSpider(scrapy.Spider):\n name = 'taifex_future_code'\n allowed_domains = ['www.taifex.com.tw']\n date = datetime.date.today().strftime(\"%Y%m%d\")\n\n def start_requests(self):\n self.logger.info(f'Parsing date: {self.date}')\n yield scrapy.Request(\n 'https://www.taifex.com.tw/cht/2/stockLists',\n self.parse)\n\n def parse(self, response):\n x_paths = [\n ('code', '//td[1]/text()'),\n ('underlying', '//td[3]/text()')\n ]\n rows = response.xpath('//tr[count(td)=10]').extract()\n for row in rows:\n loader = ItemLoader(item=FutureCodeItem(), selector=Selector(text=row))\n loader.default_input_processor = MapCompose(str, str.strip)\n loader.default_output_processor = TakeFirst()\n for field, path in x_paths:\n loader.add_xpath(field, path)\n yield loader.load_item()\n","sub_path":"exchanges/taifex/spiders/future/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"225969327","text":"import numpy as np\nimport shelve\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport logging\nimport time\nimport matplotlib.ticker as ticker\nimport sea\nfrom computers import gp\nimport os\n\ndef kerneldef5(h, k):\n \"\"\"Define the kernel used in the classifier\"\"\"\n return h(1e-4, 1e4, 10)*k('gaussian', \n [h(1e-4, 1e4, 0.1), h(1e-4, 1e4, 0.1), h(1e-4, 1e4, 0.1), \n h(1e-4, 1e4, 0.1), h(1e-4, 1e4, 0.1)])\n\ndef kerneldef3(h, k):\n \"\"\"Define the kernel used in the classifier\"\"\"\n return h(1e-4, 1e4, 10)*k('gaussian', \n [h(1e-4, 1e4, 0.1), h(1e-4, 1e4, 0.1), h(1e-4, 1e4, 0.1)])\n\ndef main():\n\n logging.basicConfig(level = logging.DEBUG)\n\n main_directory = \"../../../Thesis/Results/scott-reef/\"\n directory = main_directory + \"loc1_new_20150827_072830__method_MCJE_start_377500_8440000_hsteps30_horizon5000/\"\n trials = np.arange(25, 201, 25)\n logging.info(trials)\n\n save_directory = directory + 'PostProcess/'\n os.mkdir(save_directory) if not os.path.exists(save_directory) else None\n\n data = load_data()\n for i in trials:\n logging.info('Saving for trial %d...' % i)\n filename = directory + \"history%d.npz\" % i\n npzfile = dict(np.load(filename))\n save_maps(*data, full_directory = save_directory, **npzfile)\n logging.info('Finished saving for trial %d' % i)\n\ndef load_data():\n\n \"\"\"File Locations\"\"\"\n directory_data = '../../../Thesis/Data/'\n filename_training_data = 'training_data_unmerged.npz'\n filename_query_points = 'query_points.npz'\n filename_truth = directory_data + 'truthmodel_t800_q100000_ts250_qs500.npz'\n filename_start = directory_data + 'finalmodel_t200_q100000_ts250_qs500'\\\n '_method_LDE_start377500_8440000_hsteps30_horizon5000.npz'\n\n T_SEED = sea.io.parse('-tseed', 250)\n Q_SEED = sea.io.parse('-qseed', 500) \n N_TRAIN = sea.io.parse('-ntrain', 200)\n N_QUERY = sea.io.parse('-nquery', 100000)\n i_features = [0, 1, 2, 3, 4]\n\n X, F, y, Xq, Fq, i_train, i_query = \\\n sea.io.sample(*sea.io.load(directory_data, \n filename_training_data, filename_query_points), \n n_train = N_TRAIN, n_query = N_QUERY,\n t_seed = T_SEED, q_seed = Q_SEED, features = i_features)\n\n return X, F, y, Xq, Fq\n\ndef save_maps( X, F, y, Xq, Fq,\n full_directory = '',\n yq_mie = None,\n yq_lde = None,\n yq_pred = None,\n miss_ratio_array = None,\n vis_range = None,\n xq1_nows = None,\n xq2_nows = None,\n yq_nows = None,\n xq1_path = None,\n xq2_path = None,\n yq_path = None,\n y_unique = None,\n mycmap = None,\n xq_now = None,\n yq_now = None,\n horizon = None,\n colorcenter_analysis = None,\n colorcenter_lde = None,\n r = None,\n i_trials = None,\n **kwargs):\n\n # Plot the current situation\n fig1 = plt.figure(1, figsize = (19.2, 10.8))\n fig2 = plt.figure(2, figsize = (19.2, 10.8))\n fig3 = plt.figure(3, figsize = (19.2, 10.8))\n fig4 = plt.figure(4, figsize = (19.2, 10.8))\n fig5 = plt.figure(5, figsize = (19.2, 10.8))\n\n mycmap = cm.get_cmap(name = 'jet', lut = None)\n horizon = 5000.0\n h_steps = 30\n r = horizon/h_steps\n colorcenter_lde = colorcenter_analysis\n FONTSIZE = 50\n FONTNAME = 'Sans Serif'\n TICKSIZE = 24\n SAVE_TRIALS = 25\n\n i_trials -= 1\n miss_ratio = miss_ratio_array[i_trials]\n\n y_names_all = [ 'None',\n 'Under-Exposed', \n 'Under-Exposed',\n 'Barron Sand 1',\n 'Low Density Coral 1',\n 'Sand Biota 1',\n 'Low Density Coral 2',\n 'Dense Coral 1',\n 'Dense Coral 2',\n 'Dense Coral 3',\n 'Sand Biota 2',\n 'Low Density Coral 3',\n 'Low Density Coral 4',\n 'Patch 1',\n 'Patch 2',\n 'Patch 3',\n 'Barron Sand 2',\n 'Sand Biota 3',\n 'Over-Exposed',\n 'Barron Sand 3',\n 'Under-Exposed',\n 'Under-Exposed',\n 'Sand Biota 4',\n 'Misc',\n 'Under-Exposed']\n\n y_names = [y_names_all[i] for i in y_unique.astype(int)]\n\n # map_kwargs = {'alpha': 0.5, 'edgecolors': 'none', 's': 15}\n map_kwargs = {'marker': 'x', 's': 5}\n\n \"\"\" Linearised Model Differential Entropy Map \"\"\"\n logging.info('Saving Linearised Model Differential Entropy Map')\n\n # Prepare Figure 1\n plt.figure(fig1.number)\n plt.clf()\n sea.vis.scatter(\n Xq[:, 0], Xq[:, 1], \n c = yq_lde, cmap = cm.coolwarm, colorcenter = colorcenter_lde, \n **map_kwargs)\n sea.vis.describe_plot(title = 'Linearised Model Differential Entropy', \n xlabel = 'x [Eastings (km)]', ylabel = 'y [Northings (km)]', \n clabel = 'Differential Entropy',\n vis_range = vis_range, aspect_equal = True, \n fontsize = FONTSIZE, fontname = FONTNAME, ticksize = TICKSIZE, \n axis_scale = 1e3)\n\n # Plot the path on top\n sea.vis.scatter(xq1_nows, xq2_nows, c = yq_nows, s = 60, \n facecolors = 'none', \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n sea.vis.plot(xq1_nows, xq2_nows, c = 'k', linewidth = 2)\n sea.vis.scatter(xq_now[:, 0], xq_now[:, 1], c = yq_now, s = 120, \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n\n # Plot the horizon\n gp.classifier.utils.plot_circle(xq_now[-1], horizon, c = 'k', \n linewidth = 2, marker = '.')\n\n plt.gca().arrow(xq_now[-1][0], xq_now[-1][1] + r, 0, -r/4, \n head_width = r/4, head_length = r/4, fc = 'k', ec = 'k')\n\n # Save the plot\n fig1.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%slde%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%slde%d.eps' \n % (full_directory, i_trials + 1))\n\n # Plot the proposed path\n sea.vis.scatter(xq1_path, xq2_path, c = yq_path, \n s = 60, marker = 'D', \n vmin = y_unique[0], vmax = y_unique[-1], cmap = mycmap)\n sea.vis.plot(xq1_path, xq2_path, c = 'k', linewidth = 2)\n\n # Save the plot\n fig1.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%slde_propose%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%slde_propose%d.eps' \n % (full_directory, i_trials + 1))\n\n \"\"\" True Entropy Map \"\"\"\n logging.info('Saving Prediction Information Entropy Map')\n\n # Prepare Figure 3\n plt.figure(fig3.number)\n plt.clf()\n sea.vis.scatter(\n Xq[:, 0], Xq[:, 1], \n c = yq_mie, cmap = cm.coolwarm, colorcenter = colorcenter_analysis, \n **map_kwargs)\n sea.vis.describe_plot(title = 'Prediction Information Entropy', \n xlabel = 'x [Eastings (km)]', ylabel = 'y [Northings (km)]', \n clabel = 'Information Entropy',\n vis_range = vis_range, aspect_equal = True, \n fontsize = FONTSIZE, fontname = FONTNAME, ticksize = TICKSIZE, \n axis_scale = 1e3)\n\n # Plot the path on top\n sea.vis.scatter(xq1_nows, xq2_nows, c = yq_nows, s = 60, \n facecolors = 'none', \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n sea.vis.plot(xq1_nows, xq2_nows, c = 'k', linewidth = 2)\n sea.vis.scatter(xq_now[:, 0], xq_now[:, 1], c = yq_now, s = 120, \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n\n # Save the plot\n fig3.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%smie%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%smie%d.eps' \n % (full_directory, i_trials + 1))\n\n # Plot the horizon\n gp.classifier.utils.plot_circle(xq_now[-1], horizon, c = 'k', \n linewidth = 2, marker = '.')\n\n plt.gca().arrow(xq_now[-1][0], xq_now[-1][1] + r, 0, -r/4, \n head_width = r/4, head_length = r/4, fc = 'k', ec = 'k')\n\n # Plot the proposed path\n sea.vis.scatter(xq1_path, xq2_path, c = yq_path, \n s = 60, marker = 'D', \n vmin = y_unique[0], vmax = y_unique[-1], cmap = mycmap)\n sea.vis.plot(xq1_path, xq2_path, c = 'k', linewidth = 2)\n\n # Save the plot\n fig3.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%smie_propose%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%smie_propose%d.eps' \n % (full_directory, i_trials + 1))\n\n \"\"\" Class Prediction Map \"\"\"\n logging.info('Saving Class Prediction Map')\n\n # Prepare Figure 4\n plt.figure(fig4.number)\n plt.clf()\n sea.vis.scatter(\n Xq[:, 0], Xq[:, 1], \n c = yq_pred, vmin = y_unique[0], vmax = y_unique[-1], cmap = mycmap, \n **map_kwargs)\n sea.vis.describe_plot(\n title = 'Prediction Map [Miss Ratio: {0:.2f}{1}]'.format(\n 100 * miss_ratio, '%'), \n xlabel = 'x [Eastings (km)]', ylabel = 'y [Northings (km)]', \n clabel = 'Habitat Labels', cticks = y_unique, cticklabels = y_names,\n vis_range = vis_range, aspect_equal = True, \n fontsize = FONTSIZE, fontname = FONTNAME, ticksize = TICKSIZE, \n axis_scale = 1e3)\n\n # Plot the path on top\n sea.vis.scatter(xq1_nows, xq2_nows, c = yq_nows, s = 60, \n facecolors = 'none', \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n sea.vis.plot(xq1_nows, xq2_nows, c = 'k', linewidth = 2)\n sea.vis.scatter(xq_now[:, 0], xq_now[:, 1], c = yq_now, s = 120, \n vmin = y_unique[0], vmax = y_unique[-1], \n cmap = mycmap)\n\n # Plot the horizon\n gp.classifier.utils.plot_circle(xq_now[-1], horizon, c = 'k', \n linewidth = 2, marker = '.')\n\n plt.gca().arrow(xq_now[-1][0], xq_now[-1][1] + r, 0, -r/4, \n head_width = r/4, head_length = r/4, fc = 'k', ec = 'k')\n\n # Save the plot\n fig4.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%spred%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%spred%d.eps' \n % (full_directory, i_trials + 1))\n\n # Plot the proposed path\n sea.vis.scatter(xq1_path, xq2_path, c = yq_path, \n s = 60, marker = 'D', \n vmin = y_unique[0], vmax = y_unique[-1], cmap = mycmap)\n sea.vis.plot(xq1_path, xq2_path, c = 'k', linewidth = 2)\n\n # Save the plot\n fig4.tight_layout()\n plt.gca().set_aspect('equal', adjustable = 'box')\n plt.savefig('%spred_propose%d.png' \n % (full_directory, i_trials + 1))\n if (i_trials == 0) or (((i_trials + 1) % SAVE_TRIALS) == 0):\n plt.savefig('%spred_propose%d.eps' \n % (full_directory, i_trials + 1))\n\nif __name__ == \"__main__\":\n main()","sub_path":"informative-seafloor-exploration/scott_reef_snapshots.py","file_name":"scott_reef_snapshots.py","file_ext":"py","file_size_in_byte":11458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"403838755","text":"import sys\ndef main_interface():\n select = input('请输入相关指令代码:')\n if select == '1':\n Refer()\n elif select == '2':\n New_contact()\n elif select == '3':\n Delet()\n elif select == '4':\n sys.exit(0)\n\ndef New_contact():\n global Phone_book\n name = input('请输入联系人姓名:')\n if name in Phone_book.keys():\n print('您输入的用户名在通讯录中已存在-->>{0}:{1}'.format(name, Phone_book[name]))\n choice = input('是否更改用户(Yes/No):')\n if choice == 'Yes' or choice == 'Yes' or choice == 'yes' or choice == 'y':\n change = input('请输入用户联系电话:')\n Phone_book[name] = change\n main_interface()\n else:\n main_interface()\n else:\n choice = input('您输入的用户不存在,是否新建用户(Yes/No):')\n if choice == 'Yes' or choice == 'Yes' or choice == 'yes' or choice == 'y':\n usename = input('请输入联系人姓名:')\n phonenum = input('请输入联系人电话号码')\n Phone_book[usename] = phonenum\n print('用户插入成功')\n main_interface()\n else:\n main_interface()\n\ndef Delet():\n global Phone_book\n name = input('请输入联系人姓名:')\n if name in Phone_book.keys():\n print('您输入的用户名在通讯录中已存在-->>{0}:{1}'.format(name,Phone_book[name]))\n choice = input('是否删除用户(Yes/No):')\n if choice == 'Yes' or choice == 'Yes' or choice == 'yes' or choice == 'y':\n Phone_book.pop(name)\n print('用户已删除')\n main_interface()\n else:\n main_interface()\n else:\n print('您输入的用户不存在')\n main_interface()\ndef Refer():\n global Phone_book\n name = input('请输入联系人姓名:')\n if name in Phone_book.keys():\n print('您输入的用户名在通讯录中已存在-->>{0}:{1}'.format(name, Phone_book[name]))\n main_interface()\n else:\n print('您输入的用户不存在')\n main_interface()\n\nglobal Phone_book\nPhone_book = dict()\nprint('1.查询联系人资料')\nprint('2.插入新的联系人')\nprint('3.删除已有联系人')\nprint('4.退出程序')\nmain_interface()","sub_path":"PythonProject/AddressBook.py","file_name":"AddressBook.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"180822115","text":"import os\nfrom scipy.ndimage import zoom\nfrom warnings import warn\nfrom classes import DatasetSAX\n\n\ndef rezoom(in_data, t_dim=30, x_dim=128, y_dim=128):\n return zoom(in_data.images, [1,\n t_dim/in_data.images.shape[1], \n x_dim/in_data.images.shape[2], \n y_dim/in_data.images.shape[3]])\n\n\ndef read_and_process(in_path, t_dim, x_dim, y_dim, withErrCatch=False): # reads data in with pre-defined function and scales it to 128x128\n \"\"\"Function that creates an object of the DatasetSAX class and processes it further.\n Zooms every image to the size t_dim*x_dim*y_dim.\n \n Input:\n in_path: Path to the patient (parent) folder.\n t_dim: Number of time frames of the output image sequence.\n x_dim: Width of the output images.\n y_dim: Height of the output images.\n withErrCatch: Specifies if errors should be caught (True) or stop code execution (False)\n\n Output:\n list of in_path, zoom_time, area_multiplier and zoomed image stack. \n\n zoom_time is a list of the new time stamps of the slices (if != t_dim; shrinks/expands it to t_dim) \n area_multiplier is the area of the image in mm (calculated from metadata PixelSpacing)\n \"\"\"\n if withErrCatch:\n try:\n cur_data = DatasetSAX(in_path, os.path.basename(in_path)) \n # os.path.basename gets the name of the lowest folder\n cur_data.load()\n if cur_data.time is not None: # when would that ever be none? only if no sax data was found? but then there would be a problem anyway!?\n zoom_time = zoom(cur_data.time, [t_dim/len(cur_data.time)]) \n else:\n zoom_time = range(t_dim)\n return [in_path, zoom_time, cur_data.area_multiplier, rezoom(cur_data, t_dim, x_dim, y_dim)] # scale single images to size (?,30,128,128)\n #return {'path': in_path, 'time': zoom_time, 'area': cur_data.area_multiplier, 'images': rezoom(cur_data, t_dim=30, x_dim=128, y_dim=128)} \n except Exception as e: # catches exceptions without letting them stop the code\n warn('{}'.format(e), RuntimeWarning)\n return None\n else:\n cur_data = DatasetSAX(in_path, os.path.basename(in_path)) \n cur_data.load()\n if cur_data.time is not None: # when would that ever be none? only if no sax data was found? but then there would be a problem anyway!?\n zoom_time = zoom(cur_data.time, [t_dim/len(cur_data.time)]) \n else:\n zoom_time = range(t_dim)\n return [in_path, zoom_time, cur_data.area_multiplier, rezoom(cur_data, t_dim, x_dim, y_dim)] # scale images\n #return {'path': in_path, 'time': zoom_time, 'area': cur_data.area_multiplier, 'images': rezoom(cur_data, t_dim=30, x_dim=128, y_dim=128)} ","sub_path":"tutorial_kaggle/utils/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"237236460","text":"#!/usr/bin/python\n\n# python simpleplot.py \n# Tested for python3 Qt5\n\nimport sys\nsys.path.append(\"../sip\")\nimport Qwt\nimport numpy as np\nfrom PyQt5.QtCore import Qt, QSize\nfrom PyQt5.QtGui import QBrush, QPen\nfrom PyQt5.QtWidgets import QApplication\n\na = QApplication(sys.argv)\n\nplot=Qwt.QwtPlot()\nplot.setTitle(\"Plot Demo\")\nplot.setCanvasBackground(Qt.white)\nplot.insertLegend( Qwt.QwtLegend() )\ngrid = Qwt.QwtPlotGrid()\ngrid.attach( plot )\n\ncurve = Qwt.QwtPlotCurve()\ncurve.setTitle(\"Some Points\")\ncurve.setPen(Qt.blue,4)\ncurve.setRenderHint( Qwt.QwtPlotItem.RenderAntialiased, True );\n\nsymbol = Qwt.QwtSymbol( Qwt.QwtSymbol.Ellipse, QBrush( Qt.yellow ), QPen( Qt.red, 2 ), QSize( 8, 8 ) );\ncurve.setSymbol( symbol )\n\nx=np.arange(0,10,0.1)\ny=np.sin(x)\ncurve.setSamples(x,y)\ncurve.attach(plot)\n\nplot.resize(600,400)\nplot.replot()\nplot.show()\nsys.exit(a.exec_())\n","sub_path":"qt5examples/simpleplot.py","file_name":"simpleplot.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"205103339","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom setuptools import setup, find_packages\n\nversion, license = None, None\nwith open('people/__init__.py', 'r') as fd:\n content = fd.read()\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', content, re.MULTILINE).group(1)\n license = re.search(r'^__license__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', content, re.MULTILINE).group(1)\nif version is None: raise RuntimeError('Cannot find version information')\nif license is None: raise RuntimeError('Cannot find license information')\n\nwith open('README.md', 'r') as fd:\n long_description = fd.read()\n\nsetup(\n name='core-people',\n version=version,\n description='Research CORE ERM - people module',\n author='Ricardo Ribeiro, Hugo Cachitas',\n author_email='ricardojvr@gmail.com, hugo.cachitas@research.fchampalimaud.org',\n url='https://github.com/research-core/core-people',\n long_description=long_description,\n long_description_content_type='text/markdown',\n packages=find_packages(),\n license=license,\n install_requires=['core-common'],\n package_data={\n 'people': [\n 'fixtures/initial_data.yaml',\n 'static/img/*.png',\n 'static/*.png',\n ]\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"552710330","text":"import logging\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport os\nfrom configparser import ConfigParser\nimport subprocess\n\n# read config.ini file\nconfig_file = 'config.ini'\nconfig = ConfigParser()\nconfig.read(config_file)\n\nTOKEN = config['heroku_bot']['TOKEN']\nLINK = config['heroku_bot']['LINK']\n\n# set port number to listen in for the webhook\nPORT = int(os.environ.get('PORT', 5000))\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n# Define a few command handlers. These usually take the two arguments update and\n# context. Error handlers also receive the raised TelegramError object in error.\ndef start(update, context):\n \"\"\"Send a message when the command /start is issued.\"\"\"\n update.message.reply_text(\"Hi! I'm a Mask detective. Send me a picture and I will tell you who's wearing a mask!!\")\n\ndef object_detection(update, context):\n cid = update.message.chat.id\n image_id = context.bot.get_file(update.message.photo[-1].file_id)\n context.bot.send_message(cid, f'Analyzing image...')\n image_id.download('darknet/image.jpg')\n cwd = os.getcwd()\n os.chdir(cwd + '/darknet')\n subprocess.run(['chmod', 'a+x', 'darknet'])\n subprocess.run(['./darknet', 'detect', 'yolo-obj.cfg', 'yolo-obj_best_v2.weights', 'image.jpg', '-dont-show'])\n os.chdir(cwd)\n context.bot.send_photo(cid, open('darknet/predictions.jpg','rb'))\n\n# def help(update, context):\n# \"\"\"Send a message when the command /help is issued.\"\"\"\n# update.message.reply_text('Help!')\n\n# def echo(update, context):\n# \"\"\"Echo the user message.\"\"\"\n# update.message.reply_text(update.message.text)\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n # Make sure to set use_context=True to use the new context based callbacks\n # Post version 12 this will no longer be necessary\n updater = Updater(TOKEN, use_context=True)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", start))\n # dp.add_handler(CommandHandler(\"help\", help))\n\n # on noncommand i.e message - echo the message on Telegram\n # dp.add_handler(MessageHandler(Filters.text, echo))\n \n dp.add_handler(MessageHandler(Filters.photo, object_detection))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_webhook(listen=\"0.0.0.0\",\n port=int(PORT),\n url_path=TOKEN)\n updater.bot.setWebhook(LINK + TOKEN)\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\nif __name__ == '__main__':\n main()","sub_path":"telegram_bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"43422406","text":"import os\nfrom textx.metamodel import metamodel_from_file\n\nmm = metamodel_from_file(\n os.path.join(os.path.dirname(__file__), '../../grammar/units.tx'))\n\n\ndef test_unit():\n from textwrap import dedent\n u = dedent('''UNITS {\n (mV) = (millivolt)\n (mA) = (milliamp)\n }\n ''')\n ud = mm.model_from_str(u).unit_defs[1]\n l = ud.name\n r = ud.base_unit\n assert((l, r) == ('(mA)', '(milliamp)'))\n\n","sub_path":"pynmodl/tests/parsing/test_parse_units.py","file_name":"test_parse_units.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"185637748","text":"from pathlib import Path\n\nimport os\nimport sys\n\n__all__ = [\n 'extract_info',\n 'reload_import',\n 'to_str'\n]\n\n\ndef extract_info(exception):\n exc_type, exc_obj, exc_tb = sys.exc_info()\n filename = exc_tb.tb_frame.f_code.co_filename\n try:\n reason = eval(str(exception))\n except Exception:\n reason = str(exception)\n return dict(reason=reason, filename=filename, line=exc_tb.tb_lineno)\n\n\ndef reload_import(error):\n error_data = str(error).split()\n if ['cannot', 'import'] == error_data[0:2]:\n name = error_data[2]\n path = Path(__file__).parent / '../requirements.txt'\n with path.open('r') as req_file:\n for mod in req_file:\n if mod == name.replace('_', '-'):\n os.system('pip3 install -r requirements.txt')\n break\n print(f'Error: {error}')\n sys.exit(1)\n\n\ndef to_str(exception):\n info = extract_info(exception)\n return f'{info[\"reason\"]} on filename:{info[\"filename\"]} at line:{info[\"line\"]}'\n","sub_path":"utils/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"402312895","text":"from companies.models import Company\nfrom django import forms\nfrom documents.defs import get_categories_for_mimes\nfrom documents.models import Document\nfrom kala.templatetags.kala_tags import pretty_user\nfrom .models import Project\n\n\nclass CategoryForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.project = kwargs.pop('project')\n super(CategoryForm, self).__init__(*args, **kwargs)\n\n self.fields['category'] = forms.ChoiceField(choices=get_categories_for_mimes(\n Document.objects.active().filter(project=self.project).distinct('mime').order_by('mime').values_list(\n 'mime')), widget=forms.Select(attrs={'class': 'span3'}))\n\n\nclass CompanyForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.project = kwargs.pop('project')\n super(CompanyForm, self).__init__(*args, **kwargs)\n\n self.fields['company'] = forms.ModelChoiceField(queryset=Company.objects.active(),\n initial=self.project.company,\n widget=forms.Select(attrs={'class': 'span3'}))\n\n def save(self):\n self.project.company = self.cleaned_data['company']\n self.project.save()\n return self.project\n\n\nclass DeleteProjectsForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(DeleteProjectsForm, self).__init__(*args, **kwargs)\n\n choices = []\n for company in Company.objects.active().filter(pk__in=Project.objects.deleted().values('company')):\n projects = [(project.pk, project.name) for project in Project.objects.deleted().filter(company=company)]\n choices.append((company.name, projects))\n\n self.fields['project'] = forms.ChoiceField(choices=choices, widget=forms.Select(attrs={'class': 'span3'}))\n\n def save(self):\n project = Project.objects.deleted().get(pk=self.cleaned_data['project'])\n project.set_active(True)\n return project\n\n\ndef permission_forms(request, project):\n forms = [PermissionsForm(request.POST or None, project=project, company=project.company)]\n for company in Company.objects.active().exclude(pk=project.company.pk):\n forms.append(PermissionsForm(request.POST or None, project=project, company=company))\n return forms\n\n\nclass PermissionsForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.project = kwargs.pop('project')\n self.company = kwargs.pop('company')\n self.people = self.company.get_people_list()\n super(PermissionsForm, self).__init__(*args, **kwargs)\n self.fields[self.company] = forms.BooleanField(required=False, label='Select/Unselect All',\n widget=forms.CheckboxInput(\n attrs={'class': 'company_checkbox',\n 'pk_id': self.company.pk,\n }))\n\n for person in self.people:\n self.fields['%i' % person.pk] = forms.BooleanField(required=False, label=pretty_user(person),\n initial=True if self.project.clients.filter(\n pk=person.pk).exists() else False,\n widget=forms.CheckboxInput(\n attrs={'pk': self.company.pk}))\n\n def save(self):\n for person in self.people:\n is_selected = self.cleaned_data['%i' % person.pk]\n if is_selected:\n if not self.project.clients.filter(pk=person.pk).exists():\n self.project.clients.add(person)\n else:\n if self.project.clients.filter(pk=person.pk).exists():\n self.project.clients.remove(person)\n\n\nclass ProjectForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n self.company = kwargs.pop('company')\n self.is_admin = kwargs.pop('is_admin')\n super(ProjectForm, self).__init__(*args, **kwargs)\n if self.is_admin:\n self.fields['company'] = forms.ModelChoiceField(queryset=Company.objects.active(), initial=self.company,\n widget=forms.Select(attrs={'class': 'span3'}))\n\n class Meta:\n model = Project\n fields = ('name', 'company')\n widgets = {\n 'name': forms.TextInput(attrs={'class': 'span3'})\n }\n\n def save(self, commit=True):\n if self.is_admin:\n self.instance.owner = self.cleaned_data['company']\n else:\n self.instance.owner = self.company\n project = super(ProjectForm, self).save(commit)\n # Add all of the companies accounts to the project.\n #[self.instance.clients.add(person) for person in Person.active.filter(company=self.company)]\n return project\n\n\nclass SortForm(forms.Form):\n search = forms.ChoiceField(choices=(('DATE', 'Sort by Date'), ('AZ', 'Sort Alphabetically')),\n widget=forms.RadioSelect,\n initial='DATE')\n\n\n\n","sub_path":"projects/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"264329854","text":"# -*- coding: utf-8 -*-\n#COMECE AQUI ABAIXO\ndef valorabsoluto(x):\n if (x<0):\n x=x*(-1)\n else:\n x=x*1\n return(x) \n \ndef pi(m):\n cont=0\n soma=3\n a=0\n b=2\n for i in range (1, m+1, 1):\n a=4/(b*(b+1)*(b+2))\n cont=cont+1\n if (cont%2==1):\n soma=soma+a\n if (cont%2==0):\n soma=soma-a \n b=b+2\n return(soma)\n\ndef fat(d):\n f=1\n while (d>0):\n f=f*d\n d=d-1\n return(f)\n \ndef cos(x, epsilon):\n cont=0\n soma=1\n d=2\n c=(x**d)/fat(d)\n while (c>epsilon): \n cont=cont+1\n if (cont%2==1):\n soma=soma-c\n if (cont%2==0):\n soma=soma+c\n d=d+2\n c=(x**d)/fat(d) \n return(soma)\n \ndef razaoaurea(m, epsilon):\n e=pi(m)/5\n g=cos((e),(epsilon))\n razao=2*g\n return(razao)\n\n\nm=int(input('Digite o número de termos para PI: '))\nepsilon=float(input('Digite o epsilon para o cálculo da razão aurea: '))\nprint('%.15f' %pi(m))\nprint('%.15f' %cos(x, epsilon))\nprint('%.15f' %razaoaurea(m, epsilon))","sub_path":"moodledata/vpl_data/59/usersdata/164/61315/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394970504","text":"from discord.ext import commands\nfrom .utils import config, checks\nfrom urllib.request import urlopen\nimport json\nimport discord\nimport asyncio\n\nclass XKCD:\n \n def __init__(self, bot):\n self.bot = bot\n \n async def formatter(self, data):\n \"\"\"Formats the XKCD json data\"\"\"\n day = 'day'\n month = 'month'\n year = 'year'\n number = 'num'\n title = 'title'\n hidden = 'alt'\n image = 'img'\n \n template = '```Date: {} \\nNumber: {} \\nTitle: {} \\nTooltip Text: {} \\n```{}'\n \n day = data[day]\n month = data[month]\n year = data[year]\n number = data[number]\n title = data[title]\n hidden = data[hidden]\n image = data[image]\n \n date = '{}-{}-{}'.format(month, day, year)\n \n complete = template.format(date, number, title, hidden, image)\n \n return complete\n \n @commands.command()\n async def xkcd(self, number=None):\n \"\"\"Get your favorite XKCD comics and their attributes!\"\"\"\n \n if number == None:\n with urlopen('http://xkcd.com/info.0.json') as comic:\n comic = comic.read().decode('utf8')\n comic = json.loads(comic)\n await self.bot.say(await self.formatter(comic))\n else:\n try:\n with urlopen('http://xkcd.com/{}/info.0.json'.format(number)) as comic:\n comic = comic.read().decode('utf8')\n comic = json.loads(comic)\n await self.bot.say(await self.formatter(comic))\n except:\n await self.bot.say('Not a valid comic number')\n \ndef setup(bot):\n bot.add_cog(XKCD(bot))","sub_path":"cogs/xkcd.py","file_name":"xkcd.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"527508003","text":"# meds/run/rss.py\n#\n#\n\n\"\"\" runtime code to intialize RSS. \"\"\"\n\nfrom meds.core import kernel, launcher, objs, storage\nfrom meds.object import Object\nfrom meds.rss import RSS\n\nimport logging\n\ndef init(event):\n objs.RSS = RSS()\n objs.RSS.start()\n\ndef shutdown(event):\n if \"RSS\" in objs:\n objs.RSS.stop()\n \ndef fetcher(event):\n event.reply(\"fetching\")\n if \"RSS\" not in objs: objs.RSS = RSS()\n objs.RSS.fetcher()\n\nfetcher.threaded = True\n","sub_path":"venv/Lib/site-packages/meds/run/rss.py","file_name":"rss.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"82922213","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass POIinfo(object):\n\n def __init__(self):\n self._address = None\n self._businessarea = None\n self._direction = None\n self._distance = None\n self._id = None\n self._location = None\n self._name = None\n self._tel = None\n self._type = None\n\n @property\n def address(self):\n return self._address\n\n @address.setter\n def address(self, value):\n self._address = value\n @property\n def businessarea(self):\n return self._businessarea\n\n @businessarea.setter\n def businessarea(self, value):\n self._businessarea = value\n @property\n def direction(self):\n return self._direction\n\n @direction.setter\n def direction(self, value):\n self._direction = value\n @property\n def distance(self):\n return self._distance\n\n @distance.setter\n def distance(self, value):\n self._distance = value\n @property\n def id(self):\n return self._id\n\n @id.setter\n def id(self, value):\n self._id = value\n @property\n def location(self):\n return self._location\n\n @location.setter\n def location(self, value):\n self._location = value\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n @property\n def tel(self):\n return self._tel\n\n @tel.setter\n def tel(self, value):\n self._tel = value\n @property\n def type(self):\n return self._type\n\n @type.setter\n def type(self, value):\n self._type = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.address:\n if hasattr(self.address, 'to_alipay_dict'):\n params['address'] = self.address.to_alipay_dict()\n else:\n params['address'] = self.address\n if self.businessarea:\n if hasattr(self.businessarea, 'to_alipay_dict'):\n params['businessarea'] = self.businessarea.to_alipay_dict()\n else:\n params['businessarea'] = self.businessarea\n if self.direction:\n if hasattr(self.direction, 'to_alipay_dict'):\n params['direction'] = self.direction.to_alipay_dict()\n else:\n params['direction'] = self.direction\n if self.distance:\n if hasattr(self.distance, 'to_alipay_dict'):\n params['distance'] = self.distance.to_alipay_dict()\n else:\n params['distance'] = self.distance\n if self.id:\n if hasattr(self.id, 'to_alipay_dict'):\n params['id'] = self.id.to_alipay_dict()\n else:\n params['id'] = self.id\n if self.location:\n if hasattr(self.location, 'to_alipay_dict'):\n params['location'] = self.location.to_alipay_dict()\n else:\n params['location'] = self.location\n if self.name:\n if hasattr(self.name, 'to_alipay_dict'):\n params['name'] = self.name.to_alipay_dict()\n else:\n params['name'] = self.name\n if self.tel:\n if hasattr(self.tel, 'to_alipay_dict'):\n params['tel'] = self.tel.to_alipay_dict()\n else:\n params['tel'] = self.tel\n if self.type:\n if hasattr(self.type, 'to_alipay_dict'):\n params['type'] = self.type.to_alipay_dict()\n else:\n params['type'] = self.type\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = POIinfo()\n if 'address' in d:\n o.address = d['address']\n if 'businessarea' in d:\n o.businessarea = d['businessarea']\n if 'direction' in d:\n o.direction = d['direction']\n if 'distance' in d:\n o.distance = d['distance']\n if 'id' in d:\n o.id = d['id']\n if 'location' in d:\n o.location = d['location']\n if 'name' in d:\n o.name = d['name']\n if 'tel' in d:\n o.tel = d['tel']\n if 'type' in d:\n o.type = d['type']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/POIinfo.py","file_name":"POIinfo.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"597403493","text":"import re\nfname = input(\"Enter file name: \")\nfile=open(fname,'r')\nsuma=0\n\n\nfor x in file:\n\tline=x.rstrip()\n\tif re.findall(r'[0-9]+',line) == []: continue\n\n\telse:\n\t\tss=re.findall(r'[0-9]+',line)\n\t\tfor r in ss:\n\t\t\tsuma = suma+ int(r)\n\n\n\n#print(lst)\nprint(suma)","sub_path":"PythonToAccessWebData/regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"610463768","text":"# programmed under Python 3.4.\r\n\r\nimport tkinter\r\nfrom tkinter import ttk\r\nimport numpy\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.lines import Line2D\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\n\r\nGaussAvg = [[0, 0]]\r\nGaussCov = [[[1, 0], [0, 1]]]\r\nGaussProb = [-1.0]\r\nX = []; Y = []; F = []\r\n\r\n# mathematical functions --BEGIN--\r\ndef GaussianFunc_Mat(x, y, mu_average, CovarianceMatrix): \r\n pos_regular_X = X - mu_average[0]\r\n pos_regular_Y = Y - mu_average[1]\r\n det = CovarianceMatrix[0][0] * CovarianceMatrix[1][1] - CovarianceMatrix[0][1] * CovarianceMatrix[1][0]\r\n inv = numpy.array([[CovarianceMatrix[1][1], -CovarianceMatrix[1][0]], [-CovarianceMatrix[0][1], CovarianceMatrix[0][0]]])\r\n inv /= det\r\n X0 = inv[0][0] * pos_regular_X + inv[0][1] * pos_regular_Y\r\n Y0 = inv[1][0] * pos_regular_X + inv[1][1] * pos_regular_Y\r\n exponent=-(pos_regular_X * X0 + pos_regular_Y * Y0) / 2.0\r\n normalize_factor=1.0 / (2 * numpy.pi * numpy.sqrt(det))\r\n return numpy.exp(exponent) * normalize_factor\r\ndef GaussianFunc(position, mu_average, CovarianceMatrix): \r\n mu_tmp = numpy.array(mu_average)\r\n mu_tmp.shape = (2, 1)\r\n pos_regular = position - mu_tmp\r\n det = (CovarianceMatrix[0][0] * CovarianceMatrix[1][1] - CovarianceMatrix[0][1] * CovarianceMatrix[1][0])\r\n inv = numpy.array([[CovarianceMatrix[1][1], -CovarianceMatrix[1][0]], [-CovarianceMatrix[0][1], CovarianceMatrix[0][0]]])\r\n inv /= det\r\n exponent=-0.5 * numpy.dot(pos_regular.T, numpy.dot(inv, pos_regular))\r\n normalize_factor=1.0 / (2 * numpy.pi * numpy.sqrt(det))\r\n return numpy.exp(exponent) * normalize_factor\r\ndef GaussianFunc_1stDerivative(position, mu_average, CovarianceMatrix):\r\n mu_tmp = numpy.array(mu_average)\r\n mu_tmp.shape = (2, 1)\r\n pos_regular = position - mu_tmp\r\n det = (CovarianceMatrix[0][0] * CovarianceMatrix[1][1] - CovarianceMatrix[0][1] * CovarianceMatrix[1][0])\r\n inv = numpy.array([[CovarianceMatrix[1][1], -CovarianceMatrix[1][0]], [-CovarianceMatrix[0][1], CovarianceMatrix[0][0]]])\r\n inv /= det\r\n exponent=-0.5 * numpy.dot(pos_regular.T, numpy.dot(inv, pos_regular))\r\n normalize_factor=1.0 / (2 * numpy.pi * numpy.sqrt(det))\r\n return (-numpy.exp(exponent) * normalize_factor) * numpy.dot(inv, pos_regular)\r\ndef GaussianFunc_2ndDerivative(position, mu_average, CovarianceMatrix): \r\n mu_tmp = numpy.array(mu_average)\r\n mu_tmp.shape = (2, 1)\r\n pos_regular = position - mu_tmp\r\n det = (CovarianceMatrix[0][0] * CovarianceMatrix[1][1] - CovarianceMatrix[0][1] * CovarianceMatrix[1][0])\r\n inv = numpy.array([[CovarianceMatrix[1][1], -CovarianceMatrix[1][0]], [-CovarianceMatrix[0][1], CovarianceMatrix[0][0]]])\r\n inv /= det\r\n exponent=-0.5 * numpy.dot(pos_regular.T, numpy.dot(inv, pos_regular))\r\n normalize_factor=1.0 / (2 * numpy.pi * numpy.sqrt(det))\r\n return (numpy.exp(exponent) * normalize_factor) * (numpy.dot(numpy.dot(inv, numpy.dot(pos_regular, pos_regular.T)), inv) - inv)\r\ndef GenRandGaussDist(count):\r\n GaussAvg_Tmp = []\r\n GaussCov_Tmp = []\r\n GaussProb_Tmp = []\r\n for i in range(0,count):\r\n GaussAvg_Tmp.append(2.0 * numpy.random.rand(2) - 1.0)\r\n TmpVec = (numpy.random.rand(4) - 0.5)\r\n GaussCov_Tmp.append([ \\\r\n [TmpVec[0] * TmpVec[0] + TmpVec[1] * TmpVec[1] + 0.01, TmpVec[0] * TmpVec[2] + TmpVec[1] * TmpVec[3]], \\\r\n [TmpVec[0] * TmpVec[2] + TmpVec[1] * TmpVec[3], TmpVec[2] * TmpVec[2] + TmpVec[3] * TmpVec[3] + 0.01] \\\r\n ])\r\n GaussProb_Tmp.append(numpy.random.random())\r\n GaussProb_Tmp /= -0.1 * numpy.sum(GaussProb_Tmp)\r\n return GaussAvg_Tmp, GaussCov_Tmp, GaussProb_Tmp\r\ndef GenRandGaussDist_Single():\r\n GaussAvg_Tmp = []\r\n GaussCov_Tmp = []\r\n GaussProb_Tmp = []\r\n GaussAvg_Tmp.append(2.0 * numpy.random.rand(2) - 1.0)\r\n TmpVec = (numpy.random.rand(4) - 0.5)\r\n TmpVec[0] += 1.0; TmpVec[3] += 1.0\r\n GaussCov_Tmp.append([ \\\r\n [TmpVec[0] * TmpVec[0] + TmpVec[1] * TmpVec[1] + 0.01, TmpVec[0] * TmpVec[2] + TmpVec[1] * TmpVec[3]], \\\r\n [TmpVec[0] * TmpVec[2] + TmpVec[1] * TmpVec[3], TmpVec[2] * TmpVec[2] + TmpVec[3] * TmpVec[3] + 0.01] \\\r\n ])\r\n GaussProb_Tmp.append(-10)\r\n return GaussAvg_Tmp, GaussCov_Tmp, GaussProb_Tmp\r\n# mathematical functions --END--\r\n\r\ndef TestFunc_Mat(X, Y):\r\n RetValue = numpy.zeros_like(X)\r\n for i in range(0, len(GaussProb)):\r\n RetValue += GaussProb[i] * GaussianFunc_Mat(X, Y, GaussAvg[i], GaussCov[i])\r\n return RetValue\r\ndef TestFunc(x):\r\n RetValue = 0\r\n for i in range(0, len(GaussProb)):\r\n RetValue += GaussProb[i] * GaussianFunc(x, GaussAvg[i], GaussCov[i])\r\n return RetValue\r\ndef TestFunc_1stDerivative(x):\r\n RetValue = [[0], [0]]\r\n for i in range(0, len(GaussProb)):\r\n RetValue += GaussProb[i] * GaussianFunc_1stDerivative(x, GaussAvg[i], GaussCov[i])\r\n return RetValue\r\ndef TestFunc_2ndDerivative(x):\r\n RetValue = [[0, 0], [0, 0]]\r\n for i in range(0, len(GaussProb)):\r\n RetValue += GaussProb[i] * GaussianFunc_2ndDerivative(x, GaussAvg[i], GaussCov[i])\r\n return RetValue\r\n\r\n# common GUI routines --BEGIN--\r\ndef SizeWnd_Center(Wnd,Width,Height):\r\n ScrWidth = Wnd.winfo_screenwidth()\r\n ScrHeight = Wnd.winfo_screenheight()\r\n XPos = (ScrWidth/2) - (Width/2)\r\n YPos = (ScrHeight/2) - (Height/2)\r\n Wnd.geometry('%dx%d+%d+%d' % (Width, Height, XPos, YPos))\r\n# common GUI routines --END--\r\n\r\ndef Iterate_LM(x, f, mu):\r\n x.shape = (2, 1)\r\n Grad = TestFunc_1stDerivative(x)\r\n Hessian = TestFunc_2ndDerivative(x)\r\n det = Hessian[0][0] * Hessian[1][1] - Hessian[0][1] * Hessian[1][0]\r\n while True:\r\n if det + mu * mu > 0:\r\n break\r\n mu *= 4\r\n k = Hessian + numpy.identity(2) * mu\r\n p = numpy.linalg.det(Hessian + numpy.identity(2) * mu)\r\n s = -numpy.dot(numpy.linalg.inv(Hessian + numpy.identity(2) * mu), Grad)\r\n\r\n x_Tmp = x + s\r\n f_Tmp = TestFunc(x_Tmp)\r\n r = (f_Tmp - f) / (numpy.dot(Grad.T, s) + 0.5 * numpy.dot(s.T, numpy.dot(Hessian, s)))\r\n if r < 0.25:\r\n mu_New = 4 * mu\r\n elif r > 0.75:\r\n mu_New = 0.5 * mu\r\n else:\r\n mu_New = mu\r\n\r\n if r > 0:\r\n x_New = x + s\r\n f_New = f_Tmp\r\n else:\r\n x_New = x\r\n f_New = f\r\n\r\n return x_New, f_New, mu_New\r\n\r\n# GUI event listeners --BEGIN--\r\ndef BtnGen_OnClick():\r\n global GaussAvg, GaussCov, GaussProb\r\n if ChkVarSingle.get() > 0:\r\n GaussAvg, GaussCov, GaussProb = GenRandGaussDist_Single()\r\n else:\r\n GaussAvg, GaussCov, GaussProb = GenRandGaussDist(numpy.random.randint(1, 10))\r\n F = TestFunc_Mat(X, Y)\r\n\r\n FigMain.gca().cla()\r\n FigMain.gca().imshow(F, extent=[-1.5, 1.5, -1.5, 1.5])\r\n CvsFigure.show()\r\ndef SclIterate_OnChange(Value):\r\n LblIterate.config(text=\"Iteration:%d\" % round(float(Value)))\r\ndef BtnIterate_OnClick():\r\n # iteration\r\n x = 2.0 * numpy.random.rand(2, 1) - 1.0\r\n f = TestFunc(x)\r\n mu = 1.0\r\n FigMain.gca().autoscale(False)\r\n for i in range(0, round(SclIterate.get())):\r\n x_New, f_New, mu_New = Iterate_LM(x, f, mu)\r\n FigMain.gca().plot([x[0], x_New[0]], [x[1], x_New[1]], color=\"w\")\r\n if 0 == i:\r\n FigMain.gca().plot([x[0]], [x[1]], 'o', color=\"k\")\r\n CvsFigure.show()\r\n x = x_New; f = f_New; mu = mu_New;\r\n FigMain.gca().plot([x[0]], [x[1]], 'o', color=\"w\")\r\n CvsFigure.show()\r\n# GUI event listeners --END--\r\n\r\nx = numpy.linspace(-1.5, 1.5, 256)\r\ny = numpy.linspace(1.5, -1.5, 256)\r\nX,Y = numpy.meshgrid(x, y)\r\nF = TestFunc_Mat(X, Y)\r\n\r\nTKRoot = tkinter.Tk()\r\nTKRoot.title('Levenberg-Marquadt Method')\r\nSizeWnd_Center(TKRoot,640,400)\r\n\r\nFrmMain = ttk.Frame(TKRoot,width=240,height=400)\r\nFrmMain.pack_propagate(0)\r\nFrmMain.pack(side=\"left\", fill=\"y\", padx=10, pady=5)\r\n# controls inside FrmMain --BEGIN--\r\nFrmGen = ttk.Frame(FrmMain)\r\nFrmGen.pack(side=\"top\", fill=\"x\")\r\nChkVarSingle = tkinter.IntVar(value=0)\r\nChkSingle = ttk.Checkbutton(FrmGen, variable=ChkVarSingle, text=\"Single Concave\", onvalue=1, offvalue=0)\r\nChkSingle.pack(side=\"left\")\r\nBtnGen = ttk.Button(FrmGen, text=\"Generate\", command=BtnGen_OnClick)\r\nBtnGen.pack(side=\"right\")\r\nLblIterate = ttk.Label(FrmMain, text=\"Iteration:0\")\r\nLblIterate.pack(anchor=\"nw\")\r\nFrmIterate = ttk.Frame(FrmMain)\r\nFrmIterate.pack(side=\"top\", fill=\"x\")\r\nSclIterate = ttk.Scale(FrmIterate, from_=1, to=100, command=SclIterate_OnChange)\r\nSclIterate.pack(side=\"left\")\r\nBtnIterate = ttk.Button(FrmIterate, text=\"Start\", command=BtnIterate_OnClick)\r\nBtnIterate.pack(side=\"right\")\r\n# controls inside FrmMain --END--\r\n\r\nSclIterate.set(1);\r\n\r\nFrmCanvas = ttk.Frame(TKRoot)\r\nFrmCanvas.pack(expand=\"true\", fill=\"both\")\r\n# controls inside FrmCanvas --BEGIN--\r\nFigMain = Figure(figsize=(4,4), dpi=100)\r\nFigMain.patch.set_color(\"#FFFFFF\")\r\nFigMain.gca().cla()\r\nFigMain.gca().imshow(F, extent=[-1.5, 1.5, -1.5, 1.5])\r\nCvsFigure = FigureCanvasTkAgg(FigMain, master=FrmCanvas)\r\nCvsFigure.show();\r\nCvsFigure.get_tk_widget().pack(side=\"top\",expand=\"yes\",fill=\"both\")\r\n# controls inside FrmCanvas --END-\r\n\r\nTKRoot.mainloop()\r\n","sub_path":"LMMethod.pyw","file_name":"LMMethod.pyw","file_ext":"pyw","file_size_in_byte":8791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"340989100","text":"import json\nimport logging\n\nimport jsonschema\nfrom jsonschema import ValidationError\nfrom sqlalchemy import inspect as sainsp\nfrom sqlalchemy_jsonio.exceptions import MultipleSchemaMatches, NoSchemaFound\nfrom sqlalchemy_jsonio.registry import SchemaRegistry\nfrom sqlalchemy_jsonio.util import convert_inspection_to_nomapper_error\n\n_logger = logging.getLogger(__name__)\n\n\ndef _filter_none(entity, column): # Return true if entity has value for column\n return getattr(entity, column.key) is not None\n\n\ndef _filter_primary(entity, column): # Return true if column is not primary\n if column.primary_key:\n return False\n return True\n\n\ndef _filter_foreign(entity, column): # Return true if column is not foreign\n if column.foreign_keys:\n return False\n return True\n\n\nclass JsonIO(object):\n def __init__(self, schema_registry=None):\n self._registry = schema_registry or SchemaRegistry()\n\n @convert_inspection_to_nomapper_error\n def entity_as_dict(self, entity, ignore_primary=False, ignore_none=False, ignore_foreign=False):\n entity_dict = {}\n _logger.info(\"Creating dictionary from {}\".format(entity))\n for column in sainsp(entity).mapper.columns:\n if ignore_primary and not _filter_primary(entity, column):\n _logger.debug(\"Ignoring {}. Primary key.\".format(column.name))\n continue\n if ignore_none and not _filter_none(entity, column):\n _logger.debug(\"Ignoring {}. 'None' value.\".format(column.name))\n continue\n if ignore_foreign and not _filter_foreign(entity, column):\n _logger.debug(\"Ignoring {}. Foreign key.\".format(column.name))\n continue\n entity_dict[column.key] = getattr(entity, column.key)\n return entity_dict\n\n def entity_as_json(self, entity, ignore_primary=False, ignore_none=False, ignore_foreign=False, compact=False):\n entity_dict = self.entity_as_dict(entity, ignore_primary, ignore_none, ignore_foreign)\n if compact:\n return json.dumps(entity_dict, sort_keys=True, separators=(\",\", \":\"))\n else:\n return json.dumps(entity_dict, sort_keys=True, indent=2)\n\n def entity_from_dict(self, entity_dict, target_class=None):\n _logger.info(\"Creating entity from {}\".format(entity_dict))\n if target_class:\n self._validate_entity_dict_against_target(entity_dict, target_class)\n else:\n target_class = self._find_target_class(entity_dict)\n return target_class(**entity_dict) # Will error if there is a key that does not correspond with a field!\n\n def entity_from_json(self, entity_json, target_class=None):\n entity_dict = json.loads(entity_json)\n return self.entity_from_dict(entity_dict, target_class)\n\n def register_class(self, cls, custom_schema=None):\n self._registry.register_class(cls, custom_schema)\n\n def register_module(self, module_, depth=0):\n self._registry.register_module(module_, depth)\n\n def _find_target_class(self, entity_dict):\n _logger.info(\"Searching for unique matching schema.\")\n class_matches = []\n for cls, schema in iter(self._registry.items()):\n try:\n jsonschema.validate(entity_dict, schema)\n _logger.info(\"Dictionary matches schema for '{}'\".format(cls))\n class_matches.append(cls)\n except ValidationError:\n pass\n if len(class_matches) == 0:\n raise NoSchemaFound(\"Provided dictionary didn't match against any schema in the registry.\")\n if len(class_matches) > 1:\n raise MultipleSchemaMatches(\"\"\"Provided dictionary matched against more than one schema. \n Matched {} classes: {}.\"\"\".format(len(class_matches), class_matches))\n return class_matches[0]\n\n def _validate_entity_dict_against_target(self, entity_dict, target_class):\n try:\n schema = self._registry[target_class]\n jsonschema.validate(entity_dict, schema)\n _logger.debug(\"Dictionary matches schema for provided target '{}'\".format(target_class))\n except KeyError:\n raise NoSchemaFound(\"No schema was found for class '{}'\".format(target_class))\n # except ValidationError as ve:\n # raise ve # To_do: Custom error to clarify\n","sub_path":"sqlalchemy_jsonio/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"407889237","text":"# -*- coding: utf-8 -*-\n\n# This is the Sort Multivalue Tags plugin for MusicBrainz Picard.\n# Copyright (C) 2013 Sophist\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\nPLUGIN_NAME = u\"Sort Multi-Value Tags\"\nPLUGIN_AUTHOR = u\"Sophist\"\nPLUGIN_DESCRIPTION = u'Sort Multi-Value Tags e.g. Release Type, Lyrics alphabetically.'\nPLUGIN_VERSION = \"0.1\"\nPLUGIN_API_VERSIONS = [\"0.15\"]\nPLUGIN_LICENSE = \"GPL-2.0\"\nPLUGIN_LICENSE_URL = \"https://www.gnu.org/licenses/gpl-2.0.html\"\n\nfrom picard.metadata import register_track_metadata_processor\n\n# Define and register the Track Metadata function\n\n\ndef sort_multivalue_tags(tagger, metadata, track, release):\n\n for tag in metadata.keys():\n data = metadata.getall(tag)\n if len(data) > 1:\n sorted_data = sorted(data)\n if data != sorted_data:\n metadata.set(tag, sorted_data)\n\nregister_track_metadata_processor(sort_multivalue_tags)\n","sub_path":"plugins/sort_multivalue_tags/sort_multivalue_tags.py","file_name":"sort_multivalue_tags.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"580394416","text":"import os\nimport yaml\nimport torch\nimport json\nfrom tqdm import tqdm\nfrom torch import nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom nets.pose_hrnet import get_pose_net\nfrom torch.cuda import amp\nfrom metrics.pose_metrics import HeatMapAcc, GaussTaylorKeyPointDecoder, kps_to_dict_, evaluate_map\nfrom datasets.coco import MSCOCO\nfrom commons.model_utils import rand_seed, AverageLogger\nfrom torch.optim.adam import Adam\nfrom commons.optims_utils import IterWarmUpCosineDecayMultiStepLRAdjust\n\nrand_seed(1024)\n\n\nclass DPProcessor(object):\n def __init__(self, cfg_path):\n with open(cfg_path, 'r') as rf:\n self.cfg = yaml.safe_load(rf)\n self.data_cfg = self.cfg['data']\n self.model_cfg = self.cfg['model']\n self.optim_cfg = self.cfg['optim']\n self.val_cfg = self.cfg['val']\n print(self.data_cfg)\n print(self.model_cfg)\n print(self.optim_cfg)\n print(self.val_cfg)\n self.tdata = MSCOCO(img_root=self.data_cfg['train_img_root'],\n ann_path=self.data_cfg['train_ann_path'],\n debug=self.data_cfg['debug'],\n augment=True,\n )\n self.tloader = DataLoader(dataset=self.tdata,\n batch_size=self.data_cfg['batch_size'],\n num_workers=self.data_cfg['num_workers'],\n collate_fn=self.tdata.collate_fn,\n shuffle=True)\n self.vdata = MSCOCO(img_root=self.data_cfg['val_img_root'],\n ann_path=self.data_cfg['val_ann_path'],\n debug=False,\n augment=False,\n )\n self.vloader = DataLoader(dataset=self.vdata,\n batch_size=self.data_cfg['batch_size'],\n num_workers=self.data_cfg['num_workers'],\n collate_fn=self.vdata.collate_fn,\n shuffle=False\n )\n print(\"train_data: \", len(self.tdata), \" | \",\n \"val_data: \", len(self.vdata))\n print(\"train_iter: \", len(self.tloader), \" | \",\n \"val_iter: \", len(self.vloader))\n model: torch.nn.Module = get_pose_net(\n cfg_path=self.model_cfg['cfg_path'],\n pretrained=self.model_cfg['pretrained'],\n joint_num=self.model_cfg['joint_num']\n )\n self.scaler = amp.GradScaler(enabled=True) if self.optim_cfg['amp'] else None\n self.optimizer = Adam(\n model.parameters(), lr=self.optim_cfg['lr']\n )\n self.lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(\n self.optimizer,\n milestones=self.optim_cfg['milestones'],\n gamma=self.optim_cfg['gamma']\n )\n # self.lr_scheduler = IterWarmUpCosineDecayMultiStepLRAdjust(\n # init_lr=self.optim_cfg['lr'],\n # milestones=self.optim_cfg['milestones'],\n # warm_up_epoch=1,\n # iter_per_epoch=len(self.tloader),\n # epochs=self.optim_cfg['epochs']\n # )\n\n assert torch.cuda.is_available(), \"training only support cuda\"\n assert torch.cuda.device_count() >= len(self.cfg['gpus']), \"not have enough gpus\"\n self.inp_device = torch.device(\"cuda:{:d}\".format(self.cfg['gpus'][0]))\n self.out_device = torch.device(\"cuda:{:d}\".format(self.cfg['gpus'][-1]))\n model.to(self.inp_device)\n self.model = nn.DataParallel(\n model, device_ids=self.cfg['gpus'], output_device=self.out_device)\n # self.ema = ModelEMA(self.model)\n self.creterion = nn.MSELoss()\n self.acc_func = HeatMapAcc()\n self.best_ap = 0.\n self.loss_logger = AverageLogger()\n self.acc_logger = AverageLogger()\n self.decoder = GaussTaylorKeyPointDecoder()\n\n def train(self, epoch):\n self.loss_logger.reset()\n self.acc_logger.reset()\n self.model.train()\n pbar = tqdm(self.tloader)\n print(\"#\" * 25, \"training start\", \"#\" * 25)\n for i, (input_tensors, heat_maps, masks, _, _) in enumerate(pbar):\n input_img = input_tensors.to(self.inp_device)\n targets = heat_maps.to(self.out_device)\n mask = masks.to(self.out_device)\n self.optimizer.zero_grad()\n if self.scaler is None:\n predicts = self.model(input_img)\n loss = 0.5 * self.creterion(predicts.mul(mask[[..., None, None]]), targets.mul(mask[[..., None, None]]))\n loss.backward()\n # nn.utils.clip_grad_norm_(self.model.parameters(), 2)\n # self.lr_scheduler(self.optimizer, i, epoch)\n self.optimizer.step()\n else:\n with amp.autocast(enabled=True):\n predicts = self.model(input_img)\n loss = 0.5 * self.creterion(predicts.mul(mask[[..., None, None]]),\n targets.mul(mask[[..., None, None]]))\n self.scaler.scale(loss).backward()\n # nn.utils.clip_grad_norm_(self.model.parameters(), 2)\n # self.lr_scheduler(self.optimizer, i, epoch)\n self.scaler.step(self.optimizer)\n self.scaler.update()\n # self.ema.update(self.model)\n lr = self.optimizer.param_groups[0]['lr']\n acc = self.acc_func(predicts.mul(mask[[..., None, None]]).detach(),\n targets.mul(mask[[..., None, None]]).detach())\n self.loss_logger.update(loss.item())\n self.acc_logger.update(acc.item())\n pbar.set_description(\n \"train epoch:{:3d}|iter:{:4d}|loss:{:8.6f}|acc:{:6.4f}|lr:{:8.6f}\".format(\n epoch + 1,\n i,\n self.loss_logger.avg(),\n self.acc_logger.avg() * 100,\n lr,\n )\n )\n # self.ema.update_attr(self.model)\n self.lr_scheduler.step()\n print()\n print(\"#\" * 25, \"training end\", \"#\" * 25)\n\n @torch.no_grad()\n def val(self, epoch):\n self.loss_logger.reset()\n self.acc_logger.reset()\n self.model.eval()\n # self.ema.ema.eval()\n pbar = tqdm(self.vloader)\n kps_dict_list = list()\n print(\"#\" * 25, \"evaluating start\", \"#\" * 25)\n for i, (input_tensors, heat_maps, masks, trans_invs, img_ids) in enumerate(pbar):\n input_img = input_tensors.to(self.inp_device)\n targets = heat_maps.to(self.out_device)\n tran_inv = trans_invs.to(self.out_device)\n mask = masks.to(self.out_device)\n predicts = self.model(input_img)\n loss = 0.5 * self.creterion(predicts.mul(mask[[..., None, None]]), targets.mul(mask[[..., None, None]]))\n acc = self.acc_func(predicts.mul(mask[[..., None, None]]), targets.mul(mask[[..., None, None]]))\n self.loss_logger.update(loss.item())\n self.acc_logger.update(acc.item())\n pred_kps, scores = self.decoder(predicts, tran_inv)\n kps_to_dict_(pred_kps, scores, img_ids, kps_dict_list)\n pbar.set_description(\n \"eval epoch:{:3d}|iter:{:4d}|loss:{:8.6f}|acc:{:6.4f}\".format(\n epoch + 1,\n i,\n self.loss_logger.avg(),\n self.acc_logger.avg() * 100,\n )\n )\n with open(\"temp_test.json\", \"w\") as wf:\n json.dump(kps_dict_list, wf)\n val_ap = evaluate_map(\"temp_test.json\", self.data_cfg['val_ann_path'])['AP']\n print(\"eval epoch:{:d}|mean_loss:{:8.6f}|mean_acc:{:6.4f}|val_ap:{:6.4f}\".format(epoch + 1,\n self.loss_logger.avg(),\n self.acc_logger.avg() * 100,\n val_ap))\n print(\"#\" * 25, \"evaluating end\", \"#\" * 25)\n\n cpkt = {\n \"ema\": self.model.module.state_dict(),\n \"epoch\": epoch,\n }\n if val_ap > self.best_ap:\n self.best_ap = val_ap\n best_weight_path = os.path.join(self.val_cfg['weight_path'],\n \"{:s}_best.pth\"\n .format(self.cfg['model_name']))\n torch.save(cpkt, best_weight_path)\n last_weight_path = os.path.join(self.val_cfg['weight_path'],\n \"{:s}_last.pth\"\n .format(self.cfg['model_name']))\n torch.save(cpkt, last_weight_path)\n\n def run(self):\n for epoch in range(self.optim_cfg['epochs']):\n self.train(epoch)\n if (epoch + 1) % self.val_cfg['interval'] == 0:\n self.val(epoch)\n","sub_path":"processors/dp_pose_hrnet_solver.py","file_name":"dp_pose_hrnet_solver.py","file_ext":"py","file_size_in_byte":9169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"233477882","text":"# NOTE: assumes presence of pandas, scipy, matplotlib,\n# such as in a conda environment.\n\nfrom setuptools import setup, find_packages\n\ntest_requirements = ['sentinels>=0.0.6', 'nose>=1.0', 'python-dateutil>=2.2']\n\nsetup(\n name = \"women_tech\",\n version = \"0.01\",\n packages = find_packages(),\n\n # Dependencies on other packages:\n setup_requires = ['nose>=1.1.2'],\n tests_require = test_requirements,\n install_requires = ['ijson>=1.0', \n\t\t\t#'pandas>=0.18.0',\n\t\t\t'xlrd>=0.9.4',\n\t\t\t#'scipy>= 0.17.0',\n\t\t\t#'matplotlib>= 1.5.1',\n\t\t\t'survey_utils>=0.0.5',\n\t\t\t#'Jinja2>=2.8',\n\t\t\t'seaborn>=0.7.1', # Heatmaps\n\t\t\t] + test_requirements,\n\n # Unit tests; they are initiated via 'python setup.py test'\n #test_suite = 'json_to_relation/test',\n test_suite = 'nose.collector', \n\n #data_files = [('pymysql_utils/data', datafiles)],\n\n package_data = {\n # If any package contains *.txt or *.rst files, include them:\n # '': ['*.txt', '*.rst'],\n # And include any *.msg files found in the 'hello' package, too:\n # 'hello': ['*.msg'],\n },\n\n # metadata for upload to PyPI\n author = \"Andreas Paepcke\",\n author_email = \"paepcke@cs.stanford.edu\",\n description = \"Stats analysis for survey on Women in Tech Companies..\",\n license = \"BSD\",\n keywords = \"survey analysis\",\n #url = \"https://github.com/paepcke/json_to_relation\", # project home page, if any\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"354902809","text":"import sys\n# Memory in the computer:\n# ------\n# A big array of bytes\n# To get the or set the data in memory you need the index in the array\n\n# Terms \n# - Index into memory array\n# - Address\n# - Location\n# - Pointer\n\n# \"opcode\" == the instruction itself\n# \"operands\" == args in the instruction\nmemory = [\n 1, # PRINT_LESLIE\n 3, # SAVE_REG1, 37 r1 = 37\n 1, \n 37, \n 4, # PRINT_REG R1 print(r[1])\n 1, # R1\n 1, # PRINT_LESLIE\n 2 # HALT\n]\n\n# variables are called \"registers\"\n# * There are a fixed number\n# * They have preset names: R0, R0, R1, R2, R3 ... R7\n#\n# Registers can each hold a single byte\n\nregister = [0] * 8\n\n# start execution at address 0\n\n# Keep track of the address of currently executing intruction\npc = 0 # Program counter, pointer the instruction we're executing\n\nhalted = False\n \nPRINT_LESLIE = 1\nHALT = 2\nSAVE_REG = 3\nPRINT_REG = 4\n\nwhile not halted:\n instruction = memory[pc]\n\n if instruction == PRINT_LESLIE:\n print(\"Leslie!\")\n pc += 1\n\n elif instruction == HALT:\n halted = True\n pc += 1 \n\n elif instruction == SAVE_REG: # SAVE_REG\n reg_num = memory[pc+1]\n value = memory[pc+2]\n register[reg_num] = value\n\n print(\"register\", register)\n pc += 3\n \n \n elif instruction == PRINT_REG:\n reg_num = memory[pc+1]\n print(register[reg_num])\n pc += 2\n \n else:\n print(f\"Unknown instruction {instruction} at address {pc}\")\n sys.exit(1)","sub_path":"notes/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"5721127","text":"\n\nclass PuzzleSolver:\n def __init__(self, strategy):\n \"\"\"\n :param strategy: Strategy\n \"\"\"\n self._strategy = strategy\n\n def print_performance(self):\n print(f'{self._strategy} - Expanded Nodes: {self._strategy.num_expanded_nodes}')\n\n def print_solution(self):\n print('Solution:')\n for s in self._strategy.solution:\n print(s)\n\n def run(self):\n if not self._strategy.start.is_solvable():\n raise RuntimeError('This puzzle is not solvable')\n\n self._strategy.do_algorithm()\n\nclass Strategy:\n num_expanded_nodes = 0\n solution = None\n\n def do_algorithm(self):\n raise NotImplemented\n\n\nclass BreadthFirst(Strategy):\n def __init__(self, initial_puzzle):\n \"\"\"\n :param initial_puzzle: Puzzle\n \"\"\"\n self.start = initial_puzzle\n\n def __str__(self):\n return 'Breadth First'\n\n def do_algorithm(self):\n queue = [[self.start]]\n expanded = []\n num_expanded_nodes = 0\n path = None\n\n while queue:\n path = queue[0]\n queue.pop(0) # dequeue (FIFO)\n end_node = path[-1]\n\n if end_node.position in expanded:\n continue\n\n for move in end_node.get_moves():\n if move.position in expanded:\n continue\n queue.append(path + [move]) # add new path at the end of the queue\n\n expanded.append(end_node.position)\n num_expanded_nodes += 1\n\n if end_node.position == end_node.PUZZLE_END_POSITION:\n break\n\n self.num_expanded_nodes = num_expanded_nodes\n self.solution = path\n\n\nclass AStar(Strategy):\n def __init__(self, initial_puzzle):\n \"\"\"\n :param initial_puzzle: Puzzle\n \"\"\"\n self.start = initial_puzzle\n\n def __str__(self):\n return 'A*'\n\n @staticmethod\n def _calculate_new_heuristic(move, end_node):\n return move.heuristic_manhattan_distance() - end_node.heuristic_manhattan_distance()\n\n def do_algorithm(self):\n queue = [[self.start.heuristic_manhattan_distance(), self.start]]\n expanded = []\n num_expanded_nodes = 0\n path = None\n\n while queue:\n i = 0\n for j in range(1, len(queue)):\n if queue[i][0] > queue[j][0]: # minimum\n i = j\n\n path = queue[i]\n queue = queue[:i] + queue[i + 1:]\n end_node = path[-1]\n\n if end_node.position == end_node.PUZZLE_END_POSITION:\n break\n if end_node.position in expanded:\n continue\n\n for move in end_node.get_moves():\n if move.position in expanded:\n continue\n new_path = [path[0] + self._calculate_new_heuristic(move, end_node)] + path[1:] + [move]\n queue.append(new_path)\n expanded.append(end_node.position)\n\n num_expanded_nodes += 1\n\n self.num_expanded_nodes = num_expanded_nodes\n self.solution = path[1:]\n\n\nclass Puzzle:\n def __init__(self, position):\n \"\"\"\n :param position: a list of lists representing the puzzle matrix\n \"\"\"\n self.position = position\n self.PUZZLE_NUM_ROWS = len(position)\n self.PUZZLE_NUM_COLUMNS = len(position[0])\n self.PUZZLE_END_POSITION = self._generate_end_position()\n\n def __str__(self):\n \"\"\"\n Print in console as a matrix\n \"\"\"\n puzzle_string = '—' * 13 + '\\n'\n for i in range(self.PUZZLE_NUM_ROWS):\n for j in range(self.PUZZLE_NUM_COLUMNS):\n puzzle_string += '│{0: >2}'.format(str(self.position[i][j]))\n if j == self.PUZZLE_NUM_COLUMNS - 1:\n puzzle_string += '│\\n'\n\n puzzle_string += '—' * 13 + '\\n'\n return puzzle_string\n\n def _generate_end_position(self):\n \"\"\"\n Example end position in 4x4 puzzle\n [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]]\n \"\"\"\n end_position = []\n new_row = []\n\n for i in range(1, self.PUZZLE_NUM_ROWS * self.PUZZLE_NUM_COLUMNS + 1):\n new_row.append(i)\n if len(new_row) == self.PUZZLE_NUM_COLUMNS:\n end_position.append(new_row)\n new_row = []\n\n end_position[-1][-1] = 0\n return end_position\n\n def _swap(self, x1, y1, x2, y2):\n \"\"\"\n Swap the positions between two elements\n \"\"\"\n puzzle_copy = [list(row) for row in self.position] # copy the puzzle\n puzzle_copy[x1][y1], puzzle_copy[x2][y2] = puzzle_copy[x2][y2], puzzle_copy[x1][y1]\n\n return puzzle_copy\n\n @staticmethod\n def _is_odd(num):\n return num % 2 != 0\n\n @staticmethod\n def _is_even(num):\n return num % 2 == 0\n\n def _get_blank_space_row_counting_from_bottom(self):\n zero_row, _ = self._get_coordinates(0) # blank space\n return self.PUZZLE_NUM_ROWS - zero_row\n\n def _get_coordinates(self, tile, position=None):\n \"\"\"\n Returns the i, j coordinates for a given tile\n \"\"\"\n if not position:\n position = self.position\n\n for i in range(self.PUZZLE_NUM_ROWS):\n for j in range(self.PUZZLE_NUM_COLUMNS):\n if position[i][j] == tile:\n return i, j\n\n return RuntimeError('Invalid tile value')\n\n def _get_inversions_count(self):\n inv_count = 0\n puzzle_list = [number for row in self.position for number in row if number != 0]\n\n for i in range(len(puzzle_list)):\n for j in range(i + 1, len(puzzle_list)):\n if puzzle_list[i] > puzzle_list[j]:\n inv_count += 1\n\n return inv_count\n\n def get_moves(self):\n \"\"\"\n Returns a list of all the possible moves\n \"\"\"\n moves = []\n i, j = self._get_coordinates(0) # blank space\n\n if i > 0:\n moves.append(Puzzle(self._swap(i, j, i - 1, j))) # move up\n\n if j < self.PUZZLE_NUM_COLUMNS - 1:\n moves.append(Puzzle(self._swap(i, j, i, j + 1))) # move right\n\n if j > 0:\n moves.append(Puzzle(self._swap(i, j, i, j - 1))) # move left\n\n if i < self.PUZZLE_NUM_ROWS - 1:\n moves.append(Puzzle(self._swap(i, j, i + 1, j))) # move down\n\n return moves\n\n def heuristic_misplaced(self):\n \"\"\"\n Counts the number of misplaced tiles\n \"\"\"\n misplaced = 0\n\n for i in range(self.PUZZLE_NUM_ROWS):\n for j in range(self.PUZZLE_NUM_COLUMNS):\n if self.position[i][j] != self.PUZZLE_END_POSITION[i][j]:\n misplaced += 1\n\n return misplaced\n\n def heuristic_manhattan_distance(self):\n \"\"\"\n Counts how much is a tile misplaced from the original position\n \"\"\"\n distance = 0\n\n for i in range(self.PUZZLE_NUM_ROWS):\n for j in range(self.PUZZLE_NUM_COLUMNS):\n i1, j1 = self._get_coordinates(self.position[i][j], self.PUZZLE_END_POSITION)\n distance += abs(i - i1) + abs(j - j1)\n\n return distance\n\n def is_solvable(self):\n # 1. If N is odd, then puzzle instance is solvable if number of inversions is even in the input state.\n # 2. If N is even, puzzle instance is solvable if\n # - the blank is on an even row counting from the bottom (second-last, fourth-last, etc.)\n # and number of inversions is odd.\n # - the blank is on an odd row counting from the bottom (last, third-last, fifth-last, etc.)\n # and number of inversions is even.\n # 3. For all other cases, the puzzle instance is not solvable.\n\n inversions_count = self._get_inversions_count()\n blank_position = self._get_blank_space_row_counting_from_bottom()\n\n if self._is_odd(self.PUZZLE_NUM_ROWS) and self._is_even(inversions_count):\n return True\n elif self._is_even(self.PUZZLE_NUM_ROWS) and self._is_even(blank_position) and self._is_odd(inversions_count):\n return True\n elif self._is_even(self.PUZZLE_NUM_ROWS) and self._is_odd(blank_position) and self._is_even(inversions_count):\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n puzzle = Puzzle([[0,1,3], [4,2,5], [7,8,6]])\n\n for strategy in [BreadthFirst, AStar]:\n p = PuzzleSolver(strategy(puzzle))\n p.run()\n p.print_performance()\n p.print_solution()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"320403469","text":"# enum.py\n# enum.py provides simple enumeration like functionality and functions\nimport inspect\n\n\n# make a pseudo enum for easier storage of Algorithm, Measurements and Instructions\ndef enum(*values):\n enumDict = dict(zip(values, range(len(values))))\n return type('Enum', (), enumDict)\n\n\n# get all of the class attributes\ndef _get_attributes_of_class(class_to_analyze):\n members = inspect.getmembers(class_to_analyze, lambda a: not (inspect.isroutine(a)))\n return [member for member in members if not (member[0].startswith('__') and member[0].endswith('__'))]\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n## The two enum functions below make it easy to check that a value or name\n## belongs to the given enum, and if not present, returns None\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# allow for grabbing enum name from value\ndef name_from_value(my_enum, desired_value):\n enum_pairs = _get_attributes_of_class(my_enum)\n for (key, value) in enum_pairs:\n if desired_value is value:\n return key\n return None\n\n\n# allow for getting enum value from name, as\ndef value_from_name(my_enum, desired_name):\n enum_pairs = _get_attributes_of_class(my_enum)\n for (key, value) in enum_pairs:\n if desired_name == key:\n return value\n return None\n\n\n# method that checks to make sure a value belongs to an enum and then gives a settable value\ndef enum_value(my_enum, value_to_check):\n # check if checking a name or value\n num_or_name = isinstance(value_to_check, int)\n\n if num_or_name:\n name = name_from_value(my_enum, value_to_check)\n if (name is not None) and (name is not 'Default'):\n return value_to_check\n else:\n return None\n else:\n return value_from_name(my_enum, value_to_check)\n\n\n# method to get the correct enum value when possibly given two\ndef resolve_enum_value(my_enum, first_value, second_value):\n first_enum = enum_value(my_enum, first_value)\n second_enum = enum_value(my_enum, second_value)\n\n if None in (first_enum, second_enum):\n return first_enum or second_enum\n elif first_enum != second_enum:\n return None\n else:\n return first_enum\n","sub_path":"algorithm development/core/language_extensions/enum.py","file_name":"enum.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"49442272","text":"import geopandas as gpd\nimport pandas as pd\nimport numpy as np\n\n\ndef prepare_roads(roads):\n \"\"\"\n Preparing roads for use in the analysis. OSM contains a lot of unnecessary information, which we remove.\n We also add a unique \"Road_ID\" field that is used later in the analysis for attribute joins.\n\n Parameters\n ----------\n roads : GeoDataFrame of the roads under consideration that has been downloaded from OpenStreetMap.\n\n Returns\n ----------\n GeoDataFrame of OSM roads file with the necessary modifications for analysis\n\n \"\"\"\n print(\"Preparing roads file\")\n roads = roads[['fid', 'osm_id', 'name', 'highway', 'geometry']]\n roads['Road_ID'] = np.arange(len(roads))\n\n return(roads)\n\ndef Assign_road_hierarchy(roads):\n \"\"\"\n Fucntion assigns the hierarchy scores based on the criteria outlined in Hayes et al.\n\n Parameters\n ----------\n roads : GeoDataFrame output from the prepare_roads function.\n\n Returns\n ----------\n GeoDataFrame of the OSM roads file with assigned road hierarchy score.\n\n \"\"\"\n print(\"Assigning road hierarchy scores to road network\")\n roads.loc[roads['highway'] == 'motorway', 'hierarchy'] = 4\n roads.loc[roads['highway'] == 'motorway_link', 'hierarchy'] = 4\n roads.loc[roads['highway'] == 'trunk', 'hierarchy'] = 3\n roads.loc[roads['highway'] == 'trunk_link', 'hierarchy'] = 3\n roads.loc[roads['highway'] == 'primary', 'hierarchy'] = 3\n roads.loc[roads['highway'] == 'primary_link', 'hierarchy'] = 3\n roads.loc[roads['highway'] == 'secondary', 'hierarchy'] = 2\n roads.loc[roads['highway'] == 'secondary_link', 'hierarchy'] = 2\n roads.loc[roads['highway'] == 'tertiary', 'hierarchy'] = 2\n roads.loc[roads['highway'] == 'tertiary_link', 'hierarchy'] = 2\n roads.loc[roads['highway'] == 'unclassified', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'residential', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'living_street', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'service', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'road', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'unknown', 'hierarchy'] = 1\n roads.loc[roads['highway'] == 'pedestrian', 'hierarchy'] = 0\n print(\"Assigning road hierarchy scores to road network is complete\")\n\n return(roads)\n\ndef Assign_strategic_nodes(roads, Strategic_nodes):\n \"\"\"\n This function moves strategic nodes to their nearest road segment and then assigns a score to the road segment.\n The score is assigned based upon the criteria outlines in Hayes et al.\n\n Parameters\n ----------\n roads : GeoDataFrame output from the Assign_road_hierarchy function\n Strategic_nodes : GeoDataframe of the location and typology of each strategic node.\n\n Returns\n ----------\n GeoDataFrame that includes the strategic node score for each road segment (Node score)\n\n \"\"\"\n print(\"Reprojecting road network and strategic nodes to pseudo mercator\")\n roads = roads.to_crs(epsg=3857)\n Strategic_nodes = Strategic_nodes.to_crs(epsg=3857)\n\n # Use spatial index to search for nearest lines\n print(\"Setting spatial index\")\n roads.sindex\n offset = 500\n bbox = Strategic_nodes.bounds + [-offset, -offset, offset, offset]\n hits = bbox.apply(lambda row: list(roads.sindex.intersection(row)), axis=1)\n\n tmp = pd.DataFrame({\n # index of points table\n \"pt_idx\": np.repeat(hits.index, hits.apply(len)), # ordinal position of line - access via iloc later\n \"line_i\": np.concatenate(hits.values)\n })\n\n tmp = tmp.join(roads.reset_index(drop=True), on=\"line_i\")\n\n tmp = tmp.join(Strategic_nodes.geometry.rename(\"point\"), on=\"pt_idx\")\n\n tmp = gpd.GeoDataFrame(tmp, geometry=\"geometry\", crs=Strategic_nodes.crs)\n\n print(\"Finding closest road to each strategic node\")\n # Find closest line to each point\n tmp[\"snap_dist\"] = tmp.geometry.distance(gpd.GeoSeries(tmp.point))\n tmp = tmp.loc[tmp.snap_dist <= offset]\n tmp = tmp.sort_values(by=[\"snap_dist\"])\n\n print(\"Snapping nodes to nearest road\")\n closest = tmp.groupby(\"pt_idx\").first()\n closest = gpd.GeoDataFrame(closest, geometry=\"geometry\")\n pos = closest.geometry.project(gpd.GeoSeries(closest.point))\n new_pts = closest.geometry.interpolate(pos)\n\n snapped = gpd.GeoDataFrame(closest, geometry=new_pts)\n updated_points = Strategic_nodes.drop(columns=[\"geometry\"]).join(snapped)\n updated_points = updated_points.dropna(subset=[\"geometry\"])\n\n join = roads.merge(updated_points, on='Road_ID', how='left')\n\n print(\"Counting number of snapped nodes touching each road\")\n Number_nodes = join.groupby('Road_ID').count()\n\n roads_SN = roads.merge(Number_nodes['point'], on='Road_ID', how='left')\n\n print(\"Assigning strategic node score\")\n roads_SN.loc[roads_SN['point'] == 0, 'Node score'] = 0\n roads_SN.loc[roads_SN['point'] == 1, 'Node score'] = 4\n roads_SN.loc[roads_SN['point'] == 2, 'Node score'] = 8\n roads_SN.loc[roads_SN['point'] == 3, 'Node score'] = 12\n roads_SN.loc[roads_SN['point'] > 3, 'Node score'] = 16\n\n print(\"Strategic node score successfully applied\")\n\n return(roads_SN)\n\ndef Assign_community_facilities(POIs, roads, roads_SN):\n \"\"\"\n This function assigns am access to community facilities score by moving each POI to the nearest road segment.\n Scores assigned to segments based on the criteria outlines in Hayes et al.\n\n Parameters\n ----------\n roads : GeoDataFrame that is the output of the Assign_road_hierarchy function\n roads_SN : GeoDataFrame that is the output of the Assign_strategic_nodes function\n POIs : GeoDataFrame that has the location and typology of different ammenities.\n\n Returns\n ----------\n GeoDataFrame that contains an access to commmunity facilities score (Priority)\n \"\"\"\n print(\"Assigning access to community services and facilities score\")\n # Set the priority score for POI\n print(\"Setting priority scores for each point of interest\")\n\n POIs.loc[(POIs['amenity'] == 'police') |\n (POIs['amenity'] == 'hospital') |\n (POIs['amenity'] == 'rescue_station') |\n (POIs['amenity'] == \"fire_station\"),\n 'Priority'] = 4\n POIs.loc[(POIs['amenity'] == 'supermarket') |\n (POIs['amenity'] == 'prison') |\n (POIs['amenity'] == 'waste_transfer_station') |\n (POIs['amenity'] == 'lighthouse') |\n (POIs['amenity'] == 'social_facility') |\n (POIs['amenity'] == \"bank\") |\n (POIs['amenity'] == 'shelter') |\n (POIs['amenity'] == 'pharmacy') |\n (POIs['amenity'] == 'water_well') |\n (POIs['amenity'] == 'dentist') |\n (POIs['amenity'] == 'doctors') |\n (POIs['amenity'] == 'embassy') |\n (POIs['amenity'] == 'town_hall') |\n (POIs['amenity'] == 'public_building') |\n (POIs['amenity'] == 'water_tower') |\n (POIs['amenity'] == 'nursing_home') |\n (POIs['amenity'] == 'courthouse') |\n (POIs['amenity'] == 'fuel') |\n (POIs['amenity'] == 'consulate') |\n (POIs['amenity'] == 'chemist') |\n (POIs['amenity'] == 'veterinary'),\n 'Priority'] = 3\n POIs.loc[(POIs['amenity'] == 'kindergarten') |\n (POIs['amenity'] == 'school') |\n (POIs['amenity'] == 'library') |\n (POIs['amenity'] == 'college') |\n (POIs['amenity'] == \"university\"),\n 'Priority'] = 2\n POIs['Priority'].fillna(0.1, inplace=True)\n\n # --- Snap all POI to nearest road, but with a maximum tolerance of 50 m ---\n # Convert data to pseudo mercator\n print(\"Reprojecting POI to pseudo mercator\")\n POI = POIs.to_crs(epsg=3857)\n\n # Use spatial index to search for nearest lines\n print(\"Setting spatial index\")\n offset_POI = 25\n bbox_POI = POI.bounds + [-offset_POI, -offset_POI, offset_POI, offset_POI]\n hits_POI = bbox_POI.apply(lambda row: list(roads.sindex.intersection(row)), axis=1)\n\n tmp_POI = pd.DataFrame({\n # index of points table\n \"pt_idx\": np.repeat(hits_POI.index, hits_POI.apply(len)), # ordinal position of line - access via iloc later\n \"line_i\": np.concatenate(hits_POI.values)\n })\n\n tmp_POI = tmp_POI.join(roads.reset_index(drop=True), on=\"line_i\")\n tmp_POI = tmp_POI.join(POI.geometry.rename(\"point\"), on=\"pt_idx\")\n tmp_POI = gpd.GeoDataFrame(tmp_POI, geometry=\"geometry\", crs=POI.crs)\n\n print(\"Finding closest road to each POI\")\n # Find closest line to each point\n tmp_POI[\"snap_dist\"] = tmp_POI.geometry.distance(gpd.GeoSeries(tmp_POI.point))\n tmp_POI = tmp_POI.loc[tmp_POI.snap_dist <= offset_POI]\n tmp_POI = tmp_POI.sort_values(by=[\"snap_dist\"])\n\n print(\"Snapping nodes to nearest road\")\n closest_POI = tmp_POI.groupby(\"pt_idx\").first()\n closest_POI = gpd.GeoDataFrame(closest_POI, geometry=\"geometry\")\n pos_POI = closest_POI.geometry.project(gpd.GeoSeries(closest_POI.point))\n new_pts_POI = closest_POI.geometry.interpolate(pos_POI)\n\n snapped_POI = gpd.GeoDataFrame(closest_POI, geometry=new_pts_POI)\n updated_points_POI = POI.drop(columns=[\"geometry\"]).join(snapped_POI, lsuffix='_x', rsuffix='')\n updated_points_POI = updated_points_POI.dropna(subset=[\"geometry\"])\n\n roads_SN['Road_ID'] = roads_SN['Road_ID'].astype(object)\n updated_points_POI['Road_ID'] = updated_points_POI['Road_ID'].astype(object)\n\n join_3 = roads_SN.merge(updated_points_POI, on='Road_ID', how='left')\n\n print(\"Summing priority scores for each road\")\n Sum_POI = join_3.groupby(['Road_ID'])['Priority'].sum().reset_index()\n\n print(\"merging roads with summed POI\")\n roads_SN_POI = roads_SN.merge(Sum_POI, on='Road_ID', how='left')\n\n return(roads_SN_POI)\n\ndef Assign_criticality(roads_SN_POI):\n \"\"\"\n This function calculates the criticality score for the road network.\n Criticality is assigned based on the criteria outlined in Hayes et al.\n\n Parameters\n ----------\n roads_SN_POI : GeoDataFrame that is the output of the Assign_community_faciities function\n\n Returns\n ----------\n GeoDataFrame that contains the criticality score obtained for the road network (Criticality score)\n \"\"\"\n print(\"Merging road networks\")\n roads_criticality = roads_SN_POI\n\n print(\"Calculating criticality\")\n roads_criticality['Criticality'] = (roads_criticality['Node score'] * 0.33) + \\\n (roads_criticality['Priority'] * 0.33) + \\\n (roads_criticality['hierarchy'] * 0.33)\n # Percentile_25 = roads_criticality.Criticality.quantile(0.25)\n Percentile_50 = roads_SN_POI.Criticality.quantile(0.50)\n Percentile_90 = roads_criticality.Criticality.quantile(0.90)\n Percentile_99 = roads_criticality.Criticality.quantile(0.99)\n\n print(\"Assigning criticality score\")\n roads_criticality.loc[roads_criticality['Criticality'] <= Percentile_50, 'Criticality score'] = 1\n roads_criticality.loc[roads_criticality['Criticality'] > Percentile_50, 'Criticality score'] = 10\n roads_criticality.loc[roads_criticality['Criticality'] > Percentile_90, 'Criticality score'] = 100\n roads_criticality.loc[roads_criticality['Criticality'] > Percentile_99, 'Criticality score'] = 1000\n\n return(roads_criticality)\n\ndef Get_LoR_Score (roads_criticality):\n \"\"\"\n This function assigns a length of road score to each road segment within the road network\n Length of road score assigned based on criteria outlined in Hayes et al.\n\n Parameters\n ----------\n roads_criticality : GeoDataFrame that is the output of the Assign_criticality function\n\n Returns\n ----------\n GeoDataFrame that contains a length of road score (LoR score)\n\n \"\"\"\n print(\"reprojecting roads layer\")\n roads_criticality = roads_criticality.to_crs(epsg=3857)\n print(\"Calculating segment lengths\")\n roads_criticality['length'] = roads_criticality[\"geometry\"].length\n print(\"Obtaining quantiles\")\n Percentile_25 = roads_criticality['length'].quantile(0.25)\n Percentile_50 = roads_criticality['length'].quantile(0.50)\n Percentile_75 = roads_criticality['length'].quantile(0.75)\n print(\"Assigning length of road score\")\n roads_criticality.loc[roads_criticality['length'] <= Percentile_25, 'LoR score'] = 0.01\n roads_criticality.loc[roads_criticality['length'] > Percentile_25, 'LoR score'] = 0.1\n roads_criticality.loc[roads_criticality['length'] > Percentile_50, 'LoR score'] = 1\n roads_criticality.loc[roads_criticality['length'] > Percentile_75, 'LoR score'] = 10\n\n return(roads_criticality)\n\n\n","sub_path":"RNDS_functions.py","file_name":"RNDS_functions.py","file_ext":"py","file_size_in_byte":12686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"357943800","text":"from sierra.base_parameters import MinFlowParameter\n\nfrom sierra.utilities.converter import convert\n\n\nclass IFR_bl_Millerton_Lake_Min_Flow(MinFlowParameter):\n \"\"\"\"\"\"\n\n def _value(self, timestep, scenario_index):\n\n # get WYT index\n if 3 <= self.datetime.month:\n restoration_year = self.datetime.year\n else:\n restoration_year = self.datetime.year - 1\n\n # get date index\n ifr_schedule_cfs = self.model.tables[\"IFR Schedule below Friant Dam\"]\n\n # get full natural flow\n # fnf = self.model.tables[\"Annual Full Natural Flow\"][restoration_year]\n\n if self.model.mode == 'planning':\n date_index = self.datetime.month - 1\n else:\n month_day = (self.datetime.month, self.datetime.day)\n date_index = sum([1 for md in ifr_schedule_cfs.index if month_day >= md]) - 1\n\n # get IFR from schedule\n wyt = self.model.tables[\"SJ restoration flows\"].at[restoration_year, 'WYT']\n wyt_index = wyt - 1\n ifr_cfs = ifr_schedule_cfs.iat[date_index, wyt_index]\n if wyt in [3, 4, 5]:\n allocation_adjustment = self.model.tables[\"SJ restoration flows\"] \\\n .at[restoration_year, 'Allocation adjustment']\n ifr_cfs *= allocation_adjustment\n\n if self.model.mode == \"planning\":\n ifr_cfs *= self.days_in_month\n\n return ifr_cfs / 35.31\n\n def value(self, timestep, scenario_index):\n val = self.requirement(timestep, scenario_index, default=self._value)\n return convert(val, \"m^3 s^-1\", \"m^3 day^-1\", scale_in=1, scale_out=1000000.0)\n\n @classmethod\n def load(cls, model, data):\n try:\n return cls(model, **data)\n except Exception as err:\n print('File where error occurred: {}'.format(__file__))\n print(err)\n raise\n\n\nIFR_bl_Millerton_Lake_Min_Flow.register()\n","sub_path":"sierra/models/upper_san_joaquin/_parameters/IFR_bl_Millerton_Lake_Min_Flow.py","file_name":"IFR_bl_Millerton_Lake_Min_Flow.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"261993162","text":"import pandas\n\ndata = pandas.read_csv(\"dataset.csv\")\nl = data.shape[0]\n\nfor i in range(l):\n r = data.loc[i, :]\n row = r[0].split(\";\")\n try:\n _, created = Car.objects.get_or_create(\n id=row[0],\n brand=row[1],\n model=row[2],\n year=int(row[3]),\n city=row[4],\n body_type=row[5],\n engine_volume=round(float(row[6]), 1),\n mileage=int(row[7]),\n gear_type=row[8],\n steering_wheel=row[9],\n color=row[10],\n wheel_drive=row[11],\n custom_clearanced=True if \"TRUE\" == row[12] else False,\n price=int(row[13]),\n average_price=int(row[14]),\n link=row[15],\n fuel_type=row[16],\n )\n except:\n pass\n","sub_path":"data_insertion.py","file_name":"data_insertion.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"475420998","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport data_helpers\r\nimport collections\r\nfrom tensorflow.contrib import learn\r\n\r\ntf.logging.set_verbosity(tf.logging.INFO)\r\n\r\n#hyperparameters\r\nconf = collections.namedtuple(\"conf\", \"pos, neg, sen_len, test_sam, voc, batch_size, emb_size,\"\r\n \"fil_num, dro_rate, class_num, data_type, context_dim, test_num\")\r\n\r\nconf.pos = \"./data/custrev.pos\"\r\nconf.neg = \"./data/custrev.neg\"\r\nconf.sen_len = 105\r\nconf.test_sam = 0.1\r\nconf.voc = 5335\r\nconf.batch_size = 34\r\nconf.emb_size = 50\r\nconf.fil_num = 100\r\nconf.dro_rate = 0.5\r\nconf.class_num = 2\r\nconf.context_dim = 50\r\nconf.test_num = 377\r\nconf.data_type = tf.float32\r\n\r\n\r\n# Model\r\ndef model_fn_1(features, labels, mode):\r\n\r\n # Input Layer\r\n input_layer = tf.reshape(features[\"x\"], [-1, conf.sen_len])\r\n\r\n ###word embedding\r\n W = tf.Variable(\r\n tf.random_uniform([conf.voc, conf.emb_size], -1.0, 1.0),\r\n dtype=conf.data_type, name=\"W\")\r\n embedded_chars = tf.nn.embedding_lookup(W, input_layer, None)\r\n\r\n\r\n if mode == tf.estimator.ModeKeys.TRAIN :\r\n input_z = tf.ones([conf.batch_size, conf.context_dim], dtype=conf.data_type)\r\n else:\r\n input_z = tf.ones([conf.test_num, conf.context_dim], dtype=conf.data_type)\r\n\r\n # left context\r\n c_l1 = tf.get_variable(\"c_l1\", shape=[conf.context_dim], dtype=conf.data_type)\r\n c_l = input_z * c_l1 # c_l = c_l1 --> 配合batch大小差別 : 64/1066,用來更新 c_l(i)\r\n c_left = tf.reshape(c_l, [-1, 1, conf.context_dim]) # c_left = c_l --> 為了 tf.concat\r\n w_l = tf.get_variable(\"w_l\", [conf.context_dim, conf.context_dim], dtype=conf.data_type)\r\n w_sl = tf.get_variable(\"w_sl\", [conf.emb_size, conf.context_dim], dtype=conf.data_type)\r\n\r\n # right context\r\n c_rn = tf.get_variable(\"c_rn\", [conf.context_dim], dtype=conf.data_type)\r\n c_r = input_z * c_rn # c_r = c_rn --> 為了變成 tensor\r\n c_right = tf.reshape(c_r, [-1, 1, conf.context_dim]) # c_left = c_l --> 為了 tf.concat\r\n w_r = tf.get_variable(\"w_r\", [conf.context_dim, conf.context_dim], dtype=conf.data_type)\r\n w_sr = tf.get_variable(\"w_sr\", [conf.emb_size, conf.context_dim], dtype=conf.data_type)\r\n\r\n b = tf.zeros([conf.context_dim], dtype=conf.data_type)\r\n for i in range(conf.sen_len - 1):\r\n c_left_c = tf.nn.xw_plus_b(c_l, w_l, b, name=\"c_left_c\")\r\n c_left_e = tf.nn.xw_plus_b(embedded_chars[:, i, :], w_sl, b, name=\"c_left_e\")\r\n c_l = tf.nn.relu(c_left_c + c_left_e) # 迭代計算出 c_l2, c_l3, ..., c_l56\r\n c_left = tf.concat([c_left, tf.reshape(c_l, [-1, 1, conf.context_dim])], 1)\r\n\r\n c_right_c = tf.nn.xw_plus_b(c_r, w_r, b, name=\"c_right_c\")\r\n c_right_e = tf.nn.xw_plus_b(embedded_chars[:, conf.sen_len - 1 - i, :], w_sr, b, name=\"c_right_e\")\r\n c_r = tf.nn.relu(c_right_c + c_right_e) # 迭代計算出c_l55, c_l54, ..., c_l1\r\n c_right = tf.concat([tf.reshape(c_r, [-1, 1, conf.context_dim]), c_right], 1) # 逐一加 c_l55, c_l54, ..., c_l1\r\n\r\n total_length = conf.context_dim + conf.emb_size + conf.context_dim # total_length = 150\r\n x_input = tf.concat([c_left, embedded_chars, c_right], -1)\r\n\r\n #每個 word 做 NN\r\n conv = []\r\n w_2 = tf.get_variable(\"w_2\", [total_length, conf.fil_num], dtype=conf.data_type) # w_2 : 150*100\r\n b_2 = tf.Variable(tf.constant(0.1, shape=[conf.fil_num]), name=\"b_2\") # b_2 : 100*1\r\n\r\n for i in range(conf.sen_len):\r\n dense_layer = tf.nn.xw_plus_b(tf.reshape(x_input[:, i, :], [-1, total_length]), w_2, b_2,\r\n name=\"dense_layer\") # dense_layer : 100*1,NN : 對 xi(每個word)\r\n\r\n conv.append(tf.reshape(tf.nn.tanh(dense_layer),\r\n [-1, 1, conf.fil_num])) # conv.append : 1*100 * 56,逐一加 y1, y2, ..., y56\r\n conv = tf.concat(conv, 1) # conv : 56*100\r\n\r\n #max pooling\r\n pool = tf.nn.max_pool(value=tf.reshape(conv, [-1, 1, conf.sen_len, conf.fil_num]), # conv : 1*56 *100\r\n ksize=[1, 1, conf.sen_len, 1],\r\n strides=[1, 1, 1, 1],\r\n padding=\"VALID\")\r\n\r\n #dropout\r\n dropout = tf.layers.dropout(\r\n inputs=pool, rate=conf.dro_rate, training=mode == tf.estimator.ModeKeys.TRAIN)\r\n\r\n #fully connected layer\r\n W1 = tf.get_variable(\"W\",\r\n shape=[conf.fil_num, conf.class_num],\r\n initializer=tf.contrib.layers.xavier_initializer())\r\n b1 = tf.Variable(tf.constant(0.1, shape=[conf.class_num]), name=\"b\")\r\n\r\n #scores\r\n scores = tf.nn.xw_plus_b(tf.reshape(dropout, [-1, conf.fil_num]), W1, b1, name=\"scores\")\r\n\r\n #predictions\r\n predictions = {\r\n # Generate predictions (for PREDICT and EVAL mode)\r\n \"classes\": tf.argmax(input=scores, axis=1),\r\n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\r\n # `logging_hook`.\r\n \"probabilities\": tf.nn.softmax(scores, name=\"softmax_tensor\")\r\n }\r\n\r\n if mode == tf.estimator.ModeKeys.PREDICT:\r\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\r\n\r\n\r\n # Calculate Loss (for both TRAIN and EVAL modes)\r\n loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=scores)\r\n\r\n # Configure the Training Op (for TRAIN mode)\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)\r\n train_op = optimizer.minimize(\r\n loss=loss,\r\n global_step=tf.train.get_global_step())\r\n # optimizer = tf.train.AdamOptimizer(0.001)\r\n # train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())\r\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\r\n\r\n # Add evaluation metrics (for EVAL mode)\r\n #labels1 = tf.argmax(input=labels, axis=1)\r\n eval_metric_ops = {\r\n \"accuracy\": tf.metrics.accuracy(\r\n labels=tf.argmax(input=labels, axis=1), predictions=predictions[\"classes\"])}\r\n return tf.estimator.EstimatorSpec(\r\n mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\r\n\r\n\r\n\r\ndef main(unused_argv):\r\n\r\n x_data, y = data_helpers.load_data_and_labels(conf.pos, conf.neg)\r\n\r\n # Build vocabulary\r\n max_document_length = max([len(x.split(\" \")) for x in x_data])\r\n vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\r\n x = np.array(list(vocab_processor.fit_transform(x_data)))\r\n\r\n # Randomly shuffle data\r\n np.random.seed(10)\r\n shuffle_indices = np.random.permutation(np.arange(len(y)))\r\n x_shuffled = x[shuffle_indices]\r\n y_shuffled = y[shuffle_indices]\r\n\r\n # Split train/test set\r\n test_sample_index = -1 * int(conf.test_sam * float(len(y)))\r\n x_train, x_test = x_shuffled[:test_sample_index], x_shuffled[test_sample_index:]\r\n y_train, y_test = y_shuffled[:test_sample_index], y_shuffled[test_sample_index:]\r\n\r\n x_train1 = np.asarray(x_train)\r\n y_train1 = np.asarray(y_train, dtype = np.int32)\r\n\r\n x_test1 = np.asarray(x_test)\r\n y_test1 = np.asarray(y_test, dtype=np.int32)\r\n\r\n\r\n del x, y, x_shuffled, y_shuffled\r\n\r\n print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\r\n print(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_test)))\r\n\r\n\r\n # Create the Estimator\r\n text_classifier = tf.estimator.Estimator(model_fn=model_fn_1, model_dir=\"./models\")\r\n\r\n # Set up logging for predictions\r\n tensors_to_log = {\"probabilities\": \"softmax_tensor\"}\r\n logging_hook = tf.train.LoggingTensorHook(\r\n tensors=tensors_to_log, every_n_iter=100)\r\n\r\n # Train the model\r\n train_input_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": x_train1},\r\n y=y_train1,\r\n batch_size=conf.batch_size,\r\n num_epochs=None,\r\n shuffle=True)\r\n text_classifier.train(\r\n input_fn=train_input_fn,\r\n steps=30000,\r\n hooks=[logging_hook])\r\n\r\n # Evaluate the model and print results\r\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": x_test1},\r\n y=y_test1,\r\n batch_size=conf.test_num,\r\n num_epochs=1,\r\n shuffle=False)\r\n eval_results = text_classifier.evaluate(input_fn=eval_input_fn)\r\n print(eval_results)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n tf.app.run()","sub_path":"RCNN/CR/CR_RCNN.py","file_name":"CR_RCNN.py","file_ext":"py","file_size_in_byte":8138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"194927223","text":"# Write a program to compute a list of cubes of the items in the above list using the list comprehension. The output of the program should be:\na_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nnew = [i**3 for i in a_list]\nprint(new)\n\n\n# If you are given three sticks, you may or may not be able to arrange them in a triangle. \n# For example, if one of the sticks is 12 inches long and the other two are one inch long, \n# you will not be able to get the short sticks to meet in the middle. For any three lengths, \n# there is a simple test to see if it is possible to form a triangle:\n\n# If any of the three lengths is greater than the sum of the other two, then you cannot form\n# a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)\n\n# Write a program which takes lengths \n# of three sticks from the keyboard and then \n# prints either “Yes” or “No”, depending on whether you can or cannot form a triangle from sticks with the entered lengths. \n\nprint(\"Can you form a triange?\")\nstick_1 = input(\"What is the length of the first stick? \")\nstick_2 = input(\"What is the length of the second stick? \")\nstick_3 = input(\"What is the length of the third stick? \")\n\nif (int(stick_1) + int(stick_2)) > int(stick_3) and (int(stick_1)+ int(stick_3)) > int(stick_2) and (int(stick_3) + int(stick_2)) > int(stick_1):\n\tprint(\"Yes\")\nelse:\n\tprint(\"No\")\n","sub_path":"cube_and_triangle.py","file_name":"cube_and_triangle.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"499108030","text":"\"\"\"\nleetcode 254 Factor Combinations\n\"\"\"\n\nclass Solution(object):\n def getFactors(self, n, start = 2):\n \"\"\"\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n for x in range(start, int(math.sqrt(n))+1):\n quot, rem = divmod(n, x)\n if rem == 0:\n res.append([x, quot])\n if int(math.sqrt(quot))>= x:\n res +=[[x]+ r for r in self.getFactors(quot, x)]\n return res\n","sub_path":"python/factor_combinations.py","file_name":"factor_combinations.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"550619965","text":"from setuptools import setup, find_packages\nimport sys, os\n\nhere = os.path.abspath(os.path.dirname(__file__))\ntry:\n README = open(os.path.join(here, 'README.rst')).read()\nexcept IOError:\n README = ''\n\nversion = \"0.0.1\"\n\ntestpkgs = [\n 'WebTest == 1.4.3',\n 'nose',\n 'coverage',\n 'tgext.pluggable'\n]\n\nsetup(\n name='tgext.langdomain',\n version=version,\n description=\"TurboGears2 extension for detecting user language from the domain\",\n long_description=README,\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='turbogears2.extension',\n author='AXANT',\n author_email='tech@axant.it',\n url='https://bitbucket.org/axant/tgext.langdomain',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n namespace_packages=['tgext'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n \"TurboGears2 >= 2.3.4\",\n ],\n test_suite='nose.collector',\n tests_require=testpkgs,\n extras_require={\n # Used by Drone.io\n 'testing': testpkgs,\n },\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\"\n)\n","sub_path":"pypi_install_script/tgext.langdomain-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"569335407","text":"from discord.ext.commands import Converter, MemberConverter\nfrom discord import utils\n\n\nclass InsensitiveMemberConverter(MemberConverter):\n async def convert(self, ctx, argument):\n try:\n return await super().convert(ctx, argument)\n except Exception as e:\n member_to_find = argument.lower()\n predicate = (lambda m: member_to_find in m.name.lower()\n or member_to_find in m.display_name.lower())\n result = utils.find(predicate, ctx.guild.members)\n if result:\n return result\n raise e\n\n\nclass ReasonConverter(Converter):\n async def convert(self, ctx, argument):\n return f'Executed by {ctx.author} ({ctx.author.id}). Reason: {argument}'\n","sub_path":"utils/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"198986233","text":"import numpy as np\nimport numpy.ma as ma\nfrom landsat import Landsat\nfrom image import Image\nfrom modis import Modis\nfrom aster import Aster\nimport pandas as pd\n\n\nclass Secteur:\n \"\"\" Classe modélisant un secteur qu'on veut utiliser pour entraîner et prédire la température de surface.\n Ce secteur est composé d'images Landsat, MODIS et ASTER se superposant sur une même zone.\n On utilise l'image MODIS comme référence pour aligner, découper et rééchantillonner les autres images sur une\n zone de taille identique.\n\n Attributes:\n modis_image (Modis): Collection d'images MODIS préalablement instanciée dans la classe Modis.\n landsat_image (Landsat): Collection d'images Landsat 8 préalablement instanciée dans la classe Landsat.\n aster_image (Aster): Collection d'images Aster préalablement instanciée dans la classe Aster.\n mask (Numpy.ma.masked_array): Masque à appliquer à l'ensemble des images une fois alignées et rééchantillonnées.\n \"\"\"\n def __init__(self, modis_image, landsat_image, aster_image):\n self.modis_image = modis_image\n self.landsat_image = landsat_image\n self.aster_image = aster_image\n\n self.mask = None\n\n def prepareData(self, train_model=True, targetResolution=100):\n \"\"\" Permet de préparer les images avant l'entraînement du modèle ou à la prédiction de la température de surface.\n\n Args:\n train_model (bool): Indicateur pour déterminer si les données sont préparées pour l'entraînement ou\n pour la prédiction.\n Si la valeur de l'indicateur est \"False\", on subdivise l'image MODIS de 1km à 100m\n (ou 30m) et on reprojette les images pour avoir un nombre de pixels compatible\n (à 100m ou 30m). Sinon, on fait le tout à 1km.\n targetResolution (int): Résolution spatiale vers laquelle on veut faire la réduction d'échelle.\n Options possibles: 100 (pour une réduction à 100m), 30 (pour une réduction\n à 30m). Par défaut, on effectue le downscaling à 100m.\n \"\"\"\n\n # on prépare les images pour l'entraînement (toutes les images à 1000m)\n if train_model:\n # masquage des nuages sur l'image Landsat à 30m directement\n #self.landsat_image.maskClouds30m()\n\n # Masquage de l'image Landsat rééchantillonnée selon le pourcentage de nuages à l'intérieur d'un pixel de\n # 1000m\n #imageLandsatQa = Image(self.landsat_image.qa)\n #pourcentageNuage = imageLandsatQa.cloudOverlay(self.modis_image.lst, reduce_zone=True, data_source=self.landsat_image.src)\n\n self.landsat_image.reprojectLandsat(self.modis_image.lst)\n\n #self.landsat_image.maskClouds1000m(pourcentageNuage)\n\n # reprojection de l'image Aster pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.aster_image.reprojectAster(self.modis_image.lst)\n\n # reprojection de l'image MODIS pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.modis_image.reprojectModis(self.modis_image.lst)\n\n # on prépare les images pour la prédiction (images à 100m ou 30m)\n else:\n\n if targetResolution == 100:\n # subdivision de l'image MODIS de 1km à 100m\n self.modis_image.subdividePixel(10, \"file\",\n self.modis_image.lst.split(\".\")[0] + '_subdivided_100m.tif')\n elif targetResolution == 30:\n # subdivision de l'image MODIS de 1km à 30m (environ: très proche)\n self.modis_image.subdividePixel(33.33333333333333, \"file\",\n self.modis_image.lst.split(\".\")[0] + '_subdivided_30m.tif')\n\n # réinitialise les bandes des images aux bandes originales (rééchantillonnage de 30m à 100m au lieu de 1km\n # à 100m pour Landsat)\n self.landsat_image.b1 = self.landsat_image.b1.replace(\"_reproject\", \"\")\n self.landsat_image.b2 = self.landsat_image.b2.replace(\"_reproject\", \"\")\n self.landsat_image.b3 = self.landsat_image.b3.replace(\"_reproject\", \"\")\n self.landsat_image.b4 = self.landsat_image.b4.replace(\"_reproject\", \"\")\n self.landsat_image.b5 = self.landsat_image.b5.replace(\"_reproject\", \"\")\n self.landsat_image.b6 = self.landsat_image.b6.replace(\"_reproject\", \"\")\n self.landsat_image.b7 = self.landsat_image.b7.replace(\"_reproject\", \"\")\n self.landsat_image.qa = self.landsat_image.qa.replace(\"_reproject\", \"\")\n\n # imageLandsatQa = Image(self.landsat_image.qa)\n # pourcentageNuage = imageLandsatQa.cloudOverlay(self.modis_image.lst.split(\".\")[0] + '_subdivided_100m.tif', reduce_zone=False)\n\n self.modis_image.lst = self.modis_image.lst.replace(\"_reproject\", \"\")\n self.modis_image.qa = self.modis_image.qa.replace(\"_reproject\", \"\")\n\n self.aster_image.mnt = self.aster_image.mnt.replace(\"_reproject\", \"\")\n self.aster_image.qa = self.aster_image.qa.replace(\"_reproject\", \"\")\n\n if targetResolution == 100:\n # reprojection de l'image Landsat et ré-échantillonnage à 100m\n self.landsat_image.reprojectLandsat(self.modis_image.lst.split(\".\")[0] + '_subdivided_100m.tif',\n reduce_zone=False)\n\n # self.landsat_image.maskClouds1000m(pourcentageNuage) # masque à 100m cette fois-ci\n\n # reprojection de l'image Aster pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.aster_image.reprojectAster(self.modis_image.lst.split(\".\")[0] + '_subdivided_100m.tif',\n reduce_zone=False)\n\n # reprojection de l'image MODIS pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.modis_image.reprojectModis(self.modis_image.lst.split(\".\")[0] + '_subdivided_100m.tif',\n reduce_zone=False)\n\n elif targetResolution == 30:\n # reprojection de l'image Landsat et ré-échantillonnage à 100m\n self.landsat_image.reprojectLandsat(self.modis_image.lst.split(\".\")[0] + '_subdivided_30m.tif',\n reduce_zone=False)\n\n # self.landsat_image.maskClouds1000m(pourcentageNuage) # masque à 30m cette fois-ci\n\n # reprojection de l'image Aster pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.aster_image.reprojectAster(self.modis_image.lst.split(\".\")[0] + '_subdivided_30m.tif',\n reduce_zone=False)\n\n # reprojection de l'image MODIS pour avoir la même taille que celle de Landsat préalablement reprojetée\n self.modis_image.reprojectModis(self.modis_image.lst.split(\".\")[0] + '_subdivided_30m.tif',\n reduce_zone=False)\n\n def getDf(self, predictors, train=True):\n \"\"\" Aller chercher le DataFrame contenant l'ensemble des prédicteurs préparés pour le downscaling.\n Args:\n predictors (list): Liste de string des prédicteurs à inclure dans l'entraînement ou la prédiction\n de la réduction d'échelle. Cet argument doit prendre la forme suivante:\n ['NDVI', 'NDWI', 'NDBI', 'MNT', 'Pente']\n avec des prédicteurs disponibles dans cette méthode.\n train (bool): Indicateur pour déterminer si les données sont préparées pour l'entraînement ou\n pour la prédiction.\n Si la valeur de l'indicateur est \"False\", on combine les variables ensemble avec des\n array masqués pour qu'on puisse retirer les valeurs nulles qui ont été masquées.\n Sinon, on combine les variables ensemble avec un array standard et on masque les\n données par la suite (le Random Forest Regression n'accepte pas les valeurs nulles,\n il ignore les masques dans le Pandas DataFrame).\n Returns:\n df (Pandas DataFrame): Combinaison des variables nécessaires pour l'entraînement du modèle ou la\n prédiction de la température de surface.\n \"\"\"\n\n # ******** PRÉDICTEURS ***********\n\n predictors_dict = {}\n\n # Calcul des prédicteurs (masquage des valeurs nulles inclus dans les get)\n # Landsat\n if 'NDVI' in predictors:\n ndvi = self.landsat_image.getNdvi()\n predictors_dict['NDVI'] = ndvi\n\n if 'NDWI' in predictors:\n ndwi = self.landsat_image.getNdwi()\n predictors_dict['NDWI'] = ndwi\n\n if 'NDBI' in predictors:\n ndbi = self.landsat_image.getNdbi()\n predictors_dict['NDBI'] = ndbi\n\n if 'MNDWI' in predictors:\n mndwi = self.landsat_image.getMndwi()\n predictors_dict['MNDWI'] = mndwi\n\n if 'SAVI' in predictors:\n savi = self.landsat_image.getSAVI()\n predictors_dict['SAVI'] = savi\n\n if 'Albedo' in predictors:\n albedo = self.landsat_image.getAlbedo()\n predictors_dict['Albedo'] = albedo\n\n if 'BSI' in predictors:\n bsi = self.landsat_image.getBSI()\n predictors_dict['BSI'] = bsi\n\n if 'UI' in predictors:\n ui = self.landsat_image.getUI()\n predictors_dict['UI'] = ui\n\n if 'EVI' in predictors:\n evi = self.landsat_image.getEVI()\n predictors_dict['EVI'] = evi\n\n if 'IBI' in predictors:\n ibi = self.landsat_image.getIBI()\n predictors_dict['IBI'] = ibi\n\n if 'B1' in predictors:\n b1 = self.landsat_image.getBand(1)\n predictors_dict['B1'] = b1\n\n if 'B2' in predictors:\n b2 = self.landsat_image.getBand(2)\n predictors_dict['B2'] = b2\n\n if 'B3' in predictors:\n b3 = self.landsat_image.getBand(3)\n predictors_dict['B3'] = b3\n\n if 'B4' in predictors:\n b4 = self.landsat_image.getBand(4)\n predictors_dict['B4'] = b4\n\n if 'B5' in predictors:\n b5 = self.landsat_image.getBand(5)\n predictors_dict['B5'] = b5\n\n if 'B6' in predictors:\n b6 = self.landsat_image.getBand(6)\n predictors_dict['B6'] = b6\n\n if 'B7' in predictors:\n b7 = self.landsat_image.getBand(7)\n predictors_dict['B7'] = b7\n\n # Aster\n if 'MNT' in predictors:\n mnt = self.aster_image.getMNT()\n predictors_dict['MNT'] = mnt\n\n if 'Pente' in predictors:\n pente = self.aster_image.getPente()\n predictors_dict['Pente'] = pente\n\n if 'Orientation' in predictors:\n orientation = self.aster_image.getOrientation()\n predictors_dict['Orientation'] = orientation\n\n # Reshape les array en colonnes pour tous les prédicteurs\n for predictor in predictors_dict:\n predictors_dict[predictor] = (predictors_dict[predictor]).reshape(-1, 1)\n\n # ******** MODIS LST ***********\n\n # Conversion du array MODIS LST en un format compatible au Random Forest Regression\n lst_image = Image(self.modis_image.lst)\n\n modis_array = lst_image.getArray(masked=True, lower_valid_range=7500, upper_valid_range=65535)\n\n # convertir à des températures de surface en Celsius\n lst_metadata = lst_image.getMetadata()\n\n # vérifier si le scale_factor est présent dans les métadonnées (c'est le cas pour AppEEARS, pas EarthData)\n if 'scale_factor' in lst_metadata:\n scale_factor = float(lst_metadata['scale_factor']) # multiplier par 0.02\n add_offset = float(lst_metadata['add_offset'])\n else:\n scale_factor = float(0.02)\n add_offset = float(0)\n\n # conversion en Kelvin, puis en Celsius\n kelvin_array = np.add(np.multiply(modis_array, scale_factor), add_offset)\n lst_celsius_array = np.subtract(kelvin_array, 273.15)\n\n # Reshape en une colonne\n lst_celsius_array = lst_celsius_array.reshape(-1, 1)\n # *******************\n\n # appliquer les mêmes masques partout (si un pixel est masqué dans une image, il doit être masqué pour toutes\n # les images)\n masks = [] # ensemble des masques à remplir\n\n for predictor in predictors_dict:\n masks.append(ma.getmaskarray(predictors_dict[predictor]))\n\n masks.append(ma.getmaskarray(lst_celsius_array))\n\n # masque unique pour tous les jeux de données\n mask = sum(masks) # somme de masques: toutes les valeurs qui ne sont pas égales à 0 corresponded à une position\n # à masquer\n self.mask = mask\n\n # masquage identique de tous les jeux de données\n for predictor in predictors_dict:\n predictors_dict[predictor] = ma.masked_array(predictors_dict[predictor], mask)\n\n lst_celsius_array = ma.masked_array(lst_celsius_array, mask)\n\n # ********* Stack les colonnes ensemble **********\n\n # extraire les noms des prédicteurs et les array associés\n predictor_names = []\n predictor_values = []\n\n for predictor in predictors_dict:\n predictor_names.append(predictor)\n predictor_values.append(predictors_dict[predictor])\n\n # construction d'une matrice vide de dimensions (nombre_de_pixels, nombre_de_predicteurs + 1)\n if train:\n col_stack = ma.empty([predictor_values[0].shape[0], len(predictor_values) + 1]) # +1 = colonne pour LST\n else:\n col_stack = np.empty([predictor_values[0].shape[0], len(predictor_values) + 1]) # +1 = colonne pour LST\n\n # ajout des prédicteurs dans les colonnes (de la première jusqu'à l'avant-dernière)\n for i in range(0, len(predictor_values)):\n col_stack[:, [i]] = predictor_values[i]\n\n col_stack[:, [-1]] = lst_celsius_array # ajout de la LST dans la dernière colonne\n predictor_names.append('LST')\n\n # Création d'un dataframe Pandas qui contient la matrice construite précédemment et qui indique les labels de\n # chacune des colonnes\n df = pd.DataFrame(col_stack, columns=predictor_names) # dataframe ne gère pas les masques?\n\n # à changer pour que l'utilisateur puisse choisir où sauvegarder (et/ou s'il veut sauvegarder les CSV)\n \"\"\" # enlever cette ligne et la ligne 314 si on veut sauvegarder les données utilisées sous forme de CSV pour\n # une visualisation des données numériques fournies comme prédicteurs et comme LST\n if train:\n # Sauvegarder en CSV pour visualisation et vérification plus tard\n df.to_csv(r'data/donnees_utilisees_train.csv', index=False)\n print(\"DataFrame pour l'entraînement sauvegardé à: data/donnees_utilisees_train.csv\")\n else:\n df.to_csv(r'data/donnees_utilisees_predict.csv', index=False)\n print(\"DataFrame pour la prédiction sauvegardé à: data/donnees_utilisees_predict.csv\")\n \"\"\"\n return df\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"validation_externe/secteur.py","file_name":"secteur.py","file_ext":"py","file_size_in_byte":16008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"154008300","text":"# -*- coding: utf-8 -*-\n\"\"\" \n@Time    : 2021/7/8 22:00\n@Author  : ms\n@FileName: test_app.py\n@SoftWare: PyCharm\n\"\"\"\nfrom appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\nclass Test_wework:\n def setup(self):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['platformVersion'] = '7.1'\n desired_caps['deviceName'] = '127.0.0.1:21503'\n # com.android.settings/com.android.settings.Settings\n desired_caps['appPackage'] = 'com.tencent.wework'\n desired_caps['appActivity'] = 'com.tencent.wework.launch.WwMainActivity'\n desired_caps[\"noReset\"] = 'true'\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n self.driver.implicitly_wait(5)\n def treadown(self):\n pass\n\n def test_local(self):\n self.driver.find_element(MobileBy.XPATH,\"//*[@text='工作台']\").click()\n self.driver.find_element_by_android_uiautomator('new UiScrollable(new UiSelector().'\n 'scrollable(true).instance(0)).'\n 'scrollIntoView(new UiSelector().text(\"打卡\").'\n 'instance(0));').click()\n self.driver.find_element(MobileBy.XPATH, \"//*[@text='外出打卡']\").click()\n\n self.driver.find_element(MobileBy.XPATH,\"//*[contains(@text,'次外出')]\").click()\n # expected_conditions\n WebDriverWait(self.driver, 10).until(lambda x: \"外出打卡成功\" in x.page_source)\n # print(self.driver.find_element(MobileBy.XPATH, \"//*[contains(@text,'Clicked popup')]\").text)","sub_path":"Test_appium/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"511114352","text":"import os\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'auth.db')\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\nSECRET_KEY = \"Super Secret Key!\"\n\nDEBUG = True\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"39548754","text":"import time\n\nfrom flask import Flask\nfrom datetime import datetime\n\nTIMEOUT = 0.245\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef ping():\n return \"python - ping\\n\"\n\n@app.route(\"/timeout/\")\ndef timeout():\n time.sleep(TIMEOUT)\n return \"python - timeout\\n\"\n\n@app.route(\"/heavy/\")\ndef heavy():\n start = datetime.now()\n while True:\n now = datetime.now()\n if (now - start).total_seconds() >= TIMEOUT:\n return \"python - heavy\\n\"\n\nif (__name__ == \"__main__\"):\n app.run()","sub_path":"py/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"133637392","text":"pessoa = {\n 'nome': 'Lucas',\n 'sobrenome': 'Silva',\n 'idade': 30,\n 'cidade': 'Marília'}\n\nprint(pessoa)\n\nfor chave, valor in pessoa.items():\n print(\"\\nChave: {}\".format(chave))\n print(\"Valor: {}\".format(valor))\n\nif 'carro' not in pessoa.keys():\n print('carro')\n\nif 'carro' not in pessoa.items():\n print('carro2')\n\nfor chave in sorted(pessoa.keys()):\n print(chave)\n\nfor valor in sorted(pessoa.items()):\n print(valor)\n\nfor valor in pessoa.values():\n print(valor)\n\n\nrios = { \n 'nilo': 'egito',\n 'amazonas': 'brasil',\n 'prata': 'argentina'}\n\nfor chave, valor in rios.items():\n print(\"O {} corre por {}\".format(chave, valor))\n\nfor chave in rios.keys():\n print(chave)\n\nfor valor in rios.values():\n print(valor)\n","sub_path":"dicionarios.py","file_name":"dicionarios.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"488360771","text":"#!/usr/bin/env python\nfrom __future__ import print_function, absolute_import, division\n\nimport logging\nimport ctypes\nimport struct\n\nfrom collections import defaultdict\nfrom errno import ENOENT, ENOTTY\nfrom stat import S_IFDIR, S_IFREG\nfrom sys import argv, exit\nfrom time import time\nfrom ioctl_opt import IOWR\n\nfrom fuse import FUSE, FuseOSError, Operations, LoggingMixIn\n\nif not hasattr(__builtins__, 'bytes'):\n bytes = str\n\nclass Ioctl(LoggingMixIn, Operations):\n 'Example filesystem based on memory.py to demonstrate ioctl().'\n\n def __init__(self):\n self.files = {}\n self.data = defaultdict(bytes)\n self.fd = 0\n now = time()\n self.files['/'] = dict(st_mode=(S_IFDIR | 0o755), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=2)\n\n def create(self, path, mode):\n self.files[path] = dict(st_mode=(S_IFREG | mode), st_nlink=1,\n st_size=0, st_ctime=time(), st_mtime=time(),\n st_atime=time())\n\n self.fd += 1\n return self.fd\n\n def getattr(self, path, fh=None):\n if path not in self.files:\n raise FuseOSError(ENOENT)\n\n return self.files[path]\n\n def open(self, path, flags):\n self.fd += 1\n return self.fd\n\n def readdir(self, path, fh):\n return ['.', '..'] + [x[1:] for x in self.files if x != '/']\n\n def ioctl(self, path, cmd, arg, fh, flags, data):\n M_IOWR = IOWR(ord('M'), 1, ctypes.c_uint32)\n if cmd == M_IOWR:\n inbuf = ctypes.create_string_buffer(4)\n ctypes.memmove(inbuf, data, 4)\n data_in = struct.unpack('' % argv[0])\n exit(1)\n\n logging.basicConfig(level=logging.DEBUG)\n fuse = FUSE(Ioctl(), argv[1], foreground=True)\n","sub_path":"examples/ioctl.py","file_name":"ioctl.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"335561777","text":"import json\n\nfrom django.http import HttpResponse\n\n\nclass ErrorID(object):\n default = 500\n success = 200\n jurisdiction = 304\n value = 302\n\n\nclass JsonClass(object):\n \"\"\"所以返回Json数据的基类\"\"\"\n\n def __init__(self, success=False, errorid=ErrorID.default, html=\"\"):\n self.success = success\n self.errorID = errorid\n self.html = html\n self.other = {}\n\n self.cookie = None\n\n def render(self):\n rul = {\n \"success\": self.success,\n \"errorID\": self.errorID,\n \"html\": self.html,\n \"other\": self.other\n }\n res = HttpResponse(json.dumps(rul))\n if not(self.cookie is None):\n for k, (v, t) in self.cookie.items():\n res.set_cookie(k, v, t)\n return res\n\n","sub_path":"goodsManage/BusinessLogic/JsonClass.py","file_name":"JsonClass.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"29872291","text":"# -*- coding:utf-8 -*-\nimport os\nimport codecs\nimport shutil\nfrom pydoc import locate\nimport tensorflow as tf\nimport numpy as np\nfrom seq2seq import tasks, models, graph_utils\nfrom seq2seq.training import utils as training_utils\nfrom seq2seq.tasks.inference_task import InferenceTask, unbatch_dict\n\nSEQUENCE_LEN_MAX = 50\n\nclass DecodeOnce(InferenceTask):\n '''\n Similar to tasks.DecodeText, but for one input only.\n Source fed via features.source_tokens and features.source_len\n '''\n def __init__(self, params, callback_func):\n super(DecodeOnce, self).__init__(params)\n self.callback_func=callback_func\n \n @staticmethod\n def default_params():\n return {}\n\n def before_run(self, _run_context):\n fetches = {}\n fetches[\"predicted_tokens\"] = self._predictions[\"predicted_tokens\"]\n fetches[\"logits\"] = self._predictions[\"logits\"]\n fetches[\"features.source_tokens\"] = self._predictions[\"features.source_tokens\"]\n fetches[\"features.source_candidate_tokens\"] = self._predictions[\"features.source_candidate_tokens\"]\n fetches[\"beam_parent_ids\"] = self._predictions[\"beam_search_output.beam_parent_ids\"]\n return tf.train.SessionRunArgs(fetches)\n\n def after_run(self, _run_context, run_values):\n fetches_batch = run_values.results\n for fetches in unbatch_dict(fetches_batch):\n # Convert to unicode\n fetches[\"predicted_tokens\"] = np.char.decode(\n fetches[\"predicted_tokens\"].astype(\"S\"), \"utf-8\")\n predicted_tokens = fetches[\"predicted_tokens\"]\n\n # If we're using beam search we take the first beam\n # TODO: beam search top k\n if np.ndim(predicted_tokens) > 2:\n predicted_tokens = predicted_tokens[:, 0]\n\n fetches[\"features.source_tokens\"] = np.char.decode(\n fetches[\"features.source_tokens\"].astype(\"S\"), \"utf-8\")\n source_tokens = fetches[\"features.source_tokens\"]\n source_candidate_tokens = fetches[\"features.source_candidate_tokens\"]\n key = list(source_tokens) + [\"#\"] + [s.decode(\"UTF-8\") for s in source_candidate_tokens]\n self.callback_func(key, predicted_tokens)\n\n\n\nprint(\"start to test\")\n# TODO: pass via args\n# MODEL_DIR = \"model_fin_qa\"\nMODEL_DIR = \"model_fin_qa\"\ncheckpoint_path = tf.train.latest_checkpoint(MODEL_DIR)\nprint(\"checkpoint:\" + checkpoint_path)\n\n# Load saved training options\ntrain_options = training_utils.TrainOptions.load(MODEL_DIR)\n\n# Create the model\nmodel_cls = locate(train_options.model_class) or \\\n getattr(models, train_options.model_class)\nmodel_params = train_options.model_params\nmodel_params.update({\"inference.beam_search.beam_width\": 5})\n\nprint(\"create model class\")\nmodel = model_cls(\n params=model_params,\n mode=tf.contrib.learn.ModeKeys.INFER)\n\n\n# first dim is batch size\n# source_query_tokens_ph = tf.placeholder(dtype=tf.string, shape=(1, None), name=\"source_tokens\")\n# source_query_len_ph = tf.placeholder(dtype=tf.int32, shape=(1,), name=\"source_len\")\n# source_candidate_tokens_ph = tf.placeholder(dtype=tf.string, shape=(1, None), name=\"source_candidate_tokens\")\n# source_candidate_len_ph = tf.placeholder(dtype=tf.int32, shape=(1,), name=\"source_candidate_len\")\nsource_query_tokens_ph = tf.placeholder(dtype=tf.string, shape=(), name=\"source_tokens\")\nsource_query_len_ph = tf.placeholder(dtype=tf.int32, shape=(), name=\"source_len\")\nsource_candidate_tokens_ph = tf.placeholder(dtype=tf.string, shape=(), name=\"source_candidate_tokens\")\nsource_candidate_len_ph = tf.placeholder(dtype=tf.int32, shape=(), name=\"source_candidate_len\")\n\n# source_query_tokens_input = tf.expand_dims(source_query_tokens_ph, 0)\n# source_query_len_input = tf.expand_dims(source_query_len_ph, 0)\n# source_candidate_tokens_input = tf.expand_dims(source_candidate_tokens_ph, 0)\n# source_candidate_len_input = tf.expand_dims(source_candidate_len_ph,0)\n\n# source_query_tokens_ph = tf.string_split(source_query_tokens_ph, \" \")\n# source_query_len_ph = tf.string_split(source_query_len_ph, \" \")\n# source_candidate_tokens_ph = tf.string_split(source_candidate_tokens_ph, \" \")\n# source_candidate_len_ph = tf.string_split(source_candidate_len_ph, \" \")\n\nsource_query_tokens_input = tf.expand_dims(source_query_tokens_ph, 0)\nsource_query_len_input = tf.expand_dims(source_query_len_ph, 0)\nsource_candidate_tokens_input = tf.expand_dims(source_candidate_tokens_ph, 0)\nsource_candidate_len_input = tf.expand_dims(source_candidate_len_ph, 0)\n\nsource_query_tokens_input = tf.string_split(source_query_tokens_input)\nsource_query_tokens_input = tf.sparse_tensor_to_dense(source_query_tokens_input, default_value=\"\")\n# source_query_len_input = tf.string_split(source_query_len_input)\nsource_candidate_tokens_input = tf.string_split(source_candidate_tokens_input)\nsource_candidate_tokens_input = tf.sparse_tensor_to_dense(source_candidate_tokens_input, default_value=\"\")\n# source_candidate_len_input = tf.string_split(source_candidate_len_input)\n\nmodel(\n features={\n # \"source_tokens\": source_query_tokens_ph,\n # \"source_len\": source_query_len_ph,\n # \"source_candidate_tokens\": source_candidate_tokens_ph,\n # \"source_candidate_len\": source_candidate_len_ph\n\n # \"source_tokens\": [source_query_tokens_ph],\n # \"source_len\": [source_query_len_ph],\n # \"source_candidate_tokens\": [source_candidate_tokens_ph],\n # \"source_candidate_len\": [source_candidate_len_ph]\n\n \"source_tokens\": source_query_tokens_input,\n \"source_len\": source_query_len_input,\n \"source_candidate_tokens\": source_candidate_tokens_input,\n \"source_candidate_len\": source_candidate_len_input\n },\n labels=None,\n params={\n \"vocab_source_query\": \"dataset/fin_qa/train/vocab.sources.txt\",\n \"vocab_source_candidate\": \"dataset/fin_qa/train/vocab.sources_candidate.txt\",\n \"vocab_target\": \"dataset/fin_qa/train/vocab.targets.txt\"\n }\n)\n\nsaver = tf.train.Saver()\n# _predictions = graph_utils.get_dict_from_collection(\"predictions\")\n\ndef _session_init_op(_scaffold, sess):\n saver.restore(sess, checkpoint_path)\n tf.logging.info(\"Restored model from %s\", checkpoint_path)\n\nscaffold = tf.train.Scaffold(init_fn=_session_init_op)\nsession_creator = tf.train.ChiefSessionCreator(scaffold=scaffold)\n\n\ndef _tokens_to_str(tokens):\n return \" \".join(tokens).split(\"SEQUENCE_END\")[0].strip()\n\n# A hacky way to retrieve prediction result from the task hook...\nprediction_dict = {}\ndef _save_prediction_to_dict(source_tokens, predicted_tokens):\n prediction_dict[_tokens_to_str(source_tokens)] = _tokens_to_str(predicted_tokens)\n\n# print(\"create session\")\n# sess = tf.train.MonitoredSession(\n# session_creator=session_creator,\n# hooks=[DecodeOnce({}, callback_func=_save_prediction_to_dict)])\n\n_predictions = graph_utils.get_dict_from_collection(\"predictions\")\nfetches = {}\nfetches[\"predicted_tokens\"] = _predictions[\"predicted_tokens\"]\nfetches[\"predicted_ids\"] = _predictions[\"predicted_ids\"]\nfetches[\"features.source_tokens\"] = _predictions[\"features.source_tokens\"]\nfetches[\"features.source_candidate_tokens\"] = _predictions[\"features.source_candidate_tokens\"]\n#fetches[\"beam_parent_ids\"] = _predictions[\"beam_search_output.beam_parent_ids\"]\ntf.train.SessionRunArgs(fetches)\nsess = tf.Session()\nsess.run([tf.global_variables_initializer(), tf.local_variables_initializer(), tf.tables_initializer()])\nsaver.restore(sess, checkpoint_path)\n\nprint(\"start to export model:\")\nsaved_model_path = \"fin_biseq2seq_model\"\nif os.path.exists(saved_model_path):\n print(\"removing old saved_model:\" + saved_model_path)\n shutil.rmtree(saved_model_path)\nbuilder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)\n# Relevant change to the linked example is here!\nbuilder.add_meta_graph_and_variables(sess, [\"fin_biseq2seq\"], legacy_init_op=tf.tables_initializer())\nbuilder.save()\nprint(\"finish\")\n\n# The main API exposed\ndef query_once(source_tokens):\n tf.reset_default_graph()\n source_tokens = source_tokens.split() + [\"SEQUENCE_END\"]\n sess.run([], {\n source_query_tokens_ph: [source_tokens],\n source_query_len_ph: [len(source_tokens)],\n source_candidate_tokens_ph: [source_tokens],\n source_candidate_len_ph: [len(source_tokens)]\n })\n return prediction_dict.pop(_tokens_to_str(source_tokens))\n\ndef query_biseq2seq_once(source_query_tokens, source_candidate_tokens):\n tf.reset_default_graph()\n source_query_tokens_temp = source_query_tokens.split() + [\"SEQUENCE_END\"]\n source_query_len = len(source_query_tokens_temp)\n if SEQUENCE_LEN_MAX > source_query_len:\n source_query_tokens_temp += [\"SEQUENCE_END\"] * (SEQUENCE_LEN_MAX - source_query_len)\n source_query_tokens = ' '.join(source_query_tokens_temp)\n source_candidate_tokens_temp = source_candidate_tokens.split() + [\"SEQUENCE_END\"]\n source_candidate_len = len(source_candidate_tokens_temp)\n if SEQUENCE_LEN_MAX > source_candidate_len:\n source_candidate_tokens_temp += [\"SEQUENCE_END\"] * (SEQUENCE_LEN_MAX - source_candidate_len)\n source_candidate_tokens = ' '.join(source_candidate_tokens_temp)\n\n # source_query_tokens = source_query_tokens.split() + [\"SEQUENCE_END\"]\n # source_query_len = len(source_query_tokens)\n # source_candidate_tokens = source_candidate_tokens.split() + [\"SEQUENCE_END\"]\n # source_candidate_len = len(source_candidate_tokens)\n # slen = max(source_query_len, source_candidate_len)\n # if SEQUENCE_LEN_MAX > source_query_len:\n # source_query_tokens += [\"SEQUENCE_END\"] * (SEQUENCE_LEN_MAX - source_query_len)\n # if SEQUENCE_LEN_MAX > source_candidate_len:\n # source_candidate_tokens += [\"SEQUENCE_END\"] * (SEQUENCE_LEN_MAX - source_candidate_len)\n\n # source_query_tokens += \"SEQUENCE_END\"\n source_len = len(source_candidate_tokens.split())\n predictions, = sess.run([fetches], {\n # source_query_tokens_ph: [source_query_tokens],\n # source_query_len_ph: [slen],\n # source_candidate_tokens_ph: [source_candidate_tokens],\n # source_candidate_len_ph: [slen]\n source_query_tokens_ph: source_query_tokens,\n source_query_len_ph: source_len,\n source_candidate_tokens_ph: source_candidate_tokens,\n source_candidate_len_ph: source_len\n })\n # key = list(source_query_tokens) + [\"#\"] + list(source_candidate_tokens)\n # return prediction_dict.pop(_tokens_to_str(key))\n # return predictions\n print(predictions[\"predicted_tokens\"])\n print(\"predicted_ids:\")\n print(predictions[\"predicted_ids\"])\n print(\"beam_parent_ids:\")\n print(predictions[\"beam_parent_ids\"])\n predicted_tokens = predictions[\"predicted_tokens\"]\n if np.ndim(predicted_tokens) == 3:\n predicted_tokens = predicted_tokens[:, :, 0]\n elif np.ndim(predicted_tokens) == 2:\n predicted_tokens = predicted_tokens[:, 0]\n predicted_tokens = [b.decode(\"UTF-8\") for b in predicted_tokens[0]]\n predicted = ' '.join(predicted_tokens).split(\"SEQUENCE_END\")[0]\n predicted = ''.join(predicted.split())\n return predicted\n\ndef gather_tree(values, parents):\n \"\"\"Gathers path through a tree backwards from the leave nodes. Used\n to reconstruct beams given their parents.\"\"\"\n beam_length = values.shape[0]\n num_beams = values.shape[1]\n res = np.zeros_like(values)\n res[-1, :] = values[-1, :]\n for beam_id in range(num_beams):\n parent = parents[-1][beam_id]\n for level in reversed(range(beam_length - 1)):\n res[level, beam_id] = values[level][parent]\n parent = parents[level][parent]\n return np.array(res).astype(values.dtype)\n\n#if __name__ == \"__main__\":\n# # current prediction time ~20ms\n# print(\"----------------\")\n# os.chdir(\"dataset/fin_qa/test\")\n# with codecs.open(\"sources_query.txt\", encoding=\"utf-8\") as fiq, codecs.open(\"sources_candidate.txt\", encoding=\"utf-8\") as fic:\n# for cnt,query in enumerate(fiq):\n# if cnt > 0:\n# break\n# candidate = fic.readline().strip()\n# candidate = '账单 制 白条 还款 仅 支持 储蓄卡 ; 订单 制 白条 还款 支持 储蓄卡 、 部分 信用卡 。 具体 支持 银行 均 以 页面 显示 为准'\n# query = query.strip()\n# query = '为什么 小金库 能 还 白条 , 其他 信用卡 还 不了 ?'\n# # query = '白条 服务费 在 哪里 开发票 ? SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END SEQUENCE_END'\n# query = '白条 服务费 在 哪里 开发票 ?'\n# # candidate = '被 保险人 和 车主 必须 为 同一人 、 申请人 必须 为 车主 才 可 申请 SEQUENCE_END'\n# candidate = '被 保险人 和 车主 必须 为 同一人 、 申请人 必须 为 车主 才 可 申请'\n# predict = query_biseq2seq_once(query, candidate)\n# # predict = query_biseq2seq_once(\"运营商 服务 密码 是 多少\", \"手机 在 获取 通信 运营 公司 服务 时需 提供 的 身份 凭证 , 如 要 了解 更 多 请 咨询 运营商'\")\n# # predict = query_biseq2seq_once(query, candidate)\n# print(predict)\n\n","sub_path":"export_saved_model.py","file_name":"export_saved_model.py","file_ext":"py","file_size_in_byte":12799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"316289866","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTODO:\n- def reordering ala syndi\n- more efficient (range-aware) deduper\n\n@singledispatch.partial\ndef contains(seq, item):\n raise NotImplementedError()\n\n@contains.register(compose)\ndef _(seq, item):\n return any(item in c for c in seq.arg.children)\n\n...\n\n@singledispatch.partial\ndef algorithmic_complexity(seq);\n raise NotImplementedError()\n\n...\n\n def __contains__(self, item):\n return contains(self, item)\n\"\"\"\nfrom __future__ import absolute_import\n\nimport collections\nimport functools\nimport itertools\nimport random\nimport sys\nimport time\n\nfrom . import Nonlocal\nfrom . import abstract\nfrom . import build_ordereddict_to_list_by_key\nfrom . import cached_property\nfrom . import callables\nfrom . import check\nfrom . import six\nfrom .newable import ROOT_NAMESPACE\nfrom .newable import newable\n\n\nmap_ = map\nfilter_ = filter\n\n\n_BUILDER_FNS = []\n\n\n@abstract\nclass IterableTransform(object):\n\n @abstract.method\n def __call__(self, items): # -> items\n raise NotImplementedError()\n\n def __pos__(self):\n return compose(self, eager)\n\n def __neg__(self):\n return compose(self, lazy)\n\n def __invert__(self):\n return compose(self, flatten)\n\n def __and__(self, other):\n return chain(self, other)\n\n def __rand__(self, other):\n return chain(other, self)\n\n def __or__(self, other):\n return compose(self, other)\n\n def __ror__(self, other):\n return compose(other, self)\n\n def __mul__(self, other):\n return compose(self, map(other))\n\n def __div__(self, other):\n return compose(self, filter(other))\n\n\ndef alias(*bases):\n return callables.alias(*(bases + (IterableTransform,)))\n\n\ndef constructor(*bases, **kwargs):\n builder = kwargs.pop('builder', False)\n if kwargs:\n raise TypeError(kwargs)\n\n def inner(fn):\n fn = callables.constructor(*(bases + (IterableTransform,)))(fn)\n if builder:\n _BUILDER_FNS.append(fn)\n return fn\n return inner\n\n\ndef void(seq, exception=lambda item: RuntimeError('Unreachable', item)):\n for item in seq:\n raise exception(item)\n\n\ndef ilen(seq):\n c = 0\n for _ in seq:\n c += 1\n return c\n\n\ndef with_(seq):\n with seq:\n for item in seq:\n yield item\n\n\n@alias()\ndef flatten(items):\n return itertools.chain.from_iterable(items)\n\n\n@constructor(builder=True)\ndef compose(*children):\n all(check.is_callable(child) for child in children)\n children = list(flatten(child.args if isinstance(child, compose) else [child]\n for child in children))\n\n def run(items):\n for child in children:\n items = child(items)\n return items\n return run\n\n\n@alias()\ndef nop(items):\n return items\n\n\n@alias()\ndef lazy(items):\n for item in items:\n yield item\n\n\n@alias()\ndef eager(items):\n return items if isinstance(items, (list, tuple)) else list(items)\n\n\n@alias()\ndef discard(items):\n for item in items:\n pass\n return\n yield\n\n\n@constructor(builder=True)\ndef apply(function):\n check.is_callable(function)\n\n def run(items):\n for item in items:\n function(item)\n yield item\n\n return run\n\n\n@constructor(builder=True)\ndef map(function):\n return functools.partial(six.moves.map, check.is_callable(function))\n\n\n@constructor(builder=True)\ndef filter(predicate):\n return functools.partial(six.moves.filter, check.is_callable(predicate))\n\n\n@constructor(builder=True)\ndef filter_false(predicate):\n return functools.partial(six.moves.filterfalse, check.is_callable(predicate))\n\n\n@constructor()\ndef type_filter(type):\n return filter(lambda obj: isinstance(obj, type))\n\n\n@constructor()\ndef type_remove(type):\n return filter(lambda obj: not isinstance(obj, type))\n\n\n@constructor(builder=True)\ndef flat_map(function):\n return compose(map(function), flatten)\n\n\n@constructor()\ndef unreachable(exception=lambda item: RuntimeError('Unreachable', item)):\n def run(items):\n for item in items:\n raise exception(item)\n return\n yield\n return run\n\n\n@constructor()\ndef chain(*children):\n all(check.is_callable(child) for child in children)\n\n def run(items):\n for child in children:\n for item in child(items):\n yield item\n\n return run\n\n\n@constructor()\ndef permutate(*children):\n all(check.is_callable(child) for child in children)\n\n def run(items):\n for permutation in itertools.permutations(children):\n for item in compose(*permutation)(items):\n yield item\n\n return run\n\n\n@constructor()\ndef interleave(*children):\n all(check.is_callable(child) for child in children)\n\n def run(items):\n for item in items:\n for child in children:\n yield child((item,))\n\n return run\n\n\n@constructor()\ndef broadcast(*children):\n all(check.is_callable(child) for child in children)\n return compose(interleave(*children), flatten)\n\n\n@constructor(builder=True)\ndef guard(predicate, exception_type=ValueError):\n def run(items):\n for item in items:\n if not predicate(item):\n raise exception_type(item)\n yield item\n return run\n\n\n@constructor()\ndef type_guard(type, exception_type=TypeError):\n return guard(lambda item: isinstance(item, type), exception_type=exception_type)\n\n\n@constructor()\ndef chunk(capacity, weigh=callables.const(1)):\n check.is_callable(weigh)\n\n def run(items):\n chunk_weight = 0\n chunk = []\n for item in items:\n item_weight = weigh(item)\n if chunk_weight + item_weight > capacity:\n yield chunk\n chunk = []\n chunk_weight = 0\n chunk.append(item)\n chunk_weight += item_weight\n if chunk:\n yield chunk\n\n return run\n\n\n@constructor(builder=True)\ndef route(router):\n check.is_callable(router)\n\n def run(items):\n for target, group in itertools.groupby(items, router):\n if target is None:\n yield group\n else:\n yield target(group)\n\n return run\n\n\n@constructor(builder=True)\ndef sorted_route(router, target_order=()):\n check.is_callable(router)\n\n def run(items):\n item_lists_by_target = build_ordereddict_to_list_by_key(items, router)\n for target in target_order:\n try:\n target_items = item_lists_by_target.pop(target)\n except KeyError:\n continue\n if target is None:\n yield target_items\n else:\n yield target(target_items)\n for target, target_items in item_lists_by_target.items():\n if target is None:\n yield target_items\n else:\n yield target(target_items)\n\n return run\n\n\ndef _unpack_pairs(items):\n check.arg(len(items) % 2 == 0)\n return items[::2], items[1::2]\n\n\n@constructor(builder=True)\ndef match(*predicates_and_targets, **kwargs):\n if not kwargs.pop('strict', False):\n predicates_and_targets += (callables.const(True), None)\n predicates, targets = _unpack_pairs(predicates_and_targets)\n predicate_target_pairs = list(zip(predicates, targets))\n check.arg(all(callable(predicate) for predicate in predicates))\n check.arg(all(callable(target) or target is None for target in targets))\n\n def router(item):\n for route_predicate, target in predicate_target_pairs:\n if route_predicate(item):\n return target\n raise ValueError(item)\n\n if kwargs.pop('sorted', False):\n kwargs.setdefault('target_order', targets)\n route_ = sorted_route\n else:\n route_ = route\n return route_(router, **kwargs)\n\n\n@constructor(builder=True)\ndef type_match(*types_and_targets, **kwargs):\n target_types, targets = _unpack_pairs(types_and_targets)\n check.arg(all(isinstance(o, type) or (isinstance(o, tuple) and all(isinstance(oi, type) for oi in o))\n for o in target_types))\n\n def predicate(target_type, request):\n return isinstance(request, target_type)\n\n predicates = [functools.partial(predicate, target_type) for target_type in target_types]\n return match(*list(flatten(zip(predicates, targets))), **kwargs)\n\n\n@constructor(builder=True)\ndef flat_match(*args, **kwargs):\n return compose(match(*args, **kwargs), flatten)\n\n\n@constructor(builder=True)\ndef flat_type_match(*args, **kwargs):\n return compose(type_match(*args, **kwargs), flatten)\n\n\n@constructor(builder=True)\ndef map_type(type, fn):\n def run(items):\n for item in items:\n if isinstance(item, type):\n yield fn(item)\n else:\n yield item\n return run\n\n\n@constructor(builder=True)\ndef flat_map_type(type, fn):\n def run(items):\n for item in items:\n if isinstance(item, type):\n for out in fn(item):\n yield out\n else:\n yield item\n return run\n\n\n@constructor(builder=True)\ndef apply_type(type, fn):\n def run(items):\n for item in items:\n if isinstance(item, type):\n fn(item)\n yield item\n return run\n\n\n@constructor(builder=True)\ndef map_types(*types_and_fns):\n types, fns = _unpack_pairs(types_and_fns)\n return compose(*[map_type(type, fn) for type, fn in zip(types, fns)])\n\n\n@constructor(builder=True)\ndef flat_map_types(*types_and_fns):\n types, fns = _unpack_pairs(types_and_fns)\n return compose(*[flat_map_type(type, fn) for type, fn in zip(types, fns)])\n\n\n@constructor(builder=True)\ndef apply_types(*types_and_fns):\n types, fns = _unpack_pairs(types_and_fns)\n return compose(*[apply_type(type, fn) for type, fn in zip(types, fns)])\n\n\n@constructor()\ndef context_managed(wrapped, fn):\n def run(in_items):\n with fn(in_items):\n for out_item in wrapped(in_items):\n yield out_item\n return run\n\n\n@constructor(builder=True)\ndef chunked_flat_map(function, capacity, **kwargs):\n return compose(chunk(capacity, **kwargs), map(function), flatten)\n\n\n@constructor(builder=True)\ndef map_randomly(function, chance):\n def run(item):\n if random.random() < chance:\n item = function(item)\n return item\n return map(run)\n\n\n@constructor(builder=True)\ndef map_periodically(function, interval):\n nonlocals = Nonlocal()\n nonlocals.last_run_time = None\n\n def run(item):\n if nonlocals.last_run_time is None:\n nonlocals.last_run_time = time.time()\n return item\n time_since_last_run = time.time() - nonlocals.last_run_time\n if time_since_last_run < interval:\n return item\n item = function(item)\n nonlocals.last_run_time = time.time()\n return item\n\n return map(run)\n\n\n@constructor(builder=True)\ndef map_every_nth(function, n):\n nonlocals = Nonlocal()\n nonlocals.remaining = n\n\n def run(item):\n nonlocals.remaining -= 1\n if nonlocals.remaining < 1:\n nonlocals.remaining = n\n item = function(item)\n return item\n\n return map(run)\n\n\n@constructor(builder=True)\ndef apply_randomly(function, chance):\n def inner(item):\n function(item)\n return item\n return map_randomly(inner, chance)\n\n\n@constructor(builder=True)\ndef apply_periodically(function, interval):\n def inner(item):\n function(item)\n return item\n return map_periodically(inner, interval)\n\n\n@constructor(builder=True)\ndef apply_every_nth(function, n):\n def inner(item):\n function(item)\n return item\n return map_every_nth(inner, n)\n\n\n@constructor()\ndef deduplicate(keys=callables.entuple, verbose=False):\n \"\"\"Deduplicates items where keys is a callable returning for a given item a tuple of values by\n which the item is to be deduplicated. Implemented such that the final item in the tuple will be\n placed in a set, not a dict, for memory efficiency - as such the highest cardinality key component\n should be last in the key tuple.\n\n When verbose is not truthy simply yields deduplicated items. When verbose is truthy yields for\n each item a dict of the following keys:\n 'num_seen' - the number of deduplicated items yielded\n 'num_deduplicated' - the number of duplicate items not yielded\n 'item' - the item\n 'item_keys' - the keys by which the item was deduplicated\n 'output' - an empty tuple if the item was a duplicate, otherwise a tuple containing the item\n \"\"\"\n\n nonlocals = Nonlocal()\n nonlocals.num_seen = 0\n nonlocals.num_deduplicated = 0\n nonlocals.seen = {}\n\n def inner(item):\n item_keys = keys(item)\n check.state(item_keys, message='Keys must not be empty')\n item_keys = (None,) + item_keys\n dst = nonlocals.seen\n\n for item_key in item_keys[:-3]:\n check.state(isinstance(dst, dict), message='Keys must always be the same length.')\n try:\n dst = dst[item_key]\n except KeyError:\n next_dst = {}\n dst[item_key] = next_dst\n dst = next_dst\n\n item_key = item_keys[-2]\n try:\n dst = dst[item_key]\n except KeyError:\n next_dst = set()\n dst[item_key] = next_dst\n dst = next_dst\n\n check.state(isinstance(dst, set), message='Keys must always be the same length.')\n item_key = item_keys[-1]\n if item_key in dst:\n output = ()\n nonlocals.num_deduplicated += 1\n else:\n dst.add(item_key)\n output = (item,)\n nonlocals.num_seen += 1\n\n return {\n 'num_seen': nonlocals.num_seen,\n 'num_deduplicated': nonlocals.num_deduplicated,\n 'item': item,\n 'item_keys': item_keys[1:],\n 'output': output,\n }\n\n if verbose:\n return map(inner)\n else:\n return compose(\n map(inner),\n map(lambda dct: dct['output']),\n flatten)\n\n\n_BuilderMethod = collections.namedtuple('_BuilderAtt', 'fn args kwargs')\n_BUILDER_METHOD_ATTR = '__iterable_transform_builder_method__'\n\n\ndef builder():\n def inner(cls):\n if '_request_filter' in cls.__dict__:\n raise AttributeError('_request_filter')\n\n methods = []\n seen = set()\n for scls in cls.__mro__:\n try:\n scls_methods = getattr(scls, _BUILDER_METHOD_ATTR)\n except AttributeError:\n continue\n for name, method in scls_methods:\n if name not in seen:\n seen.add(name)\n methods.append((name, method))\n if not methods:\n raise TypeError('Must have at least one builder method')\n\n @cached_property\n def _request_filter(self):\n lst = []\n for name, method in methods:\n lst.append(method.fn(*(method.args + (getattr(self, name),)), **method.kwargs))\n return compose(*lst)\n cls._request_filter = _request_filter\n\n def __call__(self, *args, **kwargs):\n return self._request_filter(*args, **kwargs)\n # FIXME: allow overriding\n cls.__call__ = __call__\n\n return cls\n\n return inner\n\n\ndef _bind_builder(fn):\n def outer(*args, **kwargs):\n def inner(meth):\n cls_dct = sys._getframe(1).f_locals\n methods = cls_dct.setdefault(_BUILDER_METHOD_ATTR, [])\n if meth.__name__ in methods:\n raise AttributeError(meth.__name__)\n methods.append((meth.__name__, _BuilderMethod(fn, args, kwargs)))\n return meth\n return inner\n setattr(builder, fn.__name__, outer)\n\n\nfor _fn in _BUILDER_FNS:\n _bind_builder(_fn)\n\n\n@newable(contravariant=True, register=[[ROOT_NAMESPACE, 'composite_iterable_transform'],\n [IterableTransform, 'composite']])\nclass Composite(IterableTransform):\n\n children = newable.arg((newable.ref(newable.Self(IterableTransform)),), coerce_=tuple)\n\n def __init__(self, *args, **kwargs):\n self._init_args(*args, **kwargs)\n super(Composite, self).__init__()\n self._request_filter = compose(*self.children)\n self.__call__ = self._request_filter.__call__\n\n def __call__(self, *args, **kwargs):\n return self._request_filter(*args, **kwargs)\n","sub_path":"iterable_transforms.py","file_name":"iterable_transforms.py","file_ext":"py","file_size_in_byte":16561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"502644524","text":"import re\nfrom datetime import date\n\nimport discord\n\nfrom utils.i18n import _\n\nSR = \"<:sr:639897739920146437>\"\n\nROLES = {\n \"tank\": \"<:tank:645784573141319722>\",\n \"damage\": \"<:damage:645784543093325824>\",\n \"support\": \"<:support:645784563322191902>\",\n}\n\n\nclass PlayerException(Exception):\n \"\"\"Base exception class for player.py.\"\"\"\n\n pass\n\n\nclass NoStatistics(PlayerException):\n \"\"\"Exception raised when a player has no statistics to display.\"\"\"\n\n def __init__(self):\n super().__init__(\n _(\"This profile has no quick play nor competitive statistics to display.\")\n )\n\n\nclass NoHeroStatistics(PlayerException):\n \"\"\"Exception raised when a player has no quick play nor competitive stats for a given hero.\"\"\"\n\n def __init__(self, player, hero):\n super().__init__(\n _(\n f\"**{player}** has no quick play nor competitive statistics for **{hero}** to display.\"\n )\n )\n\n\nclass Player:\n\n __slots__ = (\"data\", \"platform\", \"username\", \"pages\")\n\n def __init__(self, data: dict, *, platform: str, username: str):\n self.data = data\n self.platform = platform\n self.username = username\n\n self.pages = []\n\n def __str__(self):\n return self.data[\"name\"]\n\n @property\n def avatar(self):\n return self.data[\"icon\"]\n\n @property\n def level_icon(self):\n return self.data[\"levelIcon\"]\n\n @property\n def is_private(self):\n return self.data[\"private\"]\n\n @property\n def has_statistics(self):\n return (\n self.data[\"quickPlayStats\"][\"careerStats\"]\n or self.data[\"competitiveStats\"][\"careerStats\"]\n )\n\n @staticmethod\n def add_space(key):\n \"\"\"From camel case to title (testTest -> Test Test).\"\"\"\n return (\n re.sub(\"([a-z])([A-Z])\", r\"\\g<1> \\g<2>\", key)\n .replace(\" Avg Per10Min\", \"\")\n .replace(\" Most In Game\", \"\")\n .title()\n )\n\n @staticmethod\n def get_rating_icon(rating):\n if rating > 0 and rating < 1500:\n return \"<:bronze:632281015863214096>\"\n elif rating >= 1500 and rating < 2000:\n return \"<:silver:632281054211997718>\"\n elif rating >= 2000 and rating < 2500:\n return \"<:gold:632281064596832278>\"\n elif rating >= 2500 and rating < 3000:\n return \"<:platinum:632281092875091998>\"\n elif rating >= 3000 and rating < 3500:\n return \"<:diamond:632281105571119105>\"\n elif rating >= 3500 and rating < 4000:\n return \"<:master:632281117394993163>\"\n else:\n return \"<:grandmaster:632281128966946826>\"\n\n def format_key(self, key):\n if key == \"best\":\n return key.capitalize() + \" (Most in game)\"\n elif key == \"average\":\n return key.capitalize() + \" (per 10 minutes)\"\n else:\n return self.add_space(key)\n\n async def save_ratings(self, ctx, *, profile_id, **kwargs):\n tank = kwargs.get(\"tank\", 0)\n damage = kwargs.get(\"damage\", 0)\n support = kwargs.get(\"support\", 0)\n\n query = \"\"\"SELECT tank, damage, support\n FROM rating\n INNER JOIN profile\n ON profile.id = rating.profile_id\n WHERE profile.id = $1\n AND rating.date = $2;\n \"\"\"\n\n requested_at = date.today()\n roles = await ctx.bot.pool.fetch(query, profile_id, requested_at)\n\n if roles:\n # Assuming a user uses `-profile rating` multiple times in the same day,\n # we don't want duplicate ratings. If only 1 rating differs, then we\n # insert the new ratings into the database.\n all_equals = False\n for t, d, s in roles:\n if t == tank and d == damage and s == support:\n all_equals = True\n\n if not roles or not all_equals:\n query = \"INSERT INTO rating(tank, damage, support, profile_id) VALUES($1, $2, $3, $4);\"\n await ctx.bot.pool.execute(query, tank, damage, support, profile_id)\n\n def resolve_ratings(self):\n if not self.data[\"ratings\"]:\n return None\n ratings = {}\n for key, value in self.data[\"ratings\"].items():\n ratings[key.lower()] = value[\"level\"]\n return ratings\n\n async def get_ratings(self, ctx, *, save=False, profile_id=None):\n embed = discord.Embed(color=ctx.author.color)\n embed.set_author(name=str(self), icon_url=self.avatar)\n\n ratings = self.resolve_ratings()\n\n if not ratings:\n embed.description = _(\"This profile is unranked.\")\n return embed\n\n for key, value in ratings.items():\n embed.add_field(\n name=f\"{ROLES.get(key)} **{key.upper()}**\",\n value=f\"{self.get_rating_icon(value)} **{value}**{SR}\",\n )\n embed.set_footer(\n text=_(\"Avarage: {average}\").format(average=self.data.get(\"rating\")),\n icon_url=self.data.get(\"ratingIcon\"),\n )\n\n if save:\n await self.save_ratings(ctx, profile_id=profile_id, **ratings)\n\n return embed\n\n def resolve_statistics(self, hero=\"allHeroes\"):\n if not self.has_statistics:\n raise NoStatistics()\n\n # quickplay statistics\n q = self.data.get(\"quickPlayStats\").get(\"careerStats\").get(hero) or {}\n # competitive statistics\n c = self.data.get(\"competitiveStats\").get(\"careerStats\").get(hero) or {}\n\n if hero != \"allHeroes\" and not q and not c:\n raise NoHeroStatistics(str(self), hero)\n\n keys = list({*q, *c})\n keys.sort()\n\n for i, key in enumerate(keys):\n if not q.get(key) and not c.get(key):\n del keys[i]\n\n return keys, q, c\n\n def format_statistics(self, embed, key, quickplay, competitive):\n if quickplay and quickplay[key]:\n q_t = \"\\n\".join(f\"{k}: **{v}**\" for k, v in quickplay[key].items())\n embed.add_field(name=_(\"Quickplay\"), value=self.add_space(q_t))\n if competitive and competitive[key]:\n c_t = \"\\n\".join(f\"{k}: **{v}**\" for k, v in competitive[key].items())\n embed.add_field(name=_(\"Competitive\"), value=self.add_space(c_t))\n\n def get_statistics(self, ctx):\n keys, quickplay, competitive = self.resolve_statistics()\n\n for i, key in enumerate(keys, start=1):\n embed = discord.Embed(color=ctx.author.color)\n embed.title = self.format_key(key)\n embed.set_author(name=str(self), icon_url=self.avatar)\n embed.set_thumbnail(url=self.level_icon)\n embed.set_footer(\n text=_(\"Page {current}/{total}\").format(current=i, total=len(keys))\n )\n self.format_statistics(embed, key, quickplay, competitive)\n self.pages.append(embed)\n return self.pages\n\n def get_hero(self, ctx, hero):\n keys, quickplay, competitive = self.resolve_statistics(hero)\n\n for i, key in enumerate(keys, start=1):\n embed = discord.Embed(color=ctx.author.color)\n embed.title = self.format_key(key)\n embed.set_author(name=str(self), icon_url=self.avatar)\n embed.set_thumbnail(url=ctx.bot.config.hero_url.format(hero.lower()))\n embed.set_footer(\n text=_(\"Page {current}/{total}\").format(current=i, total=len(keys))\n )\n self.format_statistics(embed, key, quickplay, competitive)\n self.pages.append(embed)\n return self.pages\n\n def private(self):\n embed = discord.Embed(color=discord.Color.red())\n embed.title = _(\"This profile is set to private\")\n embed.description = _(\n \"Profiles are set to private by default.\"\n \" You can modify this setting in Overwatch under `Options - Social`.\"\n \" Please note that these changes may take effect after approximately 30 minutes.\"\n )\n embed.set_author(name=str(self), icon_url=self.avatar)\n return embed\n","sub_path":"utils/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":8158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"14821090","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pytest\nimport selenium\nfrom selenium import webdriver\nimport time\n\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.touch_actions import TouchActions\n\nfrom zhiYiLianDanLuWeb.test_base import Test_base\n\n\nclass TestLogin(Test_base):\n\n\n @pytest.mark.skip\n def test_selenium(self):\n self.driver.get(\"https://www.huo1818.com/login\")\n action=ActionChains(self.driver)\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div[1]/div[2]/div[2]/div[1]/div[1]/input').send_keys('13107700873')\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div[1]/div[2]/div[2]/div[1]/div[2]/input').send_keys(\n '123456')\n click_xpath=self.driver.find_element_by_xpath('//*[@id=\"app\"]/div[1]/div[2]/div[2]/span[2]/button')\n action.click(click_xpath)\n # time.sleep(1)\n # def wait(x):\n # return 1>0\n # WebDriverWait(self.driver,10).until(wait())\n # WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(By.xPath,\"xxxxx\"))\n assert \"炼丹炉-监控台-数据概览\" in self.driver.title\n\n @pytest.mark.skip\n def test_touchaction(self):\n self.driver.get(\"https://www.baidu.com\")\n touchaction=TouchActions(self.driver)\n el = self.driver.find_element_by_id(\"kw\")\n el_search = self.driver.find_element_by_id(\"su\")\n el.send_keys('健身')\n el_search.click()\n touchaction.scroll_from_element(el,0,10000).perform()\n time.sleep(5)\n\n\n @pytest.mark.skip\n def test_switch_windows(self):\n self.driver.get(\"https://www.baidu.com\")\n self.driver.find_element_by_link_text(\"登录\").click()\n # print(self.driver.current_window_handle)\n self.driver.find_element_by_link_text(\"立即注册\").click()\n # print(self.driver.current_window_handle)\n # print(self.driver.window_handles)\n windows=self.driver.window_handles\n #切换窗口\n self.driver.switch_to.window(windows[-1])\n self.driver.switch_to.window(windows[0])\n\n @pytest.mark.skip\n def test_switch_frame(self):\n self.driver.get(\"https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\")\n self.driver.switch_to.frame(\"iframeResult\")\n print(self.driver.find_element_by_id(\"draggable\").text)\n self.driver.switch_to_default_content()\n\n @pytest.mark.skip\n def test_js_scroll(self):\n self.driver.get(\"https://testerhome.com/\")\n self.driver.execute_script(\"document.documentElement.scrollTop=1000\")\n time.sleep(1)\n\n def test_js_attribute(self):\n self.driver.get(\"https://www.12306.cn/index/\")\n self.driver.execute_script(\"a=document.getElementById('train_date');a.removeAttribute('readonly');a.value='2020-12-30'\")\n time.sleep(2)\n print(self.driver.execute_script(\"return document.getElementById('train_date).value\"))\n\n\n\n\n\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"zhiYiLianDanLuWeb/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"290023206","text":"\"\"\"\n Tench Cholnoky\n Radical Software, Fall 2021\n Project 1\n Sept 23, 2021\n python3\n\"\"\"\n\nimport tweepy\nimport random\n\n#import twitter bot authorizations\nfrom authorization_tokens import *\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\nmessage = \"\"\n\napi = tweepy.API(auth)\nmentions = api.mentions_timeline()\nmention_tweet = random.choice(mentions)\n\n#splits the words into a list\nmention_tweet_words = mention_tweet.text.split()\n\n\n#define the function of list 2 string\ndef list_to_string(mention_tweet_words):\n str1 = \"\"\n return (str1.join(mention_tweet_words))\n\n#function of list turned into string\ntweet_string = list_to_string(mention_tweet_words)\n\n#find the question mark and make a question test variable\nquestion_test = tweet_string.find(\"?\")\n\n#if a question mark is in the string it will return its position, which will always\n#be higher than 1. If there is no question mark, the find command will return a -1\nif question_test > -1:\n answer_list = [\"~yes~\", \"~no~\", \"~maybe~\", \"~at some point soon~\", \"~try again~\",\n \"~outlook good~\",\"~doubtful~\", \"~it is certain~\", \"~my sources say no~\"]\n answer = random.choice(answer_list)\n\n #basic formatting\n print(\"I responded to:\")\n print(\"' \" + mention_tweet.text + \" '\")\n print(\"\")\n message = (\" Thank you for your question, my answer is... \" + answer)\n #add the @ to the mention\n message = \"@\" + mention_tweet.user.screen_name + message\n print(\"I tweeted:\")\n print(message)\n api.update_status(message, in_reply_to_status_id=mention_tweet.id)\n\nelse:\n#no question mark\n #basic formatting\n print(\"I responded to:\")\n print(\"' \" + mention_tweet.text + \" '\")\n print(\"\")\n\n message = (\" Please ask me a question\")\n #add the @ to the mention\n message = \"@\" + mention_tweet.user.screen_name + message\n api.update_status(message, in_reply_to_status_id=mention_tweet.id)\n print(\"I tweeted:\")\n print(message)\n","sub_path":"app/magic-8-bot.py","file_name":"magic-8-bot.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"418549454","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom itertools import izip\nimport unittest\nfrom gaepermission import inspector\nfrom tekton import router\n\n\nclass InspectorTests(unittest.TestCase):\n def setUp(self):\n router.package_base = 'web_stub'\n\n def test_web_paths_generator(self):\n generator = inspector.web_paths('web_stub')\n expected_paths = ['/pack_stub/stub/adm',\n '/pack_stub/stub/adm_or_manager',\n '/pack_stub/stub/manager',\n '/pack_stub/stub/sysowner',\n '/pack_stub',\n '/']\n self.assertListEqual(expected_paths, [t for t in generator])\n\n def test_web_paths_security_info(self):\n path_infos = inspector.web_paths_security_info('web_stub')\n expected_paths = ['/pack_stub/stub/adm',\n '/pack_stub/stub/adm_or_manager',\n '/pack_stub/stub/manager',\n '/pack_stub/stub/sysowner',\n '/pack_stub',\n '/']\n expected_groups = ['ADMIN', 'ADMIN, MANAGER', 'MANAGER', 'SYS_OWNER', 'Permission not Required',\n 'Login not Required']\n\n expected_csrf = [True, True, True, True, False, False]\n\n for exp_path_info, exp_path, exp_groups, exp_csrf in izip(path_infos, expected_paths, expected_groups,\n expected_csrf):\n self.assertEqual(exp_path, exp_path_info.path)\n self.assertEqual(exp_groups, exp_path_info.groups)\n self.assertEqual(exp_csrf, exp_path_info.csrf)\n\n def tearDown(self):\n router.package_base = 'web_stub'","sub_path":"test/inspector_tests.py","file_name":"inspector_tests.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"413623506","text":"# -*- coding:utf8 -*-\nfrom django.conf import settings\nfrom django.conf.urls.defaults import *\nfrom django.conf.urls.defaults import patterns, url\nfrom django.views.generic.simple import direct_to_template\n#from TripleMag.models import model\nfrom TripleMag.apps.stock.views import *\n\n\nurlpatterns = patterns('',\n #股票首页\n url(r'stock/$',index,name='stock_index'),\n #非定向购买股票\n url(r'stock/buy$',buy_stock, name = \"stock_buy_stock\"),\n #卖出股票\n url(r'stock/sell/$', sell_stock , name = \"stock_sell_stock\"),\n #实时刷新卖出池\n url(r'stock/get_selling_poll/$', get_selling_poll, name = \"get_selling_poll\"),\n #查看自己的股票来源\n url(r'stock/income_record/$', income_record,{'template_name':'stock/stock_record.html'}, name=\"stock_income_record\"),\n #查看自己的购票售出记录\n url(r'stock/stock_record/$',stock_record,{'template_name':'stock/stock_record.html','include_template':'includes/stock_record.html'},name=\"stock_stock_record\"),\n #查看自己的股票奖金记录\n url('stock/stock_bonus/$',stock_bonus,{'template_name':'stock/stock_record.html','include_template':'includes/stock_bonus.html'},name=\"stock_stock_bonus\"),\n #取消自己的股票\n url(r'stock/cancle/$',cancle_stock,name=\"cancle_stock\"),\n #定向购买\n url(r'stock/direct_buy/$',direct_stock_buy,name=\"direct_stock_buy\"),\n url(r'stock/del_session/$',del_session,name=\"del_session\"),\n)\n\n","sub_path":"TripleMag/apps/stock/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"35834722","text":"\n\n#calss header\nclass _ENCOUNTER():\n\tdef __init__(self,): \n\t\tself.name = \"ENCOUNTER\"\n\t\tself.definitions = [u'a meeting, especially one that happens by chance: ', u'an occasion when people have sex, usually with someone they have not met before', u'an occasion when two teams play against each other: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_encounter.py","file_name":"_encounter.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"565703193","text":"#!/usr/bin/env python\n\n# by: Kwabena W. Agyeman - kwagyeman@openmv.io\n\nimport argparse, multiprocessing, os, re, shutil, sys\n\nINT8 = False\n\nUINT8_MODEL_C_PATH = \"tensorflow/lite/micro/tools/make/downloads/person_model_grayscale/person_detect_model_data.cc\"\nUINT8_MODEL_H_PATH = \"tensorflow/lite/micro/examples/person_detection/person_detect_model_data.h\"\n\nINT8_MODEL_C_PATH = \"tensorflow/lite/micro/tools/make/downloads/person_model_int8/person_detect_model_data.cc\"\nINT8_MODEL_H_PATH = \"tensorflow/lite/micro/examples/person_detection_experimental/person_detect_model_data.h\"\n\nMODEL_C_PATH = INT8_MODEL_C_PATH if INT8 else UINT8_MODEL_C_PATH\nMODEL_H_PATH = INT8_MODEL_H_PATH if INT8 else UINT8_MODEL_H_PATH\n\ndef patch_files(dir_path):\n for dname, dirs, files in os.walk(dir_path):\n for fname in files:\n fpath = os.path.join(dname, fname)\n with open(fpath) as f:\n s = f.read()\n s = s.replace(\"fprintf\", \"(void)\")\n with open(fpath, \"w\") as f:\n f.write(s)\n\ndef generate(target, target_arch, __folder__, args, cpus, builddir, libdir, c_compile_flags, cxx_compile_flags):\n\n print(\"==============================\\n Building Target - \" + target + \"\\n==============================\")\n\n project_folder = \"tensorflow/tensorflow/lite/micro/tools/make/gen/openmvcam_\" + target_arch + \"/prj/person_detection\" + (\"_int8\" if INT8 else \"\") + \"/make\"\n\n if (not os.path.isdir(project_folder)) or (not args.skip_generation):\n if os.system(\"cd tensorflow\" +\n \" && make -f tensorflow/lite/micro/tools/make/Makefile -j\" + str(cpus) + \" TAGS=\\\"cmsis-nn\\\" TARGET=\\\"openmvcam\\\" TARGET_ARCH=\\\"\" + target_arch + \"\\\" generate_person_detection\" + (\"_int8\" if INT8 else \"\") + \"_make_project\"):\n sys.exit(\"Make Failed...\")\n\n if os.path.exists(os.path.join(builddir, target)):\n shutil.rmtree(os.path.join(builddir, target), ignore_errors = True)\n\n shutil.copytree(project_folder,\n os.path.join(builddir, target))\n\n shutil.copytree(\"libm\",\n os.path.join(builddir, target, \"libm\"))\n\n shutil.copytree(\"tensorflow/tensorflow/lite/micro/tools/make/downloads/kissfft/\",\n os.path.join(builddir, target, \"kissfft\"))\n\n shutil.copytree(\"tensorflow/tensorflow/lite/experimental/microfrontend\",\n os.path.join(builddir, target, \"microfrontend\"))\n\n shutil.copytree(\"tensorflow/tensorflow/lite/micro/examples/micro_speech/micro_features/\",\n os.path.join(builddir, target, \"micro_features\"))\n\n patch_files(os.path.join(builddir, target, \"kissfft\"))\n patch_files(os.path.join(builddir, target, \"microfrontend\"))\n patch_files(os.path.join(builddir, target, \"micro_features\"))\n\n SRCS = [\n \"SRCS :=\",\n \"libtf.cc\",\n \"libm/exp.c\",\n \"libm/floor.c\",\n \"libm/fmaxf.c\",\n \"libm/fminf.c\",\n \"libm/frexp.c\",\n \"libm/round.c\",\n \"libm/sqrt.c\",\n \"libm/scalbn.c\",\n \"libm/cos.c\",\n \"libm/__cos.c\",\n \"libm/sin.c\",\n \"libm/__sin.c\",\n \"libm/log1p.c\",\n \"libm/__rem_pio2.c\",\n \"libm/__rem_pio2_large.c\",\n \"kissfft/kiss_fft.c\",\n \"kissfft/tools/kiss_fftr.c\",\n \"microfrontend/lib/noise_reduction_io.c\",\n \"microfrontend/lib/filterbank_io.c\",\n \"microfrontend/lib/log_scale_util.c\",\n \"microfrontend/lib/fft_util.cc\",\n \"microfrontend/lib/log_lut.c\",\n \"microfrontend/lib/filterbank_util.c\",\n \"microfrontend/lib/frontend_memmap_generator.c\",\n \"microfrontend/lib/window.c\",\n \"microfrontend/lib/pcan_gain_control_util.c\",\n \"microfrontend/lib/frontend_io.c\",\n \"microfrontend/lib/frontend.c\",\n \"microfrontend/lib/window_util.c\",\n \"microfrontend/lib/fft.cc\",\n \"microfrontend/lib/log_scale_io.c\",\n \"microfrontend/lib/filterbank.c\",\n \"microfrontend/lib/fft_io.c\",\n \"microfrontend/lib/noise_reduction_util.c\",\n \"microfrontend/lib/noise_reduction.c\",\n \"microfrontend/lib/log_scale.c\",\n \"microfrontend/lib/frontend_util.c\",\n \"microfrontend/lib/pcan_gain_control.c\",\n \"micro_features/micro_features_generator.cc\",\n \"\\\\\"\n ]\n\n with open(os.path.join(builddir, target, \"Makefile\"), 'r') as original:\n data = original.read().replace(\"SRCS := \\\\\", \" \".join(SRCS))\n data = data.replace(\"-std=c++11 -DTF_LITE_STATIC_MEMORY -DNDEBUG -O3 \", \"\")\n data = data.replace(\"-std=c11 -DTF_LITE_STATIC_MEMORY -DNDEBUG -O3 \", \"\")\n data = data.replace(\"LIBRARY_OBJS := $(filter-out tensorflow/lite/micro/examples/%, $(OBJS))\", \"LIBRARY_OBJS := $(OBJS)\")\n data = re.sub(r\"tensorflow/lite/micro/benchmarks/\\S*\", \"\", data)\n data = re.sub(r\"tensorflow/lite/micro/testing/\\S*\", \"\", data)\n data = re.sub(r\"tensorflow/lite/micro/examples/\\S*\", \"\", data)\n data = re.sub(r\"tensorflow/lite/micro/tools/make/downloads/person_model_grayscale/\\S*\", \"\", data)\n data = re.sub(r\"tensorflow/lite/micro/tools/make/downloads/person_model_int8/\\S*\", \"\", data)\n\n extra_includes = \" -I./../../tensorflow/\" \\\n \" -I./tensorflow/lite/micro/tools/make/downloads\" \\\n \" -I./../../tensorflow/tensorflow/lite/micro/tools/make/downloads/cmsis/CMSIS/Core/Include\"\n\n with open(os.path.join(builddir, target, \"Makefile\"), 'w') as modified:\n modified.write(\"CCFLAGS = \" + c_compile_flags + extra_includes + \"\\n\")\n modified.write(\"CXXFLAGS = \" + cxx_compile_flags + extra_includes + \"\\n\")\n modified.write(data)\n\n shutil.copy(os.path.join(__folder__, \"libtf.cc\"), os.path.join(builddir, target))\n shutil.copy(os.path.join(__folder__, \"libtf.h\"), os.path.join(builddir, target))\n shutil.copy(os.path.join(project_folder, MODEL_C_PATH), os.path.join(builddir, target, \"libtf_person_detect_model_data.cc\"))\n shutil.copy(os.path.join(project_folder, MODEL_H_PATH), os.path.join(builddir, target, \"libtf_person_detect_model_data.h\"))\n\n if os.system(\"cd \" + os.path.join(builddir, target) + \" && make -j \" + str(cpus) + \" lib TARGET_TOOLCHAIN_PREFIX=arm-none-eabi-\"\n \" && arm-none-eabi-gcc \" + cxx_compile_flags + \" -o libtf_person_detect_model_data.o -c libtf_person_detect_model_data.cc\" +\n \" && arm-none-eabi-ar rcs libtf_person_detect_model_data.a libtf_person_detect_model_data.o\"):\n sys.exit(\"Make Failed...\")\n\n if not os.path.exists((os.path.join(libdir, target))):\n os.mkdir(os.path.join(libdir, target))\n\n shutil.copy(os.path.join(builddir, target, \"libtensorflow-microlite.a\"), os.path.join(libdir, target, \"libtf.a\"))\n shutil.copy(os.path.join(builddir, target, \"libtf_person_detect_model_data.a\"), os.path.join(libdir, target))\n shutil.copy(os.path.join(__folder__, \"libtf.h\"), os.path.join(libdir, target))\n shutil.copy(os.path.join(builddir, target, \"libtf_person_detect_model_data.h\"), os.path.join(libdir, target))\n shutil.copy(os.path.join(builddir, target, \"LICENSE\"), os.path.join(libdir, target))\n\n with open(os.path.join(libdir, target, \"README\"), \"w\") as f:\n f.write(\"You must link this library to your application with arm-none-eabi-gcc and have implemented putchar().\\n\\n\")\n f.write(\"C Compile Flags: \" + c_compile_flags + \"\\n\\n\")\n f.write(\"CXX Compile Flags: \" + cxx_compile_flags + \"\\n\")\n\ndef build_target(target, __folder__, args, cpus, builddir, libdir):\n\n compile_flags = \"-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK \" \\\n \"-DNDEBUG \" \\\n \"-DTF_LITE_MCU_DEBUG_LOG \" \\\n \"-DTF_LITE_STATIC_MEMORY \" \\\n \"-MMD \" \\\n \"-O3 \" \\\n \"-Wall \" \\\n \"-Werror \" \\\n \"-Warray-bounds \" \\\n \"-Wextra \" \\\n \"-Wvla \" \\\n \"-Wno-missing-field-initializers \" \\\n \"-Wno-strict-aliasing \" \\\n \"-Wno-type-limits \" \\\n \"-Wno-unused-but-set-variable \" \\\n \"-Wno-unused-parameter \" \\\n \"-Wno-unused-variable \" \\\n \"-Wno-unused-value \" \\\n \"-Wno-error=sign-compare \" \\\n \"-Wno-error=nonnull \" \\\n \"-Wno-error=unused-value \" \\\n \"-fdata-sections \" \\\n \"-ffunction-sections \" \\\n \"-fmessage-length=0 \" \\\n \"-fomit-frame-pointer \" \\\n \"-funsigned-char \" \\\n \"-fshort-enums \" \\\n \"-fno-delete-null-pointer-checks \" \\\n \"-fno-exceptions \" \\\n \"-fno-unwind-tables \" \\\n \"-mabi=aapcs-linux \" \\\n \"-mfloat-abi=hard \" \\\n \"-mthumb \" \\\n \"-nostartfiles \" \\\n \"-nostdlib \"\n\n c_compile_flags = compile_flags + \\\n \"-std=c11 \"\n\n cxx_compile_flags = compile_flags + \\\n \"-std=c++11 \" \\\n \"-fno-rtti \" \\\n \"-fno-threadsafe-statics \" \\\n \"-fno-use-cxa-atexit \"\n\n if target == \"cortex-m4\":\n\n cortex_m4_compile_flags = \"-DARM_MATH_CM4 \" \\\n \"-mcpu=cortex-m4 \" \\\n \"-mfpu=fpv4-sp-d16 \" \\\n \"-mtune=cortex-m4\"\n\n cortex_m4_c_compile_flags = c_compile_flags + cortex_m4_compile_flags\n\n cortex_m4_cxx_compile_flags = cxx_compile_flags + cortex_m4_compile_flags\n\n generate(target, \"cortex-m4\", __folder__, args, cpus, builddir, libdir,\n cortex_m4_c_compile_flags, cortex_m4_cxx_compile_flags)\n\n elif target == \"cortex-m7\":\n\n cortex_m7_compile_flags = \"-DARM_MATH_CM7 \" \\\n \"-mcpu=cortex-m7 \" \\\n \"-mfpu=fpv5-sp-d16 \" \\\n \"-mtune=cortex-m7\"\n\n cortex_m7_c_compile_flags = c_compile_flags + cortex_m7_compile_flags\n\n cortex_m7_cxx_compile_flags = cxx_compile_flags + cortex_m7_compile_flags\n\n generate(target, \"cortex-m7\", __folder__, args, cpus, builddir, libdir,\n cortex_m7_c_compile_flags, cortex_m7_cxx_compile_flags)\n\n else:\n sys.exit(\"Unknown target!\")\n\ndef make():\n\n __folder__ = os.path.dirname(os.path.abspath(__file__))\n\n parser = argparse.ArgumentParser(description =\n \"Make Script\")\n\n parser.add_argument(\"--skip_generation\", \"-s\", action=\"store_true\", default=False,\n help=\"Skip TensorFlow library generation.\")\n\n args = parser.parse_args()\n\n ###########################################################################\n\n cpus = multiprocessing.cpu_count()\n\n builddir = os.path.join(__folder__, \"build\")\n\n if not os.path.exists(builddir):\n os.mkdir(builddir)\n\n libdir = os.path.join(__folder__, \"libtf\")\n\n if not os.path.exists(libdir):\n os.mkdir(libdir)\n\n ###########################################################################\n\n if (not os.path.isfile(\"tensorflow/tensorflow/lite/micro/tools/make/gen/linux_x86_64/bin/person_detection_test\" + (\"_int8\" if INT8 else \"\"))) or (not args.skip_generation):\n if os.system(\"cd tensorflow\" +\n \" && make -f tensorflow/lite/micro/tools/make/Makefile -j\" + str(cpus) + \" clean\" +\n \" && make -f tensorflow/lite/micro/tools/make/Makefile -j\" + str(cpus) + \" test_person_detection_test\" + (\"_int8\" if INT8 else \"\")):\n sys.exit(\"Make Failed...\")\n\n build_target(\"cortex-m4\", __folder__, args, cpus, builddir, libdir)\n build_target(\"cortex-m7\", __folder__, args, cpus, builddir, libdir)\n\n print(\"==============================\\n Done\\n==============================\")\n\nif __name__ == \"__main__\":\n make()\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":11955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"42156313","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport six\nimport pymongo\nfrom pymongo import MongoClient\nfrom . import mongo_core\nfrom .base import MDSROTemplate, MDSTemplate\n\n\nclass MDSRO(MDSROTemplate):\n _API_MAP = {1: mongo_core}\n\n def __init__(self, config, auth=False):\n super(MDSRO, self).__init__(config)\n self.reset_connection()\n self.auth = auth\n\n def reset_connection(self):\n self.__conn = None\n\n self.__db = None\n\n self.__event_col = None\n self.__descriptor_col = None\n self.__runstart_col = None\n self.__runstop_col = None\n\n def __setstate__(self, state):\n # TODO likely broken with auth?\n self._RUNSTART_CACHE = {}\n self._RUNSTOP_CACHE = {}\n self._DESCRIPTOR_CACHE = {}\n self.reset_connection()\n self._api = None\n self.version, self.config = state\n\n def disconnect(self):\n self.__conn = None\n self.__db = None\n self.__event_col = None\n self.__descriptor_col = None\n self.__runstart_col = None\n self.__runstop_col = None\n\n def reconfigure(self, config):\n self.disconnect()\n super(MDSRO, self).reconfigure(config)\n\n @property\n def _connection(self):\n if self.__conn is None:\n if self.auth:\n uri = 'mongodb://{0}:{1}@{2}:{3}/'.format(\n self.config['mongo_user'],\n self.config['mongo_pwd'],\n self.config['host'],\n self.config['port'])\n self.__conn = MongoClient(uri)\n else:\n self.__conn = MongoClient(self.config['host'],\n self.config.get('port', None))\n return self.__conn\n\n @property\n def _db(self):\n if self.__db is None:\n conn = self._connection\n self.__db = conn.get_database(self.config['database'])\n return self.__db\n\n @property\n def _runstart_col(self):\n if self.__runstart_col is None:\n self.__runstart_col = self._db.get_collection('run_start')\n\n self.__runstart_col.create_index([('uid', pymongo.DESCENDING)],\n unique=True)\n self.__runstart_col.create_index([('time', pymongo.DESCENDING),\n ('scan_id', pymongo.DESCENDING)],\n unique=False, background=True)\n self.__runstart_col.create_index([(\"$**\", \"text\")])\n\n return self.__runstart_col\n\n @property\n def _runstop_col(self):\n if self.__runstop_col is None:\n self.__runstop_col = self._db.get_collection('run_stop')\n self.__runstop_col.create_index('run_start',\n unique=True)\n self.__runstop_col.create_index('uid',\n unique=True)\n self.__runstop_col.create_index([('time', pymongo.DESCENDING)],\n unique=False, background=True)\n self.__runstop_col.create_index([(\"$**\", \"text\")])\n\n return self.__runstop_col\n\n @property\n def _descriptor_col(self):\n if self.__descriptor_col is None:\n # The name of the reference to the run start changed from\n # 'run_start_id' in v0 to 'run_start' in v1.\n rs_name = 'run_start'\n\n self.__descriptor_col = self._db.get_collection('event_descriptor')\n\n self.__descriptor_col.create_index([('uid', pymongo.DESCENDING)],\n unique=True)\n self.__descriptor_col.create_index([(rs_name, pymongo.DESCENDING),\n ('time', pymongo.DESCENDING)],\n unique=False, background=True)\n self.__descriptor_col.create_index([('time', pymongo.DESCENDING)],\n unique=False, background=True)\n self.__descriptor_col.create_index([(\"$**\", \"text\")])\n\n return self.__descriptor_col\n\n @property\n def _event_col(self):\n if self.__event_col is None:\n self.__event_col = self._db.get_collection('event')\n\n self.__event_col.create_index([('uid', pymongo.DESCENDING)],\n unique=True)\n self.__event_col.create_index([('descriptor', pymongo.DESCENDING),\n ('time', pymongo.ASCENDING)],\n unique=False, background=True)\n return self.__event_col\n\n def db_disconnect(self):\n \"\"\"Helper function to deal with stateful connections to mongoengine\"\"\"\n self.disconnect()\n self.clear_process_cache()\n\n def db_connect(self, database, host, port, **kwargs):\n \"\"\"Helper function to deal with stateful connections to mongoengine\n\n .. warning\n\n This will silently ignore input if the database is already\n connected, even if the input database, host, or port are\n different than currently connected. To change the database\n connection you must call `db_disconnect` before attempting to\n re-connect.\n \"\"\"\n self.clear_process_cache()\n self.reconfigure(dict(database=database,\n host=host, port=port, **kwargs))\n return self._connection\n\n def find_events(self, **kwargs):\n \"\"\"Given search criteria, locate Event Documents.\n\n Parameters\n -----------\n since : time-like, optional\n time-like representation of the earliest time that an Event\n was created. Valid options are:\n - timestamps --> time.time()\n - '2015'\n - '2015-01'\n - '2015-01-30'\n - '2015-03-30 03:00:00'\n - datetime.datetime.now()\n until : time-like, optional\n timestamp of the latest time that an Event was created. See\n docs for `since` for examples.\n descriptor : doc.Document or str, optional\n Find events for a given EventDescriptor\n uid : str, optional\n Globally unique id string provided to metadatastore\n\n Returns\n -------\n events : iterable of doc.Document objects\n \"\"\"\n gen = self._api.find_events(self._runstart_col,\n self._RUNSTART_CACHE,\n self._descriptor_col,\n self._DESCRIPTOR_CACHE,\n self._event_col,\n self.config['timezone'],\n **kwargs)\n for ev in gen:\n yield ev\n\n\nclass MDS(MDSRO, MDSTemplate):\n _INS_METHODS = {'start': 'insert_run_start',\n 'stop': 'insert_run_stop',\n 'descriptor': 'insert_descriptor',\n 'event': 'insert_event',\n 'bulk_events': 'bulk_insert_events'}\n","sub_path":"databroker/headersource/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"409544399","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# (C) British Crown Copyright 2017-2019 Met Office.\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 are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Module to contain statistical operations.\"\"\"\n\nimport warnings\n\nimport iris\nimport numpy as np\nfrom iris.exceptions import CoordinateNotFoundError\n\nfrom improver.utilities.cube_checker import (find_percentile_coordinate,\n check_cube_coordinates)\n\n\nclass ProbabilitiesFromPercentiles2D(object):\n r\"\"\"\n Generate a 2-dimensional field of probabilities by interpolating a\n percentiled cube of data to required points.\n\n Examples:\n\n Given a reference field of values against a percentile coordinate, an\n interpolation is performed using another field of values of the same\n type (e.g. height). This returns the percentile with which these\n heights would be associated in the reference field. This effectively\n uses the field of values as a 2-dimensional set of thresholds, and the\n percentiles looked up correspond to the probabilities of these\n thresholds being reached.\n\n Snow-fall level::\n\n Reference field: Percentiled snow fall level (m ASL)\n Other field: Orography (m ASL)\n\n 300m ----------------- 30th Percentile snow fall level\n 200m ----_------------ 20th Percentile snow fall level\n 100m ---/-\\----------- 10th Percentile snow fall level\n 000m --/---\\---------- 0th Percentile snow fall level\n ______/ \\_________ Orogaphy\n\n The orography heights are compared against the heights that\n correspond with percentile values to find the band in which they\n fall; this diagram hides the 2-dimensional variability of the snow\n fall level. The percentile values are then interpolated to the\n height of the point being considered. This constructs a\n 2-dimensional field of probabilities that snow will be falling at\n each point in the orography field.\n \"\"\"\n\n def __init__(self, percentiles_cube, output_name):\n \"\"\"\n Initialise class. Sets an inverse_ordering (bool) switch to true for\n cases where the percentiled data increases in the opposite sense to the\n percentile coordinate:\n\n e.g. 0th Percentile - Value = 10\n 10th Percentile - Value = 5\n 20th Percentile - Value = 0\n\n Args:\n percentiles_cube (iris.cube.Cube):\n The percentiled field from which probabilities will be obtained\n using the input cube. This cube should contain a percentiles\n dimension, with fields of values that correspond to these\n percentiles. The cube passed to the process method will contain\n values of the same diagnostic (e.g. height) as this reference\n cube.\n output_name (str):\n The name of the cube being created,\n e.g.'probability_of_snow_falling_level_below_ground_level'\n \"\"\"\n self.percentile_coordinate = find_percentile_coordinate(\n percentiles_cube)\n if self.percentile_coordinate.points.shape[0] < 2:\n msg = (\"Percentile coordinate has only one value. Interpolation \"\n \"using ProbabilitiesFromPercentiles2D requires multiple \"\n \"values are provided.\")\n raise ValueError(msg)\n self.percentiles_cube = percentiles_cube\n self.output_name = output_name\n\n # Set inverse_ordering switch\n percentile_slices = percentiles_cube.slices_over(\n self.percentile_coordinate)\n self.inverse_ordering = False\n first_percentile = percentile_slices.next().data\n for percentile_values in percentile_slices:\n last_percentile = percentile_values.data\n if (first_percentile - last_percentile >= 0).all():\n self.inverse_ordering = True\n\n def __repr__(self):\n \"\"\"Represent the configured plugin instance as a string.\"\"\"\n result = ('=. We then populate the\n value_bounds and percentile_bounds arrays.\n\n Slice 0 - 0th Percentile::\n\n [[1.0 >= 2.0, 1.0 >= 2.0, 1.0 >= 2.0],\n [3.0 >= 2.0, 3.0 >= 2.0, 3.0 >= 2.0],\n [5.0 >= 2.0, 5.0 >= 2.0, 5.0 >= 2.0]]\n\n [[False, False, False],\n [True, True, True],\n [True, True, True]]\n\n The value_bounds array has a leading dimensions with 2 indices\n to be associated with the lower [0] and upper bounds [1] about\n the threshold being considered. The [0] index is populated with\n the values in the slice of percentiles_cube at every True index.\n The [1] index is populated with the values in the next slice of\n percentiles_cube.\n ::\n\n [ [[np.nan, np.nan, np.nan],\n [2.0, 2.0, 2.0],\n [2.0, 2.0, 2.0]],\n\n [[np.nan, np.nan, np.nan],\n [4.0, 4.0, 4.0],\n [4.0, 4.0, 4.0]] ]\n\n The percentile_bounds array is also contains a leading dimension\n associated with lower and upper bounds about the thresholds. The\n lower bound array is populated at every True index with the\n current percentile value (0 in this first slice), whilst the\n upper bound array takes the percentile value from the next\n slice.\n ::\n\n [ [[-1, -1, -1],\n [0, 0, 0],\n [0, 0, 0]],\n\n [[-1, -1, -1],\n [50, 50, 50],\n [50, 50, 50]] ]\n\n After the same process is applied to the next slice, the 50th\n percentile, we end up with value_bounds::\n\n [ [[np.nan, np.nan, np.nan],\n [2.0, 2.0, 2.0],\n [4.0, 4.0, 4.0]],\n\n [[np.nan, np.nan, np.nan],\n [4.0, 4.0, 4.0],\n [4.0, 4.0, 4.0]] ]\n\n And percentile bounds::\n\n [ [[-1, -1, -1],\n [0, 0, 0],\n [50, 50, 50]],\n\n [[-1, -1, -1],\n [50, 50, 50],\n [50, 50, 50]] ]\n\n Note that where there is no availble +1 index in the\n percentiles_cube the upper bound is set to be the same as the\n lower_bound.\n\n 2. When all slices have been interated over, the interpolants are\n calculated using the threshold values and the values_bounds.\n ::\n\n (threshold_cube.data - lower_bound) /\n (upper_bound - lower_bound)\n\n If the upper_bound and lower_bound are the same this leads to\n a divide by 0 calculation, resulting in np.inf as the output.\n\n 3. The interpolants are used to calculate the percentile value at\n each point in the array using the percentile_bounds.\n ::\n\n lower_percentile_bound + interpolants *\n (upper_percentile_bounds - lower_percentile_bounds)\n\n The percentiles are divided by 100 to give a fractional\n probability.\n\n 5. Any probabilities that are calculated to be np.inf indicate that\n the associated point has a threshold value that is above\n the top percentile band. These points are given a probability\n value of 1.\n\n 4. Any points for which the calculated probability is np.nan had\n threshold values that were never found to fall within a\n percentile band, and so must be below the lowest band. These\n points are given a probability value of 0.\n\n Args:\n threshold_cube (iris.cube.Cube):\n A 2-dimensional cube of \"threshold\" values for which it is\n desired to obtain probability values from the percentiled\n reference cube. This cube should have the same x and y\n dimensions as percentiles_cube.\n percentiles_cube (iris.cube.Cube):\n A 3-dimensional cube, 1 dimension describing the percentile\n distributions, and 2-dimensions shared with the threshold_cube,\n typically x and y.\n\n Returns:\n probabilities (iris.cube.Cube):\n A 2-dimensional cube of probabilities obtained by interpolating\n between percentile values.\n\n \"\"\"\n percentiles = self.percentile_coordinate.points\n probabilities = self.create_probability_cube(percentiles_cube,\n threshold_cube)\n\n # Create array with additional 2 dimensions to contain upper and lower\n # bounds.\n array_shape = [2] + list(threshold_cube.shape)\n percentile_bounds = np.full(array_shape, -1, dtype=np.float32)\n value_bounds = np.full(array_shape, np.nan, dtype=np.float32)\n\n for index, pslice in enumerate(percentiles_cube.slices_over(\n self.percentile_coordinate)):\n # Change to use < & > to force degenerate percentile distributions\n # to use the first percentile band that the threshold falls within.\n indices = (threshold_cube.data <= pslice.data\n if self.inverse_ordering else\n threshold_cube.data >= pslice.data)\n percentile_bounds[0, indices] = percentiles[index]\n value_bounds[0, indices] = pslice.data[indices]\n try:\n # Usual behaviour where the threshold value falls between\n # values corresponding to percentiles.\n percentile_bounds[1, indices] = percentiles[index + 1]\n value_bounds[1, indices] = percentiles_cube[index+1].data[\n indices]\n except IndexError:\n # Invoked if we have reached the top of the available values.\n percentile_bounds[1, indices] = percentiles[index]\n value_bounds[1, indices] = pslice.data[indices]\n\n with np.errstate(divide='ignore', invalid='ignore'):\n numerator = (threshold_cube.data - value_bounds[0])\n denominator = np.diff(value_bounds, n=1, axis=0)[0]\n interpolants = numerator/denominator\n interpolants[denominator == 0] = np.inf\n\n with np.errstate(invalid='ignore'):\n probabilities.data, = (percentile_bounds[0] + interpolants *\n np.diff(percentile_bounds, n=1, axis=0))\n probabilities.data = probabilities.data/np.float32(100.)\n\n above_top_band = np.isinf(interpolants)\n below_bottom_band = np.isnan(value_bounds[0])\n probabilities.data[below_bottom_band] = 0.\n probabilities.data[above_top_band] = 1.\n\n return probabilities\n\n def process(self, threshold_cube):\n \"\"\"\n Slice the percentiles cube over any non-spatial coordinates\n (realization, time, etc) if present, and call the percentile\n interpolation method for each resulting cube.\n\n Args:\n threshold_cube (iris.cube.Cube):\n A cube of values, that effectively behave as thresholds, for\n which it is desired to obtain probability values from a\n percentiled reference cube.\n Returns:\n probability_cube (iris.cube.Cube):\n A cube of probabilities obtained by interpolating between\n percentile values at the \"threshold\" level.\n \"\"\"\n cube_slices = self.percentiles_cube.slices(\n [self.percentile_coordinate, self.percentiles_cube.coord(axis='y'),\n self.percentiles_cube.coord(axis='x')])\n\n if threshold_cube.ndim != 2:\n msg = ('threshold cube has too many ({} > 2) dimensions - slicing '\n 'to x-y grid'.format(threshold_cube.ndim))\n warnings.warn(msg)\n threshold_cube = next(threshold_cube.slices([\n threshold_cube.coord(axis='y'),\n threshold_cube.coord(axis='x')]))\n\n if threshold_cube.units != self.percentiles_cube.units:\n threshold_cube.convert_units(self.percentiles_cube.units)\n\n output_cubes = iris.cube.CubeList()\n for cube_slice in cube_slices:\n output_cube = self.percentile_interpolation(threshold_cube,\n cube_slice)\n output_cubes.append(output_cube)\n\n probability_cube = output_cubes.merge_cube()\n\n reference_cube = next(self.percentiles_cube.slices_over(\n self.percentile_coordinate))\n\n probability_cube = check_cube_coordinates(reference_cube,\n probability_cube)\n return probability_cube\n","sub_path":"lib/improver/utilities/statistical_operations.py","file_name":"statistical_operations.py","file_ext":"py","file_size_in_byte":18943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"278317528","text":"#import logging\nimport os\nimport csv\nimport nltk\nimport gensim\n\ndef iter_docs(stoplist):\n with open('Papers.csv', 'rb') as csvfile: \n f = csv.reader(csvfile, delimiter=',')\n readers = None\n document = []\n for row in f:\n text = row[5].replace(\",\",\"\") #for author column\n yield (x for x in gensim.utils.tokenize(text, lowercase=True, deacc=True, errors=\"ignore\") if x not in stoplist)\n\nclass MyCorpus(object):\n def __init__(self, stoplist):\n self.stoplist = stoplist\n self.dictionary = gensim.corpora.Dictionary(iter_docs(stoplist))\n \n def __iter__(self):\n for tokens in iter_docs(self.stoplist):\n yield self.dictionary.doc2bow(tokens)\n\n#logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nTEXTS_DIR = \".\"\nMODELS_DIR = \".\"\n\nstoplist = set(nltk.corpus.stopwords.words(\"english\"))\ncorpus = MyCorpus(stoplist)\n\ncorpus.dictionary.save(os.path.join(MODELS_DIR, \"mtsamples.dict\"))\ngensim.corpora.MmCorpus.serialize(os.path.join(MODELS_DIR, \"mtsamples.mm\"), corpus)\n\n\ndictionary = gensim.corpora.Dictionary.load(os.path.join(MODELS_DIR, \"mtsamples.dict\"))\ncorpus = gensim.corpora.MmCorpus(os.path.join(MODELS_DIR, \"mtsamples.mm\"))\n\ntfidf = gensim.models.TfidfModel(corpus, normalize=True)\ncorpus_tfidf = tfidf[corpus]\n\n# project to 2 dimensions for visualization\nlsi = gensim.models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2)\n\n# write out coordinates to file\nfcoords = open(os.path.join(MODELS_DIR, \"coords.csv\"), 'wb')\nfor vector in lsi[corpus]:\n if len(vector) != 2:\n continue\n fcoords.write(\"%6.4f\\t%6.4f\\n\" % (vector[0][1], vector[1][1]))\nfcoords.close()\n","sub_path":"topicModeling_LDA.py","file_name":"topicModeling_LDA.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"210026423","text":"#imports\nfrom _ast import Lambda\n\nimport pygame\nimport math\nfrom queue import PriorityQueue\n\n#window set up\nSTD_WIDTH = 1000\nWIN = pygame.display.set_mode((STD_WIDTH, STD_WIDTH))\npygame.display.set_caption(\"A* Visualizer\")\n\n#Colors\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nPURPLE = (128, 0, 128)\nORANGE = (255, 165, 0)\nGREY = (128, 128, 128)\nCYAN = (64, 224, 208)\n\nclass Square:\n def __init__(self, row, col, width, row_num):\n self.row = row\n self.col = col\n self.x = row * width\n self.y = col * width\n self.color = BLACK\n self.neighbors = []\n self.width = width\n self.row_num = row_num\n\n def get_pos(self):\n return self.row, self.col\n\n def is_closed(self):\n return self.color == RED\n\n def is_open(self):\n return self.color == GREEN\n\n def is_wall(self):\n return self.color == WHITE\n\n def is_start(self):\n return self.color == ORANGE\n\n def is_goal(self):\n return self.color == CYAN\n\n def restart(self):\n self.color = BLACK\n\n def make_start(self):\n self.color = ORANGE\n\n def close(self):\n self.color = RED\n\n def open(self):\n self.color = GREEN\n\n def build_wall(self):\n self.color = WHITE\n\n def make_end(self):\n self.color = CYAN\n\n def find_path(self):\n self.color = PURPLE\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))\n\n def update_adjacent(self, grid):\n self.adjacent = []\n if self.row < self.row_num - 1 and not grid[self.row + 1][self.col].is_wall(): #DOWN\n self.adjacent.append(grid[self.row + 1][self.col])\n\n if self.row > 0 and not grid[self.row - 1][self.col].is_wall(): #UP\n self.adjacent.append(grid[self.row - 1][self.col])\n\n if self.col < self.row_num - 1 and not grid[self.row][self.col + 1].is_wall(): #RIGHT\n self.adjacent.append(grid[self.row][self.col + 1])\n\n if self.row > 0 and not grid[self.row][self.col - 1].is_wall(): #LEFT\n self.adjacent.append(grid[self.row][self.col - 1])\n\n def __lt__(self, other):\n return False\n\ndef h(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return abs(x1 - x2) + abs(y1 - y2)\n\ndef build_grid(rows, width):\n grid = []\n gap = width // rows\n for i in range(rows):\n grid.append([])\n for j in range(rows):\n square = Square(i, j, gap, rows)\n grid[i].append(square)\n\n return grid\n\ndef draw_grid(win, rows, width):\n gap = width // rows\n for i in range(rows):\n pygame.draw.line(win, GREY, (0, i * gap), (width, i * gap))\n for j in range(rows):\n pygame.draw.line(win, GREY, (j * gap, 0), (j * gap, width))\n\ndef draw(win, grid, rows, width):\n win.fill(BLACK)\n\n for row in grid:\n for square in row:\n square.draw(win)\n\n draw_grid(win, rows, width)\n pygame.display.update()\n\ndef get_clicked_pos(pos, rows, width):\n gap = width // rows\n y, x = pos\n\n row = y // gap\n col = x // gap\n return row, col\n\ndef display_path(source, current, win, grid, rows, width):\n while current in source:\n current = source[current]\n current.find_path()\n draw(win, grid, rows, width)\n\ndef algorithm(win, rows, width, grid, start, goal):\n count = 0\n open_list = PriorityQueue()\n open_list.put((0, count, start))\n source = {}\n g_score = {square: float(\"inf\") for row in grid for square in row}\n g_score[start] = 0\n f_score = {square: float(\"inf\") for row in grid for square in row}\n f_score[start] = h(start.get_pos(), goal.get_pos())\n\n hash_open_list = {start}\n\n while not open_list.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n current = open_list.get()[2]\n hash_open_list.remove(current)\n\n if current == goal:\n display_path(source, goal, win, grid, rows, width)\n start.make_start()\n goal.make_end()\n return True\n for adjacent in current.adjacent:\n hold_g_score = g_score[current] + 1\n\n if hold_g_score < g_score[adjacent]:\n source[adjacent] = current\n g_score[adjacent] = hold_g_score\n f_score[adjacent] = hold_g_score + h(adjacent.get_pos(), goal.get_pos())\n if adjacent not in hash_open_list:\n count += 1\n open_list.put((f_score[adjacent], count, adjacent))\n hash_open_list.add(adjacent)\n adjacent.open()\n\n draw(win, grid, rows, width)\n\n if current != start:\n current.close()\n\n return False\n\n\n\ndef main(win, width):\n ROWS = 50\n grid = build_grid(ROWS, width)\n\n start = None\n goal = None\n\n run = True\n started = False\n while run:\n draw(win, grid, ROWS, width)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if pygame.mouse.get_pressed()[0]: #Left click\n pos = pygame.mouse.get_pos()\n row, col = get_clicked_pos(pos, ROWS, width)\n square = grid[row][col]\n if not start and square != goal:\n start = square\n start.make_start()\n elif not goal and square != start:\n goal = square\n goal.make_end()\n elif square != goal and square != start:\n square.build_wall()\n\n elif pygame.mouse.get_pressed()[2]: #Right click\n pos = pygame.mouse.get_pos()\n row, col = get_clicked_pos(pos, ROWS, width)\n square = grid[row][col]\n square.restart()\n if square == start:\n start = None\n if square == goal:\n goal = None\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE and start and goal:\n for row in grid:\n for square in row:\n square.update_adjacent(grid)\n algorithm(win, ROWS, width, grid, start, goal)\n\n if event.key == pygame.K_r:\n start = None\n goal = None\n grid = build_grid(ROWS, width)\n\n pygame.quit()\n\nmain(WIN, STD_WIDTH)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"181457042","text":"import jax\nimport jax.numpy as jnp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport laxy\nimport pickle\nimport sys\nimport os\nimport sw_functions as sw\nimport network_functions as nf\n\nos.environ[\"XLA_FLAGS\"] = \"--xla_gpu_cuda_data_dir=/n/helmod/apps/centos7/Core/cuda/10.1.243-fasrc01/\"\nos.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n\n\n# chosen hyperparameters described in comments\ndate = sys.argv[1]\nlr = float(sys.argv[2]) # SMURF and MLM-GREMLIN: .05\nbatch_size = sys.argv[3] # SMURF: highest; MLM-GREMLIN: 64\niters = sys.argv[4] # SMURF: \"MM\"; MLM-GREMLIN: \"G4\"\ngradual = sys.argv[5] # SMURF and MLM-GREMLIN: \"no\"\nmsa_frac = float(sys.argv[6]) # SMURF: 0.3; MLM-GREMLIN = 0.0\nmsa_memory = float(sys.argv[7]) # SMURF: 0.9; MLM-GREMLIN = 0.0\nmode = sys.argv[8] # SMURF: \"EvolveMRF\"; MLM-GREMLIN: \"Gremlin\"; Use \"TRUE\" to save the true contacts and alignments \nnum_fams = 190\n\n\nif batch_size == \"highest\":\n batch_sizes = [256, 128, 64]\nelse:\n batch_sizes = [int(batch_size)]\ngap = - 3\n\nspecial_fams = ['3G9KF','3L00A','4ONMA','1Y6ZA','2HZQA','5ITQA','2IZ6A','3LF9A','2HBWA','1RSSA','1K4IA','2QQ4A']\n \nbasic_pid = [None, None, None, None]\nbasic_steps = [1, 0, 0, 0]\nif gradual == \"yes\":\n MRF_pid = [1.00, .60, .40, .20]\n init_align_to_msa_frac = 0.0\n init_msa_memory = False\n\nelif gradual == \"no\":\n MRF_pid = [0, 0, 0, 0]\n init_align_to_msa_frac = msa_frac\n init_msa_memory = msa_memory\n \nif mode ==\"Standard\":\n MRF_steps = [1,0,0,0]\nelse:\n MRF_steps = [1/4, 1/4, 1/4, 1/4]\n\nbasic_steps = [1,0,0,0]\n \nif iters == \"S\":\n basic_steps = [int(2000*_) for _ in basic_steps]\n MRF_steps = [int(1000*_) for _ in MRF_steps]\nif iters == \"MB\":\n basic_steps = [int(2000*_) for _ in basic_steps]\n MRF_steps = [int(2000*_) for _ in MRF_steps]\nif iters == \"MM\":\n basic_steps = [int(3000*_) for _ in basic_steps]\n MRF_steps = [int(1000*_) for _ in MRF_steps]\nif iters == \"G4\":\n basic_steps = [0,0,0,0]\n MRF_steps = [4000, 0, 0, 0]\nif iters == \"G3\":\n basic_steps = [0,0,0,0]\n MRF_steps = [3000, 0, 0, 0]\nif iters == \"G2\":\n basic_steps = [0,0,0,0]\n MRF_steps = [2000, 0, 0, 0]\nif iters == \"G1\":\n basic_steps = [0,0,0,0]\n MRF_steps = [1000, 0, 0, 0]\n \ndata = np.load(\"data_unalign.npz\", allow_pickle=True)\nverbose = False\naucs = []\nfams = []\nfor n,x in enumerate(data.keys()):\n if x not in special_fams: continue\n if verbose: print(f\"family {x}\")\n a = data[x].item()\n\n # prep data\n seqs = nf.sub_sample(a[\"ms\"])\n lens = np.array([len(seq) for seq in seqs])\n ms = nf.one_hot(nf.pad_max(seqs))\n aln = nf.one_hot(nf.pad_max(nf.sub_sample(a[\"aln\"])))\n \n if mode == \"TRUE\":\n t_aln = aln\n t_contacts = a[\"true\"]\n t_contacts_mask = a[\"mask\"]\n pickle.dump((t_aln, t_contacts,t_contacts_mask),open(f\"fam_results/{date}_{x}_{mode}\",\"wb\"))\n continue\n\n if \"model\" in globals():\n del model\n nf.clear_mem()\n for batch_size in batch_sizes:\n try:\n if verbose: print(f\"attempting batch size {batch_size}\")\n if mode != \"Gremlin\":\n model = nf.BasicAlign(X=ms, lengths=lens, batch_size=batch_size, filters=512, win=18, \n sw_unroll=4, sw_temp=1.0, sw_learn_temp=False,\n sw_open=None, sw_gap=gap, sw_learn_gap=True,\n sw_restrict=False,\n seed=None, lr=lr, norm_mode=\"fast\", \n w_scale=0.1)\n if verbose: print(\"BasicAlign\")\n model.fit(basic_steps[0], verbose=verbose)\n msa_params = model.opt.get_params()\n\n if verbose: print(\"MRF\")\n\n model = nf.MRF(X=ms, lengths=lens, ss_hide=0.15, batch_size=batch_size, \n filters=512, win=18, lam=0.01,\n sw_unroll=4, sw_temp=1.0, sw_learn_temp=False,\n sw_open=None, sw_gap=None, sw_learn_gap=False,\n nat_contacts=a[\"true\"],\n nat_contacts_mask=a[\"mask\"],\n nat_aln=None, use_nat_aln=False, add_aln_loss=False, aln_lam=1.0,\n seed=None, lr=lr, norm_mode=\"fast\",\n learn_bias=True, w_scale=0.1, \n msa_memory = init_msa_memory, align_to_msa_frac = init_align_to_msa_frac, pid_thresh = MRF_pid[0])\n mrf_params = model.opt.get_params()\n for p in [\"emb\",\"gap\",\"open\"]:\n if p==\"gap\" and verbose: print(p, msa_params[p])\n mrf_params[p] = msa_params[p]\n model.opt.set_params(mrf_params)\n model.fit(MRF_steps[0], verbose=verbose)\n\n if mode == \"EvolveMRF\":\n if verbose: print(f\"reset with pid thresh: {MRF_pid[1]}\")\n model.reset_model_and_opt({\"msa_memory\": msa_memory, \"align_to_msa_frac\": msa_frac, \"pid_thresh\":MRF_pid[1]})\n model.fit(MRF_steps[1], verbose=verbose)\n \n if verbose: print(f\"reset with pid thresh: {MRF_pid[2]}\")\n model.reset_model_and_opt({\"msa_memory\": msa_memory, \"align_to_msa_frac\": msa_frac, \"pid_thresh\":MRF_pid[2]})\n model.fit(MRF_steps[2], verbose=verbose)\n\n if verbose: print(f\"reset with pid thresh: {MRF_pid[3]}\")\n model.reset_model_and_opt({\"msa_memory\": msa_memory, \"align_to_msa_frac\": msa_frac, \"pid_thresh\":MRF_pid[3]})\n model.fit(MRF_steps[3], verbose=verbose)\n\n\n print(\"X\", mode, x, model.get_auc(), batch_size)\n \n\n if mode == \"Gremlin\":\n if verbose: print(\"MRF\")\n model = nf.MRF(X=ms, lengths=lens, ss_hide=0.15, batch_size=batch_size, \n filters=512, win=18, lam=0.01,\n sw_unroll=4, sw_temp=1.0, sw_learn_temp=False,\n sw_open=None, sw_gap=None, sw_learn_gap=False,\n nat_contacts=a[\"true\"], nat_contacts_mask=a[\"mask\"],\n nat_aln=jnp.array(aln), use_nat_aln=True, add_aln_loss=False, aln_lam=1.0,\n seed=None, lr=lr, norm_mode=\"fast\",\n learn_bias=True, w_scale=0.1)\n model.fit(MRF_steps[0], verbose=True)\n \n auc = model.get_auc()\n break\n except:\n print(f\"FAIL ON {x} with batch size {batch_size}\")\n auc = None\n \n # predicted alignment and contacts\n if mode == \"Gremlin\":\n p_aln = None\n else:\n p_aln = np.copy(model.get_aln(np.array(range(10)))[0])\n #p_aln = np.copy(model.get_aln(jnp.array(range(ms.shape[0])))[0])\n p_contacts = model.get_contacts()\n \n pickle.dump((auc, p_aln, p_contacts),open(f\"fam_results/{date}_{x}_{mode}_{lr}_{o_batch_size}_{iters}_{gradual}_{msa_frac}_{msa_memory}\",\"wb\"))\n","sub_path":"examples/run_smurf_w_contacts_aln.py","file_name":"run_smurf_w_contacts_aln.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"495320632","text":"\nfrom scipy.sparse import diags\nimport numpy as np\nimport random\nimport funcs_tridiagsolver as TDMA\n\ndef test_tridiag_solver():\n tol = 0.00000001\n for n in range(3, 10):\n dl = np.random.rand(n-1)\n du = np.random.rand(n-1)\n d = np.random.rand(n);\n\n A = diags([dl, d, du], [-1,0,1]).toarray()\n b = np.random.rand(len(d))\n\n x_correct = np.matmul(np.linalg.inv(A), b)\n\n xtemp = np.zeros(n)\n gamma = np.zeros(n-1)\n beta = np.zeros(n)\n x_TDMA = np.zeros(n)\n\n TDMA.solve_tridiag(x_TDMA, b, dl, d, du, n, xtemp, gamma, beta)\n err = [abs(x-y) for (x, y) in zip(x_correct, x_TDMA)]\n assert all([x, )\n :returns: a mongo query dictionary \"\"\"\n assert topic_pairs, \"Terms list should not be empty. Use ALL_TOPICS if no topic constrains.\" # noqa\n queries = []\n for topic, is_leaf in topic_pairs:\n queries.append({\"tc\": topic, \"es.if\": is_leaf})\n\n if len(queries) > 1:\n return {\"$or\": queries}\n else:\n return queries[0]\n\n def sum_group_by_query(self, group_by_field, plot_by='time', plot_type='topics'):\n \"\"\" Based on a field we want to group by, the plot type and the attribute\n we are plotting by, return a group mongo aggregation query. \"\"\"\n query = super(ChannelTopicTrendsManager, self).sum_group_by_query(group_by_field, plot_by, plot_type)\n # TODO: dudarev: remove missed-calls from here\n if plot_type in ('topics', 'missed-posts'):\n query.update({\"count\": {\"$sum\": \"$es.tt\"}})\n return query\n\n def construct_filter_query(self, intention_ids, statuses, agents, languages):\n assert intention_ids or statuses or agents or languages, \"Filter parameters must be defined\"\n query = super(ChannelTopicTrendsManager, self).construct_filter_query(statuses, agents, languages)\n if intention_ids:\n query[\"es.in\"] = {\"$in\": intention_ids}\n\n return query\n\n def get_id_intervals(self, channel, from_ts, to_ts, topic, status):\n \"Get (`from_id`, `to_id`) parameters for a channel `channel`\"\n return (ChannelTopicTrends.make_id(channel, from_ts, topic, status),\n ChannelTopicTrends.make_id(channel, to_ts, topic, status))\n\n def by_time_span(self, channel=None, from_ts=None, to_ts=None, topic_pairs=None,\n intentions=None, statuses=None, agents=None,\n languages=None, group_by='topic',\n plot_by='time', plot_type=None, no_transform=False):\n \"\"\"\n :param channel: can be a string or a sequence\n :param from_ts: starting timeslot\n :param to_ts: end timeslot\n :param group_by: the type of grouping we are doing for aggregation\n :param topic_pairs: list of pairs (, )\n :param statuses: list of \n :param agents: list of , where each user should have .agent_id != 0\n :param languages: list of language codes or ids\n :param group_by: \n\n :returns: stats by time span\n \"\"\"\n agents = self.preprocess_agents(agents, group_by, channel)\n\n if statuses:\n statuses = is_iterable(statuses) and statuses or [statuses]\n statuses = map(get_status_code, statuses)\n else:\n statuses = SpeechActMap.STATUS_NAME_MAP.keys()\n\n intention_ids = map(get_intention_id, intentions or []) or [ALL_INTENTIONS_INT]\n topic_pairs = topic_pairs or [[ALL_TOPICS, False]]\n languages = map(get_lang_id, languages or [])\n\n from_ts = Timeslot(from_ts).timeslot\n to_ts = Timeslot(to_ts or from_ts).timeslot\n\n or_query = []\n for (topic, _), status in product(topic_pairs, statuses):\n # channel can be a string or a sequence\n if isinstance(channel, seq_types):\n for c in channel:\n from_id, to_id = self.get_id_intervals(c, from_ts, to_ts, topic, status)\n or_query.append({\"_id\": {\"$gte\": from_id, \"$lte\": to_id}})\n else:\n from_id, to_id = self.get_id_intervals(channel, from_ts, to_ts, topic, status)\n or_query.append({\"_id\": {\"$gte\": from_id, \"$lte\": to_id}})\n\n if len(or_query) == 1:\n indexed_match_query = or_query[0]\n else:\n indexed_match_query = {\"$or\": or_query}\n\n initial_pipeline = [\n {\"$match\": indexed_match_query}\n ]\n\n match_query = {}\n if plot_type:\n match_query = {\"$and\": [\n self.filter_topics(topic_pairs),\n self.construct_filter_query(intention_ids, statuses, agents, languages)]}\n pipeline = self.assemble_pipeline(initial_pipeline, match_query, plot_type, plot_by, group_by)\n res = self.execute_pipeline(pipeline)\n\n if not res['ok']:\n error_msg = \"Aggregate error=%s\" % res\n #LOGGER.error(\"%s pipeline=%s\", error_msg, pformat(pipeline))\n return {'ok': False, 'error': error_msg}\n\n features = {'agent': [(u.agent_id, u) for u in (agents or [])],\n 'intention': intention_ids,\n 'topic': topic_pairs,\n 'status': statuses,\n 'lang': make_lang_features(languages),\n 'time': None}[group_by]\n return self.postprocess_results(res, pipeline, no_transform, plot_type, from_ts,\n to_ts, group_by, plot_by, features)\n\n\nclass ChannelTopicTrends(ChannelTopicsBase, ChannelTrendsBase):\n \"\"\"\n Each document tracks stats of a specific channel-term pair during\n a specific timeslot (hours, days and months).\n In addition to what's in ChannelTrends has status, topic, intention.\n \"\"\"\n manager = ChannelTopicTrendsManager\n\n topic = fields.StringField(db_field='tc')\n status = fields.NumField(db_field='ss')\n embedded_stats = fields.ListField(fields.EmbeddedDocumentField('ExtendedEmbeddedStats'), db_field='es')\n\n indexes = [('time_slot', ), ('channel_ts', ), ('channel_ts', 'topic')]\n\n def compute_increments(self, is_leaf=True, intention_ids=None, agent=None, lang_id=None, inc_dict={}, n=1):\n \"\"\" Compute requred increments to embeded stats for this stat instance. \"\"\"\n update_dict = {k: n * v for k,v in inc_dict.iteritems()}\n self.update_embedded_stats(intention_ids, is_leaf, agent, lang_id, update_dict)\n\n @classmethod\n def increment(cls, channel=None, time_slot=None, topic=None, status=None,\n is_leaf=True, intention_ids=None, agent=None, lang_id=None,\n inc_dict={}, n=1):\n \"\"\"Deprecated\n \"\"\"\n assert channel is not None and topic is not None and intention_ids is not None \\\n and status is not None and time_slot is not None, vars()\n\n stats = cls(channel=channel, time_slot=time_slot, topic=topic, status=status)\n stats.compute_increments(is_leaf, intention_ids, agent, lang_id, inc_dict, n)\n\n stats.upsert()\n return stats\n\n def __repr__(self):\n channel_num, topic_hash, status, time_slot = self.unpacked\n dt_value, dt_level = decode_timeslot(time_slot)\n\n return '<%s id=%s channel=%s timeslot=%s %s status=%s>' % (\n self.__class__.__name__,\n self.id,\n channel_num,\n dt_value.strftime('%Y%m%d.%H'),\n dt_level,\n status\n )\n","sub_path":"db/channel_topic_trends.py","file_name":"channel_topic_trends.py","file_ext":"py","file_size_in_byte":8069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"379679456","text":"class Group(object):\n def __init__(self, _name):\n self.name = _name\n self.groups = []\n self.users = []\n\n def add_group(self, group):\n self.groups.append(group)\n\n def add_user(self, user):\n self.users.append(user)\n\n def get_groups(self):\n return self.groups\n\n def get_users(self):\n return self.users\n\n def get_name(self):\n return self.name\n\n\n\ndef is_user_in_group(user, group):\n \"\"\"\n Return True if user is in the group, False otherwise.\n Args:\n user(str): user name/id\n group(class:Group): group to check user membership against\n \"\"\"\n\n #straight find\n if user in group.get_users(): return True\n \n #noone in group\n if not group.get_groups(): return False\n \n #recursive search\n else:\n for sub_group in group.get_groups():\n if is_user_in_group(user, sub_group): return True\n \n return False\n\nparent = Group(\"parent\")\nchild = Group(\"child\")\nsub_child = Group(\"subchild\")\n\nsub_child_user = \"sub_child_user\"\nsub_child.add_user(sub_child_user)\nchild.add_group(sub_child)\nparent.add_group(child)\n\n\nsub_child_user = 'test_user_correct'\nsub_child.add_user(sub_child_user)\nchild.add_group(sub_child)\nparent.add_group(child)\n\nusers = ['test_user_1', 'test_user_2']\nfor i in users:\n sub_child.add_user(i)\nchild.add_group(sub_child)\nparent.add_group(child)\n\n\n\ndef test_user_lookup():\n \"\"\"\n test cases for lookups \n \"\"\"\n assert not is_user_in_group('test_user_incorrect', parent)\n assert is_user_in_group('test_user_correct', parent)\n assert is_user_in_group('test_user_1', child)\n assert is_user_in_group('test_user_2', child)\n assert not is_user_in_group('', parent)\n assert not is_user_in_group('', child)\n \n \n\ntest_user_lookup()","sub_path":"data_structures/Group Directory/group_directory.py","file_name":"group_directory.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"537525991","text":"N = 10\nSTART = (0, 0)\nDIRECTIONS = list(reversed([(0, 1), (1, 0), (0, -1), (-1, 0)]))\n\n\nmatrix = [[None for _ in range(N)] for _ in range(N)]\nposition = START\ndirection_i = 0\nnumber = 0\nmatrix[position[0]][position[1]] = number\nwhile True:\n new_position = [position[i] + DIRECTIONS[direction_i][i] for i in range(len(position))]\n if new_position[0] in range(0, N) and new_position[1] in range(0, N) and matrix[new_position[0]][new_position[1]] == None:\n position = new_position\n number += 1\n matrix[position[0]][position[1]] = number\n\n else:\n if direction_i == 3:\n direction_i = 0\n elif direction_i < 3:\n direction_i += 1\n new_position = [position[i] + DIRECTIONS[direction_i][i] for i in range(len(position))]\n if matrix[new_position[0]][new_position[1]] != None:\n break\n \nfor row in matrix:\n print(*row, sep='\\t')\n \n","sub_path":"Другое/matrix_spiral.py","file_name":"matrix_spiral.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"559179122","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 6 13:55:33 2020\n\n@author: Freedom \n\"\"\"\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport time\nimport pandas as pd\n\nfrom sklearn.metrics import mean_squared_error\nfrom scipy.special import kl_div\nfrom scipy.stats import wasserstein_distance\n\n#Time of simulation\nvreme_simulacije = 259200 # len of test in min ( 6 month period )\n\n#Load datasets from simulation\nvremena_otkaza = np.load('lista_vremena_otkz_5_BTD.npy', allow_pickle=True) #shape(num of simulations, len of failures in each sim)\nvremena_popravke = np.load('lista_vremena_pop_5_BTD.npy', allow_pickle=True) #shape(num of simulations, len of repairs in each sim)\nvrsta_otkaza = np.load('lista_vrsta_pop_4000_BTD.npy', allow_pickle=True) #shape(num of simulations, len of failures in each sim)\n\n#Load real data for evaluation\nname_fail = 'Data/fail_window{}_dt{}h_real.npy'.format(int(7*24*60/(24*60)),int(60/60))\nname_repair = 'Data/repair_window{}_dt{}h_real.npy'.format(int(7*24*60/(24*60)),int(60/60))\nname_class = 'Data/class_window{}_dt{}h_real.npy'.format(int(7*24*60/(24*60)),int(60/60))\nReal_data_fail = np.load(name_fail, allow_pickle=True) \nReal_data_rep = np.load(name_repair, allow_pickle=True)\nReal_data_class = np.load(name_class, allow_pickle=True)\n\nlist_fail_window_7days = []\nlist_fail_window_15days = []\nlist_fail_window_30days = []\n\nlist_repair_window_7days = []\nlist_repair_window_15days = []\nlist_repair_window_30days = []\n\ndef division(a,b):\n '''\n Returns 0 if division by 0\n '''\n if b == 0 :\n return 0 \n else:\n return a/b\n\ndef kl_divergence(p, q):\n '''\n This is known as the relative entropy \n or Kullback-Leibler divergence,\n or KL divergence, between the distributions p(x) and q(x).\n '''\n return sum(p[i] * np.log((p[i]/q[i])) for i in range(len(p)))\n\ndef gen_lambda_and_mi(podatci1,podatci2, podatci3, seq_len, t):\n '''\n This Funcion consist of 3 parts:\n 1. We generate 3 matrix with len(len_of_simulation(in minutes))\n 2.a) We put 1 in moment (minut) in which the event happend \n and 0 otherwise (for repair and failure rates)\n 2.b) We put class (1,2,3) of falilure in moment (minut) in which the event happend \n and 0 otherwise (for class of failures)\n 3. We go through Matrixes with sliding_window (window size, and step) \n '''\n\n #1. step: Generate matrix for each list\n matrix = np.zeros(vreme_simulacije)\n matrix1 = np.zeros(vreme_simulacije)\n matrix2 = np.zeros(vreme_simulacije)\n\n #2. step: Fill the each Matrix with mooments \n #(in which minute) event happend (or what type of event happend in that moment (matrix2))\n for index, value in enumerate(podatci1):\n matrix[int(value)] = 1\n matrix2[int(value)] = podatci3[index] + 1 \n for i in podatci2:\n matrix1[int(i)] = 1 \n\n #3. step: Evaluate for window_size(seq_len) and step(dt) \n lambd = []\n mi = [] \n fail_distribution = [] \n start = 0\n end = seq_len\n one_day = (24*60) / seq_len #when multiplied with window_size(seq_len) returns values scaled to 1 day\n for i in range(int((len(matrix)-seq_len)/t)):\n #Generate fail number per window and step\n ls = matrix[start:end]\n lambd.append(sum(ls)*one_day) #Number of Failures per 1 day for current window and step\n #Generate repair number per window and step\n ls1 = matrix1[start:end]\n mi.append(sum(ls1)*one_day) #Number of Repairs per 1 day for current window and step\n #Generate fail_distribution per window and step\n types_of_fail_ = []\n types_of_fail_.extend(matrix2[start:end])\n Mechanical_fail = types_of_fail_.count(1)\n Electro_fail = types_of_fail_.count(2) \n Other_fail = types_of_fail_.count(3) \n total_fail = Mechanical_fail + Electro_fail + Other_fail\n if total_fail == 0:\n total_fail += 1 # to avoid divison with 0\n ls_ = [Mechanical_fail/total_fail, Electro_fail/total_fail, Other_fail/total_fail]\n fail_distribution.append(ls_) \n \n start += t #update for step(dt)\n end += t #update for step(dt)\n return lambd, mi, fail_distribution\nResults = [] \ncount = 0 \nfor i in range(2):\n start = time.time()\n ls_ = []\n #Load data form simulation[i]\n podatci1 = vremena_otkaza[i].reshape(-1)\n podatci2 = vremena_popravke[i].reshape(-1)\n podatci3 = vrsta_otkaza[i].reshape(-1)\n print(podatci1.shape)\n #drop if the last value is larger then len_of_simulation\n if len(podatci1) > 1:\n if vreme_simulacije < podatci1[-1]:\n podatci1[:-1]\n if len(podatci2 )> 1: \n if vreme_simulacije < podatci2[-1]:\n podatci2[:-1]\n\n #make list vector with cosistant(same) len\n #sometimes one vector is longer than another for single value\n len_1 = len(podatci1)\n len_2 = len(podatci2)\n len_3 = len(podatci3)\n ls_.extend((len_1, len_2, len_3))\n min_len = min(ls_)\n podatci1 = podatci1[:min_len]\n podatci2 = podatci2[:min_len]\n podatci3 = podatci3[:min_len]\n print(podatci1.shape)\n\n seq_leng = [7*24*60] #, 15*24*60, 30*24*60] #windows of 7, 15 and 30 days\n dt = [8*60] #step of 60 minutes\n for seq_len in seq_leng:\n for t in dt:\n count += 1\n lamb, mi, fail_distribution = gen_lambda_and_mi(podatci1,podatci2,podatci3, int(seq_len), t)\n mi_gen = np.array(mi).reshape(-1)\n lamb_gen = np.array(lamb).reshape(-1)\n fail_distribution = np.array(fail_distribution).reshape(-1, 3) \n\n #append generated values to lists\n if seq_len == 7*24*60:\n list_fail_window_7days.append(lamb_gen)\n list_repair_window_7days.append(mi_gen)\n elif seq_len == 15*24*60:\n list_fail_window_15days.append(lamb_gen)\n list_repair_window_15days.append(mi_gen)\n else:\n list_fail_window_30days.append(lamb_gen)\n list_repair_window_30days.append(mi_gen)\n\n #Optinal: Save into lists\n # np.save('npy_lists/fail_window{}_dt{}h_sim{}.npy'.format(seq_len/(24*60), int(t/60), i), lamb_gen)\n # np.save('npy_lists/repair_window{}_dt{}h_sim{}.npy'.format(seq_len/(24*60),int(t/60), i), lamb_gen)\n # np.save('npy_lists/class_window{}_dt{}h_sim{}.npy'.format(seq_len/(24*60),int(t/60), i), lamb_gen)\n \n #Load real data for evaluation\n name_fail = 'Data/fail_window{}_dt{}h_real.npy'.format(int(seq_len/(24*60)),int(t/60))\n name_repair = 'Data/repair_window{}_dt{}h_real.npy'.format(int(seq_len/(24*60)),int(t/60))\n name_class = 'Data/class_window{}_dt{}h_real.npy'.format(int(seq_len/(24*60)),int(t/60))\n Real_data_fail = np.load(name_fail, allow_pickle=True)\n Real_data_repair = np.load(name_repair, allow_pickle=True)\n Real_data_class = np.load(name_class, allow_pickle=True)\n \n #MSE/Evaluation of real vs predicted failure rate\n len_tst_st = int(len(Real_data_fail)*0.8)\n Test_data_fail = Real_data_fail[len_tst_st:len_tst_st + len(lamb_gen)].reshape(-1)\n MSE_sim_f = mean_squared_error(Test_data_fail, lamb_gen) \n\n #MSE/Evaluation of real vs predicted repair rate\n len_tst_st = int(len(Real_data_fail)*0.8)\n Test_data_repair = Real_data_repair[len_tst_st:len_tst_st + len(mi_gen)].reshape(-1)\n MSE_sim_r = mean_squared_error(Test_data_repair, mi_gen)\n\n #KL_divergance/Evaluation KL_divergance for mi_gen distribution\n len_tst_st = int(len(Real_data_class)*0.8)\n Test_data_class = Real_data_class[len_tst_st:len_tst_st + len(fail_distribution)]\n res =[]\n #wasserstein_distance([0, 1, 3], [5, 6, 8])\n for i in range(len(fail_distribution)): \n kl_ = kl_divergence(fail_distribution[i], Test_data_class[i])\n res.append(kl_)\n res_ = [x for x in res if x < 1000 and x > -1000]\n KL_div = division(sum(res_),len(res_))\n \n #Append results in order 1. Failure_rate 2. Repair_rate 3. Class\n Results.extend([MSE_sim_f, MSE_sim_r, KL_div])\n print(np.array(Results).shape)\n \n end = time.time()\n print('Time:{}sec'.format(end - start)) #print time for loop[i]\n\nResults = np.array(Results) \nprint(Results.shape)\nResults = Results.reshape(-1,3)\ndf = pd.DataFrame(Results, columns=['MSE_sim_fail', 'MSE_sim_repair', 'KL_div'])\ndf.to_excel(\"Output.xlsx\", sheet_name='Rezultati')\n\nlist_fail_window_7days_mean = []\nlist_fail_window_15days_mean = []\nlist_fail_window_30days_mean = []\n\nlist_repair_window_30days_mean = []\nlist_repair_window_15days_mean = []\nlist_repair_window_7days_mean = []\n\nlist_fail_window_7days = np.array(list_fail_window_7days).T\nlist_fail_window_15days = np.array(list_fail_window_15days).T\nlist_fail_window_30days = np.array(list_fail_window_30days).T\n\nlist_repair_window_7days = np.array(list_repair_window_7days).T\nlist_repair_window_15days = np.array(list_repair_window_15days).T\nlist_repair_window_30days = np.array(list_repair_window_30days).T\n\nfor i in range(len(list_fail_window_7days)):\n list_fail_window_7days_mean.append(sum(list_fail_window_7days[i])/len(list_fail_window_7days[i]))\n list_repair_window_7days_mean.append(sum(list_repair_window_7days[i])/len(list_repair_window_7days[i]))\n\nfor i in range(len(list_fail_window_15days)):\n list_fail_window_15days_mean.append(sum(list_fail_window_15days[i])/len(list_fail_window_15days[i]))\n list_repair_window_15days_mean.append(sum(list_repair_window_15days[i])/len(list_repair_window_15days[i]))\n\nfor i in range(len(list_fail_window_30days)):\n list_fail_window_30days_mean.append(sum(list_fail_window_30days[i])/len(list_fail_window_30days[i]))\n list_repair_window_30days_mean.append(sum(list_repair_window_30days[i])/len(list_repair_window_30days[i]))\n\nnp.save('list_fail_window_7days_mean.npy', list_fail_window_7days_mean)\nnp.save('list_fail_window_15days_mean.npy', list_fail_window_15days_mean)\nnp.save('list_fail_window_30days_mean.npy', list_fail_window_30days_mean)\n\nnp.save('list_repair_window_30days_mean.npy', list_repair_window_30days_mean)\nnp.save('list_repair_window_15days_mean.npy', list_repair_window_15days_mean)\nnp.save('list_repair_window_7days_mean.npy', list_repair_window_7days_mean)","sub_path":"Machine_learning_simulations/4.Statistic Sim/1.Probibalistic/1. Test_Sim/Gen_window.py","file_name":"Gen_window.py","file_ext":"py","file_size_in_byte":10726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"231918744","text":"import re\nimport math\n\n\nclass DomainSearchHelper:\n\n # Regex used\n regex_str = r\"\"\"\n (?:\"|') # Start newline delimiter\n (\n ((?:[a-zA-Z]{1,10}://|//) # Match a scheme [a-Z]*1-10 or //\n [^\"'/]{1,}\\. # Match a domainname (any character + dot)\n [a-zA-Z]{2,}[^\"']{0,}) # The domainextension and/or path\n |\n ((?:/|\\.\\./|\\./) # Start with /,../,./\n [^\"'><,;| *()(%%$^/\\\\\\[\\]] # Next character can't be...\n [^\"'><,;|()]{1,}) # Rest of the characters can't be\n |\n ([a-zA-Z0-9_\\-/]{1,}/ # Relative endpoint with /\n [a-zA-Z0-9_\\-/]{1,} # Resource name\n \\.(?:[a-zA-Z]{1,4}|action) # Rest + extension (length 1-4 or action)\n (?:[\\?|#][^\"|']{0,}|)) # ? or # mark with parameters\n |\n ([a-zA-Z0-9_\\-/]{1,}/ # REST API (no extension) with /\n [a-zA-Z0-9_\\-/]{3,} # Proper REST endpoints usually have 3+ chars\n (?:[\\?|#][^\"|']{0,}|)) # ? or # mark with parameters\n |\n ([a-zA-Z0-9_\\-]{1,} # filename\n \\.(?:php|asp|aspx|jsp|json|\n action|html|js|txt|xml) # . + extension\n (?:[\\?|#][^\"|']{0,}|)) # ? or # mark with parameters\n )\n (?:\"|') # End newline delimiter\n \"\"\"\n\n invalid_substrings = ['.png','.jpg','.mp4','.mp3']\n\n def get_http_in_js(self, response):\n regex = re.compile(self.regex_str, re.VERBOSE)\n http_endpoints = list()\n matches_in_js = [(m.group(1), m.start(0), m.end(0)) for m in re.finditer(regex, response.text)]\n for match in matches_in_js:\n if 'http' in list(match)[0] and '.js' not in list(match)[0] and '.css' not in list(match)[0]:\n if not any(substring in list(match)[0] for substring in self.invalid_substrings):\n http_endpoints.append(list(match)[0])\n\n return http_endpoints\n\n def get_css_in_url(self, session, url):\n\n regex = re.compile(self.regex_str, re.VERBOSE)\n\n try:\n response = session.get(url, verify = False)\n except Exception:\n return []\n\n all_matches = [(m.group(1), m.start(0), m.end(0)) for m in re.finditer(regex, response.text)]\n css_endpoints = list()\n for match in all_matches:\n if '.css' in list(match)[0] and 'http' in list(match)[0]:\n css_endpoints.append(list(match)[0])\n\n return css_endpoints\n\n\n @staticmethod\n def check_scope(url_list, domain):\n\n if domain == 'None':\n return url_list\n else:\n tmp = list()\n for url in url_list:\n split_url = url.split('/')\n try:\n # Este es un mal intento de poda. Basicamente primero descartamos los //\n # Despues descartamos todo lo que sea un parametro, ya que pueden haber un monton de llamadas a\n # otras direcciones que pasan como parametro el dominio\n # Finalmente validamos que el dominio este de la manera http:// o http://www.\n split_url = split_url[2].split('?')\n if domain in split_url[0]:\n tmp.append(url)\n except IndexError:\n continue\n\n return tmp\n\n @staticmethod\n def sufficient_string_entropy(string):\n\n \"\"\"Calculate the entropy of a string.\"\"\"\n entropy = 0\n for number in range(256):\n length = len(string.encode('utf-8'))\n result = float(string.encode('utf-8').count(number)) / length\n if result != 0:\n entropy = entropy - result * math.log(result, 2)\n\n if entropy >= 4:\n return True\n else:\n return False\n\n @staticmethod\n def normalize_list(listToFix):\n\n output = listToFix\n output = filter(None, output)\n output = [item for sublist in output for item in sublist]\n output = list(dict.fromkeys(output))\n\n return output\n","sub_path":"Seguridad Informatica/Atacante/domain_search_helper.py","file_name":"domain_search_helper.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"429296401","text":"#utiliza esta funcion para saber si es primo o no\ndef esprimo(n):\n if n<2:\n return False\n else:\n for i in range(2,n):\n if n%i == 0:\n return False\n return True\n \ndef filtrarprimos(numeros):\n\tprimos = []\n\t\n\tfor x in numeros:\n\t\tif esprimo(x):\n\t\t\tprimos.append(x)\n\n\treturn primos\n\nnum = [1,2,3,4,5,6,7,8,9,10,11]\n\nprint(filtrarprimos(num))\n\n","sub_path":"Programacion_procedimental/primo.py","file_name":"primo.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"568093194","text":"from django.contrib import admin\nfrom asteriski_site.riski_info.models import Message\n\nclass MessageAdmin(admin.ModelAdmin):\n date_hierarchy = 'created_on'\n fieldsets = (\n (None, {\n 'fields': ('title', 'category', 'content')\n }),\n )\n\n def save_model(self, request, obj, form, change):\n if obj.id:\n obj.last_modifier = request.user\n else:\n obj.creator = request.user\n obj.save()\n\nadmin.site.register(Message, MessageAdmin)\n","sub_path":"asteriski_site/riski_info/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"454218643","text":"# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.\n# Например, если введено число 3486, то надо вывести число 6843.\n\n\ndef flip_flop(a, d=1, result=0):\n\n if d == 1 and a == 0:\n return int(result)\n\n elif a // d > 0:\n d = d * 10\n return flip_flop(a, d)\n\n else:\n d = d / 10\n result = a % 10 * d + result\n a = a // 10\n return flip_flop(a, int(d), result)\n\n\na = int(input('Введите целое положительное число: '))\nlen_a = len(str(a))\n\nraw_result = flip_flop(a)\n\nprint(str(raw_result).zfill(len_a))","sub_path":"lesson02/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"551438386","text":"from pico2d import *\r\nimport random\r\n\r\ncnt = 0\r\n\r\n\r\nclass Grass:\r\n def __init__(self):\r\n self.image = load_image('../res/grass.png')\r\n print(self.image)\r\n\r\n def draw(self):\r\n self.image.draw(400, 30)\r\n\r\n\r\n\r\nclass Boy:\r\n def __init__(self):\r\n global cnt\r\n print(\"Creating..\")\r\n self.x = random.randint(0, 200)\r\n self.y = random.randint(90, 550)\r\n self.speed = random.uniform(1.0, 3.0)\r\n self.frame = random.randint(0, 7)\r\n self.image = load_image('../res/run_animation.png')\r\n\r\n def draw(self):\r\n self.image.clip_draw(self.frame * 100, 0, 100, 100, self.x, self.y)\r\n\r\n def update(self):\r\n self.frame = (self.frame + 1) % 8\r\n\r\n\r\n\r\nwaypoints = []\r\nKPU_WIDTH, KPU_HEIGHT = 800, 600\r\ndx, dy = 0,0\r\ndef handle_events():\r\n global running\r\n global px, py\r\n global dx, dy\r\n global dest\r\n global waypoints\r\n events = get_events()\r\n for e in events:\r\n if e.type == SDL_QUIT:\r\n running = False\r\n # elif e.type == SDL_MOUSEMOTION:\r\n # px, py = e.x, KPU_HEIGHT - 1 - e.y\r\n elif e.type == SDL_MOUSEBUTTONDOWN:\r\n if e.button == 1:\r\n px, py = e.x, KPU_HEIGHT - 1 - e.y\r\n waypoints += [(px, py)]\r\n else:\r\n waypoints = []\r\n elif e.type == SDL_KEYDOWN and e.key == SDLK_ESCAPE:\r\n running = False\r\n\r\n\r\nopen_canvas(KPU_WIDTH,KPU_HEIGHT)\r\nwp = load_image('../res/wp.png')\r\ng = Grass()\r\nb = Boy()\r\nb2 = Boy()\r\n# b2.y = 200\r\nwaypoints = []\r\nboys = [Boy() for i in range(20)]\r\n# boys = []\r\n# for i in range(20):\r\n# boys += [ Boy() ]\r\n\r\n\r\n# for b in boys:\r\n# b.y = random.randint(90, 550)\r\n\r\nrunning = True\r\npx,py =400,300\r\n\r\n\r\nwhile running:\r\n handle_events()\r\n\r\n\r\n if len(waypoints) > 0:\r\n (px, py) = waypoints[0]\r\n for b in boys:\r\n dx, dy = px - b.x, py - b.y\r\n dist = math.sqrt(dx ** 2 + dy ** 2)\r\n if dist > 0:\r\n b.x += b.speed * dx / dist\r\n b.y += b.speed * dy / dist\r\n\r\n if dx < 0 and b.x < px: b.x = px\r\n if dx > 0 and b.x > px: b.x = px\r\n if dy < 0 and b.y < py: b.y = py\r\n if dy > 0 and b.y > py: b.y = py\r\n\r\n if (b.x, b.y) == (px, py):\r\n cnt += 1\r\n for b in boys:\r\n b.update()\r\n # b.update()\r\n # b2.update()\r\n if cnt == 20:\r\n cnt = 0\r\n del waypoints[0]\r\n cnt = 0\r\n clear_canvas()\r\n g.draw()\r\n for b in boys:\r\n b.draw()\r\n for loc in waypoints:\r\n wp.draw(loc[0], loc[1])\r\n\r\n update_canvas()\r\n\r\n delay(0.03)\r\n","sub_path":"hw_0921/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"262519613","text":"#!/usr/bin/env python3\nimport os\nimport requests\nimport json\n\n#initialize url where content will be uploaded to\nurl = \"http://35.222.40.70/fruits/\"\n#set path where files are saved\ndir = \"supplier-data/descriptions/\"\n#list all files\nlist_files = os.listdir(dir)\n#iterate through files\nfor files in list_files:\n if files.endswith(\".txt\"):\n #open all files\n with open(dir + files) as text_file:\n #read file contents and split text wit a new line\n contents = text_file.read().split(\"\\n\")\n #set up the dictionary to be used as a json format later,\n #the dictionary format is: {\"name\":\"fruit name\",\n #\"weight\": weight in lbs,\n #\"description\": \"description about the fruit\",\n #\"image_name\": image name associated with fruit with ext .jpeg\"}\n format = {\n \"name\": contents[0],\n \"weight\": int(contents[1].strip(\"lbs\")),\n \"description\": contents[2],\n \"image_name\": os.path.splitext(files)[0] + \".jpeg\"}\n #upload content to website\n response = requests.post(url, data = format)\n #print the upload's status code\n print(\"Status code:{}\".format(response.status_code))\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"541166012","text":"'''\n분류 : DFS & BFS\n문제 : 트리의 지름 (백준 1167)\n작성일자 : 2021.04.26\n''' \n\n# 목적 : 트리의 지름출력\n# 접근 : 트리의 지름 구하는 공식을 사용\n# 임의의 정점 x에서 가장 먼 정점 y를 구하고, y에서 가장 먼 정점이 트리의 지름이다\n# 인접리스트를 생성하고, 모든 점에서의 최대 거리를 구해도 가능(시간초과)\n\nimport sys\nsys.setrecursionlimit(10**8)\ninput = sys.stdin.readline\n\ndef dfs(start,depth) : \n # 최대 depth를 기록\n visit[start] = 1 \n for lst in adj_lst[start] : \n if visit[lst[0]] == 0 : # 방문한적이 없는 정점이라면\n visit[lst[0]] = 1 # 방문처리\n depth_lst[lst[0]] = depth + lst[1]\n dfs(lst[0],lst[1]+depth)\n\nN = int(input())\n# 인접리스트 생성\nadj_lst = [[] for _ in range(N+1)]\nfor _ in range(N) : \n path = list(map(int, input().split()))\n len_path = len(path)//2\n for i in range(1,len_path) : \n adj_lst[path[0]].append([path[2*i-1],path[2*i]])\n# 방문처리를 위한 리스트 생성\nvisit = [0] * (N+1)\n# 임의의 위치에서 각 정점의 depth를 저장하기 위한 리스트 생성\ndepth_lst = [0] * (N+1)\n# 임의의 점에서 dfs를 수행, 가장 큰 depth를 가지는 정점을 저장\nmax_depth = 0\ndfs(1,0) # 1번 정점에서 depth가 0인상태로 시작\nmax_depth_V = depth_lst.index(max(depth_lst))\n\n# 임의의 점에서 가장 멀은 정점을 다시 dfs\ndepth_lst = [0] * (N+1)\nvisit = [0] * (N+1)\ndfs(max_depth_V,0)\nprint(max(depth_lst))\n\n'''import sys \nfrom collections import deque \ninput = sys.stdin.readline\n\ndef bfs(s) : \n visit[s] = 1\n q = deque([(s,0)])\n ans = []\n while q : \n x,depth = q.popleft()\n ans.append(depth)\n # print(x, depth)\n for lst in adj_lst[x] :\n # print(lst[0]) \n # print(visit)\n if visit[lst[0]] == 0 :\n visit[lst[0]] = 1 \n q.append((lst[0],depth+lst[1]))\n ans.append(depth+lst[1])\n return max(ans)\n \n\nN = int(input())\nadj_lst = {i:[] for i in range(1,N+1)}\nfor _ in range(N) : \n lst = deque(list(map(int, input().split())))\n S = lst.popleft()\n while lst : \n V = lst.popleft()\n if V == -1 : \n break\n E = lst.popleft()\n adj_lst[S].append([V,E])\n # lst = list(map(int, input().split()))\n # lst.pop()\n # while len(lst) != 1 : \n # E = lst.pop()\n # V = lst.pop()\n # # print(E,V)\n # adj_lst[lst[0]].append([V,E])\n # print(adj_lst)\nans = []\nvisit = [0]*(N+1)\nmax_val = 0\nfor i in range(1,N+1) : \n max_val = max(max_val,bfs(i))\n visit = [0]*(N+1)\nprint(max_val)'''","sub_path":"graph_search/R_search_35_1167.py","file_name":"R_search_35_1167.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"267490188","text":"import plotly.express as px\r\nimport plotly.graph_objects as go\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv(\"D:/Stuff/Work/Uni/2021/Professional Studio A/Code/Python functions/total_Liability.csv\")\r\n\r\nbarchart = px.bar(\r\n\tdata_frame = df,\r\n\tx = \"Date\",\r\n\ty = \"Total Liabilities\",\r\n\torientation = \"v\",\r\n\ttitle = \"Google Annual Total Liability\"\r\n)\r\n\r\nbarchart.update_layout(\r\n autosize=False,\r\n width=1000,\r\n height=500)\r\n\r\nbarchart.write_html(\"D:/Stuff/Work/Uni/2021/Professional Studio A/Code/Stock HTML/total_Liability.html\")\r\n","sub_path":"PythonCode/totalLiability.py","file_name":"totalLiability.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"222695014","text":"\"\"\"This module handles finding, loading, and validating the configuration file.\"\"\"\n\nimport configparser\nimport logging\nimport os.path\nimport platform\n\nimport docopt\n\nimport cli\n\nlogger = logging.getLogger(__name__)\n\ndictionary = None\n\n\n\nclass Test(object):\n \"\"\"Base class for configuration tests.\"\"\"\n\n def __init__(self, config, section, key, value_type, is_required):\n self.config = config\n self.section = section\n self.key = key\n self.value_type = value_type\n self.is_required = is_required\n self.value = None\n\n # Run basic tests.\n if self.is_required:\n if not self.is_present():\n raise TestPresentError(self)\n\n if not self.is_type():\n raise TestTypeError(self)\n\n def is_type(self):\n \"\"\"\n Test if the value string value can be converted to the specified value_type. Return True if conversion is\n possible, False otherwise.\n \"\"\"\n _is_type = True\n\n if self.value_type is int:\n try:\n int(self.value)\n\n except ValueError:\n _is_type = False\n\n elif self.value_type is float:\n try:\n float(self.value)\n\n except ValueError:\n _is_type = False\n\n elif self.value_type is bool:\n is_bool = False\n strings = ['true', 'false', 'yes', 'no', '1', '0', 'on', 'off']\n\n for string in strings:\n if self.value.lower() == string:\n is_bool = True\n break\n\n if not is_bool:\n _is_type = False\n\n return _is_type\n\n def is_present(self):\n \"\"\"\n Check if the config value is present in the config file. Return true if the value is present, False otherwise.\n \"\"\"\n _is_present = False\n\n try:\n self.value = self.config[self.section][self.key]\n except KeyError:\n pass\n else:\n _is_present = True\n\n return _is_present\n\n def test(self):\n # Run value-specific tests here.\n\n return True\n\n\n\nclass CreateDirTest(Test):\n \"\"\"Test if a directory exists or can be created at the path represented by self.value.\"\"\"\n\n def test(self):\n \"\"\"\n Return True if self.value is a valid directory (after expansion of variables and user directories) or can be\n successfully created, False otherwise.\n \"\"\"\n result = False\n expanded_path = os.path.expandvars(os.path.expanduser(self.value))\n\n if os.path.isdir(expanded_path):\n result = True\n\n else:\n try:\n os.makedirs(expanded_path)\n\n except:\n raise TestCreateDirError(self)\n\n else:\n result = True\n\n return result\n\n\n\n\"\"\"Exceptions for the config module.\"\"\"\n\n\n\nclass Error(Exception):\n \"\"\"Base exception for configuration errors.\"\"\"\n pass\n\n\n\nclass LoadError(Error):\n \"\"\"Base exception for configuration loading errors.\"\"\"\n\n def __init__(self):\n self.message = None\n\n def __str__(self):\n error = 'An error occurred while loading the configuration file'\n\n if self.message is None:\n full_error = error + '.'\n\n else:\n full_error = error + ': ' + self.message\n\n return full_error\n\n\n\nclass LoadNotFoundError(LoadError):\n def __init__(self):\n super().__init__()\n self.message = 'No configuration file could be found.'\n\n\n\nclass LoadPlatformError(LoadError):\n def __init__(self, _platform):\n super().__init__()\n self._platform = _platform\n self.message = 'The platform \"{0}\" is not supported.'.format(self._platform)\n\n\n\nclass TestError(Error):\n \"\"\"Base exception for configuration testing errors.\"\"\"\n\n def __init__(self, test):\n self.test = test\n self.message = None\n\n def __str__(self):\n error = 'An error occurred while processing configuration option ' \\\n '[{0}]{1}'.format(self.test.section, self.test.key)\n\n if self.message is None:\n full_error = error + '.'\n else:\n full_error = error + ': ' + self.message\n\n return full_error\n\n\n\nclass TestCreateDirError(TestError):\n \"\"\"This exception raised when a required directory is unable to be created or accessed.\"\"\"\n\n def __init__(self, test):\n super().__init__(test)\n self.message = 'Unable to create dir \"{0}\".'.format(self.test.value)\n\n\n\nclass TestPresentError(TestError):\n \"\"\"This exception is raised when a required configuration key/value is not present in the configuration file.\"\"\"\n\n def __init__(self, test):\n super().__init__(test)\n self.message = 'Key does not exist in configuration.'\n\n\n\nclass TestTypeError(TestError):\n \"\"\"This exception is raised when a configuration value is not the correct data type.\"\"\"\n\n def __init__(self, test):\n super().__init__(test)\n self.message = 'Value \"{0}\" is not required type {1}'.format(self.test.value, self.test.value_type)\n\n\n\ndef find():\n \"\"\"\n Return the location of the config file on disk. Check for the --config option first, then search the default\n locations.\n \"\"\"\n config = None\n options = docopt.docopt(cli.__doc__)\n _platform = platform.system()\n\n logger.debug('Searching for configuration file.')\n\n if options['--config'] is not None:\n paths[_platform] = []\n paths[_platform].append(options['--config'])\n\n else:\n logger.debug('Detected platform \"{0}\".'.format(_platform))\n\n try:\n paths[_platform]\n\n except KeyError:\n raise LoadPlatformError(_platform)\n\n else:\n for path in paths[_platform]:\n logger.debug('Trying configuration path \"{0}\".'.format(path))\n\n if os.path.isfile(path):\n config = path\n logger.debug('Found configuration file \"{0}\".'.format(config))\n break\n\n if config is None:\n raise LoadNotFoundError\n\n return config\n\n\n\ndef load():\n global dictionary\n\n dictionary = configparser.ConfigParser()\n path = find()\n\n logger.debug('Reading configuration values from file.')\n dictionary.read(path)\n\n logger.debug('Validating configuration values.')\n\n for section in tests:\n for key in tests[section]:\n logger.debug('Validating configuration key [{0}]{1}.'.format(section, key))\n\n key_required = tests[section][key][0]\n key_type = tests[section][key][1]\n test_class = tests[section][key][2]\n test = test_class(dictionary, section, key, key_type, key_required)\n\n test.test()\n\n\n\npaths = {\n 'Linux': [\n '/etc/archive-framework.conf',\n os.path.expanduser('~/.config/archive-framework.conf')\n ],\n # TODO: Implement OSX support\n # 'Darwin': [],\n # TODO: Implement Windows support\n # 'Windows': []\n}\n\n\n\n\"\"\"\nThe following is a dictionary of configuration tests. The dictionary is ordered by configuration sections that each\ncontain a dictionary of each possible configuration key represented by tuples. The tuples for this format:\n\n(required, type, test)\n\nrequired - bool that specifies whether or not the configuration key is required for the application to function\n properly.\ntype - The intended data type of the configuration key. Should be one of str, int, float, or bool.\ntest - The Test (sub)class that should be used to verify that the key's value is valid. If the configuration key has\n no special requirements, the Test base class may be used.\n\"\"\"\n\n\n\ntests = {\n 'global': {\n 'data_dir': (True, str, CreateDirTest),\n }\n}\n","sub_path":"archive-framework/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"69561418","text":"import os\n\nfrom copy import deepcopy\nimport numpy as np\nfrom numpy import genfromtxt\nfrom collections import deque\nimport torch\nfrom torch.optim import Adam\nimport gym\nimport time\nimport algos.pytorch.ddpg.core as core\nfrom utils.logx import EpochLogger\nfrom utils.mpi_pytorch import setup_pytorch_for_mpi, sync_params, mpi_avg_grads\nfrom utils.mpi_tools import mpi_fork, mpi_avg, proc_id, mpi_statistics_scalar, num_procs\nfrom mpi4py import MPI\n\nclass ReplayBuffer:\n \"\"\"\n A simple FIFO experience replay buffer for DDPG agents.\n \"\"\"\n\n def __init__(self, obs_dim, act_dim, size):\n self.obs_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32)\n self.obs2_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32)\n self.act_buf = np.zeros(core.combined_shape(size, act_dim), dtype=np.float32)\n self.rew_buf = np.zeros(size, dtype=np.float32)\n self.done_buf = np.zeros(size, dtype=np.float32)\n self.ptr, self.size, self.max_size = 0, 0, size\n\n def store(self, obs, act, rew, next_obs, done):\n self.obs_buf[self.ptr] = obs\n self.obs2_buf[self.ptr] = next_obs\n self.act_buf[self.ptr] = act\n self.rew_buf[self.ptr] = rew\n self.done_buf[self.ptr] = done\n self.ptr = (self.ptr+1) % self.max_size\n self.size = min(self.size+1, self.max_size)\n\n def sample_batch(self, batch_size=32):\n idxs = np.random.randint(0, self.size, size=batch_size)\n batch = dict(obs=self.obs_buf[idxs],\n obs2=self.obs2_buf[idxs],\n act=self.act_buf[idxs],\n rew=self.rew_buf[idxs],\n done=self.done_buf[idxs])\n return {k: torch.as_tensor(v, dtype=torch.float32) for k,v in batch.items()}\n\n def save_buffer(self, checkpointfile):\n np.save(checkpointfile+\"_obs.npy\", self.obs_buf)\n np.save(checkpointfile+\"_obs2.npy\", self.obs2_buf)\n np.save(checkpointfile+\"_act.npy\", self.act_buf)\n np.save(checkpointfile+\"_rew.npy\", self.rew_buf)\n np.save(checkpointfile+\"_done.npy\", self.done_buf)\n a = open(checkpointfile + \"_vals.txt\", \"a+\")\n a.write(\"%d\\n\" % self.ptr)\n a.write(\"%d\\n\" % self.size)\n a.write(\"%d\\n\" % self.max_size)\n a.close()\n\n def load_buffer(self, checkpointfile):\n self.obs_buf = np.load(checkpointfile+\"_obs.npy\")\n self.obs2_buf = np.load(checkpointfile+\"_obs2.npy\")\n self.act_buf = np.load(checkpointfile+\"_act.npy\")\n self.rew_buf = np.load(checkpointfile+\"_rew.npy\")\n self.done_buf = np.load(checkpointfile+\"_done.npy\")\n with open(checkpointfile+'_vals.txt', 'r') as a:\n lines = a.read().splitlines()\n self.ptr = int(lines[0])\n self.size = int(lines[1])\n self.max_size = int(lines[2])\n\n\ndef ddpg(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0, \n steps_per_epoch=1000, epochs=100, replay_size=int(1e6), gamma=0.99, \n polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=128, start_steps=10000, \n update_after=250, update_every=64, act_noise=0.1, num_test_episodes=10, \n max_ep_len=1000, logger_kwargs=dict(), save_freq=1, save_prefix = \"art\",\n save_after = 5, restore_model_from_file = 1, load_after_iters = 0):\n \"\"\"\n Deep Deterministic Policy Gradient (DDPG)\n\n\n Args:\n env_fn : A function which creates a copy of the environment.\n The environment must satisfy the OpenAI Gym API.\n\n actor_critic: The constructor method for a PyTorch Module with an ``act`` \n method, a ``pi`` module, and a ``q`` module. The ``act`` method and\n ``pi`` module should accept batches of observations as inputs,\n and ``q`` should accept a batch of observations and a batch of \n actions as inputs. When called, these should return:\n\n =========== ================ ======================================\n Call Output Shape Description\n =========== ================ ======================================\n ``act`` (batch, act_dim) | Numpy array of actions for each \n | observation.\n ``pi`` (batch, act_dim) | Tensor containing actions from policy\n | given observations.\n ``q`` (batch,) | Tensor containing the current estimate\n | of Q* for the provided observations\n | and actions. (Critical: make sure to\n | flatten this!)\n =========== ================ ======================================\n\n ac_kwargs (dict): Any kwargs appropriate for the ActorCritic object \n you provided to DDPG.\n\n seed (int): Seed for random number generators.\n\n steps_per_epoch (int): Number of steps of interaction (state-action pairs) \n for the agent and the environment in each epoch.\n\n epochs (int): Number of epochs to run and train agent.\n\n replay_size (int): Maximum length of replay buffer.\n\n gamma (float): Discount factor. (Always between 0 and 1.)\n\n polyak (float): Interpolation factor in polyak averaging for target \n networks. Target networks are updated towards main networks \n according to:\n\n .. math:: \\\\theta_{\\\\text{targ}} \\\\leftarrow \n \\\\rho \\\\theta_{\\\\text{targ}} + (1-\\\\rho) \\\\theta\n\n where :math:`\\\\rho` is polyak. (Always between 0 and 1, usually \n close to 1.)\n\n pi_lr (float): Learning rate for policy.\n\n q_lr (float): Learning rate for Q-networks.\n\n batch_size (int): Minibatch size for SGD.\n\n start_steps (int): Number of steps for uniform-random action selection,\n before running real policy. Helps exploration.\n\n update_after (int): Number of env interactions to collect before\n starting to do gradient descent updates. Ensures replay buffer\n is full enough for useful updates.\n\n update_every (int): Number of env interactions that should elapse\n between gradient descent updates. Note: Regardless of how long \n you wait between updates, the ratio of env steps to gradient steps \n is locked to 1.\n\n act_noise (float): Stddev for Gaussian exploration noise added to \n policy at training time. (At test time, no noise is added.)\n\n num_test_episodes (int): Number of episodes to test the deterministic\n policy at the end of each epoch.\n\n max_ep_len (int): Maximum length of trajectory / episode / rollout.\n\n logger_kwargs (dict): Keyword args for EpochLogger.\n\n save_freq (int): How often (in terms of gap between epochs) to save\n the current policy and value function.\n\n \"\"\"\n\n #setup_pytorch_for_mpi() \n\n logger = EpochLogger(**logger_kwargs)\n logger.save_config(locals())\n\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n env, test_env = env_fn(), env_fn()\n obs_dim = env.observation_space.shape\n act_dim = env.action_space.shape[0]\n\n # Action limit for clamping: critically, assumes all dimensions share the same bound!\n act_limit = env.action_space.high[0]\n\n # Create actor-critic module and target networks\n ac = actor_critic(env.observation_space, env.action_space, **ac_kwargs)\n ac_targ = deepcopy(ac)\n\n def save_target_actor_model(checkpoint_file):\n logger.log('... Saving target actor model ...')\n checkpoint_file += \"_target_actor.model\"\n torch.save({'state_dict': ac_targ.pi.state_dict()},\n os.path.normpath(checkpoint_file))\n logger.log(\"Saved model to file:{}\".format(checkpoint_file))\n\n def save_target_critic_model(checkpoint_file):\n checkpoint_file += \"_target_critic.model\"\n torch.save({'state_dict': ac_targ.q.state_dict()},\n os.path.normpath(checkpoint_file))\n logger.log(\"Saved model to file:{}\".format(checkpoint_file))\n\n def load_target_actor_model(checkpoint_file):\n checkpoint_file += \"_target_actor.model\"\n\n checkpoint = torch.load(os.path.normpath(checkpoint_file))\n ac_targ.pi.load_state_dict(checkpoint['state_dict'])\n logger.log(\"Loaded file:{}\".format(checkpoint_file))\n\n\n def load_target_critic_model(checkpoint_file):\n logger.log('... Loading target critic model ...')\n checkpoint_file += \"_target_critic.model\"\n\n checkpoint = torch.load(os.path.normpath(checkpoint_file))\n ac_targ.q.load_state_dict(checkpoint['state_dict'])\n logger.log(\"Loaded file:{}\".format(checkpoint_file))\n\n\n # Freeze target networks with respect to optimizers (only update via polyak averaging)\n for p in ac_targ.parameters():\n p.requires_grad = False\n\n tot_time = 0\n iters_so_far = 0\n ep_so_far = 0\n prev_ep_so_far = 0\n timesteps_so_far = 0\n\n lenbuffer = deque(maxlen=100)\n rewbuffer = deque(maxlen=100)\n\n #sync_params(ac)\n\n # Experience buffer\n replay_buffer = ReplayBuffer(obs_dim=obs_dim, act_dim=act_dim, size=replay_size)\n\n # Count variables (protip: try to get a feel for how different size networks behave!)\n var_counts = tuple(core.count_vars(module) for module in [ac.pi, ac.q])\n logger.log('\\nNumber of parameters: \\t pi: %d, \\t q: %d\\n'%var_counts)\n\n # Set up function for computing DDPG Q-loss\n def compute_loss_q(data):\n o, a, r, o2, d = data['obs'], data['act'], data['rew'], data['obs2'], data['done']\n\n q = ac.q(o,a)\n\n # Bellman backup for Q function\n with torch.no_grad():\n q_pi_targ = ac_targ.q(o2, ac_targ.pi(o2))\n backup = r + gamma * (1 - d) * q_pi_targ\n\n # MSE loss against Bellman backup\n loss_q = ((q - backup)**2).mean()\n\n # Useful info for logging\n loss_info = dict(QVals=q.detach().numpy())\n\n return loss_q, loss_info\n\n # Set up function for computing DDPG pi loss\n def compute_loss_pi(data):\n o = data['obs']\n q_pi = ac.q(o, ac.pi(o))\n return -q_pi.mean()\n\n # Set up optimizers for policy and q-function\n pi_optimizer = Adam(ac.pi.parameters(), lr=pi_lr)\n q_optimizer = Adam(ac.q.parameters(), lr=q_lr)\n\n def save_actor_model(checkpoint_file):\n #opt_file = checkpoint_file + \"_actor_opt.model\"\n checkpoint_file += \"_actor.model\"\n \n saves = {\n 'state_dict' : ac.pi.state_dict(),\n 'optimizer' : pi_optimizer.state_dict(),\n }\n torch.save(saves, os.path.normpath(checkpoint_file))\n #torch.save(pi_optimizer, os.path.normpath(opt_file))\n logger.log(\"Saved model to file:{}\".format(checkpoint_file))\n\n def save_critic_model(checkpoint_file):\n #logger.log('... Saving critic model ...')\n opt_file = checkpoint_file + \"_critic_opt.model\"\n checkpoint_file += \"_critic.model\"\n saves = {\n 'state_dict' : ac.q.state_dict(),\n 'optimizer' : q_optimizer.state_dict(),\n }\n torch.save(saves, os.path.normpath(checkpoint_file))\n #torch.save(q_optimizer, os.path.normpath(opt_file))\n logger.log(\"Saved model to file:{}\".format(checkpoint_file))\n\n\n def save_everything(checkpoint_file):\n #checkpoint_file += \"_various_NNs.model\"\n checkpoint_file = \"Trials/all.tar\"\n chk = {\n 'actor_network' : ac.pi.state_dict(),\n 'critic_network' : ac.q.state_dict(),\n 'target_actor_network' : ac_targ.pi.state_dict(),\n 'target_critic_network' : ac_targ.q.state_dict(),\n 'pi_optimizer' : pi_optimizer.state_dict(),\n 'q_optimizer' : q_optimizer.state_dict(),\n }\n torch.save(chk, os.path.normpath(checkpoint_file))\n logger.log(\"Saved model to file:{}\".format(checkpoint_file))\n \n def load_everything(checkpoint_file):\n #checkpoint_file += \"_various_NNs.model\"\n checkpoint_file = \"Trials/all.tar\"\n checkpoint = torch.load(os.path.normpath(checkpoint_file))\n \n ac.pi.load_state_dict(checkpoint['actor_network'])\n ac.q.load_state_dict(checkpoint['critic_network'])\n ac_targ.pi.load_state_dict(checkpoint['target_actor_network'])\n ac_targ.q.load_state_dict(checkpoint['target_critic_network'])\n pi_optimizer.load_state_dict(checkpoint['pi_optimizer'])\n q_optimizer.load_state_dict(checkpoint['q_optimizer'])\n\n logger.log(\"Loaded file:{}\".format(checkpoint_file))\n\n\n def load_actor_model(checkpoint_file):\n #logger.log(\"... loading actor model ...\")\n #opt_file = checkpoint_file + \"_actor_opt.model\"\n checkpoint_file += \"_actor.model\"\n\n\n checkpoint = torch.load(os.path.normpath(checkpoint_file))\n ac.pi.load_state_dict(checkpoint['state_dict'])\n #for p in ac.pi.parameters():\n # p.requires_grad = True\n #pi_optimizer = Adam(ac.pi.parameters(), lr=pi_lr)\n pi_optimizer.load_state_dict(checkpoint['optimizer'])\n #ac.pi = torch.load(os.path.normpath(checkpointfile))\n #pi_optimizer = torch.load(os.path.normpath(opt_file))\n\n logger.log(\"Loaded file:{}\".format(checkpoint_file))\n\n\n def load_critic_model(checkpoint_file):\n #opt_file = checkpoint_file + \"_critic_opt.model\"\n checkpoint_file += \"_critic.model\"\n\n checkpoint = torch.load(os.path.normpath(checkpoint_file))\n \n ac.q.load_state_dict(checkpoint['state_dict'])\n #for p in ac.q.parameters():\n # p.requires_grad = True\n\n #q_optimizer = Adam(ac.q.parameters(), lr = q_lr)\n q_optimizer.load_state_dict(checkpoint['optimizer'])\n #ac.q = torch.load(os.path.normpath(checkpoint_file))\n #q_optimizer = torch.load(os.path.normpath(opt_file))\n logger.log(\"Loaded file:{}\".format(checkpoint_file))\n\n\n\n\n # Set up model saving\n logger.setup_pytorch_saver(ac)\n if restore_model_from_file == 1:\n #pi_optimizer = None\n #q_optimizer = None\n base_path = os.path.dirname(os.path.abspath(__file__))\n model_f = os.path.normpath(\n base_path + \"/../../../\" + save_prefix + '/models/' + save_prefix + \"_afterIter_\" + str(\n load_after_iters))\n model_buff = os.path.normpath(\n base_path + \"/../../../\" + save_prefix + '/buffers/' + save_prefix + \"_afterIter_\" + str(\n load_after_iters))\n \n #ac = torch.load('/home/leonidas/Desktop/data/ddpg/ddpg_s0/pyt_save/model.pt')\n #load_actor_model(model_f)\n #load_critic_model(model_f)\n load_everything(model_f)\n #load_target_actor_model(model_f)\n #load_target_critic_model(model_f)\n #ac_targ = deepcopy(ac)\n\n replay_buffer.load_buffer(model_buff)\n update_after = 0\n logger.log(\"... Loading Complete ...\")\n '''logger.log(\"---------- Pi optimizer: ----------\")\n for var in pi_optimizer.state_dict():\n print(var, \"\\t\", pi_optimizer.state_dict()[var])\n\n logger.log(\"---------- Q optimizer: ----------\")\n for var in q_optimizer.state_dict():\n print(var, \"\\t\", q_optimizer.state_dict()[var])\n #logger.log(replay_buffer.act_buf)'''\n data = genfromtxt(save_prefix + '/test_after_Iter' + str(load_after_iters) + '.csv', delimiter=',')\n for i in range(len(data)):\n data_vector = data[i]\n ep_so_far = int(data_vector[0])\n timesteps_so_far = int(data_vector[1])\n iters_so_far = int(data_vector[2])\n time_elapsed = int(data_vector[3])\n lenbuffer.append(int(data_vector[4]))\n rewbuffer.append(int(data_vector[5]))\n var_counts = tuple(core.count_vars(module) for module in [ac.pi, ac.q])\n logger.log('\\nLoaded Number of parameters: \\t pi: %d, \\t q: %d\\n'%var_counts)\n #sync_params(ac)\n #sync_params(ac_targ)\n\n\n def update(data):\n # First run one gradient descent step for Q.\n q_optimizer.zero_grad()\n loss_q, loss_info = compute_loss_q(data)\n loss_q.backward()\n #mpi_avg_grads(ac.q.q)\n q_optimizer.step()\n\n # Freeze Q-network so you don't waste computational effort \n # computing gradients for it during the policy learning step.\n for p in ac.q.parameters():\n p.requires_grad = False\n\n # Next run one gradient descent step for pi.\n pi_optimizer.zero_grad()\n loss_pi = compute_loss_pi(data)\n loss_pi.backward()\n #mpi_avg_grads(ac.pi.pi)\n pi_optimizer.step()\n\n # Unfreeze Q-network so you can optimize it at next DDPG step.\n for p in ac.q.parameters():\n p.requires_grad = True\n\n # Record things\n logger.store(LossQ=loss_q.item(), LossPi=loss_pi.item(), **loss_info)\n\n # Finally, update target networks by polyak averaging.\n with torch.no_grad():\n for p, p_targ in zip(ac.parameters(), ac_targ.parameters()):\n # NB: We use an in-place operations \"mul_\", \"add_\" to update target\n # params, as opposed to \"mul\" and \"add\", which would make new tensors.\n p_targ.data.mul_(polyak)\n p_targ.data.add_((1 - polyak) * p.data)\n\n def get_action(o, noise_scale):\n a = ac.act(torch.as_tensor(o, dtype=torch.float32))\n a += noise_scale * np.random.randn(act_dim)\n return np.clip(a, -act_limit, act_limit)\n\n def test_agent():\n for j in range(num_test_episodes):\n o, d, ep_ret, ep_len = test_env.reset(), False, 0, 0\n while not(d or (ep_len == max_ep_len)):\n # Take deterministic actions at test time (noise_scale=0)\n o, r, d, _ = test_env.step(get_action(o, 0))\n ep_ret += r\n ep_len += 1\n logger.store(TestEpRet=ep_ret, TestEpLen=ep_len)\n\n def flatten_lists(listoflists):\n return [el for list_ in listoflists for el in list_] \n\n # Prepare for interaction with environment\n total_steps = steps_per_epoch * epochs\n start_time = time.time()\n o, ep_ret, ep_len = env.reset(), 0, 0\n epoch = iters_so_far\n episodes = 0\n\n\n ep_ret_arr = []\n ep_len_arr = []\n # Main loop: collect experience in env and update/log each epoch\n for t in range(total_steps):\n if t % steps_per_epoch == 0:\n logger.log(\"********** Iteration %i ************\" % epoch)\n ep_ret_arr = []\n ep_len_arr = [] \n # Until start_steps have elapsed, randomly sample actions\n # from a uniform distribution for better exploration. Afterwards, \n # use the learned policy (with some noise, via act_noise). \n if t > start_steps:\n a = get_action(o, act_noise)\n else:\n a = env.action_space.sample()\n\n # Step the env\n o2, r, d, _ = env.step(a)\n ep_ret += r\n ep_len += 1\n\n # Ignore the \"done\" signal if it comes from hitting the time\n # horizon (that is, when it's an artificial terminal signal\n # that isn't based on the agent's state)\n d = False if ep_len==max_ep_len else d\n if d:\n episodes += 1\n\n # Store experience to replay buffer\n replay_buffer.store(o, a, r, o2, d)\n\n # Super critical, easy to overlook step: make sure to update \n # most recent observation!\n o = o2\n\n # End of trajectory handling\n if d or (ep_len == max_ep_len):\n logger.store(EpRet=ep_ret, EpLen=ep_len)\n ep_ret_arr.append(ep_ret)\n ep_len_arr.append(ep_len)\n o, ep_ret, ep_len = env.reset(), 0, 0\n\n # Update handling\n if t >= update_after and t % update_every == 0:\n for _ in range(update_every):\n batch = replay_buffer.sample_batch(batch_size)\n update(data=batch)\n\n # End of epoch handling\n if (t+1) % steps_per_epoch == 0:\n epoch += 1\n\n # Save model\n if (epoch % save_freq == 0) or (epoch == epochs):\n logger.save_state({'env': env}, None)\n\n # Test the performance of the deterministic version of the agent.\n test_agent()\n\n lrlocal = (ep_len_arr, ep_ret_arr)\n listoflrpairs = MPI.COMM_WORLD.allgather(lrlocal)\n lens, rews = map(flatten_lists, zip(*listoflrpairs))\n lenbuffer.extend(lens)\n rewbuffer.extend(rews)\n\n prev_ep_so_far = ep_so_far\n ep_so_far += len(lens)\n timesteps_so_far += sum(lens)\n iters_so_far += 1\n\n # Log info about epoch\n logger.log_tabular(\"EpLenMean\", np.mean(lenbuffer))\n logger.log_tabular(\"EpRewMean\", np.mean(rewbuffer))\n logger.log_tabular('Epoch', epoch)\n logger.log_tabular(\"EpSoFar\", ep_so_far)\n logger.log_tabular('EpthisIter', len(lens))\n logger.log_tabular('EpRet', with_min_and_max=True)\n logger.log_tabular('TestEpRet', with_min_and_max=True)\n logger.log_tabular('EpLen', average_only=True)\n logger.log_tabular('TestEpLen', average_only=True)\n logger.log_tabular('TotalEnvInteracts', t)\n logger.log_tabular('QVals', with_min_and_max=True)\n logger.log_tabular('LossPi', average_only=True)\n logger.log_tabular('LossQ', average_only=True)\n logger.log_tabular('Time', time.time()-start_time)\n logger.log_tabular('BufferSize', replay_buffer.size)\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n f = open(save_prefix + \"/training_rewards.txt\", \"a+\")\n g = open(save_prefix + \"/training_episode_lengths.txt\", \"a+\")\n h = open(save_prefix + \"/training_mean_reward.txt\", \"a+\")\n k = open(save_prefix + \"/training_mean_lengths.txt\", \"a+\")\n l = open(save_prefix + \"/iterations.txt\", \"a+\")\n m = open(save_prefix + \"/timesteps.txt\", \"a+\")\n \n for i in range((ep_so_far - prev_ep_so_far)):\n f.write(\"Episode %d \" % (prev_ep_so_far + i))\n f.write(\"Reward %d\\r\\n\" % rews[i])\n g.write(\"Episode %d \" % (prev_ep_so_far + i))\n g.write(\"Length %d\\r\\n\" % lens[i])\n \n h.write(\"Episode %d \" % ep_so_far)\n h.write(\"Reward %d\\r\\n\" % np.mean(rews))\n k.write(\"Episode %d \" % ep_so_far)\n k.write(\"Length %d\\r\\n\" % np.mean(lens))\n\n if iters_so_far % save_after == 0:\n l.write(\"%d\\r\\n\" % iters_so_far)\n m.write(\"%d\\r\\n\" % t)\n \n\n f.close()\n g.close()\n k.close()\n h.close()\n l.close()\n m.close()\n\n logger.dump_tabular()\n \n if MPI.COMM_WORLD.Get_rank() == 0 and iters_so_far % save_after == 0:\n\n '''logger.log(\"---------- Pi optimizer: ----------\")\n for var in pi_optimizer.state_dict():\n print(var, \"\\t\", pi_optimizer.state_dict()[var])\n\n logger.log(\"---------- Q optimizer: ----------\")\n for var in q_optimizer.state_dict():\n print(var, \"\\t\", q_optimizer.state_dict()[var])'''\n base_path = os.path.dirname(os.path.abspath(__file__))\n model_f = os.path.normpath(\n base_path + '/../../../' + save_prefix + '/models/' + save_prefix + \"_afterIter_\" + str(\n iters_so_far))\n model_buff = os.path.normpath(\n base_path + \"/../../../\" + save_prefix + '/buffers/' + save_prefix + \"_afterIter_\" + str(\n iters_so_far))\n #save_actor_model(model_f)\n #save_critic_model(model_f)\n #save_target_actor_model(model_f)\n #save_target_critic_model(model_f)\n save_everything(model_f)\n replay_buffer.save_buffer(model_buff)\n logger.log(\"... Saving Complete ...\")\n #logger.log(replay_buffer.act_buf)\n if episodes < 100:\n size = episodes\n else:\n size = 100\n asd = np.zeros((size, 6), dtype = np.int32)\n for i in range(size):\n asd[i] = [ep_so_far, timesteps_so_far, iters_so_far, tot_time, lenbuffer[i], rewbuffer[i]]\n np.savetxt(save_prefix + '/test_after_Iter' + str(iters_so_far) + '.csv', asd, delimiter = \",\")\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('restore', type=int, default=1)\n parser.add_argument('load_iters', type=int, default=1)\n parser.add_argument('--env', type=str, default='Pendulum-v0')\n parser.add_argument('--cpu', type=int, default=2)\n parser.add_argument('--hid', type=int, default=312)\n parser.add_argument('--l', type=int, default=2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--seed', '-s', type=int, default=0)\n parser.add_argument('--epochs', type=int, default=825)\n parser.add_argument('--exp_name', type=str, default='ddpg')\n args = parser.parse_args()\n\n #mpi_fork(args.cpu)\n\n from utils.run_utils import setup_logger_kwargs\n logger_kwargs = setup_logger_kwargs(args.exp_name, args.seed)\n\n load_iters = args.load_iters\n\n\n if args.load_iters == 1:\n \twith open(args.env + '/iterations.txt', 'r') as f:\n \t\tlines = f.read().splitlines()\n \t\tlast_iter = int(lines[-1])\n \t\tload_iters = last_iter\n\t\n ddpg(lambda : gym.make('Pendulum-v0'), actor_critic=core.MLPActorCritic,\n ac_kwargs=dict(hidden_sizes=[args.hid]*args.l), \n gamma=args.gamma, seed=args.seed, epochs=args.epochs,\n logger_kwargs=logger_kwargs, save_prefix = args.env, \n restore_model_from_file = args.restore, load_after_iters = load_iters)\n\n\n","sub_path":"algos/pytorch/ddpg/ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":26377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"436135210","text":"# -*- coding: utf-8 -*-\n# pragma pylint: disable=unused-argument, no-self-use\n'''\nCreated on 2020/10/03\n\nCommon lib for QRadar Assets API call\n'''\nfrom datetime import datetime\nimport base64, json\n\nQ_API_ASSETS = \"https://{0}/api/asset_model/assets\"\nQ_UI_ASSET = \"https://{0}/console/do/assetprofile/AssetDetails?dispatch=viewAssetDetails&assetId={1}&listName=vulnList\"\nQ_FLT_IP_ADDR = 'interfaces(ip_addresses(value)) in ({0})'\nQ_FLT_VULN_CNT = \"vulnerability_count {0}\"\nQ_FLT_CVSS_SUM = \"risk_score_sum {0}\"\nDEFAULT_RANGE = '0-49'\n\nHTTP_OK = 200\n\ndef get_qradar_auth_headers(config):\n headers = {'Accept': 'application/json',\n 'Content-Type': 'application/json' }\n if config.get('username') and config.get('password'):\n ba = base64.b64encode((config.get('username') + \":\" + config.get('password')).encode('utf-8'))\n headers['Authorization'] = \"Basic \" + ba.decode('utf-8')\n elif config.get('authtoken'):\n headers['SEC'] = config.get('authtoken')\n return headers\n\ndef get_ip_addr_filter(comma_separated_ip_list):\n ip_addrs = comma_separated_ip_list.split(',')\n quoted_ip_addrs = [] \n for line in ip_addrs:\n quoted_ip_addrs.append('\"{0}\"'.format(line.strip()))\n return Q_FLT_IP_ADDR.format(\",\".join(quoted_ip_addrs))\n\ndef get_cvss_sum_filter(cvss_sum):\n return Q_FLT_CVSS_SUM.format(cvss_sum)\n\ndef get_vuln_count_filter(vuln_count):\n return Q_FLT_VULN_CNT.format(vuln_count)\n\ndef execute_qradar_query(config, req_common, asset_filter, result_range = DEFAULT_RANGE):\n \"\"\"\n in:\n asset_filter: QRadar Assets filter expression, one of the following:\n One or more (, separated) IP addresses\n Aggregated CVSS. example: >10\n Vulnerability count. example: >5\n result_range:\n 0-49, etc\n out: results dict\n state: Success, Failed\n code: Status code from the QRadar REST API endpoint\n reason: Failed reason\n content: assets array of dict\n content_range: 0-1/2, etc\n \"\"\"\n try:\n headers = get_qradar_auth_headers(config)\n headers['Range'] = \"items={0}\".format(result_range if result_range else DEFAULT_RANGE)\n params = { 'filter': asset_filter }\n r = req_common.execute_call_v2('GET', Q_API_ASSETS.format(config.get('host')),\n headers=headers, params=params,\n verify=config.get('verify_cert'))\n if r.status_code == HTTP_OK:\n buf = r.headers.get('content-range')\n content_range = buf[buf.find(' ')+1:] if buf else None\n assets = json.loads(r.text)\n content = reformat_assets(config, assets)\n return {\n 'state': 'Success',\n 'code': r.status_code,\n 'content': content,\n 'content_range': content_range\n }\n else:\n return {\n 'state': 'Failed',\n 'code': r.status_code,\n 'reason': r.reason\n }\n except Exception as e:\n return {\n 'state': 'Failed',\n 'reason': e\n }\n\ndef reformat_assets(config, assets):\n '''\n in: QRadar Assets API JSON output\n out: Reformatted Asset JSON\n Asset Keys = [ 'id', 'asset_url', 'interfaces', 'hostnames', 'given_name', 'asset_name',\n 'aggregated_cvss', 'vulnerability_count', 'users' ]\n '''\n out_assets = []\n\n for asset in assets:\n out_asset = {}\n \n out_asset['id'] = asset.get('id')\n out_asset['asset_url'] = Q_UI_ASSET.format(config.get('host'), asset.get('id'))\n out_asset['aggregated_cvss'] = asset.get('risk_score_sum')\n out_asset['vulnerability_count'] = asset.get('vulnerability_count')\n # get interfaces information: ip & mac\n intfs = asset.get('interfaces')\n if intfs:\n out_intfs = []\n for intf in intfs:\n line = {}\n line['mac'] = intf.get('mac_address')\n ips = []\n for ip in intf.get('ip_addresses'):\n ips.append(ip.get('value'))\n line['ip'] = '|'.join(ips) \n out_intfs.append(\"{0} ({1})\".format(line.get('ip'), line.get('mac')))\n out_asset['interfaces'] = \"\\n\".join(out_intfs)\n # get host names: netbios, dns or ip\n hosts = asset.get('hostnames')\n if hosts:\n out_hosts = []\n for host in hosts:\n if host.get('type').upper() == 'NETBIOS':\n out_hosts.append(\"{0} (netbios)\".format(host.get('name')))\n elif host.get('type').upper() == 'DNS':\n out_hosts.append(\"{0} (dns)\".format(host.get('name')))\n out_asset['hostnames'] = \"\\n\".join(out_hosts)\n # get values from properties\n props = asset.get('properties')\n if props:\n for prop in props:\n if prop.get('name') == 'Given Name':\n out_asset['given_name'] = prop.get('value')\n elif prop.get('name') == 'Unified Name':\n out_asset['asset_name'] = prop.get('value')\n # get user names\n users = asset.get('users')\n if users:\n out_users = []\n tmp_users = []\n for user in users:\n tmp_user = {}\n last_seen_profiler = user.get('last_seen_profiler')\n last_seen_scanner = user.get('last_seen_scanner')\n last_seen = last_seen_profiler if last_seen_profiler else last_seen_scanner\n last_seen_date = datetime.fromtimestamp(int(last_seen)/1000)\n tmp_user['username'] = user.get('username')\n tmp_user['last_seen'] = last_seen_date\n tmp_users.append(tmp_user)\n\n sorted_users = sorted(tmp_users, key=lambda x:x['last_seen'], reverse=True)\n for sorted_user in sorted_users:\n out_users.append(\"{0} (last seen: {1})\".format(sorted_user.get('username'), sorted_user.get('last_seen')))\n out_asset['users'] = \"\\n\".join(out_users)\n\n out_assets.append(out_asset)\n \n return out_assets","sub_path":"fn_qradar_asset_search/fn_qradar_asset_search/util/qradar_assets.py","file_name":"qradar_assets.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"41817735","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.6/dist-packages/queries/validation.py\n# Compiled at: 2010-05-09 07:06:47\ntry:\n set\nexcept NameError:\n from sets import Set as set\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import models\nfrom django.forms.models import BaseModelForm, BaseModelFormSet, fields_for_model, _get_foreign_key\nfrom queries.options import flatten_fieldsets, BaseModelQuery\nfrom queries.options import HORIZONTAL, VERTICAL\n__all__ = [\n 'validate']\n\ndef validate(cls, model):\n \"\"\"\n Does basic ModelQuery option validation. Calls custom validation\n classmethod in the end if it is provided in cls. The signature of the\n custom validation classmethod should be: def validate(cls, model).\n \"\"\"\n models.get_apps()\n opts = model._meta\n validate_base(cls, model)\n if hasattr(cls, 'list_display'):\n check_isseq(cls, 'list_display', cls.list_display)\n for (idx, field) in enumerate(cls.list_display):\n if not callable(field):\n if not hasattr(cls, field):\n if not hasattr(model, field):\n try:\n opts.get_field(field)\n except models.FieldDoesNotExist:\n raise ImproperlyConfigured('%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r.' % (\n cls.__name__, idx, field, cls.__name__, model._meta.object_name))\n\n else:\n f = fetch_attr(cls, model, opts, 'list_display[%d]' % idx, field)\n if isinstance(f, models.ManyToManyField):\n raise ImproperlyConfigured(\"'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported.\" % (\n cls.__name__, idx, field))\n\n if hasattr(cls, 'list_display_links'):\n check_isseq(cls, 'list_display_links', cls.list_display_links)\n for (idx, field) in enumerate(cls.list_display_links):\n fetch_attr(cls, model, opts, 'list_display_links[%d]' % idx, field)\n if field not in cls.list_display:\n raise ImproperlyConfigured(\"'%s.list_display_links[%d]'refers to '%s' which is not defined in 'list_display'.\" % (\n cls.__name__, idx, field))\n\n if hasattr(cls, 'list_filter'):\n check_isseq(cls, 'list_filter', cls.list_filter)\n for (idx, field) in enumerate(cls.list_filter):\n get_field(cls, model, opts, 'list_filter[%d]' % idx, field)\n\n if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int):\n raise ImproperlyConfigured(\"'%s.list_per_page' should be a integer.\" % cls.__name__)\n if hasattr(cls, 'list_editable') and cls.list_editable:\n check_isseq(cls, 'list_editable', cls.list_editable)\n for (idx, field_name) in enumerate(cls.list_editable):\n try:\n field = opts.get_field_by_name(field_name)[0]\n except models.FieldDoesNotExist:\n raise ImproperlyConfigured(\"'%s.list_editable[%d]' refers to a field, '%s', not defined on %s.\" % (\n cls.__name__, idx, field_name, model.__name__))\n\n if field_name not in cls.list_display:\n raise ImproperlyConfigured(\"'%s.list_editable[%d]' refers to '%s' which is not defined in 'list_display'.\" % (\n cls.__name__, idx, field_name))\n if field_name in cls.list_display_links:\n raise ImproperlyConfigured(\"'%s' cannot be in both '%s.list_editable' and '%s.list_display_links'\" % (\n field_name, cls.__name__, cls.__name__))\n if not cls.list_display_links:\n if cls.list_display[0] in cls.list_editable:\n raise ImproperlyConfigured(\"'%s.list_editable[%d]' refers to the first field in list_display, '%s', which can't be used unless list_display_links is set.\" % (\n cls.__name__, idx, cls.list_display[0]))\n raise field.editable or ImproperlyConfigured(\"'%s.list_editable[%d]' refers to a field, '%s', which isn't editable through the query.\" % (\n cls.__name__, idx, field_name))\n\n if hasattr(cls, 'search_fields'):\n check_isseq(cls, 'search_fields', cls.search_fields)\n if cls.date_hierarchy:\n f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy)\n if not isinstance(f, (models.DateField, models.DateTimeField)):\n raise ImproperlyConfigured(\"'%s.date_hierarchy is neither an instance of DateField nor DateTimeField.\" % cls.__name__)\n if cls.ordering:\n check_isseq(cls, 'ordering', cls.ordering)\n for (idx, field) in enumerate(cls.ordering):\n if field == '?' and len(cls.ordering) != 1:\n raise ImproperlyConfigured(\"'%s.ordering' has the random ordering marker '?', but contains other fields as well. Please either remove '?' or the other fields.\" % cls.__name__)\n if field == '?':\n continue\n if field.startswith('-'):\n field = field[1:]\n if '__' in field:\n continue\n get_field(cls, model, opts, 'ordering[%d]' % idx, field)\n\n for attr in ('list_select_related', 'save_as', 'save_on_top'):\n if not isinstance(getattr(cls, attr), bool):\n raise ImproperlyConfigured(\"'%s.%s' should be a boolean.\" % (\n cls.__name__, attr))\n\n if hasattr(cls, 'inlines'):\n check_isseq(cls, 'inlines', cls.inlines)\n for (idx, inline) in enumerate(cls.inlines):\n if not issubclass(inline, BaseModelQuery):\n raise ImproperlyConfigured(\"'%s.inlines[%d]' does not inherit from BaseModelQuery.\" % (\n cls.__name__, idx))\n if not inline.model:\n raise ImproperlyConfigured(\"'model' is a required attribute of '%s.inlines[%d]'.\" % (\n cls.__name__, idx))\n if not issubclass(inline.model, models.Model):\n raise ImproperlyConfigured(\"'%s.inlines[%d].model' does not inherit from models.Model.\" % (\n cls.__name__, idx))\n validate_base(inline, inline.model)\n validate_inline(inline, cls, model)\n\n\ndef validate_inline(cls, parent, parent_model):\n if cls.fk_name:\n f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name)\n if not isinstance(f, models.ForeignKey):\n raise ImproperlyConfigured(\"'%s.fk_name is not an instance of models.ForeignKey.\" % cls.__name__)\n for attr in ('extra', 'max_num'):\n if not isinstance(getattr(cls, attr), int):\n raise ImproperlyConfigured(\"'%s.%s' should be a integer.\" % (\n cls.__name__, attr))\n\n if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet):\n raise ImproperlyConfigured(\"'%s.formset' does not inherit from BaseModelFormSet.\" % cls.__name__)\n if hasattr(cls, 'exclude') and cls.exclude:\n fk = _get_foreign_key(parent_model, cls.model, can_fail=True)\n if fk and fk.name in cls.exclude:\n raise ImproperlyConfigured(\"%s cannot exclude the field '%s' - this is the foreign key to the parent model %s.\" % (\n cls.__name__, fk.name, parent_model.__name__))\n\n\ndef validate_base(cls, model):\n opts = model._meta\n if hasattr(cls, 'raw_id_fields'):\n check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)\n for (idx, field) in enumerate(cls.raw_id_fields):\n f = get_field(cls, model, opts, 'raw_id_fields', field)\n if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):\n raise ImproperlyConfigured(\"'%s.raw_id_fields[%d]', '%s' must be either a ForeignKey or ManyToManyField.\" % (\n cls.__name__, idx, field))\n\n if cls.fields:\n check_isseq(cls, 'fields', cls.fields)\n for field in cls.fields:\n check_formfield(cls, model, opts, 'fields', field)\n\n if cls.fieldsets:\n raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__)\n if len(cls.fields) > len(set(cls.fields)):\n raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__)\n if cls.fieldsets:\n check_isseq(cls, 'fieldsets', cls.fieldsets)\n for (idx, fieldset) in enumerate(cls.fieldsets):\n check_isseq(cls, 'fieldsets[%d]' % idx, fieldset)\n if len(fieldset) != 2:\n raise ImproperlyConfigured(\"'%s.fieldsets[%d]' does not have exactly two elements.\" % (\n cls.__name__, idx))\n check_isdict(cls, 'fieldsets[%d][1]' % idx, fieldset[1])\n if 'fields' not in fieldset[1]:\n raise ImproperlyConfigured(\"'fields' key is required in %s.fieldsets[%d][1] field options dict.\" % (\n cls.__name__, idx))\n\n flattened_fieldsets = flatten_fieldsets(cls.fieldsets)\n if len(flattened_fieldsets) > len(set(flattened_fieldsets)):\n raise ImproperlyConfigured('There are duplicate field(s) in %s.fieldsets' % cls.__name__)\n for field in flattened_fieldsets:\n check_formfield(cls, model, opts, \"fieldsets[%d][1]['fields']\" % idx, field)\n\n if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm):\n raise ImproperlyConfigured('%s.form does not inherit from BaseModelForm.' % cls.__name__)\n if hasattr(cls, 'filter_vertical'):\n check_isseq(cls, 'filter_vertical', cls.filter_vertical)\n for (idx, field) in enumerate(cls.filter_vertical):\n f = get_field(cls, model, opts, 'filter_vertical', field)\n if not isinstance(f, models.ManyToManyField):\n raise ImproperlyConfigured(\"'%s.filter_vertical[%d]' must be a ManyToManyField.\" % (\n cls.__name__, idx))\n\n if hasattr(cls, 'filter_horizontal'):\n check_isseq(cls, 'filter_horizontal', cls.filter_horizontal)\n for (idx, field) in enumerate(cls.filter_horizontal):\n f = get_field(cls, model, opts, 'filter_horizontal', field)\n if not isinstance(f, models.ManyToManyField):\n raise ImproperlyConfigured(\"'%s.filter_horizontal[%d]' must be a ManyToManyField.\" % (\n cls.__name__, idx))\n\n if hasattr(cls, 'radio_fields'):\n check_isdict(cls, 'radio_fields', cls.radio_fields)\n for (field, val) in cls.radio_fields.items():\n f = get_field(cls, model, opts, 'radio_fields', field)\n if not (isinstance(f, models.ForeignKey) or f.choices):\n raise ImproperlyConfigured(\"'%s.radio_fields['%s']' is neither an instance of ForeignKey nor does have choices set.\" % (\n cls.__name__, field))\n if val not in (HORIZONTAL, VERTICAL):\n raise ImproperlyConfigured(\"'%s.radio_fields['%s']' is neither query.HORIZONTAL nor queries.VERTICAL.\" % (\n cls.__name__, field))\n\n if hasattr(cls, 'prepopulated_fields'):\n check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)\n for (field, val) in cls.prepopulated_fields.items():\n f = get_field(cls, model, opts, 'prepopulated_fields', field)\n if isinstance(f, (models.DateTimeField, models.ForeignKey,\n models.ManyToManyField)):\n raise ImproperlyConfigured(\"'%s.prepopulated_fields['%s']' is either a DateTimeField, ForeignKey or ManyToManyField. This isn't allowed.\" % (\n cls.__name__, field))\n check_isseq(cls, \"prepopulated_fields['%s']\" % field, val)\n for (idx, f) in enumerate(val):\n get_field(cls, model, opts, \"prepopulated_fields['%s'][%d]\" % (field, idx), f)\n\n\ndef check_isseq(cls, label, obj):\n if not isinstance(obj, (list, tuple)):\n raise ImproperlyConfigured(\"'%s.%s' must be a list or tuple.\" % (cls.__name__, label))\n\n\ndef check_isdict(cls, label, obj):\n if not isinstance(obj, dict):\n raise ImproperlyConfigured(\"'%s.%s' must be a dictionary.\" % (cls.__name__, label))\n\n\ndef get_field(cls, model, opts, label, field):\n try:\n return opts.get_field(field)\n except models.FieldDoesNotExist:\n raise ImproperlyConfigured(\"'%s.%s' refers to field '%s' that is missing from model '%s'.\" % (\n cls.__name__, label, field, model.__name__))\n\n\ndef check_formfield(cls, model, opts, label, field):\n if getattr(cls.form, 'base_fields', None):\n try:\n cls.form.base_fields[field]\n except KeyError:\n raise ImproperlyConfigured(\"'%s.%s' refers to field '%s' that is missing from the form.\" % (\n cls.__name__, label, field))\n\n else:\n fields = fields_for_model(model)\n try:\n fields[field]\n except KeyError:\n raise ImproperlyConfigured(\"'%s.%s' refers to field '%s' that is missing from the form.\" % (\n cls.__name__, label, field))\n\n return\n\n\ndef fetch_attr(cls, model, opts, label, field):\n try:\n return opts.get_field(field)\n except models.FieldDoesNotExist:\n pass\n\n try:\n return getattr(model, field)\n except AttributeError:\n raise ImproperlyConfigured(\"'%s.%s' refers to '%s' that is neither a field, method or property of model '%s'.\" % (\n cls.__name__, label, field, model.__name__))","sub_path":"pycfiles/django-queries-0.2.linux-i686.tar/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":13586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"372387979","text":"import pandas as pd\nfrom ast import literal_eval\nimport re\nfrom collections import defaultdict\n\ndata_src = \"data/amazon_sample.csv\"\ndata_sink = \"data/amazon_sample.csv\"\n\nword_dict_sink = \"data/count.json\"\nheadline_dict_sink = \"data/count_headline.json\"\nrare_word_replace=\"RAREWORD\"\nnumber_word_replace = \"NUMBER\"\n\ndef count_tokens(inp):\n lst = []\n for d in inp:\n lst += literal_eval(d)\n res = defaultdict(int)\n for t in lst:\n res[t] += 1\n return dict(res)\n\n\ndef get_rare(counter, threshold):\n rare_words = [w for w in counter if counter[w] <= threshold]\n return rare_words\n\n\ndef repl_one(rare_words, d):\n d = literal_eval(d)\n for it, t in enumerate(d):\n if t in rare_words:\n d[it] = rare_word_replace\n return d\n\ndef repl_numbers(d):\n d = literal_eval(d) if type(d) is str else d\n for it, t in enumerate(d):\n t = number_word_replace.join(re.split(\"\\d+?\\.\\d+\", t))\n t = number_word_replace.join(re.split(\"\\d+\", t))\n d[it] = t\n return str(d)\n\nif __name__ == \"__main__\":\n df = pd.read_csv(data_src)\n\n print(\"replace repl_numbers\")\n df[\"tokens\"] = df.tokens.map(repl_numbers)\n df[\"title_tokenized\"] = df.title_tokenized.map(repl_numbers)\n\n print(\"count tokens\")\n token_counter = count_tokens(df.tokens)\n headline_token_counter = count_tokens(df.title_tokenized)\n\n rare_tokens = get_rare(token_counter, 10)\n rare_title_tokens = get_rare(headline_token_counter, 10)\n\n print(\"replace tokens\")\n df['tokens_no_rare'] = df.tokens.map(lambda d: repl_one(rare_tokens, d))\n df['title_tokens_no_rare'] = df.title_tokenized.map(lambda d: repl_one(rare_title_tokens, d))\n df.to_csv(data_sink)\n print(\"ready\")","sub_path":"src/replace_rare_words_and_numbers.py","file_name":"replace_rare_words_and_numbers.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"91452034","text":"import random\n\n\nclass Hero:\n ammunition = 0\n action = None\n artifact = None\n\n def __init__(self, name, race, speed):\n self.name = name\n self.race = race\n self.speed = int(speed)\n \n def move(self):\n self.action.move(self.name, self.speed)\n \n def collect(self):\n self.artifact.collect(self.name, self.speed, self.ammunition)\n \n\nclass SimpleMove():\n\n def move(self, name, speed):\n print('{} moves at a speed {}'.format(name, speed))\n\n\nclass Fly():\n\n def move(self, name, speed):\n print('{} flies at a speed {}'.format(name, speed))\n\n\nclass FastSpeed():\n \n def collect(self, name, speed, ammunition):\n speed = speed * 2\n print('{} accelerated. His speed {}'.format(name, speed))\n \n\nclass SlowSpeed():\n \n def collect(self, name, speed, ammunition):\n speed = speed // 2\n print('{} slowed down. His speed {}'.format(name, speed))\n\n\nclass Shoot():\n \n def collect(self, name, speed, ammunition):\n p = random.randint(1, 10)\n ammunition += p\n print('{} found {} ammunition. His ammunition {}'.format(name, p, ammunition)) \n for i in range(p):\n print('{} shoot'.format(name))\n \n\nhalk = Hero('Halk', 'Human', '5')\nsuperman = Hero('Superman', 'Human', '10')\nherous = [halk, superman]\nfor hero in herous:\n for action in [SimpleMove(), Fly()]:\n hero.action = action\n hero.action.move(hero.name, hero.speed) \n for artifact in [FastSpeed(), SlowSpeed(), Shoot()]:\n hero.artifact = artifact\n hero.artifact.collect(hero.name, hero.speed, hero.ammunition)\n","sub_path":"Practice/S.Mikheev/Lec_2/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"136677828","text":"from lists.models import Item,List\nfrom django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\n\n\nclass ItemModelTest(TestCase):\n\n def test_display_only_items_for_that_list(self):\n current_list = List.objects.create()\n Item.objects.create(text='itemey 1',list=current_list)\n Item.objects.create(text='itemey 2',list=current_list)\n\n other_list = List.objects.create()\n Item.objects.create(text='other list item 1',list=other_list)\n Item.objects.create(text='other list item 2',list=other_list) \n\n response = self.client.get('/lists/%d/'%(current_list.id,))\n\n self.assertContains(response,'itemey 1')\n self.assertContains(response,'itemey 2')\n self.assertNotContains(response,'other list item 1')\n self.assertNotContains(response,'other list item 2')\n\n def test_cannot_save_empty_list_items(self):\n list_ = List.objects.create()\n item = Item.objects.create(text='',list=list_)\n with self.assertRaises(ValidationError):\n item.save()\n item.full_clean()\n \n def test_list_ordering(self):\n list1 = List.objects.create()\n item1 = Item.objects.create(text='i1',list=list1)\n item2 = Item.objects.create(text='i2',list=list1)\n item3 = Item.objects.create(text='i3',list=list1)\n self.assertEqual(\n list(Item.objects.all()),\n [item1,item2,item3]\n )\n\n def test_string_representation(self):\n item = Item(text='Some text')\n self.assertEqual(str(item),'Some text')\n\n def test_default_text(self):\n item = Item()\n self.assertEqual(item.text,'')\n\n def test_item_is_related_to_list(self):\n list_ = List.objects.create()\n item = Item()\n item.list = list_\n item.save()\n self.assertIn(item, list_.item_set.all())\n\n def test_duplicate_items_are_invalid(self):\n list_ = List.objects.create()\n Item.objects.create(list=list_,text='balabala')\n with self.assertRaises(ValidationError):\n item = Item(list=list_,text='balabala')\n item.full_clean()\n\n\n\n\nclass ListModelTest(TestCase):\n\n def test_get_absolute_url(self):\n list_ = List.objects.create()\n self.assertEqual(list_.get_absolute_url(),'/lists/%d/'%(list_.id,))\n\n\n\n\n\n\n","sub_path":"superlists/lists/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"156981490","text":"import dbl\nimport discord\nfrom discord.ext import commands\nimport asyncio\n\nclass DiscordBotList(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n self.dbltoken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU0MDAwMDU3ODM1MzM2NDk5MyIsImJvdCI6dHJ1ZSwiaWF0IjoxNTU2OTEzMDI3fQ.LD_0AfQkjKRJ7F9QlCOOdnmYnyGoMWTF19lEhr0TBi8'\n self.dblpy = dbl.Client(self.bot, self.dbltoken)\n self.updating = self.bot.loop.create_task(self.update_stats())\n\n async def update_stats(self):\n await self.bot.wait_until_ready()\n while self.bot.is_ready():\n try:\n await self.dblpy.post_guild_count()\n except Exception as e:\n print('[DBL] Failed to post server count\\n{}: {}'.format(type(e).__name__, e))\n await asyncio.sleep(1800)\n\ndef setup(bot):\n bot.add_cog(DiscordBotList(bot))","sub_path":"cogs/DiscordBotList.py","file_name":"DiscordBotList.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"394506656","text":"from time import sleep\n\nimport numpy as np\nfrom Boundaries import Boundaries\nfrom GeneralEnums import Field, Orientation, Information\nfrom Grid import Grid2\nfrom Fields import Fields2\nimport Constants as C\nfrom Simulation import Simulation\n\n\nif __name__ == \"__main__\":\n # change constants\n grid_size = C.GRID_SIZE - 1\n delta_t = 0.001\n\n u_matrix = np.full((grid_size + 1, grid_size), 0)\n v_matrix = np.full((grid_size, grid_size + 1), 0)\n p_matrix = np.full((grid_size + 1, grid_size + 1), 0)\n fields_matrix = Fields2(v_matrix, u_matrix, p_matrix)\n\n delta = np.full(grid_size + 1, 1/(grid_size + 1))\n delta_xy = Grid2(delta, delta)\n\n full_0 = np.full(grid_size + 1, 0)\n full_1 = np.full(grid_size + 1, 1)\n\n boundary_left = {Field.u: full_0, Field.v: full_0[1:], Field.p: full_0}\n boundary_right = {Field.u: full_0, Field.v: full_0[1:], Field.p: full_0}\n boundary_top = {Field.u: full_1[1:], Field.v: full_0, Field.p: full_0}\n boundary_bottom = {Field.u: full_0[1:], Field.v: full_0, Field.p: full_0}\n\n boundaries = Boundaries({Orientation.left: boundary_left,\n Orientation.right: boundary_right,\n Orientation.top: boundary_top,\n Orientation.bottom: boundary_bottom})\n\n sim = Simulation(fields_matrix, delta_xy, boundaries, delta_t, information=Information.all)\n sim.start()\n sleep(1000000)\n\n","sub_path":"CellsSimulation/tests/lead_driven_cavity.py","file_name":"lead_driven_cavity.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"219140433","text":"\nimport paho.mqtt.client as mqtt\nimport json\nimport ast\n# The callback for when the client receives a CONNACK response from the server.)\n\nbroker_cloud = 'iot.eclipse.org'\nbroker_fog = 'broker.hivemq.com'\n\n\n#create Client\nclient_fog = mqtt.Client()\nclient_fog.connect(broker_fog)\n\nclient_cloud = mqtt.Client()\nclient_cloud.connect(broker_cloud)\n\n\ndef on_messageRegistry(client, userdata, msg):\n print(\"Forward to Registry api_check_configurtion_changes\")\n data = ast.literal_eval(msg.payload.decode('utf-8'))\n platform_id = data[2]\n topic_name = platform_id + \"/response/registry/api_check_configuration_changes\"\n client_cloud.publish(topic_name, str(data))\n\n\n#On message for sub on /driver/response/filter/..\n\ndef on_messageFilter(client, userdata, msg):\n print('Forward to Collector api_get_states')\n data = json.loads(msg.payload.decode(\"utf-8\"))\n platform_id = data['platform_id']\n data = json.dumps(data)\n topic_name = platform_id + \"/response/collector/api_get_states\"\n client_cloud.publish(topic_name, data)\n\n\n#On message for registry/request/api-add-platform\ndef on_messageAPIAddPlatform(client, userdata, msg):\n print('Forward to Registry api_add_platform')\n data = msg.payload.decode('utf-8')\n data = json.loads(data)\n data = json.dumps(data)\n client_cloud.publish(\"registry/request/api_add_platform\", data)\n\nclient_fog.message_callback_add(\"driver/response/forwarder/api_check_configuration_changes\", on_messageRegistry)\nclient_fog.message_callback_add(\"filter/response/forwarder/api_get_states\", on_messageFilter)\nclient_fog.message_callback_add(\"registry/request/api_add_platform\", on_messageAPIAddPlatform)\n\n\nclient_fog.subscribe(\"driver/response/forwarder/api_check_configuration_changes\")\nclient_fog.subscribe(\"filter/response/forwarder/api_get_states\")\nclient_fog.subscribe(\"registry/request/api_add_platform\")\n\nclient_fog.loop_start()\nclient_cloud.loop_start()\n\nwhile True:\n continue\n","sub_path":"cross_platform/Api_Platform-master/forwarder.py","file_name":"forwarder.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"605671889","text":"import os.path\n\nfrom django.core import mail\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom send_instance.email import TemplateEmail\n\nfrom .models import Book\n\n\nclass BookEmail(TemplateEmail):\n\n def get_to(self):\n return [self.object.author_email]\n\n def get_subject(self):\n return 'New book added'\n\n\nclass TemplateEmailTest(TestCase):\n\n def setUp(self):\n self.book = Book.objects.create(\n name='Sample book',\n author_email='test@example.com',\n )\n\n def test_default_subject(self):\n email = TemplateEmail(self.book)\n self.assertEqual(email.get_subject(), unicode(self.book))\n\n def test_default_template(self):\n TemplateEmail(self.book, to=[self.book.author_email]).send()\n expected = \"ID: %s\\nBook name: Sample book\\nAuthor email: test@example.com\" % self.book.id\n self.assertIn(expected, mail.outbox[0].body)\n\n def test_custom_template(self):\n template_dirs = [\n os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'templates')),\n ]\n with override_settings(TEMPLATE_DIRS=template_dirs):\n TemplateEmail(self.book, to=[self.book.author_email]).send()\n expected = \"Book %s has been added.\" % self.book.name\n self.assertIn(expected, mail.outbox[0].body)\n\n def test_override_class(self):\n email = BookEmail(self.book).send()\n self.assertEquals(mail.outbox[0].subject, \"New book added\")\n self.assertEquals(mail.outbox[0].to, [self.book.author_email])\n","sub_path":"tests/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"} +{"seq_id":"325346487","text":"__author__ = 'NEC'\n# -*- coding:utf-8 -*-\n\n#!/usr/bin/env python\n#coding=utf-8\nimport traceback\nimport time;\nimport sys;\nimport logging;\n\nif not \"C:\\\\Users\\\\NEC\\\\PycharmProjects\\\\Snippet\\\\TimerScripts\" in sys.path:\n sys.path.append(\"C:\\\\Users\\\\NEC\\\\PycharmProjects\\\\Snippet\\\\TimerScripts\")\nif not 'BasicConfig' in sys.modules:\n BasicConfig = __import__('BasicConfig')\nelse :\n eval('import BasicConfig')\n BasicConfig = eval('reload(BasicConfig)')\nif not 'DbModule' in sys.modules:\n DbModule = __import__('DbModule')\nelse :\n eval('import DbModule')\n DbModule = eval('reload(DbModule)')\n\nclass ProxyManager:\n\n def __init__(self):\n print(\"init\")\n self.taskFlag = True;\n self.worklist = self.loadProxyRule();\n self.buildlogger()\n\n def buildlogger(self):\n self.logger = logging.getLogger('proxymanager')\n self.logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler('spam.log')\n fh.setLevel(logging.DEBUG)\n self.logger.addHandler(fh)\n\n def loadProxyRule(self):\n print(\"load from db\")\n\n def updateProxy(self):\n print(\"updating proxy rule\")\n\n def selfDetect(self):\n print(\"detecting proxy started\")\n while self.taskFlag:\n if len(self.worklist)==0:\n self.worklist = self.loadProxyRule();\n if len(self.worklist)==0:time.sleep(20);continue;\n workerid = self.worklist.pop()\n print(\"produce task\")\n time.sleep(2)\n print(\"detecting task end\")\n\n def detectworkder(self):\n print(\"working to update proxy\")\n\nif __name__ ==\"__main__\":\n proxyManager = ProxyManager();\n proxyManager.logger.info(\"ops\")\n print(\"main\")\n print(BasicConfig.mainconfig[\"db\"][\"dbname\"])","sub_path":"TimerScripts/ProxyManager.py","file_name":"ProxyManager.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"53"}