``). This is because iBook imposes\n\t a zero padding on the body element, and that cannot be controlled by the user; the introduction of the top level\n\t block element allows for suitable CSS adjustments.\n\n\t The CSS adjustment is done as follows: the :py:data:`.templates.BOOK_CSS` is extended with the exact\n\t padding values; these are retrieved (depending on the document type) from :py:data:`.config.DOCTYPE_INFO`. The\n\t expansion of :py:data:`.templates.BOOK_CSS` itself happens in the :py:meth:`.doc2epub.DocWrapper.process` method.\n\n\t Note that using simply a \"main\" element as a top level encapsulation is not a good approach, because some files (e.g., generated by\n\t bikeshed) already use that element, and there can be only one of those...\n\n\t 2. If a ``
`` element has the class name ``highlight``, the Readium extension to\n\t Chrome goes wild. That class name is used only for an internal processing of ReSpec; it is\n\t unused in the various, default CSS content. As a an emergency measure this class name is simply removed from the code, although,\n\t clearly, this is not the optimal way:-( But hopefully this will disappear and this hack can be\n\t removed, eventually.\n\n\t **Note**: this is an `acknowledged bug in Readium `__.\n\t When a newer release of Readium is deployed, this hack should be removed from the code.\n\n\t 3. Some readers *require* to have a ``type=\"text/css\"`` on the the link element for a CSS; otherwise the CSS\n\t is ignored. It is added (doesn't do any harm...)\n\n\t:param html: the object for the whole document\n\t:type html: :py:class:`xml.etree.ElementTree.ElementTree`\n\t\"\"\"\n\n\t# Hack #1\n\tbody = html.find(\".//body\")\n\n\tif len(html.findall(\".//div[@main='role']\")) == 0:\n\t\tmain = SubElement(body, \"div\")\n\t\tmain.set(\"role\", \"main\")\n\n\t\t# All children of body, except for main, should be re-parented to main and removed from body\n\t\t# Note: this is a workaround around what seems to be a bug in the html5parser. Indeed,\n\t\t# the direct creation of an Element object does not work; the SubElement method must be used\n\t\t# but this means that element should be avoided in the cycle below. Sigh...\n\t\tfor child in [x for x in body.findall(\"*\") if not (x.tag == \"div\" and x.get(\"role\", None) == \"main\")]:\n\t\t\tmain.append(child)\n\t\t\tbody.remove(child)\n\n\t# Hack #2\n\t# Change the \"highlight\" class name\n\t# noinspection PyShadowingNames\n\tdef _change_name(x):\n\t\treturn x if x != \"highlight\" else \"book_highlight\"\n\n\tfor pre in html.findall(\".//pre[@class]\"):\n\t\t# there may be several class names\n\t\tcl_names = pre.get(\"class\").split()\n\t\tnew_cl_names = map(_change_name, cl_names)\n\t\tpre.set(\"class\", \" \".join(new_cl_names))\n\n\t# Hack #3\n\t# Add the type=\"text/css\" for stylesheet elements\n\tfor lnk in html.findall(\".//link[@rel='stylesheet']\"):\n\t\tif \"type\" not in lnk.keys():\n\t\t\tlnk.set(\"type\", \"text/css\")\n\n","sub_path":"tr2epub/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"504110363","text":"#coding=utf-8\nimport tornado.web\nfrom handler.basehandler import BaseHandler\nfrom bin import base\n\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nclass EditProjectExperienceHandler(BaseHandler):\n @tornado.web.authenticated\n def post(self):\n job_id = self.get_argument(\"id\", \"\")\n project_name = self.get_argument(\"project_name\", \"\")\n project_starttime = self.get_argument(\"project_starttime\", \"\")\n project_endtime = self.get_argument(\"project_endtime\", \"\")\n project_detail = self.get_argument(\"project_detail\", \"\")\n values = dict(project_name=project_name,\n project_starttime=project_starttime,\n project_endtime=project_endtime,\n project_detail=project_detail\n )\n\n from optsql.updateMySQL import update_one_project_experience\n result = update_one_project_experience(id=job_id, values=values)\n if result:\n rtinfo = dict(status=0, result=result)\n else:\n rtinfo = dict(status=1, result=\"更改失败!\")\n self.write(base.get_json(rtinfo))","sub_path":"handler/project_experience/edit_project_experienct.py","file_name":"edit_project_experienct.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"482286741","text":"#공원id(p_id) -> 해당 공원에 있는 운동기구list를 가져오는 appi\nfrom flask_restx import Resource, reqparse\nfrom sqlalchemy.sql.type_api import NULLTYPE\nfrom ._m_equip import Mequip\nimport app\nfrom sqlalchemy import text\n\n\nparser = reqparse.RequestParser()\nparser.add_argument('id', help='공원 ID', type=int, required=True)\n\n@Mequip.route('/p_e_list')\nclass P_E_List(Resource):\n @Mequip.expect(parser)\n @Mequip.response(200, 'Success')\n @Mequip.response(500, 'Internal Server Error')\n def get(self):\n args = parser.parse_args()\n id = args['id']\n\n sql = 'SELECT * FROM equip WHERE p_id=:id'\n query = {\n 'id': id\n }\n rows = app.app.database.execute(text(sql), query).fetchall()\n \n #쿼리 결과가 null\n if not rows:\n return {\n 'code': 'error',\n 'message': '(no query results) error'\n }, 500\n \n retVal = [] \n for row in rows: \n r = { \n 'e_id' : row['e_id'],\n 'p_id' : row['p_id'],\n 'e_name' : row['e_name'],\n 'category' : row['category']\n }\n retVal.append(r)\n \n\n return { \n 'code':'successs', \n 'message':'',\n 'response': {\n 'List': retVal\n }\n }, 200\n\n \n \n \n","sub_path":"socien_api_server/route/__m_equip/p_e_list.py","file_name":"p_e_list.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"610103283","text":"\"\"\"Generic, basic gates (such as AND gates).\n\nThis is implemented as a set of callables which maintain their enumerated\nstate, and return a LUT object with the proper look up table for their function\nand number of bits (inputs).\"\"\"\n\n\nfrom .base import staticvariable\nfrom . import lut\n\n\n@staticvariable('cnt', 0)\ndef AND(bits=2, name=None):\n if not name:\n name = 'AND' + str(AND.cnt)\n AND.cnt += 1\n\n return lut.LUT(lut.generate_AND(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef OR(bits=2, name=None):\n if not name:\n name = 'OR' + str(OR.cnt)\n OR.cnt += 1\n\n return lut.LUT(lut.generate_OR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef NOR(bits=2, name=None):\n if not name:\n name = 'NOR' + str(NOR.cnt)\n NOR.cnt += 1\n\n return lut.LUT(lut.generate_NOR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef NAND(bits=2, name=None):\n if not name:\n name = 'NAND' + str(NAND.cnt)\n NAND.cnt += 1\n\n return lut.LUT(lut.generate_NAND(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef XOR(bits=2, name=None):\n if not name:\n name = 'XOR' + str(XOR.cnt)\n XOR.cnt += 1\n\n return lut.LUT(lut.generate_XOR(bits), name=name)\n\n\n@staticvariable('cnt', 0)\ndef XNOR(bits=2, name=None):\n if not name:\n name = 'XNOR' + str(XNOR.cnt)\n XNOR.cnt += 1\n\n return lut.LUT(lut.generate_XNOR(bits), name=name)\n","sub_path":"logic/gate.py","file_name":"gate.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"337172591","text":"#!/usr/bin/python3.6\n\nimport sys\nfrom itertools import groupby\nfrom operator import itemgetter\n\n\ndef read_mapper_output(file, separator='\\t'):\n for line in file:\n yield line.rstrip().split(separator, 1)\n\n\ndef main(separator='\\t'):\n hashtable={}; # maintain dictionary to store count of word\n # input comes from STDIN (standard input)\n data = read_mapper_output(sys.stdin, separator=separator)\n\n for current_word, group in groupby(data, itemgetter(0)):\n try:\n total_count = sum(int(count) for current_word, count in group)\n if current_word not in hashtable:\n hashtable[current_word] = total_count;\n else:\n hashtable[current_word] += total_count;\n except ValueError:\n # count was not a number, so silently discard this item\n pass\n\n sortedTuple = sorted(hashtable.items(), key=itemgetter(1),reverse=True); # sort hashtable by word occurence count\n for tuples in sortedTuple:\n print(\"%s%s%d\" % (tuples[0], separator, tuples[1]));\n\nif __name__ == \"__main__\":\n main()","sub_path":"part3/Word_Co-occurenc_Sports/Code/reducer_latest.py","file_name":"reducer_latest.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"461054858","text":"import allure\n\nfrom unittest import TestCase\nfrom library.httpclient import HttpClient\n\n\n@allure.feature('Test Weather api')\nclass Weather(TestCase):\n \"\"\"Weather api test cases\"\"\"\n\n def setUp(self):\n \"\"\"Setup of the test\"\"\"\n\n self.host = 'http://www.weather.com.cn'\n self.ep_path = '/data/cityinfo'\n self.client = HttpClient()\n\n @allure.story('Test of HangZhou')\n @allure.severity(allure.severity_level.NORMAL)\n def test_weather_hangzhou(self):\n city_code = '101210101'\n exp_city = '杭州'\n self._test(city_code, exp_city)\n\n @allure.story('Test of FuYang')\n @allure.severity(allure.severity_level.MINOR)\n def test_weather_fuyang(self):\n city_code = '101220801'\n exp_city = '阜阳'\n self._test(city_code, exp_city)\n\n @allure.story('Test of NingBo')\n def test_weather_ningbo(self):\n city_code = '101210401'\n exp_city = '宁波'\n self._test(city_code, exp_city)\n\n @allure.story('Test of ShangHai')\n @allure.severity(allure.severity_level.BLOCKER)\n def test_weather_shanghai(self):\n city_code = '101020100'\n exp_city = '上海'\n self._test(city_code, exp_city)\n\n @allure.story('Test of GuiYang')\n @allure.severity(allure.severity_level.TRIVIAL)\n def test_weather_guiyang(self):\n city_code = '101260101'\n exp_city = '贵阳'\n self._test(city_code, exp_city)\n\n def _test(self, city_code, exp_city):\n url = f'{self.host}{self.ep_path}/{city_code}.html'\n response = self.client.Get(url=url)\n act_city = response.json()['weatherinfo']['city']\n print(f'Expect city = {exp_city}, while actual city = {act_city}')\n # self.assertEqual(exp_city, act_city, f'Expect city = {exp_city}, while actual city = {act_city}')\n self.assertEqual(exp_city, act_city)","sub_path":"test/weather_test.py","file_name":"weather_test.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"639801791","text":"#pip install playsound\nfrom os import listdir\nfrom os.path import isfile, join\nimport random\nfrom playsound import playsound\nimport winsound\n\nclass musicPlayer:\n wavname = None\n def Player():\n global wavname\n yes = list()\n audiofiles = [f for f in listdir(r'./audio') if isfile(join(r'./audio', f))]\n for af in audiofiles:\n inter = af.split('.')\n yes.append(int(inter[0]))\n playnum = random.randint(0,max(yes))\n wavname = r'./audio/'+str(playnum)+'.wav'\n winsound.PlaySound(wavname, winsound.SND_ASYNC | winsound.SND_ALIAS )\n def Stop():\n winsound.PlaySound(None, winsound.SND_ASYNC)\n","sub_path":"musicPlayer.py","file_name":"musicPlayer.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"520528153","text":"# https://www.interviewbit.com/problems/noble-integer/\n\n# gt := greater than\n# ge := greater than or equal to\n\nclass Solution:\n # @param A : list of integers\n # @return an integer\n def solve(self, nums):\n \n nums.sort()\n nums.reverse()\n \n # nums are in descending order\n # there are 0 numbers ge nums[0]\n # there is 1 number ge nums[1], the number at nums[0]\n # there are 2 numbers ge nums[2], the numbers at nums[:2]\n # there are 3 numbers ge nums[3], the numbers at nums[:3]\n # etc...\n prev_num = None\n for i, num in enumerate(nums):\n if num == i:\n if num != prev_num:\n # prev_num > num\n # in fact\n # nums[:i] > num\n # meaning there are\n # i = num numbers in nums gt num\n return 1\n prev_num = num\n return -1\n\n# gotcha:\n# getting rid of duplicates before doing sort() and reverse() does not work\n# \n# for example, given the following list\n# \n# [ 1, 2, 7, 0, 9, 3, 6, 0, 6 ]\n# \n# [ 1, 2, 7, 0, 9, 3, 6 ] # after removing duplicates\n# \n# [ 0, 1, 2, 3, 6, 7, 9 ] # after sorting\n# \n# 0 1 2 3 4 5 6\n# [ 9, 7, 6, 3, 2, 1, 0 ] # after reversing\n# \n# while it is true that there are 3 unique numbers\n# (9, 7, 6) that are gt 3, there are actually\n# 4 numbers that are gt 3 in the original list\n# (9, 7, 6, 6)","sub_path":"interviewbit.com/Arrays/noble_integer.py","file_name":"noble_integer.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"194867085","text":"#coding:utf-8\nimport numpy as np\nimport pandas as pd\nnp.random.seed(2)\nnums = np.random.randn(3)\nprint(nums)\nseries = pd.Series(nums)\nresult = series.pct_change(periods=2)\nprint(result)\n# -0.47302468\n# -2.19246293\n\n# 4.125749","sub_path":"study_pandas/study_ewm.py","file_name":"study_ewm.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"93160242","text":"#!/usr/bin/python3 \n# -*- coding: utf-8 -*-\n# @File : test_20201011_6周_陈宝顺.py\n# @Author : Baoshun.Chin\n# @Time : 2020-10-11 22:32\n# @Site : \n# @version : V1.0\n\n# 一、作业:\n# 1.使用pytest编写5条商城接口测试case\n\nimport pytest\nimport requests\n# import yaml\n\nip = 'http://121.42.15.146:9090'\n\nclass Test_mtx_case():\n def setup_class(self):\n print('开始执行case')\n\n # 注册case\n # 1.未注册的账号:符合规范的用户&密码\n # 2.用户名不正确,密码符合规范\n # 3.已注册的账号,再次注册\n # @pytest.mark.skip\n @pytest.mark.parametrize('accounts,pwd,type,is_agree_agreement,result',\n [\n ('chin123', 'abc123456', 'username', '1', '注册成功'),\n ('s', '123456', 'username', '1', '用户名格式由 字母数字下划线 2~18 个字符'),\n ('_abc', '12345', 'username', '1', '账号已存在')\n ])\n def test_register(self, accounts, pwd, type, is_agree_agreement, result):\n # 注册接口\n url = ip + '/mtx/index.php?s=/index/user/reg.html'\n headers = {\n 'X-Requested-With': 'XMLHttpRequest'\n }\n data = {\n 'accounts': accounts,\n 'pwd': pwd,\n 'type': type,\n 'is_agree_agreement': is_agree_agreement\n }\n res = requests.post(url=url, data=data, headers=headers)\n r = res.json()\n print(r)\n print(r['msg'])\n assert result == r['msg']\n\n # 登录case\n # 1.正确的用户名和密码登录\n # 2.正确的用户名和错误的密码登录\n # 3.错误的用户名和错误的密码\n # 4.未注册的账号登录\n # @pytest.mark.skip\n @pytest.mark.parametrize('accounts,pwd,result',\n [\n ('1234', '123456', '登录成功'),\n ('1234', '!123478@', '密码错误'),\n ('123A', '123456L', '帐号不存在'),\n ('@12345', 'abcdefg', '帐号不存在')])\n def test_login(self, accounts, pwd, result):\n # 登录接口\n url = ip + '/mtx/index.php?s=/index/user/login.html'\n headers = {\n 'X-Requested-With': 'XMLHttpRequest',\n }\n data = {\n 'accounts': accounts,\n 'pwd': pwd\n }\n res = requests.post(url=url, data=data, headers=headers)\n # print(res.text)\n r = res.json()\n print(r)\n assert result == r['msg']\n\n def teardown_class(self):\n print('case执行完毕')\n\nif __name__ == '__main__':\n pytest.main('test_20201011_6周_陈宝顺.py')","sub_path":"Course0823/Week06/task/test_20201011_6周_陈宝顺.py","file_name":"test_20201011_6周_陈宝顺.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"443798853","text":"\"\"\"\n tests.tests_dratf04\n ~~~~~~~~~~~~~~~~~~~~~~\n\n Test against `Common test suite`_.\n\n .. _`Common test suite`:: https://github.com/json-schema/JSON-Schema-Test-Suite\n\"\"\"\n\nfrom jsonspec.validators import load, ValidationError, CompilationError\nfrom jsonspec.reference.providers import SpecProvider, ProxyProvider\nfrom jsonspec import driver as json\n\nimport io\nimport os\nimport pytest\nimport logging\nfrom pathlib import Path\nfrom six import PY2\nlogger = logging.getLogger(__name__)\nhere = os.path.dirname(os.path.abspath(__file__))\n\n\ndef contents(*paths):\n fullpath = os.path.join(here, 'suite', *paths)\n d = len(fullpath)\n for filepath in Path(fullpath).glob('**/*.json'):\n with filepath.open('r', encoding='utf-8') as file:\n yield json.load(file), filepath.as_posix()[d:].lstrip('/')\n\n\nprovider = ProxyProvider(SpecProvider())\nfor data, src in contents('remotes'):\n provider[os.path.join('http://localhost:1234', src)] = data\n\n\ndef scenarios(draft):\n # no ECMA 262 regex parser\n skip = ['optional/jsregex.json']\n if PY2:\n # json module cannot handle well unicode strings\n skip.extend(('minLength.json', 'maxLength.json'))\n\n for data, src in contents('tests', draft):\n if src in skip:\n continue\n\n for block in data:\n for test in block['tests']:\n yield (block['schema'], test['description'],\n test['data'], test['valid'], src)\n\n\n@pytest.mark.parametrize('schema, description, data, valid, src',\n scenarios('draft3'))\ndef test_common(schema, description, data, valid, src):\n try:\n load(schema, provider=provider,\n spec='http://json-schema.org/draft-03/schema#').validate(data)\n if not valid:\n assert False, description\n except (ValidationError, CompilationError) as error:\n if valid:\n logger.exception(error)\n assert False, description\n","sub_path":"tests/test_draft03.py","file_name":"test_draft03.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"543984491","text":"# -*- coding: utf-8 -*-\nimport re\nimport urllib\nfrom urlparse import urljoin\nimport scrapy\nimport requests\nimport json\n\n## 用開放資料比對議員性別\nr = requests.get(\"http://cand.moi.gov.tw/of/ap/cand_json.jsp?electkind=0200000\")\nnamejson = json.loads(r.content.strip(' \\s\\n\\r'))\ndef GetGender(json,name):\n for i in json:\n s = re.sub(u'[\\s ]', '', i['idname'])\n if(s==name):\n return i['sex']\n\n## 轉換年月日格式\ndef GetDate(text):\n matchTerm = re.search(u'''\n (?P[\\d]+)[\\s]*年[\\s]*\n (?P[\\d]+)[\\s]*月[\\s]*\n (?P[\\d]+)\n ''', text, re.X)\n if matchTerm:\n return '%04d-%02d-%02d' % (int(matchTerm.group('year'))+1911, int(matchTerm.group('month')), int(matchTerm.group('day')))\n else:\n return None\n\nclass Spider(scrapy.Spider):\n name = \"councilors\"\n allowed_domains = [\"www.kmc.gov.tw\"]\n start_urls = [\"http://www.kmc.gov.tw/index.php/kmc-info/%E8%AD%B0%E5%93%A1%E8%B3%87%E8%A8%8A\",]\n download_delay = 0.5\n\n def parse(self, response):\n nodes = response.xpath(u'//a[re:test(@title, \"議(員|長)$\")]')\n for node in nodes:\n item = {}\n item['election_year'] = '2014'\n item['in_office'] = True\n item['term_start'] = '%s-12-25' % item['election_year']\n item['term_end'] = {'date': '2018-12-24'}\n item['name'], item['title'] = node.xpath('@title').extract_first().split()\n item['gender'] = GetGender(namejson, item['name'])\n item['county'] = u'基隆市'\n item['district'] = node.xpath('normalize-space(string(ancestor::tr/td[1]))').extract_first()\n yield scrapy.Request(urljoin(response.url, node.xpath('@href').extract_first()), callback=self.parse_profile, meta={'item': item})\n\n def parse_profile(self, response):\n global namejson\n item = response.meta['item']\n item['image'] = response.xpath('//img[contains(@src, \"/member/\")]/@src').extract_first()\n item['links'] = [{'url': response.url, 'note': u'議會個人官網'}]\n item['constituency'] = response.xpath('//td/text()').re(u'選區:\\s*(.+)')[0].strip()\n item['party'] = response.xpath('//td/text()').re(u'政黨:\\s*(.+)')[0].strip()\n item['birth'] = GetDate(response.xpath('//td/text()').re(u'出生日期:\\s*(.+)')[0]).strip()\n website = response.xpath('//td/text()').re(u'網站連結:\\s*(.+)')\n if website:\n item['links'].append({'url': website[0].strip(), 'note': u'個人網站'})\n item['contact_details'] = []\n contact_mappings = {\n u'連絡電話': 'voice',\n u'傳真號碼': 'fax',\n u'服務處': 'address',\n u'電子郵件': 'email'\n }\n for label, name in contact_mappings.items():\n values = [x.strip() for x in response.xpath(u'//td[re:test(., \"%s:\")]/text()' % '\\s*'.join(label)).re(u'%s:\\s*(.+)\\s*' % label) if x.strip()]\n for value in values:\n item['contact_details'].append({\n 'label': label,\n 'type': name,\n 'value': value\n })\n item['experience'] = [x.strip() for x in response.xpath(u'//img[contains(@src, \"speaker0\")]')[1].xpath('ancestor::tr/following-sibling::tr[1]//tr/td[1]/text()').extract() if x.strip()]\n item['platform'] = [x.strip() for x in response.xpath(u'//img[contains(@src, \"speaker0\")]')[2].xpath('ancestor::tr/following-sibling::tr[1]//tr/td[1]/text()').extract() if x.strip()]\n yield item\n","sub_path":"crawler/kmc/councilors.py","file_name":"councilors.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"509200731","text":"import os\n\nimport numpy as np\nimport numpy.testing as npt\nimport tensorflow as tf\nfrom monty import data\n\ntf.enable_eager_execution()\n\nTEST_FILE_PATH = 'resources/PBMC_test.csv'\n\n\ndef test_download_file_not_present(mocker):\n try:\n os.remove(TEST_FILE_PATH)\n except OSError:\n pass\n mocked_s3 = mocker.patch('s3fs.S3FileSystem.get')\n\n assert data.download_if_not_present(local_file_path=TEST_FILE_PATH) == TEST_FILE_PATH\n mocked_s3.assert_called_once_with('pbmcasinglecell/PBMC.csv', TEST_FILE_PATH)\n\n\ndef test_download_file_present(mocker):\n try:\n os.remove(TEST_FILE_PATH)\n except OSError:\n pass\n dataset = open(TEST_FILE_PATH, 'w')\n dataset.write(' ')\n mocked_s3 = mocker.patch('s3fs.S3FileSystem.get')\n\n assert data.download_if_not_present(local_file_path=TEST_FILE_PATH) == TEST_FILE_PATH\n assert mocked_s3.call_count == 0\n os.remove(TEST_FILE_PATH)\n\n\ndef test_create_dataset():\n iterator = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None).batch(2).make_one_shot_iterator()\n npt.assert_array_equal(iterator.get_next(), np.array([[2, 1, 0, 1, 0], [0, 0, 0, 0, 0]], dtype=np.float32))\n\n\ndef test_drop_outliers():\n dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None)\n non_outliers = data.drop_outliers(dataset, minimum_expressed_genes=1, minimum_library_size=100)\n iterator = non_outliers.batch(2).make_one_shot_iterator()\n first_batch = iterator.get_next()\n\n npt.assert_array_equal(first_batch, np.array([[41, 42, 43, 44, 45]], dtype=np.float32))\n assert first_batch.shape == (1, 5)\n\n\ndef test_normalize_data():\n dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None) \\\n .batch(1)\n dataset = data.normalize_dataset(dataset)\n iterator = dataset.make_one_shot_iterator()\n npt.assert_allclose(iterator.get_next()[0], np.vectorize(lambda x: np.log(x + 1))([2, 1, 0, 1, 0]))\n\n\ndef test_denormalize_data():\n dataset = data.create_dataset(\"test_resources/PBMC_test.csv\", 5, 1, False, None) \\\n .batch(1)\n dataset = data.denormalize_dataset(dataset)\n iterator = dataset.make_one_shot_iterator()\n npt.assert_allclose(iterator.get_next()[0], np.vectorize(lambda x: np.exp(x) - 1)([2, 1, 0, 1, 0]))\n\n\ndef test_denormalize_normalize_data():\n assert [data.denormalize_op(data.normalize_op(x)).numpy() for x in [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]] \\\n == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]\n","sub_path":"tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"565982646","text":"import pytest, json, jsonpath, requests\n\ndef test_addNew_data():\n API_url=\"http://thetestingworldapi.com/api/studentsDetails\"\n f= open('E:/TestFiles/API/requestJson.json', 'r')\n request_json=json.loads(f.read())\n response=requests.post(API_url, request_json)\n print(response.text)\n print(response.status_code)\n id=jsonpath.jsonpath(response.json(), 'id')\n print(\"ID:\", id[0])\n\n tech_url=\"http://thetestingworldapi.com/api/technicalskills\"\n f= open('E:/TestFiles/API/techDetails.json', 'r')\n request_json=json.loads(f.read())\n request_json['id']=id[0]\n request_json['st_id']=int(id[0])\n response=requests.post(tech_url, request_json)\n print(response.text)\n\n address_api=\"http://thetestingworldapi.com/api/addresses\"\n f = open('E:/TestFiles/API/address.json', 'r')\n request_json = json.loads(f.read())\n request_json['stId']=id[0]\n response = requests.post(address_api, request_json)\n print(response.content)\n #\n # finalDetails1=\"http://thetestingworldapi.com/api/FinalStudentDetails/\"+str(id[0])\n # response=requests.get(finalDetails1)\n # print(response.text)\n\n","sub_path":"test_end2end.py","file_name":"test_end2end.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"196161580","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 14 19:38:09 2016\n\n@author: vinay.benny\n\"\"\"\n\nimport numpy as np;\nimport pandas as pd;\nimport os;\nfrom sklearn.feature_selection import VarianceThreshold;\nimport itertools;\nfrom sklearn.decomposition import PCA;\nfrom sklearn.preprocessing import StandardScaler;\nfrom matplotlib import pyplot as plt;\nfrom sklearn.pipeline import Pipeline;\nfrom sklearn.linear_model import LogisticRegression;\nfrom sklearn.grid_search import GridSearchCV;\nfrom sklearn.cross_validation import cross_val_score;\n\n\ndef rem_constant_feat(pd_dataframe):\n selector = VarianceThreshold();\n selector.fit(pd_dataframe);\n variant_indices = selector.get_support(indices=True);\n all_indices = np.arange(pd_dataframe.columns.size);\n nonvariant_indices = np.delete(all_indices, variant_indices);\n pd_dataframe = pd_dataframe.drop(labels=pd_dataframe[nonvariant_indices], axis=1);\n print(\" - Deleted %s / %s features (~= %.1f %%)\" % (nonvariant_indices.size, \n all_indices.size ,100.0 * (np.float(nonvariant_indices.size) / all_indices.size)));\n return pd_dataframe, nonvariant_indices;\n \ndef rem_identical_feat(pd_dataframe):\n delete_feats = [];\n n_features = pd_dataframe.shape[1]\n for feat1, feat2 in itertools.combinations(iterable=pd_dataframe.columns, r=2):\n if np.array_equal(pd_dataframe[feat1], pd_dataframe[feat2]):\n delete_feats.append(feat2);\n \n delete_feats = np.unique(delete_feats);\n pd_dataframe = pd_dataframe.drop(labels=delete_feats, axis=1);\n print(\" - Deleted %s / %s features (~= %.1f %%)\" % (\n len(delete_feats), n_features,\n 100.0 * (np.float(len(delete_feats)) / n_features)))\n return pd_dataframe, delete_feats;\n \ndef apply_norm_feat(pd_dataframe): \n normalizer = StandardScaler(); \n norm_xtrain = normalizer.fit_transform(xtrain); \n print(\" - Normalized the training dataset\");\n return norm_xtrain, normalizer;\n\ndef apply_PCA(xtrain): \n \n pca = PCA(n_components=100);\n #logistic = LogisticRegression();\n #pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]); \n \n #n_components = [100, 150, 200];\n #Cs=np.logspace(-4, 4, 3);\n #estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, logistic__C=Cs), verbose=2);\n #estimator.fit(xtrain, ytrain);\n xtrain_comps = pca.fit_transform(xtrain);\n print(\" - Applied PCA on the training dataset\");\n return xtrain_comps, pca;\n \ndef pca_visualize(pca, xtrain, ytrain):\n \n classes = np.sort(np.unique(ytrain))\n labels = [\"Satisfied customer\", \"Unsatisfied customer\"]\n fig = plt.figure(figsize=(10, 7))\n ax = fig.add_subplot(1, 1, 1)\n colors = [(0.0, 0.63, 0.69), 'black']\n markers = [\"o\", \"D\"]\n for class_ix, marker, color, label in zip(\n classes, markers, colors, labels):\n ax.scatter(xtrain[np.where(ytrain == class_ix), 0],\n xtrain[np.where(ytrain == class_ix), 1],\n marker=marker, color=color, edgecolor='whitesmoke',\n linewidth='1', alpha=0.9, label=label)\n ax.legend(loc='best')\n plt.title(\n \"Scatter plot of the training data examples projected on the \"\n \"2 first principal components\")\n plt.xlabel(\"Principal axis 1 - Explains %.1f %% of the variance\" % (\n pca.explained_variance_ratio_[0] * 100.0))\n plt.ylabel(\"Principal axis 2 - Explains %.1f %% of the variance\" % (\n pca.explained_variance_ratio_[1] * 100.0))\n plt.show();\n return;\n \n \ndef make_submission(clf, xtest, ids, name='submission_test.csv'):\n y_prob = clf.predict_proba(xtest)\n with open(name, 'w') as f:\n f.write('ID')\n f.write(',TARGET')\n f.write('\\n')\n for id, probs in zip(ids, y_prob):\n probas = ','.join([id] + map(str, probs.tolist()))\n f.write(probas)\n f.write('\\n')\n print(\"Wrote submission to file {}.\".format(name)) \n\nif __name__ == \"__main__\": \n np.random.seed(93); \n os.chdir(\"C:/Users/vinay.benny/Documents/Kaggle/Santader\");\n train = pd.DataFrame.from_csv(\"train.csv\");\n test = pd.DataFrame.from_csv(\"test.csv\");\n \n #Remove constant features in train, and drop the same in test \n train, indices = rem_constant_feat(train);\n test = test.drop(labels=test[indices], axis=1);\n \n #Remove identical features in training datasets, and drop the same in test\n train, feats = rem_identical_feat(train);\n test = test.drop(labels=feats, axis=1);\n \n # Apply normalization to training data, and use the normalizer on test\n ytrain = train[\"TARGET\"];\n xtrain = train.drop(labels=\"TARGET\", axis=1); \n norm_xtrain, normalizer = apply_norm_feat(xtrain);\n norm_xtest = normalizer.transform(test);\n \n #Apply principal components analysis on training, and transform the test data \n #xtrain_comps, pcaest = apply_PCA(norm_xtrain);\n pca = PCA();\n #xtest_comps = pcaest.transform(norm_xtest);\n #pca_visualize(pcaest, xtrain_comps, ytrain);\n \n #Apply logistic regression on training data\n logistic = LogisticRegression(); \n #param_grid_vals = {'C':np.logspace(-4, 4, 3)}\n pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]);\n #estimator = GridSearchCV(logistic, param_grid=param_grid_vals, verbose=2);\n n_components = [100];\n Cs=np.logspace(-5, -1, 5);\n estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, logistic__C=Cs), verbose=2);\n estimator.fit(norm_xtrain, ytrain);\n \n ytest_prob = make_submission(estimator, norm_xtest, test.index.values.astype(str));\n \n \n \n \n \n \n \n \n ","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"474193719","text":"\n\nimport math\nimport sys\nimport csv\n\nignore = []\nArrayOfNumObj = []\nArrayOfSymObj = []\n\nclass Tbl():\n def __init__(self):\n self.rows = []\n self.spec = []\n self.goals = [] \n self.less = []\n self.more = []\n self.name = []\n self.nums = []\n self.syms = []\n self.weight = []\n global ignore # holds the indeces of the columns that should be ignored\n self.all = [] # holds all the categories \n self.x = [] # holds all independent columns\n self.y = [] # holds all dependent columns\n \n \n def categories(self,i,txt):\n if txt == \"$\":\n self.nums.append(i)\n self.weight.append(1)\n self.x.append(i)\n self.all.append(i)\n \n elif txt == \"<\":\n self.nums.append(i)\n self.weight.append(-1)\n self.y.append(i)\n self.all.append(i)\n self.goals.append(i)\n self.less.append(i)\n \n elif txt == \">\":\n self.nums.append(i)\n self.weight.append(1)\n self.y.append(i)\n self.all.append(i)\n self.goals.append(i)\n self.more.append(i)\n \n elif txt == \"!\":\n self.syms.append(i)\n self.weight.append(1)\n self.y.append(i)\n self.all.append(i)\n \n elif txt == \"?\":\n self.ignore.append(i)\n \n else:\n self.syms.append(i)\n self.weight.append(1)\n self.x.append(i)\n self.all.append(i)\n \n return self.nums, self.syms, self.all, self.x, self.y, self.weight\n \n def TblUpdate(self,row):\n self.items = []\n for i in range(len(row)):\n self.items.append(row[i])\n self.rows.append(self.items)\n \n return self.rows\n \n############################################ \n\nclass num():\n def __init__(self):\n self.n = 0\n self.mu = 0\n self.m2 = 0\n self.sd = 0\n self.hi = (-math.exp(32))\n self.lo = (math.exp(32)) \n self.w = 1\n pass\n \n def NumUpdate(self,i,x):\n if i not in ignore: \n self.n = self.n + 1\n if float(x) < self.lo:\n self.lo = float(x)\n if float(x) > self.hi:\n self.hi = float(x)\n delta = float(x) - self.mu\n self.mu = self.mu + delta / self.n\n self.m2 = self.m2 + delta * (float(x) - self.mu)\n if self.n > 1:\n self.sd = (self.m2 / (self.n - 1))**0.5\n \n return self\n \n def norm(self,i,x):\n if i in ignore:\n return x\n else:\n return (float(x) - self.lo)/(self.hi - self.lo + math.exp(-32))\n \n############################################ \n\nclass sym():\n def __init__(self):\n self.n = 0\n self.nk = 0\n self.counts = []\n self.strings = []\n self.most = 0\n self.mode = None\n self._ent = None\n pass\n \n def SymUpdate(self,i,x):\n if i not in ignore:\n self.n = self.n + 1\n self._ent = None\n if str(x) not in self.strings:\n index = len(self.counts)\n self.strings.append(str(x))\n self.counts.append(1)\n \n else:\n index = self.strings.index(str(x))\n self.counts[index] = self.counts[index] + 1 \n \n \n if self.counts[index] > self.most:\n self.most = self.counts[index]\n self.mode = str(x)\n return self\n \n def norm(self,i,x):\n return x\n \n################################################\n\ndef dominate1(i,j,t, Num):\n e = 2.71828\n n = len(t.goals)\n sum1 = 0\n sum2 = 0\n temp_i = 0\n \n for index in range(len(t.goals)):\n ind = t.goals[index]\n w = t.weight[ind]\n x = Num[ind].norm(ind, t.rows[i][ind])\n y = Num[ind].norm(ind, t.rows[j][ind])\n sum1 = sum1 - e**(w * (float(x)-float(y))/n)\n sum2 = sum2 - e**(w * (float(y)-float(x))/n) \n if sum1/n < sum2/n:\n temp_i = temp_i + 1 # shows how many times i dominates j\n return sum1/n < sum2/n\n\n################################################\ndef Unsupervised(TableColumn):\n data = TableColumn\n n = len(data)\n data = sorted(data)\n epsilon = 0.2*(np.std(data))\n rangeSize = n**0.5\n binSize = math.ceil(rangeSize)\n binIndeces = []\n i = int(binSize)\n startIndex = 0\n counter = 1\n while i < n-1:\n while span(data,startIndex,i) < epsilon:\n if i+1 > n-1:\n break\n else:\n i = i + 1\n binIndeces.append(i)\n \n if (i + int(binSize) - 1) < n-1:\n print (\"%d:\"%counter, \"Range size = %d\" %(i-startIndex), \", span = %f\" %span(data,startIndex,i), \", lo = %.10f\" % min(data[startIndex:i]), \", hi = %.10f\" % max(data[startIndex:i]))\n counter = counter + 1\n startIndex = i \n i = i + int(binSize) \n else: \n print (\"%d:\"%counter, \"Range size = %d\" %(len(data)-startIndex), \", span = %f\" %span(data,startIndex,i), \", lo = %.10f\" % min(data[startIndex:i]), \", hi = %.10f\" % max(data[startIndex:i]))\n break\n \n \n return binIndeces,data\n\n###############################################################\n\ndef supervised(data,labels):\n ranges = []\n for i in range(len(labels)+1):\n globals()['range%s' % str(i+1)] = []\n number = 2\n i = 0\n for j in range(len(labels)):\n \n while j==0 and data[i] < labels[j]:\n range1.append(data[i])\n i = i + 1\n if i > len(data)-1:\n break\n if j == 0:\n ranges.append(range1)\n \n while i < len(data)-1 and j < len(labels)-1 and labels[j] <= data[i] and data[i] < labels[j+1]:\n globals()['range%s' % str(number)].append(data[i])\n i = i + 1\n if i > len(data)-1:\n break \n if number < len(labels) + 1: \n ranges.append(globals()['range%s' % str(number)])\n number = number + 1\n \n while j == len(labels) - 1 and data[i] >= labels[j]:\n globals()['range%s' % str(number)].append(data[i])\n i = i + 1\n if i > len(data)-1:\n break\n\n ranges.append(globals()['range%s' % str(number)])\n counter = 1\n for i in range(len(ranges)):\n print (\"Label = %d:\"%counter, \"most = %.10f\" %ranges[i][len(ranges[i])-1])\n counter = counter + 1\n \n return ranges\n\n\ndef span(data,startingIndex, endIndex):\n delta = max(data[startingIndex:endIndex]) - min(data[startingIndex:endIndex])\n return delta\n####################################################################################\n\ndef sortDom(domHolder,Table,features):\n dom = 0\n temp = Table\n for i in range(len(Table.rows)):\n if dominate1(dom,i,Table, features): \n dom = i\n domHolder.append(dom) \n del temp[dom]\n sortDom(domHolder,temp,features)\n\n return domHolder \n \n##################################################################################### \nTable = Tbl()\n\n#FileName = sys.argv[-1]\nFileName = 'auto.csv'\nrow_counter = 0\nNum_objectHolder = []\nSym_objectHolder = []\nwith open(FileName, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n #print(reader)\n for row in reader:\n if row_counter == 0:\n print (row)\n for i in range (len(row)):\n txt = row[i][0]\n Table.categories(i,txt)\n for j in range(len(Table.nums)):\n globals()['Num%s' % Table.nums[j]] = num()\n \n for j in range(len(Table.syms)):\n globals()['Sym%s' % Table.syms[j]] = sym()\n row_counter = 1\n \n else:\n if '?' in row: # ignoring those rows with missing value\n continue \n \n else:\n if i in Table.nums:\n index = Table.nums.index(i)\n Num_objectHolder.append(globals()['Num%s' % Table.nums[index]].NumUpdate(i, row[i]))\n\n \n if i in Table.syms:\n index = Table.syms.index(i)\n Sym_objectHolder.append(globals()['Sym%s' % Table.syms[index]].SymUpdate(i, row[i]))\n Table.TblUpdate(row)\n \n\ndomHolder = []\nsortDom(domHolder,Table, Num_objectHolder)\n \n\n","sub_path":"HW4/HW4.py","file_name":"HW4.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"516194632","text":"# compressing text using static huffman algorithm\n# static huffman algorithm:\n# step 1: calculate frequency of each character\n# step 2: build an huffman tree base on frequency of each character\n# step 3: assign bit value to each branches\n\nclass StaticHuffman:\n def __init__(self, string=None, path=None):\n self.__string = string\n self.__path = path # for input file (will implement later)\n self.__codes = {} # storing binary encode of each characters\n\n class HuffmanNode:\n def __init__(self, char, freq, left=None, right=None):\n self.char = char\n self.freq = freq\n self.left = left\n self.right = right\n\n # generate frequency dictionary for building huffman tree\n def gen_frequency_dict(self):\n frequency = {}\n string = self.__string\n for char in string:\n if not char in frequency:\n frequency[char] = 0\n frequency[char] += 1\n\n return frequency\n\n # generate huffman tree's root with child\n def __gen_huffman_tree(self):\n\n # support method for generating huffman tree\n def get_two_min_node(node_list):\n lst = sorted(node_list, key = lambda x: x.freq, reverse=False)\n\n first_min_node = lst[0]\n second_min_node = lst[1]\n\n return [first_min_node, second_min_node]\n\n huffman_list = []\n frequency_dict = self.gen_frequency_dict()\n\n for char in frequency_dict:\n node = self.HuffmanNode(char, frequency_dict[char])\n huffman_list.append(node)\n\n # keep removing two smallest frequency node and\n # adding the sum of frequency as an new node\n # to the node list until getting the root of the tree\n while (len(huffman_list) > 1):\n first_node, second_node = get_two_min_node(huffman_list)\n huffman_list.remove(first_node)\n huffman_list.remove(second_node)\n\n node = self.HuffmanNode(None, first_node.freq + second_node.freq, first_node, second_node)\n huffman_list.append(node)\n\n return huffman_list[0]\n\n # support method to assign binary number to branch\n def __gen_code_helper(self, root, current_code):\n if (root == None):\n return\n\n if root.char != None:\n self.__codes[root.char] = current_code\n return\n\n self.__gen_code_helper(root.left, current_code + \"0\")\n self.__gen_code_helper(root.right, current_code + \"1\")\n\n def gen_code(self):\n root = self.__gen_huffman_tree()\n current_code = \"\"\n self.__gen_code_helper(root, current_code)\n return self.__codes\n\n\n# =================== END OF STATIC HUFFMAN CLASS ============================\n\nif __name__ == '__main__':\n string = \"abbc\"\n static_huffman = StaticHuffman(string)\n print(static_huffman.gen_frequency_dict())\n print(static_huffman.gen_code())","sub_path":"HW/HW-06/static_huffman.py","file_name":"static_huffman.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"465589396","text":"import pyrealsense2 as rs\nimport numpy as np\nimport cv2\n\n\n#Abrimos\npipeline = rs.pipeline()\nconfig = rs.config()\n\nconfig.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30)\n\n# Iniciamos el stream\npipeline.start(config)\n\n\ndef DibujarContornos(imagen,contornos,color,Palabra):\n for c in contornos:\n M = cv2.moments(c)\n if (M[\"m00\"]==0):M[\"m00\"]=1\n x = int(M[\"m10\"] / M[\"m00\"])\n y = int(M[\"m01\"] / M[\"m00\"])\n cv2.drawContours(imagen,[c],0,color,2)\n epsilon = 0.1*cv2.arcLength(c,True)\n approx = cv2.approxPolyDP(c,epsilon,True)\n cv2.drawContours(imagen,approx,0,color,2)\n cv2.putText(imagen,str(Palabra),(x,y),1,2,(0,0,0),2)\n\n\ntry:\n while True:\n frames = pipeline.wait_for_frames()#Obtiene frame\n color = frames.get_color_frame()\n if not color:\n continue\n color_image = np.asanyarray(color.get_data())\n hsv_image = cv2.cvtColor(color_image,cv2.COLOR_BGR2HSV)#Convertimos BGR a HSV para deteccion de colores\n\n\n #Comenzamos a definir los limites del color rojo\n Red_Min = (165,90,80)#HSV\n Red_Max = (180,255,255)#HSV\n\n #Comenzamos a definir los limites del color Azul\n BLue_Min = (90,90,80)#HSV\n Blue_Max = (135,255,255)#HSV\n #Hacemos la discriminacion de valores que no pertenecen al rojo\n mascaraR = cv2.inRange(hsv_image,Red_Min,Red_Max)#verifica cuales pixeles estan dentro del rango, los que no esten los hace negros\n Red_Output = cv2.bitwise_and(color_image,color_image,mask=mascaraR)#la imagen de entrada se filtra con la mascara y se genera la salida (entrada,salida,mascara)\n\n\n #SECCION DEL AZUL\n mascaraB = cv2.inRange(hsv_image,BLue_Min,Blue_Max)#verifica cuales pixeles estan dentro del rango, los que no esten los hace negros\n Blue_Output = cv2.bitwise_and(color_image,color_image,mask=mascaraB)#la imagen de entrada se filtra con la mascara y se genera la salida (entrada,salida,mascara)\n\n #Contornos Rojos\n ContornoRojo = cv2.findContours(mascaraR,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]\n DibujarContornos(color_image,ContornoRojo,(255,255,255),\"Equipo\")\n #Contornos Azules\n ContornoAzul = cv2.findContours(mascaraB,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]\n DibujarContornos(color_image,ContornoAzul,(255,255,255),\"Enemigo\")\n\n\n cv2.imshow('RGB', color_image)\n cv2.imshow('Rojo', Red_Output)\n cv2.imshow('Azul', Blue_Output)\n\n\n cv2.waitKey(1)#muestra la imagen en N milisegundos\n\nfinally:\n pipeline.stop()\n","sub_path":"Contornos.py","file_name":"Contornos.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"189648452","text":"import os\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\nclass L2Norm(nn.Module):\n def __init__(self,n_channels, scale):\n super(L2Norm,self).__init__()\n self.n_channels = n_channels\n self.gamma = scale or None\n self.eps = 1e-10\n self.weight = nn.Parameter(torch.Tensor(self.n_channels))\n self.reset_parameters()\n\n def reset_parameters(self):\n init.constant(self.weight,self.gamma)\n\n def forward(self, x):\n norm = x.pow(2).sum(dim=1, keepdim=True).sqrt()+self.eps\n #x /= norm\n x = torch.div(x,norm)\n # print('weight L2:',self.weight.size(),self.weight[0],x.size())\n out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x) * x\n return out\n\nclass VGG(object):\n def __init__(self,batch_norm=False):\n self.layer1 = self.block(2,3,64,maxp=False)\n self.layer2 = self.block(2,64,128)\n self.layer3 = self.block(3,128,256)\n self.layer4 = self.block(3,256,512,mmode=True)\n self.layer5 = self.block(3,512,512)\n self.layer6 = nn.Conv2d(512,1024,kernel_size=3,padding=6,dilation=6)\n self.layer7 = nn.Conv2d(1024,1024,kernel_size=1)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool1 = nn.MaxPool2d(kernel_size=2,stride=2)\n\n def conv2(self,kernel_in,kernel_out,k_size,padd=1,bnorm=False):\n conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd)\n norm = nn.BatchNorm2d(kernel_out)\n relu = nn.ReLU(inplace=True)\n if bnorm :\n layers = [conv,norm,relu]\n else:\n layers = [conv,relu]\n return layers\n def maxpool(self,km_size=2,step=2,mode=False):\n return [nn.MaxPool2d(kernel_size=km_size,stride=step,ceil_mode=mode)]\n\n def block(self,n,filter_in,filter_out,batch_norm=False,mmode=False,maxp=True):\n layers = []\n if maxp:\n layers.extend(self.maxpool(mode=mmode))\n layers+=(self.conv2(filter_in,filter_out,3,bnorm=batch_norm))\n for i in range(1,n):\n layers.extend(self.conv2(filter_out,filter_out,3,bnorm=batch_norm))\n return layers\n\n def forward(self):\n layers = []\n layers+=self.layer1\n layers.extend(self.layer2)\n layers.extend(self.layer3)\n layers.extend(self.layer4)\n layers.extend(self.layer5)\n layers.extend([self.maxpool1])\n layers.extend([self.layer6])\n layers.extend([self.relu])\n layers.extend([self.layer7])\n layers.extend([self.relu])\n return layers\n\nclass ExtractLayers(object):\n def __init__(self,filter_in):\n self.layer1 = self.conv2(filter_in,256,1,0)\n self.layer2 = self.conv2(256,512,3,1,2)\n self.layer3 = self.conv2(512,128,1,0)\n self.layer4 = self.conv2(128,256,3,1,2)\n\n def conv2(self,kernel_in,kernel_out,k_size,padd=1,step=1,bnorm=False):\n conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd,stride=step)\n norm = nn.BatchNorm2d(kernel_out)\n relu = nn.ReLU(inplace=True)\n if bnorm :\n layers = [conv,norm,relu]\n else:\n # layers = [conv,relu]\n layers = [conv]\n return layers\n def forward(self):\n layers = []\n layers += self.layer1\n layers.extend(self.layer2)\n layers.extend(self.layer3)\n layers.extend(self.layer4)\n return layers\n\nclass Multibox(object):\n def __init__(self,num_classes,prior_num=1):\n anchors = prior_num*4\n cls_num = num_classes * prior_num\n self.regress_layer1 = self.conv2(256,anchors,3)\n self.regress_layer2 = self.conv2(512,anchors,3)\n self.regress_layer3 = self.conv2(512,anchors,3)\n self.regress_layer4 = self.conv2(1024,anchors,3)\n self.regress_layer5 = self.conv2(512,anchors,3)\n self.regress_layer6 = self.conv2(256,anchors,3)\n self.confidence_layer1 = self.conv2(256,3+(cls_num-1),3)\n self.confidence_layer2 = self.conv2(512,cls_num,3)\n self.confidence_layer3 = self.conv2(512,cls_num,3)\n self.confidence_layer4 = self.conv2(1024,cls_num,3)\n self.confidence_layer5 = self.conv2(512,cls_num,3)\n self.confidence_layer6 = self.conv2(256,cls_num,3)\n\n def conv2(self,kernel_in,kernel_out,k_size,padd=1,dilate=1,bnorm=False):\n conv = nn.Conv2d(kernel_in,kernel_out,kernel_size=k_size,padding=padd,dilation=dilate)\n norm = nn.BatchNorm2d(kernel_out)\n if bnorm :\n layers = [conv,norm]\n else:\n layers = [conv]\n return layers\n def forward(self):\n loc = list()\n conf = list()\n loc += self.regress_layer1\n loc.extend(self.regress_layer2)\n loc.extend(self.regress_layer3)\n loc.extend(self.regress_layer4)\n loc.extend(self.regress_layer5)\n loc.extend(self.regress_layer6)\n conf += self.confidence_layer1\n conf.extend(self.confidence_layer2)\n conf.extend(self.confidence_layer3)\n conf.extend(self.confidence_layer4)\n conf.extend(self.confidence_layer5)\n conf.extend(self.confidence_layer6)\n return conf,loc\n\nclass S3FD(nn.Module):\n def __init__(self,class_num,num_anchor=1):\n super(S3FD,self).__init__()\n #self.lo = nn.Sequential(*vgg(cfg,3))\n net = VGG()\n add_layers = ExtractLayers(1024) \n Head = Multibox(class_num,num_anchor)\n head0,head1 = Head.forward()\n self.num_classes = class_num\n self.vgg = nn.ModuleList(net.forward())\n self.extras = nn.ModuleList(add_layers.forward())\n self.conf = nn.ModuleList(head0)\n self.loc = nn.ModuleList(head1)\n self.L2Norm3_3 = L2Norm(256, 10)\n self.L2Norm4_3 = L2Norm(512, 8)\n self.L2Norm5_3 = L2Norm(512, 5)\n self.softmax = nn.Softmax(dim=-1)\n # self.num_anchors = 34125\n self.num_anchor = num_anchor\n self.fpn_sizes = [25600,6400,1600,400,100,25]\n #self.extracts = nn.ModuleList(add_extras(extras_cfg,1024))\n def forward(self,x):\n fpn = list()\n loc = list()\n conf = list()\n iou = list()\n # x = x.permute(0,3,1,2)\n for idx in range(16):\n x = self.vgg[idx](x)\n s = self.L2Norm3_3(x)\n fpn.append(s)\n for idx in range(16,23):\n x = self.vgg[idx](x)\n s = self.L2Norm4_3(x)\n fpn.append(s)\n for idx in range(23,30):\n x = self.vgg[idx](x)\n s = self.L2Norm5_3(x)\n fpn.append(s)\n for idx in range(30,len(self.vgg)):\n x = self.vgg[idx](x)\n fpn.append(x)\n for idx,tmp in enumerate(self.extras):\n x = tmp(x)\n x = F.relu(x, inplace=True)\n if idx == 1 or idx==3:\n fpn.append(x)\n #calcu the class_score and location_regress\n loc_x = self.loc[0](fpn[0])\n conf_x = self.conf[0](fpn[0])\n max_conf, _ = torch.max(conf_x[:, 0:3, :, :], dim=1, keepdim=True)\n conf_x = torch.cat((max_conf, conf_x[:, 3:, :, :]), dim=1)\n loc.append(loc_x.permute(0, 2, 3, 1).contiguous())\n conf.append(conf_x.permute(0, 2, 3, 1).contiguous())\n for i in range(1, len(fpn)):\n x = fpn[i]\n # tmpx = self.conf[i](x)\n # tmpy = self.loc[i](x)\n # N,A,H,W = tmpx.shape\n conf.append(self.conf[i](x).permute(0, 2, 3, 1).contiguous())\n loc.append(self.loc[i](x).permute(0, 2, 3, 1).contiguous())\n # tmpx = tmpx.view(N,-1,self.num_classes,H,W)\n # conf.append(tmpx.permute(0,3,4,1,2))\n\n # loc = torch.cat([layer_tmp.view(layer_tmp.size(0), -1) for layer_tmp in loc], 1)\n # conf = torch.cat([layer_tmp.view(layer_tmp.size(0), -1) for layer_tmp in conf], 1)\n loc = torch.cat([layer_tmp.view(-1,self.fpn_sizes[idx]*4*self.num_anchor) for idx,layer_tmp in enumerate(loc)],1)\n conf = torch.cat([layer_tmp.view(-1,self.fpn_sizes[idx]*self.num_anchor*self.num_classes) for idx,layer_tmp in enumerate(conf)],1)\n # output = (loc.view(loc.size(0), -1, 4),self.softmax(conf.view(conf.size(0), -1,self.num_classes)))\n # output = (loc.view(-1,self.num_anchors,4),self.softmax(conf.view(-1,self.num_anchors,self.num_classes)))\n # output = (loc,conf)\n output = (loc.view(loc.size(0), -1, 4),conf.view(conf.size(0), -1, self.num_classes))\n return output\n\n def weights_init(self, m):\n if isinstance(m, nn.Conv2d):\n self.xavier(m.weight.data)\n m.bias.data.zero_()\n def xavier(self, param):\n init.xavier_uniform(param)\n\n\nif __name__==\"__main__\":\n a = torch.ones([1,3,640,640])\n net = S3FD(2)\n print(net)\n c= net(a)","sub_path":"src/network/vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":8879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"561944153","text":"\r\nimport cv2\r\nimport numpy as np\r\n\r\nclass palletHandler(object):\r\n pass\r\n def __init__(self, window_name, mode = \"RGB\", h = 150, w = 500):\r\n self.mode = mode # RGB, BGR, HSV\r\n self.h, self.w = h, w\r\n self.color = np.zeros((h, w, 3), np.uint8)\r\n self.a, self.b, self.c = 0,0,0\r\n self.wind = window_name\r\n cv2.namedWindow(self.wind)\r\n \r\n if self.mode == \"RGB\":\r\n cv2.createTrackbar('R', self.wind, 0, 127, self.na)\r\n cv2.createTrackbar('G', self.wind, 0, 127, self.na)\r\n cv2.createTrackbar('B', self.wind, 0, 127, self.na)\r\n elif self.mode == \"HSV\":\r\n cv2.createTrackbar('H', self.wind, 0, 180, self.na)\r\n cv2.createTrackbar('S', self.wind, 0, 127, self.na)\r\n cv2.createTrackbar('V', self.wind, 0, 127, self.na)\r\n\r\n def update(self):\r\n \"\"\"Returns the pallet RGB\"\"\"\r\n cv2.imshow(self.wind, self.color)\r\n if self.mode == \"RGB\":\r\n self.a = cv2.getTrackbarPos('R', self.wind) * 2\r\n self.b = cv2.getTrackbarPos('G', self.wind) * 2\r\n self.c = cv2.getTrackbarPos('B', self.wind) * 2\r\n self.color[:] = [self.c, self.b, self.a]\r\n elif self.mode == \"HSV\":\r\n self.a = cv2.getTrackbarPos('H', self.wind)\r\n self.b = cv2.getTrackbarPos('S', self.wind) * 2\r\n self.c = cv2.getTrackbarPos('V', self.wind) * 2\r\n self.color[:] = cv2.cvtColor(np.uint8([[[self.a, self.b, self.c]]]), cv2.COLOR_HSV2RGB)[0][0]\r\n\r\n return self.a, self.b, self.c\r\n\r\n def set_values(self, v1, v2, v3):\r\n if self.mode == \"RGB\":\r\n cv2.setTrackbarPos('R', self.wind, v1)\r\n cv2.setTrackbarPos('G', self.wind, v2)\r\n cv2.setTrackbarPos('B', self.wind, v3)\r\n elif self.mode == \"HSV\":\r\n cv2.setTrackbarPos('H', self.wind, v1)\r\n cv2.setTrackbarPos('S', self.wind, v2)\r\n cv2.setTrackbarPos('V', self.wind, v3)\r\n\r\n def na(*_, **__):\r\n pass\r\n","sub_path":"prob1_Tracking/Old/palletHandler.py","file_name":"palletHandler.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"432988486","text":"# -*- coding: utf-8 -*-\n# 爬取网易悦图上的图片 (财经类)\nimport requests\nimport re\nimport json\nimport os\nimport time\nfrom bs4 import BeautifulSoup\nimport pymysql\nimport pymysql.cursors\nfrom yuntu import YunTu\nimport jieba\n\n\nprint('连接到mysql服务器...')\ndb = pymysql.connect(\"localhost\",\"root\",\"123456\",\"specialthing\",charset=\"utf8\")\nprint('连接上了!')\ncursor = db.cursor()\ncursor.execute(\"DROP TABLE IF EXISTS EVENT\")\n\nsql1 = \"\"\"CREATE TABLE EVENT(\n id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n title VARCHAR(100) DEFAULT NULL,\n tag VARCHAR(100) DEFAULT NULL,\n description VARCHAR(500) DEFAULT NULL,\n article VARCHAR(10000) DEFAULT NULL)\"\"\"\n\ncursor.execute(sql1)\nprint('================')\n\nprint('请输入事件:')\nsearchEvent = input(\"searchEvent:\")\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',\n}\n\n\ndata = []\ndata2 = ''\n\n# i为页数,可以设置大一点\nfor i in range(1, 10):\n url = 'http://api.search.sina.com.cn/?c=news&t=&q=%s&page=%d&sort=rel&num=10&ie=utf-8&qq-pf-to=pcqq.c2c' % (searchEvent, i)\n\n r = requests.get(url, headers=headers)\n # print(r.text)\n # 匹配所有的url,'.{3,200}' 为url为长度控制\n temp = re.findall(r'\"url\":\"(http:.{3,200}.shtml)\",', r.text, re.S)\n # print(temp)\n # print(len(temp))\n # 去掉url里面的'\\',这样request就不会出错。\n for j in temp:\n j = j.replace('\\\\', '')\n data.append(j)\nprint(data)\nprint(len(data))\n\n# 遍历data里面的url,逐个网页获取我们要的内容,并存进数据库。 有些文章的article形式不统一,所以会出现一些空的article\nfor url in data:\n r = requests.get(url)\n r.encoding = ('utf-8')\n # 非常致命的一点,如果html代码开头就有注释的话,BeautifulSoup是找不到想要的标签的!!!! 所以破坏掉前面的注释!\n html = r.text.replace('', '')\n # html = open('1.html', 'r', encoding='utf-8').read().replace('', '')\n # print(html)\n title = []\n tag = []\n description = []\n article = []\n\n try:\n soup = BeautifulSoup(html, \"html5lib\") # 配置soup 'html5lib'优点:最好的容错性,以浏览器的方式解析文档,生成HTML5格式的文档 缺点:速度慢,不依赖外部扩展\n\n # title = re.findall(r'', html, re.S)[0] # 有缺陷,meta是写给浏览器和爬虫看的,没有这个也不会影响内容,所有尽量后body里面的属性\n # keywords = re.findall(r'', html, re.S)[0]\n tag = re.findall(r'', html, re.S)[0] # 但是非title属性一般都会在mata里面有,方便浏览器检索。\n description = re.findall(r'', html, re.S)[0]\n # article = re.findall(r'', html, re.S)[0]\n\n # BeautifulSoup去掉特定标签及内容的方法!!!! 对象为 soup对象\n [s.extract() for s in soup('script')]\n [s.extract() for s in soup('style')]\n\n # print(soup.find_all(\"div\", class_='article'))\n\n title = soup.find_all(class_='main-title')[0] # 寻找 'main-title'类的内容\n title = re.sub(r'<[^>]*>', \"\", str(title)) # 去标签!\n article = soup.find_all(\"div\", class_='article')[0]\n article = re.sub(r'<[^>]*>', \"\", str(article)) # 去掉所有的html标签!! 剩下的基本上都是文本内容。\n data2 += article # 字符串拼接,后面传给 wordcloud\n except:\n pass\n # article = re.sub(r'<[^>]*>', \"\", str(article))\n\n # 存入数据库,由于id设置为主键自增,所以这里不需要写id的值 原始数据!!!\n sql = \"INSERT INTO EVENT(title, tag, description, article) VALUES('%s', '%s', '%s', '%s')\" % (title, tag, description, article)\n try:\n cursor.execute(sql)\n db.commit()\n except:\n pass\n\na = []\nprint(data2) # 分词前\nwords = list(jieba.cut(data2)) # 分词后\nfor word in words:\n if len(word) > 1:\n a.append(word)\ntxt = r' '.join(a)\nprint(txt)\nYunTu.wordcloudplot(txt)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cp_specialThing2.py","file_name":"cp_specialThing2.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"150955230","text":"from fabric.api import task, sudo, cd, env, execute\nfrom fabric.utils import warn\nfrom fabkit.common.utils import TRUE_ARGS\n\n\ndef _pre_deploy():\n execute('db.backup')\n\n\n@task\ndef deploy(pre_deploy=True, post_deploy=True):\n \"\"\" Deployment via git pull directly on the server. For use on the older sites\"\"\"\n if pre_deploy in TRUE_ARGS:\n _pre_deploy()\n\n with cd(env.project_root):\n sudo('git pull --rebase', user=env.run_as)\n\n if post_deploy in TRUE_ARGS:\n _post_deploy()\n\n\ndef _post_deploy():\n \"\"\" Some of the older websites may not have django static files\"\"\"\n \n execute('website.app.pip_install')\n execute('website.app.syncdb')\n execute('website.app.migrate')\n\n if env.get('run_collectstatic', True):\n execute('website.app.collectstatic')\n else:\n warn(\"collectstatic skipped\")\n\n execute('website.reload')\n\n custom_post_deploy = env.get('post_deploy', None)\n if custom_post_deploy:\n execute(custom_post_deploy)","sub_path":"fabkit/website/legacy.py","file_name":"legacy.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"73255560","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/breilly/git/fm-orchestrator/module_build_service/db_session.py\n# Compiled at: 2019-12-12 15:53:56\nimport sqlalchemy.event\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.pool import NullPool\nfrom module_build_service import conf\nfrom module_build_service.models import session_before_commit_handlers\n__all__ = ('db_session', )\n\ndef _setup_event_listeners(db_session):\n \"\"\"\n Starts listening for events related to the database session.\n \"\"\"\n if not sqlalchemy.event.contains(db_session, 'before_commit', session_before_commit_handlers):\n sqlalchemy.event.listen(db_session, 'before_commit', session_before_commit_handlers)\n from module_build_service.monitor import db_hook_event_listeners\n db_hook_event_listeners(db_session.bind.engine)\n\n\ndef apply_engine_options(conf):\n options = {'configuration': {'sqlalchemy.url': conf.sqlalchemy_database_uri}}\n if conf.sqlalchemy_database_uri.startswith('sqlite://'):\n options.update({'connect_args': {'check_same_thread': False}, 'poolclass': NullPool})\n else:\n pool_options = {}\n\n def apply_mbs_option(mbs_config_key, sa_config_key):\n value = getattr(conf, mbs_config_key, None)\n if value is not None:\n pool_options[sa_config_key] = value\n return\n\n apply_mbs_option('sqlalchemy_pool_size', 'pool_size')\n apply_mbs_option('sqlalchemy_pool_timeout', 'pool_timeout')\n apply_mbs_option('sqlalchemy_pool_recycle', 'pool_recycle')\n apply_mbs_option('sqlalchemy_max_overflow', 'max_overflow')\n options.update(pool_options)\n return options\n\n\nengine_opts = apply_engine_options(conf)\nengine = sqlalchemy.engine_from_config(**engine_opts)\nsession_factory = sessionmaker(bind=engine)\ndb_session = scoped_session(session_factory)\n_setup_event_listeners(db_session)","sub_path":"pycfiles/module-build-service-3.1.0.tar/db_session.py","file_name":"db_session.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"329063296","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@authors: Vanderlei Pereira, Thiago Maurici\r\n\"\"\"\r\n\r\nimport asyncio\r\nimport random\r\nimport websockets\r\n\r\nPORT = 50008\r\nHOST = '127.0.0.1'\r\n\r\nasync def a_plus_b(websocket, path):\r\n while True:\r\n n1 = float(input(\"Número A: \"))\r\n n2 = float(input(\"Número B: \"))\r\n await websocket.send(str(n1+n2))\r\n await asyncio.sleep(random.random() * 3)\r\n\r\n\r\nstart_server = websockets.serve(a_plus_b, HOST, PORT)\r\nasyncio.get_event_loop().run_until_complete(start_server)\r\nasyncio.get_event_loop().run_forever()","sub_path":"WebSockets/websocket_server.py","file_name":"websocket_server.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"533024666","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Bullet(Sprite):\n \"\"\"子弹类,由飞船进行发射\"\"\"\n def __init__(self,ai_settings,screen,ship):\n \"\"\"飞船所处的位置创建一个子弹对象\"\"\"\n # 确保父类正确的初始化\n super().__init__() \n #self.ai_settings=ai_settings\n self.screen=screen\n # 设置子弹矩形\n self.rect=pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)\n # 子弹位置由飞船决定\n self.rect.centerx=ship.rect.centerx\n self.rect.top=ship.rect.top\n\n # 设置子弹位置,颜色\n self.y=float(self.rect.y)\n self.color=ai_settings.bullet_color\n self.speed_factor=ai_settings.bullet_speed_factor\n\n def update(self):\n \"\"\"子弹向上运动\"\"\"\n # 更新子弹位置\n self.y -=self.speed_factor\n\n # 子弹rect位置\n self.rect.y=self.y\n \n def draw_bullet(self):\n \"\"\"屏幕上绘制子弹\"\"\"\n pygame.draw.rect(self.screen,self.color,self.rect)","sub_path":"bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"17362563","text":"# https://atcoder.jp/contests/dp/tasks/dp_a\n\nn=int(input())\nh=list(map(int, input().split()))\n\ndp=[10**9 for i in range(n)]\ndp[0]=0\nfor i in range(n):\n if i+1
\", outfile)\n\n dat = read.data(infile, file_format=P.intype, cfg=cfg, xg=xg)\n\n write.data(outfile, dat, file_format=P.format, xg=xg)\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"scripts/convert_data.py","file_name":"convert_data.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"404898628","text":"import argparse\nfrom app.core.main import Worker\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--s', help='source file', type=str)\n parser.add_argument('--d', help='target file', type=str)\n parser.add_argument('--m', help='method, possible variants '\n '(transpose,sum,determinant)', type=str)\n args = parser.parse_args()\n worker = Worker(args.s, args.d, args.m)\n worker.run()\n","sub_path":"app/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"50530967","text":"import json, re\nfrom numbers import Number\n\nTAB_INDENT = ' '\nregion_regex = re.compile('(us|eu|ap|sa)-(east|west|south|northeast|southeast|central)-(1|2)')\nspace = re.compile('\\s')\nregion_path = ''\n\ndef get_info(data):\n request_headers = data['request_headers']\n request_body = data['request_body']\n warning = True\n\n host = request_headers['Host'].split('.')\n service = host[-3]\n if region_regex.findall(service):\n service = host[-4]\n\n with open('objectidmap.json') as fl:\n object_map = json.load(fl)\n for s in object_map:\n if s != 'default' and service in object_map[s]['serviceNames']:\n service = s\n warning = False\n\n action = request_body['Action']\n\n return service, warning, action\n\ndef codify_json(data):\n '''\n Return HTML block representing a json object. The portions of\n the html corresponding to key/values will contain specfic data-json\n attributes to aid with front-end traversal.\n '''\n def span(c, v, sel=''):\n if sel:\n return '%s' % (c, sel, v)\n else:\n return '%s' % (c, v)\n\n def dquote(s):\n return '\"%s\"' % s\n\n def tab(n):\n return TAB_INDENT * n\n\n def apply_attrs(d, sel='', depth=0):\n global region_path\n ################################\n # Handle the terminal cases\n ################################\n if d is None:\n return span('value', span('literal', 'null', sel))\n\n if isinstance(d, bool):\n return span('value', span('literal', str(d).lower(), sel))\n\n if isinstance(d, basestring):\n # if we have a region, save its path\n if region_regex.findall(d) and not space.findall(d) and region_path == '':\n region_path = sel\n return span('value', dquote(span('string', d, sel)))\n\n if isinstance(d, Number):\n return span('value', span('number', d, sel))\n\n ################################\n # Now for the recursive steps\n ################################\n elif isinstance(d, dict):\n num_keys = len(d)\n\n # Don't bother creating a new line and indenting for an empty dict\n if num_keys == 0:\n s = '{}'\n else:\n s = '{\\n'\n for i, (k,v) in enumerate(d.iteritems()):\n # The current selector for this key is where we are plus\n # ['key']\n this_sel = sel + '%s,' % k\n\n # Indent for formatting\n s += tab(depth+1)\n\n # Add an attribute span around the key name\n s += dquote(span('attribute', k)) + ': '\n\n # Append the formatted value\n s += apply_attrs(v, this_sel, depth+1)\n\n # Add commas and newlines as needed\n if i :rotating_light: Race called in *{}*\".format(\n payload.division.upper()\n ),\n \"mrkdwn_in\": [\"fields\"],\n \"author_name\": \"Elections Bot\",\n \"author_icon\": \"https://pbs.twimg.com/profile_images/998954486205898753/gbb2psb__400x400.jpg\", # noqa\n \"title\": \"Winner for {}\".format(payload.office),\n \"title_link\": payload.page_url,\n \"text\": WINNING,\n \"footer\": \"Associated Press\",\n \"fields\": [\n {\n \"title\": \"Winning vote\",\n \"value\": \"{}% | {:,} votes\".format(\n int(round(float(payload.vote_percent) * 100)),\n int(payload.vote_count),\n ),\n \"short\": True,\n },\n {\n \"title\": \"Precincts reporting\",\n \"value\": \"{}%\".format(\n int(round(float(\n payload.precincts_reporting_percent\n ) * 100))\n ),\n \"short\": True,\n },\n ],\n \"ts\": int(time.time()),\n }\n ]\n\n client = get_client()\n\n if app_settings.AWS_S3_BUCKET == \"interactives.politico.com\":\n bot_channel = \"#elections-bot\"\n else:\n bot_channel = \"#elections-bot-stg\"\n\n client.chat.post_message(\n bot_channel,\n \"\",\n attachments=bot_attachment_data,\n as_user=False,\n username=\"Elections Bot\",\n )\n","sub_path":"aploader/tasks/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"219586745","text":"import csv\n\ndef asList(filepath):\n \n #as a list\n with open(filepath,'rt')as f:\n data = csv.reader(f)\n print(data)\n count = 0\n for row in data:\n print(row)\n count = count+1\n print(count) \n\ndef asDict(filepath):\n \n #as a dictionary\n reader = csv.DictReader(open(filepath))\n print(reader)\n for raw in reader:\n print(raw)\n\n\nfilepath = './Social_Network_Ads.csv'\nasList(filepath)\nasDict(filepath)","sub_path":"Class Work/Day 9 - Files/socialFileRead.py","file_name":"socialFileRead.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"647500612","text":"import sys\nsys.stdin = open('7465.txt')\n\ndef find(n):\n if n == p[n]:\n return n\n else:\n return find(p[n])\n\ndef union(s, e):\n n1, n2 = find(s), find(e)\n if n1 > n2:\n p[n1] = n2\n else:\n p[n2] = n1\n\nT = int(input())\nfor t in range(1, T + 1):\n N, M = map(int, input().split())\n num = [list(map(int, input().split())) for _ in range(M)]\n p = list(range(N + 1))\n\n for i in range(M):\n s, e = num[i][0], num[i][1]\n union(s, e)\n \n ans = set()\n for i in p:\n ans.add(find(i))\n\n print('#{} {}'.format(t, len(ans) - 1))","sub_path":"algorithm/0423/7465_창용마을무리의개수.py","file_name":"7465_창용마을무리의개수.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"373327375","text":"import os, sys, csv, argparse, re\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SQLContext, HiveContext, SparkSession\n\ndef identifyByHeader(f,colDel):\n return len(next(csv.reader(f, delimiter=colDel)))\n\ndef parseData(f,colDel):\n arr={}\n for rec in csv.reader(f, delimiter=colDel):\n arr[len(rec)]=arr.setdefault(len(rec),0)+1\n return max(arr,key=arr.get)\n\ndef adjustNewline(wh,reader,numOfAttr,colDel,recDel,ignoreHdr):\n jnval=':jn:'\n jn=[jnval]\n hdrLine=next(reader) if ignoreHdr else reader\n for rec in reader:\n irec=rec\n while len(irec)?/'*&^%$#@!|\\~`\\\"]\",\"\",w).replace(removeChar,'') for w in row])\n sqlContext = SQLContext(sc)\n sqlContext.sql(\"drop table IF EXISTS \"+dataBase+\".temptable_\"+hiveTable)\n df = getDataFrame(sqlContext,dataList,headerExist)\n df.write.mode('overwrite').saveAsTable(dataBase+\".temptable_\"+hiveTable)\n \n\ndef main(args, sc, hc):\n absFile=args.fileToClean\n hdrBool=args.headerAvail\n colDel=args.delimiter\n ignoreHdr=args.ignoreHeader\n tmpFile=args.outFile\n recDel='\\n'\n dataBase='bbiuserdb'\n hiveTable='departments'\n fh=open(absFile,'rb')\n numOfAttr=identifyByHeader(fh,colDel) if hdrBool else parseData(fh,colDel)\n readCSVWriteHive(sc, fh, 1.6, colDel=colDel, headerExist=hdrBool, dataBase=dataBase, hiveTable=hiveTable) \n #wh.close()\n fh.close()\n\ndef parseArguments(parser):\n # Positional mandatory arguments\n parser.add_argument(\"-f\", \"--fileToClean\", help=\"Absolute FileName - File to be cleansed\")\n parser.add_argument(\"-t\", \"--headerAvail\", help=\"True/False - Data to be cleansed contains header record (Attribute Names)\")\n parser.add_argument(\"-d\", \"--delimiter\", help=\"[,:|] Column Delimiter of the data file\")\n # Optional arguments\n parser.add_argument(\"-o\", \"--outFile\", help=\"Output File\", default='tmp_file')\n parser.add_argument(\"-i\", \"--ignoreHeader\", help=\"Ignore the First Record\", default=True)\n # Print version\n parser.add_argument(\"--version\", action=\"version\", version='%(prog)s - Version 1.0')\n # Parse arguments\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n # Parse the arguments\n parser = argparse.ArgumentParser(\"Perform Cleansing of data specific to Client\")\n args = parseArguments(parser)\n\n # Raw print arguments\n print(\"You are running the script with arguments: \")\n for a in args.__dict__:\n if args.__dict__[a]:\n print(\"Values provided for : \"+ str(a) + \": \" + str(args.__dict__[a]))\n else:\n parser.print_help()\n sys.exit(0)\n sc = SparkContext()\n hc = SparkSession.builder.enableHiveSupport().getOrCreate()\n\n main(args,sc,hc)\n","sub_path":"genericProcess/spark/PySpark/GenericProcesses/cleanse.py","file_name":"cleanse.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"214926109","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom bs4 import BeautifulSoup\nimport traceback, sys\nfrom datetime import datetime, timedelta\nimport re\nfrom dateutil.parser import parse as date_parser\nfrom scraper.items import NewsItem\nimport json\nfrom .redis_spiders import RedisSpider\nimport datetime\n\n# from scrapy_redis.spiders import RedisSpider\n\n# class LtnSpider(RedisSpider):\nclass Ltn_keywordsSpider(scrapy.Spider):\n name = \"ltn_keywords\"\n \n\n def start_requests(self):\n \n if isinstance(self, RedisSpider):\n return\n \n # url\n requests=[{\n \"url\": 'https://www.myip.com/',\n \"url_pattern\":\"https://search.ltn.com.tw/list?keyword={}&type=all&sort=date&start_time={}&end_time={}&sort=date&type=all&page=1\",\n \"keywords_list\": ['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'],\n \"interval\": 3600 * 2,\n \"days_limit\": 3600 * 24 * 2,\n \"media\": \"ltn\",\n \"name\": \"ltn_keywords\",\n \"scrapy_key\": \"ltn_keywords:start_urls\",\n \"priority\": 1,\n \"search\": False,\n \"enabled\": True,\n }]\n \n for request in requests:\n yield scrapy.Request(request['url'],\n meta=request,\n dont_filter=True,\n callback=self.parse)\n \n def parse(self, response):\n meta = response.meta\n meta['page'] = 1\n #搜尋時間範圍 \n now=datetime.datetime.now()\n end_time=now.strftime(\"%Y%m%d\")\n time_delta=datetime.timedelta(days=2) \n start_time=(now-time_delta).strftime(\"%Y%m%d\")\n for keyword in meta['keywords_list']:\n url=meta['url_pattern'].format(keyword,start_time,end_time)\n yield scrapy.Request(url,\n meta=meta,\n dont_filter=True,\n callback=self.parse_list)\n \n\n def parse_list(self, response):\n meta = response.meta\n soup = BeautifulSoup(response.body, 'html.parser')\n if(len(soup.findAll(class_=\"cont\"))!=0):\n for s in soup.findAll(class_=\"cont\"):\n url = s.find('a').get('href')\n if 'ec.ltn.com.tw' in url: \n yield response.follow(url,\n meta=meta,\n callback=self.parse_article_ec) \n elif ('news.ltn.com.tw' in url):\n yield response.follow(url,\n meta=meta,\n callback=self.parse_article_news)\n \n current_page = re.search(\"page=(\\d+)\", response.url).group(1)\n next_page = re.sub(\"page=(\\d+)\", \"page={}\".format(int(current_page) + 1), response.url)\n \n yield scrapy.Request(next_page,\n dont_filter=True,\n meta=meta,\n callback=self.parse_list)\n \n def parse_article_ec(self, response):\n meta = response.meta\n soup = BeautifulSoup(response.body, 'html.parser')\n \n metadata = {'category':'','image_url':[]}\n \n content, author, metadata['image_url'] = self.parse_content_author_image_ec(soup)\n \n title=soup.find(class_=\"whitecon boxTitle boxText\").find('h1').string \n metadata['category'] = '自由財經'\n \n item = NewsItem()\n item['url'] = response.url\n item['article_title'] = title\n item['author'] = author\n item['author_url'] = []\n item['comment'] = []\n item['date'] = self.parse_datetime(soup)\n item['content'] = content\n item['metadata'] = metadata\n item['content_type'] = 0\n item['media'] = 'ltn'\n item['proto'] = 'LTN_PARSE_ITEM'\n return item\n\n def parse_article_news(self, response):\n meta = response.meta\n soup = BeautifulSoup(response.body, 'html.parser')\n \n metadata = {'category':'','image_url':[]}\n \n content, author, metadata['image_url'] = self.parse_content_author_image_news(soup)\n \n if 'title' in meta and 'tagText' in meta:\n title = meta['title']\n metadata['category'] = meta.get('tagText', \"\")\n else:\n title, metadata['category'] = self.parse_title_metadata(soup)\n \n item = NewsItem()\n item['url'] = response.url\n item['article_title'] = title\n item['author'] = author\n item['author_url'] = []\n item['comment'] = []\n item['date'] = self.parse_datetime(soup)\n item['content'] = content\n item['metadata'] = metadata\n item['content_type'] = 0\n item['media'] = 'ltn'\n item['proto'] = 'LTN_PARSE_ITEM'\n return item\n\n\n def parse_datetime(self,soup):\n date = soup.find('meta', {'name':'pubdate'})\n if date:\n return date['content'].replace('Z', '+0800')\n \n date = soup.find('span', {'class':'time'})\n if date:\n return date_parser(date.text).strftime('%Y-%m-%dT%H:%M:%S+0800')\n\n date = soup.find('div', {'class':'article_header'})\n if date:\n return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S+0800')\n \n date = soup.find('div', {'class':'writer'})\n if date:\n return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800')\n\n def parse_title_metadata(self,soup): \n title = soup.find('title').text.replace(' - 自由時報電子報', '').replace(' 自由電子報', '')\n title_ = title.split('-')\n if not title_[-1]:\n del title_[-1]\n if len(title_) > 2:\n category = title_[-1]\n del title_[-1]\n ti = ''.join(x for x in title_)\n return ti.strip(), category.strip()\n elif len(title_) == 2:\n category = title_[1]\n ti = title_[0]\n return ti.strip(), category.strip()\n elif '3C科技' in title_[0]:\n category = '3C科技'\n ti = title_[0].replace('3C科技', '')\n return ti.strip(), category\n elif '玩咖Playing' in title_[0]: \n category = '玩咖Playing'\n ti = title_[0].replace('玩咖Playing', '') \n return ti.strip(), category\n else:\n category = ''\n ti = title_[0]\n return ti.strip(), category\n \n \n def find_author(self,list_text):\n list_text = [x for x in list_text if x!='文']\n tmp = [x for x in list_text if '記者' in x]\n if tmp:\n author = tmp[0].replace('記者', '').replace('攝影', '').strip() \n else:\n author = min(list_text, key=len)\n return author\n \n def parse_content_author_image_ec(self,soup): \n \n # content\n content=''\n for text in soup.find(class_=\"text\").findAll('p')[1:4]:\n content=content+text.get_text()\n for text in soup.find(class_=\"text\").findAll('p')[5:-2]:\n content=content+text.get_text()\n \n # author\n au = ''\n author_text=soup.find(class_='text').findAll('p')[1].get_text()\n begin=author_text.rfind('〔')\n end=author_text.find('/')\n if begin!=-1 & end!=-1:\n au=author_text[begin+1:end]\n if '記者' in au:\n au=au.replace('記者', '')\n \n # image\n image_url = []\n image_url.append(soup.find(class_='text').find(class_=\"lazy_imgs_ltn\")['data-src'])\n\n return content, au, image_url\n\n def parse_content_author_image_news(self,soup): \n content = soup.find('div',{'itemprop':'articleBody'})\n\n # image\n image_url = []\n for photo in content.find_all('div','photo boxTitle'):\n image_url.append(photo.find('img')['src'])\n\n # content\n for appE1121 in content.find_all('p','appE1121'):\n appE1121.clear()\n for photo in content.find_all('div','photo boxTitle'):\n photo.clear()\n for photo in content.find_all('span','ph_b ph_d1'):\n photo.clear()\n for tag in content.find_all('script'):\n tag.clear()\n content = ''.join(x.text for x in content.find_all('p') if x.text!='爆')\n content = ''.join(content.split())\n\n #author\n au = ''\n reg = re.compile(r'([\\D*/\\D*]|〔\\D*/\\D*〕)', re.VERBOSE)\n author_reg = reg.findall(content)\n if author_reg:\n au = author_reg[0].split('/')[0].replace('〔', '').replace('[', '').replace('記者', '').replace('編譯', '')\n\n if not au:\n author = soup.find('div', {'class':'writer boxTitle'})\n if author: \n au = author.find('a')['data-desc']\n if not au:\n author = soup.find('p', {'class':'auther'})\n if author:\n tmp = author.find('span').text.split('/')\n au = self.find_author(tmp)\n if not au: \n author = soup.find('p', {'class':'writer'})\n if author:\n tmp = author.find('span').text.split('/')\n au = self.find_author(tmp)\n if not au: \n author = soup.find('div', {'class':'writer'})\n if author:\n tmp = author.find('span').text.split('/')\n au = self.find_author(tmp)\n if not au: \n author = soup.find('div', {'class':'conbox_tit boxTitle'})\n if author:\n au = author.find('a')['data-desc']\n if not au:\n author = soup.find('div', {'class':'article_header'})\n if author:\n tmp = author.find('span').text.split('/')\n au = self.find_author(tmp)\n if not au:\n try:\n author = soup.find('div', {'itemprop':'articleBody'}).find('p')\n except:\n author = ''\n if author:\n if '/' in author.text:\n tmp = author.text.split('/')\n au = self.find_author(tmp)\n if author.find('strong'):\n au = author.find('strong').text.split('◎')[1].replace('記者', '').replace('攝影', '').strip()\n if '■' in author.text:\n au = author.text.replace('■', '')\n if not au:\n try:\n author = soup.find('div', {'itemprop':'articleBody'}).find('span', {'class':'writer'})\n except:\n author = ''\n if author:\n if '/' in author.text:\n tmp = author.text.split('/')\n au = self.find_author(tmp)\n if not au:\n try:\n author = soup.find('div', {'itemprop':'articleBody'}).find('h4')\n except:\n author = ''\n if author:\n if '/' in author.text:\n tmp = author.text.split('/')\n au = self.find_author(tmp)\n elif '◎' in author.text:\n au = author.text.replace('◎', '')\n return content, au, image_url","sub_path":"info-scraper-master/scraper/scraper/spiders/ltn_keywords.py","file_name":"ltn_keywords.py","file_ext":"py","file_size_in_byte":11485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"384746653","text":"## from config import Config as Config\r\n\r\nimport xbmc,xbmcaddon,xbmcplugin,os\r\n_addon_id=\"plugin.program.RepositoriesBrowser\"; _addon_name=\"Repository Highway\"; \r\n_addon=xbmcaddon.Addon(id=_addon_id); \r\n\r\ndef gAI(t):\r\n\ttry: return _addon.getAddonInfo(t)\r\n\texcept: \r\n\t\t#if t==\"name\": return _addon_name\r\n\t\t#else: return \"\"\r\n\t\treturn \"\"\r\n\r\nclass Config:\r\n\taddon_id=_addon_id\r\n\t#name='Repositories Browser'\r\n\taddon=_addon\r\n\thandle=0\r\n\tname=gAI('name'); \r\n\t#name=\"XBMCHUB Repositories Browser\"; \r\n\tpath=gAI('path'); \r\n\t#profile=xbmc.translatePath(gAI('profile'))\r\n\tdisclaimer=gAI('disclaimer'); description=gAI('description'); summary=gAI('summary'); \r\n\ticon=gAI('icon'); fanart=gAI('fanart'); \r\n\taddon_type=gAI('type'); author=gAI('author'); version=gAI('version'); stars=gAI('stars'); changelog=gAI('changelog'); \r\n\t\r\n\tartPath=xbmc.translatePath(os.path.join(path,'art'))\r\n\t\r\n\t\r\n\tACTION_PREVIOUS_MENU \t\t= 10\t## ESC action\r\n\tACTION_NAV_BACK \t\t\t\t= 92\t## Backspace action\r\n\tACTION_MOVE_LEFT \t\t\t\t= 1\t## Left arrow key\r\n\tACTION_MOVE_RIGHT \t\t\t= 2\t## Right arrow key\r\n\tACTION_MOVE_UP \t\t\t\t\t= 3\t## Up arrow key\r\n\tACTION_MOVE_DOWN \t\t\t\t= 4\t## Down arrow key\r\n\tACTION_MOUSE_WHEEL_UP \t= 104\t## Mouse wheel up\r\n\tACTION_MOUSE_WHEEL_DOWN = 105\t## Mouse wheel down\r\n\tACTION_MOUSE_DRAG \t\t\t= 106\t## Mouse drag\r\n\tACTION_MOUSE_MOVE \t\t\t= 107\t## Mouse move\r\n\tdef gSetting(self,setting):\r\n\t\ttry: return self.addon.getSetting(setting)\r\n\t\texcept: return \"\"\r\n\tdef set_setting(self,setting,value):\r\n\t\tself.addon.setSetting(id=setting,value=value)\r\n\tdef get_string(self, string_id):\r\n\t\ttry: return self.addon.getLocalizedString(string_id)\r\n\t\texcept: return \"\"\r\n\tdef get_id(self):\r\n\t\ttry: return self.addon.getAddonInfo('id')\r\n\t\texcept: return self.addon_id\r\n\tdef note(self,title='',msg='',delay=5000,image='http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/US_99_%281961%29.svg/40px-US_99_%281961%29.svg.png'):\r\n\t\txbmc.executebuiltin('XBMC.Notification(\"%s\",\"%s\",%d,\"%s\")' % (title,msg,delay,image))\r\n\tdef show_settings(self): self.addon.openSettings()\r\n\tdef eod(self):\r\n\t\txbmcplugin.endOfDirectory(self.handle)\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t","sub_path":"Netxeon/plugin.program.RepositoriesBrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"171126496","text":"'''\n3D Printer: POE Lab 2\n\nThis script pulls data sent over USB\nby the Ardino and saves it to be plotted\nby numpy\n\nauthors: mpatil99, awenstrup\n'''\n#Import statements\nimport serial\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Variable definitions\n\nport = '/dev/ttyACM0'\nbaudRate = 9600\n\na = 8442\nb = -0.9307\n\nvalues = list()\n\n\n\n#Setup\nserialPort = serial.Serial(port=port, baudrate=9600, timeout=None)\n\n\ndef adc_to_dist(num):\n if num > 0:\n return a * (num ** b)\n else:\n return 150\n\ndef input_to_scatter(l, xres, yres):\n format_list(l)\n array = np.array(l).reshape(yres, xres)\n print(array)\n print(array.shape)\n return array\n\ndef format_list(l):\n for i, n in enumerate(l):\n if n > 150:\n l[i] = 150\n if n < 15:\n l[i] = 15\n\n return l.reverse()\n\ndef test_plot():\n l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n scatter = input_to_scatter(l, 4, 3)\n\n # make these smaller to increase the resolution\n dx, dy = 2, 2\n\n x = range(0, 8 + dx, dx)\n y = range(0, 6 + dy, dy)\n\n print(x)\n print(y)\n\n plt.pcolormesh(x, y, scatter)\n plt.xlabel(\"Theta (degrees)\")\n plt.ylabel(\"Phi (degrees)\")\n plt.title(\"3D Scan of letter 'A'\")\n plt.show()\n\ntime.sleep(1)\n\n#Loop\nrunning = True\nwhile running:\n\n line = serialPort.readline()\n if len(line) > 0:\n dist = adc_to_dist(int(line.decode().strip()))\n print('Distance is ', dist)\n values.append(dist)\n print()\n\n if len(values) == 600:\n running = False\n\n x = range(0, 60 + 2, 2)\n y = range(0, 40 + 2, 2)\n\n plt.pcolormesh(x, y, input_to_scatter(values, 30, 20))\n plt.xlabel(\"Theta (degrees)\")\n plt.ylabel(\"Phi (degrees)\")\n plt.title(\"3D Scan of letter 'A'\")\n plt.show()\n","sub_path":"Firmware/pulldata.py","file_name":"pulldata.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"38206454","text":"import altair as alt\nfrom vega_datasets import data\n\ndef make_static_chart():\n '''\n '''\n return alt.Chart(data=data.cars.url).mark_circle(size=60).encode(\n x='Horsepower:Q',\n y='Miles_per_Gallon:Q',\n color='Origin:N'\n ).interactive()\n\ndef make_interactive_chart():\n '''\n '''\n pts = alt.selection(type=\"single\", encodings=['x'])\n\n rect = alt.Chart(data.movies.url).mark_rect().encode(\n alt.X('IMDB_Rating:Q', bin=True),\n alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),\n alt.Color('count()',\n scale=alt.Scale(scheme='greenblue'),\n legend=alt.Legend(title='Total Records')\n )\n )\n\n circ = rect.mark_point().encode(\n alt.ColorValue('grey'),\n alt.Size('count()',\n legend=alt.Legend(title='Records in Selection')\n )\n ).transform_filter(\n pts\n )\n\n bar = alt.Chart(data.movies.url).mark_bar().encode(\n x='Major_Genre:N',\n y='count()',\n color=alt.condition(pts, alt.ColorValue(\"steelblue\"), alt.ColorValue(\"grey\"))\n ).properties(\n selection=pts,\n width=550,\n height=200\n )\n\n return alt.vconcat(\n rect + circ,\n bar\n ).resolve_legend(\n color=\"independent\",\n size=\"independent\"\n )\n","sub_path":"src/altair.py","file_name":"altair.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"190564665","text":"import logging\nfrom unittest import TestCase\n\nfrom icon_azure_ad_admin.actions import GetUserInfo\nfrom icon_azure_ad_admin.connection import Connection\n\nimport json\n\n\nclass TestGetUserInfo(TestCase):\n def test_get_user_info(self):\n log = logging.getLogger(\"TestLogger\")\n\n test_connection = Connection()\n test_get_user_info = GetUserInfo()\n\n test_connection.logger = log\n test_get_user_info.logger = log\n\n with open(\"../tests/get_user_info.json\") as file:\n data = json.load(file)\n connection_params = data.get(\"body\").get(\"connection\")\n\n action_params = {\n \"user_id\": \"user@example.com\"\n }\n\n test_connection.connect(connection_params)\n test_get_user_info.connection = test_connection\n\n result = test_get_user_info.run(action_params)\n expected = {'user_information': {'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',\n 'businessPhones': [], 'displayName': 'Joey McAdams', 'givenName': 'Joey',\n 'jobTitle': 'Sr. Software Engineer', 'mail': '', 'mobilePhone': '',\n 'officeLocation': '', 'preferredLanguage': '', 'surname': 'McAdams',\n 'userPrincipalName': 'user@example.com',\n 'id': '08290005-23ba-46b4-a377-b381d651a2fb', 'accountEnabled': True}}\n self.assertEqual(result, expected)\n","sub_path":"azure_ad_admin/unit_test/test_get_user_info.py","file_name":"test_get_user_info.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"348708868","text":"# -*- coding: utf-8 -*-\n\"\"\"Test suite for repos bootstrapping (install).\"\"\"\nimport os\nimport sys\nfrom collections import namedtuple\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nimport appdirs\nimport pytest\n\nfrom igniter.bootstrap_repos import BootstrapRepos\nfrom igniter.bootstrap_repos import PypeVersion\nfrom pype.lib import OpenPypeSettingsRegistry\n\n\n@pytest.fixture\ndef fix_bootstrap(tmp_path, pytestconfig):\n bs = BootstrapRepos()\n bs.live_repo_dir = pytestconfig.rootpath / 'repos'\n bs.data_dir = tmp_path\n return bs\n\n\ndef test_pype_version():\n v1 = PypeVersion(1, 2, 3)\n assert str(v1) == \"1.2.3\"\n\n v2 = PypeVersion(1, 2, 3, client=\"x\")\n assert str(v2) == \"1.2.3-x\"\n assert v1 < v2\n\n v3 = PypeVersion(1, 2, 3, variant=\"staging\")\n assert str(v3) == \"1.2.3-staging\"\n\n v4 = PypeVersion(1, 2, 3, variant=\"staging\", client=\"client\")\n assert str(v4) == \"1.2.3-client-staging\"\n assert v3 < v4\n assert v1 < v4\n\n v5 = PypeVersion(1, 2, 3, variant=\"foo\", client=\"x\")\n assert str(v5) == \"1.2.3-x\"\n assert v4 < v5\n\n v6 = PypeVersion(1, 2, 3, variant=\"foo\")\n assert str(v6) == \"1.2.3\"\n\n v7 = PypeVersion(2, 0, 0)\n assert v1 < v7\n\n v8 = PypeVersion(0, 1, 5)\n assert v8 < v7\n\n v9 = PypeVersion(1, 2, 4)\n assert v9 > v1\n\n v10 = PypeVersion(1, 2, 2)\n assert v10 < v1\n\n v11 = PypeVersion(1, 2, 3, path=Path(\"/foo/bar\"))\n assert v10 < v11\n\n assert v5 == v2\n\n sort_versions = [\n PypeVersion(3, 2, 1),\n PypeVersion(1, 2, 3),\n PypeVersion(0, 0, 1),\n PypeVersion(4, 8, 10),\n PypeVersion(4, 8, 20),\n PypeVersion(4, 8, 9),\n PypeVersion(1, 2, 3, variant=\"staging\"),\n PypeVersion(1, 2, 3, client=\"client\")\n ]\n res = sorted(sort_versions)\n\n assert res[0] == sort_versions[2]\n assert res[1] == sort_versions[6]\n assert res[2] == sort_versions[1]\n assert res[-1] == sort_versions[4]\n\n str_versions = [\n \"5.5.1\",\n \"5.5.2-client\",\n \"5.5.3-client-strange\",\n \"5.5.4-staging\",\n \"5.5.5-staging-client\",\n \"5.6.3\",\n \"5.6.3-staging\"\n ]\n res_versions = []\n for v in str_versions:\n res_versions.append(PypeVersion(version=v))\n\n sorted_res_versions = sorted(res_versions)\n\n assert str(sorted_res_versions[0]) == str_versions[0]\n assert str(sorted_res_versions[-1]) == str_versions[5]\n\n with pytest.raises(ValueError):\n _ = PypeVersion()\n\n with pytest.raises(ValueError):\n _ = PypeVersion(major=1)\n\n with pytest.raises(ValueError):\n _ = PypeVersion(version=\"booobaa\")\n\n v11 = PypeVersion(version=\"4.6.7-client-staging\")\n assert v11.major == 4\n assert v11.minor == 6\n assert v11.subversion == 7\n assert v11.variant == \"staging\"\n assert v11.client == \"client\"\n\n\ndef test_get_main_version():\n ver = PypeVersion(1, 2, 3, variant=\"staging\", client=\"foo\")\n assert ver.get_main_version() == \"1.2.3\"\n\n\ndef test_get_version_path_from_list():\n versions = [\n PypeVersion(1, 2, 3, path=Path('/foo/bar')),\n PypeVersion(3, 4, 5, variant=\"staging\", path=Path(\"/bar/baz\")),\n PypeVersion(6, 7, 8, client=\"x\", path=Path(\"boo/goo\"))\n ]\n path = BootstrapRepos.get_version_path_from_list(\n \"3.4.5-staging\", versions)\n\n assert path == Path(\"/bar/baz\")\n\n\ndef test_search_string_for_pype_version(printer):\n strings = [\n (\"3.0.1\", True),\n (\"foo-3.0\", False),\n (\"foo-3.0.1\", True),\n (\"3\", False),\n (\"foo-3.0.1-client-staging\", True),\n (\"foo-3.0.1-bar-baz\", True)\n ]\n for ver_string in strings:\n printer(f\"testing {ver_string[0]} should be {ver_string[1]}\")\n assert PypeVersion.version_in_str(ver_string[0])[0] == ver_string[1]\n\n\n@pytest.mark.slow\ndef test_install_live_repos(fix_bootstrap, printer):\n pype_version = fix_bootstrap.create_version_from_live_code()\n sep = os.path.sep\n expected_paths = [\n f\"{pype_version.path}{sep}repos{sep}avalon-core\",\n f\"{pype_version.path}{sep}repos{sep}avalon-unreal-integration\",\n f\"{pype_version.path}\"\n ]\n printer(\"testing zip creation\")\n assert os.path.exists(pype_version.path), \"zip archive was not created\"\n fix_bootstrap.add_paths_from_archive(pype_version.path)\n for ep in expected_paths:\n assert ep in sys.path, f\"{ep} not set correctly\"\n\n printer(\"testing pype imported\")\n del sys.modules[\"pype\"]\n import pype # noqa: F401\n\n # test if pype is imported from specific location in zip\n assert \"pype\" in sys.modules.keys(), \"Pype not imported\"\n assert sys.modules[\"pype\"].__file__ == \\\n f\"{pype_version.path}{sep}pype{sep}__init__.py\"\n\n\ndef test_find_pype(fix_bootstrap, tmp_path_factory, monkeypatch, printer):\n\n test_pype = namedtuple(\"Pype\", \"prefix version suffix type valid\")\n\n test_versions_1 = [\n test_pype(prefix=\"foo-v\", version=\"5.5.1\",\n suffix=\".zip\", type=\"zip\", valid=False),\n test_pype(prefix=\"bar-v\", version=\"5.5.2-client\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"baz-v\", version=\"5.5.3-client-strange\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"bum-v\", version=\"5.5.4-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"zum-v\", version=\"5.5.5-client-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"fam-v\", version=\"5.6.3\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"5.6.3-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"fim-v\", version=\"5.6.3\",\n suffix=\".zip\", type=\"zip\", valid=False),\n test_pype(prefix=\"foo-v\", version=\"5.6.4\",\n suffix=\".txt\", type=\"txt\", valid=False),\n test_pype(prefix=\"foo-v\", version=\"5.7.1\",\n suffix=\"\", type=\"dir\", valid=False),\n ]\n\n test_versions_2 = [\n test_pype(prefix=\"foo-v\", version=\"10.0.0\",\n suffix=\".txt\", type=\"txt\", valid=False),\n test_pype(prefix=\"lom-v\", version=\"7.2.6\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"bom-v\", version=\"7.2.7-client\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"woo-v\", version=\"7.2.8-client-strange\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"loo-v\", version=\"7.2.10-client-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"kok-v\", version=\"7.0.1\",\n suffix=\".zip\", type=\"zip\", valid=True)\n ]\n\n test_versions_3 = [\n test_pype(prefix=\"foo-v\", version=\"3.0.0\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"goo-v\", version=\"3.0.1\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"hoo-v\", version=\"4.1.0\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"4.1.2\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"3.0.1-client\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"3.0.1-client-strange\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"3.0.1-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"3.0.1-client-staging\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"foo-v\", version=\"3.2.0\",\n suffix=\".zip\", type=\"zip\", valid=True)\n ]\n\n test_versions_4 = [\n test_pype(prefix=\"foo-v\", version=\"10.0.0\",\n suffix=\"\", type=\"dir\", valid=True),\n test_pype(prefix=\"lom-v\", version=\"11.2.6\",\n suffix=\".zip\", type=\"dir\", valid=False),\n test_pype(prefix=\"bom-v\", version=\"7.2.7-client\",\n suffix=\".zip\", type=\"zip\", valid=True),\n test_pype(prefix=\"woo-v\", version=\"7.2.8-client-strange\",\n suffix=\".zip\", type=\"txt\", valid=False)\n ]\n\n def _create_invalid_zip(path: Path):\n with ZipFile(path, \"w\") as zf:\n zf.writestr(\"test.foo\", \"test\")\n\n def _create_valid_zip(path: Path, version: str):\n with ZipFile(path, \"w\") as zf:\n zf.writestr(\n \"pype/version.py\", f\"__version__ = '{version}'\\n\\n\")\n\n def _create_invalid_dir(path: Path):\n path.mkdir(parents=True, exist_ok=True)\n with open(path / \"invalid\", \"w\") as fp:\n fp.write(\"invalid\")\n\n def _create_valid_dir(path: Path, version: str):\n pype_path = path / \"pype\"\n version_path = pype_path / \"version.py\"\n pype_path.mkdir(parents=True, exist_ok=True)\n with open(version_path, \"w\") as fp:\n fp.write(f\"__version__ = '{version}'\\n\\n\")\n\n def _build_test_item(path, item):\n test_path = path / \"{}{}{}\".format(item.prefix,\n item.version,\n item.suffix)\n if item.type == \"zip\":\n if item.valid:\n _create_valid_zip(test_path, item.version)\n else:\n _create_invalid_zip(test_path)\n elif item.type == \"dir\":\n if item.valid:\n _create_valid_dir(test_path, item.version)\n else:\n _create_invalid_dir(test_path)\n else:\n with open(test_path, \"w\") as fp:\n fp.write(\"foo\")\n\n # in PYPE_PATH\n e_path = tmp_path_factory.mktemp(\"environ\")\n\n # create files and directories for test\n for test_file in test_versions_1:\n _build_test_item(e_path, test_file)\n\n # in pypePath registry\n p_path = tmp_path_factory.mktemp(\"pypePath\")\n for test_file in test_versions_2:\n _build_test_item(p_path, test_file)\n\n # in data dir\n d_path = tmp_path_factory.mktemp(\"dataPath\")\n for test_file in test_versions_2:\n _build_test_item(d_path, test_file)\n\n # in provided path\n g_path = tmp_path_factory.mktemp(\"providedPath\")\n for test_file in test_versions_3:\n _build_test_item(g_path, test_file)\n\n # dir vs zip preference\n dir_path = tmp_path_factory.mktemp(\"dirZipPath\")\n for test_file in test_versions_4:\n _build_test_item(dir_path, test_file)\n\n printer(\"testing finding Pype in given path ...\")\n result = fix_bootstrap.find_pype(g_path, include_zips=True)\n # we should have results as file were created\n assert result is not None, \"no Pype version found\"\n # latest item in `result` should be latest version found.\n expected_path = Path(\n g_path / \"{}{}{}\".format(\n test_versions_3[3].prefix,\n test_versions_3[3].version,\n test_versions_3[3].suffix\n )\n )\n assert result, \"nothing found\"\n assert result[-1].path == expected_path, \"not a latest version of Pype 3\"\n\n monkeypatch.setenv(\"PYPE_PATH\", e_path.as_posix())\n\n result = fix_bootstrap.find_pype(include_zips=True)\n # we should have results as file were created\n assert result is not None, \"no Pype version found\"\n # latest item in `result` should be latest version found.\n expected_path = Path(\n e_path / \"{}{}{}\".format(\n test_versions_1[5].prefix,\n test_versions_1[5].version,\n test_versions_1[5].suffix\n )\n )\n assert result, \"nothing found\"\n assert result[-1].path == expected_path, \"not a latest version of Pype 1\"\n\n monkeypatch.delenv(\"PYPE_PATH\", raising=False)\n\n # mock appdirs user_data_dir\n def mock_user_data_dir(*args, **kwargs):\n return d_path.as_posix()\n\n monkeypatch.setattr(appdirs, \"user_data_dir\", mock_user_data_dir)\n fix_bootstrap.registry = OpenPypeSettingsRegistry()\n fix_bootstrap.registry.set_item(\"pypePath\", d_path.as_posix())\n\n result = fix_bootstrap.find_pype(include_zips=True)\n # we should have results as file were created\n assert result is not None, \"no Pype version found\"\n # latest item in `result` should be latest version found.\n expected_path = Path(\n d_path / \"{}{}{}\".format(\n test_versions_2[3].prefix,\n test_versions_2[3].version,\n test_versions_2[3].suffix\n )\n )\n assert result, \"nothing found\"\n assert result[-1].path == expected_path, \"not a latest version of Pype 2\"\n\n result = fix_bootstrap.find_pype(e_path, include_zips=True)\n assert result is not None, \"no Pype version found\"\n expected_path = Path(\n e_path / \"{}{}{}\".format(\n test_versions_1[5].prefix,\n test_versions_1[5].version,\n test_versions_1[5].suffix\n )\n )\n assert result[-1].path == expected_path, \"not a latest version of Pype 1\"\n\n result = fix_bootstrap.find_pype(dir_path, include_zips=True)\n assert result is not None, \"no Pype versions found\"\n expected_path = Path(\n dir_path / \"{}{}{}\".format(\n test_versions_4[0].prefix,\n test_versions_4[0].version,\n test_versions_4[0].suffix\n )\n )\n assert result[-1].path == expected_path, \"not a latest version of Pype 4\"\n","sub_path":"tests/igniter/test_bootstrap_repos.py","file_name":"test_bootstrap_repos.py","file_ext":"py","file_size_in_byte":13417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"23251431","text":"'''\nXMBC Script - IMDB Watched-Sync\n\nMarks movies or series rated on your IMDB account as 'watched' in XBMC's library.\n\nCreated on 16 apr 2014\n@author: Anton Jansson\n'''\n\nimport imdb\nimport json\nimport settings\nimport xbmc\nimport xbmcaddon\nimport xbmcgui\n\n__addon__ = xbmcaddon.Addon()\n__addonname__ = __addon__.getAddonInfo('name')\n__addonid__ = __addon__.getAddonInfo('id')\n__icon__ = __addon__.getAddonInfo('icon')\n\nNOTIFICATION_TIME = 5000\n\nRPC_GET_UNWATCHED_MOVIES = {\n \"jsonrpc\": \"2.0\",\n \"id\": \"libMovies\",\n \"method\": \"VideoLibrary.GetMovies\",\n \"params\": { \n \"filter\": {\n \"field\": \"playcount\",\n \"operator\": \"is\",\n \"value\": \"0\"\n },\n \"properties\" : [\"imdbnumber\"] \n }\n}\nRPC_SET_MOVIE_WATCHED = {\n \"jsonrpc\": \"2.0\",\n \"id\": \"setWatched\",\n \"method\": \"VideoLibrary.SetMovieDetails\",\n \"params\": {\n \"movieid\" : 0,\n \"playcount\": 1\n }\n}\n\ndef executeJSONRPC(query):\n return json.loads(xbmc.executeJSONRPC(json.dumps(query)))\n\ndef getIMDBWatched():\n response = imdb.loadRatedItems(settings.getIMDBUser())\n if (response['success']):\n return response['result']\n else:\n xbmcgui.Dialog().ok(__addonname__, \n __addon__.getLocalizedString(32101) + '[CR]' +\n response['error'],\n '',\n __addon__.getLocalizedString(32102))\n return []\n\ndef getUnwatchedMovies():\n response = executeJSONRPC(RPC_GET_UNWATCHED_MOVIES)\n return response.get('result', {}).get('movies', [])\n\ndef getMovieIdsToUpdate():\n \"\"\"Returns an array of movieIds that are rated (watched) on IMDB.\"\"\"\n localUnwatched = getUnwatchedMovies()\n imdbWatched = getIMDBWatched()\n \n localWatched = [x['movieid'] for x in localUnwatched if x['imdbnumber'] in imdbWatched]\n \n return localWatched\n\ndef setWatched(movieid):\n RPC_SET_MOVIE_WATCHED['params']['movieid'] = movieid\n executeJSONRPC(RPC_SET_MOVIE_WATCHED)\n\ndef showNotification(text):\n xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(__addonname__, text, NOTIFICATION_TIME, __icon__))\n\ndef updateLibrary():\n if (not settings.check()):\n xbmc.executebuiltin('Addon.OpenSettings(%s)'%(__addonid__))\n return\n \n movieIds = getMovieIdsToUpdate()\n for movie in movieIds:\n setWatched(movie)\n \n showNotification(str(len(movieIds)) + \" movies were marked as watched\")","sub_path":"resources/lib/watched_sync.py","file_name":"watched_sync.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"223950068","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom requests.exceptions import HTTPError\n\nNCAAF_URL=\"https://www.espn.com/college-football/teams\"\n\ndef fetch_ncaaf_teams(url=NCAAF_URL):\n \"\"\"Fetch the list of ncaa football teams\n \n Args:\n url (string): the url of the web page for ncaa football teams \n \n Returns:\n \n \"\"\"\n teams = []\n \n response = requests.get(url)\n html = response.content\n soup = BeautifulSoup(html, 'html.parser')\n \n conferences = soup.find_all(\"div\", class_=\"headline\")\n for conference in conferences:\n conference_name = conference.get_text()\n team_links = conference.parent.find_all(\"a\", class_=\"AnchorLink\")\n for team_link in team_links:\n if team_link.find(\"h2\"):\n team_url = team_link['href']\n team_name = team_link.get_text()\n team_id = int(team_url.split(\"/\")[-2])\n teams.append({\"id\": team_id, \"name\": team_name, \"conference\": conference_name, \"url\": team_url})\n return teams\n","sub_path":"assignment/cpsc6300-001/ps01/espn.py","file_name":"espn.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"31377977","text":"import tensorflow as tf\nimport numpy as np \nimport cPickle as pickle \n#import tf_util\nimport argparse\nimport os\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu', type=int, default=2, help='GPU to use [default: GPU 0]')\n#parser.add_argument('--model', default='lanenet', help='Model name: pointnet_cls or pointnet_cls_basic [default: pointnet_cls]')\nparser.add_argument('--max_epoch', type=int, default=1000000, help='Epoch to run [default: 100]')\nparser.add_argument('--batch_size', type=int, default=5000, help='Batch Size during training [default: 32]')\nparser.add_argument('--log_dir', default='log', help='Log dir [default: log]')\nparser.add_argument('--learning_rate', type=float, default=0.001, help='Initial learning rate [default: 0.001]')\nparser.add_argument('--decay_step', type=int, default=200000, help='Decay step for lr decay [default: 50000]')\nparser.add_argument('--decay_rate', type=float, default=0.7, help='Decay rate for lr decay [default: 0.8]')\nFLAGS = parser.parse_args()\n\nBATCH_SIZE = FLAGS.batch_size\nMAX_EPOCH = FLAGS.max_epoch\nBASE_LEARNING_RATE = FLAGS.learning_rate\nGPU_INDEX = FLAGS.gpu\nDECAY_STEP = FLAGS.decay_step\nDECAY_RATE = FLAGS.decay_rate\nLOG_DIR = FLAGS.log_dir\n\nnum_feat = 271\nnum_mid = 10\n\nbatch_size = BATCH_SIZE\n\nif not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR)\nos.system('cp pm.py %s' % (LOG_DIR))\nLOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w')\nLOG_FOUT.write(str(FLAGS)+'\\n')\n\ndef log_string(out_str):\n LOG_FOUT.write(out_str+'\\n')\n LOG_FOUT.flush()\n print(out_str)\n\ndef get_learning_rate(batch):\n learning_rate = tf.train.exponential_decay(\n BASE_LEARNING_RATE, # Base learning rate.\n batch * BATCH_SIZE, # Current index into the dataset.\n DECAY_STEP, # Decay step.\n DECAY_RATE, # Decay rate.\n staircase=True)\n learing_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\n return learning_rate \n\ndef shuffle_data(data, labels):\n idx = np.arange(len(labels))\n np.random.shuffle(idx)\n return data[idx, ...], labels[idx], idx\n\n\ndef optim(loss, category, lr=0.0001, beta1=0.9, beta2=0.99):\n optim = tf.train.AdamOptimizer(learning_rate=lr, beta1=beta1, beta2=beta2)\n\n var_list = [t for t in tf.trainable_variables() if t.name.startswith(category)]\n gradient = optim.compute_gradients(loss, var_list = var_list)\n\n global_step = tf.Variable(0, name='global_step', trainable=False)\n return optim.apply_gradients(gradient, global_step=global_step), global_step\n\ndef placeholder_input(batch_size, num_feat):\n place_input = tf.placeholder(tf.float32, shape=(batch_size, num_feat))\n place_output = tf.placeholder(tf.float32, shape=(batch_size, 1))\n return place_input, place_output\n\ndef cal_loss(gt, loss):\n num_all = gt.get_shape()[0].value\n num_pos = tf.reduce_sum(gt)\n num_neg = num_all - num_pos\n #loss_weight = gt * ((num_neg) / (num_pos) - 1) + 1.0\n loss_weight = gt * (10 - 1) + 1.0\n loss_f = tf.reduce_sum(loss*loss_weight)\n #tf.Print(num_pos, data)\n return loss_f\n\ndef get_model(input_ph, gt_ph):\n batch_size = input_ph.get_shape()[0].value\n with tf.variable_scope('main_net'): \n weight_l1 = tf.get_variable('weight_l1', [num_feat, num_mid])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n layer_1 = tf.tanh(tf.matmul(input_ph, weight_l1))\n\n weight_o = tf.get_variable('weight_o', [num_mid, 1])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n layer_o = tf.sigmoid(tf.matmul(layer_1, weight_o))\n\n weight_sum = tf.reduce_sum(tf.abs(weight_l1))\n\n #loss_rc_raw = (layer_o-gt_ph)*(layer_o-gt_ph)\n loss_rc_raw = -(gt_ph * tf.log(layer_o) + (1-gt_ph) * tf.log(1-layer_o))\n loss_rc = cal_loss(gt_ph, loss_rc_raw)\n\n with tf.variable_scope('pm_net'):\n shut_mat = tf.constant(1 - np.eye(num_mid), dtype = np.float32)\n weight_dict = {}\n pm_dict = {}\n #pm_out_dict = {}\n pm_loss_dict = {}\n loss_pm_sum = tf.Variable(0.0, trainable=False)\n for i in range(num_mid):\n weight_dict['weight_pm_'+str(i)] = tf.get_variable('weight_pm_'+str(i), [num_mid,1])#, initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0))\n pm_dict['pm_dict_'+str(i)] = tf.matmul(layer_1*shut_mat[i], weight_dict['weight_pm_'+str(i)])\n pm_loss_dict['pm_loss' + str(i)] = tf.reduce_mean((pm_dict['pm_dict_'+str(i)] - layer_1[i])*(pm_dict['pm_dict_'+str(i)] - layer_1[i])) \n loss_pm_sum += pm_loss_dict['pm_loss' + str(i)]\n loss_main = loss_rc + 0.15* weight_sum - loss_pm_sum#/num_mid\n tf.summary.scalar('loss_main', loss_main)\n tf.summary.scalar('loss_pm', loss_pm_sum)\n tf.summary.scalar('loss_rc', loss_rc)\n tf.summary.scalar('loss_l1', weight_sum)\n tf.summary.histogram('weight_dis', weight_l1)\n return loss_main, loss_pm_sum, layer_o, layer_1\n\ndef train_one_epoch(input_data, gt_data, sess, ops, train_writer):\n \"\"\" ops: dict mapping from string to tf ops \"\"\"\n #is_training = True\n \n # Shuffle train files\n #train_file_idxs = np.arange(0, len(TRAIN_FILES))\n #np.random.shuffle(train_file_idxs)\n \n log_string('----' + str('Hahahahaha') + '-----')\n current_data, current_label, _ = shuffle_data(input_data, gt_data) \n #current_label = np.squeeze(current_label)\n \n file_size = current_data.shape[0]\n num_batches = file_size / BATCH_SIZE\n \n for batch_idx in range(num_batches):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = (batch_idx+1) * BATCH_SIZE\n\n in_data = current_data[start_idx:end_idx, :, :]\n in_gt = current_label[start_idx:end_idx, :, :]\n\n summary, step, _, loss_val,l_matrix,t_matrix = sess.run([ops['merged'], ops['step'],\n ops['train_op'], ops['loss'], ops['matrix'],ops['trans_ma']], feed_dict=feed_dict)\n train_writer.add_summary(summary, step)\n loss_sum += loss_val\n\n\n log_string('loss: %f' % (loss_sum/num_batches))\n\n\nwith tf.Graph().as_default():\n with tf.device('/gpu:'+str(GPU_INDEX)):\n input_ph, gt_ph = placeholder_input(batch_size, num_feat)\n\n loss_main, loss_pm_sum, layer_o, layer_1 = get_model(input_ph, gt_ph)\n\n\n train_main, main_global_step = optim(loss_main, category = 'main_net')\n train_pm, pm_global_step = optim(loss_pm_sum, category = 'pm_net')\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.allow_soft_placement = True\n config.log_device_placement = False\n\n sess = tf.Session(config = config)\n\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'), sess.graph)\n test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'))\n\n #input_data = pickle.load()\n #gt_data = pickle.load()\n #input_data = np.random.random((400,280))\n #gt_data = np.random.random((400,1))\n data_all = np.load('./data/data.npy')\n input_data = data_all[0:1400000, 0:-1]\n gt_data = np.reshape(data_all[0:1400000, -1],(-1, 1))\n\n input_test = data_all[-148208:, 0:-1]\n gt_test = np.reshape(data_all[-148208:, -1],(-1, 1))\n file_size = input_data.shape[0]\n num_batches = file_size / BATCH_SIZE\n sess.run(init)\n for epoch in range(MAX_EPOCH):\n log_string('**** EPOCH %03d ****' % (epoch))\n sys.stdout.flush()\n \n current_data, current_label, _ = shuffle_data(input_data, gt_data) \n \n file_size = current_data.shape[0]\n num_batches = file_size / BATCH_SIZE\n loss_sum = 0\n for batch_idx in range(num_batches):\n start_idx = batch_idx * BATCH_SIZE\n end_idx = (batch_idx+1) * BATCH_SIZE\n\n in_data = current_data[start_idx:end_idx, ...]\n in_gt = current_label[start_idx:end_idx, ...]\n \n _, main_step, loss_val = sess.run([train_main, main_global_step, loss_main], feed_dict={input_ph: in_data, gt_ph: in_gt})\n _, pm_step, summary = sess.run([train_pm, pm_global_step, merged], feed_dict={input_ph: in_data, gt_ph: in_gt})\n #summary = sess.run([merged])\n\n\n train_writer.add_summary(summary, main_step)\n loss_sum += loss_val\n ind_test = np.random.randint(0, 148208 - batch_size)\n re_test = sess.run([layer_o], feed_dict={input_ph: input_test[ind_test:ind_test+batch_size, ...], gt_ph: gt_test[ind_test:ind_test+batch_size, ...]})\n\n for ind_loop in range(batch_size):\n print [re_test[0][ind_loop], gt_test[ind_test + ind_loop]]\n #print re_test\n #print gt_test[ind_test:ind_test+100, ...]\n\n\n log_string('loss: %f' % (loss_sum/num_batches))\n\n \n # Save the variables to disk.\n if epoch % 10 == 0:\n save_path = saver.save(sess, os.path.join(LOG_DIR, \"model.ckpt\"))\n log_string(\"Model saved in file: %s\" % save_path)\n\n\n","sub_path":"pm.py","file_name":"pm.py","file_ext":"py","file_size_in_byte":9373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"420826718","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pandas as pd, numpy as np\nimport unicodedata\nimport math\nimport string\nfrom bs4 import BeautifulSoup\nfrom gensim import corpora\nfrom gensim import models\nimport MeCab\n\n\n\n# MeCabの辞書にNEologdを指定。\n# mecabは携帯素解析用、wakatiは分かち書き用\nmecab = MeCab.Tagger('-d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd/')\nwakati = MeCab.Tagger(\"-Owakati -d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd/\")\n\n# 形態素解析を行う関数を定義\n# ファイルを入力するとファイルを出力し、文字列を渡すと文字列を返します。引数fileで変更します。\n# 単に分かち書きしたいだけの場合は引数にmecab=wakatiとすると実現できます。\ndef MecabMorphologicalAnalysis(path='./text.txt', output_file='wakati.txt', mecab=mecab, file=False):\n mecab_text = ''\n if file:\n with open(path) as f:\n for line in f:\n mecab_text += mecab.parse(line)\n with open(output_file, 'w') as f:\n print(mecab_text, file=f)\n else:\n for path in path.split('\\n'):\n mecab_text += mecab.parse(path)\n return mecab_text\n\n\n\n# 記号文字は分析をするにあたって邪魔になるため、記号を取り除く関数を定義します。\n# 下のYahooNews関数で使用します。\ndef symbol_removal(soup):\n soup = unicodedata.normalize(\"NFKC\", soup)\n exclusion = \"「」『』【】〈〉《》≪≫、。・◇◆■●\" + \"\\n\" + \"\\r\" + \"\\u3000\" # 除去する記号文字を指定\n soup = soup.translate(str.maketrans(\"\", \"\", string.punctuation + exclusion))\n return soup\n\n\n\n# 青空文庫の情報をスクレイピングして、テーブルデータに整形する処理を行う関数を定義します。 \n# 引数に指定した数のタイトルを出力します。(デフォルトは30) \n# 中でsymbol_removal関数を使用しています。\ndef Aozora_table(n=30):\n url = \"https://www.aozora.gr.jp/access_ranking/2019_xhtml.html\"\n res = requests.get(url)\n res.encoding = 'shift-jis'\n soup = BeautifulSoup(res.content, \"html.parser\")\n\n url_list = [url[\"href\"] for i, url in enumerate(soup.find_all(\"a\", target=\"_blank\")) if i < n]\n\n title = []\n category = []\n text = []\n for url in url_list:\n res = requests.get(url)\n url_start = url[:37]\n res.encoding = 'shift-jis'\n soup = BeautifulSoup(res.content, \"html.parser\")\n for i, a in enumerate(soup.find_all(\"a\")):\n if i == 7:\n url_end = a[\"href\"][1:]\n url = url_start + url_end\n res = requests.get(url)\n res.encoding = 'shift-jis'\n soup = BeautifulSoup(res.content, \"html.parser\")\n title.append(soup.find(\"h1\").string)\n category.append(soup.find(\"h2\").string)\n for tag in soup.find_all([\"rt\", \"rp\"]):\n tag.decompose()\n soup = soup.find(\"div\",{'class': 'main_text'}).get_text()\n text.append(symbol_removal(soup))\n df = pd.DataFrame({'title': title, 'category': category, 'text': text})\n return df\n\n\n# Yahooニュースをスクレイピングする関数です。\n# 引数で指定した数の記事をとってきてデータフレームを返します。\ndef YahooNews(n=30):\n url = \"https://news.yahoo.co.jp/topics/top-picks\"\n URL = \"https://news.yahoo.co.jp/\"\n res = requests.get(url)\n soup = BeautifulSoup(res.text, \"html.parser\")\n all_page_links = []\n all_page_links.append(url)\n all_links = []\n while True:\n try:\n next = soup.find(\"li\", class_=\"pagination_item-next\").find(\"a\")[\"href\"]\n next_link = URL + next\n all_page_links.append(next_link)\n next_res = requests.get(next_link)\n soup = BeautifulSoup(next_res.text, \"html.parser\")\n except:\n break\n \n title_list = []\n category_list = []\n text_list = []\n for url in all_page_links: # all_page_links: 全てのニュースのリスト\n res = requests.get(url) # url: 25個分のニュースのリスト\n soup = BeautifulSoup(res.text, \"html.parser\")\n page_soup = soup.find_all(\"a\", class_=\"newsFeed_item_link\")\n for href in page_soup:\n link = href[\"href\"] # link: 一つのニュースのリンク(本文は一部のみ)\n all_links.append(link)\n \n if len(all_links) <= n:\n n = len(all_links)\n \n i = 0\n for link in all_links:\n link_res = requests.get(link)\n href_soup = BeautifulSoup(link_res.text, \"html.parser\")\n try:\n title = href_soup.find(\"h1\", class_=re.compile(\"^sc\")).string\n except:\n continue\n title_link = href_soup.find(\"a\", class_=\"sc-fUKxqW\")[\"href\"] # title_link: 本文\n res = requests.get(title_link)\n soup = BeautifulSoup(res.text, \"html.parser\")\n\n category = soup.find_all(\"li\", class_=\"current\")\n try:\n category = category[1].string\n except:\n continue\n else:\n for tag in soup.find_all([\"a\"]):\n tag.decompose()\n try:\n soup = soup.find(\"div\", class_=\"article_body\").get_text()\n soup = symbol_removal(soup)\n \n text_list.append(soup)\n title_list.append(title)\n category_list.append(category)\n i += 1 # 本文が正常に保存できたことをトリガーにしてカウントを一つ増やすことにします。\n pro_bar = ('=' * math.ceil(i / (n / 20))) + (' ' * int((n / (n / 20)) - math.ceil(i / (n / 20))))\n print('\\r[{0}] {1}記事'.format(pro_bar, i), end='')\n if i >= n:\n df = pd.DataFrame({'title': title_list, 'category': category_list, 'text': text_list})\n return df\n except:\n continue\n df = pd.DataFrame({'title': title_list, 'category': category_list, 'text': text_list})\n return df\n\n\n\n# 分かち書きされた2階層の単語のリストを渡すことで、TF-IDFでソートされたユニークな単語のリストを得る。\ndef sortedTFIDF(sentences):\n \n # 単語にIDを添付します。\n dictionary = corpora.Dictionary(sentences)\n \n # 作品ごとの単語の出現回数をカウント\n corpus = list(map(dictionary.doc2bow, sentences))\n \n # 単語ごとにTF-IDFを算出\n test_model = models.TfidfModel(corpus)\n corpus_tfidf = test_model[corpus]\n \n # ID:TF-IDF → TF-IDF:単語 に変換。TF-IDFを左に持ってくることで、sortedを用いてTF-IDFを基準にソートすることができます。\n texts_tfidf = []\n for doc in corpus_tfidf:\n text_tfidf = []\n for word in doc:\n text_tfidf.append([word[1], dictionary[word[0]]])\n texts_tfidf.append(text_tfidf)\n \n # TF-IDFを基準にソートを行います。\n sorted_texts_tfidf = []\n for text in texts_tfidf:\n sorted_text = sorted(text, reverse=True)\n sorted_texts_tfidf.append(sorted_text)\n\n return sorted_texts_tfidf\n\n\n\n# v1とv2のコサイン類似度を出力します。\ndef cos_sim(v1, v2):\n return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))","sub_path":"work/analysis/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":7405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"4254071","text":"def triangle(n):\n import random\n count = 0\n for i in range(n):\n first_line = random.random()\n random_number = random.random()\n second_line = (1-first_line) * random_number\n third_line = 1 - first_line - second_line\n numbers = [first_line, second_line, third_line]\n numbers.sort()\n if numbers[0]+ numbers[1] > numbers[2]:\n count += 1\n if count == 0:\n return 0\n else:\n return count/n\n\n\ndef expectation(n,m):\n mean = 0\n for i in range(m):\n mean += triangle(n)\n print( mean / m)\n\nexpectation(500,20)\nexpectation(1000,20) \nexpectation(10000,20)\n\n\n\n\n\n\n","sub_path":"semester1/프로그래밍/codes/make_triangle_assignment.py","file_name":"make_triangle_assignment.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"249574148","text":"from django.db import models\nfrom datetime import datetime, timedelta\nfrom django.shortcuts import reverse, redirect\nfrom django.utils import timezone as tmz\n\nclass Company(models.Model):\n name = models.CharField('Company name', max_length=30)\n size_limit = models.DecimalField('Traffic limit for a month(in TB)', max_digits=10, decimal_places=2)\n \n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = 'Company'\n verbose_name_plural = 'Companies'\n\nclass Users(models.Model):\n full_name = models.CharField('Full name', max_length=40)\n email = models.EmailField('Email', null=True, blank=True)\n company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='Company')\n\n def __str__(self):\n return 'User {} || company {}'.format(self.full_name, self.company)\n \n class Meta:\n verbose_name = 'User'\n verbose_name_plural = 'Users'\n\nclass TransferLogs(models.Model):\n user = models.ForeignKey(Users, on_delete=models.CASCADE, verbose_name='User')\n date = models.DateTimeField('Date n time of transfer', default=tmz.now())\n recource = models.CharField('Recourse', max_length=40)\n transferred = models.BigIntegerField('Was transferred(in bytes)')\n\n \n def __str__(self):\n return 'User {} transferred {} into {}'.format(self.user.full_name, self.transferred, self.recource)\n \n\n class Meta:\n verbose_name = 'Transfer log'\n verbose_name_plural = 'Transfer logs'\n\nclass Report(models.Model):\n company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='Company')\n traffic_used = models.DecimalField('Was used (in TB)', default=0, max_digits=10, decimal_places=2)\n date_start = models.DateField('Date start of using traffic', default=datetime.now())\n date_end = models.DateField('Date end of using traffic', default=datetime.now()+timedelta(days=30))\n exceeding_limit = models.DecimalField('Exceeding the limit for', max_digits=6, decimal_places=2, default=0,)\n more_than_limit = models.BooleanField('Whether the limit was exceeded', default=False)\n\n def __str__(self):\n return self.company.name\n \n \n class Meta:\n verbose_name = 'Report'\n verbose_name_plural = 'Reports'\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"601245701","text":"from DDQN_Model import ddqnTrainer\r\nfrom get_environment import GetEnv\r\nfrom gather_training_points import readReward\r\nimport pyautogui\r\nfrom time import sleep\r\n\r\n\r\nFrames = 4\r\nOutFrameSize = 80\r\nInFrameDim = (556, 838, 449, 786)\r\nInputShape = (Frames, InFrameDim[1]-InFrameDim[0], InFrameDim[3] - InFrameDim[2])\r\nTotalStepLimit = 5000000\r\nActionSpace = 5\r\n\r\n\r\nclass Environment:\r\n def __init__(self):\r\n self.env = GetEnv(inDim=InFrameDim, outDim=(OutFrameSize, OutFrameSize))\r\n self.out = []\r\n for i in range(5):\r\n self.out.append(self.env.takeImage(4, \"None\"))\r\n while True:\r\n self.out.append(self.env.takeImage(4, \"None\"))\r\n self.out.pop(0)\r\n\r\n def getEnvironment(self):\r\n return self.out\r\n\r\n def step(self, action):\r\n print(f\"action: {action}\")\r\n if action == 0:\r\n pyautogui.press('left')\r\n elif action == 1:\r\n pyautogui.press('up')\r\n elif action == 2:\r\n pyautogui.press('down')\r\n elif action == 3:\r\n pyautogui.press('right')\r\n elif action == 4:\r\n pyautogui.press('enter')\r\n else:\r\n sleep(1 / 28)\r\n\r\n\r\ndef main():\r\n run = 0\r\n total_step = 0\r\n game_model = ddqnTrainer(InputShape, ActionSpace)\r\n prev_score = 0\r\n while True:\r\n run += 1\r\n env = Environment()\r\n current_state = env.getEnvironment()\r\n step = 0\r\n score = readReward()\r\n while total_step <= TotalStepLimit:\r\n total_step += 1\r\n step += 1\r\n print(f\"Step: {total_step}\")\r\n action = game_model.move(current_state)\r\n env.step(action)\r\n next_state = env.getEnvironment()\r\n current_score = score.mainLoop()\r\n reward = current_score - prev_score\r\n print(reward)\r\n prev_score = current_score\r\n game_model.remember(current_state, action, reward, next_state)\r\n game_model.step_update(total_step)\r\n\r\n\r\nmain()\r\n","sub_path":"Main_Pacman_Bot.py","file_name":"Main_Pacman_Bot.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"419115211","text":"from django.forms import ModelForm,Textarea,TextInput\nfrom .models import Contact,Subscriber\nfrom django import forms\nfrom captcha.fields import ReCaptchaField\n\n\nclass ContactForm(ModelForm):\n captcha = ReCaptchaField()\n\n class Meta:\n model = Contact\n fields = ('name','email','subject','message','captcha')\n labels = {\n 'name': 'Your name (optional):',\n 'email': 'Email:',\n 'subject': 'Subject:',\n 'message': 'Message:',\n }\n widgets = {\n 'message': Textarea(attrs={\n 'cols': 80,\n 'rows': 20,\n 'class': 'materialize-textarea',\n }),\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['captcha'].label = ''\n \n\n\nclass UnSubscriberForm(forms.Form):\n email = forms.EmailField(required=False,widget=forms.TextInput(attrs={\n \"class\":\"unsub-form-style\",\n }))\n\n \n\n ","sub_path":"pages/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"305590481","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom contextlib import contextmanager\nfrom distutils.version import LooseVersion\n\nfrom tensorflow.contrib.framework import arg_scope\nfrom tensorflow.python.framework import ops\n\nfrom .imagenet_utils import *\nfrom .keras_utils import *\nfrom .layers import conv2d\n\n\n__outputs__ = 'outputs'\n\n\ndef print_collection(collection, scope):\n if scope is not None:\n print(\"Scope: %s\" % scope)\n for x in tf.get_collection(collection, scope=scope):\n name = x.name\n if scope is not None:\n name = name[len(scope)+1:]\n print(\"%s %s\" % (name, x.shape))\n\n\ndef parse_scopes(inputs):\n if not isinstance(inputs, list):\n inputs = [inputs]\n outputs = []\n for scope_or_tensor in inputs:\n if isinstance(scope_or_tensor, tf.Tensor):\n outputs.append(scope_or_tensor.aliases[0])\n elif isinstance(scope_or_tensor, str):\n outputs.append(scope_or_tensor)\n else:\n outputs.append(None)\n return outputs\n\n\ndef print_outputs(scopes=None):\n scopes = parse_scopes(scopes)\n for scope in scopes:\n print_collection(__outputs__, scope)\n\n\ndef print_weights(scopes=None):\n scopes = parse_scopes(scopes)\n for scope in scopes:\n print_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope)\n\n\ndef print_summary(scopes=None):\n scopes = parse_scopes(scopes)\n for scope in scopes:\n if scope is not None:\n print(\"Scope: %s\" % scope)\n weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n names = [w.name for w in weights]\n starts = [n.rfind('/') + 1 for n in names]\n ends = [n.rfind(':') for n in names]\n\n layers = sum([n[s:e] == 'weights'\n for (n, s, e) in zip(names, starts, ends)])\n parameters = sum([w.shape.num_elements() for w in weights])\n print(\"Total layers: %d\" % layers)\n print(\"Total weights: %d\" % len(weights))\n print(\"Total parameters: {:,}\".format(parameters))\n\n\ndef get_outputs(scope=None):\n scope = parse_scopes(scope)[0]\n return tf.get_collection(__outputs__, scope=scope)\n\n\ndef get_weights(scope=None):\n scope = parse_scopes(scope)[0]\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n\n\ndef crop_idx(total_size, crop_size, crop_loc, crop_grid):\n if isinstance(total_size, int):\n total_size = (total_size, total_size)\n if isinstance(crop_size, int):\n crop_size = (crop_size, crop_size)\n if crop_loc > -1:\n row_loc = crop_loc // crop_grid[0]\n col_loc = crop_loc % crop_grid[1]\n row_start = row_loc * (total_size[0] - crop_size[0]) // 2\n col_start = col_loc * (total_size[1] - crop_size[1]) // 2\n else:\n row_start = np.random.randint(0, total_size[0] - crop_size[0], 1)[0]\n col_start = np.random.randint(0, total_size[1] - crop_size[1], 1)[0]\n return row_start, col_start\n\n\ndef crop(img, crop_size, crop_loc=4, crop_grid=(3, 3)):\n r, c = crop_idx(img.shape[1:3], crop_size, crop_loc, crop_grid)\n return img[:, r:r+crop_size, c:c+crop_size, :]\n\n\ndef init(scopes):\n sess = tf.get_default_session()\n assert sess is not None, 'The default session should be given.'\n\n if not isinstance(scopes, list):\n scopes = [scopes]\n\n for scope in scopes:\n sess.run(tf.variables_initializer(get_weights(scope)))\n\n\ndef var_scope(name):\n def decorator(func):\n def wrapper(*args, **kwargs):\n scope = kwargs.get('scope', None)\n reuse = kwargs.get('reuse', None)\n with tf.variable_scope(scope, name, reuse=reuse):\n return func(*args, **kwargs)\n return wrapper\n return decorator\n\n\ndef ops_to_outputs(func):\n def wrapper(*args, **kwargs):\n x = func(*args, **kwargs)\n ops.add_to_collection(__outputs__, x)\n return x\n return wrapper\n\n\n@contextmanager\ndef arg_scopes(l):\n for x in l:\n x.__enter__()\n yield\n\n\ndef set_args(largs, conv_bias=True):\n def real_set_args(func):\n def wrapper(*args, **kwargs):\n is_training = kwargs.get('is_training', False)\n layers = sum([x for (x, y) in largs(is_training)], [])\n layers_args = [arg_scope(x, **y) for (x, y) in largs(is_training)]\n if not conv_bias:\n layers_args += [arg_scope([conv2d], biases_initializer=None)]\n with arg_scope(layers, outputs_collections=__outputs__):\n with arg_scopes(layers_args):\n return func(*args, **kwargs)\n return wrapper\n return real_set_args\n\n\ndef set_weights(weights, values):\n sess = tf.get_default_session()\n assert sess is not None, 'The default session should be given.'\n\n if len(weights) > len(values): # excluding weights in Optimizer\n weights = weights[:len(values)]\n\n assert len(weights) == len(values), 'The sizes of symbolic and ' \\\n 'actual weights do not match.' \\\n\n ops = [w.assign(v) for (w, v) in zip(weights[:-2], values[:-2])]\n if weights[-1].shape != values[-1].shape: # for transfer learning\n ops += [w.initializer for w in weights[-2:]]\n else:\n ops += [w.assign(v) for (w, v) in zip(weights[-2:], values[-2:])]\n sess.run(ops)\n\n\ndef load_weights(scopes, weights_path):\n scopes = parse_scopes(scopes)\n\n data = np.load(weights_path, encoding='bytes')\n values = data['values']\n\n if LooseVersion(tf.__version__) > LooseVersion('1.3.0'):\n for (i, name) in enumerate(data['names']):\n if '/beta' in name:\n values[i], values[i+1] = values[i+1], values[i]\n\n for scope in scopes:\n weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n set_weights(weights, values)\n\n\ndef load_torch_weights(scopes, weights_path, move_rules=None):\n try:\n import torch\n import torch.nn as nn\n import torch.nn.functional as F\n except ImportError:\n torch = None\n assert torch is not None, '`load_torch_weights` requires `torch`.'\n\n scopes = parse_scopes(scopes)\n\n model = torch.load(weights_path)\n names = list(model.keys())\n if move_rules is not None:\n if isinstance(move_rules, list):\n for (name, loc) in move_rules:\n idx = names.index(name)\n names.insert(idx + loc, names.pop(idx))\n\n for (i, name) in enumerate(names):\n if 'running_mean' in name:\n names[i-1], names[i-2] = names[i-2], names[i-1]\n\n values = []\n for name in names:\n val = model[name].numpy()\n if val.ndim == 4:\n val = np.transpose(val, [2, 3, 1, 0])\n if val.ndim == 2:\n val = np.transpose(val, [1, 0])\n if val.ndim == 4:\n groups = val.shape[3] // val.shape[2]\n if (groups == 32) or (groups == 64):\n values += np.split(val, groups, axis=3)\n else:\n values.append(val)\n else:\n values.append(val)\n\n for scope in scopes:\n weights = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n set_weights(weights, values)\n\n\ndef remove_utils(module_name, exceptions):\n import sys\n from . import utils\n module = sys.modules[module_name]\n for util in dir(utils):\n if not ((util.startswith('_')) or (util in exceptions)):\n try:\n delattr(module, util)\n except:\n None\n delattr(module, 'keras_utils')\n","sub_path":"tensornets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"174205722","text":"# (c) Copyright [2021] Micro Focus or one of its affiliates.\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# This is a script for re-ip local Vertica node in Kubernetes Init Container\n# and restart local Vertica node in Kubernetes Vertica app container\n# the script is expected to be simple and lightweight\nimport sys\nimport subprocess\nimport os\nimport configparser\nimport argparse\n\ndef checkAdmintoolsConfExists(atConfFilePath):\n return os.path.isfile(atConfFilePath)\n\ndef getCommandResult(args, label):\n proc = subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=True)\n result, error = proc.communicate()\n if proc.returncode != 0:\n print(f\"Error in running command {label}: {error.decode(sys.stdout.encoding)}\")\n return result.decode(sys.stdout.encoding)\n\ndef getActiveDB():\n activeDb = \"\"\n args = \"/opt/vertica/bin/admintools -t show_active_db\"\n activeDbStr = getCommandResult(args, \"get active db\").rstrip()\n if not activeDbStr:\n return \"\"\n # split output by \" \", following the output format of show_active_db\n activeDb = activeDbStr.split(\" \")[0]\n print(f\"active database is: {activeDb}\")\n return activeDb\n\ndef getLocalVerticaNodeName(dbName, atConfFilePath):\n localVNodeName = \"\"\n if atConfFilePath is None or not os.path.isfile(atConfFilePath) or os.stat(atConfFilePath).st_size <= 0:\n return False, localVNodeName\n\n atConfig = configparser.ConfigParser()\n try:\n atConfig.read(atConfFilePath)\n except configparser.Error as err:\n print(f\"Error during reading admintools.conf: {err}\")\n return False, localVNodeName\n\n if not atConfig.has_section('Nodes'):\n return False, localVNodeName\n\n # important assumption: all nodes have the same catalog path\n templateNodeInfo = atConfig.items('Nodes')[0]\n catalogPath = templateNodeInfo[1].split(\",\")[1]\n\n # get local vertica node name by checking catalog directory on local pod\n args = f\"ls {catalogPath}/{dbName}/ | grep '^v_.*_catalog$' | head -1 | sed 's/_[^_]*$//'\"\n\n localVNodeName = getCommandResult(args, \"get local Vertica node name\").rstrip()\n if not localVNodeName:\n return False, localVNodeName\n return True, localVNodeName\n\ndef getLocalPodIp():\n return os.environ['POD_IP']\n\ndef getDbAdminPwd():\n getPwdArgs = \"cat /etc/podinfo/superuser-passwd 2> /dev/null || :\"\n dbadminPwd = getCommandResult(getPwdArgs, \"get dbadmin secret\").rstrip()\n return dbadminPwd\n\ndef reIpLocalNodeClusterUp(activeDb, atConfFilePath, localVNodeName):\n localVNodeNewIp = getLocalPodIp()\n\n if not localVNodeNewIp:\n return False, \"Failed to get IP address of local Pod.\"\n\n # get dbadmin password\n dbadminPwd = getDbAdminPwd()\n args = \"\"\n # call AT db_change_node_ip to re-ip the local Vertica node\n passOpts = \" -p {}\".format(dbadminPwd) if dbadminPwd else \"\"\n args = f\"/opt/vertica/bin/admintools -t db_change_node_ip -d {activeDb} -s {localVNodeName} --new-host-ips {localVNodeNewIp}{passOpts}\"\n\n print(f\"Updating IP address of local Vertica node {localVNodeName} to be {localVNodeNewIp} ...\")\n nodeReIpResult = getCommandResult(args, \"update IP address of local Vertica node\")\n\n # check if the node has been re-iped successfully\n nodeReIpMsg = \"IP addresses of nodes have been updated successfully\"\n nodeNoIpChangeMsg = \"Skip updating IP addresses: all nodes have up-to-date addresses\"\n if nodeReIpMsg in nodeReIpResult or nodeNoIpChangeMsg in nodeReIpResult:\n return True, \"\"\n else:\n return False, \"Failed to update IP address for local Vertica node, check admintools.log for more information.\"\n\ndef restartLocalNode(activeDb, atConfFilePath, localVNodeName):\n # get dbadmin password\n dbadminPwd = getDbAdminPwd()\n args = \"\"\n # call AT restart_node to restart the local Vertica node\n passOpts = \" -p {}\".format(dbadminPwd) if dbadminPwd else \"\"\n args = f\"/opt/vertica/bin/admintools -t restart_node -d {activeDb} -s {localVNodeName}{passOpts}\"\n\n print(f\"Restarting local Vertica node {localVNodeName} ...\")\n restartResult = getCommandResult(args, \"restart local Vertica node\")\n\n # check if the node has been restarted successfully\n nodeRestartMsg = f\"{localVNodeName}: (UP)\"\n if nodeRestartMsg in restartResult:\n return True, \"\"\n else:\n return False, \"Failed to restart local Vertica node, check admintools.log for more information.\"\n\ndef main():\n argParser = argparse.ArgumentParser()\n argParser.add_argument(\"--re-ip-node\",\n action = 'store_true',\n dest = \"reIpNode\",\n help = \"Update IP address of local Vertica node\")\n argParser.add_argument(\"--restart-node\",\n action = 'store_true',\n dest = \"restartNode\",\n help = \"Restart local Vertica node\")\n args = argParser.parse_args()\n atConfFilePath = \"/opt/vertica/config/admintools.conf\"\n # step 1: check if there is an admintools.conf, if no, then local host does not belong to a Vertica cluster\n atConfExists = checkAdmintoolsConfExists(atConfFilePath)\n if not atConfExists:\n print(\"The host does not belong to a Vertica cluster.\")\n sys.exit(0)\n\n # step 2: check if there's an UP database, if not then we need to first bring up the database\n # we do not handle bringing up database in this script\n activeDb = getActiveDB()\n if activeDb == \"\":\n print(\"There is no UP database to restart the node, try start the database first.\")\n sys.exit(0)\n\n # find local vertica node name\n (succeeded, localVNodeName) = getLocalVerticaNodeName(activeDb, atConfFilePath)\n if not succeeded:\n print(\"Local Vertica node does not belong to a Vertica database.\")\n sys.exit(0)\n\n if args.reIpNode:\n # re-ip the local Vertica node. When a Pod dies, it could take a short while for the Vertica node in that Pod\n # to switch to status DOWN. Therefore, this step may fail due to that the Vertica node is not DOWN yet, but Init\n # Container will retry this script, so no retry needed in this script.\n (succeeded, msg) = reIpLocalNodeClusterUp(activeDb, atConfFilePath, localVNodeName)\n if not succeeded:\n print(f\"Error in updating IP address for local Vertica node: {msg}\")\n sys.exit(1)\n else:\n print(\"IP address of local Vertica node has been updated successfully.\")\n sys.exit(0)\n elif args.restartNode:\n (succeeded, msg) = restartLocalNode(activeDb, atConfFilePath, localVNodeName)\n if not succeeded:\n print(f\"Error in restarting local Vertica node: {msg}\")\n sys.exit(1)\n else:\n print(\"Local Vertica node has been restarted successfully.\")\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n","sub_path":"docker-vertica/re-ip-node.py","file_name":"re-ip-node.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"108444826","text":"import cli.app\nimport logging\n\nfrom stockpredict.training import TrainingManager\nfrom stockpredict.network import StockNeuralNetwork\n\nlogger = logging.getLogger()\nlogging.basicConfig(level=logging.DEBUG)\n\n\n@cli.app.CommandLineApp\ndef train(app):\n \"\"\"\n Trains a network with a CSV file data\n :param app: \n :return: \n \"\"\"\n # # Set log level\n # assert app.params.log_level in ['DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']\n # logger.debug(\"DEBUG\")\n # logger.info(\"INFO\")\n # logger.warn(\"WARN\")\n # logger.error(\"ERROR\")\n # logger.critical(\"CRITICAL\")\n # logging.basicConfig(level=getattr(logging, app.params.log_level))\n\n # Choose Trainer\n trainer = TrainingManager()\n\n # Choose network for or create new one\n logger.info(\"Setting up network.\")\n net = StockNeuralNetwork(previous=int(app.params.previous) or 50, future=int(app.params.future) or 3)\n trainer.set_network(net)\n\n # Run training\n logger.info(\"Starting training from {} file.\".format(app.params.input_csv))\n trainer.train_from_csv(csv_path=app.params.input_csv, col_dict={\n 'DATE': 'Data',\n 'OPEN': 'Otwarcie',\n 'CLOSE': 'Zamkniecie',\n 'LOW': 'Najnizszy',\n 'HIGH': 'Najwyzszy',\n 'VOLUME': 'Wolumen'\n })\n # Data,Otwarcie,Najwyzszy,Najnizszy,Zamkniecie,Wolumen\n\n\ntrain.add_param(\"-c\", \"--input-csv\", help=\"Input csv file with stock data\", required=True, action=\"store\")\ntrain.add_param(\"-p\", \"--previous\", help=\"Number of previous sessions (analyzed)\", required=False, action=\"store\")\ntrain.add_param(\"-f\", \"--future\", help=\"Number of future sessions (predicted)\", required=False, action=\"store\")\ntrain.add_param(\"-l\", \"--log-level\", help=\"Log level (default is WARN)\", required=False, default='WARN', action=\"store\")\n\nif __name__ == \"__main__\":\n train.run()\n","sub_path":"scli.py","file_name":"scli.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"120198748","text":"#!/usr/bin/env python3\nfrom middlewared.client import Client\n\nimport asyncio\nimport inspect\nimport os\nimport setproctitle\n\nfrom . import logger\nfrom .common.environ import environ_update\nfrom .utils import LoadPluginsMixin\nfrom .utils.io_thread_pool_executor import IoThreadPoolExecutor\nimport middlewared.utils.osc as osc\nfrom .utils.run_in_thread import RunInThreadMixin\n\nMIDDLEWARE = None\n\n\nclass FakeMiddleware(LoadPluginsMixin, RunInThreadMixin):\n \"\"\"\n Implements same API from real middleware\n \"\"\"\n\n def __init__(self, overlay_dirs):\n super().__init__(overlay_dirs)\n self.client = None\n self.logger = logger.Logger('worker')\n self.logger.getLogger()\n self.logger.configure_logging('console')\n self.loop = asyncio.get_event_loop()\n self.run_in_thread_executor = IoThreadPoolExecutor('IoThread', 1)\n\n async def _call(self, name, serviceobj, methodobj, params=None, app=None, pipes=None, io_thread=False, job=None):\n try:\n with Client('ws+unix:///var/run/middlewared-internal.sock', py_exceptions=True) as c:\n self.client = c\n job_options = getattr(methodobj, '_job', None)\n if job and job_options:\n params = list(params) if params else []\n params.insert(0, FakeJob(job['id'], self.client))\n if asyncio.iscoroutinefunction(methodobj):\n return await methodobj(*params)\n else:\n return methodobj(*params)\n finally:\n self.client = None\n\n async def _run(self, name, args, job=None):\n service, method = name.rsplit('.', 1)\n serviceobj = self.get_service(service)\n methodobj = getattr(serviceobj, method)\n return await self._call(name, serviceobj, methodobj, params=args, job=job)\n\n async def call(self, method, *params, timeout=None, **kwargs):\n \"\"\"\n Calls a method using middleware client\n \"\"\"\n return self.client.call(method, *params, timeout=timeout, **kwargs)\n\n def call_sync(self, method, *params, timeout=None, **kwargs):\n \"\"\"\n Calls a method using middleware client\n \"\"\"\n return self.client.call(method, *params, timeout=timeout, **kwargs)\n\n async def call_hook(self, name, *args, **kwargs):\n with Client(py_exceptions=True) as c:\n return c.call('core.call_hook', name, args, kwargs)\n\n def send_event(self, name, event_type, **kwargs):\n with Client(py_exceptions=True) as c:\n return c.call('core.event_send', name, event_type, kwargs)\n\n\nclass FakeJob(object):\n\n def __init__(self, id, client):\n self.id = id\n self.client = client\n self.progress = {\n 'percent': None,\n 'description': None,\n 'extra': None,\n }\n\n def set_progress(self, percent, description=None, extra=None):\n self.progress['percent'] = percent\n if description:\n self.progress['description'] = description\n if extra:\n self.progress['extra'] = extra\n self.client.call('core.job_update', self.id, {'progress': self.progress})\n\n\ndef main_worker(*call_args):\n global MIDDLEWARE\n loop = asyncio.get_event_loop()\n coro = MIDDLEWARE._run(*call_args)\n try:\n res = loop.run_until_complete(coro)\n except SystemExit:\n raise RuntimeError('Worker call raised SystemExit exception')\n # TODO: python cant pickle generator for obvious reasons, we should implement\n # it using Pipe.\n if inspect.isgenerator(res):\n res = list(res)\n return res\n\n\ndef receive_events():\n c = Client('ws+unix:///var/run/middlewared-internal.sock', py_exceptions=True)\n c.subscribe('core.environ', lambda *args, **kwargs: environ_update(kwargs['fields']))\n c.subscribe('core.reconfigure_logging', lambda *args, **kwargs: logger.reconfigure_logging())\n\n environ_update(c.call('core.environ'))\n\n\ndef worker_init(overlay_dirs, debug_level, log_handler):\n global MIDDLEWARE\n MIDDLEWARE = FakeMiddleware(overlay_dirs)\n os.environ['MIDDLEWARED_LOADING'] = 'True'\n MIDDLEWARE._load_plugins()\n os.environ['MIDDLEWARED_LOADING'] = 'False'\n setproctitle.setproctitle('middlewared (worker)')\n osc.die_with_parent()\n logger.setup_logging('worker', debug_level, log_handler)\n receive_events()\n","sub_path":"src/middlewared/middlewared/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"620546493","text":"import os\nimport requests\nimport datetime\n\ndef do_ping():\n os.system('fping -e -a -r 0 output.txt')\n\ndef load_hosts():\n global hosts\n hosts = set()\n f = open('hosts.txt')\n for line in f:\n hosts.add(line.strip())\n\ndef parse_output():\n global output\n output = {}\n global hosts\n output = { k:None for k in hosts }\n f = open('output.txt')\n for line in f:\n terms = line.strip().split()\n host = terms[0]\n time = terms[1][1:]\n output[host] = time\n\ndef full():\n time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n do_ping()\n parse_output()\n global output\n print(output)\n for k in output:\n v = output[k]\n url = os.getenv('STORE_URL')\n print('url:', url)\n success = 'false' if v is None else 'true'\n payload = '{\"origin\":\"raspi2a\", \"target\":\"%s\", \"success\":\"%s\", \"rtt\":\"%s\", \"time\":\"%s\"}' % (k, success, v, time)\n # print('payload:', payload)\n h = {'Content-type': 'application/json'}\n r = requests.post(url, data=payload, headers=h)\n print(r, r.text)\n\n\nload_hosts()\nfull()\nprint('done!')\n\n","sub_path":"p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"483102570","text":"import pynbody\nimport numpy as np\nimport sys\n\ntime = str(sys.argv[1])\nhalo = int(sys.argv[2])\n\nsim = pynbody.load('/nobackup/nnsanche/pioneer50h243GM7.1536gst1bwK1BH/pioneer50h243GM7.1536gst1bwK1BH.00'+time)\n#sim = pynbody.load('/nobackup/nnsanche/NO_BHs/pioneer50h243GM7.1536gst1bwK1/pioneer50h243GM7.1536gst1bwK1.00'+time)\n#sim = pynbody.load('/nobackup/nnsanche/NO_BHs/pioneer50h243GM4.1536gst1bwK1/pioneer50h243GM4.1536gst1bwK1.00'+time)\nh = sim.halos()\nsat = h[halo]\nsat_iords = sat.g['iord']\nprint('Number of particles in the satellite',str(halo),' at timestep',time,':',len(sat_iords))\nprint('Saving in text file')\nnp.savetxt('GM7_h'+str(halo)+'iords_'+time+'.txt',sat_iords)\n","sub_path":"Sanchez2018_plots/profiles_plot7/exclude_iords.py","file_name":"exclude_iords.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"450948091","text":"\"\"\"spider_django URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'spider.views.index'),\n url(r'^index/', 'spider.views.index', name='index'),\n url(r'^handle1/', 'spider.views.handle1', name='handle1'),\n url(r'^handle2/', 'spider.views.handle2', name='handle2'),\n url(r'^handle3/', 'spider.views.handle3', name='handle3'),\n url(r'^handle4/', 'spider.views.handle4', name='handle4'),\n url(r'^handle5/', 'spider.views.handle5', name='handle5'),\n url(r'^handle6/', 'spider.views.handle6', name='handle6'),\n url(r'^handle7/', 'spider.views.handle7', name='handle7'),\n url(r'^handle8/', 'spider.views.handle8', name='handle8'),\n url(r'^handle9/', 'spider.views.handle9', name='handle9'),\n url(r'^sentiment/', 'spider.views.sentiment', name='sentiment'),\n url(r'^sentiment2/', 'spider.views.sentiment2', name='sentiment2'),\n url(r'^deleteCommentFile/', 'spider.views.deleteCommentFile', name='deleteCommentFile'),\n url(r'^deleteUserFile/', 'spider.views.deleteUserFile', name='deleteUserFile'),\n url(r'^deleteGlobalVar/', 'spider.views.deleteGlobalVar', name='deleteGlobalVar'),\n url(r'^test/', 'spider.views.test', name='test'),\n]\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"spider_django/spider_django/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"624786811","text":"import sys\r\nsys.path.insert(0, './resnet')\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\n#from resnet152 import get_resnet\r\n# from convert2 import load_image\r\nfrom generator_v3 import combine_embeddings, generator_me\r\nfrom discriminator import discriminator\r\nfrom rnn_module import rnn_module\r\nfrom get_data_v2 import load_data, get_training_batch\r\n\r\n\r\n######## CONSTANTS #######\r\nloss_vals = []\r\nacc_vals = []\r\nvocabulary_size = 15881\r\ninput_embedding_size = 200\r\nrnn_size = 512\r\nrnn_layer = 2\r\ndim_hidden = 2048\r\nepsilon = 1e-3\r\n##########################\r\n\r\nsess = tf.InteractiveSession()\r\n\r\nload_weights = False\r\nsave_ver = '2_nonoise'\r\nimport_weight_file = 'weights_g_v1.npy'\r\n\r\nif load_weights:\r\n weights = np.load(import_weight_file).item()\r\n\r\n var_dict = {\r\n 'cefcW1': tf.Variable(tf.truncated_normal([4096,4096])),\r\n 'cefcb1': tf.Variable(tf.constant(0.1, shape=[4096])),\r\n 'gfcW1': tf.Variable(weights['gfcW1']),\r\n 'gfcb1': tf.Variable(weights['gfcb1']),\r\n 'gfcW2': tf.Variable(weights['gfcW2']),\r\n 'gfcb2': tf.Variable(weights['gfcb2']),\r\n 'gfcW3': tf.Variable(weights['gfcW3']),\r\n 'gfcb3': tf.Variable(weights['gfcb3']),\r\n 'gfcW4': tf.Variable(weights['gfcW4']),\r\n 'gfcb4': tf.Variable(weights['gfcb4']),\r\n 'rnnqW': tf.Variable(weights['rnnqW'], name='embed_ques_W'),\r\n 'rnnsW': tf.Variable(weights['rnnsW'], name='embed_state_W'),\r\n 'rnnsb': tf.Variable(weights['rnnsb'], name='embed_state_b'),\r\n 'rnnoutbeta': tf.Variable(weights['rnnoutbeta']),\r\n 'rnnoutscale': tf.Variable(weights['rnnoutscale']),\r\n 'cnnoutbeta': tf.Variable(weights['cnnoutbeta']),\r\n 'cnnoutscale': tf.Variable(weights['cnnoutscale']),\r\n 'featbeta': tf.Variable(weights['featbeta']),\r\n 'featscale': tf.Variable(weights['featscale']),\r\n }\r\n\r\n #batch_no = weights['batch_no']\r\n batch_no = 0\r\nelse:\r\n weights = np.load(import_weight_file).item()\r\n\r\n var_dict = {\r\n 'cemcnnfcW1': tf.Variable(weights['cemcnnfcW1']),\r\n 'cemcnnfcb1': tf.Variable(weights['cemcnnfcb1']),\r\n 'ceacnnfcW1': tf.Variable(weights['ceacnnfcW1']),\r\n 'ceacnnfcb1': tf.Variable(weights['ceacnnfcb1']),\r\n 'cemrnnfcW1': tf.Variable(weights['cemrnnfcW1']),\r\n 'cemrnnfcb1': tf.Variable(weights['cemrnnfcb1']),\r\n 'cearnnfcW1': tf.Variable(weights['cearnnfcW1']),\r\n 'cearnnfcb1': tf.Variable(weights['cearnnfcb1']),\r\n 'gfcW1': tf.Variable(tf.truncated_normal([4096, 4096])),\r\n 'gfcb1': tf.Variable(tf.constant(0.1, shape=[4096])),\r\n 'gfcW2': tf.Variable(tf.truncated_normal([4096, 4096*1])),\r\n 'gfcb2': tf.Variable(tf.constant(0.1, shape=[4096*1])),\r\n 'gfcW3': tf.Variable(tf.truncated_normal([4096*1, 3500])),\r\n 'gfcb3': tf.Variable(tf.constant(0.1, shape=[3500])),\r\n 'gfcW4': tf.Variable(tf.truncated_normal([3500, 3000])),\r\n 'gfcb4': tf.Variable(tf.constant(0.1, shape=[3000])),\r\n 'rnnqW': tf.Variable(weights['rnnqW'], name='embed_ques_W'),\r\n 'rnnsW': tf.Variable(weights['rnnsW'], name='embed_state_W'),\r\n 'rnnsb': tf.Variable(weights['rnnsb'], name='embed_state_b'),\r\n 'rnnoutbeta': tf.Variable(weights['rnnoutbeta']),\r\n 'rnnoutscale': tf.Variable(weights['rnnoutscale']),\r\n 'cnnoutbeta': tf.Variable(weights['cnnoutbeta']),\r\n 'cnnoutscale': tf.Variable(weights['cnnoutscale']),\r\n 'featbeta': tf.Variable(tf.zeros([4096])),\r\n 'featscale': tf.Variable(tf.ones([4096])),\r\n 'gbeta': tf.Variable(tf.zeros([3000])),\r\n 'gscale': tf.Variable(tf.ones([3000]))\r\n }\r\n\r\n batch_no = 0\r\n\r\n\r\n# placeholder for noise variable to be passed into generator\r\nnoise = tf.placeholder(tf.float32, (None, 4096))\r\n\r\n# answer placeholrder\r\nanswers_true = tf.placeholder(tf.float32, (None, 3000))\r\ncnn_out_true = tf.placeholder(tf.float32, (None, 2048))\r\n\r\n\r\n# load nlp portion\r\nwith tf.variable_scope(\"rnn_module1\"):\r\n rnn_out_true, questions_true = rnn_module(var_dict) \r\n\r\ncnn_mean, cnn_var = tf.nn.moments(cnn_out_true, [0])\r\ncnn_out_true_n = tf.nn.batch_normalization(cnn_out_true,cnn_mean,cnn_var,var_dict['cnnoutbeta'],\r\n var_dict['cnnoutscale'],epsilon)\r\n\r\nrnn_mean, rnn_var = tf.nn.moments(rnn_out_true, [0])\r\nrnn_out_true_n = tf.nn.batch_normalization(rnn_out_true,rnn_mean,rnn_var,var_dict['rnnoutbeta'],\r\n var_dict['rnnoutscale'],epsilon)\r\n\r\n# combine features from image and question\r\nfeatures_true = combine_embeddings(cnn_out_true_n, rnn_out_true_n, var_dict)\r\n\r\n#features = tf.add(features_true, noise)\r\nfeatures = features_true\r\n#feat_mean, feat_var = tf.nn.moments(features_true, [0])\r\n#features_true_n = tf.nn.batch_normalization(features_true,feat_mean,feat_var,var_dict['featbeta'],\r\n# var_dict['featscale'],epsilon)\r\n\r\n# load generator network\r\ng_true = generator_me(features, var_dict)\r\n\r\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=g_true, labels=answers_true))\r\n\r\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\nwith tf.control_dependencies(update_ops):\r\n train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)\r\n\r\n# init variables\r\nsess.run(tf.global_variables_initializer())\r\n\r\n\r\n\r\n\r\nprint('loading data...\\n\\n')\r\nqa_data = load_data()\r\nprint('done loading data...\\n\\n')\r\n#batch_no = 0\r\nbatch_size = 50\r\n#while batch_no*batch_size < len(qa_data['training']):\r\nwhile batch_no < 4000:\r\n print('batch = ' + str(batch_no))\r\n (questions_in_true, answer_in_true, im_feat_true) = get_training_batch(batch_no, batch_size, qa_data)\r\n\r\n noise_in = np.random.normal(scale=0.3, size=[batch_size,4096])\r\n\r\n train_step.run(feed_dict={\r\n noise: noise_in, \r\n answers_true: answer_in_true,\r\n cnn_out_true: im_feat_true,\r\n questions_true: questions_in_true,\r\n })\r\n\r\n loss_val = sess.run(loss, feed_dict={\r\n noise: noise_in, \r\n answers_true: answer_in_true,\r\n cnn_out_true: im_feat_true,\r\n questions_true: questions_in_true,\r\n })\r\n\r\n g_out = sess.run(g_true, feed_dict={ \r\n noise: noise_in, \r\n answers_true: answer_in_true,\r\n cnn_out_true: im_feat_true,\r\n questions_true: questions_in_true,\r\n })\r\n\r\n print('loss = ' + str(loss_val))\r\n loss_vals.append(loss_val)\r\n np.save('loss_vals_g_v' + save_ver, loss_vals)\r\n #print(loss_val)\r\n\r\n answers_out = np.argmax(g_out, axis=1)\r\n answers_idx_true = np.argmax(answer_in_true, axis=1)\r\n error = float(np.sum(answers_out == answers_idx_true)) / float(batch_size)\r\n acc_vals.append(error)\r\n np.save('acc_vals_g_v' + save_ver, acc_vals)\r\n print('error = ' + str(error))\r\n\r\n if batch_no % 25 == 0:\r\n weights_save = {}\r\n for key in var_dict:\r\n weights_save[key] = var_dict[key].eval()\r\n weights_save['batch_no'] = batch_no\r\n np.save('weights_g_v' + save_ver, weights_save)\r\n\r\n batch_no += 1\r\n\r\n ","sub_path":"train_g_v2_nonoise.py","file_name":"train_g_v2_nonoise.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"324930501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 16 17:45:00 2019\n\n@author: TAPAN\n\"\"\"\n\n\n\nimport pandas as pd\nfrom selenium import webdriver\nfrom collections import OrderedDict\n\n\n\n\nsource = \"https://bidplus.gem.gov.in/bidlists\"\n\n\n#driver = webdriver.Firefox(executable_path=r'C:/Users/hp/Downloads/geckodriver')\ndriver = webdriver.Chrome(r\"D:\\Forsk\\Day 08\\Work\\chromedriver.exe\")\n\ndriver.get(source) # Opening the submission url\n\n\n\n\nright_table=driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[1]')\n\n\n#//*[@id=\"pagi_content\"]/div[1]/div[1]/p[1]/a\n#//*[@id=\"pagi_content\"]/div[2]/div[1]/p[1]/a\n\n#//*[@id=\"pagi_content\"]/div[1]/div[2]/p[1]/span\n#//*[@id=\"pagi_content\"]/div[2]/div[2]/p[1]/span\n\n\n#//*[@id=\"pagi_content\"]/div[1]/div[2]/p[2]/span\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[3]/p[2]\n#\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[4]/p[1]/span\n#\n#//*[@id=\"pagi_content\"]/div[1]/div[4]/p[2]/span\n\n\nbid_id=[]\nitem=[]\nquantity=[]\ndept_name_address=[]\nstart_date=[]\nend_date=[]\nstart_time=[]\nend_time=[]\n\n\nfor val in range(1,11):\n bid_id.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[1]/p[1]/a'.format(val)).text)\n item.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[2]/p[1]/span'.format(val)).text)\n quantity.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[2]/p[2]/span'.format(val)).text)\n dept_name_address.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[3]/p[2]'.format(val)).text)\n start_date.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[4]/p[1]/span'.format(val)).text)\n end_date.append(driver.find_element_by_xpath('//*[@id=\"pagi_content\"]/div[{}]/div[4]/p[2]/span'.format(val)).text)\n \n\nstart_date_list=[i[:i.find(' ')] for i in start_date]\nstart_time=[i[i.find(' ') + 1:] for i in start_date]\n\nend_date_list=[i[:i.find(' ')] for i in end_date]\nend_time=[i[i.find(' ') + 1:] for i in end_date]\n\n\n \ncol_name = [\"Bid No.\",\"Item\",\"Quantity\",\"Dept name & address\",\"Start Date\",\"End Date\",\"Start Time\",\"End Time\"]\ncol_data = OrderedDict(zip(col_name,[bid_id,item,quantity,dept_name_address,start_date_list,end_date_list,start_time,end_time]))\n\n\n\nprint(bid_id)\nprint(item)\nprint(quantity)\nprint(start_time)\nprint (end_time)\n\n\n\n\nimport mysql.connector \n# connect to MySQL server along with Database name\n\nconn = mysql.connector.connect(user='CUQQMCS80b', password='TRLKYhvlac',\n host='remotemysql.com', database = 'CUQQMCS80b')\n#, database = 'forsk_test'\n\n# creating cursor\nc = conn.cursor()\n\n# STEP 0\n#c.execute(\"DROP DATABASE employee;\")\n\n# STEP 1\n#c.execute(\"CREATE DATABASE GeM;\")\n\n# STEP 2\n#c.execute(\"DROP Table dat;\")\n\n\n# STEP 3\nc.execute (\"\"\"CREATE TABLE dat(\n Bid_id TEXT,\n item TEXT,\n Quantity INTEGER,\n Dept_name_address TEXT,\n Start_Date TEXT,\n End_Date TEXT,\n Start_Time TEXT,\n End_Time TEXT\n )\"\"\")\n\n\nfor i in range(10):\n c.execute(\"INSERT INTO dat VALUES ('{}','{}',{},'{}','{}','{}','{}','{}')\".format (bid_id[i],item[i],quantity[i],dept_name_address[i],start_date[i],end_date[i],start_time[i],end_time[i]))\n\n\n\n\n\n\n# c.execute(\"INSERT INTO employee VALUES ({},'{}', '{}', {})\".format(idd, first,last,pay))\n\n\nc.execute(\"SELECT * FROM dat\")\n\nconn.commit()\nconn.close()\n\n# STEP 5\n# returns one or otherwise None as a tuple\n#print ( c.fetchone()) \n#\n## returns one or otherwise None as a tuple\n#print ( c.fetchmany(2)) \n#\n## returns a list of tuples\n#print ( c.fetchall() )\n#\n#\n## Since now the cursor has read all the rows and we are at End\n## So again fetching the records from the database\n#c.execute(\"SELECT * FROM employees\")\n#\n#\n## STEP 6\n#df = DataFrame(c.fetchall()) # putting the result into Dataframe\n#df.columns = [\"id\",\"first\",\"last\",\"pay\"]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Day 09/bid_plus_db.py","file_name":"bid_plus_db.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"296769950","text":"# -*- coding: utf-8 -*-\n\nfrom plugin import Plugin\n\nfrom flask import jsonify, abort\n\nclass LangsPlugin(Plugin):\n name = \"langs\"\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n\n def on_get_all(self, request):\n langs = self.system['mongo'].db.langs\n output = []\n for lang in langs.find():\n output.append({'id' : lang['id']})\n return jsonify(output), 200, {\"X-Total-Count\": str(len(output)), \n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Access-Control-Expose-Headers\": \"X-Total-Count\"}\n\n def on_get(self, id, request):\n langs = self.system['mongo'].db.langs\n lang = langs.find_one({'id' : id})\n if lang:\n output = {'id' : lang['id']}\n else:\n abort(404)\n return jsonify(output)\n\n def on_create(self, request):\n langs = self.system['mongo'].db.langs\n id = request.json['id']\n lang_id = langs.insert({'id': id})\n new_lang = langs.find_one({'_id': lang_id })\n output = {'id' : new_lang['id']}\n return jsonify(output)\n\n def on_update(self, id, request):\n output = {'id' : id}\n return jsonify(output)\n\n def on_delete(self, id, request):\n langs = self.system['mongo'].db.langs\n lang = langs.delete_one({'id' : id})\n if lang:\n output = {'id' : id}\n else:\n abort(404)\n return jsonify(output)\n","sub_path":"docker-images/bot/plugins/langs.py","file_name":"langs.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"514433389","text":"# \n\n# Minimal CGI script for Online Python Tutor (v3).\n\nimport cgi\nimport json\nimport pg_logger\nimport sys\n\n\ndef cgi_finalizer(input_code, output_trace):\n \"\"\"Write JSON output for js/pytutor.js as a CGI result.\"\"\"\n ret = dict(code=input_code, trace=output_trace)\n json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr\n print(\"Content-type: text/plain; charset=iso-8859-1\\n\")\n print(json_output)\n\n\nif len(sys.argv) > 1:\n user_script = open(sys.argv[1]).read()\nelse:\n form = cgi.FieldStorage()\n user_script = form['user_script'].value\n # convert from string to a Python boolean ...\n cumulative_mode = (form['cumulative_mode'].value == 'true')\n\npg_logger.exec_script_str(user_script, cumulative_mode, cgi_finalizer)\n","sub_path":"PyTutorGAE/web_exec.py","file_name":"web_exec.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"121816204","text":"from typing import (\n Iterable,\n List,\n Literal,\n Optional,\n Set,\n Union,\n TypeVar,\n Type,\n get_args,\n)\n\n\nclass Fmi2CoSim:\n def __init__(self) -> None:\n pass\n\n\nT = TypeVar(\"T\", float, int, bool, str)\n_variability_all = Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"]\n_causality_all = Literal[\"exact\", \"approx\", \"calculated\"]\n\n\nclass Fmi2Variable:\n def __init__(\n self,\n name: str,\n type: Type[T],\n causality: Literal[\n \"parameter\",\n \"calculated_parameter\",\n \"input\",\n \"output\",\n \"local\",\n \"independent\",\n ],\n variability: _variability_all,\n initial: _causality_all,\n description: str = None,\n declared_type: str = None,\n quantity: str = None,\n unit: str = None,\n display_unit: str = None,\n relative_quantity: bool = None,\n min: T = None,\n max: T = None,\n nominal: T = None,\n unbounded: bool = None,\n start: T = None,\n derivative: int = None,\n reinit: bool = None,\n ) -> None:\n\n if type not in get_args(T):\n raise ValueError(\n f\"Invalid data type for variable: {name}, choices are: '{get_args(T)}', got: {type}\"\n )\n # TODO add validation logic here\n\n self.name = name\n self.type = type\n self.description = description\n self.causality = causality\n self.variability = variability\n self.initial = initial\n self.declared_type = declared_type\n self.quantity = quantity\n self.unit = unit\n self.display_unit = display_unit\n self.relative_quantity = relative_quantity\n self.min = min\n self.max = max\n self.nominal = nominal\n self.unbounded = unbounded\n self.start = start\n self.derivative = derivative\n self.reinit = reinit\n\n\nclass Fmi2FMU:\n def __init__(\n self,\n model_name: str,\n fmi2_version: str = None,\n guid: str = None,\n description: str = None,\n author: str = None,\n version: str = None,\n copyright: str = None,\n license: str = None,\n generation_tool: str = None,\n generation_data_and_time: str = None,\n variable_naming_convention: Literal[\"flat\", \"structured\"] = None,\n number_of_event_indicators=None,\n ) -> None:\n self._variables: List[Fmi2Variable] = []\n\n def define_model_exchange(self):\n raise NotImplementedError(\"currently only co-sim is supported\")\n\n def define_cosimulation(\n self,\n model_identifier: str,\n needs_execution_tool: bool = None,\n can_handle_variable_communication_step_size: bool = None,\n can_interpolate_inputs: bool = None,\n max_output_derivative_order: int = None,\n can_run_asynchronuously: bool = None,\n can_be_instantiated_only_once_per_process: bool = None,\n can_not_use_memory_management_functions: bool = None,\n can_get_and_set_fmu_state: bool = None,\n can_serialize_fmu_state: bool = None,\n provides_directional_derivative: bool = None,\n ):\n pass\n\n def define_log_categories(self, categories: Iterable[str]):\n pass\n\n def define_unit_definitions(self):\n pass\n\n def define_default_experiment(self):\n pass\n\n def define_vendor_annotations(self):\n pass\n\n def _add_variable(\n self,\n name: str,\n type: Type[T],\n causality: Literal[\n \"parameter\",\n \"calculated_parameter\",\n \"input\",\n \"output\",\n \"local\",\n \"independent\",\n ],\n variability: Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"],\n initial: Literal[\"exact\", \"approx\", \"calculated\"],\n declared_type=None,\n quantity: str = None,\n unit: str = None,\n display_unit: str = None,\n relative_quantity: bool = None,\n min: T = None,\n max: T = None,\n nominal: T = None,\n unbounded: bool = None,\n start: T = None,\n derivative: int = None,\n reinit: bool = None,\n description: str = None,\n ):\n self._variables.append(\n Fmi2Variable(\n name=name,\n type=type,\n causality=causality,\n variability=variability,\n initial=initial,\n declared_type=declared_type,\n quantity=quantity,\n unit=unit,\n display_unit=display_unit,\n relative_quantity=relative_quantity,\n min=min,\n max=max,\n nominal=nominal,\n unbounded=unbounded,\n start=start,\n derivative=derivative,\n reinit=reinit,\n description=description,\n )\n )\n\n def add_parameter(\n self,\n name: str,\n type: Type[T],\n variability: Literal[\"fixed\", \"tunable\"],\n start: T,\n description: str = None,\n ):\n self._add_variable(\n name=name,\n type=type,\n variability=variability,\n causality=\"parameter\",\n initial=\"exact\",\n start=start,\n description=description,\n )\n\n def add_calculated_parameter(\n self,\n name: str,\n type: Type[T],\n variability: Literal[\"fixed\", \"tunable\"],\n initial=Literal[\"approx\", \"calculated\"],\n description: str = None,\n ):\n pass\n\n def add_input(\n self,\n name: str,\n type: Type[T],\n variability: Literal[\"discrete\", \"continuous\"],\n start: T = None,\n min: T = None,\n max: T = None,\n description: str = None,\n ):\n pass\n\n def add_output(\n self,\n name: str,\n type: Type[T],\n variability: Literal[\"constant\", \"discrete\", \"continuous\"],\n initial: Literal[\"exact\", \"calculated\"],\n start: T = None,\n description: str = None,\n ):\n pass\n\n def add_local_variable(\n self,\n name: str,\n type: Type[T],\n variability: Literal[\"constant\", \"fixed\", \"tunable\", \"discrete\", \"continuous\"],\n initial: Literal[\"exact\", \"approx\", \"calculated\"],\n description: str = None,\n ):\n pass\n\n def add_independent_variable(\n self, name: str, description: str = None,\n ):\n pass\n\n\nclass Fmi3FMU:\n pass\n\n\nif __name__ == \"__main__\":\n\n cosim = Fmi2CoSim()\n\n adder = Fmi2FMU(\"adder\")\n adder.add_input(\"real_a\", type(float), \"continuous\", start=0.0)\n adder.add_input(\"real_b\", type(float), \"continuous\", start=0.0)\n adder.add_output(\n \"real_c\", type(float), variability=\"continuous\", initial=\"calculated\",\n )\n\n adder.add_input(\"integer_c\", int, \"discrete\")\n adder.add_input(\"integer_b\", int, \"discrete\")\n adder.add_output(\n \"integer_c\", int, \"discrete\", initial=\"calculated\",\n )\n\n adder.add_input(\"boolean_c\", bool, \"discrete\")\n adder.add_input(\"boolean_b\", bool, \"discrete\")\n adder.add_output(\n \"boolean_c\", bool, \"discrete\", initial=\"calculated\",\n )\n\n adder.add_input(\"integer_c\", str, \"discrete\")\n adder.add_input(\"integer_b\", str, \"discrete\")\n adder.add_output(\n \"integer_c\", str, \"discrete\", initial=\"calculated\",\n )\n\n # adder.export(outdir=\"...\", language=\"python\")\n\n","sub_path":"tool/unifmu/authoring.py","file_name":"authoring.py","file_ext":"py","file_size_in_byte":7564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"188193834","text":"import re\nfrom copy import deepcopy\n\n\ndef _has_mod(mod):\n return lambda n: any(map(\n lambda m: m.kind == mod.kind(), n.modifiers\n )) if n is not None else False\n\n\nclass CBSelect:\n def __init__(self, *selects, asname=None):\n self.selects = list(selects)\n self.as_name = asname\n self.label = None\n\n def __mod__(self, other):\n if isinstance(other, CBSelect):\n self.selects.extend(other.selects)\n self.label = other.label\n self.as_name = (\n other.as_name if other.as_name is not None else self.as_name\n )\n else:\n self.label = other\n return self\n\n def __rmod__(self, other):\n if isinstance(other, CBSelect):\n self.selects.extend(other.selects)\n self.label = other.label\n self.as_name = (\n other.as_name if other.as_name is not None else self.as_name\n )\n else:\n self.label = other\n return self\n\n\nclass CB:\n _depth = 0\n\n def __init__(self, init=None):\n self.kind = 'Python.Code.Root'\n\n self.label = None\n self.selects = []\n self.select_as = None\n self.type = init\n self.children = []\n self.constraints = []\n self.modifiers = []\n\n self.last = self\n self.parent = None\n\n self.merge_key_l = None\n self.merge_key_r = None\n\n self.id = 0\n\n def idify(self):\n idx = 0\n worklist = [ self ]\n while len(worklist) > 0:\n idx += 1\n current = worklist.pop()\n current.id = idx\n for child in current.children:\n worklist.append(child)\n\n def part_of_merge(self):\n return (\n self.merge_key_l is not None \n or self.merge_key_r is not None\n )\n\n def remove_mod(self, mod):\n self.modifiers = [\n x for x in self.modifiers if x.kind != mod.kind()\n ]\n return self\n\n def without_mods(self):\n self.modifiers = []\n return self\n\n def with_mods(self, *args):\n self.modifiers = list(args)\n return self\n\n def with_mod(self, mod):\n self.modifiers.append(mod)\n return self\n\n def with_constraints(self, *args):\n self.constraints = list(args)\n return self\n\n def add_constraints(self, *args):\n self.constraints.extend(list(args))\n return self\n\n def with_constraint(self, constraint):\n self.constraints.append(constraint)\n return self\n\n def is_merge(self, lkey, rkey):\n assert len(self.children) == 1\n self.merge_key_l = lkey\n self.children[0].merge_key_r = rkey\n return self\n\n def with_labels_from(self, other):\n self.label = other.label\n return self\n\n def without_labels(self):\n self.label = None\n return self\n\n #############################################################################\n # TREE-PATH-EXPR CONVERSION\n #############################################################################\n \n def to_path(self):\n if self.type.startswith('$'):\n return '' # Virtual nodes have no contribution (at this level)\n\n # Handle \"normal\" nodes\n as_path = self.type if '$' not in self.type else ''\n for con in sorted(self.constraints, key=lambda c: c.precedence):\n as_path = con.to_path(as_path)\n return as_path\n \n #############################################################################\n # QUERY CONSTRUCTION (merge/bubbleup/nest)\n #############################################################################\n\n def bubbleup(self):\n self.last = self.last.parent\n return self\n\n def nest(self, other):\n other.parent = self.last\n self.last.children.append(other)\n self.last = other\n return self\n\n def merge(self, other):\n self.parent = other.parent\n self.last.type = other.type\n self.last.label = other.label\n self.last.children += other.children\n self.last.constraints += other.constraints\n self.last.modifiers += other.modifiers\n self.last.selects = other.selects\n self.last.select_as = other.select_as\n return self\n\n def insert_and(self):\n new_root = deepcopy(self)\n old_children = new_root.children\n new_root.children = []\n new_root.last = new_root\n\n the_and = CB('$and')\n for child in old_children:\n the_and.nest(child).bubbleup()\n \n return new_root.nest(the_and)\n\n #############################################################################\n # TREE WALK/EDIT\n #############################################################################\n\n def has_mod(self, mod):\n if _has_mod(mod)(self):\n return True\n\n return False\n\n def get_con(self, con):\n for c in self.constraints:\n if c.kind == con.kind():\n return c\n\n return None\n\n def rewrite(self, selector, rewriter):\n if selector(self):\n return rewriter(self)\n\n new_children = []\n for child in self.children:\n new_children.append(\n child.rewrite(selector, rewriter)\n )\n self.children = new_children\n return self\n \n def rewrite_mods(self, mods):\n changed = self\n for mod in mods:\n changed = changed.rewrite(_has_mod(mod), mod.rewrite)\n return changed\n\n def rewrite_all_mods(self):\n for mod in CB.ALL_MODS:\n while self.has_mod(mod):\n self = self.rewrite_mods([mod])\n return self\n\n #############################################################################\n # LABEL ASSIGN (via %)\n # - usage CB(..) % 'label'\n #############################################################################\n\n def __mod__(self, other):\n if isinstance(other, CBSelect):\n self.selects = other.selects\n self.label = other.label\n self.select_as = other.as_name\n else:\n self.label = other\n return self\n\n def __rmod__(self, other):\n if isinstance(other, CBSelect):\n self.selects = other.selects\n self.label = other.label\n self.select_as = other.as_name\n else:\n self.label = other\n return self\n\n #############################################################################\n # DISPLAY (str/debug methods)\n #############################################################################\n\n def __str__(self):\n indent = ' ' * CB._depth\n res = '{}(\\n'.format(indent)\n\n # Render our props \n if self.merge_key_l:\n res += '{} MERGE (L) key=`{}`\\n'.format(indent, self.merge_key_l)\n if self.merge_key_r:\n res += '{} MERGE (R) key=`{}`\\n'.format(indent, self.merge_key_r)\n if self.type is not None:\n if hasattr(self, 'id'):\n res += '{} type ({})=`{}`\\n'.format(indent, self.id, self.type)\n else:\n res += '{} type=`{}`\\n'.format(indent, self.type)\n if len(self.modifiers) > 0:\n res += '{} mods={{{}}}\\n'.format(indent,\n ';'.join(map(str, self.modifiers)))\n if len(self.constraints) > 0:\n res += '{} cons={{{}}}\\n'.format(indent,\n ';'.join(map(str, self.constraints)))\n if self.label is not None:\n res += '{} label=`{}`\\n'.format(indent, self.label)\n \n # Render children (indent/dedent)\n CB._depth += 2\n res += '{} children=[\\n'.format(indent)\n res += (','.join(map(str, self.children)) +\n '\\n') if len(self.children) > 0 else ''\n CB._depth -= 2\n \n res += '{} ]\\n'.format(indent)\n res += '{})'.format(indent)\n\n # Fixup (make prettier)\n res = re.sub(r'\\)\\n *\\]', ')]', res)\n res = re.sub(r'\\[\\n *\\(', '[(', res)\n res = re.sub(r'\\[\\n *\\n? *\\]', '[ ]', res)\n res = re.sub(r'\\), +\\(', '), (', res)\n return res\n\n #############################################################################\n","sub_path":"applications/jupyter-extension/nteract_on_jupyter/notebooks/codebookold/python/querybuilder.py","file_name":"querybuilder.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"446182879","text":"class STModule:\n def __init__(self):\n self.name = 'ipy/persistence'\n self.language = 'ipy'\n self.description = 'Set a new value in HKCU\\...\\Run registry key to get a session each time the user connects (works only with msbuild)'\n self.author = '@maximemf'\n self.options = {\n 'Path': {\n 'Description' : 'Path to the stager file',\n 'Required' : True,\n 'Value' : \"C:\\\\\\\\WINDOWS\\\\\\\\Temp\\\\\\\\msbuild.xml\"\n }\n }\n\n def payload(self):\n with open('modules/ipy/src/persistence.py', 'r') as module_src:\n src = module_src.read()\n src = src.replace('PATH', self.options['Path']['Value'])\n return src\n","sub_path":"Server/modules/ipy/persistence.py","file_name":"persistence.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"264546222","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom ast import literal_eval\nwith open('config.py', encoding='utf-8') as f:\n text = f.read()\n exec(text)\n\n\ndef get_all_config_options(text):\n result = []\n N = len(text)\n for i in range(N):\n current = text[i]\n if current == '\\n':\n if i + 1 < N:\n next_character = text[i + 1]\n if next_character.isalpha():\n inds = text[i + 1:].index('=') - 1\n current_config_options = text[i + 1:i + 1 + inds]\n result.append(current_config_options)\n return result\n\n\ndef change(var, new, is_str=True):\n text = open('config.py', encoding='utf-8').read()\n text_ls = list(text)\n var_len = len(var) + 1\n var_ind = text.index('\\n' + var + ' ') + var_len\n next_line = text[var_ind:].index('\\n')\n if is_str:\n text_ls[var_ind:var_ind + next_line] = f\" = '{new}'\"\n else:\n text_ls[var_ind:var_ind + next_line] = f\" = {new}\"\n with open('config.py', 'w', encoding='utf-8') as f:\n f.write(''.join(text_ls))\n\n\nclass Root(Tk):\n def __init__(self):\n super(Root, self).__init__()\n self.title(\"Settings\")\n self.minsize(800, 600)\n self.wm_iconbitmap('piano.ico')\n self.config_options_bar = Scrollbar(self)\n self.config_options_bar.place(x=235, y=120, height=170, anchor=CENTER)\n self.choose_config_options = Listbox(\n self, yscrollcommand=self.config_options_bar.set)\n self.choose_config_options.bind('<>',\n self.show_current_config_options)\n all_config_options = get_all_config_options(text)\n self.options_num = len(all_config_options)\n self.all_config_options = all_config_options\n for k in all_config_options:\n self.choose_config_options.insert(END, k)\n self.choose_config_options.place(x=0, y=30, width=220)\n self.config_options_bar.config(\n command=self.choose_config_options.yview)\n self.config_name = ttk.Label(self, text='')\n self.config_name.place(x=300, y=20)\n self.config_contents = Text(self,\n undo=True,\n autoseparators=True,\n maxundo=-1)\n self.config_contents.bind('', self.config_change)\n self.config_contents.place(x=350, y=50, width=400, height=400)\n self.choose_filename_button = ttk.Button(self,\n text='choose filename',\n command=self.choose_filename)\n self.choose_directory_button = ttk.Button(\n self, text='choose directory', command=self.choose_directory)\n self.choose_filename_button.place(x=0, y=250)\n self.choose_directory_button.place(x=0, y=320)\n self.save = ttk.Button(self, text=\"save\", command=self.save_current)\n self.save.place(x=0, y=400)\n self.saved_text = ttk.Label(text='saved')\n self.search_text = ttk.Label(self, text='search for config options')\n self.search_text.place(x=0, y=450)\n self.search_contents = StringVar()\n self.search_contents.trace_add('write', self.search)\n self.search_entry = Entry(self, textvariable=self.search_contents)\n self.search_entry.place(x=0, y=480)\n self.search_inds = 0\n self.up_button = ttk.Button(\n self,\n text='up',\n command=lambda: self.change_search_inds(-1),\n width=8)\n self.down_button = ttk.Button(\n self,\n text='down',\n command=lambda: self.change_search_inds(1),\n width=8)\n self.up_button.place(x=170, y=480)\n self.down_button.place(x=250, y=480)\n self.search_inds_list = []\n self.value_dict = {i: str(eval(i)) for i in self.all_config_options}\n\n def config_change(self, e):\n try:\n current = self.config_contents.get('1.0', 'end-1c')\n current = literal_eval(current)\n if type(current) == str:\n current = f\"'{current}'\"\n current_config = self.choose_config_options.get(ANCHOR)\n exec(f'{current_config} = {current}', globals())\n except:\n pass\n\n def change_search_inds(self, num):\n self.search_inds += num\n if self.search_inds < 0:\n self.search_inds = 0\n if self.search_inds_list:\n search_num = len(self.search_inds_list)\n if self.search_inds >= search_num:\n self.search_inds = search_num - 1\n first = self.search_inds_list[self.search_inds]\n self.choose_config_options.selection_clear(0, END)\n self.choose_config_options.selection_set(first)\n self.choose_config_options.selection_anchor(first)\n self.choose_config_options.see(first)\n self.show_current_config_options(0)\n\n def search(self, *args):\n current = self.search_contents.get()\n all_config_options = self.all_config_options\n self.search_inds_list = [\n i for i in range(self.options_num)\n if current in all_config_options[i]\n ]\n if self.search_inds_list:\n self.search_inds = 0\n first = self.search_inds_list[self.search_inds]\n self.choose_config_options.selection_clear(0, END)\n self.choose_config_options.selection_set(first)\n self.choose_config_options.selection_anchor(first)\n self.choose_config_options.see(first)\n self.show_current_config_options(0)\n else:\n self.choose_config_options.selection_clear(0, END)\n\n def show_current_config_options(self, e):\n current_config = self.choose_config_options.get(ANCHOR)\n self.config_name.configure(text=current_config)\n self.config_contents.delete('1.0', END)\n current_config_value = eval(current_config)\n if type(current_config_value) == str:\n current_config_value = f\"'{current_config_value}'\"\n else:\n current_config_value = str(current_config_value)\n self.config_contents.insert(END, current_config_value)\n\n def choose_filename(self):\n filename = filedialog.askopenfilename(initialdir='.',\n title=\"choose filename\",\n filetype=((\"all files\",\n \"*.*\"), ))\n self.config_contents.delete('1.0', END)\n self.config_contents.insert(END, f\"'{filename}'\")\n self.config_change(0)\n\n def choose_directory(self):\n directory = filedialog.askdirectory(\n initialdir='.',\n title=\"choose directory\",\n )\n self.config_contents.delete('1.0', END)\n self.config_contents.insert(END, f\"'{directory}'\")\n self.config_change(0)\n\n def show_saved(self):\n self.saved_text.place(x=140, y=400)\n self.after(1000, self.saved_text.place_forget)\n\n def save_current(self):\n changed = False\n for each in self.all_config_options:\n current_value = eval(each)\n current_value_str = str(current_value)\n before_value = self.value_dict[each]\n if current_value_str != before_value:\n change(each, current_value_str, type(current_value) == str)\n self.value_dict[each] = current_value_str\n changed = True\n if changed:\n self.show_saved()\n\n\nroot = Root()\nroot.mainloop()\n","sub_path":"change_settings.pyw","file_name":"change_settings.pyw","file_ext":"pyw","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"206560982","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0] * 256 # memory with 256 bytes\n self.reg = [0] * 8 # 8 general-purpose registers\n self.pc = 0 # program counter, pointing at current command\n self.sp = self.reg[7] # stack pointer, reg[7] reserved position\n self.fl_l = False # 00000LGE\n self.fl_g = False\n self.fl_e = False\n\n def load(self):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n try:\n with open(sys.argv[1]) as f:\n for line in f:\n comment_split = line.split(\"#\") # splits each line or comment into a list of strings\n num = comment_split[0].strip() # removes spaces, ignores second index\n if num == '': # ignore blank lines\n continue\n val = int(num, 2) # binary\n self.ram[address] = val\n address += 1\n except FileNotFoundError:\n print(f\"{sys.argv[0]}: {sys.argv[1]} not found\")\n sys.exit(2)\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n elif op == \"SUB\":\n self.reg[reg_a] -= self.reg[reg_b]\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n elif op == \"DIV\":\n self.reg[reg_a] /= self.reg[reg_b]\n elif op == \"CMP\":\n if self.reg[reg_a] == self.reg[reg_b]:\n # set equal flag E to 1, else 0\n self.fl_e = True\n if self.reg[reg_a] < self.reg[reg_b]:\n # set lass flag L to 1, else 0\n self.fl_l = True\n if self.reg[reg_a] > self.reg[reg_b]:\n # set greater flag G to 1, else 0\n self.fl_g = True\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def ram_read(self, address):\n '''Should accept an address and return the stored value in the ram'''\n return self.ram[address]\n \n def ram_write(self, address, value):\n '''Should accept an address and value and write the value to that place in ram'''\n self.ram[address] = value\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n LDI = 0b10000010\n PRN = 0b01000111\n MUL = 0b10100010\n ADD = 0b10100000\n PUSH = 0b01000101\n POP = 0b01000110\n HLT = 0b00000001\n CAL = 0b01010000\n RET = 0b00010001\n CMP = 0b10100111\n JMP = 0b01010100\n JEQ = 0b01010101\n JNE = 0b01010110\n\n running = True\n\n while running:\n # instruction = self.ram[self.pc]\n instruction = self.ram_read(self.pc)\n reg_a = self.ram_read(self.pc+1)\n reg_b = self.ram_read(self.pc+2)\n\n if instruction == LDI: # save the value to reg\n # +1 is an register address, +2 is a value\n self.reg[reg_a] = reg_b\n self.pc += 3\n elif instruction == HLT: # HLT - halt\n running = False\n self.pc += 1\n elif instruction == PRN: # print\n # get value from +1 (address at register)\n value = self.reg[reg_a]\n print(value)\n self.pc += 2\n elif instruction == MUL:\n self.alu('MUL', reg_a, reg_b)\n self.pc += 3\n elif instruction == ADD:\n self.alu('ADD', reg_a, reg_b)\n self.pc += 3\n elif instruction == PUSH: # push value given to register\n # get value from register address\n value = self.reg[reg_a]\n # decrement stack pointer\n self.sp -= 1\n self.ram_write(self.sp, value)\n self.pc += 2\n elif instruction == POP: # return value given to register\n # get value from top of stack\n value = self.ram_read(self.sp)\n # set value to register address given\n self.reg[reg_a] = value\n # decrement stack pointer and add to program counter\n self.sp -= 1\n self.pc += 2\n elif instruction == CAL: # jumps to address given\n # compute return address after call finishes\n return_address = self.pc + 2\n # push return address on the stack\n self.reg[self.sp] -= 1\n self.ram[self.reg[self.sp]] = return_address\n # set pc to value in given register\n self.pc = self.reg[reg_a]\n elif instruction == RET:\n # pop return address from top of stack\n return_address = self.ram[self.reg[self.sp]]\n self.reg[self.sp] += 1\n # set pc\n self.pc = return_address\n \n # SPRINT\n elif instruction == CMP: # compare reg_a and reg_b\n self.alu('CMP', reg_a, reg_b)\n self.pc += 3\n elif instruction == JMP: # jump to given reg address\n # set pc to the given register address\n self.pc = self.reg[reg_a]\n elif instruction == JEQ: # if E is 1, jump to given address\n if self.fl_e == True:\n self.pc = self.reg[reg_a]\n else:\n self.pc += 2\n elif instruction == JNE: # if E is 0, jump to stored given address\n if self.fl_e == False:\n self.pc = self.reg[reg_a]\n else:\n self.pc += 2\n\n else:\n print('Unknown Instruction:', instruction)\n sys.exit(1)","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"557091220","text":"# coding=utf-8\nimport numpy as np\n\nfrom pypint.problems import IInitialValueProblem, HasExactSolutionMixin, HasDirectImplicitMixin\nfrom pypint.utilities import assert_condition, assert_is_instance, class_name, assert_named_argument\nfrom pypint.solvers.cores.implicit_sdc_core import ImplicitSdcCore\n\n\nclass OneDimensionalHeatEquation(IInitialValueProblem, HasExactSolutionMixin, HasDirectImplicitMixin):\n \"\"\":math:`u'(t, \\\\phi_t) = \\\\alpha \\\\laplace u(t, \\\\phi_t)`\n\n Describes the following first-order ODE initial value problem:\n\n .. math::\n\n \\\\begin{align}\n u'(t, \\\\phi_t) &= \\\\alpha \\\\laplace u(x, \\\\phi_t) \\\\\\\\\n u(x, 0) &= u_0 (x)\n \\\\end{align}\n\n With an exact solution.\n\n Parameters\n ----------\n alpha : :py:class:`float`\n *(optional)*\n Coefficient :math:`\\\\lambda`\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(OneDimensionalHeatEquation, self).__init__(*args, **kwargs)\n HasExactSolutionMixin.__init__(self, *args, **kwargs)\n HasDirectImplicitMixin.__init__(self, *args, **kwargs)\n\n if self.time_start is None:\n self.time_start = 0.0\n if self.time_end is None:\n self.time_end = 1.0\n if self.initial_value is None:\n self.initial_value = complex(1.0, 0.0) * np.ones(self.dim)\n\n if \"alpha\" not in kwargs:\n kwargs[\"alpha\"] = 1.0\n self.alpha = kwargs[\"alpha\"]\n\n if isinstance(self.alpha, complex):\n self.numeric_type = np.complex\n\n # self.exact_function = lambda phi_of_time: self.initial_value * np.exp(self.lmbda * phi_of_time)\n\n self._strings[\"rhs\"] = r\"\\alpha \\laplace u(x,t)\"\n self._strings[\"exact\"] = r\"derivable using Fourier transformation\"\n\n # multigrid stuff needed\n\n\n def evaluate(self, time, phi_of_time, partial=None):\n super(OneDimensionalHeatEquation, self).evaluate(time, phi_of_time, partial)\n if partial is not None and isinstance(self.lmbda, complex):\n if isinstance(partial, str) and partial == \"impl\":\n return self.lmbda.imag * phi_of_time\n elif partial == \"expl\":\n return self.lmbda.real * phi_of_time\n else:\n return self.lmbda * phi_of_time\n\n def direct_implicit(self, *args, **kwargs):\n \"\"\"Direct Implicit Formula for :math:`u'(t, \\\\phi_t) &= \\\\lambda u(t, \\\\phi_t)`\n \"\"\"\n assert_is_instance(self.lmbda, complex,\n message=\"Direct implicit formula only valid for imaginay lambda: NOT %s\"\n % class_name(self.lmbda),\n checking_obj=self)\n\n assert_named_argument('phis_of_time', kwargs, checking_obj=self)\n assert_named_argument('delta_node', kwargs, checking_obj=self)\n assert_named_argument('integral', kwargs, checking_obj=self)\n\n _phis = kwargs[\"phis_of_time\"]\n assert_is_instance(_phis, list, message=\"Direct implicit formula needs multiple phis.\", checking_obj=self)\n assert_condition(len(_phis) == 3, ValueError, message=\"Need exactly three different phis.\", checking_obj=self)\n\n # _phis[0] : previous iteration -> previous step\n # _phis[1] : previous iteration -> current step\n # _phis[2] : current iteration -> previous step\n\n _dn = kwargs[\"delta_node\"]\n # TODO: make this numerics check more advanced (better warning for critical numerics)\n assert_condition(_dn * self.lmbda.real != 1.0,\n ArithmeticError, \"Direct implicit formula for lambda={:f} and dn={:f} not valid. \"\n .format(self.lmbda, _dn) + \"Try implicit solver.\",\n self)\n _int = kwargs[\"integral\"]\n\n if 'core' in kwargs and isinstance(kwargs['core'], ImplicitSdcCore):\n return (_phis[2] - _dn * self.lmbda * _phis[1] + _int) / (1 - self.lmbda * _dn)\n else:\n return \\\n (_phis[2]\n + _dn * (complex(0, self.lmbda.imag) * (_phis[2] - _phis[0]) - self.lmbda.real * _phis[1])\n + _int) \\\n / (1 - self.lmbda.real * _dn)\n\n @property\n def lmbda(self):\n return self._lmbda\n\n @lmbda.setter\n def lmbda(self, lmbda):\n self._lmbda = lmbda\n\n def print_lines_for_log(self):\n _lines = super(LambdaU, self).print_lines_for_log()\n _lines['Coefficients'] = '\\lambda = {}'.format(self.lmbda)\n return _lines\n\n def __str__(self):\n str = super(LambdaU, self).__str__()\n str += r\", \\lambda={}\".format(self.lmbda)\n return str\n","sub_path":"examples/problems/one_dimensional_heatequation.py","file_name":"one_dimensional_heatequation.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"507973430","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nfrom numpy import savez_compressed\nfrom tqdm import tqdm_notebook as tqdm\nfrom numpy import load\n\nsize = (180,120)\n\ndef save_tarin_images_as_list(train_files, images_path, y_dict, size):\n data_list = list()\n label_list = list()\n for file in tqdm(train_files):\n path = images_path + file\n pixels = load_img(path, target_size= size)\n pixels = img_to_array(pixels)\n data_list.append(pixels)\n label_list.append(y_dict[file.split(\".\")[0]])\n return [data_list,label_list]\n\nimages_path = \"./images/\"\nfiles = os.listdir(images_path)\n\ntrain_files = [i for i in files if \"Train\" in i]\n\ntrain_df = pd.read_csv(\"train.csv\")\n\nprint(\"Total: \", len(train_df))\nprint(\"Healthy: \",len(train_df[train_df[\"healthy\"] == 1]))\nprint(\"Diseased: \",len(train_df[train_df[\"healthy\"] == 0]))\n\ny_dict = train_df.set_index('image_id')['healthy'].to_dict()\n\ndata = save_tarin_images_as_list(train_files, images_path, y_dict, size)\n\nX = data[0]\ny = data[1]\n\nfilename = 'PestData_Train.npz'\nsavez_compressed(filename, X, np.array([[i] for i in y]))\nprint('Saved dataset: ', filename)\n","sub_path":"Make_data.py","file_name":"Make_data.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"437797925","text":"import os\n\ndef doWork(file, lineEnding):\n print(file)\n fileObj = open(file, \"rb\")\n fileText = fileObj.read()\n current = 0;\n new = 0;\n\n if lineEnding is \"CRLF\":\n new = b\"\\r\\n\"\n elif lineEnding is \"CR\":\n new = b\"\\r\"\n elif lineEnding is \"LF\":\n new = b\"\\n\"\n \n if fileText.find(b\"\\r\\n\") >= 0:\n current = b\"\\r\\n\"\n elif fileText.find(b\"\\r\") >= 0:\n current = b\"\\r\"\n elif fileText.find(b\"\\n\") >= 0:\n current = b\"\\n\"\n\n fileObj.close()\n if current != 0:\n\n print(current)\n print(new)\n newText = fileText.replace(current, new)\n\n fileObj = open(file, \"wb\")\n fileObj.write(newText)\n fileObj.close()\n\ndef Run(fileType, lineEnding):\n entries = os.listdir()\n for filename in entries:\n if filename.find(\".\") >= 0:\n array = filename.split(\".\")\n if(array[1] == fileType):\n doWork(filename, lineEnding)\n\nRun(\"h\", \"CRLF\")\nRun(\"cpp\", \"CRLF\")\ninput('Done!')\n","sub_path":"Frameworks/OpenGL Framework/data/source/ClassCreatorTool/pyLineEndings.py","file_name":"pyLineEndings.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"197253392","text":"import math\nfrom settings import *\nfrom app.utils import *\nfrom app.container import Container\nfrom app.cell import Cell\nfrom app.room import Room\nfrom .entity import Entity\n\n\nclass Grid(Entity):\n \"\"\" Represent the grid that contains rooms and cells \"\"\"\n\n def __init__(self):\n self.object = type(self).__name__\n Container.add_children('grid', self)\n self.w = SIZE['LAYOUT']['W']\n self.h = SIZE['LAYOUT']['H']\n self.matrix = self.load_matrix()\n self.rooms = []\n\n @property\n def columns_nb(self):\n return math.floor(self.w / SIZE['CELL']['W'])\n\n @property\n def lines_nb(self):\n return math.floor(self.h / SIZE['CELL']['H'])\n\n @property\n def cells_nb(self):\n return self.columns_nb * self.lines_nb\n\n @property\n def first_empty_cell(self):\n cell_id = sorted(self.empty_cells_list)[0]\n return self.get_cell(get_pos(cell_id)[0], get_pos(cell_id)[1])\n\n @property\n def empty_cells(self):\n empty_cells = []\n for line in range(0, self.lines_nb):\n for col in range(0, self.columns_nb):\n if self.matrix[line][col].char == CHAR['EMPTY']:\n empty_cells.append(self.matrix[line][col])\n return empty_cells\n\n @property\n def empty_cells_list(self):\n return [cell.id for cell in self.empty_cells]\n\n @property\n def rooms_nb(self):\n return len(self.rooms)\n\n def load_matrix(self):\n matrix = {}\n for line in range(0, self.lines_nb):\n matrix[line] = {}\n for col in range(0, self.columns_nb):\n matrix[line][col] = Cell(col, line)\n return matrix\n\n def get_cell(self, cx, cy):\n if cx <= self.columns_nb and cx >= 0 and cy <= self.lines_nb and cy >= 0:\n return self.matrix[cy][cx]\n return None\n\n def add_room(self, cells):\n assert (int(cells) >= SIZE['MIN_ROOM_CELLS'])\n assert (int(cells) <= SIZE['MAX_ROOM_CELLS'])\n assert (int(cells) % 2 == 0)\n cell = self.first_empty_cell\n room = Room(cell.cx, cell.cy, cells)\n self.rooms.append(room)\n return room\n\n def get_room(self, room_id):\n for room in self.rooms:\n if room_id == room.id:\n return room\n","sub_path":"app/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"625387330","text":"import urllib2\nimport os\n \n#Openin the CS department page.\n\nreq = urllib2.Request(url=\"http://www.iitkgp.ac.in/department/CS\")\n\n#Creating a directory for storing the faculty HTML files.\n\nos.mkdir('facultyInfo2')\n\nfor line in urllib2.urlopen(req).readlines():\n\tif \"/department/CS/faculty/cs\" in line:\n\n\t\t#Getting the faculty HTML page.\n\t\t\n\t\tlink = line[line.find(\"href=\") + 6 : line.find(\";\")]\n\t\treq = urllib2.Request(url = 'http://www.iitkgp.ac.in' + link)\n\n\t\t#Storing the page in an HTML file.\n\n\t\tf = open('facultyInfo2/' + 'cs-' + link.split(';')[0].split('-')[1] + '.html', \"w\")\n\t\tf.write(urllib2.urlopen(req).read())\n\n\t\t#Closing the file.\n\n\t\tf.close()","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"536908021","text":"##################################################################################################\n# This is a flask application that provides api end points for the weather data in Hawaii\n# The home page specifies various end points. The end points returns a json response of the \n# requested data as per the endpoint url. All the data is taken from the SQLite database\n# \"hawaii.sqlite\" in the Resources folder.\n##################################################################################################\n\n# import dependencies\nfrom flask import Flask, jsonify\nimport datetime as dt\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nStations = Base.classes.stations\nMeasurements = Base.classes.measurements\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\n# Initializing the Flask app\napp = Flask(__name__)\n\n#################################################\n# Flask Routes\n#################################################\n\n# This is the home page of the application. It will list all the valid end points\n@app.route(\"/\")\ndef home():\n print(\"Server received request for 'Home' page...\")\n text = \"Welcome to the Surf API page!
\\\n Below are some of the api endpoints that you can use to get the weather data for Hawaii:
\\\n * /api/v1.0/precipitation - To get the precipitation data for the last year
\\\n * /api/v1.0/temperature - To get the temperature data for the last year
\\\n * /api/v1.0/stations - To get the stations list
\\\n * /api/v1.0/start-date - To get the min, max and avg temperatures for all days starting the specified date
\\\n * /api/v1.0/start-date/end-date - To get the min, max and avg temperatures for all days between the specified dates\"\n return text\n\n# This end point lists all the precipitation data for all the days for the last year i.e. starting a year ago\n@app.route(\"/api/v1.0/precipitation\")\ndef get_precipitation():\n\n # server logging\n print(\"Server received request for precipitation page...\")\n\n prev_year_date = dt.date.today() - dt.timedelta(days=365)\n\n # query precipitation data for the previous year\n results = session.query(Measurements.station_id, Measurements.date, Measurements.precipitation).\\\n filter(Measurements.date >= prev_year_date).\\\n order_by(Measurements.date)\n\n precipitation_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n p_dict = {}\n\n p_dict[\"date\"]=row.date \n p_dict[\"station_id\"]=row.station_id\n p_dict[\"precipitation\"]=row.precipitation\n precipitation_data.append(p_dict)\n\n # return the json representation of the data\n return jsonify(precipitation_data)\n\n# This end point lists all the temperature data for all the days for the last year i.e. starting a year ago\n@app.route(\"/api/v1.0/temperature\")\ndef get_temperature():\n\n # server logging\n print(\"Server received request for temperature page...\")\n\n prev_year_date = dt.date.today() - dt.timedelta(days=365)\n\n # query temperature data for the previous year\n results = session.query(Measurements.station_id, Measurements.date, Measurements.temperature).\\\n filter(Measurements.date >= prev_year_date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n\n t_dict[\"date\"]=row.date \n t_dict[\"station_id\"]=row.station_id\n t_dict[\"temperature\"]=row.temperature\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n# This end point lists all the station data\n@app.route(\"/api/v1.0/stations\")\ndef get_stations():\n\n # server logging\n print(\"Server received request for stations page...\")\n\n results = session.query(Stations).all()\n \n # Create a dictionary from the row data and append to a list of stations\n all_stations = []\n\n for station in results:\n station_dict = {}\n\n station_dict[\"station_id\"] = station.station_id\n station_dict[\"station_name\"] = station.station_name\n station_dict[\"latitude\"] = station.latitude\n station_dict[\"longitude\"] = station.longitude\n station_dict[\"elevation\"] = station.elevation\n all_stations.append(station_dict)\n\n # return the json representation of the data\n return jsonify(all_stations)\n\n# This end point lists the min, max and avg temperatures for all days starting \n# from the start date specified in the end point\n@app.route(\"/api/v1.0/\")\ndef get_weather_start(start):\n\n # server logging\n print(\"Server received request for start page...\")\n \n try:\n start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()\n except:\n return \"Invalid endpoint value: {}
Please enter start date in the format YYYY-MM-DD\".format(start)\n \n results = session.query(Measurements.date, func.min(Measurements.temperature).label(\"tmin\"), \\\n func.max(Measurements.temperature).label(\"tmax\"), \\\n func.avg(Measurements.temperature).label(\"tavg\")).\\\n filter(Measurements.date >= start_date).\\\n group_by(Measurements.date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n\n t_dict[\"date\"]=row.date \n t_dict[\"min temperature\"]=row.tmin\n t_dict[\"max temperature\"]=row.tmax\n t_dict[\"avg temperature\"]=round(row.tavg,2)\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n# This end point lists the min, max and avg temperatures for all days \n# between the start date and end date specified in the end point\n@app.route(\"/api/v1.0//\")\ndef get_weather_start_end(start, end):\n\n # server logging\n print(\"Server received request for start-end page...\")\n try:\n start_date = dt.datetime.strptime(start, '%Y-%m-%d').date()\n end_date = dt.datetime.strptime(end, '%Y-%m-%d').date()\n except:\n return \"Invalid endpoint value: {}/{}
Please enter start and end dates in the format YYYY-MM-DD\".format(start, end)\n \n results = session.query(Measurements.date, func.min(Measurements.temperature).label(\"tmin\"), \\\n func.max(Measurements.temperature).label(\"tmax\"), \\\n func.avg(Measurements.temperature).label(\"tavg\")).\\\n filter(Measurements.date >= start_date).\\\n filter(Measurements.date <= end_date).\\\n group_by(Measurements.date).\\\n order_by(Measurements.date)\n\n temp_data = []\n\n # Create a list of dictionaries to represent the data\n for row in results:\n t_dict = {}\n \n t_dict[\"date\"]=row.date \n t_dict[\"min temperature\"]=row.tmin\n t_dict[\"max temperature\"]=row.tmax\n t_dict[\"avg temperature\"]=round(row.tavg,2)\n temp_data.append(t_dict)\n\n # return the json representation of the data\n return jsonify(temp_data)\n\n\n#################################################\n# Flask Run App\n#################################################\nif __name__ == \"__main__\":\n # Run the app\n app.run(debug=True)","sub_path":"surf/surf_api.py","file_name":"surf_api.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"5842487","text":"import datetime\nimport os\nfrom urllib.parse import urlparse\n\nimport pytest\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.conf import settings\n\nfrom peterbecom.plog.models import BlogItem, BlogComment, Category\n\n\n@pytest.mark.django_db\ndef test_homepage_cache_rendering(client, tmpfscacheroot):\n url = reverse(\"home\")\n\n blog1 = BlogItem.objects.create(\n title=\"TITLE1\",\n text=\"BLABLABLA\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=10),\n )\n BlogComment.objects.create(\n oid=\"c1\", comment=\"textext\", blogitem=blog1, approved=True\n )\n\n BlogComment.objects.create(\n oid=\"c2\", comment=\"tuxtuxt\", blogitem=blog1, approved=True\n )\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TITLE1\" in content\n assert \"2 comments\" in content\n\n blog1.title = \"TUTLE1\"\n blog1.save()\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TUTLE1\" in content\n\n blog2 = BlogItem.objects.create(\n oid=\"t2\",\n title=\"TATLE2\",\n text=\"BLEBLE\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=1),\n )\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"TATLE2\" in content\n assert \"0 comments\" in content\n assert \"TUTLE1\" in content\n assert \"2 comments\" in content\n\n # by categories only\n cat1 = Category.objects.create(name=\"CATEGORY1\")\n cat2 = Category.objects.create(name=\"CATEGORY2\")\n blog1.categories.add(cat1)\n blog1.save()\n blog2.categories.add(cat2)\n blog2.save()\n\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" in content\n assert \"CATEGORY2\" in content\n\n url = reverse(\"only_category\", args=[\"CATEGORY2\"])\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" not in content\n assert \"CATEGORY2\" in content\n\n url = reverse(\"only_category\", args=[\"CATEGORY1\"])\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"CATEGORY1\" in content\n assert \"CATEGORY2\" not in content\n\n bulk = []\n for i in range(2, 21):\n bulk.append(\n BlogItem(\n oid=\"t-{}\".format(i),\n title=\"TITLE-{}\".format(i),\n text=\"BLEBLE\",\n display_format=\"structuredtext\",\n pub_date=timezone.now() - datetime.timedelta(seconds=20 + i),\n )\n )\n BlogItem.objects.bulk_create(bulk)\n\n url = reverse(\"home\")\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n assert \"/p2\" in content\n visible_titles = []\n not_visible_titles = []\n for item in BlogItem.objects.all():\n if item.title in content:\n visible_titles.append(item.title)\n else:\n not_visible_titles.append(item.title)\n\n url = reverse(\"home_paged\", args=(2,))\n response = client.get(url)\n content = response.content.decode(\"utf-8\")\n batch_size = settings.HOMEPAGE_BATCH_SIZE\n for each in visible_titles[:batch_size]:\n assert each not in content\n for each in not_visible_titles[:batch_size]:\n assert each in content\n assert \"/p3\" in content\n\n\n@pytest.mark.django_db\ndef test_about_page_fs_cached(client, tmpfscacheroot):\n fs_path = os.path.join(tmpfscacheroot, \"about\", \"index.html\")\n assert not os.path.isfile(fs_path)\n url = reverse(\"about\")\n response = client.get(url)\n assert response.status_code == 200\n assert os.path.isfile(fs_path)\n\n\n@pytest.mark.django_db\ndef test_about_page_with_newline_request_path(client, tmpfscacheroot):\n url = reverse(\"about\")\n response = client.get(url + \"\\n\")\n assert response.status_code == 301\n assert urlparse(response[\"location\"]).path == url\n","sub_path":"peterbecom/homepage/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"284248373","text":"from __future__ import print_function\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchsummary import summary\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\ndef getTransformer():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n return transform\n\ndef trainset():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n return trainset\n\ndef testset():\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n return testset\n\ndef getclasses():\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n return classes\n\n\n\n# functions to show an image\n\n\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n\n\n# get some random training images\n\n#trainset = trainset()\n#testset = testset()\n#trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n# shuffle=True, num_workers=2)\n#testloader = torch.utils.data.DataLoader(testset, batch_size=4,\n# shuffle=False, num_workers=2)\n\n#dataiter = iter(trainloader)\n#images, labels = dataiter.next()\n\n# show images\n#imshow(torchvision.utils.make_grid(images))\n# print labels\n#classes = getclasses()\n#print(' '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n\ndropout_value = 0.1\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # Input Block\n self.convblock1 = nn.Sequential(\n nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=2, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=2, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 36 , RF= 5*5\n\n self.pool1 = nn.MaxPool2d(2, 2) # output_size = 18, RF= 6*6\n\n # CONVOLUTION BLOCK 1\n self.convblock2 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=2, groups=128 , bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 20 , RF= 14*14\n self.pool2 = nn.MaxPool2d(2, 2) # output_size = 10, RF= 16*16\n \n # CONVOLUTION BLOCK 2\n self.convblock3 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=3, dilation = 3, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=256, out_channels=10, kernel_size=3, padding=2, bias=False),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout_value)\n ) # output_size = 12, RF= 48*48\n self.pool3 = nn.MaxPool2d(2, 2) # output_size = 6, RF= 56*56\n \n # OUTPUT BLOCK\n self.gap = nn.Sequential(\n nn.AvgPool2d(kernel_size=4)\n ) # output_size = 1\n\n self.convblock5 = nn.Sequential(\n nn.Conv2d(in_channels=10, out_channels=10, kernel_size=(1, 1), padding=0, bias=False),\n ) \n\n\n self.dropout = nn.Dropout(dropout_value)\n\n def forward(self, x):\n x = self.convblock1(x)\n x = self.pool1(x)\n x = self.convblock2(x)\n x = self.pool2(x)\n x = self.convblock3(x)\n x = self.pool3(x)\n #print(x.shape) \n x = self.gap(x) \n x = self.convblock5(x)\n \n x = x.view(-1, 10)\n return F.log_softmax(x, dim=-1)\n\ndef getDevice():\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n return device\n\n\n\ndef getOptimizer():\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n return optimizer\n\n\n\ndef testImages(testloader):\n dataiter = iter(testloader)\n images, labels = dataiter.next()\n\n# print images\n imshow(torchvision.utils.make_grid(images))\n print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))\n return images\n\n","sub_path":"Session7/CNNNetUtility.py","file_name":"CNNNetUtility.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"336660252","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 14 16:27:14 2022\n\n@author: bdobson\n\"\"\"\n\nfrom wsimod.nodes.nodes import Node\nfrom wsimod.core import constants \n\ndef decorate_leakage_set(self, f):\n \"\"\"Decorator to extend the functionality of `f` by introducing leakage. \n This is achieved by adjusting the volume of the request (vqip) to include\n anticipated leakage, calling the original function `f`, and then \n distributing the leaked amount to groundwater.\n\n Args:\n self (instance of Distribution class): The Distribution object to be \n extended\n f (function): The function to be extended. Expected to be the \n Distribution object's pull_set function.\n\n Returns:\n pull_set (function): The decorated function which includes the \n original functionality of `f` and additional leakage operations.\n \"\"\"\n def pull_set(vqip, **kwargs):\n vqip['volume'] /= (1 - self.leakage)\n \n reply = f(vqip, **kwargs)\n \n amount_leaked = self.v_change_vqip(reply, \n reply['volume'] * self.leakage)\n \n reply = self.extract_vqip(reply, amount_leaked)\n \n unsuccessful_leakage = self.push_distributed(amount_leaked, of_type = 'Groundwater')\n if unsuccessful_leakage['volume'] > constants.FLOAT_ACCURACY:\n print('warning, distribution leakage not going to GW in {0} at {1}'.format(self.name, self.t))\n reply = self.sum_vqip(reply, unsuccessful_leakage)\n \n return reply\n return pull_set\n \ndef decorate_leakage_check(self, f):\n \"\"\"Decorator to extend the functionality of `f` by introducing leakage. \n This is achieved by adjusting the volume of the request (vqip) to include\n anticipated leakage and then calling the original function `f`.\n\n Args:\n self (instance of Distribution class): The Distribution object to be \n extended\n f (function): The function to be extended. Expected to be the \n Distribution object's pull_set function.\n\n Returns:\n pull_check (function): The decorated function which includes the \n original functionality of `f` and additional leakage operations.\n \"\"\"\n def pull_check(vqip, **kwargs):\n if vqip is not None:\n vqip['volume'] /= (1 - self.leakage)\n reply = f(vqip, **kwargs)\n amount_leaked = self.v_change_vqip(reply, \n reply['volume'] * self.leakage)\n \n reply = self.extract_vqip(reply, amount_leaked)\n return reply\n return pull_check\n\nclass Distribution(Node):\n def __init__(self, leakage = 0, **kwargs):\n \"\"\"A Node that cannot be pushed to. Intended to pass calls to FWTW - \n though this currently relies on the user to connect it properly\n \n Args:\n leakage (float, optional): 1 > float >= 0 to express how much \n water should be leaked to any attached groundwater nodes. This\n number represents the proportion of total flow through the node\n that should be leaked. \n Defaults to 0.\n \n Functions intended to call in orchestration:\n None\n \n Key assumptions:\n - No distribution processes yet represented, this class is just \n for conveyance.\n \n Input data and parameter requirements:\n - None\n \"\"\"\n self.leakage = leakage\n super().__init__(**kwargs)\n #Update handlers \n self.push_set_handler['default'] = self.push_set_deny\n self.push_check_handler['default'] = self.push_check_deny\n \n if leakage > 0:\n self.pull_set_handler['default'] = decorate_leakage_set(self, \n self.pull_set_handler['default'])\n self.pull_check_handler['default'] = decorate_leakage_check(self, \n self.pull_check_handler['default'])\n \nclass UnlimitedDistribution(Distribution):\n def __init__(self,**kwargs):\n \"\"\"A distribution node that provides unlimited water while tracking pass \n balance\n\n Functions intended to call in orchestration:\n None\n \n Key assumptions:\n - Water demand is always satisfied.\n \n Input data and parameter requirements:\n - None\n \"\"\"\n super().__init__(**kwargs)\n #Update handlers \n self.pull_set_handler['default'] = self.pull_set_unlimited\n self.pull_check_handler['default'] = lambda x : self.v_change_vqip(self.empty_vqip(), constants.UNBOUNDED_CAPACITY)\n \n #States\n self.supplied = self.empty_vqip()\n \n self.mass_balance_in.append(lambda : self.supplied)\n \n def pull_set_unlimited(self, vqip):\n \"\"\"Respond that VQIP was fulfilled and update state variables for mass balance\n\n Args:\n vqip (dict): A VQIP amount to request\n\n Returns:\n vqip (dict): A VQIP amount that was supplied\n \"\"\"\n #TODO maybe need some pollutant concentrations?\n vqip = self.v_change_vqip(self.empty_vqip(), vqip['volume'])\n self.supplied = self.sum_vqip(self.supplied, vqip)\n return vqip\n \n def end_timestep(self):\n \"\"\"Update state variables\n \"\"\"\n self.supplied = self.empty_vqip()","sub_path":"wsimod/nodes/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"150754925","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.index, name='index'),\n path('about', views.about, name='about'),\n path('menu', views.menu, name='menu'),\n path('login', views.login, name='login'),\n path('register', views.register, name='register'),\n path('cart', views.cart, name='cart'),\n path('settings', views.settings, name='settings'),\n path('user_orders', views.user_orders, name='user_orders'),\n path('order', views.order, name='order'),\n path('no_js', views.no_js, name='no_js'),\n path('cookie_disabled', views.cookie_disabled, name='cookie_disabled'),\n path('logout', views.logout, name='logout'),\n path('confirm_account/',\n views.confirm_account, name='confirm_account'),\n path('update_cart', views.update_cart, name='update_cart'),\n path('change_email', views.change_email, name='change_email'),\n path('confirm_email_change/',\n views.confirm_email_change, name='confirm_email_change'),\n path('change_password', views.change_password, name='change_password'),\n]\n","sub_path":"core_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"289519102","text":"from keras.models import Model\nimport numpy as np\nimport gzip, struct, random\nfrom keras.models import load_model\nimport matplotlib.pylab as plt\nfrom keras.utils import to_categorical\n\n# load the data from the files\n\nwith gzip.open('t10k-labels-idx1-ubyte.gz') as f:\n magic, num = struct.unpack(\">II\", f.read(8))\n test_labels = np.fromstring(f.read(), dtype=np.int8)\n\nwith gzip.open('t10k-images-idx3-ubyte.gz') as f:\n magic, num, rows, cols = struct.unpack(\">IIII\", f.read(16))\n test_images = np.fromstring(f.read(), dtype=np.uint8).reshape(num, rows, cols, 1)\n\n# Normalize and encode the labeling of data set\ntest_labels_encoded = to_categorical(test_labels)\ntest_images = test_images / 255\nn = int(len(test_images) / 2)\nX_valid, y_valid = test_images[:n], test_labels_encoded[:n]\nX_test, y_test = test_images[n:], test_labels_encoded[n:]\n\n# load the model form the saved model\ncnn_model = load_model('my_model.h5')\n\n\n# Evaluate the model\ncnn_scores = cnn_model.evaluate(X_test, y_test, verbose=0)\n\nprint(\"CNN Scores: \", (cnn_scores))\nprint(\"CNN Error: %.2f%%\" % (100 - cnn_scores[1] * 100))\n\nplt.figure(figsize=(14, 5))\nplt.plot(cnn_history.history['categorical_accuracy'][3:], '-o', label='train')\nplt.plot(cnn_history.history['val_categorical_accuracy'][3:], '-o', label='test')\nplt.legend()\nplt.title('CNN Accuracy');\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"600832038","text":"import compute\nimport pyopencl\nimport numpy\n\nclass Stimuli:\n def __init__(self, cs = None, numStimulus=None):\n if not isinstance(cs, compute.ComputeSystem):\n raise ValueError(\"[stimuli] Expected cs to be of type: {}, but got: {}\".format(type(ComputeSystem), type(cs)))\n self.cs = cs\n\n if not isinstance(numStimulus, int):\n raise ValueError(\"[Stimuli] Expected numStimulus to be of type {} but got: {}\".format(type(int), type(numStimulus)))\n self.numS = numStimulus\n\n self._numbytesSStates = numpy.uint32().nbytes * self.numS\n\n self.bufferSStates = pyopencl.Buffer(cs.getContext(), pyopencl.mem_flags.READ_WRITE, size=self._numbytesSStates)\n\n self.clearStates()\n\n def clearStates(self):\n pyopencl.enqueue_fill_buffer(self.cs.getQueue(), self.bufferSStates, numpy.uint32(0), 0, self._numbytesSStates)\n\n def setStates(self, states = []):\n pyopencl.enqueue_copy(self.cs.getQueue(), self.bufferSStates, states)\n #pyopencl.enqueue_write_buffer(self.cs.getQueue(), self.bufferSStates, numpy.uint32(0), self._numbytesSStates, states)\n\n def getStates(self):\n vecStates = None\n pyopencl.enqueue_read_buffer(self.cs.getQueue(), True, 0, self._numbytesSStates, vecStates)\n return vecStates\n\n def printStates(self):\n vecStates = None\n pyopencl.enqueue_read_buffer(self.cs.getQueue(), True, 0, self._numbytesSStates, vecStates)\n for i in xrange(self.numS):\n print(\"{} \".format(vecStates[i]))\n\nif __name__ == \"__main__\":\n cs = compute.ComputeSystem(devicetype=compute.GPU)\n s = Stimuli(cs=cs, numStimulus=4)\n","sub_path":"htm/cortex/stimuli.py","file_name":"stimuli.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"316475498","text":"# Exercise 17: More Files\n\n# -*- coding: utf-8 -*-\n\nfrom os.path import exists\nfrom sys import argv\n\nscript, from_file, to_file = argv\n\nprint(\"Copying from %s to %s\" % (from_file, to_file))\n\n# we could do these two on one line too, how?\nin_file = open(from_file)\nin_data = in_file.read()\n# in_data = open(from_file).read()\n\nprint(\"The input file is %d bytes long\" % len(in_data))\n\nprint(\"Does the output file exist? %r\" % exists(to_file))\nprint(\"Ready, hit RETURN to continue, CTRL-C to abort.\")\ninput()\n\nout_file = open(to_file, 'w')\nout_file.write(in_data)\n\nprint(\"Alright, all done.\")\n# open(to_file, 'w').write(open(from_file).read())\nout_file.close()\nin_file.close()\n","sub_path":"ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"32212510","text":"def hcf(x,y):\n if x>y:\n small=y\n else:\n small=x\n for i in range(1,small+1):\n if x%i==0 and y%i==0:\n re=i\n return re\n\ns=list(input())\ns.remove(\"[\")\ns.remove(\"]\")\ns=\"\".join(s)\ncard=sorted(s.split(\",\"))\nnum=[]\ntemp=1\nfor i in range(0,len(card)-1):\n if card[i]==card[i+1]:\n temp+=1\n else:\n num.append(temp)\n temp=1\n if i==len(card)-1:\n num.append(temp)\nnum=sorted(num)\nif max(num)<2:\n print(False)\nelif len(num)==1:\n print(True)\nelse:\n temp=hcf(num[0],num[1])\n for i in range(2,len(num)):\n temp=hcf(temp,num[i])\n if temp<2:\n print(False)\n else:\n print(True)","sub_path":"Code/CodeRecords/2325/60787/245021.py","file_name":"245021.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"559054824","text":"import cv2\nimport numpy as np\nfrom lailib.image.resize import resize_height_keep_ratio\nfrom math import sin, cos, ceil, pi\nfrom skimage import morphology\nfrom PIL import ImageFont, ImageDraw, Image\nimport os\nimport math\nimport random\nfrom skimage.filters import threshold_sauvola\nfrom scipy.ndimage import interpolation\nimport pdb\n\n\ndef savola(img):\n thresh_sauvola = threshold_sauvola(img, window_size=25)\n binary_sauvola = img > thresh_sauvola\n ret_sauvola = binary_sauvola.astype(np.uint8) * 255\n return ret_sauvola\n\n\ndef otsu_thresh(im):\n '''\n binarize image with otsu algorithm\n :param im: uint8 numpy array\n :return: binarized image as uint8 numpy array\n '''\n to_binarize = np.copy(np.uint8(im))\n ret2, th2 = cv2.threshold(to_binarize, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n return th2\n\n\ndef hor_crop(im, binarized):\n '''\n\n crop image only on horizontal direction\n\n Args:\n im: uint8ndarray\n input image to be cropped\n binarized: uint8ndarray\n binarized version of im,\n at least this binarized image should have\n the same shape as im\n Returns:\n cropped image\n '''\n\n row_sums = np.sum(binarized, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n\n cropped = im[:, col_start:col_end]\n\n return cropped\n\n\ndef resize_on_long_aixs(full_im, cropped_im):\n full_h, full_w = full_im.shape\n cropped_h, cropped_w = cropped_im.shape\n full_ratio = full_h / full_w\n cropped_ratio = cropped_h / cropped_w\n if full_ratio > cropped_ratio:\n # based on w\n cropped_im = cv2.resize(cropped_im, (full_w, int(full_w / cropped_w * cropped_h)))\n else:\n # based on h\n cropped_im = cv2.resize(cropped_im, (int(full_h / cropped_h * cropped_w), full_h))\n return cropped_im\n\n\ndef resize_image(image_cv, new_height, **kwargs):\n '''\n resize image with given height, keep ratio\n :param image_cv: image to be resized\n :param new_height: new height of the output image\n :param inte_method: interpolation method\n :return: resized image\n '''\n (height, width) = image_cv.shape\n new_width = int(float(width) * new_height / float(height))\n image_cv = cv2.resize(image_cv, (new_width, new_height), **kwargs)\n return image_cv\n\n\ndef crop_and_padding(image_cv, padding=0, new_height=None, binarized=False):\n '''\n crop and padding an image, may resize image to a height\n :param image_cv: input image, uint8 numpy array, assumed to be gray scale\n (if binarized set to true, image will be kept binarized)\n :param padding: padding to each side\n :param new_height: new_height of image if required\n :return: cropped and potentially padded and resized image (uint8)\n '''\n col_sums = np.sum(image_cv, axis=1)\n row_start = np.where(col_sums)[0][0]\n rev_col_sum = np.flip(col_sums, axis=0)\n rev_end = np.where(rev_col_sum)[0][0]\n row_end = col_sums.shape[0] - rev_end\n\n row_sums = np.sum(image_cv, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n\n cropped = image_cv[row_start:row_end, col_start:col_end]\n\n # TODO add rand noise to height\n if new_height:\n cropped = resize_image(cropped, new_height)\n if binarized:\n ret2, cropped = cv2.threshold(cropped, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n height, width = cropped.shape\n final_out = cropped\n if padding:\n final_out = np.zeros((height + 2 * padding, width + 2 * padding))\n final_out[padding:-padding, padding:-padding] = cropped\n return final_out\n\n\ndef process_thin_img(im):\n kernel = np.ones((3, 3), np.uint8)\n im = np.pad(im, ((3, 3), (3, 3)), 'maximum')\n im = 255 - ((255 - im) * 0.8).astype(np.uint8)\n im = cv2.erode(im, kernel, iterations=10)\n im = blur_image(im)\n return im\n\n\ndef blur_image(im):\n kernel = np.ones((5, 5), np.float32) / 25\n dst = cv2.filter2D(im, -1, kernel)\n return dst\n\n\ndef flip_tuple(coord):\n return (coord[1], coord[0])\n\n\ndef erode_plus(orig_img, target_thickness=2):\n orig_img = otsu_thresh(orig_img)\n orig_img = 255 - orig_img\n orig_img_copy = orig_img.copy()\n element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n skel = morphology.skeletonize(orig_img > 0)\n erode_baseline = None\n thickness = 0\n\n while True:\n # does not support 0 or 1 thickness yet\n thickness += 1\n orig_sum = np.sum(orig_img > 0)\n # erode but keep skel\n orig_img = cv2.dilate(orig_img, element, iterations=1)\n orig_img = cv2.erode(orig_img, element, iterations=2)\n orig_img = cv2.bitwise_or(np.array(skel, dtype=np.uint8) * 255, orig_img)\n # calcualte erode rate, if too little, it means it's almost skel already\n erode_rate = orig_sum - np.sum(orig_img > 0)\n if erode_baseline is None:\n erode_baseline = erode_rate\n else:\n if (erode_rate < erode_baseline / 2) or (erode_rate < 10):\n break\n # print(thickness)\n orig_img = orig_img_copy.copy()\n if thickness - target_thickness + 1 < 0:\n return orig_img, thickness\n # raise NotImplementedError(\"wait\")\n # print(thickness - target_thickness + 1)\n for i in range(thickness - target_thickness + 1):\n orig_img = cv2.dilate(orig_img, element, iterations=1)\n orig_img = cv2.erode(orig_img, element, iterations=2)\n orig_img = cv2.bitwise_or(np.array(skel, dtype=np.uint8) * 255, orig_img)\n # orig_img = blur_image(255 - orig_img)\n orig_img = 255 - orig_img\n return orig_img, thickness\n\n\ndef fix_lr_boundary(image_cv, padding=15):\n '''\n fix left and right padding for an image\n :param image_cv: input image, uint8 numpy array, assumed to be gray scale\n (if binarized set to true, image will be kept binarized)\n :return: cropped and potentially padded and resized image (uint8)\n '''\n up_padding = 10\n down_padding = 15\n _, binarized = cv2.threshold(image_cv, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n im_h, im_w = image_cv.shape\n col_sums = np.sum(binarized, axis=1)\n row_start = np.where(col_sums)[0][0]\n rev_col_sum = np.flip(col_sums, axis=0)\n rev_end = np.where(rev_col_sum)[0][0]\n row_end = col_sums.shape[0] - rev_end\n row_sums = np.sum(binarized, axis=0)\n col_start = np.where(row_sums)[0][0]\n rev_row_sum = np.flip(row_sums, axis=0)\n rev_end = np.where(rev_row_sum)[0][0]\n col_end = row_sums.shape[0] - rev_end\n if (row_end - row_start) > 0.3 * im_h:\n cropped = image_cv[row_start:row_end, col_start:col_end]\n else:\n cropped = image_cv[:, col_start:col_end]\n height, width = cropped.shape\n rel_up_padding = ceil(up_padding * height / 75)\n rel_down_padding = ceil(down_padding * height / 75)\n rel_lr_padding = ceil(padding * height / 75)\n final_out = cropped\n if padding:\n if (row_end - row_start) > 0.3 * im_h:\n final_out = np.zeros((height + rel_up_padding + rel_down_padding, width + 2 * rel_lr_padding))\n final_out[rel_up_padding:-rel_down_padding, rel_lr_padding:-rel_lr_padding] = cropped\n else:\n final_out = np.zeros((height, width + 2 * rel_lr_padding))\n final_out[:, rel_lr_padding:-rel_lr_padding] = cropped\n return final_out\n\n\ndef estimate_skew_angle(image, angles):\n \"\"\"estimate skew angle \"\"\"\n estimates = []\n for a in angles:\n v = np.mean(interpolation.rotate(image, a, order=0, mode='constant'), axis=1)\n v = np.var(v)\n estimates.append((v, a))\n _, a = max(estimates)\n return a\n\n\ndef estimate_skew(flat, bignore, maxskew, skewsteps):\n ''' estimate skew angle and rotate'''\n d0, d1 = flat.shape\n o0, o1 = int(bignore * d0), int(bignore * d1)\n flat = 1 - flat\n est = flat[o0:d0 - o0, o1:d1 - o1]\n ma = maxskew\n ms = int(2 * maxskew * skewsteps)\n angle = estimate_skew_angle(est, np.linspace(-ma, ma, ms + 1))\n flat = interpolation.rotate(flat, angle, mode='constant', reshape=0)\n flat[flat < 0] = 0.\n flat = 1 - flat\n return flat, angle\n\n\ndef deskew(image):\n bignore = 0.1\n maxskew = 2\n skewsteps = 8\n image = image.copy() / 255.0\n image, angle = estimate_skew(image, bignore, maxskew, skewsteps)\n return (image * 255).astype(np.uint8)\n\n\ndef pad2square(im):\n h, w = im.shape\n if h > w:\n pad_w = h - w\n left_pad = pad_w // 2\n right_pad = pad_w - left_pad\n im = np.pad(im, ((0, 0), (left_pad, right_pad)), constant_values=((255, 255), (255, 255)))\n else:\n pad_h = w - h\n up_pad = pad_h // 2\n down_pad = pad_h - up_pad\n im = np.pad(im, ((up_pad, down_pad), (0, 0)), constant_values=((255, 255), (255, 255)))\n return im\n","sub_path":"src/util/image_util.py","file_name":"image_util.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"329654465","text":"import time\n\nfrom rammi import _\nfrom rammi.interface import DictableInstance\n\nimport settings\n\n\nclass Course(DictableInstance):\n _fields = (\n 'title',\n 'description',\n 'price',\n 'price_description',\n 'time_description',\n 'is_free',\n 'credits',\n 'link_source',\n 'link_registration',\n\n #\n # Keys:\n # job_title\n # name\n # website\n #\n 'teacher',\n\n #\n # Keys:\n # category_id: []\n #\n 'categories',\n\n #\n # List of dicts with keys:\n # epoch -- seconds since Jan 1, 1970\n # duration -- in seconds\n #\n 'schedules',\n\n 'user_id',\n 'epoch_created'\n )\n\n _required_fields = (\n 'title',\n 'description',\n 'price',\n 'credits',\n 'link_source',\n\n 'user_id'\n )\n\n teacher_default = lambda self: {}\n categories_default = lambda self: {}\n schedules_default = lambda self: []\n\n @property\n def categories_trans(self):\n result = {}\n\n for category_id, subcategories in self.categories.iteritems():\n result[category_id] = [_(subcategory) for subcategory in subcategories]\n\n return result\n\n def validate(self, *args, **kwargs):\n errors = super(Course, self).validate(*args, **kwargs)\n required_msg = _('%s is required')\n\n if not getattr(self, 'teacher', None):\n errors.append({\n 'field' : 'teacher',\n 'message': required_msg % 'teacher',\n })\n elif not self.teacher.get('name'):\n errors.append({\n 'field' : 'teacher.name',\n 'message': required_msg % 'teacher.name',\n })\n\n if getattr(self, 'is_free', None) is None:\n errors.append({\n 'field' : 'is_free',\n 'message': required_msg % 'is_free',\n })\n\n\n if not getattr(self, 'schedules', None):\n errors.append({\n 'field' : 'schedules',\n 'message' : required_msg % 'schedules',\n })\n\n if errors:\n errors.append({\n 'field' : None,\n 'message': _('Please Fill All Required Fields'),\n })\n\n return errors\n\n def to_dict(self, format=None, *args, **kwargs):\n result = super(Course, self).to_dict(*args, **kwargs)\n\n if format == 'ajax':\n result.update({\n 'categories_trans': self.categories_trans\n })\n\n # add date string in schedule\n for schedule in result.get('schedules', []):\n if 'datetime' not in schedule or 'duration' not in schedule:\n continue\n\n starttime = time.gmtime(schedule.get('datetime'))\n endtime = time.gmtime(schedule.get('datetime') + schedule.get('duration'))\n\n schedule.update({\n 'startdate_string': time.strftime(settings.FORMAT_DATE, starttime),\n 'starttime_string': time.strftime(settings.FORMAT_TIME, starttime),\n 'enddate_string' : time.strftime(settings.FORMAT_DATE, endtime),\n 'endtime_string' : time.strftime(settings.FORMAT_TIME, endtime),\n })\n\n\n return result\n\n\nclass CourseCategory(DictableInstance):\n _fields = (\n 'title',\n 'subcategories'\n )\n\n def get_translated_title(self):\n return _(self.title)\n\n def get_translated_subcategories(self):\n return [_(subcategory) for subcategory in self.subcategories]\n\n def to_dict(self, format=None, *args, **kwargs):\n result = super(CourseCategory, self).to_dict(*args, **kwargs)\n\n if format == 'ajax':\n result.update({\n 'title_trans': self.get_translated_title(),\n 'subcategories_trans': self.get_translated_subcategories()\n })\n\n return result\n","sub_path":"conted/courses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"532627251","text":"import cv2\nimport numpy as np\n\n\n# SIFT based correction - functions\n\ndef enhance(image, clip_limit=5):\n # convert image to LAB color model\n image_lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n\n # split the image into L, A, and B channels\n l_channel, a_channel, b_channel = cv2.split(image_lab)\n\n # apply CLAHE to lightness channel\n clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(8, 8))\n cl = clahe.apply(l_channel)\n\n # merge the CLAHE enhanced L channel with the original A and B channel\n merged_channels = cv2.merge((cl, a_channel, b_channel))\n\n # convert image from LAB color model back to RGB color model\n final_image = cv2.cvtColor(merged_channels, cv2.COLOR_LAB2BGR)\n return final_image \n\n\ndef find_matches_and_homography(imageL, imageR, MIN_MATCH_COUNT=11, GOOD_PERC=0.7, FLANN_INDEX_KDTREE=0):\n\n sift = cv2.KAZE_create()\n img1 = enhance(imageL)\n img2 = enhance(imageR)\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks = 50)\n\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n good = []\n for m,n in matches:\n if m.distance < GOOD_PERC*n.distance:\n good.append(m)\n if len(good)>=MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1, 1 ,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1, 1, 2)\n H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\n matchesMask = mask.ravel().tolist()\n else:\n print(\"Not enough matches are found - %d/%d\" % (len(good),MIN_MATCH_COUNT))\n matchesMask = None\n\n return good, matchesMask, H, kp1, kp2\n\n\ndef adjust_keypoints(keypoints, H):\n left_keypoints_crop = {item['keypointType']: [item['xCrop'], item['yCrop']] for item in keypoints['leftCrop']}\n right_keypoints_crop = {item['keypointType']: [item['xCrop'], item['yCrop']] for item in keypoints['rightCrop']}\n\n # adjust left and right keypoints\n left_keypoints_crop_adjusted, right_keypoints_crop_adjusted = [], []\n for i, bp in enumerate([item['keypointType'] for item in keypoints['leftCrop']]):\n kpL = left_keypoints_crop[bp]\n ptx = np.array([kpL[0], kpL[1], 1])\n zx = np.dot(H, ptx)\n kpL2R = [zx[0] / zx[2], zx[1] / zx[2]]\n\n kpR = right_keypoints_crop[bp]\n pty = np.array([kpR[0], kpR[1], 1])\n zy = np.dot(np.linalg.inv(H), pty)\n kpR2L = [zy[0] / zy[2], zy[1] / zy[2]]\n\n kpL_adjusted = [(kpL[0] + kpR2L[0]) / 2.0, (kpL[1] + kpR2L[1]) / 2.0]\n kpR_adjusted = [(kpR[0] + kpL2R[0]) / 2.0, (kpR[1] + kpL2R[1]) / 2.0]\n item_left = keypoints['leftCrop'][i]\n item_right = keypoints['rightCrop'][i]\n\n new_item_left = {\n 'keypointType': bp,\n 'xCrop': kpL_adjusted[0],\n 'xFrame': item_left['xFrame'] - item_left['xCrop'] + kpL_adjusted[0],\n 'yCrop': kpL_adjusted[1],\n 'yFrame': item_left['yFrame'] - item_left['yCrop'] + kpL_adjusted[1]\n }\n left_keypoints_crop_adjusted.append(new_item_left)\n\n new_item_right = {\n 'keypointType': bp,\n 'xCrop': kpR_adjusted[0],\n 'xFrame': item_right['xFrame'] - item_right['xCrop'] + kpR_adjusted[0],\n 'yCrop': kpR_adjusted[1],\n 'yFrame': item_right['yFrame'] - item_right['yCrop'] + kpR_adjusted[1]\n }\n right_keypoints_crop_adjusted.append(new_item_right)\n\n adjusted_keypoints = {\n 'leftCrop': left_keypoints_crop_adjusted,\n 'rightCrop': right_keypoints_crop_adjusted\n }\n return adjusted_keypoints\n\n\n\n \n","sub_path":"alok/biomass_estimation/archive/production_data_analysis_v3/template_matching.py","file_name":"template_matching.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"24229703","text":"#\n# @lc app=leetcode.cn id=2 lang=python3\n#\n# [2] 两数相加\n#\n# https://leetcode-cn.com/problems/add-two-numbers/description/\n#\n# algorithms\n# Medium (32.69%)\n# Total Accepted: 86.8K\n# Total Submissions: 265.7K\n# Testcase Example: '[2,4,3]\\n[5,6,4]'\n#\n# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。\n#\n# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。\n#\n# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。\n#\n# 示例:\n#\n# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)\n# 输出:7 -> 0 -> 8\n# 原因:342 + 465 = 807\n#\n#\n#\n# Definition for singly-linked list.\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n\n def chain_table_to_int(self, x: ListNode):\n s = ''\n while x:\n s += str(x.val)\n x = x.next\n if s:\n print(s)\n return int(s[::-1])\n else:\n return 0\n\n def addTwoNumbers(self, l1: ListNode, l2: ListNode):\n\n return [int(x) for x in str(self.chain_table_to_int(l1) + self.chain_table_to_int(l2))[::-1]]\n\n# class Solution:\n#\n# def chain_table_to_int(self, x: ListNode):\n# s = ''\n# while x and x.next:\n# s += str(x.val)\n# x = x.next\n# if s:\n# return int(s[::-1])\n# else:\n# return 0\n#\n# def addTwoNumbers(self, l1: ListNode, l2: ListNode):\n#\n# return [int(x) for x in str(self.chain_table_to_int(l1) + self.chain_table_to_int(l2))[::-1]]\n","sub_path":"vs_leetcode/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"483240228","text":"# Copyright 2019 The Casbin Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nfrom werkzeug.wrappers import Request\r\nfrom werkzeug.exceptions import Forbidden\r\nfrom apps.libs.error_code import my_Forbidden\r\nfrom flask_jwt import jwt\r\nfrom apps.api.model.model import Users\r\n\r\n\r\nclass CasbinMiddleware:\r\n def __init__(self, app, enforcer):\r\n self.app = app\r\n self.enforcer = enforcer\r\n\r\n def __call__(self, environ, start_response):\r\n request = Request(environ)\r\n\r\n # 检查每个请求的权限。\r\n if not self.check_permission(request):\r\n # 未授权,返回http 403错误。\r\n return my_Forbidden()(environ, start_response)\r\n # return Forbidden()(environ, start_response)\r\n\r\n # 权限已通过,请转到下一个模块\r\n return self.app(environ, start_response)\r\n\r\n def check_permission(self, request):\r\n # 根据您的身份验证方法对其进行自定义。\r\n user = None\r\n try:\r\n token = str(request.headers.get('Authorization')).split(' ')[1]\r\n id = jwt.decode(token, \"pangyd\", algorithms=['HS256'])['identity']\r\n user = Users.get(id).username\r\n except Exception:\r\n user = None\r\n if user is None:\r\n user = 'anonymous'\r\n path = request.path\r\n method = request.method\r\n return self.enforcer.enforce(user, path, method)\r\n","sub_path":"apps/rbac/authz/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"47032114","text":"import numpy as np\nnp.random.seed(1337)\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten\nfrom keras.optimizers import Adam\n\nmnist_data = np.load('mnist.npz')\nX_train,y_train = mnist_data['x_train'],mnist_data['y_train']\nX_test,y_test = mnist_data['x_test'],mnist_data['y_test']\n\nprint('数据大小:',X_train.shape)\nprint('原始数据标签:',y_train[0:10])\nprint('-'*50)\n\nX_train = X_train.reshape(-1,1,28,28)/255.\nX_test = X_test.reshape(-1,1,28,28)/255.\ny_train = np_utils.to_categorical(y_train,num_classes = 10)\ny_test = np_utils.to_categorical(y_test, num_classes = 10)\n\nprint('转换成one-hot后的数据标签:',y_train[0:10])\nprint('-'*19+'data加载完毕'+'-'*19)\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(batch_input_shape=(None,1,28,28),\n\tfilters=32,\n\tkernel_size=5,\n\tstrides=1,\n\tpadding='same',\n\tdata_format='channels_first',))\n\nmodel.add(Activation('relu'))\n\nmodel.add(MaxPooling2D(pool_size=2,\n\tstrides=2,\n\tpadding='same',\n\tdata_format='channels_first'))\n\nmodel.add(Convolution2D(batch_input_shape=(None,1,28,28),\n\tfilters=64,\n\tkernel_size=5,\n\tstrides=1,\n\tpadding='same',\n\tdata_format='channels_first',))\n\nmodel.add(Activation('relu'))\n\nmodel.add(MaxPooling2D(pool_size=2,\n\tstrides=2,\n\tpadding='same',\n\tdata_format='channels_first'))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024))\nmodel.add(Activation('relu'))\n\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nadam = Adam(lr=1e-4)\n\nmodel.compile(optimizer=adam,\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nprint('数据训练中......')\nmodel.fit(X_train, y_train, epochs=10, batch_size=64,)\nprint('数据训练完毕.')\n\nprint('开始测试模型......')\nloss, accuracy = model.evaluate(X_test, y_test)\nprint('\\nTest Loss: ', loss)\nprint('\\nTest Accuracy: ', accuracy)\n\n\n\n\n\n\n","sub_path":"深度学习/Templet/Train_Nets/Keras/Mnist/sample_cnn.py","file_name":"sample_cnn.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"206215229","text":"#!/usr/bin/env python3\n\nimport os\nimport cv2\nimport numpy as np\nfrom glob import glob\nimport tensorflow as tf\n\nfrom config import cfg\nfrom celeba import CelebA\nfrom generators import generator_tf as G\nfrom discriminators import discriminator_tf as D\n\n\ndef model_inputs(w, h, c, z_dim):\n # Input for the model, image\n _i = tf.placeholder(tf.float32, [None, w, h, c], 'real_input_images')\n _z = tf.placeholder(tf.float32, [None, z_dim], 'input_z')\n return _i, _z\n\ndef model_loss(inp_real, inp_z, out_channel, alpha=0.2, smooth_factor=0.1):\n # Loss from the real image for G and D\n d_model_real, d_logits_real = D(inp_real, alpha=alpha)\n d_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_real,\n labels=tf.ones_like(d_model_real) * (1 - smooth_factor)))\n\n # Loss from the fake image for G and D\n inp_fake = G(inp_z, out_channel, alpha=alpha)\n d_model_fake, d_logits_fake = D(inp_fake, reuse=True, alpha=alpha)\n d_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_fake,\n labels=tf.zeros_like(d_model_fake)))\n\n g_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=d_logits_fake,\n labels=tf.ones_like(d_model_fake)))\n\n return d_loss_real + d_loss_fake, g_loss\n\ndef model_opt(d_loss, g_loss, lr, beta1):\n # Optimization operations for the losses of D and G\n # Get weights and bias to update\n t_vars = tf.trainable_variables()\n d_vars = [var for var in t_vars if var.name.startswith('discriminator')]\n g_vars = [var for var in t_vars if var.name.startswith('generator')]\n\n # Optimize\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n d_train_opt = tf.train.AdamOptimizer(lr, beta1=beta1)\\\n .minimize(d_loss, var_list=d_vars)\n g_train_opt = tf.train.AdamOptimizer(lr, beta1=beta1)\\\n .minimize(g_loss, var_list=g_vars)\n\n return d_train_opt, g_train_opt\n\ndef show_generator_output(sess, n_img, inp_z, out_channel, img_mode='RGB'):\n # Show the output from the generator\n cmap = None if img_mode == 'RGB' else 'gray'\n z_dim = inp_z.get_shape().as_list()[-1]\n example_z = np.random.uniform(-1, 1, size=[n_img, z_dim])\n\n samples = sess.run(G(inp_z, out_channel, False), feed_dict={inp_z: example_z})\n\n images_grid = helper.images_square_grid(samples, image_mode)\n return images_grid\n\ndef train(nb_epochs, batch_size, z_dim, lr, beta1, get_batches, data_shape,\n data_img_mode, print_every=10, show_every=100):\n # Train method for the GAN\n inp_real, inp_z = model_inputs(*data_shape, z_dim)\n d_loss, g_loss = model_loss(inp_real, inp_z, data_shape[2])\n d_train_opt, g_train_opt = model_opt(d_loss, g_loss, lr, beta1)\n\n saver = tf.train.Saver()\n sample_z = np.random.uniform(-1, 1, size=(72, z_dim))\n\n samples, losses = [], []\n\n steps = 0\n count = 0\n with tf.Session() as sess:\n saver = tf.train.Saver()\n sess.run(tf.global_variables_initializer())\n\n # continue training\n save_path = saver.save(sess, \"/tmp/model.ckpt\")\n ckpt = tf.train.latest_checkpoint('./model/')\n saver.restore(sess, save_path)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n os.mkdir('output')\n for epoch_i in range(nb_epochs):\n os.mkdir('output/'+ str(epoch_i))\n for batch_images in get_batches(batch_size):\n steps += 1\n batch_images *= 2.0\n \n # Sample random noise for G\n batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))\n \n # Run optimizers\n sess.run(d_train_opt, feed_dict={inp_real: batch_images, input_z: batch_z})\n sess.run(g_train_opt, feed_dict={input_z: batch_z})\n \n if steps % print_every == 0:\n # At the end of each epoch, get the losses and print them out\n train_loss_d = d_loss.eval({inp_real: batch_images, inp_z: batch_z})\n train_loss_g = g_loss.eval({inp_z: batch_z})\n print(\"Epoch {}/{} Step {}...\".format(epoch_i+1, nb_epochs, steps),\n \"Discriminator Loss: {:.4f}...\".format(train_loss_d),\n \"Generator Loss: {:.4f}\".format(train_loss_g))\n # Save losses for viewing after training\n losses.append((train_loss_d, train_loss_g))\n\n if steps % show_every == 0:\n count = count +1\n iterr = count*show_every\n # Show example output for the generator\n images_grid = show_generator_output(sess, 25, inp_z, data_shape[2], data_img_mode)\n dst = os.path.join(\"output\", str(epoch_i), str(iterr)+\".png\")\n pyplot.imsave(dst, images_grid)\n \n # saving the model\n if epoch_i % 10 == 0:\n if not os.path.exists('./model/'):\n os.makedirs('./model')\n saver.save(sess, './model/' + str(epoch_i))\n\n# Get the data in a readable format\ndataset = CelebA()\n\n# Tensorflow\nwith tf.Graph().as_default():\n train(cfg.NB_EPOCHS, cfg.BATCH_SIZE, cfg.SIZE_G_INPUT, cfg.LEARNING_RATE,\n cfg.BETA1, dataset.get_batches, dataset.shape, dataset.image_mode)\n\n\nfor f in glob(\"output/**/*.png\"):\n image = cv2.imread(f)\n # cv2.imshow('my_image', image)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n large = cv2.resize(image, (0,0), fx=3, fy=3)\n cv2.imwrite(f, large)","sub_path":"GAN_experiments/celebrities_face_generator/test_tf.py","file_name":"test_tf.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"378156528","text":"from functools import partial\n\nfrom pyschieber.stich import Stich\nfrom pyschieber.trumpf import Trumpf\n\nUNDER = 11\nNAELL = 9\n\n\ndef stich_obe_unde(played_cards, operation, trumpf):\n suit = played_cards[0].card.suit\n (_, index) = operation(\n [(played_card.card.value, i) for i, played_card in enumerate(played_cards) if played_card.card.suit == suit])\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n\n\ndef stich_trumpf(played_cards, trumpf):\n trumpfs = [(played_card.card.value, i) for i, played_card in enumerate(played_cards) if\n played_card.card.suit.name == trumpf.name]\n if trumpfs:\n values = [trumpf[0] for trumpf in trumpfs]\n if UNDER in values: # Under\n index = trumpfs[values.index(UNDER)][1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n if NAELL in values:\n index = trumpfs[values.index(NAELL)][1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n index = max(trumpfs)[1]\n return Stich(player=played_cards[index].player, played_cards=played_cards, trumpf=trumpf)\n else:\n return stich_obe_unde(played_cards=played_cards, operation=max, trumpf=trumpf)\n\n\nstich_rules = {\n Trumpf.OBE_ABE: partial(stich_obe_unde, operation=max, trumpf=Trumpf.OBE_ABE),\n Trumpf.UNDE_UFE: partial(stich_obe_unde, operation=min, trumpf=Trumpf.UNDE_UFE),\n}\n\nfor trumpf in filter(lambda x: x != Trumpf.OBE_ABE and x != Trumpf.UNDE_UFE and x != Trumpf.SCHIEBEN, Trumpf):\n stich_rules[trumpf] = partial(stich_trumpf, trumpf=trumpf)\n\n\ndef card_allowed(first_card, chosen_card, hand_cards, trumpf):\n chosen_suit = chosen_card.suit\n if chosen_card not in hand_cards:\n return False\n if first_card is None:\n return True\n first_suit = first_card.suit\n if first_suit == chosen_suit or chosen_suit.name == trumpf.name:\n return True\n else:\n if trumpf not in [Trumpf.OBE_ABE, Trumpf.UNDE_UFE]:\n hand_suits = [hand_card.suit for hand_card in hand_cards if\n hand_card.suit.name != trumpf.name and hand_card.value != UNDER]\n else:\n hand_suits = [hand_card.suit for hand_card in hand_cards]\n if first_suit in hand_suits:\n return False\n else:\n return True\n\n\ndef allowed_cards(hand_cards, table_cards, trumpf):\n cards = []\n if len(table_cards) > 0:\n for card in hand_cards:\n if card_allowed(table_cards[0], card, hand_cards, trumpf):\n cards.append(card)\n else:\n cards += hand_cards\n return cards\n","sub_path":"pyschieber/rules/stich_rules.py","file_name":"stich_rules.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"418623582","text":"import requests\n\nheaders = {\n \"User-Agent\": \"User-Agent, Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\"\n\n}\n\nurl = 'https://hr.tencent.com/position.php?keywords=python&tid=87&lid=2218'\n\ndata ={\n'keywords': 'python',\n'tid': 87,\n'lid': 2218,\n}\n\nresponse =requests.post(url,data=data,headers=headers)\n\nprint(response)","sub_path":"requests_tengxun.py","file_name":"requests_tengxun.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"438531364","text":"import math\n\ndef get_g_month_length(g_month, g_year):\n if g_month != 2:\n return [None, 31, None, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][g_month]\n else:\n return 28 + (g_year % 4 == 0 and (\n g_year % 100 != 0 or g_year % 400 == 0))\n\ndef get_ts_total_seasons(ts_season, ts_year):\n return (ts_season - 1) + 4 * (ts_year - 1)\n\ndef get_ts_equinox_length(ts_total_seasons):\n c1 = ts_total_seasons % 3 == 0\n c2 = ts_total_seasons % 44 == 0\n return 1 + c1 - c2\n\ndef get_ts_lunar_equinox_length(ts_total_seasons):\n c1 = ts_total_seasons % 3 == 0\n c2 = ts_total_seasons % int(math.log(2, 10) * 1024) == 0\n return 1 - c1 + c2\n\ndef next_day(g_day, g_month, g_year, ts_day, ts_month, ts_equinox, ts_season,\nts_year, ts_lun_day, ts_lun_count, ts_lun_year):\n # simple\n if g_day != get_g_month_length(g_month, g_year):\n r_g_day = g_day + 1\n r_g_month = g_month\n r_g_year = g_year\n elif g_month != 12:\n r_g_day = 1\n r_g_month = g_month + 1\n r_g_year = g_year\n else:\n r_g_day = 1\n r_g_month = 1\n r_g_year = g_year + 1\n # complicated\n if ts_equinox:\n lun_day_jump = get_ts_lunar_equinox_length(get_ts_total_seasons(\n ts_season, ts_year)) / 2\n if ts_day != get_ts_equinox_length(get_ts_total_seasons(\n ts_season, ts_year)):\n r_ts_day = ts_day + 1\n r_ts_month = ts_month\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n r_ts_day = 1\n r_ts_month = 1\n r_ts_equinox = False\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n if ts_day != 30:\n lun_day_jump = 1\n r_ts_day = ts_day + 1\n r_ts_month = ts_month\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n elif ts_month != 3:\n lun_day_jump = 1\n r_ts_day = 1\n r_ts_month = ts_month + 1\n r_ts_equinox = ts_equinox\n r_ts_season = ts_season\n r_ts_year = ts_year\n else:\n skip_equinox = get_ts_equinox_length(get_ts_total_seasons(\n ts_season + 1, ts_year)) == 0\n new_year = ts_season == 4\n lun_day_jump = get_ts_lunar_equinox_length(get_ts_total_seasons(\n ts_season + 1, ts_year)) / (1 if skip_equinox else 2)\n r_ts_day = 1\n r_ts_month = 1 if skip_equinox else None\n r_ts_equinox = not skip_equinox\n r_ts_season = 1 if new_year else ts_season + 1\n r_ts_year = ts_year + 1 if new_year else ts_year\n r_ts_lun_day = (ts_lun_day + lun_day_jump) % 29\n if r_ts_lun_day < ts_lun_day:\n if r_ts_year == ts_lun_year:\n r_ts_lun_count = ts_lun_count + 1\n r_ts_lun_year = ts_lun_year\n else:\n r_ts_lun_count = 1\n r_ts_lun_year = r_ts_year\n else:\n r_ts_lun_count = ts_lun_count\n r_ts_lun_year = ts_lun_year\n return r_g_day, r_g_month, r_g_year, r_ts_day, r_ts_month, \\\n r_ts_equinox, r_ts_season, r_ts_year, r_ts_lun_day, r_ts_lun_count, \\\n r_ts_lun_year\n\ndef main():\n # d = 13, 12, 2012, 23, 3, False, 4, 0, 0.0, 13, 0\n # the below is equivalent to the above\n d = 26, 12, 2011, 4, 1, False, 1, 0, 0.0, 1, 0\n desc = ('day', 'month', 'year', 'day', 'month', 'equinox?',\n 'season', 'year', 'lunar day', 'lunar month', 'lunar year')\n while True:\n '''\n if (d[3], d[4], d[6]) == (30, 3, 4) and d[-4] % 77 == 0 and d[-4] % 3 != 0 and d[-3] == 28:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n if (d[3], d[4], d[6]) == (1, 1, 1) and d[-4] % 77 == 1 and d[-4] % 3 != 1 and d[-3] == 1:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n if d[-3] in (28.5, 0.5) and 840 > d[-4] > 630:\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n '''\n if d[2] in (2017, 2018):\n for i, j in zip(desc, d):\n print(f'{i}: {j}')\n print('\\n')\n d = next_day(*d)\n\nif __name__ == '__main__':\n main()\n","sub_path":"internarrative_commit_system_test/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"137526464","text":"# -*- coding:utf8 -*-\n# File : data_provider_discogan.py\n# Author : Jiayuan Mao\n# Email : maojiayuan@gmail.com\n# Date : 4/2/17\n# \n# This file is part of TensorArtist\n\nimport os.path as osp\n\nimport numpy as np\nimport tqdm\n\nfrom tartist import image\nfrom tartist.app import gan\nfrom tartist.core import get_env\nfrom tartist.core.utils.thirdparty import get_tqdm_defaults\nfrom tartist.data import flow, kvstore\n\n\nclass DiscoGANSplitDataFlow(flow.SimpleDataFlowBase):\n def __init__(self, kva, kvb):\n super().__init__()\n self._kva = kva\n self._kvb = kvb\n self._img_shape = get_env('dataset.img_shape', (64, 64))\n\n def _crop_and_resize(self, img):\n img = image.imdecode(img)\n img = image.resize(img, self._img_shape)\n return img\n\n def _gen(self):\n ita = iter(self._kva)\n itb = iter(self._kvb)\n while True:\n res = dict(\n img_a=self._crop_and_resize(next(ita)),\n img_b=self._crop_and_resize(next(itb))\n )\n yield res\n\n\ndef _make_dataflow(batch_size=1, use_prefetch=False):\n img_shape = get_env('dataset.img_shape', (64, 64))\n\n data_dir = get_env('dir.data')\n db_a = osp.join(data_dir, get_env('dataset.db_a'))\n db_b = osp.join(data_dir, get_env('dataset.db_b'))\n\n dfs = []\n dfa = flow.KVStoreRandomSampleDataFlow(lambda: kvstore.LMDBKVStore(db_a))\n dfb = flow.KVStoreRandomSampleDataFlow(lambda: kvstore.LMDBKVStore(db_b))\n df = DiscoGANSplitDataFlow(dfa, dfb)\n df = flow.BatchDataFlow(df, batch_size, sample_dict={\n 'img_a': np.empty(shape=(batch_size, img_shape[0], img_shape[1], 3), dtype='float32'),\n 'img_b': np.empty(shape=(batch_size, img_shape[0], img_shape[1], 3), dtype='float32'),\n })\n if use_prefetch:\n df = flow.MPPrefetchDataFlow(df, nr_workers=2)\n return df\n\n df = gan.GANDataFlow(dfs[0], dfs[1],\n get_env('trainer.nr_g_per_iter', 1), get_env('trainer.nr_d_per_iter', 1))\n\n\ndef make_dataflow_train(env):\n batch_size = get_env('trainer.batch_size')\n dfs = [_make_dataflow(batch_size, use_prefetch=True) for i in range(2)]\n\n df = gan.GANDataFlow(dfs[0], dfs[1], \n get_env('trainer.nr_g_per_iter', 1), get_env('trainer.nr_d_per_iter', 1))\n\n return df\n\n\ndef make_dataflow_demo(env):\n return _make_dataflow(1)\n\n\ndef demo(feed_dict, results, extra_info):\n img_a, img_b = feed_dict['img_a'][0], feed_dict['img_b'][0]\n img_ab, img_ba = results['img_ab'][0] * 255, results['img_ba'][0] * 255\n img_aba, img_bab = results['img_aba'][0] * 255, results['img_bab'][0] * 255\n\n img = np.vstack([\n np.hstack([img_a, img_ab, img_aba]), \n np.hstack([img_b, img_ba, img_bab])\n ])\n img = img.astype('uint8')\n img = image.resize_minmax(img, 512, 2048)\n\n image.imshow('demo', img)\n\n","sub_path":"examples/generative-model/data_provider_discogan.py","file_name":"data_provider_discogan.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"64181017","text":"\"\"\"\nFunctions and data to use for formatting Pathoscope and NuVs analysis document. Formatted documents are destined for\nAPI responses or CSV/Excel formatted file downloads.\n\n\"\"\"\nimport asyncio\nimport csv\nimport io\nimport json\nimport statistics\nfrom collections import defaultdict\n\nimport aiofiles\nimport openpyxl.styles\n\nimport virtool.analyses.db\nimport virtool.analyses.utils\nimport virtool.db.core\nimport virtool.db.utils\nimport virtool.history.db\nimport virtool.otus.db\nimport virtool.otus.utils\n\nCSV_HEADERS = (\n \"OTU\",\n \"Isolate\",\n \"Sequence\",\n \"Length\",\n \"Weight\",\n \"Median Depth\",\n \"Coverage\"\n)\n\n\ndef calculate_median_depths(document: dict) -> dict:\n \"\"\"\n Calculate the median depth for all hits (sequences) in a Pathoscope result document.\n\n :param document: the pathoscope analysis document to calculate depths for\n :return: a dict of median depths keyed by hit (sequence) ids\n\n \"\"\"\n depths = dict()\n\n for hit in document[\"results\"]:\n depths[hit[\"id\"]] = statistics.median(hit[\"align\"])\n\n return depths\n\n\nasync def create_pathoscope_coverage_cache(db, document):\n cache = defaultdict(lambda: defaultdict(lambda: dict()))\n\n for hit in document[\"results\"]:\n for isolate in hit[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n otu_id = hit[\"id\"]\n isolate_id = isolate[\"id\"]\n sequence_id = sequence[\"id\"]\n\n if sequence.get(\"align\"):\n cache[otu_id][isolate_id][sequence_id] = virtool.analyses.utils.transform_coverage_to_coordinates(sequence[\"align\"])\n\n document = {\n \"analysis\": {\n \"id\": document[\"_id\"]\n },\n \"cache\": cache\n }\n\n await db.coverage.insert_one(document)\n\n return document\n\n\nasync def ensure_pathoscope_coverage_cache(db, document):\n cache = await db.coverage.find_one({\"analysis.id\": document[\"_id\"]})\n\n if cache is None:\n cache = await create_pathoscope_coverage_cache(db, document)\n\n for hit in document[\"results\"]:\n for isolate in hit[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n otu_id = hit[\"id\"]\n isolate_id = isolate[\"id\"]\n sequence_id = sequence[\"id\"]\n\n if sequence.get(\"align\"):\n sequence[\"align\"] = cache[\"cache\"][otu_id][isolate_id][sequence_id]\n\n\nasync def load_results(settings: dict, document: dict) -> dict:\n \"\"\"\n Load the analysis results. Hide the alternative loading from a `results.json` file. These files are only\n generated if the analysis data would have exceeded the MongoDB size limit (16mb).\n\n The document is returned unmodified if loading from file is not required.\n\n :param settings: the application settings\n :param document: the document to load results for\n :return: a complete analysis document\n\n \"\"\"\n if document[\"results\"] == \"file\":\n path = virtool.analyses.utils.join_analysis_json_path(\n settings[\"data_path\"],\n document[\"_id\"],\n document[\"sample\"][\"id\"]\n )\n\n async with aiofiles.open(path, \"r\") as f:\n data = json.loads(await f.read())\n return {\n **document,\n \"results\": data\n }\n\n return document\n\n\nasync def format_aodp(app, document):\n patched_otus = await gather_patched_otus(app, document[\"results\"])\n\n hits = defaultdict(list)\n\n for hit in document[\"results\"]:\n hits[hit[\"sequence_id\"]].append(hit)\n\n for otu in patched_otus.values():\n otu[\"id\"] = otu.pop(\"_id\")\n\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n sequence[\"hits\"] = hits[sequence[\"_id\"]]\n sequence[\"id\"] = sequence.pop(\"_id\")\n\n return {\n **document,\n \"results\": list(patched_otus.values())\n }\n\n\nasync def format_pathoscope(app, document):\n document = await load_results(\n app[\"settings\"],\n document\n )\n\n patched_otus = await gather_patched_otus(app, document[\"results\"])\n\n formatted = dict()\n\n for hit in document[\"results\"]:\n\n otu_id = hit[\"otu\"][\"id\"]\n\n otu_document = patched_otus[otu_id]\n\n max_ref_length = 0\n\n for isolate in otu_document[\"isolates\"]:\n max_ref_length = max(max_ref_length, max([len(s[\"sequence\"]) for s in isolate[\"sequences\"]]))\n\n otu = {\n \"id\": otu_id,\n \"name\": otu_document[\"name\"],\n \"version\": otu_document[\"version\"],\n \"abbreviation\": otu_document[\"abbreviation\"],\n \"isolates\": otu_document[\"isolates\"],\n \"length\": max_ref_length\n }\n\n formatted[otu_id] = otu\n\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n if sequence[\"_id\"] == hit[\"id\"]:\n sequence.update(hit)\n sequence[\"length\"] = len(sequence[\"sequence\"])\n\n del sequence[\"otu\"]\n del sequence[\"otu_id\"]\n del sequence[\"isolate_id\"]\n\n document[\"results\"] = [formatted[otu_id] for otu_id in formatted]\n\n for otu in document[\"results\"]:\n for isolate in list(otu[\"isolates\"]):\n if not any((key in sequence for sequence in isolate[\"sequences\"]) for key in (\"pi\", \"final\")):\n otu[\"isolates\"].remove(isolate)\n continue\n\n for sequence in isolate[\"sequences\"]:\n if \"final\" in sequence:\n sequence.update(sequence.pop(\"final\"))\n del sequence[\"initial\"]\n if \"pi\" not in sequence:\n sequence.update({\n \"pi\": 0,\n \"reads\": 0,\n \"coverage\": 0,\n \"best\": 0,\n \"length\": len(sequence[\"sequence\"])\n })\n\n sequence[\"id\"] = sequence.pop(\"_id\")\n del sequence[\"sequence\"]\n\n await ensure_pathoscope_coverage_cache(app[\"db\"], document)\n\n return document\n\n\nasync def format_nuvs(app, document):\n document = await load_results(\n app[\"settings\"],\n document\n )\n\n hit_ids = list({h[\"hit\"] for s in document[\"results\"] for o in s[\"orfs\"] for h in o[\"hits\"]})\n\n cursor = app[\"db\"].hmm.find({\"_id\": {\"$in\": hit_ids}}, [\"cluster\", \"families\", \"names\"])\n\n hmms = {d.pop(\"_id\"): d async for d in cursor}\n\n for sequence in document[\"results\"]:\n for orf in sequence[\"orfs\"]:\n for hit in orf[\"hits\"]:\n hit.update(hmms[hit[\"hit\"]])\n\n return document\n\n\nasync def format_analysis_to_excel(app, document):\n depths = calculate_median_depths(document)\n\n formatted = await format_analysis(app, document)\n\n output = io.BytesIO()\n\n wb = openpyxl.Workbook()\n ws = wb.active\n\n ws.title = f\"Pathoscope for {document['sample']['id']}\"\n\n header_font = openpyxl.styles.Font(name=\"Calibri\", bold=True)\n\n for index, header in enumerate(CSV_HEADERS):\n col = index + 1\n cell = ws.cell(column=col, row=1, value=header)\n cell.font = header_font\n\n rows = list()\n\n for otu in formatted[\"results\"]:\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n row = [\n otu[\"name\"],\n virtool.otus.utils.format_isolate_name(isolate),\n sequence[\"accession\"],\n sequence[\"length\"],\n sequence[\"pi\"],\n depths.get(sequence[\"id\"], 0),\n sequence[\"coverage\"]\n ]\n\n assert len(row) == len(CSV_HEADERS)\n\n rows.append(row)\n\n for row_index, row in enumerate(rows):\n row_number = row_index + 2\n for col_index, value in enumerate(row):\n ws.cell(column=col_index + 1, row=row_number, value=value)\n\n wb.save(output)\n\n return output.getvalue()\n\n\nasync def format_analysis_to_csv(app, document):\n depths = calculate_median_depths(document)\n\n formatted = await format_analysis(app, document)\n\n output = io.StringIO()\n\n writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)\n\n writer.writerow(CSV_HEADERS)\n\n for otu in formatted[\"results\"]:\n for isolate in otu[\"isolates\"]:\n for sequence in isolate[\"sequences\"]:\n row = [\n otu[\"name\"],\n virtool.otus.utils.format_isolate_name(isolate),\n sequence[\"accession\"],\n sequence[\"length\"],\n sequence[\"pi\"],\n depths.get(sequence[\"id\"], 0),\n sequence[\"coverage\"]\n ]\n\n writer.writerow(row)\n\n return output.getvalue()\n\n\nasync def format_analysis(app, document: dict) -> dict:\n \"\"\"\n Format an analysis document to be returned by the API.\n\n :param app: the application object\n :param document: the analysis document to format\n :return: a formatted document\n\n \"\"\"\n workflow = document.get(\"workflow\")\n\n if workflow:\n if workflow == \"nuvs\":\n return await format_nuvs(app, document)\n\n if \"pathoscope\" in workflow:\n return await format_pathoscope(app, document)\n\n if workflow == \"aodp\":\n return await format_aodp(app, document)\n\n raise ValueError(\"Could not determine analysis workflow\")\n\n\nasync def gather_patched_otus(app, results):\n # Use set to only id-version combinations once.\n otu_specifiers = {(hit[\"otu\"][\"id\"], hit[\"otu\"][\"version\"]) for hit in results}\n\n patched_otus = await asyncio.gather(*[\n virtool.history.db.patch_to_version(\n app,\n otu_id,\n version\n ) for otu_id, version in otu_specifiers\n ])\n\n return {patched[\"_id\"]: patched for _, patched, _ in patched_otus}\n","sub_path":"virtool/analyses/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":9988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"35808396","text":"class Player:\n def __init__(self, name):\n self.name = name;\n self.steps = []\n self.choose = True\n\n def players_turn(self):\n self.choose = True\n try:\n while self.choose:\n a = int(input(\"Player's turn\\n\"))\n if self.steps.count(a) == 0:\n if a < 9 and a >= 0:\n self.steps.append(a)\n return a\n except:\n print('Something went wrong. '\n 'Write to the developer... ivandubovtsov@gmail.com')\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"80465653","text":"from util_class import ListNode\nclass Solution:\n \"\"\"\n @param head: The first node of linked list\n @param x: An integer\n @return: A ListNode\n \"\"\"\n def partition(self, head, x):\n # write your code here\n if not head:\n return None\n \n dummy = ListNode(0)\n dummy.next = head\n small_head = ListNode(0) \n big_head = ListNode(0)\n s_head, b_head = small_head, big_head\n while head:\n tmp = head.next\n head.next = None\n if head.val < x:\n s_head.next = head\n s_head = s_head.next\n else:\n b_head.next = head\n b_head = b_head.next\n head = tmp \n \n s_head.next = big_head.next\n \n return small_head.next","sub_path":"96_partition-list/partition-list.py","file_name":"partition-list.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"395522256","text":"# sudo lsof -iTCP -sTCP:LISTEN -n -P\n# https://dreamfit01.herokuapp.com/ | https://git.heroku.com/dreamfit01.git\n\n# heroku\thttps://git.heroku.com/dreamfit01.git (fetch)\n# heroku\thttps://git.heroku.com/dreamfit01.git (push)\n# origin\thttps://github.com/donaldvallejo/CarsCloud.git (fetch)\n# origin\thttps://github.com/donaldvallejo/CarsCloud.git (push)\n\nimport os\nfrom datetime import datetime\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nhost = os.environ.get('MONGODB_URI', 'mongodb://localhost:27017/cars')\nclient = MongoClient(host=f'{host}?retryWrites=false')\ndb = client.get_default_database()\ncars = db.cars\ncomments = db.comments\n\napp = Flask(__name__)\n\n@app.route('/')\ndef cars_index():\n \"\"\"Show all cars\"\"\"\n return render_template('cars_index.html', cars=cars.find())\n\n@app.route('/home')\ndef home():\n \"\"\"Show Home page\"\"\"\n return render_template('home.html')\n\n@app.route('/finance')\ndef finance():\n \"\"\"Show Finance page\"\"\"\n return render_template('finance.html')\n\n@app.route('/cars/new')\ndef cars_new():\n \"\"\"Create cars\"\"\"\n return render_template('cars_new.html', car = {}, title='New Cars')\n\n@app.route('/cars', methods=['POST'])\ndef cars_submit():\n \"\"\"Submit cars to database\"\"\"\n car = {\n 'Make': request.form.get('Make'),\n 'Model': request.form.get('Model'),\n 'Description': request.form.get('Description'),\n 'Color': request.form.get('Color'),\n 'Price': request.form.get('Price'),\n 'Image': request.form.get('Image'),\n 'created_at': datetime.now()\n }\n\n car_id = cars.insert_one(car).inserted_id\n print(\"Check to see if Data is even happening \\n\", car_id, car)\n return redirect(url_for('cars_show', car_id=car_id))\n\n@app.route('/cars/')\ndef cars_show(car_id):\n \"\"\"Show a single car.\"\"\"\n car = cars.find_one({'_id': ObjectId(car_id)})\n car_comments = comments.find({'car_id': ObjectId(car_id)})\n return render_template('cars_show.html', car=car, comments=car_comments)\n\n@app.route('/cars//edit')\ndef cars_edit(car_id):\n \"\"\"Show the edit form for a car.\"\"\"\n car = cars.find_one({'_id': ObjectId(car_id)})\n return render_template('cars_edit.html', car=car, title='Edit Car')\n\n@app.route('/search', methods=['POST'])\ndef search():\n searched_cars = cars.find()\n search = request.form.get('search')\n search_items = []\n for car in searched_cars:\n if search.lower() in car['Make'].lower():\n search_items.append(car)\n elif search.lower() in car['Model'].lower():\n search_items.append(car)\n elif search.lower() in car['Color'].lower():\n search_items.append(car)\n elif search.lower() in car['Price'].lower():\n search_items.append(car)\n else:\n print('how did you break this?')\n return render_template('cars_index.html', cars=search_items)\n\n@app.route('/cars/', methods=['POST'])\ndef cars_update(car_id):\n \"\"\"Submit an edited cars\"\"\"\n updated_car = {\n 'Make': request.form.get('Make'),\n 'Model': request.form.get('Model'),\n 'Description': request.form.get('Description'),\n 'Color': request.form.get('Color'),\n 'Price': request.form.get('Price'),\n 'Image': request.form.get('Image'),\n }\n cars.update_one(\n {'_id': ObjectId(car_id)},\n {'$set': updated_car})\n return redirect(url_for('cars_show', car_id=car_id))\n\n@app.route('/cars//delete', methods=['POST'])\ndef cars_delete(car_id):\n \"\"\"Delete one car.\"\"\"\n cars.delete_one({'_id': ObjectId(car_id)})\n return redirect(url_for('cars_index'))\n\n@app.route('/cars/comments', methods=['POST'])\ndef comments_new():\n \"\"\"Submit a new comment.\"\"\"\n comment = {\n 'title': request.form.get('title'),\n 'content': request.form.get('content'),\n 'car_id': ObjectId(request.form.get('car_id'))\n }\n comment_id = comments.insert_one(comment).inserted_id\n return redirect(url_for('cars_show', car_id=request.form.get('car_id')))\n\n@app.route('/cars/comments/', methods=['POST'])\ndef comments_delete(comment_id):\n \"\"\"Action to delete a comment.\"\"\"\n comment = comments.find_one({'_id': ObjectId(comment_id)})\n comments.delete_one({'_id': ObjectId(comment_id)})\n return redirect(url_for('cars_show', car_id=comment.get('car_id')))\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=os.environ.get('PORT', 5000))","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"414983189","text":"import arcpy\r\n\r\nfrom code_library.common.geospatial import geometry\r\nfrom code_library.common import log\r\n\r\nlog.init_log(arc_script = True)\r\n\r\np1 = arcpy.GetParameterAsText(0)\r\np2 = arcpy.GetParameterAsText(1)\r\n\r\ncen_dist,out_table,out_points = geometry.simple_centroid_distance(p1,p2,spatial_reference = p1,dissolve=True,return_file=True)\r\n\r\n\r\nlog.warning(\"Centroid Distance: %s\" % cen_dist)\r\nlog.warning(\"Points representing the centroids and a table with the distances have been returned to the TOC\")\r\n\r\narcpy.SetParameterAsText(2,out_points)\r\narcpy.SetParameterAsText(3,out_table)","sub_path":"releases/cws_toolbox/current/cws_toolbox/simple_centroid_distance/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"4524678","text":"#!/bin/python3\n# Copyright 2019-2020 CSIRO Land and Water\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis example gets some Sensor Observations from a given Cosmoz station\n\"\"\"\n\nfrom urllib.request import Request, urlopen\nfrom urllib.parse import urljoin, urlencode\nfrom datetime import datetime, timezone\nimport json\n\nCOSMOZ_API_URL = \"https://esoil.io/cosmoz-data-pipeline/rest/\" # Keep the trailing slash on here\n\nSTATION_NUMBER = 21\nPROCESSING_LEVEL = 4 # Choose processing level 1, 2, 3, 4, or 0 (for Raw)\n\n# Endpoint to get a station's observations is \"pipeline/rest/stations/{id}/observations\"\nstations_endpoint = urljoin(COSMOZ_API_URL, \"stations/\")\nstation_endpoint = urljoin(stations_endpoint, \"{}/\".format(str(STATION_NUMBER)))\nstation_obs_endpoint = urljoin(station_endpoint, \"observations\")\n\n# Time Period Start Date\nstart_date = datetime(2019, 1, 1, tzinfo=timezone.utc)\nstart_date_str = start_date.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\") # ISO8601 Format\n# Time Period End Date\nend_date = datetime(2019, 1, 31, tzinfo=timezone.utc)\nend_date_str = end_date.strftime(\"%Y-%m-%dT%H:%M:%S.000Z\") # ISO8601 Format\n# Add request query params\nquery_params = {\n \"processing_level\": PROCESSING_LEVEL,\n \"startdate\": start_date_str,\n \"enddate\": end_date_str,\n}\nquery_params = urlencode(query_params)\nstation_obs_url = \"{}?{}\".format(station_obs_endpoint, query_params)\n\n# Add a header to specifically ask for JSON output\nrequest_headers = {\"Accept\": \"application/json\"}\n\n# Construct a GET request, with that URL and those headers\nstation_obs_request = Request(station_obs_url, method=\"GET\", headers=request_headers)\n# Execute the request, and wait for the response.\nwith urlopen(station_obs_request) as http_response:\n try:\n response = http_response.read()\n except Exception:\n raise RuntimeError(\"Cannot read HTTP Response\")\n try:\n payload = json.loads(response)\n except Exception:\n raise RuntimeError(\"Invalid JSON response\")\nprint(\"Got Observations Meta:\")\nfor k, v in payload['meta'].items():\n print(\"\\t{}: {}\".format(str(k), str(v)))\n\ncount = payload['meta']['count']\nsite = payload['meta']['site_no']\nprint(\"Showing {} Observations for station {}.\".format(str(count), str(site)))\nfor i, o in enumerate(payload['observations']):\n print(\"Observation {} of {}:\".format(i+1, count))\n for k, v in o.items():\n print(\"\\t{}: {}\".format(str(k), str(v)))\n","sub_path":"example4_station_observations.py","file_name":"example4_station_observations.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"105791512","text":"from numpy.random import *\n\npopulation = ['M']*20000 + ['F']*20000 + ['m']\ndef nextGen(population):\n\tnewGen = []\n\tif population.count('F')==0:\n\t\treturn newGen\n\twhile len(newGen) < population.count('M') + population.count('F'):\n\t\tA = population[randint(len(population))]\n\t\tB = population[randint(len(population))]\n\t\tif A.lower() != B.lower():\n\t\t\tif A == 'm' or B == 'm':\n\t\t\t\tnewGen.append('m')\n\t\t\telse:\n\t\t\t\tif randint(2)==0:\n\t\t\t\t\tnewGen.append('M')\n\t\t\t\telse:\n\t\t\t\t\tnewGen.append('F')\n\treturn newGen\n\ndef simulate(initalPopulation, generations):\n\tresults = []\n\tcP = initalPopulation\n\tfor i in range(generations):\n\t\tresults.append([cP.count('M'), cP.count('F'), cP.count('m')])\n\t\tcP = nextGen(cP)\n\treturn results","sub_path":"Bio/mucke.py","file_name":"mucke.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"410657790","text":"import json\nfrom sqlalchemy import exc, or_\nfrom marshmallow import ValidationError\nfrom flask import request, Response, make_response, current_app\nfrom flask_classful import FlaskView\nfrom app import db\n\n\ndef output_json(data, code, headers=None):\n \"\"\" Form api responses as JSON\n \"\"\"\n\n content_type = 'application/json'\n\n dumped = json.dumps(data)\n\n if headers:\n headers.update({'Content-Type': content_type})\n else:\n headers = {'Content-Type': content_type}\n\n response = make_response(dumped, code, headers)\n\n return response\n\n\nclass APIError(Exception):\n \"\"\" Exception to raise when API call errors\n\n Attributes:\n error_code -- HTML response error code to pass back.\n error_source -- value where the error occured.\n \"\"\"\n\n def __init__(self, error_code, error_source):\n self.error_code = error_code\n self.error_source = error_source\n\n\nclass ApiView(FlaskView):\n trailing_slash = False\n\n excluded_methods = ['filter_query', 'unique_filter']\n\n representations = {'application/json': output_json}\n\n def __init__(self,):\n super().__init__()\n self.model = None\n self.schema = None\n # Unique filters to check, Post, Put and Patch requets\n self.update_filter = None \n # Use tablename, otherwise overwite this for messages.\n self.model_str = None\n\n\n def filter_query(self, query, raw_filters):\n \"\"\"\n Modified version of accpeted answer from:\n https://stackoverflow.com/questions/14845196/dynamically-constructing-filters-in-sqlalchemy\n\n 1 - Split the desired filters out from filters url argument\n 2 - split each filter into the Column corresponding to the Model.Column, the filter operator and the search value\n 3 - using a lambda funciton create corresponding SQLAlchemy ORM Internal\n - https://docs.sqlalchemy.org/en/13/orm/internals.html\n 4 - Create and chain the filter(s) to the query.\n\n Example:\n import requests\n r = requests.get('http://server/api/user?filters=FirstName eq \"Jimmy\" AND LastName eq \"Bob\")\n \"\"\"\n\n for filter_ in raw_filters.split(' AND '):\n try:\n key, op, value = filter_.split(' ', maxsplit=2)\n except ValueError:\n raise APIError(400, f'Invalid filter: {filter_}')\n\n value = value.strip(\"'\")\n value = value.strip('\"')\n\n column = getattr(self.model, key, None)\n if not column:\n raise APIError(400, f'Invalid field: {key}')\n\n if op == 'in':\n values = value.split(',')\n values = [v.strip(' ') for v in values]\n filt = column.in_(values)\n else:\n try:\n attr = list(filter(lambda e: hasattr(column, f\"{e}\"), [f'{op}', f'{op}_', f'__{op}__']))[0]\n except IndexError:\n raise APIError(400, f'Invalid operation: {op}')\n if value == 'null':\n value = None\n\n filt = getattr(column, attr)(value)\n query = query.filter(filt)\n return query\n\n\n def unique_filter(self, filter_dict: dict):\n \"\"\" Create a single or set of filter for Unique fields on a model.\n\n Keyword Arguments;\n\n filter_dict: contains Model Column and value in key:value pair.\n\n If there are mulitple Unqiue fields, will return tuple in \n \n \"\"\"\n _return_filter = []\n for key,value in filter_dict.items():\n column = getattr(self.model, key)\n _filter = getattr(column, '__eq__')(value)\n _return_filter.append(_filter)\n \n if not _return_filter:\n # Always True filter to return if filter_dict fails to produce a filter\n _return_filter = (1 == 1)\n else:\n # Create an SQL 'OR' Filter for multiple fields \n if len(_return_filter) > 1:\n _return_filter = or_(*_return_filter)\n \n return _return_filter\n\n\n def index(self,) -> Response:\n \"\"\" Index route to provide list of Users \"\"\"\n args = {\n 'filters': request.args.get('filters', ''),\n 'pageSize': request.args.get('pageSize', 25),\n 'page': request.args.get('page', 1)\n }\n\n current_app.logger.info('logger test')\n if args['filters']:\n try:\n data = self.filter_query(\n query=db.session.query(self.model),\n raw_filters=args['filters'])\n except APIError as err:\n return {\"message\": err.error_source}, err.error_code\n else:\n data = db.session.query(self.model)\n \n return self.schema(many=True).jsonify(data)\n\n\n def get(self, pk_id: int) -> Response:\n \"\"\" Get method to retrieve specific record.\n \n Keyword arguments:\n pk_id -- Primary Key value of Model\n\n \"\"\"\n data = db.session.\\\n query(\n self.model).\\\n filter(\n (self.model.ID == pk_id)).\\\n first()\n \n return self.schema().jsonify(data)\n\n\n def post(self,) -> Response:\n \"\"\" POST method to create record. \"\"\"\n\n json_data = request.get_json()\n\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n\n try:\n data = self.schema().load(json_data)\n except ValidationError as err:\n return err.messages, 422\n\n update_dict = {f\"{f}\": data[f] for f in self.update_filter}\n _unq_filter = self.unique_filter(update_dict)\n\n record = db.session.\\\n query(\n self.model).\\\n filter(\n _unq_filter ).\\\n first()\n\n if record is None:\n record = self.model(\n **data)\n try:\n db.session.add(record)\n db.session.commit()\n data, response = {\"message\": f\"Created {self.model_str}\"}, 200\n except exc.SQLAlchemyError as e:\n db.session.rollback()\n current_app.logger.exception(e)\n data, response = {\"message\": f\"Could not create {self.model_str}\"}, 200\n else:\n data, response = {\"message\": f\"{self.model_str} already exists.\"}, 200\n\n return data, response\n\n\n def put(self, pk_id) -> Response:\n \"\"\" PUT method to Update entire Record\n\n Keyword arguments:\n pk_id -- Primary Key value of record Model\n\n Note: Primary Key is created by Database Sequence, therefore\n PUT method only works when record already exists.\n Similar functionality to PATCH, but whole record needs to be\n sent in request.\n \"\"\"\n\n record_query = db.session.query(self.model).get(pk_id)\n\n # User agent should know target resource via GET request.\n if not record_query:\n return {\"message\": \"Record not found\"}, 404\n\n json_data = request.get_json()\n\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n\n try:\n data = self.schema().load(json_data)\n except ValidationError as err:\n return err.messages, 422\n\n try:\n for k, v in data.items():\n setattr(record_query, k, v)\n db.session.commit()\n data, code = {'message': f\"{self.model_str} updated.\"}, 200\n except (exc.SQLAlchemyError, TypeError):\n db.session.rollback()\n data, code = {\"message\": f\"{self.model_str} record could not be updated.\"}, 500\n\n return data, code\n\n\n def patch(self, pk_id) -> Response:\n \"\"\" Patch method to update part(s) of record model.\n\n Keyword arguments:\n pk_id -- Primary Key value of record Model\n\n Inspired by ConnectWise API.\n Patch body needs to be an array containing dict(s) of update instruction.\n Example:\n import requests\n patch = [\n {\n 'op': 'replace',\n 'path': 'FirstName',\n 'value': 'Jimmy'\n }\n ]\n\n requets.patch('http://server/api/user/1', json=patch)\n\n Update occurs similiary to PUT method, however patch doesn't require\n whole record in request. Allows for reduce bandwidth requests for larger models.\n \"\"\"\n record_query = db.session.query(self.model).filter((self.model.ID == pk_id)).first()\n\n # User agent should know target resource via GET request.\n if not record_query:\n return {\"message\": \"Record not found\"}, 404\n \n request_data = request.get_json(force=True, silent=True)\n if not request_data:\n return {'message': 'No content provided.'}, 400\n\n # Build patch from supplied data\n apply_patch = {}\n allowed_operations = (\"replace\",)\n for patch_data in request_data:\n try:\n if patch_data.get(\"op\").lower() not in allowed_operations:\n return {'message': f'Operation \"{patch_data.get(\"op\")}\" not supported.'}, 400\n except AttributeError:\n return {'message': f'Invalid operation {patch_data.get(\"op\")}.'}, 400\n\n apply_patch.update({patch_data.get('path'): patch_data.get(\"value\")})\n\n # Validate request data\n try:\n self.schema().load(apply_patch)\n except ValidationError as err:\n return {'message': err.messages}, 400\n\n try:\n for k, v in apply_patch.items():\n setattr(record_query, k, v)\n db.session.commit()\n data, code = {'message': f\"{self.model_str} updated.\"}, 200\n except (exc.SQLAlchemyError, TypeError):\n db.session.rollback()\n data, code = {\"message\": f\"{self.model_str} record could not be updated.\"}, 500\n\n return data, code\n\n \n def delete(self, pk_id) -> Response: \n \"\"\" Delete method to remove specific record.\n \n Keyword arguments:\n pk_id -- Primary Key value of Model\n\n \"\"\"\n record = db.session.query(self.model).filter((self.model.ID == pk_id)).first()\n\n if record:\n try:\n db.session.delete(record)\n db.session.commit()\n data, response = {\"message\": f\"{self.model_str} record deleted.\"}, 200\n except exc.SQLAlchemyError:\n db.session.rollback()\n data, response = {\"message\": f\"{self.model_str} record could not be deleted.\"}, 500\n else:\n data, response = {\"message\": f\"No matching {self.model_str} record.\"}, 404\n \n return data, response\n","sub_path":"app/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"491423640","text":"from youtube.face_evoLVe_PyTorch.align.YTPredictor import YTPredictor\nimport os\nimport cv2\n\n\ncurrent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))\nabsPath_to_youtube = os.path.abspath(os.path.join(current_dir, 'youtube'))\nytPredictor = YTPredictor(absPath_to_youtube=absPath_to_youtube, \\\ncast_length=8, compress_width=400, skip_frames=12, frame_range=[0,400])\n\nf = open(os.path.join(current_dir,'trailer_list.txt'),'r')\nlist_of_trailer = f.read().splitlines()\nf.close()\nprint(list_of_trailer)\ncast_list=[]\nweight_list=[]\n\nfor i in range(len(list_of_trailer)):\n path_to_video = os.path.join(current_dir, \"videos/\"+list_of_trailer[i])\n result = ytPredictor.__call__(yt_url=None, path_to_video=path_to_video)\n cast_ = [result[i][0] for i in range(len(result))]\n freq_ = [result[i][1][0] for i in range(len(result))]\n weight_ = [float(itm)/sum(freq_list) for itm in freq_]\n cast_list.append(cast_)\n weight_list.append(weight_)\n if i>2:\n break","sub_path":"code/models/test_for_video.py","file_name":"test_for_video.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"359814224","text":"import Adafruit_DHT\r\nimport datetime\r\nimport json\r\n\r\n\r\n\"Reading Data of Temperature and Humidity\"\r\n\r\nclass DHT11_Reader(object):\r\n\r\n def __init__(self):\r\n\r\n self.humidity = 0\r\n self.temperature = 0\r\n\r\n def sensorData(self):\r\n\r\n try:\r\n self.humidity, self.temperature = Adafruit_DHT.read_retry(11, 27)\r\n \"Reading Data of sensor DHT11 on PIN 27 of Raspberry\"\r\n except:\r\n print(\"ReadingDHT: ERROR IN READING THE SENSOR\")\r\n if self.humidity is not None and self.temperature is not None:\r\n get_time = datetime.datetime.now()\r\n current_time = get_time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n print('Time: ',current_time,'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(self.temperature, self.humidity))\r\n \"put all the data in a Json\"\r\n OutputJson = json.dumps({\"temperature\": self.temperature, \"humidity\": self.humidity ,\"time\":current_time})\r\n\r\n return OutputJson\r\n else:\r\n print('ReadingDHT: ERROR IN SENDING JSON')\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n \"this is for testing we use this class in the PublishTempHum class\"\r\n data_of_DHT = DHT11_Reader()\r\n while True:\r\n data_of_DHT.sensorData()\r\n","sub_path":"Progetto/Raspberry/TempandHumidity.py","file_name":"TempandHumidity.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"63075358","text":"import pandas as pd \nimport numpy as np \n\n#Set seed:\nnp.random.seed(301200)\n\n#Files:\nfolder='/gpfs3/well/win-fmrib-analysis/users/lhw539/ixi/'\nfilenames=['ixi_train','ixi_val','ixi_test']\n\nfor filename in filenames:\n filepath=folder+filename\n df=pd.read_csv(filepath+'.csv')\n \n df_female=df[df[\"Sex\"]==0]\n df_male=df[df[\"Sex\"]==1]\n\n n_female=df_female.shape[0]\n n_male=df_male.shape[0]\n \n print(\"Original data set: number of female: \", n_female)\n print(\"Original data set: number of male: \", n_male)\n\n factor=n_female/n_male\n factor_int=np.floor(factor).astype(int)\n random_share=factor-factor_int\n n_rand_choice=np.round(random_share*n_male).astype(int)\n rand_subset=np.random.permutation(n_male)[:n_rand_choice].astype(int)\n df_balanced=pd.concat([df_male.iloc[rand_subset]]+[df_male for it in range(factor_int)]+[df_female])\n print(\"Balanced values: \", np.unique(df_balanced[\"Sex\"],return_counts=True))\n new_file_path=filepath+'_balanced_'+'sex'+'.csv'\n df_balanced.to_csv(new_file_path)\n print(\"Saved to: \", new_file_path)","sub_path":"data/ixi/oversample.py","file_name":"oversample.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"283516958","text":"#!/usr/bin/env python\n# coding: utf-8\n#\n# Author: Kazuto Nakashima\n# URL: https://kazuto1011.github.io\n# Date: 07 January 2019\n\nfrom __future__ import absolute_import, division, print_function\n\nimport json\nimport multiprocessing\nimport os\nfrom pathlib import Path\n\nimport click\nimport joblib\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom omegaconf import OmegaConf\nfrom PIL import Image\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchnet.meter import MovingAverageValueMeter\nfrom tqdm import tqdm\n\nfrom libs.datasets import get_dataset\nfrom libs.models import DeepLabV2_ResNet101_MSC\nfrom libs.utils import scores\n\n\ndef makedirs(dirs):\n if not os.path.exists(dirs):\n os.makedirs(dirs)\n\n\ndef get_device(cuda):\n cuda = cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if cuda else \"cpu\")\n if cuda:\n print(\"Device:\")\n for i in range(torch.cuda.device_count()):\n print(\" {}:\".format(i), torch.cuda.get_device_name(i))\n else:\n print(\"Device: CPU\")\n return device\n\n\ndef get_params(model, key):\n # For Dilated FCN\n if key == \"1x\":\n for m in model.named_modules():\n if \"layer\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n for p in m[1].parameters():\n yield p\n # For conv weight in the ASPP module\n if key == \"10x\":\n for m in model.named_modules():\n if \"aspp\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n yield m[1].weight\n # For conv bias in the ASPP module\n if key == \"20x\":\n for m in model.named_modules():\n if \"aspp\" in m[0]:\n if isinstance(m[1], nn.Conv2d):\n yield m[1].bias\n\n\ndef resize_labels(labels, size):\n \"\"\"\n Downsample labels for 0.5x and 0.75x logits by nearest interpolation.\n Other nearest methods result in misaligned labels.\n -> F.interpolate(labels, shape, mode='nearest')\n -> cv2.resize(labels, shape, interpolation=cv2.INTER_NEAREST)\n \"\"\"\n new_labels = []\n for label in labels:\n label = label.float().numpy()\n label = Image.fromarray(label).resize(size, resample=Image.NEAREST)\n new_labels.append(np.asarray(label))\n new_labels = torch.LongTensor(new_labels)\n return new_labels\n\n\n@click.command()\n@click.option(\n \"-c\",\n \"--config-path\",\n type=click.File(),\n help=\"Dataset configuration file in YAML\",\n)\n@click.option(\n \"-m\",\n \"--model-path\",\n type=click.Path(exists=True),\n required=True,\n help=\"PyTorch model to be loaded\",\n)\n@click.option(\n \"--img-dir\", \"--img_dir\",\n type=click.Path(exists=True),\n required=True,\n help=\"Image directory\",\n)\n@click.option(\n \"--seg-dir\", \"--seg_dir\",\n type=click.Path(exists=True),\n required=True,\n help=\"Segmentation directory\",\n)\n@click.option(\n \"--cuda/--cpu\", default=True, help=\"Enable CUDA if available [default: --cuda]\"\n)\ndef main(config_path, model_path, cuda, img_dir, seg_dir):\n \"\"\"\n Evaluation on validation set\n \"\"\"\n config_path = Path(os.path.dirname(os.path.realpath(__file__))) /'cocostuff164k.yaml'\n # Configuration\n CONFIG = OmegaConf.load(config_path)\n device = get_device(cuda)\n torch.set_grad_enabled(False)\n\n # Dataset\n dataset = get_dataset(CONFIG.DATASET.NAME)(\n root=CONFIG.DATASET.ROOT,\n split=CONFIG.DATASET.SPLIT.VAL,\n ignore_label=CONFIG.DATASET.IGNORE_LABEL,\n mean_bgr=(CONFIG.IMAGE.MEAN.B, CONFIG.IMAGE.MEAN.G, CONFIG.IMAGE.MEAN.R),\n augment=False,\n img_dir=img_dir,\n seg_dir=seg_dir,\n )\n print(dataset)\n\n # DataLoader\n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=CONFIG.SOLVER.BATCH_SIZE.TEST,\n num_workers=CONFIG.DATALOADER.NUM_WORKERS,\n shuffle=False,\n )\n\n # Model\n model = eval(CONFIG.MODEL.NAME)(n_classes=CONFIG.DATASET.N_CLASSES)\n state_dict = torch.load(model_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(state_dict)\n model = nn.DataParallel(model)\n model.eval()\n model.to(device)\n\n # Path to save logits\n logit_dir = os.path.join(\n CONFIG.EXP.OUTPUT_DIR,\n \"features\",\n CONFIG.EXP.ID,\n CONFIG.MODEL.NAME.lower(),\n CONFIG.DATASET.SPLIT.VAL,\n \"logit\",\n )\n makedirs(logit_dir)\n print(\"Logit dst:\", logit_dir)\n\n # Path to save scores\n save_dir = os.path.join(\n CONFIG.EXP.OUTPUT_DIR,\n \"scores\",\n CONFIG.EXP.ID,\n CONFIG.MODEL.NAME.lower(),\n CONFIG.DATASET.SPLIT.VAL,\n )\n makedirs(save_dir)\n save_path = os.path.join(save_dir, \"scores.json\")\n print(\"Score dst:\", save_path)\n\n preds, gts = [], []\n for image_ids, images, gt_labels in tqdm(\n loader, total=len(loader), dynamic_ncols=True\n ):\n # Image\n images = images.to(device)\n\n # Forward propagation\n logits = model(images)\n\n # Save on disk for CRF post-processing\n for image_id, logit in zip(image_ids, logits):\n filename = os.path.join(logit_dir, image_id + \".npy\")\n np.save(filename, logit.cpu().numpy())\n\n # Pixel-wise labeling\n _, H, W = gt_labels.shape\n logits = F.interpolate(\n logits, size=(H, W), mode=\"bilinear\", align_corners=False\n )\n probs = F.softmax(logits, dim=1)\n labels = torch.argmax(probs, dim=1)\n\n preds += list(labels.cpu().numpy())\n gts += list(gt_labels.numpy())\n # Pixel Accuracy, Mean Accuracy, Class IoU, Mean IoU, Freq Weighted IoU\n score = scores(gts, preds, n_class=CONFIG.DATASET.N_CLASSES)\n\n with open(save_path, \"w\") as f:\n json.dump(score, f, indent=4, sort_keys=True)\n print(score)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"deeplab/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"136540224","text":"import argparse\n\n### Setup argument parser ###\n\nparser = argparse.ArgumentParser(description=\"\"\"\nWelcome to CYAMESE: training a model that learns an individual's cytometry\nfingerprint. This is a program made as a rotation project by George\nHartoularos in Atul Butte's lab at University of California, San Francisco.\n\nThe input is a series of studies done at Stanford in Mark Davis' group in \nwhich CYTOF data was collected from the peripheral blood cells of patients \nbefore being vaccinated for influenza. Because it is pre-vaccination, this\nrepresents a patient in their \"healthy\" state. The idea is that by treating\nthese flow cytometry data as \"images\" of a person, we can learn what that\nindividual looks like simply based on their cytometry profile.\n\nRight now the program only takes in those studies as input, but will \neventually generalize to any flow/gene expression data. The program is still\nbeing developed and is not ready to make accurate predictions.\n\nThis is made for python2 and uses the Keras machine learning framework \nwith TensorFlow as backend.\n\n\"\"\", formatter_class=argparse.RawTextHelpFormatter)\n\nparser.add_argument('f', metavar='pathtofcs', type=str,\n help='location of fcs files with metadata pickle')\n\nparser.add_argument('-o',metavar='output_file',type=str, default=None,\n help='name of output folder with pickled datasets' + \n ' (default=results)')\n\nparser.add_argument('-s', metavar='subset', type=int, default=-1,\n help='random subset of files to use for training ' + \n '(default: use all)')\n\nparser.add_argument('-e', metavar='epochs', type=int, default=100,\n help='number of epochs to train (default=100) ')\n\nparser.add_argument('-nc', metavar='numcells', type=int, default=1500,\n help='number of cells per \"image\" of individual ' + \n '(default=1500)')\n\nparser.add_argument('-tr', metavar='trainloops', type=int, default=300,\n help='number of image pairs per subject for training ' + \n '(defaults=300)')\n\nparser.add_argument('-te', metavar='testloops', type=int, default=300,\n help='number of image pairs per subject for testing ' + \n '(defaults=300)')\n\nparser.add_argument('--lb', action='store_false', default=True,\n help='option to print loading bar (default: on)')\n\nparser.add_argument('--gpu', action='store_true', default=False,\n help='option if running on GPU (default: off)')\n\n\nargs = parser.parse_args() # Parse arguments\n\npathtofcs = args.f\noutput = args.o\nrand_subset = args.s\nepochs = args.e\nnumcells = args.nc\ntrainloops = args.tr\ntestloops = args.te\nloadbar = args.lb\ngpu_switch = args.gpu\n\n'''\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~TODO:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSprinkle exceptions throughout all scripts to catch inputs if they are\nnot of the right type.\n\nFigure out why I'm getting the:\nUserWarning: text in segment does not start and end with delimiter\nwarning from fcm when I use all of the data; occurs towards the beginning\n\nMake a separate script for just acquiring the data that uses the API.\n\nEventually, make the testing be only from a new subject, see if it can be \nused to recognize new patients off the bat. There will be two testing sets.\nOne asks can we recognize the same subject from the training. The other, \ncooler more important question: can we recognize a new patient that \nwasn't even trained on at all?\n\n\n'''\n\n# Imports\nimport itertools as it\nimport os\nimport cPickle as pkl\nprint(\"Welcome to CYAMESE: training a model that learns an individual's\\\n cytometry fingerprint. Beginning program.\")\n\nimport tensorflow as tf\n\nfrom metautils import makemeta\nfrom markers import setmarkers\nfrom createpairs import generatedicts, pairandsplit, testpairs\n\n###########################################################################\n'''\nQuick input check\n'''\nif pathtofcs[-1] != '/': # add the forward slash if it's not there\n pathtofcs += '/'\nif not os.path.exists(pathtofcs): # Confirm that meta path exists\n print('Supplied pathtofcs does not exist. Try again.')\n raise SystemExit\n'''\nThe training regimen is only using data from Mark Davis' study\nfrom Stanford. The chosen studies are shown below. Despite the \nnumbering, they are in chronological order. The dictionary\n\"studdict\" is used to index the studies according to chronology.\nThe \"split\" variable splits the studies into training and testing.\nThe training data is based *only* on the first two years, while the\ntesting data uses all three years.\n\nSplit is a tuple of exactly two tuples that dictates what data will \nbe used for training and testing. The first tuple is training and the\nsecond is testing. Training tuple will compare two different studies\nto eachother to create positive pairs (the same subject in SDY311 and\nSDY112) and negative pairs (different subjects in the same or different \nstudies).\n'''\n\nstudies = ['SDY311', 'SDY112', 'SDY315']\nstuddict = dict(zip(range(3),studies))\nsplit = (('SDY311', 'SDY112'), ('SDY315',))\n\n'''\nThe \"TIME\" channel in the flow data is an irrelevant parameter, not\nso much a phenotype of the cells but only useful for troubleshooting\nexperimentation. It will be ignored.\n'''\n\nignorechan = ['TIME'] # images will not contain this channel\n\n'''\nmakemeta takes the metadata file (a pickled pandas dataframe) located\nin the directory created from the apidownload script, and unpickles it.\nIf a random number of subjects has been specified, it only extracts the\ndata from those subjects.\n'''\nprint(\"Making meta data file.\")\nmeta, numsubs = makemeta(pathtofcs, studies, studdict, rand_subset)\n\nfiles = list(meta['filename'])\n\n'''\nsetmarkers makes a set of unique markers common to all the flow cytometry\ndata files. It will ignore any channels fed in by ignorechan and also \ncheck that there are at least 20 markers to learn from.\n'''\nprint(\"Extracting out common markers from flow data.\")\nmarkerset = setmarkers(pathtofcs, files, ignorechan=ignorechan)\n\n'''\ngeneratedicts generates dictionaries that have subject/study pairs as\nkeys and a numpy array of the cells x markers data as the value. It ensures\nthat the flow data have the markers all in the same order. It also splits\nthe data into train and test such that, although data from the same\nsubject/study might be used in both training and testing, that the same data\nfrom an individual cell is not reused.\n'''\nprint(\"Generating dictionaries with the data.\")\nalltrain, alltest = generatedicts(studies, numsubs, files, pathtofcs, \n markerset, split, loadbar)\n\n'''\npairandsplit is the main workhorse of the data formatting. It takes random \nimages from a person's flow data and pairs it with either the same person's \nflow data from a different study (positive pair) or a different person's flow \ndata from the same or different year (negative pair). Depending on how many\nloops are used, it might need to reuse cells; it does this in such a way that\nit never reuses the same cell before using all others first. The most \nimportant part is that it doesnt not bias the training towards any one \nindividual or class: there is a roughly equal representation of positive and\nnegative pairs, of individuals, of studies, and of cells.\n'''\npairandsplit(alltrain, alltest, numcells, \n trainloops, testloops, split, loadbar)\n","sub_path":"cyamese_scripts/generatepkls.py","file_name":"generatepkls.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"345361548","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\n#from config import remote_db_endpoint, remote_db_port\n#from config import remote_gwsis_dbname, remote_gwsis_dbuser, remote_gwsis_dbpwd\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\n\nfrom flask import Flask, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\nremote_db_endpoint=os.environ['remote_db_endpoint']\nremote_db_port=os.environ['remote_db_port']\nremote_gwsis_dbname=os.environ['remote_gwsis_dbname']\nremote_gwsis_dbuser=os.environ['remote_gswis_dbuser']\nremote_gwsis_dbpwd=os.environ['remote_gwsis_dbpwd']\napiKey=os.environ['quandlkey']\nAPI_KEY=os.environ['mapboxkey']\n\napp = Flask(__name__)\n\n\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = f\"mysql+pymysql://root:{remote_gwsis_dbpwd}@codingbootcamp.ctxjv3tnsa2p.us-east-2.rds.amazonaws.com/gwsis\"\ndb = SQLAlchemy(app)\n\nBase = automap_base()\nBase.prepare(db.engine, reflect=True)\n\ndata_base_table = Base.classes.earnings\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/map\")\ndef map_visual():\n return render_template(\"map.html\")\n\n@app.route(\"/charts\")\ndef chart_visual():\n return render_template(\"charts.html\")\n \n@app.route(\"/data\")\ndef table():\n return render_template(\"data.html\")\n\n@app.route(\"/regression\")\ndef regression():\n return render_template(\"regression.html\")\n\n@app.route(\"/x\")\ndef samples():\n \n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n data = df.to_dict()\n\n return (\n jsonify(data)\n )\n\n@app.route(\"/list\")\ndef list_data():\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n data_list = {\n \"Index\": df.level_0.values.tolist(),\n \"Stock\": df['Stock Name'].values.tolist(),\n \"Reported Date\": df['Reported Date'].values.tolist(),\n \"Earnings Per Share\": df['Earnings Per Share'].values.tolist(),\n \"Forecasted Earnings Per Share\": df['Forecasted Earnings Per Share'].values.tolist(),\n \"% Surprise\": df['% Surprise'].values.tolist()\n }\n return (\n jsonify(data_list)\n )\n\n@app.route(\"/dict\")\ndef list_dict():\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n list_dict = []\n for index, row in df.iterrows():\n x = {\"Index\": row['level_0'],\n \"Stock Name\": row['Stock Name'],\n \"Reported Date\": row['Reported Date'],\n \"Earnings Per Share\": row['Earnings Per Share'],\n \"Forecasted Earnings Per Share\": row['Forecasted Earnings Per Share'],\n \"% Surprise\": row['% Surprise'],}\n list_dict.append(x)\n\n return(jsonify(list_dict))\n\n@app.route(\"/names\")\ndef names():\n \"\"\"Return a list of sample names.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(data_base_table).statement\n df = pd.read_sql_query(stmt, db.session.bind)\n\n # Return a list of the column names (sample names)\n return jsonify(list(df.columns)[2:])\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"364579740","text":"from tkinter import *\nimport members as members\nimport books as books\n\nroot = Tk()\n\nclass Welcome():\n\n def __init__(self, master):\n\n ## master setting\n self.master=master\n self.master.geometry('850x650+400+200')\n self.master.title('Welcome')\n\n ## menu pannel\n self.menu_pannel=Frame(self.master, width=20, height=100)\n self.menu_pannel.grid(row=0,column=0, sticky=N)\n\n self.label1=Label(self.menu_pannel, text='하정글방 관리 프로그램 for Dad', fg='green').grid(row=0, column=1, padx=3, pady=3)\n\n self.button_list=[]\n self.button1 = Button(self.menu_pannel, text='회원관리',fg='blue', height=3, width=15, command=self.gotoMembers)\n self.button1.grid(row=1,column=1, padx=3, pady=10)\n self.button_list.append(self.button1)\n\n self.button2 = Button(self.menu_pannel, text='도서관리',fg='blue', height=3, width=15, command=self.gotoBooks)\n self.button2.grid(row=2,column=1,padx=3, pady=10)\n self.button_list.append(self.button2)\n\n self.button3 = Button(self.menu_pannel, text='대여관리',fg='blue', height=3, width=15)\n self.button3.grid(row=3,column=1,padx=3, pady=10)\n self.button_list.append(self.button3)\n\n self.button4 = Button(self.menu_pannel, text='끝내기',fg='blue', height=3, width=15, command=self.finish)\n self.button4.grid(row=4, column=1,padx=3, pady=10)\n self.button_list.append(self.button4)\n\n ## function pannel\n self.function_pannel=Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n\n def set_button_free(self):\n for button in self.button_list:\n button.configure(relief=RAISED)\n\n def gotoMembers(self):\n self.set_button_free()\n self.button1.configure(relief=SUNKEN)\n\n self.function_pannel.grid_forget()\n self.function_pannel.destroy()\n self.function_pannel=Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n myGUI=members.Members(self.function_pannel)\n\n\n def gotoBooks(self):\n self.set_button_free()\n self.button2.configure(relief=SUNKEN)\n\n self.function_pannel.grid_forget()\n self.function_pannel.destroy()\n self.function_pannel = Frame(self.master, width=100, height=100)\n self.function_pannel.grid(row=0, column=1, sticky=N, padx=3, pady=30)\n myGUI=books.Books(self.function_pannel)\n\n\n def finish(self):\n self.master.destroy()\n\ndef main():\n myGUIWelcome=Welcome(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"441197804","text":"import unittest\nfrom Model.DatabaseConfiguration import TestConnection\nimport psycopg2\nimport Controller.TableTransformer as transformer\n\n#This file contains tests for TableTransformer that specifically creates new tables when transforming. This tests data manipulation methods of TableTransformer\n#For the tests on data manipulation methods of TableTransformer that don't copy but overwrite the tables refer to \"test_TableTransformer.py\"\n\nclass TestTransformerCopy(unittest.TestCase):\n db_connection = None\n engine = None\n test_object = None\n\n @classmethod\n def setUpClass(cls):\n cls.db_connection = TestConnection().get_db()\n cls.engine = TestConnection().get_engine()\n cls.test_object = transformer.TableTransformer(0, cls.db_connection, cls.engine, False, False)\n cur = cls.db_connection.cursor()\n cur.execute('CREATE SCHEMA IF NOT EXISTS \"0\"')\n cls.db_connection.commit()\n creation_query = \"\"\"CREATE TABLE \"0\".test_table (\n string VARCHAR(255) NOT NULL,\n number INTEGER NOT NULL,\n date_time VARCHAR(255) NOT NULL,\n garbage VARCHAR(255));\"\"\"\n creation_query1 = 'CREATE TABLE \"0\".test_table1 AS TABLE \"0\".test_table'\n creation_query2 = 'CREATE TABLE \"0\".test_table2 AS TABLE \"0\".test_table'\n #In some cases the test fails in a way that tearDownClass is not called and the table still exists\n #Sadly we can't confirm if the table is still correct, because of transformations performed on it\n try:\n cur.execute(creation_query)\n\n except psycopg2.ProgrammingError:\n #If it was still present in the database we better drop the schema and rebuild it\n cls.db_connection.rollback()\n cur.execute('DROP SCHEMA \"0\" CASCADE')\n cur.execute('CREATE SCHEMA \"0\"')\n cls.db_connection.commit()\n cur.execute(creation_query)\n cls.db_connection.commit()\n \n \n values = [('C-Corp', 1, '08/08/1997'), ('Apple', 22, '01/04/1976'), ('Microsoft', 8, '04/04/1975') , ('Nokia', 18, '12/05/1865') ,\n ('Samsung', 7, '01/03/1938'),('Huawei', 10, '15/09/1987'), ('Razer', 3, '01/01/1998'),\n ('Imagine Breakers', 14, '21/09/1996'), ('Sony', 9, '07/05/1946'), ('Asus', 12, '02/04/1989'),\n ('Hewlett-Packard', 5, '01/01/1939'), ('Toshiba', 8, '01/07/1975'), ('LG Electronics', -3, '01/10/1958'),\n ('Nintendo', 21, '23/09/1989'), ('Elevate ltd', 41, '08/08/1997'), ('Dummy', -17, '01/07/1975')]\n\n for v in values:\n cur.execute('INSERT INTO \"0\".test_table VALUES(%s, %s, %s)', v)\n\n cur.execute(creation_query1)\n cur.execute(creation_query2)\n cur.execute('UPDATE \"0\".test_table1 SET number = null WHERE number > 40')\n\n \n cls.db_connection.commit()\n\n @classmethod\n def tearDownClass(cls):\n cls.db_connection.cursor().execute('DROP SCHEMA \"0\" CASCADE')\n cls.db_connection.commit()\n #Close database connection\n cls.db_connection.close()\n\n\n def __test_table_exists(self, tablename):\n \"\"\"Test whether a table exists in the test schema after performing a operation that should create new table in the schema.\"\"\"\n cur = self.db_connection.cursor()\n cur.execute('SELECT table_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s ', ['0', tablename])\n result = cur.fetchone()\n if result is None:\n return False\n else:\n return True\n \n\n def test_delete_attribute(self):\n \"\"\"Test to see if TableTransformer can correctly delete an attribute resulting in a new table.\"\"\"\n self.test_object.delete_attribute('test_table', 'garbage', 'new_table1') #Delete attribute \"garbage\"\n #Now the only attributes should be \"string\", \"number\", \"date_time\"\n cur = self.db_connection.cursor()\n result = self.__test_table_exists('new_table1')\n self.assertTrue(result)\n #Let's see if we can find the deleted attribute\n cur.execute(\"\"\"SELECT column_name FROM information_schema.columns WHERE table_schema = '0'\n AND table_name = 'new_table1'\"\"\")\n tablenames = cur.fetchall()\n found = False\n for name in tablenames:\n if name[0] == 'garbage':\n found = True\n\n #Assert if it is in fact not found amongst remaining tablenames\n self.assertEqual(found, False)\n self.db_connection.commit()\n\n def test_find_and_replace(self):\n \"\"\"A test for the find and replace method resulting in a new table.\"\"\"\n self.test_object.find_and_replace('test_table','string', 'C-Corp', 'Replacement', new_name='new_table2')\n result = self.__test_table_exists('new_table2')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table2 WHERE string = 'Replacement'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 1)\n self.assertEqual(result[2], '08/08/1997')\n self.db_connection.commit()\n\n def test_find_and_replace_string(self):\n \"\"\"A test for find and replace method but for finding substrings resulting in a new table.\"\"\"\n #Find a word with substring Sam and replace the whole word with Foobar\n self.test_object.find_and_replace('test_table', 'string', 'Sam', 'Foobar', False, True, 'new_table3')\n result = self.__test_table_exists('new_table3')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table3 WHERE string = 'Foobar'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 7)\n self.assertEqual(result[2], '01/03/1938')\n\n #Find a word with substring To and replace the substring only with Waka\n self.test_object.find_and_replace('test_table', 'string', 'To', 'Waka', False, False, 'new_table4')\n result = self.__test_table_exists('new_table1')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table4 WHERE string = 'Wakashiba'\")\n result = cur.fetchone()\n #We found Toshiba but replaced To with Waka to get Wakashiba\n self.assertEqual(result[1], 8)\n self.assertEqual(result[2], '01/07/1975')\n\n def test_regex_find_and_replace(self):\n \"\"\"A test for the method of TableTransformer that uses regular expressions. This will result in a new table.\"\"\"\n #Use a regular expression to find Nintendo and replace it with SEGA\n self.test_object.regex_find_and_replace('test_table', 'string', 'Nin.*', 'SEGA', False, 'new_table5')\n result = self.__test_table_exists('new_table5')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table5 WHERE string = 'SEGA'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 21)\n self.assertEqual(result[2], '23/09/1989')\n\n #Use the regex to find a word without case sensitivity\n self.test_object.regex_find_and_replace('new_table5', 'string', 'sega', 'SEGA', False, 'new_table6')\n result = self.__test_table_exists('new_table6')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table6 WHERE string = 'SEGA'\")\n result = cur.fetchone()\n self.assertEqual(result[1], 21)\n self.assertEqual(result[2], '23/09/1989')\n\n #Use the regex to find a word with case sensitivity\n self.test_object.regex_find_and_replace('new_table6', 'string', 'sega', 'Ethereal', True, 'new_table7')\n result = self.__test_table_exists('new_table7')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT * FROM \\\"0\\\".new_table7 WHERE string = 'Ethereal'\")\n result = cur.fetchone()\n self.assertIsNone(result) #Shouldn't be able to find out due the difference in case\"\"\"\n\n def test_numeric_conversion(self):\n \"\"\"Test the conversion of numeric types (INTEGER, FLOAT). This will result in a new table.\"\"\"\n #From integer to float\n self.test_object.change_attribute_type('test_table', 'number', 'FLOAT', new_name='new_table8')\n result = self.__test_table_exists('new_table8')\n self.assertTrue(result)\n cur = self.db_connection.cursor()\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table8\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'double precision')\n #From float to integer\n self.test_object.change_attribute_type('new_table8', 'number', 'INTEGER', new_name='new_table9')\n result = self.__test_table_exists('new_table9')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table9\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'integer')\n #From integer to VARCHAR(255)\n self.test_object.change_attribute_type('test_table', 'number', 'VARCHAR(255)', new_name='new_table10')\n result = self.__test_table_exists('new_table10')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table10\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'character varying')\n\n def test_character_conversion(self):\n \"\"\"Test the conversion of character types. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n #Make it into a varchar for testing purposes\n self.test_object.change_attribute_type('test_table', 'number', 'VARCHAR(255)', new_name='new_table11')\n result = self.__test_table_exists('new_table11')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table11\")\n result = cur.fetchone()[0]\n self.assertEqual(result,'character varying')\n\n self.test_object.change_attribute_type('new_table11', 'number', 'FLOAT', new_name='new_table12')\n result = self.__test_table_exists('new_table12')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table12\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'double precision')\n \n #Change to varchar(30)\n self.test_object.change_attribute_type('new_table12', 'number', 'VARCHAR(n)', \"\", '30', new_name='new_table13')\n result = self.__test_table_exists('new_table13')\n self.assertTrue(result)\n cur.execute(\"SELECT pg_typeof(number) FROM \\\"0\\\".new_table13\")\n result = cur.fetchone()[0]\n self.assertEqual(result, 'character varying')\n \n def test_datetime_conversion(self):\n \"\"\"Test the conversion of an attribute to a date/time type. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n #Convert date_string column to actual DATE type\n self.test_object.change_attribute_type('test_table', 'date_time', 'DATE', 'DD/MM/YYYY', new_name='new_table14')\n result = self.__test_table_exists('new_table14')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(date_time) FROM \"0\".new_table14')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'date')\n self.db_connection.commit()\n #Convert the same column to a timestamp\n self.test_object.change_attribute_type('test_table', 'date_time', 'TIMESTAMP', 'DD/MM/YYYY TIME', new_name='new_table15')\n result = self.__test_table_exists('new_table15')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(date_time) FROM \"0\".new_table15')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'timestamp without time zone')\n self.db_connection.commit()\n #Set date_string of another to a time string and try to convert it\n query_1 = 'UPDATE \"0\".test_table SET garbage = \\'08:42 PM\\' WHERE garbage is NULL'\n cur.execute(query_1)\n self.test_object.change_attribute_type('test_table', 'garbage', 'TIME', 'HH12:MI AM/PM', new_name='new_table16')\n result = self.__test_table_exists('new_table16')\n self.assertTrue(result)\n cur.execute('SELECT pg_typeof(garbage) FROM \"0\".new_table16')\n result = cur.fetchone()[0]\n self.assertEqual(result, 'time without time zone')\n self.db_connection.commit()\n\n def test_one_hot_encode(self):\n \"\"\"Test the one-hot-encoding method for a column with unique and duplicate values. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.one_hot_encode('test_table', 'string', 'new_table17')\n result = self.__test_table_exists('new_table17')\n self.assertTrue(result)\n #Query to get all columns from the encoded table\n query = (\"SELECT column_name FROM information_schema.columns \"\n \"WHERE table_schema = '0' AND table_name = 'new_table17'\")\n cur.execute(query)\n all_columns = cur.fetchall()\n #This should be all the columns\n expected = ['number', 'date_time', 'garbage', 'Apple', 'Asus', 'Dummy', 'Elevate ltd',\n 'Hewlett-Packard', 'Huawei', 'Imagine Breakers', 'LG Electronics', 'Microsoft', 'Nintendo', 'Nokia', 'Razer',\n 'C-Corp', 'Samsung', 'Sony', 'Toshiba']\n \n for element in expected: #Test if expected elements are part of the table\n test_result = (element,) in all_columns\n self.assertTrue(test_result)\n #There should 22 columns, 3 previous one + 16 unique categories \n self.assertEqual(len(all_columns), 19)\n self.db_connection.commit()\n\n def test_equidistant_discretization(self):\n \"\"\"Test the equidistant discretization method. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.discretize_using_equal_width('test_table', 'number', 4, 'new_table18')\n result = self.__test_table_exists('new_table18')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table18')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n #There should be 3 buckets.\n self.assertEqual(len(all_values), 4)\n all_values = sorted(all_values)\n expected_values = ['[-17 , -2[', '[-2 , 13[', '[13 , 28[', '[28 , 43[']\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < -2 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -2[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < 13 AND number > -2 '\n 'AND number_categorical <> \\'[-2 , 13[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table18 WHERE number < 43 AND number > 28 '\n 'AND number_categorical <> \\'[28 , 43[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n def test_equifrequent_discretization(self):\n \"\"\"Test the equifrequent discretization method. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.discretize_using_equal_frequency('test_table', 'number', 'new_table19')\n result = self.__test_table_exists('new_table19')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table19')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , 4[', '[15 , 42[', '[4 , 9[', '[9 , 15[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < -4 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -4[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < 9 AND number > 4 '\n 'AND number_categorical <> \\'[4 , 9[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table19 WHERE number < 42 AND number > 15 '\n 'AND number_categorical <> \\'[15 , 42[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n def test_discretization_with_custom_ranges(self):\n \"\"\"Test the discretization with custom ranges method. This will result in a new table.\"\"\"\n #Let's simulate equidistant discretization with our custom bins.\n cur = self.db_connection.cursor()\n ranges = [-17, -2, 13, 28, 43]\n #self.test_object.set_to_overwrite()\n self.test_object.discretize_using_custom_ranges('test_table', 'number', ranges, True, 'new_table20')\n result = self.__test_table_exists('new_table20')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table20')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , -2[', '[-2 , 13[', '[13 , 28[', '[28 , 43[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n #Let's check if the values are actually being put in the correct buckets\n cur.execute('SELECT * FROM \"0\".new_table20 WHERE number < -2 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -2[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table20 WHERE number < 43 AND number > 28 '\n 'AND number_categorical <> \\'[28 , 43[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n\n #Let's simulate equifrequent discretization with our custom bins.\n ranges = [-17, 4, 9, 15, 42]\n self.test_object.discretize_using_custom_ranges('test_table', 'number', ranges, True, 'new_table21')\n result = self.__test_table_exists('new_table21')\n self.assertTrue(result)\n cur.execute('SELECT DISTINCT number_categorical FROM \"0\".new_table21')\n self.db_connection.commit()\n all_values = cur.fetchall()\n all_values = [x[0] for x in all_values]\n all_values = sorted(all_values)\n expected_values = ['[-17 , 4[', '[15 , 42[', '[4 , 9[', '[9 , 15[']\n #There should be 4 buckets\n self.assertEqual(len(all_values), 4)\n self.assertEqual(all_values, expected_values)\n cur.execute('SELECT * FROM \"0\".new_table21 WHERE number < -4 AND number > -17 '\n 'AND number_categorical <> \\'[-17 , -4[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n cur.execute('SELECT * FROM \"0\".new_table21 WHERE number < 42 AND number > 15 '\n 'AND number_categorical <> \\'[15 , 42[\\'')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n \n def test_delete_outliers(self):\n \"\"\"Test the method of TableTransformer to delete outliers. This will result in a new table.\"\"\"\n #Test outliers larger than presented value\n cur = self.db_connection.cursor()\n self.test_object.delete_outliers('test_table', 'number', True, 40, 0, 'new_table22')\n result = self.__test_table_exists('new_table22')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table22 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n self.test_object.delete_outliers('test_table', 'number', True, 20, 0, 'new_table23')\n result = self.__test_table_exists('new_table23')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table23 WHERE number > 20')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n #Test outliers smaller than presented value\n self.test_object.delete_outliers('test_table', 'number', False, -15, 0, 'new_table24')\n result = self.__test_table_exists('new_table24')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table24 WHERE number < -15')\n result = cur.fetchone()\n self.assertIsNone(result)\n\n self.test_object.delete_outliers('test_table', 'number', False, 0, 0, 'new_table25')\n result = self.__test_table_exists('new_table25')\n self.assertTrue(result)\n cur.execute('SELECT * FROM \"0\".new_table25 WHERE number < 0')\n result = cur.fetchone()\n self.assertIsNone(result)\n self.db_connection.commit()\n \n def test_fill_nulls_with_mean(self):\n \"\"\"Test the method of TableTransformer that fills null values with the mean. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_mean('test_table1', 'number', 'new_table26')\n result = self.__test_table_exists('new_table26')\n self.assertTrue(result)\n #Test if it's really set to null\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n #Test whether any nulls are left open\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number is null')\n result = cur.fetchone()\n self.assertIsNone(result)\n #The mean by excluding values > 40 is 10 (cast to int), let's check if the value is here\n cur.execute('SELECT * FROM \"0\".new_table26 WHERE number = 10 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n self.assertEqual(1,1)\n \n def test_fill_nulls_with_median(self):\n \"\"\"Test the method of TableTransformer that fills null values with the median. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_median('test_table1', 'number', 'new_table27')\n result = self.__test_table_exists('new_table27')\n self.assertTrue(result)\n #Test if it's really set to null\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number > 40')\n result = cur.fetchone()\n self.assertIsNone(result)\n #Test whether any nulls are left open\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number is null')\n result = cur.fetchone()\n self.assertIsNone(result)\n #The median by excluding values > 40 is 9, let's check if the value is here\n cur.execute('SELECT * FROM \"0\".new_table27 WHERE number = 9 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n \n def test_fill_nulls_with_custom_value(self):\n \"\"\"Test the method of TableTransformer that fills null values with a custom value.\"\"\"\n cur = self.db_connection.cursor()\n self.test_object.fill_nulls_with_custom_value('test_table1', 'number', 10000, 'new_table28')\n result = self.__test_table_exists('new_table28')\n self.assertTrue(result)\n #The value we used should correspond to the row with string = 'Dummy'\n cur.execute('SELECT * FROM \"0\".new_table28 WHERE number = 10000 AND string = \\'Elevate ltd\\'')\n result = cur.fetchall()\n self.assertIsNotNone(result)\n \n def test_delete_rows_using_conditions(self):\n \"\"\"Test method of TableTransformer deletes rows by using provided predicates. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n predicate1 = ['string', '=', 'C-Corp']\n self.test_object.delete_rows_using_predicate_logic('test_table', predicate1, 'new_table29')\n result = self.__test_table_exists('new_table29')\n self.assertTrue(result)\n query = \"SELECT * FROM \\\"0\\\".new_table29 WHERE string = 'C-Corp'\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNone(result)\n\n predicate2 = ['string', '=', 'Nokia', 'AND', 'number', '=', '18', 'AND', 'date_time', '!=', '01/01/2001']\n self.test_object.delete_rows_using_predicate_logic('test_table', predicate2, 'new_table30')\n result = self.__test_table_exists('new_table30')\n self.assertTrue(result)\n query = \"SELECT * FROM \\\"0\\\".new_table30 WHERE string = 'Nokia' AND number = 18\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNone(result)\n \n def test_datetime_extraction(self):\n \"\"\"This one is for testing the extraction of parts of the date/time done by TableTransformer. This will result in a new table.\"\"\"\n cur = self.db_connection.cursor()\n cur.execute('ALTER TABLE \"0\".test_table2 ALTER COLUMN date_time TYPE DATE USING to_date(date_time , \\'DD/MM/YYYY\\')')\n self.test_object.extract_part_of_date('test_table2', 'date_time', 'MONTH', 'new_table31')\n result = self.__test_table_exists('new_table31')\n self.assertTrue(result)\n #Get all the column names for the table\n query = (\"SELECT column_name FROM information_schema.columns \"\n \"WHERE table_schema = '0' AND table_name = 'new_table31'\")\n cur.execute(query)\n all_columns = cur.fetchall()\n result = False\n \n for elem in all_columns:\n if elem[0] == 'date_time_part':\n result = True\n\n self.assertTrue(result)\n\n query = \"SELECT * FROM \\\"0\\\".new_table31 WHERE number = 21 AND date_time_part = 'September'\"\n cur.execute(query)\n result = cur.fetchone()\n self.assertIsNotNone(result)\n self.assertEqual(result[0], 'Nintendo')\n","sub_path":"client/unit_tests/test_TableTransformerCopy.py","file_name":"test_TableTransformerCopy.py","file_ext":"py","file_size_in_byte":26409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"158403572","text":"from datetime import datetime;\nfrom os.path import isfile as isFile;\n\nclass Logger:\n\n def __init__(self, log_filename_postfix = \"log\", log_filename_extension = \"log\", path_to_log = \".\"):\n\n self.log_filename_postfix = log_filename_postfix;\n self.log_filename_extension = log_filename_extension;\n self.path_to_log = path_to_log;\n self.initLogFile();\n\n return None;\n\n def initLogFile(self, log_filename_postfix = None, \\\n log_filename_extension = None, \\\n path_to_log = None):\n \"\"\" PRIVATE \"\"\"\n\n if not log_filename_postfix:\n log_filename_postfix = self.log_filename_postfix;\n\n if not log_filename_extension:\n log_filename_extension = self.log_filename_extension;\n\n if not path_to_log:\n path_to_log = self.path_to_log;\n\n self.the_day = self.timeStamp()[:10];\n self.log_file_name = \"{}/{}_{}.{}\".\\\n format(\n path_to_log,\n self.the_day,\n log_filename_postfix,\n log_filename_extension\n );\n if not isFile(self.log_file_name):\n self.writeDown(\"The log file created. \\n ----------------------------------------------- \\n\\n\");\n\n def timeStamp(self, digits_after_dot = 2):\n \"\"\" PRIVATE \"\"\"\n full_string_of_time_stamp = str(datetime.now());\n\n if digits_after_dot >= 6:\n string_of_time_stamp = full_string_of_time_stamp;\n else:\n if digits_after_dot <=0:\n cut_mark = -7;\n else:\n cut_mark = digits_after_dot - 6;\n string_of_time_stamp = full_string_of_time_stamp[:cut_mark];\n\n return string_of_time_stamp;\n\n def writeDown(self, message_string):\n\n the_timestamp = self.timeStamp();\n the_day = the_timestamp[:10];\n if the_day != self.the_day:\n self.initLogFile();\n\n log_string = \"{}: {} \\n\\n\".\\\n format(\n self.timeStamp(),\n message_string\n );\n\n print(log_string);\n with open(self.log_file_name, \"a\") as log_file:\n log_file.write(log_string);\n\n return None;\n","sub_path":"rhythmic/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"573262261","text":"import configparser,tweepy,string\n\nclass tweets_dld:\n #global variables for twitter API authentication \n c_key = ''\n c_secret = ''\n a_token = ''\n a_secret = ''\n query_hashtags = ''\n\n def __init__(self):\n #read auth variables from config file\n config = configparser.RawConfigParser()\n config.read('auth_secrets.properties')\n global c_key,c_secret,a_token,a_secret,query_hashtags\n '''c_key = config.get('OAUTH_SECRETS FOR TWITTER DEV','CONSUMER_KEY')\n c_secret = config.get('OAUTH_SECRETS FOR TWITTER DEV','CONSUMER_SECRET') \n a_token = config.get('OAUTH_SECRETS FOR TWITTER DEV','ACCESS_TOKEN')\n a_secret = config.get('OAUTH_SECRETS FOR TWITTER DEV','ACCESS_SECRET')\n\n #hashtags or twitter handles to be searched for \n query_hashtags = config.get('INPUTS FOR COMMAND_LINE','TWITTER_HASHTAGS')'''\n c_key = 'VasRnWFD11likduxgFlMVDtbb'\n c_secret = 'fhMWY43TKctq9F75FjUF132kDOdlNpxDPRdYUSl0hB4gHJWXFL'\n a_token = '1193177629-XCk9qe8vvazKzL5dx6tJWoOU8uNfftJWczD3n2x'\n a_secret = 'yTZi285mwLZJ2LJjh51c6AvkcnfbptJxgjQUQjBKgY8jW'\n \n query_hashtags = '#sunRail OR ExpandSunRail OR sunRail OR Sunrailriders OR RideSunRail OR #RideSunRail OR #Ridesunrail +exclude:retweets'\n\n def gather_tweets(self):\n #print('reached tweet download')\n #authenticate twitter API access using the credentials populated above\n auth = tweepy.auth.OAuthHandler(c_key, c_secret)\n auth.set_access_token(a_token, a_secret)\n api = tweepy.API(auth)\n\n # initialize a list to hold all the tweepy Tweets\n alltweets = []\n\n # make initial request for most recent tweets (200 is the maximum allowed count)\n new_tweets = api.search(q=query_hashtags, count=10)\n #print(new_tweets)\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # save the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n # keep grabbing tweets until there are no tweets left to grab\n while len(new_tweets) > 0:\n #print(\"getting tweets before %s\" % (oldest))\n\n # all subsiquent requests use the max_id param to prevent duplicates\n new_tweets = api.search(q=query_hashtags, max_id=oldest)\n #print(new_tweets)\n # save most recent tweets\n alltweets.extend(new_tweets)\n\n # update the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n\n #print(\"...%s tweets downloaded so far\" % (len(alltweets)))\n\n #list of tweets with selected attributes like URLs, Hashtags, text etc.\n #outtweets = [[tweet.id, ascii(tweet.text), tweet.created_at, tweet.retweet_count, tweet.entities['urls'], tweet.entities['hashtags']] for tweet in alltweets]\n\n outtweets = {}\n tweetObjList = []\n for tweet in alltweets:\n tweetObjMap = {}\n tweetObjMap['tweet_id'] = tweet.id\n tweetObjMap['text'] = ascii(tweet.text)\n tweetObjMap['created_at'] = tweet.created_at\n tweetObjMap['retweet_count'] = tweet.retweet_count\n tweetObjMap['urls'] = tweet.entities['urls']\n tweetObjMap['hashtags'] = tweet.entities['hashtags']\n tweetObjList.append(tweetObjMap)\n\n outtweets['tweetObj'] = tweetObjList\n return outtweets\n \n","sub_path":"WebContent/Tweepy-Client/TweetDld.py","file_name":"TweetDld.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"282631925","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 20 14:12:25 2018\n\n@author: Donghyun Kang\n\"\"\"\nimport pytest\n\ndef operate(a, b, oper):\n \"\"\"Apply an arithmetic operation to a and b.\"\"\"\n if type(oper) is not str:\n raise TypeError(\"oper must be a string\")\n elif oper == '+':\n return a + b\n elif oper == '-':\n return a - b\n elif oper == '*':\n return a * b\n elif oper == '/':\n if b == 0:\n raise ZeroDivisionError(\"division by zero is undefined\")\n return a / b\n raise ValueError(\"oper must be one of '+', '/', '-', or '*'\")\n \ndef test_operate():\n with pytest.raises(TypeError) as typeinfo:\n operate(1, 1, 2)\n assert typeinfo.value.args[0] == \"oper must be a string\"\n\n with pytest.raises(TypeError) as typeinfo:\n operate(1, 1, [1,2])\n assert typeinfo.value.args[0] == \"oper must be a string\"\n\n assert operate(4, 3, \"+\") == 7\n assert operate(4, 3, \"-\") == 1\n assert operate(4, 3, \"*\") == 12\n assert operate(12, 3, \"/\") == 4\n \n with pytest.raises(ZeroDivisionError) as zero:\n operate(12, 0, \"/\") == 4 \n assert zero.value.args[0] == \"division by zero is undefined\" \n \n with pytest.raises(ValueError) as v_err:\n operate(1, 2, \"a\")\n assert v_err.value.args[0] == \"oper must be one of '+', '/', '-', or '*'\"\n \n \n \n \n \n","sub_path":"Assignments/A7/P3_test.py","file_name":"P3_test.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"67639721","text":"# Method could be a function\n# pylint: disable=R0201\n# Too many public methods\n# pylint: disable=R0904\n# Missing docstring\n# pylint: disable=C0111\n\nfrom tempfile import NamedTemporaryFile\nimport unittest\n\nfrom ete3 import Tree\n\n\nfrom variation.clustering import (do_tree, get_subtrees, annotate_tree,\n write_tree_to_nexus_file, FigtreeConfig)\n\n\nclass ClusteringTest(unittest.TestCase):\n def test_upgma(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"upgma\")\n newick_tree = \"((((H,C):0.73,G):0.77,O):1.49,R):3.69;\"\n expected_tree = Tree(newick_tree)\n result = expected_tree.compare(tree)\n assert result[\"source_edges_in_ref\"] - 1 < 0.00001\n assert result[\"ref_edges_in_source\"] - 1 < 0.00001\n\n def test_nj(self):\n dists = [5, 9, 10, 9, 10, 8, 8, 9, 7, 3]\n labels = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n tree = do_tree(dists, labels, method=\"nj\")\n newick_tree = \"(C:2,((A:2,B:3):3,(D:2,E:1):2):2);\"\n expected_tree = Tree(newick_tree)\n result = expected_tree.compare(tree, unrooted=True)\n assert result[\"source_edges_in_ref\"] - 1 < 0.00001\n assert result[\"ref_edges_in_source\"] - 1 < 0.00001\n\n def test_cluster_selection_by_cutoff(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n ultrametric_length = 10\n tree = do_tree(dists, labels, method=\"upgma\")\n tree.convert_to_ultrametric(tree_length=ultrametric_length)\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=4)}\n assert leaves == {frozenset({'O'}), frozenset({'C', 'H', 'G'}),\n frozenset({'R'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=0)}\n assert leaves == {frozenset({'C', 'H', 'G', 'O', 'R'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=15)}\n assert not leaves\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=7)}\n assert leaves == {frozenset({'R'}), frozenset({'G'}),\n frozenset({'C', 'H'}), frozenset({'O'})}\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=8)}\n assert leaves == {frozenset({'R'}), frozenset({'C'}),\n frozenset({'H'}), frozenset({'O'}),\n frozenset({'G'})}\n\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"nj\")\n\n leaves = {frozenset(node.get_leaf_names())\n for node in get_subtrees(tree, dist_treshold=4)}\n assert leaves == {frozenset({'R'})}\n\n def test_draw_figtree(self):\n dists = [1.45, 1.51, 1.57, 2.98, 2.94, 3.04, 7.51, 7.55, 7.39, 7.10]\n labels = [\"H\", \"C\", \"G\", \"O\", \"R\"]\n tree = do_tree(dists, labels, method=\"nj\")\n leaf_annotations = {\"R\": {\"group1\": \"A\", \"group2\": \"C\", \"group3\": \"A\"},\n \"O\": {\"group1\": \"A\", \"group2\": \"A\", \"group3\": \"A\"},\n \"H\": {\"group1\": \"B\", \"group2\": \"B\", \"group3\": \"B\"},\n \"C\": {\"group1\": \"B\", \"group2\": \"A\", \"group3\": \"B\"},\n \"G\": {\"group1\": \"C\", \"group2\": \"D\", \"group3\": \"B\"}\n }\n annotate_tree(tree, leaf_annotations)\n figtree_config = FigtreeConfig(branch_color_attribute=\"group1\",\n leaf_label_color_attribute=\"group2\",\n )\n with NamedTemporaryFile(mode=\"w\") as test_fhand:\n write_tree_to_nexus_file(tree, test_fhand,\n figtree_config=figtree_config)\n test_fhand.flush()\n fhand = open(test_fhand.name, \"r\")\n test_string = fhand.read()\n fhand.close()\n tree_string = test_string.split(\";\")[5]\n leaves = tree_string.split(\"],\")\n assert \"H:0.71[&\" in leaves[0]\n assert \"group1=B\" in leaves[0]\n assert \"G:0.755[&\" in leaves[2]\n assert \"group1=C\" in leaves[2]\n assert \"set appearance.branchColorAttribute=\\\"group1\\\";\" in test_string\n assert \"set tipLabels.colorAttribute=\\\"group2\\\";\" in test_string\n\n figtree_config = FigtreeConfig(branch_color_attribute=\"group1\")\n chosen_features = [\"group1\", \"group2\"]\n with NamedTemporaryFile(mode=\"w\") as test_fhand:\n write_tree_to_nexus_file(tree, test_fhand,\n figtree_config=figtree_config,\n chosen_features=chosen_features)\n test_fhand.flush()\n fhand = open(test_fhand.name, \"r\")\n test_string = fhand.read()\n fhand.close()\n tree_string = test_string.split(\";\")[5]\n leaves = tree_string.split(\"],\")\n assert \"group1=A\" in leaves[2]\n assert \"set appearance.branchColorAttribute=\\\"group1\\\";\" in test_string\n assert \"set tipLabels.colorAttribute=\\\"group2\\\";\" not in test_string\n assert \"group3\" not in leaves[0]\n assert \"group3\" not in leaves[2]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_clustering.py","file_name":"test_clustering.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"555663007","text":"import re,glob\n\ndef change_file(file):\n\tprint(file);\n\tfp = open(file, 'r');\n\tdata = [];\n\tfor line in fp:\n\t\tmatch = re.search('#import.*\"(?P.+)\"', line);\n\t\tif match:\n\t\t\theader = match.group('header');\n\t\t\tif header == 'cocos2d.h':\n\t\t\t\tcontinue;\n\t\t\tdata.append('#include \"{0}\"\\n'.format(header));\n\t\t\tcontinue;\n\n\t\tmatch = re.search('@interface *(?P\\S+)\\s*:\\s*(?P\\S+)\\s*{*', line);\n\t\tif match:\n\t\t\tclass_name = match.group('class');\n\t\t\tbase_name = match.group('base');\n\t\t\tif base_name == 'NSObject':\n\t\t\t\tbase_name = 'CCObject';\n\t\t\tdata.append('class {0} : public {1}\\n'.format(class_name, base_name));\n\t\t\tdata.append('{\\n');\n\t\t\tcontinue;\n\t\tif re.search('@end', line):\n\t\t\tdata.append('};\\n');\n\t\t\tcontinue;\n\n\t\tmatch = re.search('-\\((?P\\w+)\\)\\s*(?P\\w+);', line);\n\t\tif match:\n\t\t\treturn_value = match.group('return');\n\t\t\tfunc = match.group('func');\n\t\t\tdata.append('\t{0} {1}();\\n'.format(return_value, func));\n\t\t\tcontinue;\n\t\tdata.append(line);\n\tfp.close();\n\n\tfpw = open(file, 'w');\n\tfpw.writelines(data);\n\tfpw.close();\n\ndef change_all(path):\n\tfile_list = glob.glob(\"./*.h\");\n\tfor file in file_list:\n\t\tchange_file(file);\n\t\tbreak;\n\n\nchange_all('');","sub_path":"ccfd/Classes/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"352199085","text":"\"\"\"\n驗證單字是否有拼錯\n\"\"\"\n\nfrom googletrans import Translator\nimport csv\nimport sys\nimport xlrd\n\n\ndef readExcel(filename):\n workbook = xlrd.open_workbook(filename)\n sheet = workbook.sheet_by_index(0)\n card_lst = []\n for rowx in range(sheet.nrows):\n cols = sheet.row_values(rowx)\n print(cols)\n card_lst.append(cols)\n return card_lst\n\n\nankitxtfile = 'Feb.4.xlsx'\n\nif not len(sys.argv) < 2:\n ankitxtfile = sys.argv[1]\n\nif ankitxtfile.find('xls') > 1:\n pkgname = ankitxtfile.replace('.xlsx', '').replace('.xls', '')\n card_lst = readExcel(ankitxtfile)\nelse:\n pkgname = ankitxtfile.replace('.txt', '')\n with open(ankitxtfile, 'r', encoding='utf8') as f:\n cardstr = f.read()\n card_lst = list(csv.reader(cardstr.splitlines(), delimiter='\\t'))\n\ntranslator = Translator()\n\nfor c in card_lst:\n c.append(translator.translate(c[0], dest='zh-TW').text)\n\nwith open('verification_' + pkgname + '.csv', mode='w', encoding='utf-8-sig', newline='') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerows(card_lst)\n","sub_path":"anki01/GetTranslation.py","file_name":"GetTranslation.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"77942797","text":"''' Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:\n\n– IMC abaixo de 18,5: Abaixo do Peso\n\n– Entre 18,5 e 25: Peso Ideal\n\n– 25 até 30: Sobrepeso\n\n– 30 até 40: Obesidade\n\n– Acima de 40: Obesidade Mórbida '''\n\npeso = float(input('Peso em kg: (Exemplo: 78.5) '))\naltura = float(input('Altura em m: (Exemplo: 1.75) '))\nimc = peso / (altura * altura)\nif imc < 18.5:\n faixa = 'ABAIXO DO PESO'\nelif imc >= 18.5 and imc < 25:\n faixa = 'PESO IDEAL'\nelif imc >= 25 and imc < 30:\n faixa = 'SOBREPESO'\nelif imc >= 30 and imc < 40:\n faixa = 'OBESIDADE'\nelse:\n faixa = 'OBESIDADE MÓRBIDA'\nprint(f'''Seu peso é {peso:.1f} kg e sua altura é {altura:.2f} m. \nO IMC é {imc:.1f} e sua faixa é: {faixa}.''')\n","sub_path":"exercicio043.py","file_name":"exercicio043.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"346963336","text":"from __future__ import annotations\n\nimport contextlib\nimport csv\nimport os\nfrom typing import TYPE_CHECKING\n\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.template import loader\n\nfrom hunt.hint_request import maybe_release_hint, prepare_next_hint, request_hint\nfrom hunt.level_mgr import upload_new_level\nfrom hunt.levels import list_levels, look_for_level, maybe_load_level\nfrom hunt.models import AppSetting, HuntEvent\nfrom hunt.utils import max_level, no_players_during_lockout\n\nif TYPE_CHECKING:\n from django.http.request import HttpRequest\n\n from hunt.utils import AuthenticatedHttpRequest\n\n\n# Send users to the hunt and admins to management.\n@login_required\n@no_players_during_lockout\ndef go_home(request: AuthenticatedHttpRequest) -> HttpResponse:\n if request.user.is_staff:\n return redirect(\"/mgmt\")\n\n return redirect(\"/home\")\n\n\n# Admin-only page to download hunt event logs.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef get_hunt_events(_request: HttpRequest) -> HttpResponse:\n meta = HuntEvent._meta\n field_names = [field.name for field in meta.fields]\n\n response = HttpResponse(content_type=\"text/csv\")\n response[\"Content-Disposition\"] = f\"attachment; filename={meta}.csv\"\n writer = csv.writer(response)\n\n writer.writerow(field_names)\n\n queryset = HuntEvent.objects.all()\n for obj in queryset:\n writer.writerow([getattr(obj, field) for field in field_names])\n\n return response\n\n\n# Hunt homepage.\n@login_required\n@no_players_during_lockout\ndef home(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"welcome.html\")\n\n # Staff can see all levels.\n user = request.user\n team_level = max_level() if user.is_staff else user.huntinfo.level\n\n context = {\"display_name\": user.get_username(), \"team_level\": team_level}\n return HttpResponse(template.render(context, request))\n\n\n# Level page.\n@login_required\n@no_players_during_lockout\ndef level(request: AuthenticatedHttpRequest, level: int) -> HttpResponse:\n # Release a hint, if appropriate.\n user = request.user\n maybe_release_hint(user)\n\n # Prepare the next hint, if appropriate.\n hunt_info = user.huntinfo\n if hunt_info.next_hint_release is None:\n prepare_next_hint(hunt_info)\n\n # Show the level.\n return HttpResponse(maybe_load_level(request, level))\n\n\n# Error page.\n@login_required\n@no_players_during_lockout\ndef oops(request: AuthenticatedHttpRequest) -> HttpResponse:\n # Shouldn't be here. Show an error page.\n template = loader.get_template(\"oops.html\")\n context = {\"team_level\": request.user.huntinfo.level}\n\n # Return the rendered template.\n return HttpResponse(template.render(context, request))\n\n\n# Map (or alt map).\n@login_required\n@no_players_during_lockout\ndef map(request: AuthenticatedHttpRequest) -> HttpResponse:\n # If we're configured to use the alt map, do so.\n settings = None\n with contextlib.suppress(AppSetting.DoesNotExist):\n settings = AppSetting.objects.get(active=True)\n\n use_alternative_map = False if settings is None else settings.use_alternative_map\n if use_alternative_map:\n return alt_map(request)\n\n # If we don't have a Google Maps API key, use the alt map.\n gm_api_key = os.environ.get(\"GM_API_KEY\")\n if gm_api_key is None:\n return alt_map(request)\n\n # Use the Google map.\n template = loader.get_template(\"google-map.html\")\n context = {\"api_key\": gm_api_key, \"lvl\": request.GET.get(\"lvl\")}\n\n return HttpResponse(template.render(context, request))\n\n\n# Alt map.\n@login_required\n@no_players_during_lockout\ndef alt_map(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"alternate-map.html\")\n arcgis_api_key = os.environ.get(\"ARCGIS_API_KEY\")\n context = {\"api_key\": arcgis_api_key, \"lvl\": request.GET.get(\"lvl\")}\n return HttpResponse(template.render(context, request))\n\n\n# Level list.\n@login_required\n@no_players_during_lockout\ndef levels(request: AuthenticatedHttpRequest) -> HttpResponse:\n return HttpResponse(list_levels(request))\n\n\n# Search request endpoint.\n@login_required\n@no_players_during_lockout\ndef do_search(request: AuthenticatedHttpRequest) -> HttpResponse:\n return redirect(look_for_level(request))\n\n\n# Coordinate search page.\n@login_required\n@no_players_during_lockout\ndef search(request: AuthenticatedHttpRequest) -> HttpResponse:\n lvl = request.GET.get(\"lvl\")\n\n template = loader.get_template(\"search.html\")\n context = {\"lvl\": lvl}\n\n return HttpResponse(template.render(context, request))\n\n\n# Nothing here.\n@login_required\n@no_players_during_lockout\ndef nothing(request: AuthenticatedHttpRequest) -> HttpResponse:\n template = loader.get_template(\"nothing.html\")\n\n team_level = request.user.huntinfo.level\n lvl = request.GET.get(\"lvl\")\n search_level = None if lvl is None else int(lvl)\n\n context = {\"team_level\": team_level, \"search_level\": search_level}\n return HttpResponse(template.render(context, request))\n\n\n# Request a hint.\n@login_required\n@no_players_during_lockout\ndef hint(request: AuthenticatedHttpRequest) -> HttpResponse:\n return redirect(request_hint(request))\n\n\n# Management home.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef mgmt(request: HttpRequest) -> HttpResponse:\n template = loader.get_template(\"mgmt.html\")\n\n context = {\"success\": request.GET.get(\"success\")}\n return HttpResponse(template.render(context, request))\n\n\n# Level uploader page.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef level_mgmt(request: HttpRequest) -> HttpResponse:\n template = loader.get_template(\"level-mgmt.html\")\n next_level = request.GET.get(\"next\", 1)\n\n context = {\"success\": request.GET.get(\"success\"), \"next\": next_level}\n return HttpResponse(template.render(context, request))\n\n\n# Upload level endpoint.\n@user_passes_test(lambda u: u.is_staff) # type: ignore[union-attr]\ndef add_new_level(request: HttpRequest) -> HttpResponse:\n return redirect(upload_new_level(request))\n","sub_path":"hunt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"35887260","text":"import os\nimport sys\n\nimport environ\n\nfrom django.utils.translation import gettext_lazy as _\n\nbase_dir = environ.Path(__file__) - 3\nlive_dir = base_dir.path('.live')\n\nPROJECT_ALIAS = 'project'\nPROJECT_DISPLAY_NAME = 'Project'\n\n# Defaults\nenv = environ.Env(\n DEBUG=(bool, False),\n EMAIL_BACKEND=(str, 'django.core.mail.backends.smtp.EmailBackend'),\n EMAIL_HOST=(str, 'localhost'),\n EMAIL_HOST_USER=(str, ''),\n EMAIL_HOST_PASSWORD=(str, ''),\n EMAIL_PORT=(int, 25),\n EMAIL_USE_TLS=(bool, False),\n EMAIL_USE_SSL=(bool, False),\n SERVER_EMAIL=(str, 'root@localhost'),\n DEFAULT_FROM_EMAIL=(str, 'info@localhost'),\n EMAIL_SUBJECT_PREFIX=(str, PROJECT_DISPLAY_NAME),\n DATABASE_HOST=(str, 'localhost'),\n DATABASE_PORT=(str, ''),\n DATABASE_MAX_CONNS=(int, 20),\n ADMINS=(list, []),\n SHOW_DEBUG_TOOLBAR=(bool, False),\n LOAD_EXTERNAL_REFS=(bool, True),\n)\n\nenviron.Env.read_env(base_dir('.env'))\nsys.path.append(base_dir('apps'))\n\nDEBUG = env('DEBUG')\nSECRET_KEY = env('SECRET_KEY')\nALLOWED_HOSTS = ['*']\nINTERNAL_IPS = (\n '127.0.0.1',\n '0.0.0.0',\n)\nSITE_ID = 1\n\n# Follow this convention, but ignore in corner cases:\n# 1. Django\n# 2. Debug/testing\n# 3. Third party\n# 4. Local\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'debug_toolbar',\n 'hijack',\n 'compat',\n\n 'corsheaders',\n 'parler',\n 'sekizai',\n\n 'users',\n 'common',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'htmlmin.middleware.HtmlMinifyMiddleware',\n 'htmlmin.middleware.MarkRequestMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\n\n# =============================================================================\n# Templates\n# =============================================================================\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n base_dir('templates'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'sekizai.context_processors.sekizai',\n ],\n 'debug': DEBUG,\n },\n },\n]\n\nALLOWABLE_TEMPLATE_SETTINGS = ('DEBUG', 'LOAD_EXTERNAL_REFS', 'PROJECT_DISPLAY_NAME')\n\nHTML_MINIFY = not DEBUG\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': lambda req: (\n req.environ.get('SERVER_NAME', None) != 'testserver' and\n req.META.get('REMOTE_ADDR', None) in INTERNAL_IPS and\n DEBUG and\n env('SHOW_DEBUG_TOOLBAR')\n ),\n}\n\n\n# =============================================================================\n# Database\n# =============================================================================\n\n# CONN_MAX_AGE must be set to 0, or connections will never go back to the pool\nDATABASES = {\n 'default': {\n 'ENGINE': 'django_db_geventpool.backends.postgresql_psycopg2',\n 'NAME': env('DATABASE_NAME'),\n 'USER': env('DATABASE_USER'),\n 'PASSWORD': env('DATABASE_PASSWORD'),\n 'HOST': env('DATABASE_HOST'),\n 'PORT': env('DATABASE_PORT'),\n 'ATOMIC_REQUESTS': False,\n 'CONN_MAX_AGE': 0,\n 'OPTIONS': {\n 'MAX_CONNS': env('DATABASE_MAX_CONNS'),\n },\n }\n}\n\n\n# =============================================================================\n# Auth\n# =============================================================================\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nAUTH_USER_MODEL = 'users.User'\nLOGIN_REDIRECT_URL = '/'\n\n\n# =============================================================================\n# i18n/l10n\n# =============================================================================\n\nLANGUAGE_CODE = 'en'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nLANGUAGES = [\n ('en', _('English')),\n]\n\nLOCALE_PATHS = [base_dir('locale')]\n\nPARLER_LANGUAGES = {\n SITE_ID: (\n {'code': 'en',},\n ),\n}\n\n\n# =============================================================================\n# Static and media\n# =============================================================================\n\nSTATICFILES_DIRS = [\n base_dir('static'),\n]\n\nSTATIC_ROOT = live_dir('static')\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = live_dir('media')\nMEDIA_URL = '/media/'\n\nif not DEBUG:\n # Add WhiteNoiseMiddleware immediately after SecurityMiddleware.\n # Avoid using whitenoise. Configure a server to provide static.\n # Use whitenoise only in corner cases or for debugging purposes.\n index = MIDDLEWARE.index('django.middleware.security.SecurityMiddleware')\n MIDDLEWARE.insert(index + 1, 'whitenoise.middleware.WhiteNoiseMiddleware')\n\nLOAD_EXTERNAL_REFS = env('LOAD_EXTERNAL_REFS')\n\n\n# =============================================================================\n# Mailing\n# =============================================================================\n\nEMAIL_BACKEND = env('EMAIL_BACKEND')\nEMAIL_HOST = env('EMAIL_HOST')\nEMAIL_HOST_USER = env('EMAIL_HOST_USER')\nEMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')\nEMAIL_PORT = env('EMAIL_PORT')\nEMAIL_USE_TLS = env('EMAIL_USE_TLS')\nEMAIL_USE_SSL = env('EMAIL_USE_SSL')\nSERVER_EMAIL = env('SERVER_EMAIL') # Email to send error messages\nDEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL')\nEMAIL_SUBJECT_PREFIX = env('EMAIL_SUBJECT_PREFIX')\n\n\n# =============================================================================\n# Caches\n# =============================================================================\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}\n\n\n# =============================================================================\n# Hijack\n# =============================================================================\n\nHIJACK_LOGIN_REDIRECT_URL = '/admin/'\nHIJACK_LOGOUT_REDIRECT_URL = HIJACK_LOGIN_REDIRECT_URL\nHIJACK_ALLOW_GET_REQUESTS = True\n\n\n# =============================================================================\n# Fixtures\n# =============================================================================\n\nFIXTURE_DIRS = [\n base_dir('fixtures'),\n]\n\n\n# See apps/common/management/commands/pushfixtures.py\nFIXTURES = [\n# 'file.json',\n]\n\n\n# =============================================================================\n# Others\n# =============================================================================\n\nROOT_URLCONF = 'core.urls'\nWSGI_APPLICATION = 'core.wsgi.application'\n\nCORS_ORIGIN_ALLOW_ALL = True\n\nADMINS = []\nadmins = env('ADMINS')\nfor admin in admins:\n ADMINS.append(admin.split(':'))\n","sub_path":"{{cookiecutter.project_slug}}/core/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"86073947","text":"# Copyright 2020 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport pytest\nfrom lgbserver import LightGBMModelRepository\n\nmodel_dir = os.path.join(os.path.dirname(__file__), \"example_model\")\ninvalid_model_dir = os.path.join(os.path.dirname(__file__), \"model_not_exist\", \"model\")\n\n\n@pytest.mark.asyncio\nasync def test_load():\n repo = LightGBMModelRepository(model_dir=model_dir, nthread=1)\n model_name = \"model\"\n await repo.load(model_name)\n assert repo.get_model(model_name) is not None\n assert repo.is_model_ready(model_name)\n\n\n@pytest.mark.asyncio\nasync def test_load_fail():\n repo = LightGBMModelRepository(model_dir=model_dir, nthread=1)\n model_name = \"model\"\n with pytest.raises(Exception):\n await repo.load(model_name)\n assert repo.get_model(model_name) is None\n assert not repo.is_model_ready(model_name)\n","sub_path":"python/lgbserver/lgbserver/test_lightgbm_model_repository.py","file_name":"test_lightgbm_model_repository.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"363128828","text":"from typing import TypeVar\n\nfrom aiohttp.web import Application, RouteTableDef\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom nekitdev.constants import ROOT_ROUTE, STATIC, STATIC_NAME, TEMPLATES\n\n__all__ = (\"environment\", \"routes\", \"setup_app\")\n\nenvironment = Environment(\n loader=FileSystemLoader(TEMPLATES),\n trim_blocks=True,\n lstrip_blocks=True,\n enable_async=True,\n)\n\nroutes = RouteTableDef()\n\nroutes.static(ROOT_ROUTE + STATIC_NAME, STATIC)\n\n\nA = TypeVar(\"A\", bound=Application)\n\n\ndef setup_app(app: A) -> A:\n app.add_routes(routes)\n\n return app\n","sub_path":"nekitdev/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"412382196","text":"from django.conf.urls import patterns, url\n\nfrom .views import *\n\nurlpatterns = patterns(\n '',\n url(r'^callback/$', CallBackFormView.as_view(), name='callback'),\n url(r'^appointment/$', AppointmentFormView.as_view(), name='appointment'),\n url(r'^email/$', EmailFormView.as_view(), name='email'),\n url(r'^confirmation/$', Confirmation.as_view(), name='confirmation'),\n)\n","sub_path":"mailchimp_forms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"612475621","text":"from __future__ import division\n\nfrom ml.rbm.config import TrainingConfiguration\nfrom math import sqrt\n\nimport ml.rbm.orrbm\n\n# RBM configuration\nn_vis=784\nn_hid=5000\nrbm_cfg = TrainingConfiguration(dataset='mnistv',\n n_vis=n_vis, n_hid=n_hid,\n batch_size=20,\n n_gibbs_steps=15,\n epochs=30,\n step_rate=0.1,\n use_pcd=True,\n binarize_data='round',\n initial_momentum=0, final_momentum=0, \n use_final_momentum_from_epoch=0,\n weight_cost=0,\n init_method='uniform', \n init_weight_sigma=4 * sqrt(6. / (n_hid + n_vis)), \n init_bias_sigma=0,\n seed=1)\n\n# Classifier\nclassifier='mlp'\n\n# ORRBM\nn_samples = 10000\niters = 20\nk = 10\nbeta = 2\n\n# dataset\nby = ml.rbm.orrbm.base_y\noverlaps = [(0, by), (5, by), (10, by), (15, by)]\n\n\n\n","sub_path":"ml/apps/orrbm_shiftstat/basic/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"557539959","text":"from flask import Flask\nfrom datastore import db\nfrom flask_restful import Api\nfrom handlers import *\nfrom models import *\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom handlers.generate_prediction import *\n\n\ndef _init_app():\n app = Flask(__name__)\n app.config.from_pyfile(\"config.py\")\n app.secret_key = \"secret123\"\n return app\n\n\napp = _init_app()\n\n\ndef _init_db(app):\n db.init_app(app)\n with app.app_context():\n db.create_all()\n # Ensure FOREIGN KEY for sqlite3\n if 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:\n def _fk_pragma_on_connect(dbapi_con, con_record): # noqa\n dbapi_con.execute('pragma foreign_keys=ON')\n\n with app.app_context():\n from sqlalchemy import event\n event.listen(db.engine, 'connect', _fk_pragma_on_connect)\n\n\ndef _init_routes():\n api = Api(app)\n api.add_resource(Home, \"/\", methods=[\"GET\"])\n api.add_resource(Login, \"/login\", methods=[\"GET\", \"POST\"])\n api.add_resource(Register, \"/register\", methods=[\"GET\", \"POST\"])\n api.add_resource(PHCDashboard, \"/phcdashboard\", methods=[\"GET\"])\n api.add_resource(UploadCSV, \"/uploadcsv\", methods=[\"GET\", \"POST\"])\n api.add_resource(Logout, \"/logout\", methods=[\"GET\"])\n api.add_resource(Reports, \"/reports\", methods=[\"GET\"])\n api.add_resource(Output, \"/output/\", methods=[\"GET\"])\n api.add_resource(GenRep, \"/gen\", methods=[\"GET\"]) # Manual Report generation trigger\n # Generate report for non-default algorithms. Default is ARIMA\n api.add_resource(Algo, \"/algo\", methods=[\"GET\"])\n api.add_resource(DownloadTemplate, \"/download_template\", methods=[\"GET\", \"POST\"])\n api.add_resource(Admin, \"/admin\", methods=[\"GET\", \"POST\"])\n api.add_resource(CoronavirusHandler, \"/coronavirus\", methods=[\"GET\", \"POST\"])\n api.add_resource(About, \"/about\", methods=[\"GET\"])\n api.add_resource(AdminLogin, \"/admin_login\", methods=[\"GET\",\"POST\"])\n\n\nif __name__ == \"__main__\":\n scheduler = BackgroundScheduler(daemon=True)\n scheduler.add_job(generate_report, trigger='cron', day_of_week='mon-sun', hour='0', minute='0')\n scheduler.add_job(train_all_models,trigger='cron',day_of_week='sun',hour='0' ,minute='0')\n scheduler.start()\n _init_routes()\n _init_db(app)\n app.run(debug=False,threaded=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"103138867","text":"\"\"\"Tests for the base DTA record\"\"\"\n\nfrom unittest.mock import patch\n\nfrom swissdta.records.record import DTARecord\n\n\n@patch('swissdta.records.header.DTAHeader.validate')\ndef test_validate_header(mocker):\n \"\"\"Verifies that the record validation triggers the header validation.\"\"\"\n record = DTARecord()\n assert not mocker.called, \"header validation should not be called before record validation is triggered\"\n record.validate()\n assert mocker.call, \"header validation should be called when record validation is triggered\"\n","sub_path":"tests/test_record.py","file_name":"test_record.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"98079956","text":"#-*- coding:utf-8 -*-\n# @Time : 2017/7/21 17:46\n# @Author : Sml2h3\n# @Site : www.ydyd.me\n# @File : Clawer.py\n# @Software: PyCharm\nimport sys\nsys.setrecursionlimit(110000)\nimport requests\nimport time\nfrom Logger.Logger import Logger\nfrom gevent import monkey\nfrom Login.Login import Login\nmonkey.patch_socket()\nfrom lxml import etree\nimport gevent\nfrom gevent.pool import Pool\n# import pymysql\nfrom Config.DB import *\nLogger = Logger('Clawer')\n\n\nclass Clawer(object):\n def __init__(self, config, cookies):\n self.conn = config.conn\n self.cookies = cookies\n self.page = 1\n self.ckvalid = True\n\n def _run_master(self):\n if self.check_j_token():\n gevent.spawn(self.clawer_master).join()\n else:\n self._run_master()\n\n def _run_slaver(self):\n if self.check_j_token():\n pool = Pool(2)\n while True:\n urls = [ self.conn.spop(\"urls\") for i in range(5) ]\n result = pool.map(self.clawer_slaver, urls)\n\n else:\n self._run_slaver()\n\n def check_j_token(self):\n # 判断是否第一次访问\n Logger.info(\"正在判断是否需要生成j_token\")\n result = requests.get(\"http://openlaw.cn/search/judgement/type?causeId=a3ea79cf193f4e07a27a900e29585dbb&page=1\",\n cookies=self.cookies)\n if result and result.status_code == 200:\n if 'wch3116@hotmail.com' in result.text:\n # 需要\n Logger.info(\"需要生成j_token,即将开始进入j_token计算\")\n v = self.txt_wrap_by('window.v=\"', '\"', result.text)\n j_token = self.__get_j_token(v)\n self.cookies = requests.utils.add_dict_to_cookiejar(self.cookies, {\"j_token\": j_token})\n else:\n # 不需要\n Logger.info(\"不需要生成j_token\")\n return True\n else:\n Logger.warning(\"判断失败,休息一会重新判断~\")\n time.sleep(5)\n return False\n\n def clawer_slaver(self, url):\n header = {\n 'Host': 'openlaw.cn',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36',\n 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Referer': url,\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n }\n result = requests.get(url, cookies=self.cookies, headers=header)\n if result and result.status_code == 200:\n\n html = etree.HTML(result.text)\n #判决时间\n time_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[1]/text()')\n if len(time_tem) > 0:\n time = time_tem[0].rstrip().replace(\" \", '')\n else:\n time = \"0\"\n #判决标题\n title_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/h2/text()')\n if len(title_tem) > 0:\n title = title_tem[0]\n else:\n title = \"\"\n if title == \"\":\n self.clawer_slaver(url)\n return\n Logger.info(title)\n #判决法院\n fy_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[2]/a/text()')\n if len(fy_tem) > 0:\n fy = fy_tem[0]\n else:\n fy = \"\"\n #案号\n ah_tem = html.xpath('//*[@id=\"ht-kb\"]/article/header/ul/li[3]/text()')\n if len(ah_tem) > 0:\n ah = ah_tem[0]\n else:\n ah = \"\"\n #控告人和控诉人\n content = html.xpath('//*[@id=\"Litigants\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n litigants = c\n content = html.xpath('//*[@id=\"Explain\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n explain = c\n #诉讼程序\n content = html.xpath('//*[@id=\"Procedure\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n procedure = c\n #观点\n content = html.xpath('//*[@id=\"Opinion\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n option = c\n #裁定\n content = html.xpath('//*[@id=\"Verdict\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n verdict = c\n #通知\n content = html.xpath('//*[@id=\"Inform\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n info = c\n #结束语\n content = html.xpath('//*[@id=\"Ending\"]/p//text()')\n c = \"\"\n for t in content:\n c += t\n end = c\n Logger.info(title)\n # conn = pymysql.connect(host='rm-2ze7441de5149074.redis.rds.aliyuncs.com', port=3306, user='root', passwd='CSDNb405', db='openlaw', charset='utf8')\n # cursor = conn.cursor()\n # result = cursor.execute('insert into law(title, litigants, explain, procedure, opinion, verdict, inform, ending, time, fy, an) vaules(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',(str(title), str(litigants), str(explain), str(procedure), str(option), str(verdict), str(info), str(end), str(time), str(fy), str(ah)))\n # conn.commit()\n # cursor.close()\n # conn.close()\n session = DBSession()\n # 创建新User对象:\n new_user = Law(title=title, litigants=litigants, explain=explain, procedure=procedure, opinion=option, verdict=verdict, inform=info, ending=end, time=time, fy=fy, an=ah)\n # 添加到session:\n session.add(new_user)\n # 提交即保存到数据库:\n session.commit()\n session.close()\n # 关闭session:\n Logger.info(\"任务:\"+ url + \"完成\")\n\n def clawer_master(self, url=\"\"):\n if url == \"\":\n page = self.page\n self.page += 1\n url = \"http://openlaw.cn/search/judgement/type?causeId=a3ea79cf193f4e07a27a900e29585dbb&page=\"\n url += str(page)\n # 代理服务器\n proxyHost = \"proxy.abuyun.com\"\n proxyPort = \"9020\"\n\n # 代理隧道验证信息\n proxyUser = \"H4871716T867Q1LD\"\n proxyPass = \"CCAE03DE2E35FBA2\"\n\n proxyMeta = \"http://%(user)s:%(pass)s@%(host)s:%(port)s\" % {\n \"host\": proxyHost,\n \"port\": proxyPort,\n \"user\": proxyUser,\n \"pass\": proxyPass,\n }\n\n proxy_handler = {\n \"http\": proxyMeta,\n \"https\": proxyMeta,\n }\n\n header = {\n 'Host': 'openlaw.cn',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36',\n 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',\n 'Referer': url,\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',\n }\n Logger.info(\"正在抓取的页数为\" + str(page))\n result = requests.get(url, cookies=self.cookies, headers=header, proxies=proxy_handler)\n if result and result.status_code == 200:\n if \"抱歉不能为您显示更多的内容!\" in result.text:\n Logger.info(\"Cookies已经失效需要重新登录\")\n self.cookies = Login()._run()\n html = etree.HTML(result.text)\n href = html.xpath('//*[@id=\"ht-kb\"]/article/h3/a/@href')\n #//*[@id=\"ht-kb\"]/article[2]/h3/a\n if len(href)>0:\n urls = [ 'http://openlaw.cn'+i for i in href ]\n Logger.info(\"第\" + str(page) + \"页成功爬取到文书链接,数据量为\" + str(len(urls)) + \"条\")\n Logger.info(\"正在将任务上传至Redis服务器,等待从机进行下一步操作\")\n for url in urls:\n self.conn.sadd('urls', url)\n Logger.info(\"上传至Redis服务器成功,即将开始爬去第二页的内容\")\n else:\n Logger.info(\"本页未爬取到链接\")\n self.clawer_master()\n\n else:\n Logger.warning(\"访问出错,休息一会吧~\")\n time.sleep(3)\n self.clawer_master(url)\n\n def txt_wrap_by(self, start_str, end, html):\n start = html.find(start_str)\n if start >= 0:\n start += len(start_str)\n end = html.find(end, start)\n if end >= 0:\n return html[start:end].strip()\n\n def __get_j_token(self, str):\n cookie = str[2: 4] + 'n' + str[0: 1] + 'p' + str[4: 8] + 'e' + str[1: 2] + str[16: len(str) - 1] + str[8: 16]\n return cookie\n","sub_path":"Clawer/Clawer.py","file_name":"Clawer.py","file_ext":"py","file_size_in_byte":9190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"215232640","text":"from direct.distributed.PyDatagram import *\nimport urlparse\nfrom src.otp.distributed.OtpDoGlobals import *\nfrom src.otp.distributed.DistributedDirectoryAI import DistributedDirectoryAI\nfrom src.toontown.distributed.ToontownInternalRepository import ToontownInternalRepository\nimport src.toontown.minigame.MinigameCreatorAI\nfrom src.otp.otpbase import BackupManager\n\nif config.GetBool('want-rpc-server', False):\n from src.toontown.rpc.ToontownRPCServer import ToontownRPCServer\n from src.toontown.rpc.ToontownRPCHandler import ToontownRPCHandler\n\nclass ToontownUberRepository(ToontownInternalRepository):\n def __init__(self, baseChannel, serverId):\n ToontownInternalRepository.__init__(self, baseChannel, serverId, dcSuffix='UD')\n\n self.notify.setInfo(True)\n\n def handleConnected(self):\n ToontownInternalRepository.handleConnected(self)\n rootObj = DistributedDirectoryAI(self)\n rootObj.generateWithRequiredAndId(self.getGameDoId(), 0, 0)\n\n if config.GetBool('want-rpc-server', False):\n endpoint = config.GetString('rpc-server-endpoint', 'http://localhost:8080/')\n self.rpcServer = ToontownRPCServer(endpoint, ToontownRPCHandler(self))\n self.rpcServer.start(useTaskChain=True)\n\n self.backups = BackupManager.BackupManager(\n filepath=self.config.GetString('backups-filepath', 'backups/'),\n extension=self.config.GetString('backups-extension', '.json'))\n\n self.createGlobals()\n self.notify.info('Done.')\n\n def createGlobals(self):\n \"\"\"\n Create \"global\" objects.\n \"\"\"\n\n self.csm = simbase.air.generateGlobalObject(OTP_DO_ID_CLIENT_SERVICES_MANAGER, 'ClientServicesManager')\n self.chatAgent = simbase.air.generateGlobalObject(OTP_DO_ID_CHAT_MANAGER, 'ChatAgent')\n self.friendsManager = simbase.air.generateGlobalObject(OTP_DO_ID_ttcy_FRIENDS_MANAGER, 'ttcyFriendsManager')\n self.globalPartyMgr = simbase.air.generateGlobalObject(OTP_DO_ID_GLOBAL_PARTY_MANAGER, 'GlobalPartyManager')\n self.groupManager = simbase.air.generateGlobalObject(OPT_DO_ID_GROUP_MANAGER, 'GroupManager')\n self.megaInvasionManager = simbase.air.generateGlobalObject(\n OTP_DO_ID_MEGA_INVASION_MANAGER, 'MegaInvasionManager')\n","sub_path":"src/toontown/uberdog/ToontownUberRepository.py","file_name":"ToontownUberRepository.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"491418218","text":"#!/usr/bin/env python3\n\nround=0\nanswer=\" \"\n\nwhile round<3 and answer !='Brian':\n round=round+1\n answer=input('Finish the movie title, \"Monty Python\\'s The Life of ______\": ')\n \n if answer.lower()=='brian':\n print('Correct')\n break\n elif answer.lower()=='shrubbery':\n print('You gave the super secret answer!')\n break\n elif round==3:\n print('Sorry, the answer was Brian.')\n else:\n print('Sorry! Try again!')\n\n","sub_path":"montypython/monty_python2.py","file_name":"monty_python2.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"164465180","text":"# v1 -> Pickle dataframes read with pandas - \"Load data\" section\n# v2 -> Splits LSTM into 2 (LSTM and case)\n# v3 -> Uses FastText embeddings\n# v4 -> Conversion to token IDs, prunning and padding moved to preprocessing\n# v5 -> Splits cases in 5 different LSTMs\n# v6 -> Sigmoid function introduced.\n# Loss function changed from nn.BCEWithLogitsLoss() to nn.BCE()\n# Dropout added to LSTMS\n# v7 -> Test function added\n# Metric computations added\n# Saves model and results history\n# v8 -> Adds attention layers\n# v9 -> Adds flexible attention and hidden dims to global initialization\n# v10 -> Article text removed from model\n# v11 -> Article text added to model\n# v12 -> Encodes case passages in for loop\n\n#%% Imports\n\nimport os\nimport torch\nimport pickle\nimport pandas as pd\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import roc_auc_score, roc_curve\n\n# Function definition\n#%% DataClass definition\n\nclass ECHR_dataset(Dataset):\n def __init__(self, data_df):\n self.article_tensor = torch.LongTensor(data_df['article_text'].to_list())\n self.cases_tensor = torch.LongTensor(data_df['case_texts'].to_list())\n self.outcome_tensor = torch.Tensor(data_df['outcome'].to_list())\n \n def __len__(self):\n return self.outcome_tensor.size()[0]\n \n def __getitem__(self, idx):\n X_article = self.article_tensor[idx, :]\n X_cases = self.cases_tensor[idx, :]\n Y = self.outcome_tensor[idx]\n \n return X_article, X_cases, Y\n\n#%% Model definition\n\nclass ECHR_model(nn.Module):\n \n def __init__(self, input_size, hidden_dim, ouput_size, pretrained_embeddings,\n att_dim, dropout):\n super(ECHR_model, self).__init__()\n\n self.input_size = input_size\n self.hidden_dim = hidden_dim\n self.output_size = output_size\n self.dropout = dropout\n self.num_layers = 1\n self.num_passages = 5 #300\n self.seq_len = 512\n\n # Embedding\n self.embed = nn.Embedding.from_pretrained(pretrained_embeddings)\n \n # Dropout\n self.drops = nn.Dropout(self.dropout)\n \n # Encode article\n self.lstm_art = nn.LSTM(input_size = self.input_size,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True) \n \n # Encode case senteces\n self.lstm_case_sent = nn.LSTM(input_size = self.input_size,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True)\n \n # Encode case document\n self.lstm_case_doc = nn.LSTM(input_size = self.hidden_dim * 2,\n hidden_size = self.hidden_dim,\n num_layers = self.num_layers,\n bidirectional = True,\n batch_first = True)\n \n # Fully connected\n self.fc_1 = nn.Linear(in_features = self.hidden_dim * 2 * 2,\n out_features = self.output_size)\n \n # Sigmoid\n self.sigmoid = nn.Sigmoid()\n \n def forward(self, X_art, X_case):\n # Embedding\n x_art = self.embed(X_art) # batch_size x seq_len x embed_dim\n x_case = self.embed(X_case) # batch_size x (seq_len x n_passages) x embed_dim\n \n # Article encoding\n x_art = self.lstm_art(x_art) # Tuple (len = 2)\n x_art_fwd = x_art[0][:, -1, 0:64] # batch_size x hidden_dim\n x_art_bkwd = x_art[0][:, 0, 64:128] # batch_size x hidden_dim\n x_art = torch.cat((x_art_fwd, x_art_bkwd), dim = 1) # batch_size x (hidden_dim x 2)\n x_art = self.drops(x_art) # batch_size x (hidden_dim x 2) \n \n # Case sentence encoding\n #x_case_sent = torch.FloatTensor()\n x_case_sent = torch.FloatTensor().to(device)\n \n for idx in range(0, self.num_passages):\n span_b = self.seq_len * idx\n span_e = self.seq_len * (idx + 1)\n x_aux = self.lstm_case_sent(x_case[:, span_b:span_e, :]) # Tuple (len = 2)\n x_aux_fwd = x_aux[0][:, -1, 0:64] # batch_size x hidden_dim\n x_aux_bkwd = x_aux[0][:, 0, 64:128] # batch_size x hidden_dim\n x_aux = torch.cat((x_aux_fwd, x_aux_bkwd), dim = 1) # batch_size x (hidden_dim x 2)\n x_aux = self.drops(x_aux) # batch_size x (hidden_dim x 2)\n x_aux = x_aux.unsqueeze(1) # batch_size x 1 x (hidden_dim x 2)\n x_case_sent = torch.cat((x_case_sent, x_aux), dim=1) # batch_size x n_passages x (hidden_dim x 2)\n \n # Case document encoding\n x_case_doc = self.lstm_case_doc(x_case_sent) # Tuple (len = 2)\n x_case_doc_fwd = x_case_doc[0][:, -1, 0:64] # batch_size x hidden_dim\n x_case_doc_bkwd = x_case_doc[0][:, 0, 64:128] # batch_size x hidden_dim\n x_case_doc = torch.cat((x_case_doc_fwd, x_case_doc_bkwd),\n dim = 1) # batch_size x (hidden_dim x 2)\n x_case_doc = self.drops(x_case_doc) # batch_size x (hidden_dim x 2)\n \n # Concatenate article and passage encodings\n x = torch.cat((x_art, x_case_doc), dim = 1) # batch size x (hidden_dim x 2 x 2)\n \n # Fully connected layer\n x = self.fc_1(x) # batch size x output_size\n \n # Sigmoid function\n x = self.sigmoid(x) # batch size x output_size\n \n return x\n\n#%% Train function\n\ndef train_epoch_func(model, criterion, optimizer, train_dl, train_loss_history):\n model.train()\n train_acc = 0\n total_entries = 0\n sum_train_loss = 0\n \n for X_art, X_case, Y in tqdm(train_dl, total = len(train_dl)):\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Zero gradients\n optimizer.zero_grad()\n \n #Forward + backward + optimize\n pred = model(X_art, X_case).view(-1)\n loss = criterion(pred, Y)\n \n # Backpropagate\n loss.backward()\n \n # Update model\n optimizer.step() \n \n # Book-keeping\n current_batch_size = X_art.size()[0]\n total_entries += current_batch_size\n sum_train_loss += (loss.item() * current_batch_size)\n \n avg_train_loss = sum_train_loss / total_entries\n train_loss_history.append(avg_train_loss)\n \n return avg_train_loss, train_loss_history\n\n#%% Validation function\n\ndef val_epoch_func(model, criterion, dev_dl, val_loss_history):\n model.eval()\n val_acc = 0\n sum_correct = 0\n sum_val_loss = 0\n total_entries = 0\n\n for X_art, X_case, Y in dev_dl:\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Compute predictions:\n with torch.no_grad():\n pred = model(X_art, X_case).view(-1)\n loss = criterion(pred, Y)\n \n # Book-keeping\n current_batch_size = X_art.size()[0]\n total_entries += current_batch_size\n sum_val_loss += (loss.item() * current_batch_size)\n pred = torch.round(pred.view(pred.shape[0]))\n sum_correct += (pred == Y).sum().item() \n \n avg_loss = sum_val_loss / total_entries\n accuracy = sum_correct / total_entries\n val_loss_history.append(avg_loss)\n print(\"valid loss %.3f and accuracy %.3f\" % (avg_loss, accuracy))\n \n return avg_loss, accuracy, val_loss_history\n\n#%% Test function\n\ndef test_func(model, test_dl):\n model.eval()\n Y_predicted_score = []\n Y_predicted_binary = []\n Y_ground_truth = []\n\n for X_art, X_case, Y in test_dl:\n \n # Move to cuda\n if next(model.parameters()).is_cuda:\n X_art = X_art.to(device)\n X_case = X_case.to(device)\n Y = Y.to(device)\n \n # Compute predictions and append\n with torch.no_grad():\n pred_batch_score = model(X_art, X_case).view(-1)\n pred_batch_binary = torch.round(pred_batch_score.view(pred_batch_score.shape[0]))\n Y_predicted_score += pred_batch_score.tolist()\n Y_predicted_binary += pred_batch_binary.tolist()\n Y_ground_truth += Y.tolist()\n \n return Y_predicted_score, Y_predicted_binary, Y_ground_truth\n\n#%% Path definition\n\nrun_folder = os.path.join(os.path.split(os.getcwd())[0], '01_data', '02_runs', '14_art_5_50_pass') \npath_model_train = os.path.join(run_folder, 'model_train.pkl')\npath_model_dev = os.path.join(run_folder, 'model_dev.pkl')\npath_model_test = os.path.join(run_folder, 'model_test.pkl')\noutput_path_model = os.path.join(run_folder, 'model.pt')\noutput_path_results = os.path.join(run_folder, 'results.pkl')\ninput_path_id_2_embed = os.path.join(os.path.split(os.getcwd())[0], '01_data', '01_preprocessed', 'id_2_embed_dict.pkl')\n\n\"\"\"\nrun_folder = 'C:/Users/siban/Dropbox/CSAIL/Projects/12_Legal_Outcome_Predictor/01_data/02_runs/12_art_6_300_pass'\npath_model_train = os.path.join(run_folder, 'model_train.pkl')\npath_model_dev = os.path.join(run_folder, 'model_dev.pkl')\npath_model_test = os.path.join(run_folder, 'model_test.pkl')\noutput_path_model = os.path.join(run_folder, 'model.pt')\noutput_path_results = os.path.join(run_folder, 'results.pkl')\ninput_path_id_2_embed = 'C://Users//siban//Dropbox//CSAIL//Projects//12_Legal_Outcome_Predictor//01_data/01_preprocessed//id_2_embed_dict.pkl'\n\"\"\"\n\n#%% Global initialization\n\nseed = 1234\nn_epochs = 20\nbatch_size = 500\nlearning_rate = 0.001\ndropout = 0.4\nmomentum = 0.9\nwd = 0.00001\nuse_cuda = True\ndevice = torch.device('cuda:1')\n\nembed_dim = 200\ninput_size = embed_dim\nhidden_dim = 64\natt_dim = 100\noutput_size = 1\npad_idx = 0\n\n#%% Load data\n\nprint('Loading data')\nwith open(input_path_id_2_embed, 'rb') as fr:\n id_2_embed = pickle.load(fr)\n\nmodel_train = pd.read_pickle(path_model_train)\nmodel_dev = pd.read_pickle(path_model_dev)\nmodel_test = pd.read_pickle(path_model_test)\nprint('Done')\n\n\"\"\"\n#-------------------------------- FOR DEBUGGING -------\nmodel_train = model_train[0:50]\nmodel_dev = model_dev[0:int(50 * 0.2)]\nmodel_test = model_test[0:int(50 * 0.2)]\n#------------------------------------------------------\n\"\"\"\n\n#%% Instantiate dataclasses\n\nprint('Instantiating dataclases')\ntrain_dataset = ECHR_dataset(model_train)\ndev_dataset = ECHR_dataset(model_dev)\ntest_dataset = ECHR_dataset(model_test)\nprint('Done')\n\n#%% Instantiate dataloaders\n\nprint('Instantiating dataloaders')\ntrain_dl = DataLoader(train_dataset, batch_size = batch_size, shuffle = True)\ndev_dl = DataLoader(dev_dataset, batch_size = batch_size * 2, shuffle = False)\ntest_dl = DataLoader(test_dataset, batch_size = batch_size * 2, shuffle = False)\nprint('Done')\n\n#%% Instantiate model\n\npretrained_embeddings = torch.FloatTensor(list(id_2_embed.values()))\nmodel = ECHR_model(input_size, hidden_dim, output_size, pretrained_embeddings,\n att_dim, dropout)\n\n# Move to cuda\nif use_cuda and torch.cuda.is_available():\n print('Moving model to cuda')\n model = model.to(device)\n print('Done')\n\nprint(model)\n\n#%% Instantiate optimizer & criterion\n\noptimizer = torch.optim.Adam(model.parameters(), lr = learning_rate,\n weight_decay = wd)\n#optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate,\n# momentum = momentum)\ncriterion = nn.BCELoss()\n\n#%% Training\n\ntrain_loss_history = []\nval_loss_history = []\n\nfor epoch in tqdm(range(0, n_epochs), desc = 'Training'):\n train_loss, train_loss_history = train_epoch_func(model, criterion,\n optimizer, train_dl, train_loss_history)\n print(\"training loss: \", train_loss)\n _, _, val_loss_history = val_epoch_func(model, criterion, dev_dl, val_loss_history)\n\n#%% Testing\n\nY_predicted_score, Y_predicted_binary, Y_ground_truth = test_func(model, test_dl)\n\n#%% Compute Metrics\n\ntn, fp, fn, tp = confusion_matrix(Y_ground_truth, Y_predicted_binary).ravel()\n\nprecision = tp / (tp + fp)\nrecall = tp / (tp + fn)\nf1 = 2 * (precision * recall) / (precision + recall)\n\nauc = roc_auc_score(Y_ground_truth, Y_predicted_score)\n\nprint(f'Precision: {precision:.3f}')\nprint(f'Recall: {recall:.3f}')\nprint(f'F1: {f1:.3f}\\n')\nprint(f'AUC: {auc:.3f}\\n')\n\n#%% Save model and results\n\ntorch.save(model, output_path_model)\nresults = {'training_loss': train_loss_history,\n 'validation_loss': val_loss_history,\n 'Y_test_ground_truth': Y_ground_truth,\n 'Y_test_prediction_scores': Y_predicted_score,\n 'Y_test_prediction_binary': Y_predicted_binary}\nwith open(output_path_results, 'wb') as fw:\n pickle.dump(results, fw) \n","sub_path":"00_old_versions/08_model_full_case_no_att/05_model_v12.py","file_name":"05_model_v12.py","file_ext":"py","file_size_in_byte":13914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"34196652","text":"\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib.colors import LogNorm\nimport numpy as np\nfrom copy import deepcopy as copy\nfrom astropy.io import fits\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass GC():\n def __init__(self, ID, x, y, ra, dec, SNR=0, g=np.nan, z=np.nan, wave=None, spec=None, bg_spec=None, v=0, dv=0, m=0, dm=0, r=0, galaxy='FCC47', g_MUSE=0,\n z_MUSE=0, age=0, dage=0, m_age=0, dm_age=0, m_miles=0, dm_miles=0, m_amiles=0, dm_amiles=0, m_CaT=0, dm_CaT=0, m_ssp=0, dm_ssp=0, dm_b=0, m_b=0):\n self.ID = ID\n self.x = x\n self.y = y\n self.ra = ra\n self.dec = dec\n self.SNR = SNR\n self.g = g\n self.z = z\n self.r = r\n self.wave = wave\n spec[np.isinf(spec)] = 0.0\n spec[np.isnan(spec)] = 0.0\n self.spec = spec\n bg_spec[np.isinf(bg_spec)] = 0.0\n bg_spec[np.isnan(bg_spec)] = 0.0\n self.bg_spec = bg_spec\n self.v = v\n self.dv = dv\n self.m = m\n self.dm = dm\n self.g_MUSE = g_MUSE # process_spec(self.wave, self.spec, 'F475W')\n self.z_MUSE = z_MUSE # process_spec(self.wave, self.spec, 'F850LP')\n self.galaxy = galaxy\n self.age = age\n self.dage = dage\n self.m_age = m_age\n self.dm_age = dm_age\n self.m_miles = m_miles\n self.dm_miles = dm_miles\n self.m_amiles = m_amiles\n self.dm_amiles = dm_amiles\n self.m_CaT = m_CaT\n self.dm_CaT = dm_CaT\n self.m_b = m_b\n self.dm_b = dm_b\n self.m_ssp = m_CaT\n self.dm_ssp = dm_CaT\n\n def set_v(self, v=0, dv=0):\n self.v = v\n self.dv = dv\n\n def set_ra_dec(self, ra=0, dec=0):\n self.ra = np.round(ra, 7)\n self.dec = np.round(dec, 7)\n\n def set_m(self, m=0, dm=0):\n self.m = m\n self.dm = dm\n\n def set_ID(self, ID=0):\n self.ID = int(ID)\n\n def get_MUSE_mag(self):\n self.g_MUSE = process_spec(self.wave, self.spec, 'F475W')\n self.z_MUSE = process_spec(self.wave, self.spec, 'F850LP')\n\n def set_r(self, r=0):\n self.r = r\n\n\ndef get_rad(x_pix, y_pix, xc=207, yc=387):\n '''\n Simple routine to calculate the projected distance in arcsec\n '''\n rs = np.zeros(len(x_pix))\n for i in range(len(x_pix)):\n rs[i] = np.sqrt((x_pix[i] - xc)**2 + (y_pix[i] - yc)**2) # in pixel coords\n return rs * 0.2 # in arcsec\n\n\ndef create_catalog(GCs, output_directory='./', galaxy='FCC47'):\n '''\n Creates the MUSE catalog as a fits file in the output directory\n '''\n # the spectra\n wave = GCs[0].wave\n\n filename = '{0}_GC_catalog.fits'.format(galaxy)\n print(\"- Writing: \" + output_directory + filename)\n cols = []\n cols.append(fits.Column(name='GC_ID', format='D', array=[GCs[i].ID for i in range(len(GCs))]))\n cols.append(fits.Column(name='X_PIX', format='D', array=[GCs[i].x for i in range(len(GCs))]))\n cols.append(fits.Column(name='Y_PIX', format='D', array=[GCs[i].y for i in range(len(GCs))]))\n cols.append(fits.Column(name='SNR', format='D', array=[GCs[i].SNR for i in range(len(GCs))]))\n cols.append(fits.Column(name='RA', format='D', array=[GCs[i].ra for i in range(len(GCs))]))\n cols.append(fits.Column(name='DEC', format='D', array=[GCs[i].dec for i in range(len(GCs))]))\n cols.append(fits.Column(name='g', format='D', array=[GCs[i].g for i in range(len(GCs))]))\n cols.append(fits.Column(name='z', format='D', array=[GCs[i].z for i in range(len(GCs))]))\n cols.append(fits.Column(name='v', format='D', array=[GCs[i].v for i in range(len(GCs))]))\n cols.append(fits.Column(name='dv', format='D', array=[GCs[i].dv for i in range(len(GCs))]))\n cols.append(fits.Column(name='m', format='D', array=[GCs[i].m for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm', format='D', array=[GCs[i].dm for i in range(len(GCs))]))\n cols.append(fits.Column(name='r', format='D', array=[GCs[i].r for i in range(len(GCs))]))\n cols.append(fits.Column(name='age', format='D', array=[GCs[i].age for i in range(len(GCs))]))\n cols.append(fits.Column(name='g_MUSE', format='D',\n array=[GCs[i].g_MUSE for i in range(len(GCs))]))\n cols.append(fits.Column(name='z_MUSE', format='D',\n array=[GCs[i].z_MUSE for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_miles', format='D',\n array=[GCs[i].m_miles for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_miles', format='D',\n array=[GCs[i].dm_miles for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_amiles', format='D',\n array=[GCs[i].m_amiles for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_amiles', format='D',\n array=[GCs[i].dm_amiles for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_CaT', format='D',\n array=[GCs[i].m_CaT for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_CaT', format='D',\n array=[GCs[i].dm_CaT for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_b', format='D',\n array=[GCs[i].m_b for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_b', format='D',\n array=[GCs[i].dm_b for i in range(len(GCs))]))\n cols.append(fits.Column(name='m_ssp', format='D',\n array=[GCs[i].m_ssp for i in range(len(GCs))]))\n cols.append(fits.Column(name='dm_ssp', format='D',\n array=[GCs[i].dm_ssp for i in range(len(GCs))]))\n cols.append(fits.Column(name='galaxy', format='A6',\n array=[GCs[i].galaxy for i in range(len(GCs))]))\n tbhdu = fits.BinTableHDU.from_columns(fits.ColDefs(cols))\n\n dwave = wave[1] - wave[0]\n wave0 = wave[0]\n wave1 = wave[-1]\n hdr = fits.Header()\n hdr['wave0'] = np.round(wave0, 4)\n hdr['wave1'] = np.round(wave1 + dwave, 4)\n hdr['dwave'] = dwave\n hdr['galaxy'] = galaxy\n\n hdu = fits.PrimaryHDU(header=hdr)\n hdu1 = fits.ImageHDU([GCs[i].spec + GCs[i].bg_spec for i in range(len(GCs))])\n hdu2 = fits.ImageHDU([GCs[i].bg_spec for i in range(len(GCs))])\n hdulist = fits.HDUList([hdu, tbhdu, hdu1, hdu2])\n if os.path.isfile(output_directory + filename):\n os.remove(output_directory + filename)\n hdulist.writeto(output_directory + filename)\n\n\ndef read_fits(file, i=1):\n hdulist = fits.open(file)\n data = hdulist[i].data\n # print(hdulist[i].header)\n return data, hdulist[i].header\n\n\ndef initialize_catalog(file, already_fitted=False, galaxy='FCC47'):\n GC_cat_table = read_fits(file, i=1)[0]\n GC_specs_unsubtracted = read_fits(file, i=2)[0]\n GC_specs_bg = read_fits(file, i=3)[0]\n header = read_fits(file, i=0)[1]\n wave = np.arange(header['wave0'], np.round(header['wave1'], 4), header['dwave'])\n if len(wave) == len(GC_specs_unsubtracted[0]) + 1:\n wave = wave[:-1]\n GCs = []\n miles = False\n amiles = False\n CaT = False\n get_ages = False\n best_ssp = False\n # print(GC_cat_table.names)\n if 'm_miles' in GC_cat_table.names:\n miles = True\n if 'm_amiles' in GC_cat_table.names:\n amiles = True\n if 'm_CaT' in GC_cat_table.names:\n CaT = True\n if 'm_ssp' in GC_cat_table.names:\n best_ssp = True\n if 'm_b' in GC_cat_table.names:\n balmer_met = True\n else:\n balmer_met = False\n if 'm_age' in GC_cat_table.names:\n get_ages = True\n for i, ID in enumerate(GC_cat_table.field('GC_ID')):\n xpix, ypix = GC_cat_table.field('X_PIX')[i], GC_cat_table.field('Y_PIX')[i]\n ra, dec = GC_cat_table.field('RA')[i], GC_cat_table.field('DEC')[i]\n SNR = GC_cat_table.field('SNR')[i]\n g = GC_cat_table.field('g')[i]\n z = GC_cat_table.field('z')[i]\n spec = GC_specs_unsubtracted[i] - GC_specs_bg[i]\n bg_spec = GC_specs_bg[i]\n galaxy = GC_cat_table.field('galaxy')[i]\n if already_fitted:\n v = GC_cat_table.field('v')[i]\n dv = GC_cat_table.field('dv')[i]\n m = GC_cat_table.field('m')[i]\n dm = GC_cat_table.field('dm')[i]\n r = GC_cat_table.field('r')[i]\n g_MUSE = GC_cat_table.field('g_MUSE')[i]\n z_MUSE = GC_cat_table.field('z_MUSE')[i]\n if miles:\n m_miles = GC_cat_table.field('m_miles')[i]\n dm_miles = GC_cat_table.field('dm_miles')[i]\n else:\n m_miles = 0\n dm_miles = 0\n if amiles:\n m_amiles = GC_cat_table.field('m_amiles')[i]\n dm_amiles = GC_cat_table.field('dm_amiles')[i]\n else:\n m_amiles = 0\n dm_amiles = 0\n if CaT:\n m_CaT = GC_cat_table.field('m_CaT')[i]\n dm_CaT = GC_cat_table.field('dm_CaT')[i]\n else:\n m_CaT = 0\n dm_CaT = 0\n if best_ssp:\n m_ssp = GC_cat_table.field('m_ssp')[i]\n dm_ssp = GC_cat_table.field('dm_ssp')[i]\n else:\n m_ssp = 0\n dm_ssp = 0\n if balmer_met:\n m_b = GC_cat_table.field('m_b')[i]\n dm_b = GC_cat_table.field('dm_b')[i]\n else:\n m_b = 0\n dm_b = 0\n if get_ages:\n age = GC_cat_table.field('age')[i]\n dage = GC_cat_table.field('dage')[i]\n m_age = GC_cat_table.field('m_age')[i]\n dm_age = GC_cat_table.field('dm_age')[i]\n else:\n age, dage, m_age, dm_age = 0, 0, 0, 0\n GCs.append(GC(ID, xpix, ypix, ra, dec, SNR=SNR, g=g, z=z, wave=wave, spec=spec, bg_spec=bg_spec, galaxy=galaxy,\n v=v, dv=dv, m=m, dm=dm, r=r, g_MUSE=g_MUSE, z_MUSE=z_MUSE, m_miles=m_miles, dm_miles=dm_miles,\n m_CaT=m_CaT, dm_CaT=dm_CaT, m_ssp=m_ssp, dm_ssp=dm_ssp, m_amiles=m_amiles, dm_amiles=dm_amiles, m_b=m_b, dm_b=dm_b,\n age=age, dage=dage, dm_age=dm_age, m_age=m_age))\n else:\n GCs.append(GC(ID, xpix, ypix, ra, dec, SNR=SNR, g=g, z=z,\n wave=wave, spec=spec, bg_spec=bg_spec, galaxy=galaxy))\n return GCs\n\n\ndef remove_from_cat(remove_file, GCs):\n IDs_to_remove = np.loadtxt(remove_file)\n\n new_GCs = []\n for i, GCi in enumerate(GCs):\n if GCi.ID in IDs_to_remove:\n print('Will remove GC {0}'.format(i))\n else:\n new_GCs.append(GCi)\n print('The new catalog contains {} GCs!'.format(len(new_GCs)))\n return new_GCs\n\n\ndef get_statistics_from_dist(array, lims=[1000, 2000], use_lims=False):\n if use_lims:\n mask = (array > lims[0]) & (array < lims[1])\n array = array[mask]\n med = np.percentile(array, 50)\n err_p = np.percentile(array, 100-16.84) - med\n err_m = med - np.percentile(array, 16.84)\n err = 0.5 * (np.round(err_p, 2) + np.round(err_m, 2))\n return np.round(med, 2), err\n\n\ndef der_snr(flux):\n \"\"\"\n REFERENCES * ST-ECF Newsletter, Issue #42:\n www.spacetelescope.org/about/further_information/newsletters/html/newsletter_42.html\n * Software:\n www.stecf.org/software/ASTROsoft/DER_SNR/\n AUTHOR Felix Stoehr, ST-ECF\n 24.05.2007, fst, initial import\n 01.01.2007, fst, added more help text\n 28.04.2010, fst, return value is a float now instead of a numpy.float64\n \"\"\"\n flux = np.array(flux[np.isfinite(flux)])\n # Values that are exactly zero (padded) or NaN are skipped\n flux = flux[(flux != 0.0) & np.isfinite(flux)]\n n = len(flux)\n # For spectra shorter than this, no value can be returned\n if n > 4:\n signal = np.median(flux)\n noise = 0.6052697 * np.median(np.abs(2.0 * flux[2:n-2] - flux[0:n-4] - flux[4:n]))\n return float(signal / noise)\n else:\n return 0.0\n\n\nclass host_galaxy():\n def __init__(self, name, xc=0, yc=0, PA=0, eps=0, vsys=0, Reff=0, mB=0, xoffset=0, yoffset=0, fwhm=0.8, mc=0):\n self.name = name\n self.xc = xc\n self.yc = yc\n self.PA = PA\n self.eps = eps\n self.vsys = vsys\n self.Reff = Reff\n self.mB = mB\n self.xoffset = xoffset\n self.yoffset = yoffset\n self.fwhm = fwhm/0.2\n self.mc = mc\n\n\ndef dist_circle(xc, yc, s):\n \"\"\"\n Returns an array in which the value of each element is its distance from\n a specified center. Useful for masking inside a circular aperture.\n\n The (xc, yc) coordinates are the ones one can read on the figure axes\n e.g. when plotting the result of my find_galaxy() procedure.\n\n FROM MGEFIT\n \"\"\"\n x, y = np.ogrid[:s[0], :s[1]] - np.array([yc, xc]) # note yc before xc\n rad = np.sqrt(x**2 + y**2)\n return rad\n\n\ndef get_galaxy_info(galaxy, file='/Users/kfahrion/Documents/Data_clean/MUSE_Data/galaxies.dat'):\n f = open(file)\n for line in f.readlines()[1:]: # skip header:\n columns = line.strip().split()\n gal_name = columns[0]\n if gal_name == galaxy:\n xc = int(columns[1])\n yc = int(columns[2])\n PA = float(columns[3])\n eps = float(columns[4])\n vsys = float(columns[5])\n Reff = float(columns[6])\n mB = float(columns[7])\n xoffset = float(columns[8])\n yoffset = float(columns[9])\n fwhm = float(columns[10])\n m_c = float(columns[11])\n try:\n return host_galaxy(galaxy, xc=xc, yc=yc, PA=PA, eps=eps, vsys=vsys, Reff=Reff, mB=mB, xoffset=xoffset, yoffset=yoffset, fwhm=fwhm, mc=m_c)\n except:\n print('{} not found in galaxies.dat!'.format(galaxy))\n return host_galaxy(galaxy)\n","sub_path":"GC_support.py","file_name":"GC_support.py","file_ext":"py","file_size_in_byte":14088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"251559776","text":"import tensorflow as tf\n\n\n# def scale_l2(x, eps=1e-3):\n# # shape(x) = (batch, num_timesteps, d)\n# # Divide x by max(abs(x)) for a numerically stable L2 norm.\n# # 2norm(x) = a * 2norm(x/a)\n# # Scale over the full sequence, dims (1, 2)\n# alpha = tf.reduce_max(tf.abs(x), (1, 2), keep_dims=True) + 1e-12\n# l2_norm = alpha * tf.sqrt(\n# tf.reduce_sum(tf.pow(x / alpha, 2), (1, 2), keep_dims=True) + 1e-6)\n# x_unit = x / l2_norm\n# return eps * x_unit\n\ndef scale_l2(x, eps=1e-3):\n # scale over the full batch\n return eps * tf.nn.l2_normalize(x, dim=[0, 1, 2])\n\ndef mask_by_length(t, length):\n \"\"\"Mask t, 3-D [batch, time, dim], by length, 1-D [batch,].\"\"\"\n maxlen = t.get_shape().as_list()[1]\n\n # Subtract 1 from length to prevent the perturbation from going on 'eos'\n mask = tf.sequence_mask(length, maxlen=maxlen)\n mask = tf.expand_dims(tf.cast(mask, tf.float32), -1)\n # shape(mask) = (batch, num_timesteps, 1)\n return t * mask\n\ndef logsoftmax(x):\n xdev = x - tf.reduce_max(x, 1, keep_dims=True)\n lsm = xdev - tf.log(tf.reduce_sum(tf.exp(xdev), 1, keep_dims=True))\n return lsm\n\ndef normalize_embed(self, emb, vocab_freqs):\n vocab_freqs = tf.constant(\n vocab_freqs, dtype=tf.float32, shape=[self.vocab_size, 1])\n weights = vocab_freqs / tf.reduce_sum(vocab_freqs)\n mean = tf.reduce_sum(weights * emb, 0, keep_dims=True)\n var = tf.reduce_sum(weights * tf.pow(emb - mean, 2.), 0, keep_dims=True)\n stddev = tf.sqrt(1e-6 + var)\n return (emb - mean) / stddev\n\ndef adv_example(inputs, loss):\n grad, = tf.gradients(\n loss,\n inputs,\n aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)\n grad = tf.stop_gradient(grad)\n perturb = scale_l2(grad)\n\n return inputs + perturb\n\ndef kl_divergence_with_logits(q_logit, p_logit):\n # https://github.com/takerum/vat_tf\n q = tf.nn.softmax(q_logit)\n qlogq = tf.reduce_mean(tf.reduce_sum(q * logsoftmax(q_logit), 1))\n qlogp = tf.reduce_mean(tf.reduce_sum(q * logsoftmax(p_logit), 1))\n kl = qlogq - qlogp\n return kl\n\ndef virtual_adversarial_loss(logits, length, sentence, pos1, pos2, pcnn_mask, logits_fn,\n lexical=None, num_iter=1, small_coef=1e-6):\n # Stop gradient of logits. See https://arxiv.org/abs/1507.00677 for details.\n logits = tf.stop_gradient(logits)\n\n # Initialize perturbation with random noise.\n d_sent = tf.random_normal(shape=tf.shape(sentence))\n\n # Perform finite difference method and power iteration.\n # See Eq.(8) in the paper http://arxiv.org/pdf/1507.00677.pdf,\n # Adding small noise to input and taking gradient with respect to the noise\n # corresponds to 1 power iteration.\n agg_method = tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N\n for _ in range(num_iter):\n d_sent = scale_l2(mask_by_length(d_sent, length), small_coef) \n vadv_sent = sentence + d_sent\n d_logits = logits_fn(vadv_sent, pos1, pos2, pcnn_mask)\n\n kl = kl_divergence_with_logits(logits, d_logits)\n d_sent, = tf.gradients(kl, d_sent, aggregation_method=agg_method)\n d_sent = tf.stop_gradient(d_sent)\n\n vadv_sent = sentence + scale_l2(d_sent)\n vadv_logits = logits_fn(vadv_sent, pos1, pos2, pcnn_mask)\n\n return kl_divergence_with_logits(logits, vadv_logits)","sub_path":"src-pcnn/models/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"542374496","text":"from twython import Twython, TwythonError\nimport time\n#Api info goes here\nAPP_KEY = 'XXXXX'\nAPP_SECRET = 'XXXXX'\nOAUTH_TOKEN = 'XXXXX'\nOAUTH_TOKEN_SECRET = 'XXXXX'\n#Use Twython to set up api access to twitter\napi = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n\n#Read the things we need to tweet\nwith open('tweets.txt', 'r+') as tweetsfile:\n\ttweets = tweetsfile.readlines()\n\n#Loop through all the tweets\nfor line in tweets[:]: \n\ttry:\n\t\t\t#What are we tweeting\n\t\t\tprint (\"Trying to tweet:\\n\" + line)\n\t\t\t#DEBUG\n\t\t\t#length = str(len(line))\n\t\t\t#print (\"Line length: \" + length)\n\t\t\t#Attempt to send the tweet - exception will show & we'll move on.\n\t\t\tapi.update_status(status=line)\n\t\t\t#Debug\n\t\t\tprint(\"Successfully tweeted:\\n\" + line) \n\t#OHNOES!\n\texcept TwythonError as e:\n\t\t#in case it didn't work\n\t\terror = str(e)\n\t\tprint(\"Something went wrong :( \\nError message: \" + error + \"\\n\")\n\t\tpass\n\t#Rate limit \n\ttime.sleep(5)\n#Yey it worked\nprint (\"I have tweeted AllTheThings fit to tweet!\")\n\t","sub_path":"tweetbot.py","file_name":"tweetbot.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"465500787","text":"import threading\nfrom time import sleep, time\nfrom typing import Callable, Dict, List\n\nfrom basic_speech_to_text import speech_to_text, is_keyword_said, is_wake_up_word_said\nfrom plant_intent_recognizer.detect_intent import RasaIntent, Intent\n\nCALLBACK_INTENTS: Dict[Intent, List[Callable[[], None]]] = {}\n\n\ndef register_function_for_intent(intent: Intent):\n \"\"\"Register a function to be called every time an intent is detected by VoiceController\"\"\"\n def inner_decorator(f):\n def wrapped(*args, **kwargs):\n response = f(*args, **kwargs)\n return response\n\n print(f\"Registering {f} for intent: {intent.value}\")\n functions = CALLBACK_INTENTS.get(intent, [])\n functions.append(f)\n CALLBACK_INTENTS[intent] = functions\n return wrapped\n\n return inner_decorator\n\n\ndef _trigger_function_on_intent(intent: Intent):\n \"\"\"Trigger all function registered for this intent\"\"\"\n if intent not in CALLBACK_INTENTS:\n return\n functions = CALLBACK_INTENTS[intent]\n for f in functions:\n f()\n\n\nclass VoiceController:\n\n def __init__(self, active_time_delay=10):\n \"\"\"\n :param active_time_delay time in seconds after the keyword was said before being not \"active\"\n \"\"\"\n self._rasa_intent = RasaIntent()\n self.active = False\n self._stop = False\n self.active_time_delay = active_time_delay\n self.last_active_time = None\n\n self._thread = threading.Thread(target=self.run, args=())\n self._thread.daemon = True # Daemonize thread\n\n def stop(self):\n \"\"\"Stopping gracefully, might take a few seconds\"\"\"\n self._stop = True\n self._thread.join()\n\n def start(self):\n self._thread.start() # Call run()\n\n def run(self):\n self._stop = False\n while not self._stop:\n if self.active: # We actively listen to user command\n text = speech_to_text()\n print(f\"text: {text}\", flush=True)\n if text:\n intent = self._rasa_intent.detect_intent(text)\n print(f\"intent: {intent}\\n\", flush=True)\n _trigger_function_on_intent(intent)\n self.last_active_time = time()\n elif time() - self.last_active_time > self.active_time_delay:\n print(\"SLEEP MODE\", flush=True)\n self.active = False\n elif is_wake_up_word_said():\n print(\"ACTIVE MODE\", flush=True)\n self.active = True\n self.last_active_time = time()\n else:\n print(\"😴\", end='', flush=True) # Still in sleep mode\n\n\nif __name__ == '__main__':\n \"\"\"Example on how to use the register_function_for_intent wrapper\"\"\"\n @register_function_for_intent(intent=Intent.GREET)\n def greeting():\n print(\"Hello !\")\n\n @register_function_for_intent(intent=Intent.GREET)\n def greeting2():\n print(\"Hello 2 !\")\n\n @register_function_for_intent(intent=Intent.GOODBYE)\n def goodbye():\n print(\"goodbye !\")\n\n vc = VoiceController()\n vc.start()\n print(\"I can continue to do stuff\")\n sleep(60)\n print(\"Time to stop\")\n vc.stop()\n","sub_path":"voice_controller.py","file_name":"voice_controller.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"422244424","text":"#!/usr/bin/env python\n\nimport json\nfrom collections import namedtuple\nimport os\nimport re\nimport sys\n\n\nDevice = namedtuple('Device', ('major', 'minor'))\n\ndef get_container_block_file(ctid):\n \"\"\"Get the device file information for /dev/vdb in the container.\"\"\"\n\n device_info = os.stat('/var/lib/vz/private/{0}/dev/vdb'.format(ctid))\n return Device(\n major=os.major(device_info.st_rdev),\n minor=os.minor(device_info.st_rdev)\n )\n\n\ndef get_device_mappings(ctid):\n \"\"\"Get all devices mapped in the vz config file.\"\"\"\n\n device_line = \"\"\n with open('/etc/vz/conf/{0}.conf'.format(ctid), 'r') as f:\n for line in f:\n if line.startswith('DEVICES'):\n device_line = line\n break\n else:\n raise ValueError(\"No DEVICES line found in vz conf.\")\n\n return tuple(\n Device(major=int(m[0]), minor=int(m[1]))\n for m in re.findall('b:(\\d+):(\\d+)', device_line)\n )\n\n\ndef get_iscsi_device(ctid):\n \"\"\"Get device info for the actual iscsi mount point on the host.\n\n This uses the Cinder data stored in the ext_storage json file.\n \"\"\"\n\n iscsi_data = None\n with open('/etc/vz/conf/{0}.ext_storage'.format(ctid), 'r') as f:\n iscsi_data = json.loads(f.read())\n\n symlink = \"/dev/disk/by-path/ip-{0}-iscsi-{1}-lun-{2}\".format(\n iscsi_data['vdb']['data']['target_portal'],\n iscsi_data['vdb']['data']['target_iqn'],\n iscsi_data['vdb']['data']['target_lun'],\n )\n final_path = os.path.realpath(symlink)\n device_info = os.stat(final_path)\n return Device(\n major=os.major(device_info.st_rdev),\n minor=os.minor(device_info.st_rdev)\n )\n\nif __name__ == '__main__':\n\n for ctid in os.listdir('/var/lib/vz/private'):\n # Ignore any dirs that aren't integer CTID's (like . or ..).\n try:\n int(ctid)\n except:\n continue\n try:\n bf = get_container_block_file(ctid)\n dms = get_device_mappings(ctid)\n iscsi = get_iscsi_device(ctid)\n sys.stdout.write('Container Block File: {0}\\n'.format(bf))\n sys.stdout.write('Container Device Mappings: {0}\\n'.format(dms))\n sys.stdout.write('ISCSI Device: {0}\\n'.format(iscsi))\n if bf not in dms or bf != iscsi:\n sys.stderr.write('FAIL: Devices do not match for {0}!\\n'.format(ctid))\n sys.exit(-1)\n\n sys.stdout.write('PASS: Devices match for {0}.\\n'.format(ctid))\n except Exception as e:\n sys.stderr.write('SKIPPING: {0}. Something went wrong. {1}\\n'.format(ctid, e))\n","sub_path":"DBaaS/check_volume.py","file_name":"check_volume.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"215012038","text":"import woodwork as ww\nfrom woodwork.accessor_utils import _is_koalas_series\nfrom woodwork.logical_types import (\n Boolean,\n BooleanNullable,\n Categorical,\n Datetime,\n Double,\n EmailAddress,\n Integer,\n IntegerNullable,\n LogicalType,\n Timedelta,\n Unknown,\n)\nfrom woodwork.tests.testing_utils import to_pandas\nfrom woodwork.utils import import_or_none\n\nUNSUPPORTED_KOALAS_DTYPES = [\n \"int32\",\n \"intp\",\n \"uint8\",\n \"uint16\",\n \"uint32\",\n \"uint64\",\n \"uintp\",\n \"float_\",\n \"object\",\n \"category\",\n]\n\nks = import_or_none(\"databricks.koalas\")\n\n\ndef get_koalas_dtypes(dtypes):\n return [dtype for dtype in dtypes if dtype not in UNSUPPORTED_KOALAS_DTYPES]\n\n\ndef test_integer_inference(integers):\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in integers:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Integer)\n\n\ndef test_double_inference(doubles):\n dtypes = [\"float\", \"float32\", \"float64\", \"float_\"]\n if _is_koalas_series(doubles[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in doubles:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Double)\n\n\ndef test_boolean_inference(bools):\n dtypes = [\"bool\", \"boolean\"]\n\n for series in bools:\n for dtype in dtypes:\n cast_series = series.astype(dtype)\n inferred_type = ww.type_system.infer_logical_type(cast_series)\n if to_pandas(cast_series).isnull().any():\n assert isinstance(inferred_type, BooleanNullable)\n else:\n assert isinstance(inferred_type, Boolean)\n\n\ndef test_datetime_inference(datetimes):\n dtypes = [\"object\", \"string\", \"datetime64[ns]\"]\n if _is_koalas_series(datetimes[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in datetimes:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Datetime)\n\n\ndef test_email_inference(emails):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(emails[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in emails:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, EmailAddress)\n\n\ndef test_email_inference_failure(bad_emails):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(bad_emails[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in bad_emails:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert not isinstance(inferred_type, EmailAddress)\n\n\ndef test_categorical_inference(categories):\n dtypes = [\"object\", \"string\", \"category\"]\n if _is_koalas_series(categories[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in categories:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_inference_based_on_dtype(categories_dtype):\n \"\"\"\n This test specifically targets the case in which a series can be inferred\n to be categorical strictly from its pandas dtype, but would otherwise be\n inferred as some other type.\n \"\"\"\n inferred_type = ww.type_system.infer_logical_type(categories_dtype[\"cat\"])\n assert isinstance(inferred_type, Categorical)\n\n inferred_type = ww.type_system.infer_logical_type(categories_dtype[\"non_cat\"])\n assert not isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_integers_inference(integers):\n with ww.config.with_options(numeric_categorical_threshold=0.5):\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in integers:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_categorical_double_inference(doubles):\n with ww.config.with_options(numeric_categorical_threshold=0.5):\n dtypes = [\"float\", \"float32\", \"float64\", \"float_\"]\n if _is_koalas_series(doubles[0]):\n dtypes = get_koalas_dtypes(dtypes)\n for series in doubles:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Categorical)\n\n\ndef test_timedelta_inference(timedeltas):\n dtypes = [\"timedelta64[ns]\"]\n for series in timedeltas:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Timedelta)\n\n\ndef test_unknown_inference(strings):\n dtypes = [\"object\", \"string\"]\n if _is_koalas_series(strings[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in strings:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Unknown)\n\n\ndef test_unknown_inference_all_null(nulls):\n dtypes = [\"object\", \"string\", \"category\", \"datetime64[ns]\"]\n if _is_koalas_series(nulls[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in nulls:\n for dtype in dtypes:\n inferred_type = ww.type_system.infer_logical_type(series.astype(dtype))\n inferred_type.transform(series)\n assert isinstance(inferred_type, Unknown)\n\n\ndef test_pdna_inference(pdnas):\n expected_logical_types = [\n Unknown,\n IntegerNullable,\n BooleanNullable,\n ]\n\n for index, series in enumerate(pdnas):\n inferred_type = ww.type_system.infer_logical_type(series)\n assert isinstance(inferred_type, expected_logical_types[index])\n\n\ndef test_updated_ltype_inference(integers, type_sys):\n inference_fn = type_sys.inference_functions[ww.logical_types.Integer]\n type_sys.remove_type(ww.logical_types.Integer)\n\n class Integer(LogicalType):\n primary_dtype = \"string\"\n\n type_sys.add_type(Integer, inference_function=inference_fn)\n\n dtypes = [\"int8\", \"int16\", \"int32\", \"int64\", \"intp\", \"int\", \"Int64\"]\n if _is_koalas_series(integers[0]):\n dtypes = get_koalas_dtypes(dtypes)\n\n for series in integers:\n for dtype in dtypes:\n inferred_type = type_sys.infer_logical_type(series.astype(dtype))\n assert isinstance(inferred_type, Integer)\n assert inferred_type.primary_dtype == \"string\"\n","sub_path":"woodwork/tests/type_system/test_ltype_inference.py","file_name":"test_ltype_inference.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"508745341","text":"class queue:\n def __init__(self,n):\n self.arr=[0]*n\n self.head=0\n self.tail=-1\n def enqueue(self,k):\n self.tail+=1\n self.arr[self.tail]=k\n def dequeue(self):\n t=self.arr[self.head]\n self.head+=1\n return t\n def empty(self):\n return self.head-self.tail==1\n\nclass node:\n def __init__(self,val):\n self.val=val\n self.link=None\n\ndef adjacent(G,v):\n arr=[]\n ptr=G[v]\n while(ptr):\n arr.append(ptr.val)\n ptr=ptr.link\n return arr\n\nn=int(input('No. of nodes: '))\nG=[None]*n\nfor i in range(n):\n a=int(input('No. of adjacent nodes of node ' + str(i) +': '))\n for j in range(a):\n an=node(int(input()))\n an.link=G[i]\n G[i]=an\n\nindegree=[0]*n\nfor i in range(n):\n for w in adjacent(G,i):\n indegree[w]+=1\n\nq=queue(n)\nfor i in range(n):\n if(indegree[i]==0):\n q.enqueue(i)\n\nprint('Topological sorted order: ')\nfor i in range(n): #Topological sort\n e=q.dequeue()\n indegree[e]=-1\n print(e,end=' ')\n for w in adjacent(G,e):\n indegree[w]-=1\n if(indegree[w]==0):\n q.enqueue(w)","sub_path":"Graph/Topological_sort.py","file_name":"Topological_sort.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"474623690","text":"from os.path import join, dirname\n\nfrom nmigen import Fragment, Module, ClockSignal, DomainRenamer\n\nfrom cores.axi import AxiEndpoint\nfrom cores.axi.axi_lite_peripheral_connector import AxiLitePeripheralConnector\nfrom cores.axi.full_to_lite import AxiFullToLiteBridge\nfrom cores.axi.interconnect import AxiInterconnect\nfrom soc.memorymap import Address\nfrom soc.soc_platform import SocPlatform\nfrom cores.primitives.xilinx_s7.ps7 import PS7\nfrom .program_bitstream_ssh import program_bitstream_ssh\n\n\nclass ZynqSocPlatform(SocPlatform):\n base_address = Address(0x4000_0000, 0, (0x7FFF_FFFF - 0x4000_0000) * 8)\n pydriver_memory_accessor = open(join(dirname(__file__), \"memory_accessor_devmem.py\")).read()\n\n def __init__(self, platform):\n super().__init__(platform)\n self.ps7 = PS7(here_is_the_only_place_that_instanciates_ps7=True)\n self.final_to_inject_subfragments.append((self.ps7, \"ps7\"))\n\n def peripherals_connect_hook(platform, top_fragment: Fragment, sames):\n if platform.peripherals:\n m = Module()\n platform.ps7.fck_domain(domain_name=\"axi_lite\", requested_frequency=100e6)\n if not hasattr(platform, \"is_sim\"): # we are not in a simulation platform\n axi_full_port: AxiEndpoint = platform.ps7.get_axi_gp_master(ClockSignal(\"axi_lite\"))\n axi_lite_bridge = m.submodules.axi_lite_bridge = DomainRenamer(\"axi_lite\")(\n AxiFullToLiteBridge(axi_full_port)\n )\n axi_lite_master = axi_lite_bridge.lite_master\n else: # we are in a simulation platform\n axi_lite_master = AxiEndpoint(addr_bits=32, data_bits=32, master=True, lite=True)\n self.axi_lite_master = axi_lite_master\n interconnect = m.submodules.interconnect = DomainRenamer(\"axi_lite\")(\n AxiInterconnect(axi_lite_master)\n )\n\n for peripheral in platform.peripherals:\n controller = DomainRenamer(\"axi_lite\")(AxiLitePeripheralConnector(peripheral))\n m.d.comb += interconnect.get_port().connect_slave(controller.axi)\n m.submodules += controller\n platform.to_inject_subfragments.append((m, \"axi_lite\"))\n self.prepare_hooks.append(peripherals_connect_hook)\n\n def pack_bitstream_fatbitstream(self, builder):\n self.add_file(\"to_raw_bitstream.py\", open(join(dirname(__file__), \"to_raw_bitstream.py\")).read())\n builder.append_host(\"python3 to_raw_bitstream.py {{name}}.bit > {{name}}.bin\")\n builder.append_self_extracting_blob_from_file(\"{{name}}.bin\", \"/usr/lib/firmware/{{name}}.bin\")\n builder.append_command(\"echo {{name}}.bin > /sys/class/fpga_manager/fpga0/firmware\\n\")\n\n def toolchain_program(self, *args, **kwargs):\n program_bitstream_ssh(self, *args, **kwargs)","sub_path":"src/soc/platforms/zynq/zynq_soc_platform.py","file_name":"zynq_soc_platform.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"7732303","text":"import socket\nimport sys\n\n#---- INIT ----\nif len(sys.argv) < 2 :\n\tip = '0.0.0.0'\n\tport = 10000\n\n\nelif len(sys.argv) < 3 :\n\tip = sys.argv[1]\n\tport = 10000\n\nelse :\n\tip = sys.argv[1]\n\tport = int(sys.argv[2])\n\n\n# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect the client\n# client.connect((target, port))\nclient.connect((ip, port))\n\n# send some data \nclient.send('TEST')\n\n# receive the response data (4096 is recommended buffer size)\nresponse = client.recv(4096)\n\nprint(response)","sub_path":"test/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"623863813","text":"import pandas as pd\nimport csv\nimport json\nimport os\n\nPATH = '../json_data_dump_2/'\nO_PATH = '../scrutiny-thresh-1.0-2-samples/'\ngrp_id = 'grp0'\nprint('finding file names')\nfile_names = os.listdir(PATH)\n\ncnt_histogram = {\n 2:0,\n 3:0,\n 4:0,\n 5:0,\n 6:0\n }\n\nranking = []\ncnt = 0\nfor name in file_names:\n cnt += 1\n data_path = PATH + name\n print(\"Currently on \" + str(cnt) + \"th file\")\n with open(data_path) as infile:\n final_dump = {}\n data = json.load(infile)\n n_nodes = len(data['nodes'])\n cnt_histogram[n_nodes] += 1\n\n if len(data['nodes']) == 2:\n\n d_fuv = abs(data['nodes'][0]['fuv_mag']-data['nodes'][1]['fuv_mag'])\n d_nuv = abs(data['nodes'][0]['nuv_mag']-data['nodes'][1]['nuv_mag'])\n if (d_fuv > 1.0 or d_nuv > 1.0):\n outlier_rec = [['ID', 'RA', 'DEC'],\n [data['nodes'][0]['obsid'],\n data['nodes'][0]['ra'],\n data['nodes'][0]['dec']],\n [data['nodes'][1]['obsid'],\n data['nodes'][1]['ra'],\n data['nodes'][1]['dec']]]\n\n with open(O_PATH + data['lvl1_grp_id'] +'.csv', \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(outlier_rec)\n\n if d_fuv > d_nuv:\n attr = d_fuv\n else:\n attr = d_nuv\n\n ranking.append([attr, data['lvl1_grp_id']])\n\nprint(cnt_histogram)\nranking.sort()\n\nwith open(O_PATH + 'ranking.csv', \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(ranking)\n","sub_path":"finding-outliers.py","file_name":"finding-outliers.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"166897426","text":"import matplotlib.image as mpimg\nimport numpy.testing as npt\nimport os\nimport numpy as np\nimport matplotlib.image as mpimg\nimport re\nfrom PIL import Image\n\n# Helper functions\ndef load_image(infilename):\n data = mpimg.imread(infilename)\n return data\n\ndef img_float_to_uint8(img):\n rimg = img - np.min(img)\n rimg = (rimg / np.max(rimg) * 255).round().astype(np.uint8)\n return rimg\n\n# Concatenate an image and its groundtruth\ndef concatenate_images(img, gt_img):\n nChannels = len(gt_img.shape)\n w = gt_img.shape[0]\n h = gt_img.shape[1]\n if nChannels == 3:\n cimg = np.concatenate((img, gt_img), axis=1)\n else:\n gt_img_3c = np.zeros((w, h, 3), dtype=np.uint8)\n gt_img8 = img_float_to_uint8(gt_img) \n gt_img_3c[:,:,0] = gt_img8\n gt_img_3c[:,:,1] = gt_img8\n gt_img_3c[:,:,2] = gt_img8\n img8 = img_float_to_uint8(img)\n cimg = np.concatenate((img8, gt_img_3c), axis=1)\n return cimg\n\ndef make_img_overlay(img, predicted_img):\n w = img.shape[0]\n h = img.shape[1]\n color_mask = np.zeros((w, h, 3), dtype=np.uint8)\n color_mask[:,:,0] = predicted_img*255\n\n img8 = img_float_to_uint8(img)\n background = Image.fromarray(img8, 'RGB').convert(\"RGBA\")\n overlay = Image.fromarray(color_mask, 'RGB').convert(\"RGBA\")\n new_img = Image.blend(background, overlay, 0.2)\n return new_img\n\nforeground_threshold = 0.25 # percentage of pixels > 1 required to assign a foreground label to a patch\n\n# assign a label to a patch\ndef patch_to_label(patch):\n df = np.mean(patch)\n if df > foreground_threshold:\n return 1\n else:\n return 0\n\n\ndef mask_to_submission_strings(im, img_number):\n \"\"\"Reads a single image and outputs the strings that should go into the submission file\"\"\"\n patch_size = 16\n for j in range(0, im.shape[1], patch_size):\n for i in range(0, im.shape[0], patch_size):\n patch = im[i:i + patch_size, j:j + patch_size]\n label = patch_to_label(patch)\n yield(\"{:03d}_{}_{},{}\".format(img_number, j, i, label))\n\n\ndef masks_to_submission(submission_filename, *images):\n \"\"\"Converts images into a submission file\"\"\"\n with open(submission_filename, 'w') as f:\n f.write('id,prediction\\n')\n for index, image in enumerate(images[0:]):\n f.writelines('{}\\n'.format(s) for s in mask_to_submission_strings(image, index+1))\n\n# Extract patches from a given image\ndef img_crop_(im, w, h):\n list_patches = []\n imgwidth = im.shape[0]\n imgheight = im.shape[1]\n is_2d = len(im.shape) < 3\n \n for i in range(0, imgheight, h):\n i0 = i\n \n for j in range(0, imgwidth, w):\n j0 = j\n \n j_plus_w = j+w-1\n i_plus_h = i+h-1\n \n if i_plus_h >= imgheight:\n i_plus_h = imgheight-1\n i0= imgheight - h\n \n if j_plus_w >= imgwidth:\n j_plus_w = imgwidth-1\n j0 = imgwidth - w\n \n if is_2d:\n im_patch = im[i0:i_plus_h+1, j0:j_plus_w+1]\n else:\n im_patch = im[i0:i_plus_h+1, j0:j_plus_w+1, :]\n \n list_patches.append(im_patch)\n\n return list_patches\n\ndef build_from_patches(list_patches, h, w):\n patch_width = list_patches[0].shape[0]\n patch_height = list_patches[0].shape[1]\n is_2d = len(list_patches[0].shape) < 3\n rebuild_img = np.zeros((h, w))\n \n npt.assert_equal(is_2d == True, True)\n npt.assert_equal(len(list_patches) == 4, True)\n \n for i in range(0, patch_height):\n for j in range(0, patch_width):\n rebuild_img[i,j] = list_patches[0][i,j]\n \n width_begin = patch_width-(w%patch_width)\n for i in range(0, patch_height):\n for j in range(width_begin, patch_width):\n rebuild_img[i,patch_width+j-width_begin] = list_patches[1][i,j]\n \n height_begin = patch_height-(h%patch_height)\n for i in range(height_begin, patch_height):\n for j in range(0, patch_width):\n rebuild_img[patch_height+i-height_begin,j] = list_patches[2][i,j]\n \n for i in range(patch_height-(h%patch_height), patch_height):\n for j in range(0, patch_width):\n rebuild_img[patch_height+i-height_begin,patch_width+j-width_begin] = list_patches[3][i,j]\n \n return rebuild_img\n\ndef predict(image_input, model):\n patches = img_crop_(image_input, 400, 400)\n patches = np.array(patches)\n patch_predictions = model.predict(patches, verbose=1)\n patch_predictions = np.squeeze(patch_predictions)\n img = build_from_patches(patch_predictions, 608, 608)\n return img","sub_path":"playground/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"295630192","text":"from pathlib import Path\nfrom diot import Diot\nfrom bioprocs.utils import shell2 as shell\nfrom bioprocs.utils.reference import bamIndex\nfrom bioprocs.utils.tsvio2 import TsvReader, TsvWriter\n\ninfile = {{i.infile | quote}}\noutdir = Path({{o.outdir | quote}})\noutfile = {{o.outfile | quote}}\nsample = {{i.infile | stem2 | quote}}\nhla_la = {{args.hla_la | quote}}\npicard = {{args.picard |quote}}\nbwa = {{args.bwa | quote}}\njava = {{args.java | quote}}\nsamtools = {{args.samtools | quote}}\nnthread = {{args.nthread | repr}}\nparams = {{args.params | repr}}\n\nbamIndex(infile, samtools = samtools)\nshell.load_config(hla_la = hla_la)\n\nparams.picard_sam2fastq_bin = shell.which(picard)\nparams.bwa_bin = shell.which(bwa)\nparams.samtools_bin = shell.which(samtools)\nparams.java_bin = shell.which(java)\nparams.maxThreads = nthread\nparams.workingDir = outdir.parent\nparams.sampleID = sample\nparams.BAM = infile\nparams.graph = 'PRG_MHC_GRCh38_withIMGT'\n\nshell.fg.hla_la(**params)\n\nhlafile = outdir.joinpath('hla', 'R1_bestguess_G.txt')\nreader = TsvReader(hlafile)\nwriter = TsvWriter(outfile)\nwriter.cnames = ['Type', 'Allele', 'Reported'] + [cname for cname in reader.cnames if cname != 'Allele']\nwriter.writeHead()\n\nhits = []\nfor r in reader:\n\tif r.Locus not in hits:\n\t\thits.append(r.Locus)\n\t\tr.Type = r.Locus + ('_' if len(r.Locus) > 1 else '') + '1'\n\telse:\n\t\tr.Type = r.Locus + ('_' if len(r.Locus) > 1 else '') + '2'\n\tr.Reported = r.Allele\n\tr.Allele = 'HLA-' + r.Allele\n\twriter.write(r)\n","sub_path":"bioprocs/scripts/imtherapy/pHLA_LA.py","file_name":"pHLA_LA.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"431067506","text":"from __future__ import division, print_function, absolute_import\r\nimport os\r\nfrom tabula import read_pdf\r\nimport shutil\r\nimport pypyodbc\r\n\r\nstrDirectory=\"PDFs\\\\\"\r\nlMonths=['Jan?17','Feb?17','Mar?17','Apr?17','May?17','Jun?17','Jul?17','Aug?17','Sep?17','Oct?17','Nov?17','Dec?17']\r\nmonth_dict = {\"Jan?17\":\"01\",\"Feb?17\":\"02\",\"Mar?17\":\"03\",\"Apr?17\":\"04\", \"May?17\":\"05\", \"Jun?17\":\"06\",\"Jul?17\":\"07\",\"Aug?17\":\"08\",\"Sep?17\":\"09\",\"Oct?17\":\"10\",\"Nov?17\":\"11\",\"Dec?17\":\"12\"}\r\nconnection = pypyodbc.connect(r'Driver={SQL Server};Server=DEFR2DB61\\GTT;Database=YE_Mapping;Trusted_Connection=yes;')\r\ncursor = connection.cursor()\r\nSQLCommand = (\"INSERT INTO TS_TAX_RECEIVED \"\r\n \"(GID, Period, Payment_name_detail,AmountHome,Rate, CurrencyHost, id_file) \"\r\n\"VALUES (?,?,?,?,?,?,?) select SCOPE_IDENTITY()\")\r\ndef to_dict(name):\r\n return month_dict[name]\r\n\r\ndef ConvertPdfToExcel(sPath):\r\n dfPDF=read_pdf(sPath, pages=\"1\")\r\n dfPDF=dfPDF.dropna(axis=0,how='all')\r\n #countColumn=len(dfPDF.columns) - 1\r\n #dfPDF.drop(dfPDF.columns[[0,countColumn]], axis=1,inplace=True)\r\n dfPDF.columns.values[1] = 'Concept'\r\n bColumnHeaderCorrect=(True in dfPDF.columns.isin(lMonths))\r\n print(dfPDF)\r\n if (bColumnHeaderCorrect==True):\r\n sGID = os.path.splitext(sPath)[0][-8:]\r\n print(sPath)\r\n print(sGID)\r\n iterdfPDF = iter(dfPDF)\r\n next(iterdfPDF)\r\n for column in iterdfPDF:\r\n sServiceMonth=\"2017\" + to_dict(column)\r\n print(sServiceMonth)\r\n dfRev = dfPDF.loc[dfPDF.Component == \"Total Compensation (EUR)\"]\r\n sTotal_Revenues=dfRev[column].tolist()[0]\r\n fTotal_Revenues=float(sTotal_Revenues.replace(' ', '').replace(',', '.'))\r\n dfDed = dfPDF.loc[dfPDF.Component == \"Social Security Contributions\"]\r\n sTotal_Deduction=dfDed[column].tolist()[0]\r\n fTotal_Deduction=float(sTotal_Deduction.replace(' ', '').replace(',', '.'))\r\n dfExch = dfPDF.loc[dfPDF.Component == \"Exchange rate\"]\r\n sExchange_Rate = dfExch[column].tolist()[0]\r\n fExchange_Rate=float(sExchange_Rate.replace(' ', '').replace(',', '.'))\r\n Values = [sGID, sServiceMonth, 'TOTAL REVENUES',fTotal_Revenues,fExchange_Rate,'CLP', 1158]\r\n Values1 = [sGID, sServiceMonth, 'TOTAL DEDUCTIONS',fTotal_Deduction,fExchange_Rate,'CLP', 1158]\r\n #cursor.execute(SQLCommand, Values)\r\n #cursor.execute(SQLCommand, Values1)\r\n #connection.commit()\r\n print(dfPDF.to_string())\r\n else:\r\n print(\"Failed: \" + sPath)\r\n shutil.copy(rootpath1+ sPath,\r\n rootpath2+ os.path.basename(sPath))\r\n\r\n\r\n\r\nfor root, dirs, files in os.walk(strDirectory):\r\n for filename in files:\r\n #try:\r\n ConvertPdfToExcel(strDirectory + \"\\\\\" + filename)\r\n #except:\r\n #print(\"Failed: \" + filename)\r\n #shutil.copy(rootpath1+strDirectory+filename, rootpath2+\"Failed\\\\\"+filename)","sub_path":"Python/convert-pdf.py","file_name":"convert-pdf.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"112577508","text":"from django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.core import signing\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\n\nfrom . import constants as c\n\n\nclass Verifier():\n email_subject_template = 'email/verify_subject.txt'\n email_body_template_html = 'email/verify_body.html'\n email_body_template_txt = 'email/verify_body.txt'\n\n def __init__(self, user):\n self.user = user\n\n def get_email_context(self, verification_key):\n url = reverse('accounts:verify', kwargs={'verification_key': verification_key})\n return {\n 'domain': Site.objects.get_current().domain,\n 'url': url,\n 'user': self.user,\n }\n\n def send_verify_email(self):\n verification_key = self.get_verification_key()\n context = self.get_email_context(verification_key)\n subject = render_to_string(\n template_name=self.email_subject_template,\n context=context,\n )\n # Force subject to a single line to avoid header-injection issues\n subject = ''.join(subject.splitlines())\n message = render_to_string(\n template_name=self.email_body_template_txt,\n context=context,\n )\n html_message = render_to_string(\n template_name=self.email_body_template_html,\n context=context,\n )\n self.user.email_user_alternative(subject, message, from_email=settings.VERIFICATION_FROM_EMAIL,\n html_message=html_message, bcc=[settings.VERIFICATION_FROM_EMAIL])\n\n def get_verification_key(self):\n return signing.dumps(\n obj=self.user.get_username(),\n salt=settings.VERIFICATION_SALT,\n )\n\n\nclass VerificationError(Exception):\n pass\n\n\ndef send_manually_verify_email(user):\n ctx = {'user': user}\n subject = c.VERIFY_MANUALLY_EMAIL_SUBJECT\n email_body_template_html = 'email/verify_manual_body.html'\n email_body_template_txt = 'email/verify_manual_body.txt'\n\n message = render_to_string(\n template_name=email_body_template_txt,\n context=ctx,\n )\n html_message = render_to_string(\n template_name=email_body_template_html,\n context=ctx,\n )\n\n user.email_user_alternative(subject, message, from_email=settings.VERIFICATION_FROM_EMAIL,\n html_message=html_message, bcc=[settings.VERIFICATION_FROM_EMAIL])\n","sub_path":"Maco/accounts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"56298063","text":"# -*- coding: utf-8 -*-\n\n#################################################\n# tf.contrib.learn Quickstart\n#################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\n\n# Data sets\nIRIS_TRAINING = \"iris_training.csv\"\nIRIS_TEST = \"iris_test.csv\"\n\n#################################################\n# エントリーポイント\n# [Args]:\n#################################################\nif __name__ == '__main__':\n\n # Load datasets.\n training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING,\n target_dtype=np.int)\n test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST,\n target_dtype=np.int)\n\n # Specify that all features have real-value data0\n # 萼片の幅、萼片の高さ、花弁の幅、花弁の高さの4次元データ\n # (sepal width, sepal height, petal width, and petal height)\n feature_columns = [tf.contrib.layers.real_valued_column(\"\", dimension=4)]\n\n # Build 3 layer DNN with 10, 20, 10 units respectively.\n classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,\n hidden_units=[10, 20, 10],\n n_classes=3,\n model_dir=\"/tmp/iris_model\")\n\n # Fit model.\n print('--------------------------------------------------')\n print('Start fitting.')\n classifier.fit(x=training_set.data,\n y=training_set.target,\n steps=2000)\n\n # Evaluate accuracy.\n accuracy_score = classifier.evaluate(x=test_set.data,\n y=test_set.target)[\"accuracy\"]\n print('--------------------------------------------------')\n print('Accuracy: {0:f}'.format(accuracy_score))\n\n # Classify two new flower samples.\n # 新しい2サンプルを判定。正解は[1 2]らしい。\n new_samples = np.array(\n [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)\n y = classifier.predict(new_samples)\n print('--------------------------------------------------')\n print('Predictions: {}'.format(str(y)))","sub_path":"09.tf_contrib_learn/quick_start.py","file_name":"quick_start.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"332501474","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# Messy Things project organizer for Blender.\n# Copyright (C) 2017-2019 Mikhail Rachinskiy\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# ##### END GPL LICENSE BLOCK #####\n\n\nfrom bpy.types import Operator\nfrom bpy.props import BoolProperty\n\nfrom .cleanup_obj import cleanup_objects\nfrom .cleanup_mod import cleanup_modifiers\nfrom .cleanup_mat import cleanup_materials\nfrom .cleanup_gp import cleanup_gpencil\n\n\nclass SCENE_OT_messythings_cleanup(Operator):\n bl_label = \"Messy Things Cleanup\"\n bl_description = \"Remove redundant or purge all datablocks of set type\"\n bl_idname = \"scene.messythings_cleanup\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n use_cleanup_objects: BoolProperty(\n name=\"Objects\",\n description=(\n \"Remove lattice, curve and empty mesh objects that are not in use by \"\n \"modifiers, constraints, curve Bevel Object and Taper Object properties\"\n ),\n )\n use_cleanup_modifiers: BoolProperty(\n name=\"Modifiers\",\n description=\"Remove Curve, Lattice, Boolean and Shrinkwrap modifiers with empty Object or Target fields\",\n )\n use_cleanup_materials: BoolProperty(\n name=\"Materials (Purge)\",\n description=\"Purge all materials from file, additionally remove material slots from objects\",\n )\n use_cleanup_gpencil: BoolProperty(\n name=\"Annotations\",\n description=\"Remove redundant (Blender 2.7x) grease pencil object data from non grease pencil objects\"\n )\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False\n\n col = layout.column(align=True)\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_objects\")\n row.label(icon=\"OBJECT_DATA\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_modifiers\")\n row.label(icon=\"MODIFIER_DATA\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_materials\")\n row.label(icon=\"MATERIAL\")\n\n row = col.row(align=True)\n row.prop(self, \"use_cleanup_gpencil\")\n row.label(icon=\"OUTLINER_OB_GREASEPENCIL\")\n\n def execute(self, context):\n msgs = []\n\n if self.use_cleanup_objects:\n curve, lat, mesh = cleanup_objects(context)\n msgs.append(f\"{curve} curve\")\n msgs.append(f\"{lat} lattice\")\n msgs.append(f\"{mesh} mesh\")\n\n if self.use_cleanup_modifiers:\n mod = cleanup_modifiers(context)\n msgs.append(f\"{mod} modifiers\")\n\n if self.use_cleanup_materials:\n mat = cleanup_materials(context)\n msgs.append(f\"{mat} materials\")\n\n if self.use_cleanup_gpencil:\n gp = cleanup_gpencil(context)\n msgs.append(f\"{gp} grease pencil\")\n\n if not msgs:\n return {\"CANCELLED\"}\n\n msg = \"Removed: \" + \", \".join(msgs)\n self.report({\"INFO\"}, msg)\n\n return {\"FINISHED\"}\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n","sub_path":"All_In_One/addons/messythings/op_cleanup/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"420430673","text":"import torch\nimport numpy as np\nimport argparse\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nimport os,copy\nimport matplotlib.pyplot as plt\nimport _pickle as cPickle\nfrom transformer_imputation_helper import *\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True\ntorch.manual_seed(1)\ntorch.cuda.manual_seed(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-d', '--device', type=int,help='device')\nparser.add_argument('-o', '--out-dir', type=str,help='dir to save checkpoints')\nparser.add_argument('-t', '--test', action='store_true',help='test')\nparser.add_argument('-w', '--warm-start', action='store_true',help='warm_start')\nparser.add_argument('-f', '--test-file', type=str,help='test-file')\nparser.add_argument('-e', '--start-epoch', type=int,help='checkpoint')\nparser.add_argument('-n', '--expname', type=str,help='checkpoint')\nparser.add_argument('-l', '--load-epoch', type=int,help='checkpoint')\nargs = parser.parse_args()\n\n\nlog_file = 'transformer_janta_%d_%s'%(args.load_epoch,args.expname)\n\nargs.device = 0\nargs.out_dir = '/mnt/infonas/blossom/pbansal/dump'\ndevice = torch.device('cuda:%d'%args.device)\nbatch_size = 64\nlr = 1e-4\n\ntrain_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_train_examples.npy')\nval_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_test_examples.npy')\nupdate_set = TransformerDataset('../dataset/2djantahack_complete.npy','../dataset/2djantahack_all_examples.npy')\n\ntrain_loader = torch.utils.data.DataLoader(train_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\nval_loader = torch.utils.data.DataLoader(val_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\nupdate_loader = torch.utils.data.DataLoader(update_set,batch_size = batch_size,drop_last = False,shuffle=True,collate_fn = transformer_collate)\n\nif (args.expname == 'both' or args.expname == 'both2'):\n model = OurModel(sizes=[76,28],ninp=32,embedding_size=16,nhid=32,nlayers=4,nhead=2,other_residuals=True).to(device)\nelse :\n model = OurModel(sizes=[76,28],ninp=32,embedding_size=16,nhid=32,nlayers=4,nhead=2,other_residuals=False).to(device)\n \nbest_state_dict = model.state_dict()\nbest_loss = float('inf')\nwriter = SummaryWriter(os.path.join('runs',log_file))\n\n\nprint (\"Starting Stage 1\")\n\noptim = torch.optim.Adam(model.parameters(),lr=lr)\n\nmax_epoch = 200\nswitch_epoch = args.load_epoch\niteration = int((args.load_epoch*len(train_set))/batch_size)\nstart_epoch = args.load_epoch\n\nfor epoch in range(start_epoch,max_epoch):\n print (\"Starting Epoch : %d\"%epoch)\n\n if (epoch == switch_epoch):\n print (\"Starting Stage 2\")\n model_dict = model.state_dict()\n best_state_dict = torch.load('best_janta_%depochs'%args.load_epoch)\n best_state_dict = {k: v for k, v in best_state_dict.items() if k not in ['outlier_layer1.weight','outlier_layer1.bias'] }\n model_dict.update(best_state_dict)\n model.load_state_dict(model_dict)\n residuals = torch.zeros(update_set.feats.shape).to(device)\n other_residuals = torch.zeros(update_set.feats.shape).to(device)\n means = torch.zeros(update_set.feats.shape).to(device)\n stds = torch.zeros(update_set.feats.shape).to(device)\n with torch.no_grad():\n for inp_,context_info in update_loader :\n out_,y_pred,sigma_pred = model.core(inp_.to(device),context_info)\n temp = (out_.to(device)-y_pred)/torch.exp(sigma_pred/2)\n if (args.expname == 'both'):\n other_residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = temp.to(device) # change here\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n elif (args.expname == 'both2'):\n other_residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = (out_.to(device)-y_pred) # change here\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n elif (args.expname == 'residuals'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = temp.to(device) # change here\n elif (args.expname == 'residuals2'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = (out_.to(device)-y_pred) # change here\n elif (args.expname == 'normalised'):\n residuals[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = out_.to(device) # change here\n else :\n raise Exception\n means[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = y_pred\n stds[context_info['time'],context_info['index'][:,0],context_info['index'][:,1]] = sigma_pred\n if (args.expname == 'both' or args.expname == 'both2'):\n model.other_residuals = other_residuals\n model.residuals = residuals\n model.means = means\n model.stds = stds\n model.switch()\n optim.zero_grad()\n \n if (epoch % 1 == 0):\n loss_mre_num,loss_mre_den,loss_crps = 0,0,0\n with torch.no_grad():\n for inp_,context_info in val_loader :\n loss = model.validate(inp_.to(device),context_info)\n loss_mre_num += loss['mae']*inp_.shape[0]\n loss_mre_den += loss['sum']*inp_.shape[0]\n loss_crps += loss['crps']*inp_.shape[0]\n writer.add_scalar('validation/mre_loss',loss_mre_num/loss_mre_den,iteration)\n writer.add_scalar('validation/mae_loss',loss_mre_num/len(val_set),iteration)\n writer.add_scalar('validation/crps_loss',loss_crps/len(val_set),iteration)\n \n if ((not model.stage2) and loss_crps < best_loss):\n best_loss = loss_crps\n best_state_dict = model.state_dict()\n \n print ('done validation')\n \n for inp_,context_info in train_loader :\n loss = model(inp_.to(device),context_info)\n optim.zero_grad()\n loss['nll'].backward()\n optim.step()\n iteration += 1\n writer.add_scalar('training/nll_loss',loss['nll'],iteration)\n writer.add_scalar('training/mae_loss',loss['mae'],iteration)\n\n\n\n\n","sub_path":"Transformer1Stage/transformer_imputation_ablation.py","file_name":"transformer_imputation_ablation.py","file_ext":"py","file_size_in_byte":6666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"153283788","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 11 11:42:19 2016\n\n@author: aaa34169\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport scipy as sp\nfrom scipy import signal\nimport btk\nimport pdb\n\nsys.path.append('C:\\\\Users\\\\AAA34169\\\\Documents\\\\Programming\\\\API\\\\pyCGA\\\\')\nimport core.tools as ct\n\nimport core.cgmModel as cgm\nimport core.modelFilters as cmf\nimport core.modelDecorator as cmd\nimport core.bodySegmentParameters as cbsp\nimport core.forceplates as cpf\nimport core.enums as cenum\nimport core.signal_processing as csip\nimport core.analysis as can\nimport core.cycle as cc\n\n\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \nplt.close(\"all\")\n\n\n\n\n\nclass GaitAnalysisTest(): \n\n @classmethod\n def viconCGM1(cls):\n \"\"\"\n \n \"\"\"\n\n MAIN_PATH = \"C:\\\\Users\\\\AAA34169\\\\Documents\\\\VICON DATA\\\\pyCGA-Data\\\\CGM1\\\\PIG standard\\\\basic-filtered\\\\\"\n \n \n kinematicAcqs=[]\n for gaitKinematicFilename in [\"MRI-US-01, 2008-08-08, 3DGA 12.c3d\" , \"MRI-US-01, 2008-08-08, 3DGA 13.c3d\",\"MRI-US-01, 2008-08-08, 3DGA 14.c3d\"]:\n acqGaitKinematics = ct.smartReader(str(MAIN_PATH + gaitKinematicFilename))\n kinematicAcqs.append(acqGaitKinematics)\n\n kineticAcqs=[] # To \n for gaitKineticFilename in [\"MRI-US-01, 2008-08-08, 3DGA 12.c3d\" , \"MRI-US-01, 2008-08-08, 3DGA 13.c3d\"]:\n acqGaitKinetics = ct.smartReader(str(MAIN_PATH + gaitKineticFilename))\n kineticAcqs.append(acqGaitKinetics)\n\n # -------------\n # CYCLE ANALYSIS\n #-------------\n # cycle builder\n cyclesBuilder = cc.GaitAnalysisCyclesBuilder(spatioTemporalAcquisitions=None, \n kinematicAcquisitions=kinematicAcqs,\n kineticAcquisitions= kineticAcqs,\n emgAcquisitions=None\n ) \n \n\n # cycle filter \n cf = cc.CyclesFilter()\n cf.setBuilder(cyclesBuilder) \n cyclesAnalysis = cf.getCyclesAnalysis()\n \n # -------------\n # GAIT ANALYSIS\n #-------------\n\n # dictionnaries \n subject={\"ipp\": \"000\",\n \"firstname\": \"NA\",\n \"surname\": \"NA\",\n \"sex\": \"M\",\n \"dob\": \"-\"\n }\n \n experimental={ \n \"date\": \"NA\",\n \"doctor\": \"NA\",\n \"context\": \"Research\",\n \"task\": \"S\",\n \"shoe\": \"N\",\n \"orthosis Prothesis\": \"N\",\n \"external Device\": \"N\",\n \"person assistance\": \"N\",\n \"nerve-block left\": \"NA\",\n \"nerve-block right\": \"NA\"\n } \n \n kinematicLabelsDict ={ 'Left': [\"LHipAngles\",\"LKneeAngles\",\"LAnkleAngles\"],\n 'Right': [\"RHipAngles\",\"RKneeAngles\",\"RAnkleAngles\"] }\n\n kineticLabelsDict ={ 'Left': [\"LHipMoment\",\"LKneeMoment\",\"LAnkleMoment\", \"LHipPower\",\"LKneePower\",\"LAnklePower\"],\n 'Right': [\"RHipMoment\",\"RKneeMoment\",\"RAnkleMoment\", \"RHipPower\",\"RKneePower\",\"RAnklePower\"]}\n\n \n \n # analysis Builder\n analysisBuilder = can.ConcreteGaitAnalysisBuilder(cyclesAnalysis,\n kinematicLabelsDict,\n kineticLabelsDict,\n modelLabel = \"NA\",\n subjectInfos = subject,\n experimentalInfos = experimental)\n \n # Filter\n af = can.AnalysisFilter()\n af.setBuilder(analysisBuilder)\n af.construct()\n stats = af.getStats() \n\n #af.exportDataFrame(\"fileOut\")\n\n\nif __name__ == \"__main__\":\n \n GaitAnalysisTest.viconCGM1()\n","sub_path":"tests/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"56239463","text":"import gdal\nimport gdalconst\nimport struct\n\nclass GeoTiffHandler:\n\n def __init__(self, file_name):\n self._fmttypes = {\n\t gdalconst.GDT_Byte: 'B',\n\t gdalconst.GDT_Int16: 'h',\n\t gdalconst.GDT_UInt16: 'H',\n\t gdalconst.GDT_Int32: 'i',\n\t gdalconst.GDT_UInt32: 'I',\n\t gdalconst.GDT_Float32: 'f',\n\t gdalconst.GDT_Float64: 'f'\n\t }\n self.ds = gdal.Open(file_name, gdalconst.GA_ReadOnly)\n if self.ds is None:\n raise FileNotFoundError(file_name)\n self.transf = self.ds.GetGeoTransform()\n self.cols = self.ds.RasterXSize\n self.rows = self.ds.RasterYSize\n self.bands = self.ds.RasterCount\n self.transfInv = gdal.InvGeoTransform(self.transf)\n\n def _pt2fmt(self, pt):\n return self._fmttypes.get(pt, 'x')\n\n def get_value_at_position(self, lat, lon, raster_band=1):\n band = self.ds.GetRasterBand(raster_band)\n bandtype = gdal.GetDataTypeName(band.DataType)\n px, py = gdal.ApplyGeoTransform(self.transfInv, lon, lat)\n if px > self.cols or py > self.rows:\n return None\n structval = band.ReadRaster(int(px), int(py), 1, 1,\n buf_type=band.DataType)\n fmt = self._pt2fmt(band.DataType)\n value = struct.unpack(fmt, structval)\n if value[0] == band.GetNoDataValue():\n if fmt == 'f':\n return float('nan')\n else:\n return None\n else:\n result = value[0]\n return value[0]\n\n def get_values_at_position(self, lat, lon):\n results = []\n for raster_band in range(1, self.bands+1):\n results.append(self.get_value_at_position(lat, lon, raster_band))\n return results\n","sub_path":"surface_map/geotiff_handler.py","file_name":"geotiff_handler.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"78673863","text":"from dlcliche.image import *\nfrom lib_fat2019 import *\n\nAPPNAME = 'final'\n\nconf.DURATION = 8\nconf.AUG_LEVEL = 1\nconf.CV = 1\nconf.RELABEL = ''\n\nconf.DATA = Path('/mnt/dataset/freesound-audio-tagging-2019')\nconf.ROOT = Path('/mnt/dataset/fat2019_files')\nconf.WORK = Path('/mnt/dataset/work/fat2019')\n\nconf.MODEL = 'specgram'\nconf.PRETRAINED_MODEL = 'base_models/base_36_specgram_6s_l1_best2.pth' # 'base_models/base_16_specgram_best.pth'\n\nconf.RESAMPLE = False\nconf.RESAMPLE_SIZES = None\n\nconf.USE_NOISY = True\nconf.NOISY_DATA = 'NOISY_SINGLE'\nconf.NOISY_SAMPLE_SIZES = None\n\nconf.NOISY_REMOVE_NG = ['Bus', 'Run',\n 'Male_speech_and_man_speaking',\n 'Cricket',\n 'Race_car_and_auto_racing',\n 'Printer',\n 'Church_bell',\n 'Crowd',\n 'Gong',\n 'Mechanical_fan',\n 'Traffic_noise_and_roadway_noise',\n 'Waves_and_surf']\n\nconf.noisy_OKs = ['Accelerating_and_revving_and_vroom', 'Accordion', 'Acoustic_guitar', 'Applause', 'Bark',\n 'Bass_drum', 'Bass_guitar', 'Bathtub_(filling_or_washing)', 'Bicycle_bell', 'Burping_and_eructation',\n 'Buzz', 'Car_passing_by', 'Cheering', 'Chewing_and_mastication', 'Child_speech_and_kid_speaking',\n 'Chink_and_clink', 'Chirp_and_tweet', 'Clapping', 'Computer_keyboard', 'Crackle',\n 'Cupboard_open_or_close', 'Cutlery_and_silverware','Dishes_and_pots_and_pans', 'Drawer_open_or_close', 'Drip',\n 'Electric_guitar', 'Fart', 'Female_singing', 'Female_speech_and_woman_speaking', 'Fill_(with_liquid)',\n 'Finger_snapping', 'Frying_(food)', 'Gasp', 'Glockenspiel', 'Gurgling',\n 'Harmonica', 'Hi-hat', 'Hiss', 'Keys_jangling', 'Knock',\n 'Male_singing', 'Marimba_and_xylophone', 'Meow', 'Microwave_oven', 'Motorcycle',\n 'Purr', 'Raindrop', 'Scissors', 'Screaming', 'Shatter',\n 'Sigh', 'Sink_(filling_or_washing)', 'Skateboard', 'Slam', 'Sneeze',\n 'Squeak', 'Stream', 'Strum', 'Tap', 'Tick-tock',\n 'Toilet_flush', 'Trickle_and_dribble', 'Walk_and_footsteps', 'Water_tap_and_faucet', 'Whispering',\n 'Writing', 'Yell', 'Zipper_(clothing)']\n\nconf.FORCE_SINGLE_LABEL = True\nconf.SUPER_MIXUP = True\n\nupdate_conf(conf)\nset_fastai_random_seed()\n\nbest_weight = f'{conf.NAME}_{APPNAME}'\n\ndf, X_train, learn, data = fat2019_initialize_training(conf)\n\nlearn.fit_one_cycle(8, 1e-1)\nlearn.fit_one_cycle(10, 1e-2)\nlearn.unfreeze()\nlearn.fit_one_cycle(20, 1e-2)\nlearn.fit_one_cycle(20, 1e-2)\nlearn.fit_one_cycle(20, 1e-2)\n\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(30, slice(1e-3, 1e-2))\nlearn.fit_one_cycle(300, slice(1e-4, 1e-2), callbacks=get_saver_callbacks(conf, learn, best_weight))\n\nprint(f'Writing {best_weight}.csv ...')\ndf = evaluate_weight(conf, f'{best_weight}', for_what='train')\ndf.to_csv(f'work/models/{best_weight}.csv')\nprint('lwlrap', df_lwlrap_sum(df))\nprint(df[:10])\n","sub_path":"app-final-sp1s_8s.py","file_name":"app-final-sp1s_8s.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"457203188","text":"###########################################\n\n## Author : Divyesh Mehta\n## Type : Algorithm\n## Name : Dining Philosopher Problem\n## Language : Python\n\n###########################################\n\n#This program is an implementation of Dining Philosopher Problem\n\nimport threading\nimport random\nimport time\n\nclass Philosopher(threading.Thread):\n process = True\n\n def __init__(self, name, rfork, lfork):\n threading.Thread.__init__(self)\n self.name = name\n self.lfork = rfork\n self.rfork = lfork\n\n def run(self):\n while (self.process):\n time.sleep(random.uniform(1, 10))\n print(\"{} is hungry\".format(self.name))\n self.eat()\n\n def eat(self):\n fork1, fork2 = self.lfork, self.rfork\n\n while self.process:\n fork1.acquire(True)\n locked = fork2.acquire(False)\n if locked:\n break\n fork1.release()\n print(\"{} is swapping forks\".format(self.name))\n fork1, fork2 = fork2, fork1\n else:\n return\n\n self.eating()\n fork2.release()\n fork1.release()\n\n def eating(self):\n print(\"{} starts eating\".format(self.name))\n time.sleep(random.uniform(1, 10))\n print(\"{} started thinking\".format(self.name))\n\n\ndef DiningPhilosophers():\n forks = [threading.Lock() for n in range(5)]\n philosopher_names = ['Binod', 'Rashi', 'Gopi', 'Riya', 'Mike']\n\n philosophers = [Philosopher(philosopher_names[i], forks[i % 5], forks[(i + 1) % 5]) \\\n for i in range(5)]\n\n random.seed(100)\n Philosopher.process = True\n for p in philosophers:\n p.start()\n time.sleep(100)\n Philosopher.process = False\n print(\"Process Finished :)\")\n return\n\nDiningPhilosophers()\n","sub_path":"Python/dining_philosopher_problem.py","file_name":"dining_philosopher_problem.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"388673093","text":"\"\"\"\n\n------------------SENTIMENT ANALYSIS---------------------\n\n\n\"\"\"\n\nkey = \"c268c7f360854a62ae033b75205b916c\"\nendpoint = \"https://openbooknlp.cognitiveservices.azure.com/\"\n\n# from azure.ai.textanalytics import single_analyze_sentiment\n# from azure.ai.textanalytics import single_detect_language\n# from azure.ai.textanalytics import single_recognize_entities\n\nfrom azure.ai.textanalytics import TextAnalyticsClient, TextAnalyticsApiKeyCredential\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=TextAnalyticsApiKeyCredential(key))\n\ndocuments = [\n \"I did not like the restaurant. The food was too spicy. I had such a horrible time there I feel depressed as I was lonely.\",\n \"I feel amazeballs today. Such a wonderful time at these hackathons! Happiest day of my life!\",\n \"Mala kahich mahit nahi kay challay ithe?\"\n]\ndef detect_language(documents):\n # [START batch_detect_language]\n result = text_analytics_client.detect_language(documents)\n text = []\n for idx, doc in enumerate(result):\n if not doc.is_error:\n text.append(\"Document text: {}\".format(documents[idx]))\n text.append(\"Language detected: {}\".format(doc.primary_language.name))\n text.append(\"ISO6391 name: {}\".format(doc.primary_language.iso6391_name))\n text.append(\"Confidence score: {}\\n\".format(doc.primary_language.score))\n if doc.is_error:\n text.append(doc.id)\n text.append(doc.error)\n return \"
\".join(text)\n # [END batch_detect_language]\n\ndef extract_key_phrases(documents):\n # [START batch_extract_key_phrases]\n \n text = []\n result = text_analytics_client.extract_key_phrases(documents)\n for doc in result:\n if not doc.is_error:\n text.append(\" \\n\".join(doc.key_phrases))\n elif doc.is_error:\n text.append('')\n # text.append(doc.error) \n\n return \",\".join(text)\n\ndef analyze_sentiment(documents):\n # [START batch_analyze_sentiment]\n result = text_analytics_client.analyze_sentiment(documents)\n docs = [doc for doc in result if not doc.is_error]\n sentiments = []\n sad_sentiments = []\n text = []\n for idx, doc in enumerate(docs):\n text.append(\"{}\".format(documents[idx]))\n text.append(\"sentiment: {} \\n\".format(doc.sentiment))\n sentiments.append(doc.sentiment)\n text.append(\" positive {0:.3f}; neutral {1:.3f}; negative {2:.3f} \\n\".format(\n doc.sentiment_scores.positive,\n doc.sentiment_scores.neutral,\n doc.sentiment_scores.negative,\n ))\n sad_sentiments.append(doc.sentiment_scores.negative)\n\n # for idx, sentence in enumerate(doc.sentences):\n # text.append(\"Sentence {} sentiment: {}\".format(idx+1, sentence.sentiment))\n # text.append(\"Sentence score: positive={0:.3f}; neutral={1:.3f}; negative={2:.3f}\".format(\n # sentence.sentiment_scores.positive,\n # sentence.sentiment_scores.neutral,\n # sentence.sentiment_scores.negative,\n # ))\n text.append(\"\\n\\n\\n\\n\\n\")\n \n top_sentiment = [[sentiments.count(i), i ] for i in set(sentiments)]\n top_sentiment.sort()\n top_sentiment = top_sentiment[-1][1]\n sad_avg = sum(sad_sentiments)/len(sad_sentiments)\n advice = 'keep up the mood'\n if sad_avg> 0.60 :\n advice = 'Hey are you okay? Talking to someone will make it better. Open your mind to a similar person or consult a profession in the chat section.'\n \n print('\\n\\n\\n\\n\\n',sad_avg,top_sentiment,sad_sentiments)\n return \"\\n\".join(text), top_sentiment, advice\n\n\"\"\"\n\n----------FLASK APP FROM HERE---------------------\n\n\n\"\"\"\nfrom flask import Flask\nfrom datetime import datetime\nfrom flask import render_template, request\nimport re\nimport os\nfrom ocr import return_ocr\nimport json\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\",result_string='',date=datetime.now(),txt_entry='')\n\n\n@app.route('/result',methods = ['POST'])\ndef result():\n if request.method == 'POST':\n result = request.form.get('paragraph_text')\n documents = result.split('.')\n result_string, top_sentiment, advice = analyze_sentiment(documents) \n phrases = extract_key_phrases(documents)\n dict_to_send = {\n \"01\":{\"tags\":phrases}\n }\n print(dict_to_send)\n with open('result.json', 'w') as fp:\n json.dump(dict_to_send, fp)\n return render_template(\"home.html\",result_string=result_string,date=datetime.now(),txt_entry=result,\n phrases=phrases, top_sentiment=top_sentiment, advice=advice)\n\n\n@app.route('/ocr',methods = ['POST','GET'])\ndef ocr():\n if request.method == 'POST':\n APP_ROOT = os.getcwd()\n target = os.path.join(APP_ROOT, 'static\\image')\n if not os.path.isdir(target):\n os.mkdir(target)\n for file in request.files.getlist(\"file\"):\n filename = file.filename\n destination = \"\\\\\".join([target, filename])\n file.save(destination)\n text, lines = return_ocr(destination)\n\n return render_template(\"home.html\",txt_entry=text,date=datetime.now())\n\n@app.route(\"/test\")\n\ndef test():\n sen = request.args.get('sen')\n confidence = request.args.get('confidence')\n\n return \"your sentiment is {} with confidence score {}\".format(sen,confidence)\n\n\n# @app.route(\"/new\")\n# def new():\n# journal = request.args.get('Param')\n# documents=[journal]\n# print (documents)\n# return analyze_sentiment(documents) + extract_key_phrases(documents) #+ detect_language(documents)\n\n # extract_key_phrases(documents)\n # analyze_sentiment(documents)\n # detect_language(documents)\n # print (journal)\n \n\n# New functions\n@app.route(\"/about/\")\ndef about():\n return render_template(\"about.html\")\n\n@app.route(\"/contact/\")\ndef contact():\n return render_template(\"contact.html\")\n\n\n@app.route(\"/search/\")\ndef search():\n with open('result.json') as json_file:\n user = json.load(json_file)\n tags = user[\"01\"][\"tags\"]\n tags = tags.split(',')\n\n with open('site/data.json') as json_file:\n users = json.load(json_file)\n user_tags = [users[i][\"tags\"] for i in users.keys()]\n user_tags = [x.split(',') for x in user_tags]\n \n return render_template(\"search.html\",len = len(tags), tags = tags, users = users, len_users = len(users) )\n\nif __name__ == '__main__':\n app.run(debug=True)\n# '127.0.0.1', port=8080,\n\n# @app.route(\"/api/data\")\n# def get_data():\n# return app.send_static_file(\"data.json\")","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"613511670","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:copyright: Copyright 2016-2020 Sphinx Confluence Builder Contributors (AUTHORS)\n:license: BSD-2-Clause (LICENSE)\n\"\"\"\n\nfrom bs4 import CData\nfrom tests.lib import build_sphinx\nfrom tests.lib import parse\nfrom tests.lib import prepare_conf\nimport os\nimport unittest\n\nclass TestConfluenceSphinxCodeblock(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.config = prepare_conf()\n test_dir = os.path.dirname(os.path.realpath(__file__))\n self.dataset = os.path.join(test_dir, 'datasets', 'common')\n\n def test_storage_sphinx_codeblock_caption(self):\n out_dir = build_sphinx(self.dataset, config=self.config,\n filenames=['code-block-caption'])\n\n with parse('code-block-caption', out_dir) as data:\n title_param = data.find('ac:parameter', {'ac:name': 'title'})\n self.assertIsNotNone(title_param)\n self.assertEqual(title_param.text, 'code caption test')\n\n def test_storage_sphinx_codeblock_default(self):\n out_dir = build_sphinx(self.dataset, config=self.config,\n filenames=['code-block'])\n\n with parse('code-block', out_dir) as data:\n code_macros = data.find_all('ac:structured-macro')\n self.assertIsNotNone(code_macros)\n self.assertEqual(len(code_macros), 3)\n\n for code_macro in code_macros:\n self.assertTrue(code_macro.has_attr('ac:name'))\n self.assertEqual(code_macro['ac:name'], 'code')\n\n # python block\n python_block = code_macros.pop(0)\n\n python_block_lang = python_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(python_block_lang)\n self.assertEqual(python_block_lang.text, 'python')\n\n python_block_linenumbers = python_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(python_block_linenumbers)\n self.assertEqual(python_block_linenumbers.text, 'true')\n\n python_block_body = python_block.find('ac:plain-text-body')\n python_block_cdata = next(python_block_body.children, None)\n self.assertIsNotNone(python_block_cdata)\n self.assertTrue(isinstance(python_block_cdata, CData))\n\n # sql block\n sql_block = code_macros.pop(0)\n\n sql_block_lang = sql_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(sql_block_lang)\n self.assertEqual(sql_block_lang.text, 'sql')\n\n sql_block_linenumbers = sql_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(sql_block_linenumbers)\n self.assertEqual(sql_block_linenumbers.text, 'false')\n\n sql_block_body = sql_block.find('ac:plain-text-body')\n sql_block_cdata = next(sql_block_body.children, None)\n self.assertIsNotNone(sql_block_cdata)\n self.assertTrue(isinstance(sql_block_cdata, CData))\n\n # ruby block\n ruby_block = code_macros.pop(0)\n\n ruby_block_lang = ruby_block.find('ac:parameter',\n {'ac:name': 'language'})\n self.assertIsNotNone(ruby_block_lang)\n self.assertEqual(ruby_block_lang.text, 'ruby')\n\n ruby_block_linenumbers = ruby_block.find('ac:parameter',\n {'ac:name': 'linenumbers'})\n self.assertIsNotNone(ruby_block_linenumbers)\n self.assertEqual(ruby_block_linenumbers.text, 'false')\n\n ruby_block_body = ruby_block.find('ac:plain-text-body')\n ruby_block_cdata = next(ruby_block_body.children, None)\n self.assertIsNotNone(ruby_block_cdata)\n self.assertTrue(isinstance(ruby_block_cdata, CData))\n\n # (check at least one code block's content)\n self.assertEqual(ruby_block_cdata,\n \"puts 'this is a print statement!'\")\n","sub_path":"tests/unit-tests/test_sphinx_codeblock.py","file_name":"test_sphinx_codeblock.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"138835117","text":"from django.conf.urls import url\r\nfrom django.urls import path\r\n\r\nfrom blog.views import FeedView, TogglePersonalFeedView, ReadPostView, SubscribeView, PostNewView, PostDetailView\r\n\r\nurlpatterns = [\r\n url(r'^user/(?P[0-9]+)/subscribe', SubscribeView.as_view(), name='subscribe'),\r\n url(r'^personalize', TogglePersonalFeedView.as_view(), name='personalize'),\r\n path(r'post/', PostDetailView.as_view(), name='post_detail'),\r\n url(r'^post/new', PostNewView.as_view(), name='new_post'),\r\n url(r'^post/(?P[0-9]+)/read', ReadPostView.as_view(), name='read_post'),\r\n url('^$', FeedView.as_view(), name='feed'),\r\n\r\n]\r\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"295756466","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 26 20:39:58 2017\r\n\r\n@author: Richard祥\r\n\"\"\"\r\n\r\ndef read_data(filename):\r\n lin = []\r\n with open(filename,'r',encoding='utf-8') as f :\r\n for line in f:\r\n lines = list(line.replace('\\n','').split(' '))\r\n print(lines)\r\n if lines :\r\n for i in range(len(lines)): \r\n lin.append(lines[i])\r\n else :\r\n continue\r\n return lin\r\ndef main():\r\n file=input('Write the filename: ')\r\n result=read_data(file)\r\n with open('Data.txt','w') as files:\r\n if result :\r\n for i in range(len(result)) :\r\n files.write(result[i])\r\n files.write('\\n')\r\n else : \r\n pass\r\nmain()","sub_path":"读取TXT文件数据.py","file_name":"读取TXT文件数据.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"181705370","text":"#!/usr/bin/env python\nimport xml.etree.ElementTree as etree\ntry: import urllib.request as urllib # py3\nexcept: import urllib # py2\n\ndef parse_rss(url):\n\tns = \"\"\n\tout = {}\n\t\n\trss = etree.parse(urllib.urlopen(url)).getroot()\n\tif len(rss.tag.split(\"}\")) > 1:\n\t\tns = rss.tag.split(\"}\")[0] + \"}\"\n\t\n\tif ns == \"{http://www.w3.org/2005/Atom}\":\n\t\tfor item in rss.getiterator(ns + \"entry\"):\n\t\t\tout[item.find(ns + \"title\").text] = item.find(ns + \"link\").attrib['href']\n\n\telse:\n\t\tfor item in rss.getiterator(ns + \"item\"):\n\t\t\tout[item.find(ns + \"title\").text] = item.find(ns + \"link\").text\n\t\n\treturn out\n\nif __name__ == \"__main__\":\n\timport sys\n\tif len(sys.argv) > 1:\n\t\tfor k, v in parse_rss(sys.argv[1]).items():\n\t\t\tprint(\"%s: %s\" % (k, v))\n\telse:\n\t\tprint(\"Usage: %s url\" % sys.argv[0])\n\n","sub_path":"apertium-tools/scraper/rssfucker.py","file_name":"rssfucker.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"367881535","text":"from _collections import deque\nimport sys\nqueue = deque()\nN = int(sys.stdin.readline())\n\nfor _ in range(N):\n tmpList = sys.stdin.readline().split()\n if tmpList[0] == \"push\":\n queue.appendleft(tmpList[1])\n elif tmpList[0] == \"top\":\n if len(queue) > 0:\n print(queue[-1])\n else:\n print(-1)\n elif tmpList[0] == \"size\":\n print(len(queue))\n elif tmpList[0] == \"empty\":\n if len(queue) > 0:\n print(0)\n else:\n print(1)\n elif tmpList[0] == \"pop\":\n if len(queue) > 0:\n print(queue.pop())\n else:\n print(-1)\n elif tmpList[0] == \"front\":\n if len(queue) > 0:\n print(queue[-1])\n else:\n print(-1)\n elif tmpList[0] == \"back\":\n if len(queue) > 0:\n print(queue[0])\n else:\n print(-1)","sub_path":" 200 - 자료구조 1/큐.py","file_name":"큐.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"245686404","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 13 16:13:02 2016\r\n\r\n@author: huliqun\r\n\"\"\"\r\nimport logging\r\n\r\nfrom workserver.util import LogUtil\r\nfrom workserver.util import SysUtil\r\n\r\n\r\nclass BatchBase(object):\r\n db = None\r\n dbr = None\r\n\r\n def __init__(self):\r\n className = self.__class__.__name__\r\n LogUtil.initLogBatch(className)\r\n SysUtil.global_init()\r\n self.engine = SysUtil.get_engine_handle()\r\n self.db = SysUtil.get_db_handle()\r\n self.logger = logging.getLogger('batchLog_' + className)\r\n\r\n def initialize(self):\r\n self.session = self.db()\r\n\r\n def release(self):\r\n self.session.close()\r\n\r\n def errorReturn(self):\r\n self.session.rollback()\r\n self.session.close()\r\n","sub_path":"workserver/batch/BatchBase.py","file_name":"BatchBase.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"597707672","text":"from app import models\nfrom app.app import mm_driver, config\nfrom app.app import app\nfrom flask import current_app\nfrom flask_apscheduler import APScheduler\nimport atexit\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import date, timedelta\n\nDICT_NEWS_KEY = \"dict_news\"\nSTANDARD_HEADERS = {\"User-Agent\": \"Zeus-Scraper/1.0 (+https://zeus.ugent.be/contact/)\"}\n\nDICT_NEWS_URL_BASE = \"https://helpdesk.ugent.be/nieuws/\"\n\nHYDRA_API_RESTO_BASE = \"https://hydra.ugent.be/api/2.0/resto/menu/nl/\"\n\nscheduler = APScheduler()\n\n\ndef get_dict_news():\n r = requests.get(DICT_NEWS_URL_BASE, headers=STANDARD_HEADERS)\n soup = BeautifulSoup(r.text, \"html.parser\")\n result = []\n for table in soup.find_all(\"table\", [\"table-newsoverview\"]):\n for row in table.find_all(\"tr\"):\n date = row.find(\"td\", [\"date\"]).find(\"span\").text\n link_element = row.find(\"a\")\n link_id = int(link_element.get(\"href\").split(\"?id=\")[-1])\n link = DICT_NEWS_URL_BASE + link_element.get(\"href\")\n message = link_element.text\n result.append(\n {\"id\": link_id, \"date\": date, \"message\": message, \"link\": link}\n )\n return result\n\n\ndef post_dict_news(n):\n message = f'**DICT NIEUWS** op {n[\"date\"]}: [{n[\"message\"]}]({n[\"link\"]})'\n print(f\"Posting {message}\")\n mm_driver.posts.create_post(\n options={\"channel_id\": config.sysadmin_channel_id, \"message\": message}\n )\n\n\n@scheduler.task(\"interval\", id=\"dict_news_task\", minutes=5)\ndef dict_news_task():\n with app.app_context():\n dict_config = models.KeyValue.query.filter_by(\n keyname=DICT_NEWS_KEY\n ).first() or models.KeyValue(DICT_NEWS_KEY, \"111\")\n news_items = get_dict_news()\n current_maxseen = int(dict_config.value)\n for news_item in get_dict_news():\n if news_item[\"id\"] > current_maxseen:\n current_maxseen = news_item[\"id\"]\n post_dict_news(news_item)\n dict_config.value = str(current_maxseen)\n dict_config.save()\n\n\ndef render_menu(menu_json):\n rendered = f\"#### Menu voor {menu_json['date']}\\n\"\n\n render_item = lambda i: f\" - {i['name']}\"\n\n soups = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"kind\"] == \"soup\", menu_json[\"meals\"]),\n )\n )\n mains = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"type\"] == \"main\", menu_json[\"meals\"]),\n )\n )\n colds = \"\\n\".join(\n map(\n render_item,\n filter(lambda m: m[\"type\"] == \"cold\", menu_json[\"meals\"]),\n )\n )\n\n rendered += f\"##### Soep\\n{soups}\\n##### Hoofdgerecht\\n{mains}\\n##### Koud\\n{colds}\"\n return rendered\n\n\n@scheduler.task(\"cron\", id=\"resto_menu_task\", hour=4)\ndef resto_menu_task():\n today = date.today()\n today_url = f\"{HYDRA_API_RESTO_BASE}{today.year}/{today.month}/{today.day}.json\"\n try:\n today_json = requests.get(today_url).json()\n assert today_json['open']\n except:\n today_json = None\n\n tomorrow = today + timedelta(days=1)\n tomorrow_url = (\n f\"{HYDRA_API_RESTO_BASE}{tomorrow.year}/{tomorrow.month}/{tomorrow.day}.json\"\n )\n try:\n tomorrow_json = requests.get(tomorrow_url).json()\n assert tomorrow_json['open']\n except:\n tomorrow_json = None\n\n today_repr = render_menu(today_json) if today_json is not None else \"\"\n tomorrow_repr = render_menu(tomorrow_json) if tomorrow_json is not None else \"\"\n\n if (today_json is not None) or (tomorrow_json is not None):\n requests.post(\n config.resto_voedsels_webhook,\n json={\"text\": \"\\n\\n\".join([today_repr, tomorrow_repr])},\n )\n\n\nscheduler.api_enabled = True\nscheduler.init_app(app)\nscheduler.start()\n","sub_path":"app/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"446643928","text":"# -*- coding: utf-8 -*-\n\nfrom ze.spiders import ZeSpider\n\nclass FolhaDeSaoPauloSpider(ZeSpider):\n\n name = 'folhadesp'\n allowed_domains = ['folha.uol.com.br']\n parses = [{\n \"ze.items.creativework.ArticleItem\": {\n \"fields\": { \n \"name\": [ \n \"[itemprop=name]::text\", \n \"[itemprop=alternativeHeadline]::attr(content)\", \n \"article header h1::text\" \n ], \n \"image\": [ \n \"[itemprop=image]::attr(content)\", \n \"[property='og:image']::attr(content)\" \n ], \n \"description\": [ \n \"[itemprop=description]::text\", \n \".documentDescription::text\" \n ], \n \"author\": [\n \"[itemprop=author]::text\", \n \".author p::text\"\n ], \n \"datePublished\": [\n \"[itemprop=datePublished]::text\",\n \"article time::text\"\n ], \n \"dateModified\": [\n \"[itemprop=dateModified]::text\"\n ], \n \"articleBody\": [\n \"[itemprop=articleBody]\",\n \".content\" \n ], \n \"keywords\": [\n \"[itemprop=keywords]::text\", \n \"[itemprop=keywords]::attr(content)\"\n ]\n }\n }\n }]\n","sub_path":"ze/spiders/folhadesp.py","file_name":"folhadesp.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"392766422","text":"from flask import Blueprint, render_template, redirect, url_for, request, flash\nfrom flask_login import login_user, logout_user, login_required, current_user\n\nfrom datetime import datetime\n\nfrom src import db\nfrom src.models.tabelas import *\nfrom src.packages import CriptografiaAES\nfrom src.utils.usuario_utils import user_is_funcionario\n\ncripto = CriptografiaAES()\n\nauth_module = Blueprint('auth', __name__, url_prefix=\"/auth\",\n template_folder='../templates')\n\n\n@auth_module.route(\"/login\", methods=[\"GET\",\"POST\"])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('usuario.get_historico'))\n\n if request.method == 'GET':\n return render_template('login.html')\n\n if request.method == 'POST':\n email = request.form.get('email')\n senha = request.form.get('senha')\n\n chave_usuario = Tabela_chaves.query.filter_by(email=email).first()\n\n if not chave_usuario:\n flash('Por favor, verifique suas informações e tente novamente!', category='danger')\n return redirect(url_for('auth.login'))\n else:\n usuario = Usuario.query.filter_by(id_usuario=chave_usuario.id_usuario).first()\n senha_usuario = cripto.descriptografar(chave_usuario.chave_privada, usuario.password)\n\n if senha == senha_usuario:\n login_user(usuario)\n\n if user_is_funcionario(chave_usuario, current_user):\n return redirect(url_for('agendamento.agendamento'))\n\n return redirect(url_for('usuario.perfil'))\n else:\n flash('Por favor, verifique suas informações e tente novamente!', category='danger')\n return redirect(url_for('auth.login'))\n\n\n@auth_module.route('/registrar', methods=[\"GET\",\"POST\"])\ndef registrar():\n if request.method == 'GET':\n return render_template('registrar.html')\n\n if request.method == 'POST':\n email = request.form.get('email')\n nome = request.form.get('nome')\n cpf = request.form.get('cpf')\n senha = request.form.get('senha')\n data_nascimento = request.form.get('data')\n\n chave_usuario = Tabela_chaves.query.filter_by(email=email).first()\n\n if chave_usuario:\n flash('E-mail de usuário já existe!', category='danger')\n return redirect(url_for('auth.registrar'))\n\n chave = cripto.criaChave()\n\n try:\n data_nascimento = datetime.strptime(data_nascimento,'%Y-%m-%d').date()\n except ValueError as e:\n data_nascimento = datetime.strptime(data_nascimento,'%Y-%d-%m').date()\n\n is_func = False\n novo_usuario = Usuario(\n nome=cripto.criptografar(chave[\"chave\"], nome),\n email=cripto.criptografar(chave[\"chave\"], email),\n password=cripto.criptografar(chave[\"chave\"], senha),\n cpf=cripto.criptografar(chave[\"chave\"], cpf),\n data_nascimento=cripto.criptografar(chave[\"chave\"], data_nascimento),\n funcionario=cripto.criptografar(chave[\"chave\"], is_func)\n )\n\n db.session.add(novo_usuario)\n db.session.commit()\n\n nova_chave = Tabela_chaves(\n id_usuario=novo_usuario.id_usuario,\n chave_privada=chave[\"chave\"],\n email=email\n )\n\n db.session.add(nova_chave)\n db.session.commit()\n\n flash(f'Usuário {nome} cadastrado com sucesso', category='success')\n\n return redirect(url_for('auth.login'))\n\n\n@auth_module.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('.login'))","sub_path":"src/controllers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"323837352","text":"#!/usr/bin/env python3\n\nfrom mnist import MNIST\nfrom nnlib import NeuralNetwork\n\nbrain = NeuralNetwork()\n\nbrain.numOfLayers = 4\nbrain.numOfNeurons = [784, 32, 16, 10]\nbrain.programName = 'image-recognition'\n\nbrain.generateNeurons()\nbrain.useStoredWeights()\nbrain.useStoredBias()\n\n\nmndata = MNIST('image-recognition_trainingdata')\n\nprint('Carregando os dados para o treinamento...')\n\ntrain_images, train_labels = mndata.load_training()\n\nprint('Carregado!!')\n\nprint('--- tratando as imagens ---')\nfor i in range(len(train_images)):\n\tfor j in range(len(train_images[i])):\n\t\ttrain_images[i][j] = train_images[i][j]/255\n\nprint('--- imagens tratadas ---')\n\nprint('O treinamento iniciado!')\n\nquantidade = len(train_labels)\n\nfor i in range(quantidade):\n\tresult = [0]*10\n\tresult[train_labels[i]] = 1\n\tbrain.train(train_images[i], result)\n\tif i % 1000 == 0: print(round(100*i/quantidade, 1))\n\nprint('Treinamento finalizado!!')\n\nprint('Carregando os dados para o teste...')\n\ntest_images, test_labels = mndata.load_testing()\n\nprint('Dados carregados!')\n\nprint('--- tratando as imagens ---')\nfor i in range(len(test_images)):\n\tfor j in range(len(test_images[i])):\n\t\ttest_images[i][j] = test_images[i][j]/255\nprint('--- imagens tratadas ---')\n\nprint('Teste iniciado!')\n\nfor i in range(10):\t#number of tests to display\n\tguess = brain.guess(test_images[i])\n\tprint('------------')\n\tprint(guess)\n\tprint('guess: ' + str(guess.tolist().index(max(guess))))\n\tprint('real answer: ' + str(test_labels[i]))\n\nprint('Teste finalizado!')\n\nbrain.storeWeights()\nbrain.storeBias()\n","sub_path":"image-recognition.py","file_name":"image-recognition.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"233134144","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport soundfile as sf\n\nfrom mic_py.mic_io import read_mic_wav_from_lst, read_mic_wav_from_folder\nfrom mic_py.mic_stft import stft_arr\nfrom mic_py.feats import istft\nfrom mic_py.mic_geometry import get_sensor_positions, get_source_position, get_sensor_positions_kinect\nfrom mic_py.mic_steering import propagation_vector_free_field\nfrom mic_py.mic_ds_beamforming import ds_beamforming, ds_align\nfrom mic_py.mic_zelin import cross_spectral, calc_beta, zelin_filter\nfrom mic_py.mic_localisation import pseudospectrum_MUSIC, pseudospectrum_MUSIC_kinect\n\n\n\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n\n #################################################################\n # 1.0 - _no_echo_dist_1_0_angle_60 PROFILE MVDR\n vert_mic_count = 1\n hor_mic_count = 4\n max_len_sec = 80\n n_fft = 512\n\n in_wav_path = r'./data/_kinect/'\n #################################################################\n #################################################################\n _mix_start = 1\n _mix_end = 3\n #################################################################\n\n\n #################################################################\n # 1.0 - Read signal\n x_all_arr, sr = read_mic_wav_from_folder(in_wav_path, vert_mic_count, hor_mic_count, max_len_sec = max_len_sec)\n x_all_arr = x_all_arr[:,(np.int32)(_mix_start*sr):(np.int32)(_mix_end*sr)]\n\n (n_channels, n_samples) = x_all_arr.shape\n\n print (\"Array data read done!\")\n print (\" n_channels = \", n_channels)\n print (\" n_samples = \", n_samples)\n print (\" freq = \", sr)\n\n #################################################################\n # 2 - Do STFT\n stft_arr = stft_arr(x_all_arr, fftsize = n_fft)\n (n_bins, n_sensors, n_frames) = stft_arr.shape\n\n print (\"STFT calc done!\")\n print (\" n_bins = \", n_bins)\n print (\" n_sensors = \", n_sensors)\n print (\" n_frames = \", n_frames)\n\n #################################################################\n # 3 - Do localisation\n L = 1\n angle_step = 1\n arr_angle_h = range(-90, 90, angle_step)\n #arr_angle_v = range(-90, 90, angle_step)\n arr_angle_v = np.array([0])\n\n POW = pseudospectrum_MUSIC(stft_arr, L, arr_angle_h, arr_angle_v,\n n_fft = n_fft,\n sr = sr)\n\n\n # (len(arr_angle_h), len(arr_angle_v), n_bins)\n print (\"POW.shape = {}\".format(POW.shape))\n\n #################################################################\n # 4 - Plot DN\n lst_freq_bins = [10, 20, 30, 40, 150]\n\n for f_bin in lst_freq_bins:\n freq = f_bin*sr/n_fft\n plt.plot(arr_angle_h, POW[:, 0, f_bin], label=\"{} HZ\".format(freq))\n\n plt.plot(arr_angle_h, np.mean(POW[:, 0, 10:50], axis=1), label=\"AVERAGE\")\n\n plt.xlabel('angle_h (s)')\n plt.ylabel('MUSIC POW')\n plt.title('MUSIC alg')\n plt.legend(loc=\"upper right\")\n plt.grid(True)\n plt.savefig(r\".\\out\\MUSIC.png\")\n plt.show()\n\n\n","sub_path":"ma_py/_main_LOC_kinect.py","file_name":"_main_LOC_kinect.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"32589052","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom sklearn import metrics\nfrom sklearn.metrics import r2_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom category_encoders import TargetEncoder\nimport time\n\ndef load_data():\n df = pd.read_csv(\"ModelData_product.csv\")\n df = df.loc[:, ~df.columns.str.contains('Unnamed: 0')]\n return df\ndef preprocessing(df):\n encoder = TargetEncoder()\n df['MainColorGroupDesc_en'] = encoder.fit_transform(df['MainColorGroupDesc'], df['ReturnRate'])\n encoder3 = TargetEncoder()\n df['USSize_en'] = encoder3.fit_transform(df['USSize'], df['ReturnRate'])\n ProductDivision_dummy = pd.get_dummies(df.ProductDivision)\n df = pd.concat([df, ProductDivision_dummy], axis=1)\n ERPMasterGender_dummy = pd.get_dummies(df.ERPMasterGender)\n df = pd.concat([df, ERPMasterGender_dummy], axis=1)\n x = df.drop(columns='ReturnRate')\n y = df[['ReturnRate']]\n y = y.values.ravel()\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=2021)\n x_train = x_train.drop(columns=['MainColorGroupDesc',\n 'ProductDivision',\n 'ERPMasterGender',\n 'USSize', 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n x_test_output = x_test.drop(columns=[\n 'ProductDivision',\n 'ERPMasterGender',\n 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n x_test = x_test.drop(columns=[\n 'MainColorGroupDesc',\n 'ProductDivision',\n 'ERPMasterGender',\n 'USSize', 'ReturnQuantity',\n 'ComfortRating',\n 'SizeRating',\n 'WidthRating'])\n return x_train, x_test, y_train, y_test, x_test_output\n\ndef dic(df):\n Product_Type_name = df[\"ProductDivision\"].unique()\n Product_Gender_name = df[\"ERPMasterGender\"].unique()\n Product_Color_name = df[\"MainColorGroupDesc\"].unique()\n Product_Size_name = df[\"USSize\"].unique()\n MainColorGroupDesc_dic = df[['MainColorGroupDesc', 'MainColorGroupDesc_en']]\n MainColorGroupDesc_dic = MainColorGroupDesc_dic.drop_duplicates()\n color_dic = pd.Series(MainColorGroupDesc_dic.MainColorGroupDesc_en.values,\n index=MainColorGroupDesc_dic.MainColorGroupDesc).to_dict()\n USSize_dic = df[['USSize', 'USSize_en']]\n USSize_dic = USSize_dic.drop_duplicates()\n USSize_dic.head()\n Size_dic = pd.Series(USSize_dic.USSize_en.values, index=USSize_dic.USSize).to_dict()\n return color_dic, Size_dic, Product_Type_name, Product_Gender_name, Product_Color_name, Product_Size_name\n\n@st.cache(allow_output_mutation=True)\ndef RandomForest(x_train, x_test, y_train, y_test):\n # Train the model\n\n RF = RandomForestRegressor(n_estimators=1000,\n min_samples_split= 10,\n min_samples_leaf= 4,\n max_features= 'auto',\n max_depth= 10,\n bootstrap= True)\n RF.fit(x_train, y_train)\n RF_pred = RF.predict(x_test)\n MAE = metrics.mean_absolute_error(y_test, RF_pred)\n MSE = metrics.mean_squared_error(y_test, RF_pred)\n RMSE = metrics.mean_squared_error(y_test, RF_pred)\n Rsquare = r2_score(y_test, RF_pred)\n return MAE, MSE, RMSE, Rsquare, RF\n\ndef Calculate_New_Transaction_Return(color_dic, Size_dic, ProductLine,\n Gender,\n Color,\n Size,\n UnitPrice,\n SalesQuantity,\n ReviewsCount,\n OverallRating):\n # set Footwear variable\n if ProductLine == \"Footwear\":\n Footwear = 1\n else:\n Footwear = 0\n\n # set KIDS variable\n if Gender == \"KIDS\":\n KIDS = 1\n else:\n KIDS = 0\n if ProductLine == \"Apparel\":\n Apparel = 1\n else:\n Apparel = 0\n\n # set KIDS variable\n if Gender == \"WNS\":\n WNS = 1\n else:\n WNS = 0\n if ProductLine == \"Accessories\":\n Accessories = 1\n else:\n Accessories = 0\n\n # set KIDS variable\n if Gender == \"MNS\":\n MNS = 1\n else:\n MNS = 0\n Color = color_dic[Color]\n # set USSize_en variable\n Size = Size_dic[Size]\n\n # new test data\n new_test_data = np.array([[UnitPrice, SalesQuantity, OverallRating, ReviewsCount, Color, Size, Accessories, Apparel,\n Footwear, KIDS, MNS, WNS]])\n return new_test_data\n\n\ndef main():\n st.title(\"Prediction Product Return Rate\")\n st.subheader(\"Using Machine Learning Regression Algorithms\")\n data = load_data()\n x_train, x_test, y_train, y_test, x_test_output = preprocessing(data)\n # check-box to show the merged clean data\n\n if st.checkbox('Show Raw Data'):\n st.write(\"This Dataset was Merged and Cleaned\")\n st.write(data.head())\n\n\n if st.checkbox('Show Model Performance'):\n st.write(\"This model is build by Random forest Algorithm\")\n MAE, MSE, RMSE, Rsquare, RF = RandomForest(x_train, x_test, y_train, y_test)\n st.text(\"Mean Absolute Error MAE: \")\n st.write(MAE)\n st.text(\"Mean Squared Error MSE: \")\n st.write(MSE)\n st.text(\"Root Mean Squared Error RMSE:\")\n st.write(RMSE)\n st.text(\"R^2:\")\n st.write(Rsquare)\n\n\n if (st.checkbox(\"Want to predict on your selected Input? \")):\n\n color_dic, Size_dic, Product_Type_name, Product_Gender_name, Product_Color_name, Product_Size_name = dic(data)\n number_UnitPrice = st.slider('UnitPrice', step=1, min_value=0, max_value=600)\n number_SalesQuanity = st.number_input('SalesQuanity', step=2, min_value=0, max_value=1904)\n number_ReviewCount = st.slider('Product Reviews Count', step=1, min_value=0, max_value=50)\n number_OverallRating = st.slider('Online Overall Rating', step=1, min_value=0, max_value=5)\n number_MainColorGroupDesc = st.selectbox('Product MainColor', Product_Color_name)\n number_USSize = st.selectbox('Product Size', Product_Size_name)\n option_ERPMasterGender = st.selectbox('Gender Category?', Product_Gender_name)\n option_ProductDivision = st.selectbox('Product Line?', Product_Type_name)\n\n new_test_data = Calculate_New_Transaction_Return(color_dic, Size_dic, option_ProductDivision,\n option_ERPMasterGender, number_MainColorGroupDesc,\n number_USSize, number_UnitPrice, number_SalesQuanity,\n number_ReviewCount, number_OverallRating)\n if st.button(\"Predict\"):\n with st.spinner('Wait for it...'):\n time.sleep(2)\n result = RF.predict(new_test_data)\n st.success('The Reture Rate is {}'.format(result))\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"202468938","text":"from conflux._utils.rpc_abi import (\n RPC,\n)\nfrom web3.manager import (\n RequestManager as DefaultRequestManager,\n)\nfrom web3.providers import (\n BaseProvider,\n)\nfrom web3.providers.ipc import (\n IPCProvider,\n)\nfrom web3.providers.rpc import (\n HTTPProvider,\n)\nfrom web3.providers.websocket import (\n WebsocketProvider,\n)\nfrom typing import (\n Any,\n cast,\n Dict,\n List,\n Optional,\n Sequence,\n TYPE_CHECKING\n)\nfrom web3._utils.module import (\n attach_modules,\n)\nfrom eth_abi.codec import (\n ABICodec,\n)\nfrom web3._utils.abi import (\n build_default_registry,\n build_strict_registry,\n map_abi_data,\n)\nfrom conflux.cfx import Cfx\nfrom eth_utils import (\n to_wei,\n from_wei,\n)\nfrom eth_utils.address import (\n to_checksum_address\n)\nfrom eth_utils.conversions import (\n to_bytes\n)\nfrom web3._utils.contracts import (\n find_matching_fn_abi\n)\nfrom web3._utils.abi import (\n get_abi_output_types\n)\nfrom cfx_address import (\n Address\n)\nfrom web3 import (\n Web3,\n)\n\ndef get_default_modules() -> Dict[str, Sequence[Any]]:\n return {\n \"cfx\": (Cfx,),\n }\n\nclass Conflux:\n # Providers\n HTTPProvider = HTTPProvider\n IPCProvider = IPCProvider\n WebsocketProvider = WebsocketProvider\n\n # Managers\n RequestManager = DefaultRequestManager\n\n # Currency Utility\n toDrip = staticmethod(to_wei)\n fromDrip = staticmethod(from_wei)\n\n cfx: Cfx\n\n def __init__(\n self,\n provider: Optional[BaseProvider] = None,\n middlewares: Optional[Sequence[Any]] = None,\n modules: Optional[Dict[str, Sequence[Any]]] = None,\n ) -> None:\n self.manager = self.RequestManager(self, provider, middlewares)\n\n self.codec = ABICodec(build_default_registry())\n\n if modules is None:\n modules = get_default_modules()\n\n attach_modules(self, modules)\n\n self._w3 = Web3(Web3.EthereumTesterProvider())\n\n @property\n def clientVersion(self) -> str:\n return self.manager.request_blocking(RPC.cfx_clientVersion, [])\n\n def contract(self, address, abi):\n hex_address = address\n if Address.has_network_prefix(address):\n hex_address = Address(address).eth_checksum_address\n\n return self._w3.eth.contract(address=hex_address, abi=abi)\n\n def call_contract_method(self, address, abi, method_name, *kargs):\n contract = self.contract(address, abi)\n tx = contract.functions[method_name](*kargs).buildTransaction({\n \"gas\": 21000,\n \"gasPrice\": 1,\n })\n call_result = self.cfx.call({\n \"to\": address,\n \"data\": tx['data']\n })\n fn_abi = find_matching_fn_abi(contract.abi, self._w3.codec, method_name, kargs)\n output_types = get_abi_output_types(fn_abi)\n decoded_result = self._w3.codec.decode_abi(output_types, to_bytes(hexstr=call_result))\n if len(output_types) == 1:\n return decoded_result[0]\n else:\n return decoded_result\n","sub_path":"conflux/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"404615099","text":"import tflearn\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\n\nimport dataset as data\n\n#import the cnn graphs\nimport graphs_norm.cnn_2layers as conv2\nimport graphs_norm.cnn_6layers as conv6\nimport graphs_norm.cnn_8layers as conv8\n#import alexnet\nimport graphs_norm.alexnet as alexnet\nimport graphs_norm.resnext as resnext\nimport graphs_norm.inception as inception\nimport graphs_norm.googlenet as googlenet\nimport graphs_norm.convnet as conv\n\nGRAPHS_DIR='graphs_norm/'\n#have to be in the same directory of the script or terminal\nDATASET_DIR='dataset/validation/'\n# MODEL_DIR='models/'\n# MODEL_DIR='models_augm/'\nMODEL_DIR='models_norm/'\nFILE_NAME='summary_norm.csv'\nNOTES = 'note?'\n\n# 50x50 pixel\nIMG_SIZE = 50\n\n#create summary file\nwith open(FILE_NAME, 'w') as f:\n f.write('dataset,model,pp,pv,pt,vp,vv,vt,perc_full,perc_empty,perc_tot\\n')\n\n\n\ndef eval(model_graph):\n print('model_graph: ',model_graph)\n tf.reset_default_graph()\n LR=model_graph.split('-')[2]\n dot_split = model_graph.split('.')\n dash_split = dot_split[-2].split('-')\n model = dash_split[-1]\n model_name = model\n graph = globals()[model]\n network = graph.network([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n model = tflearn.DNN(network, tensorboard_dir='log')\n name = os.path.join(MODEL_DIR, model_graph)\n model.load(name)\n print('Model successfully loaded from ', name)\n\n # load\n for dataset in os.listdir(DATASET_DIR):\n test_data = np.load(os.path.join(DATASET_DIR,dataset))\n print('test_data:', dataset)\n \n c1 = 0\n c2 = 0\n w1 = 0\n w2 = 0\n ft = 0\n et = 0\n\n for num, data in enumerate(test_data[:]):\n # full [0,1] empty [1,0]\n img_data = data[0]\n img_num = data[1]\n\n orig = img_data\n # restore the image shape\n data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n # the [0] is the return of the prediction and is the prob of the image being a cat\n model_out = model.predict([data])[0]\n\n if img_num[0] == 0: ft = ft + 1\n else: et = et + 1\n \n if np.argmax(model_out) == 1: \n # print('model thinks is full')\n if img_num[0] == 0: c1 = c1 + 1\n else: w1 = w1 + 1\n\n else: \n # print('model thinks is empty')\n if img_num[0] == 1: c2 = c2 + 1\n else: w2 = w2 + 1\n\n \n print('full: ',ft)\n print('empty: ',et)\n print('classificata come piena ma era vuota : ',w1)\n print('classificata come vuota ma era piena: ',w2)\n print('classificata come piena ed era piena : ',c1)\n print('classificata come vuota ed era vuota: ',c2)\n\n # % full right\n perc_full = c1 * 100 / ft\n perc_empty = c2 * 100 / et\n perc_tot = (c1+c2)*100/(ft+et)\n perc_full = float(\"{0:.2f}\".format(perc_full))\n perc_empty = float(\"{0:.2f}\".format(perc_empty))\n perc_tot = float(\"{0:.2f}\".format(perc_tot))\n\n # write\n with open(FILE_NAME, 'a') as f:\n f.write('{},{},{},{},{},{},{},{},{},{},{}\\n'.format(dataset,model_name,c1,w2,ft,w1,c2,et,perc_full,perc_empty,perc_tot))\n\n \n\n# REPEAT FOR ALL THE MODELS\nfor data in tqdm(os.listdir(MODEL_DIR)):\n if not data.startswith('.'):\n model_name = data.split('.')\n model_ext = model_name[-1]\n model_graph = '.'.join(model_name[:-1])\n if model_ext =='data-00000-of-00001':\n eval(model_graph)\n\n\n\nwith open(FILE_NAME, 'a') as f:\n f.write('{}\\n'.format(NOTES))\n\n\n ########## PLOT DATA and SHOW PREDICTIONS ##########\n #plot the data\n# fig = plt.figure()\n\n# #reset the graph\n# tf.reset_default_graph()\n# conv2_convnet = conv2.convnet([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n# # tenserboard_dir not needed on mac or ubuntu\n# conv2_model = tflearn.DNN(conv2_convnet, tensorboard_dir='log')\n# #load the model\n# conv2_model.load(CNN2)\n# print('model ',CNN2,' loaded!')\n\n# def a():\n# #reset the graph\n# tf.reset_default_graph()\n# conv2_convnet = conv2.convnet([None,IMG_SIZE,IMG_SIZE,1], 'input', LR)\n# # tenserboard_dir not needed on mac or ubuntu\n# conv2_model = tflearn.DNN(conv2_convnet, tensorboard_dir='log')\n# #load the model\n# conv2_model.load(CNN2)\n# print('model ',CNN2,' loaded!')\n#\n# c = 0\n# w = 0\n# f = 0\n# e = 0\n#\n# for num, data in enumerate(test_data[:]):\n# # full [0,1] empty [1,0]\n# img_data = data[0]\n# img_num = data[1]\n#\n# # 3 by 4 and the numbur is the number plus 1 (because array starts from 0)\n# # y = fig.add_subplot(3,4,num+1)\n# orig = img_data\n# # restore the image shape\n# data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n# # the [0] is the return of the prediction and is the prob of the image being a cat\n# model_out = model.predict([data])[0]\n# # model_conv6_out = conv6_model.predict([data])[0]\n# # model_conv8_out = conv8_model.predict([data])[0]\n# # model_alexnet_out = alexnet_model.predict([data])[0]\n#\n# if img_num[0] == 0:\n# f = f + 1\n# else: \n# e = e + 1\n# \n# if np.argmax(model_out) == 1: \n# # print('img_num: ',img_num)\n# # print('model thinks is full')\n# # print('model out: ',model_conv2_out)\n# # print('model out: ',model_conv2_out[0])\n# if img_num[0] == 0:\n# c = c + 1\n# else:\n# w = w + 1\n#\n# else: \n# if img_num[0] == 1:\n# c = c + 1\n# else:\n# w = w + 1\n#\n# print('full: ',f)\n# print('empty: ',e)\n#\n# print('wrong: ',w)\n# print('right: ',c)\n#\n# # y.imshow(orig, cmap='gray')\n# # string = str_label_c,' ',model_conv2_out,' - ',str_label_a,' ',model_alexnet_out\n# # print(string)\n# # plt.title(string)\n# # y.axes.get_xaxis().set_visible(False)\n# # y.axes.get_yaxis().set_visible(False)\n# # plt.show()\n# # # write\n# # with open('submission-file.csv','w') as f:\n# # f.write('id,label\\n')\n# #\n# # with open('submission-file.csv','a') as f:\n# # for data in tqdm(test_data):\n# # img_num = data[1]\n# # img_data = data[0]\n# # orig = img_data\n# # data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n# # model_out = model.predict([data])[0]\n# # f.write('{},{}\\n'.format(img_num, model_out[1]))\n#\n","sub_path":"1_evaluate_norm.py","file_name":"1_evaluate_norm.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"388132277","text":"import sys\n\ndef parse(fea):\n subs = {}\n baseGlyphs = None\n for statement in fea.statements:\n if getattr(statement, \"name\", None) in (\"isol\", \"ccmp\"):\n for substatement in statement.statements:\n if hasattr(substatement, \"glyphs\"):\n # Single\n originals = substatement.glyphs[0].glyphSet()\n replacements = substatement.replacements[0].glyphSet()\n subs.update(dict(zip(originals, replacements)))\n elif hasattr(substatement, \"glyph\"):\n # Multiple\n subs[substatement.glyph] = substatement.replacement\n elif getattr(statement, \"name\", None) == \"GDEF\":\n for substatement in statement.statements:\n if hasattr(substatement, \"baseGlyphs\"):\n baseGlyphs = substatement.baseGlyphs\n if hasattr(baseGlyphs, \"glyphclass\"):\n baseGlyphs = baseGlyphs.glyphclass\n\n return subs, baseGlyphs\n\ndef build(font, features):\n subs, baseGlyphs = parse(features)\n\n temp_glyph = font.createChar(-1, \"TempXXX\")\n\n for base in subs:\n names = subs[base]\n glyph = font.createMappedChar(base)\n # build the composite on a temp glyph to prevent FontForge from using\n # its built-in knowledge about components of some encoded glyphs.\n temp_glyph.clear()\n temp_glyph.addReference(names[0])\n for name in names[1:]:\n temp_glyph.appendAccent(name)\n temp_glyph.build()\n glyph.clear()\n glyph.references = temp_glyph.references\n glyph.useRefsMetrics(names[0])\n glyph.color = 0xff0000\n baseGlyphs.glyphs.append(base)\n\n font.removeGlyph(temp_glyph)\n","sub_path":"tools/buildencoded.py","file_name":"buildencoded.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"17347763","text":"# 문제9.\n# 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요.\n\nst = input('입력>')\nfor i in st:\n i = st.strip()\nprint ('결과>'+''.join(reversed(i)))\n\n# s = 'java'\n# s = s.strip()\n# print(s)","sub_path":"practice01/quiz_09.py","file_name":"quiz_09.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"275113748","text":"import numpy as np\nimport pandas as pd\nfrom functions import *\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n# Get the data\nstd_train_Km = np.load('std_train_Km.npy')\nstd_test_Km = np.load('std_test_Km.npy')\nstd_train_Vmax = np.load('std_train_Vmax.npy')\nstd_test_Vmax = np.load('std_test_Vmax.npy')\ntrain_labels = np.load('trainLabels.npy')\ntest_labels = np.load('testLabels.npy')\nstd_test_data = np.concatenate((std_test_Km, std_test_Vmax), axis = 1)\nstd_train_data = np.concatenate((std_train_Km, std_train_Vmax), axis = 1)\nindices_all = np.load('indices.npy')\n\nprint(len(indices_all))\n\nstd_train_data = std_train_data[:,indices_all]\nstd_test_data = std_test_data[:,indices_all]\n\n# define the grid search parameters\nnb_neurons = [10,50,100,500,1000]\nepochs = [50,100,500,1000]\nparam_grid = dict(nb_neurons=nb_neurons,epochs = epochs)\n\n# create model with only one hidden layer\n#model_1 = KerasClassifier(build_fn=create_model_1, batch_size=256, verbose=0)\n\n#grid_1 = GridSearchCV(estimator=model_1, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=3, verbose=5)\n#grid_result_1 = grid_1.fit(std_train_data, train_labels)\n\n# summarize results\n#print(\"Best: %f using %s\" % (grid_result_1.best_score_, grid_result_1.best_params_))\n#means_1 = grid_result_1.cv_results_['mean_test_score']\n#stds_1 = grid_result_1.cv_results_['std_test_score']\n#params_1 = grid_result_1.cv_results_['params']\n\n# save results\n#cv_results_1 = pd.DataFrame(grid_result_1.cv_results_)\n#cv_results_1.to_pickle('cv_results_NN_1')\n\n# create model with two hidden layers (having the same neurons)\nmodel_2 = KerasClassifier(build_fn=create_model_2,batch_size=512, verbose=0)\n\ngrid_2 = GridSearchCV(estimator=model_2, param_grid=param_grid, scoring='accuracy', n_jobs=-1, cv=3, verbose=5)\ngrid_result_2 = grid_2.fit(std_train_data, train_labels)\n\n# summarize results\nprint(\"Best: %f using %s\" % (grid_result_2.best_score_, grid_result_2.best_params_))\nmeans_2 = grid_result_2.cv_results_['mean_test_score']\nstds_2 = grid_result_2.cv_results_['std_test_score']\nparams_2 = grid_result_2.cv_results_['params']\n\n# save results\ncv_results_2 = pd.DataFrame(grid_result_2.cv_results_)\ncv_results_2.to_pickle('cv_results_NN_2')\n\n\n","sub_path":"project2/NN_grid_final.py","file_name":"NN_grid_final.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"472403605","text":"import hazelcast\n\nfrom hazelcast import ClientConfig\nfrom hazelcast.serialization.api import Portable\nfrom hazelcast.serialization.predicate import SqlPredicate, and_, is_between, is_equal_to\n\n\nclass User(Portable):\n FACTORY_ID = 1\n CLASS_ID = 1\n\n def __init__(self, username=None, age=None, active=None):\n self.username = username\n self.age = age\n self.active = active\n\n def write_portable(self, writer):\n writer.write_utf(\"username\", self.username)\n writer.write_int(\"age\", self.age)\n writer.write_boolean(\"active\", self.active)\n\n def read_portable(self, reader):\n self.username = reader.read_utf(\"username\")\n self.age = reader.read_int(\"age\")\n self.active = reader.read_boolean(\"active\")\n\n def get_factory_id(self):\n return self.FACTORY_ID\n\n def get_class_id(self):\n return self.CLASS_ID\n\n def __repr__(self):\n return \"User[username='{}', age={}, active={}]\".format(self.username, self.age, self.active)\n\n\ndef generate_users(users):\n users.put(\"Rod\", User(\"Rod\", 19, True))\n users.put(\"Jane\", User(\"Jane\", 20, True))\n users.put(\"Freddy\", User(\"Freddy\", 23, True))\n\n\nif __name__ == \"__main__\":\n config = ClientConfig()\n portable_factory = {User.CLASS_ID: User}\n config.serialization_config.add_portable_factory(User.FACTORY_ID, portable_factory)\n # Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1\n hz = hazelcast.HazelcastClient(config)\n # Get a Distributed Map called \"users\"\n users = hz.get_map(\"users\").blocking()\n # Add some users to the Distributed Map\n generate_users(users)\n # Create a Predicate from a String (a SQL like Where clause)\n sql_query = SqlPredicate(\"active AND age BETWEEN 18 AND 21)\")\n # Creating the same Predicate as above but with a builder\n criteria_query = and_(is_equal_to(\"active\", True), is_between(\"age\", 18, 21))\n # Get result collections using the two different Predicates\n result1 = users.values(sql_query)\n result2 = users.values(criteria_query)\n # Print out the results\n print(result1)\n print(result2)\n # Shutdown this Hazelcast Client\n hz.shutdown()\n","sub_path":"examples/org-website/query_sample.py","file_name":"query_sample.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"497950603","text":"\"\"\"Definitions of type inference for primitives.\"\"\"\n\n\nfrom functools import partial\nfrom operator import getitem\n\nfrom ..dtype import Int, Float, Bool, Tuple, List, Array, UInt, Number, \\\n TypeType, Class, Function, pytype_to_myiatype, Problem, type_cloner, \\\n JTagged, EnvType, SymbolicKeyType\nfrom ..infer import ANYTHING, GraphInferrer, PartialInferrer, \\\n MyiaTypeError, register_inferrer, Track, Inferrer, MetaGraphInferrer, \\\n ExplicitInferrer, VOID, TransformedReference, MultiInferrer, \\\n DummyInferrer, Context\nfrom ..infer.jinf import JInferrer\nfrom ..ir import Graph, MetaGraph\nfrom ..utils import Namespace, Var, RestrictedVar, is_dataclass_type\n\nfrom ..dtype import ismyiatype\nfrom . import ops as P\nfrom .inferrer_utils import static_getter, getelement\nfrom .ops import Primitive\nfrom .py_implementations import typeof, issubtype\n\n\ntype_inferrer_constructors = {}\n\n\n_number_types = [\n Int[8], Int[16], Int[32], Int[64],\n UInt[8], UInt[16], UInt[32], UInt[64],\n Float[16], Float[32], Float[64],\n]\n\n\nasync def _check_shape_type(track, shp):\n shp_t = await track.check(Tuple, shp)\n for elem_t in shp_t.elements:\n track.engine.equiv.declare_equivalent(UInt[64], elem_t, [])\n return shp_t\n\n\n@type_cloner.variant\ndef _import_type(self, t: Function, track):\n return ExplicitInferrer(\n track,\n [self(t2, track) for t2 in t.arguments],\n self(t.retval, track)\n )\n\n\n@type_cloner.variant\ndef _stag_type(self, t: Inferrer):\n return EnvType\n\n\nclass TypeTrack(Track):\n \"\"\"Infer the type of a constant.\n\n Note: the type of a Primitive or of a Graph is an Inferrer.\n\n Attributes:\n constructors: A map of Inferrer constructors. Each constructor\n takes an engine as argument and returns an Inferrer. These\n will be used to infer types for primitives.\n\n \"\"\"\n\n def __init__(self,\n engine,\n name,\n *,\n constructors=type_inferrer_constructors):\n \"\"\"Initialize a TypeTrack.\n\n If a TypeTrack is present, it is always required.\n \"\"\"\n super().__init__(engine, name)\n self.constructors = constructors\n\n async def infer_constant(self, ctref):\n \"\"\"Get the property for a ref of a Constant node.\"\"\"\n v = self.engine.pipeline.resources.convert(ctref.node.value)\n t = self.from_value(v, ctref.context)\n if ismyiatype(t, Number):\n v = RestrictedVar(_number_types)\n prio = 1 if ismyiatype(t, Float) else 0\n return self.engine.loop.create_var(v, t, prio)\n else:\n return t\n\n def from_value(self, v, context):\n \"\"\"Infer the type of a constant.\"\"\"\n if isinstance(v, Primitive):\n return self.constructors[v](self)\n elif isinstance(v, Graph):\n return GraphInferrer(self, v, context)\n elif isinstance(v, MetaGraph):\n return MetaGraphInferrer(self, v)\n elif is_dataclass_type(v):\n rec = self.constructors[P.make_record](self)\n typ = pytype_to_myiatype(v)\n vref = self.engine.vref({'value': typ, 'type': TypeType})\n return PartialInferrer(self, rec, [vref])\n else:\n return typeof(v)\n\n def from_external(self, t):\n \"\"\"Convert a type provided outside the inferrer.\n\n This will replace every Function type by an ExplicitInferrer.\n \"\"\"\n return _import_type(t, self)\n\n def default(self, values):\n \"\"\"Return a default type; this method raises an exception.\"\"\"\n raise Exception('There is no default value for the type track.') \\\n # pragma: no cover\n\n def jtag(self, t):\n \"\"\"Return type for J(x) given typeof(x).\"\"\"\n # It doesn't need to be recursive, because the only legal operation on\n # JTagged is Jinv.\n if isinstance(t, Inferrer):\n return JInferrer(t, lambda elems: Tuple[elems])\n else:\n return JTagged[t]\n\n def stag(self, t):\n \"\"\"Return type for sensitivity of x given typeof(x).\"\"\"\n return _stag_type(t)\n\n\n########################\n# Default constructors #\n########################\n\n\ntype_inferrer = partial(register_inferrer,\n constructors=type_inferrer_constructors)\n\n\n@type_inferrer(P.switch, nargs=3)\nasync def infer_type_switch(track, cond, tb, fb):\n \"\"\"Infer the return type of switch.\"\"\"\n await track.check(Bool, cond)\n v = await cond['value']\n if v is True:\n # We only visit the first branch if the condition is provably true\n return await tb['type']\n elif v is False:\n # We only visit the second branch if the condition is provably false\n return await fb['type']\n elif v is ANYTHING:\n # The first branch to finish will return immediately. When the other\n # branch finishes, its result will be checked against the other.\n res = await track.assert_same(tb, fb, refs=[tb, fb])\n if isinstance(res, Inferrer):\n tinf = await tb['type']\n finf = await fb['type']\n return MultiInferrer((tinf, finf), [tb, fb])\n return res\n else:\n raise AssertionError(\"Invalid condition value for switch\")\n\n\n@type_inferrer(P.partial, nargs=None)\nasync def infer_type_partial(track, fn, *args):\n \"\"\"Infer the return type of partial.\"\"\"\n fn_t = await fn['type']\n return PartialInferrer(track, fn_t, args)\n\n\n@type_inferrer(P.scalar_cast, nargs=2)\nasync def infer_type_scalar_cast(track, x, t):\n \"\"\"Infer the return type of scalar_cast.\"\"\"\n await track.will_check(Number, x)\n await track.check(TypeType, t)\n new_t = await t['value']\n if new_t is ANYTHING:\n raise MyiaTypeError(\n f'Type to cast to must be known at compile time.',\n refs=[x, t]\n )\n elif not ismyiatype(new_t, Number):\n raise MyiaTypeError(f'Cannot cast to {new_t}', refs=[t])\n return new_t\n\n\n@type_inferrer(P.make_tuple, nargs=None)\nasync def infer_type_make_tuple(track, *args):\n \"\"\"Infer the return type of make_tuple.\"\"\"\n elts = [await x.get_raw('type') for x in args]\n return Tuple[elts]\n\n\n@type_inferrer(P.tuple_getitem, nargs=2)\nasync def infer_type_tuple_getitem(track, seq, idx):\n \"\"\"Infer the return type of tuple_getitem.\"\"\"\n seq_t = await track.check(Tuple, seq)\n await track.check(Int, idx)\n idx_v = await idx['value']\n if idx_v is ANYTHING:\n raise MyiaTypeError(\n 'Tuples must be indexed with a constant',\n refs=[seq, idx]\n )\n nelems = len(seq_t.elements)\n if not -nelems <= idx_v < nelems:\n raise MyiaTypeError(\n 'Tuple element out of range',\n refs=[seq, idx]\n )\n\n return seq_t.elements[idx_v]\n\n\n@type_inferrer(P.list_getitem, nargs=2)\nasync def infer_type_list_getitem(track, seq, idx):\n \"\"\"Infer the return type of list_getitem.\"\"\"\n seq_t = await track.check(List, seq)\n await track.check(Int, idx)\n return seq_t.element_type\n\n\n@type_inferrer(getelement, nargs=1)\nasync def infer_type_getelement(track, seq):\n \"\"\"Infer the return type of getting some arbitrary element.\"\"\"\n seq_t = await track.check((List, Array), seq)\n if ismyiatype(seq_t, List):\n return seq_t.element_type\n else:\n return seq_t.elements\n\n\n@type_inferrer(P.tuple_setitem, nargs=3)\nasync def infer_type_tuple_setitem(track, seq, idx, value):\n \"\"\"Infer the return type of tuple_setitem.\"\"\"\n seq_t = await track.check(Tuple, seq)\n await track.check(Int, idx)\n idx_v = await idx['value']\n if idx_v is ANYTHING:\n raise MyiaTypeError(\n 'Tuples must be indexed with a constant',\n refs=[idx]\n )\n value_t = await value['type']\n elts = seq_t.elements\n try:\n elts[idx_v]\n except IndexError:\n raise MyiaTypeError('Index out of bounds', refs=[idx])\n new_elts = tuple([*elts[:idx_v], value_t, *seq_t.elements[idx_v + 1:]])\n return Tuple[new_elts]\n\n\n@type_inferrer(P.list_setitem, nargs=3)\nasync def infer_type_list_setitem(track, seq, idx, value):\n \"\"\"Infer the return type of list_setitem.\"\"\"\n seq_t = await track.check(List, seq)\n await track.check(Int, idx)\n await track.will_check(seq_t.element_type, value)\n return seq_t\n\n\n@type_inferrer(P.list_append, nargs=2)\nasync def infer_type_list_append(track, seq, value):\n \"\"\"Infer the return type of list_append.\"\"\"\n seq_t = await track.check(List, seq)\n await track.will_check(seq_t.element_type, value)\n return seq_t\n\n\n@type_inferrer(P.typeof, nargs=1)\nasync def infer_type_typeof(track, _):\n \"\"\"Infer the return type of typeof.\"\"\"\n return TypeType\n\n\n@type_inferrer(P.hastype, nargs=2)\nasync def infer_type_hastype(track, x, t):\n \"\"\"Infer the return type of hastype.\"\"\"\n def ismyiatype(x): # noqa: D400\n \"\"\"Type\"\"\"\n return x is TypeType\n\n await track.check(ismyiatype, t)\n return Bool\n\n\n@type_inferrer(P.bool_not, nargs=1)\nasync def infer_type_bool_not(track, x):\n \"\"\"Infer the return type of not.\"\"\"\n await track.will_check(Bool, x)\n return Bool\n\n\n@type_inferrer(P.bool_and, P.bool_or, P.bool_eq, nargs=2)\nasync def infer_type_bool_and(track, x, y):\n \"\"\"Infer the return type of bool_and.\"\"\"\n await track.will_check(Bool, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_eq, P.scalar_ne, nargs=2)\nasync def infer_type_generic_compare(track, x, y):\n \"\"\"Infer the return type of a generic comparison operator.\"\"\"\n await track.will_check(Number, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_lt, P.scalar_gt, P.scalar_le, P.scalar_ge, nargs=2)\nasync def infer_type_arith_compare(track, x, y):\n \"\"\"Infer the return type of an arithmetic comparison operator.\"\"\"\n await track.will_check(Number, x, y)\n return Bool\n\n\n@type_inferrer(P.scalar_uadd, P.scalar_usub, P.scalar_floor, P.scalar_trunc,\n nargs=1)\nasync def infer_type_arith_unary(track, x):\n \"\"\"Infer the return type of a unary arithmetic operator.\"\"\"\n return await track.will_check(Number, x)\n\n\n@type_inferrer(P.scalar_exp, P.scalar_log, P.scalar_sin,\n P.scalar_cos, P.scalar_tan, nargs=1)\nasync def infer_type_arith_unary_float(track, x):\n \"\"\"Infer the return type of a floating point unary arithmetic operator.\"\"\"\n return await track.will_check(Float, x)\n\n\n@type_inferrer(P.scalar_add, P.scalar_sub, P.scalar_mul, P.scalar_div,\n P.scalar_mod, P.scalar_pow, nargs=2)\nasync def infer_type_arith_bin(track, x, y):\n \"\"\"Infer the return type of a binary arithmetic operator.\"\"\"\n return await track.will_check(Number, x, y)\n\n\n@type_inferrer(P.shape, nargs=1)\nasync def infer_type_shape(track, ary):\n \"\"\"Infer the return type of shape.\"\"\"\n await track.check(Array, ary)\n shp = await ary['shape']\n return Tuple[[UInt[64]]*len(shp)]\n\n\n@type_inferrer(P.array_map, nargs=None)\nasync def infer_type_array_map(track, fn, *arrays):\n \"\"\"Infer the return type of array_map.\"\"\"\n if len(arrays) < 1:\n raise MyiaTypeError('array_map requires at least one array')\n fn_t = await fn['type']\n await track.check(Array, *arrays)\n vrefs = [TransformedReference(track.engine, getelement, a)\n for a in arrays]\n return Array[await fn_t(*vrefs)]\n\n\n@type_inferrer(P.array_reduce, nargs=3)\nasync def infer_type_reduce(track, fn, ary, shp):\n \"\"\"Infer the return type of array_reduce.\"\"\"\n fn_t = await fn['type']\n await _check_shape_type(track, shp)\n await track.check(Array, ary)\n xref = TransformedReference(track.engine, getelement, ary)\n res_elem_t = await fn_t(xref, xref)\n return Array[res_elem_t]\n\n\n@type_inferrer(P.array_scan, nargs=4)\nasync def infer_type_across_array(track, fn, init, ary, ax):\n \"\"\"Infer the return type of scan/array_reduce.\"\"\"\n fn_t = await fn['type']\n init_t = await init['type']\n ax_t = await ax['type']\n ary_t = await track.check(Array, ary)\n if not ary_t.elements == init_t:\n raise MyiaTypeError(\n \"Initial value must have the same type as array elements\",\n refs=[init, ary]\n )\n if not ax_t == UInt[64]:\n raise MyiaTypeError(\"Axis must be u64\", refs=[ax])\n xref = TransformedReference(track.engine, getelement, ary)\n return Array[await fn_t(xref, xref)]\n\n\n@type_inferrer(P.distribute, nargs=2)\nasync def infer_type_distribute(track, v, shp):\n \"\"\"Infer the return type of distribute.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, shp)\n return v_t\n\n\n@type_inferrer(P.reshape, nargs=2)\nasync def infer_type_reshape(track, v, shape):\n \"\"\"Infer the return type of reshape.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, shape)\n return v_t\n\n\n@type_inferrer(P.transpose, nargs=2)\nasync def infer_type_transpose(track, v, permutation):\n \"\"\"Infer the return type of transpose.\"\"\"\n v_t = await track.check(Array, v)\n await _check_shape_type(track, permutation)\n return v_t\n\n\n@type_inferrer(P.invert_permutation, nargs=1)\nasync def infer_type_invert_permutation(track, permutation):\n \"\"\"Infer the return type of invert_permutation.\"\"\"\n return await permutation.get_raw('type')\n\n\n@type_inferrer(P.dot, nargs=2)\nasync def infer_type_dot(track, a, b):\n \"\"\"Infer the return type of dot.\"\"\"\n return await track.will_check(Array, a, b)\n\n\n@type_inferrer(P.return_, nargs=1)\nasync def infer_type_return_(track, x):\n \"\"\"Infer the return type of return_.\"\"\"\n return await x.get_raw('type')\n\n\n@type_inferrer(P.list_map, nargs=None)\nasync def infer_type_list_map(track, f, *lsts):\n \"\"\"Infer the return type of list_map.\"\"\"\n f_t = await f['type']\n await track.check(List, *lsts)\n argrefs = [TransformedReference(track.engine, getelement, xs)\n for xs in lsts]\n ret_t = await f_t(*argrefs)\n return List[ret_t]\n\n\n@type_inferrer(P.identity, nargs=1)\nasync def infer_type_identity(track, x):\n \"\"\"Infer the return type of identity.\"\"\"\n return await x.get_raw('type')\n\n\n@type_inferrer(P.resolve, nargs=2)\nasync def infer_type_resolve(track, data, item):\n \"\"\"Infer the return type of resolve.\"\"\"\n def chk(data_v, item_v):\n if not isinstance(data_v, Namespace): # pragma: no cover\n raise MyiaTypeError(\n f'data argument to resolve must be Namespace, not {data_v}',\n refs=[data]\n )\n if not isinstance(item_v, str): # pragma: no cover\n raise MyiaTypeError(\n f'item argument to resolve must be a string, not {item_v}.',\n refs=[item]\n )\n\n async def on_dcattr(data, data_t, item_v): # pragma: no cover\n raise MyiaTypeError('Cannot resolve on Class.')\n\n return await static_getter(\n track, data, item,\n fetch=getitem,\n on_dcattr=on_dcattr,\n chk=chk\n )\n\n\n@type_inferrer(P.getattr, nargs=2)\nasync def infer_type_getattr(track, data, item):\n \"\"\"Infer the return type of getattr.\"\"\"\n def chk(data_v, item_v):\n if not isinstance(item_v, str):\n raise MyiaTypeError(\n f'item argument to getattr must be string, not {item_v}.',\n refs=[item]\n )\n\n async def on_dcattr(data, data_t, item_v):\n return data_t.attributes[item_v]\n\n return await static_getter(\n track, data, item,\n fetch=getattr,\n on_dcattr=on_dcattr,\n chk=chk\n )\n\n\n@type_inferrer(P.scalar_to_array, nargs=1)\nasync def infer_type_scalar_to_array(track, x):\n \"\"\"Infer the return type of scalar_to_array.\"\"\"\n x_t = await track.will_check(Number, x)\n return Array[x_t]\n\n\n@type_inferrer(P.array_to_scalar, nargs=1)\nasync def infer_type_array_to_scalar(track, ary):\n \"\"\"Infer the return type of array_to_scalar.\"\"\"\n ary_t = await track.check(Array, ary)\n return ary_t.elements\n\n\n@type_inferrer(P.broadcast_shape, nargs=2)\nasync def infer_type_broadcast_shape(track, xs, ys):\n \"\"\"Infer the return type of broadcast_shape.\"\"\"\n xs_t = await _check_shape_type(track, xs)\n ys_t = await _check_shape_type(track, ys)\n shp_xs_n = len(xs_t.elements)\n shp_ys_n = len(ys_t.elements)\n return Tuple[[UInt[64] for i in range(max(shp_xs_n, shp_ys_n))]]\n\n\n@type_inferrer(P.make_record, nargs=None)\nasync def infer_type_make_record(track, cls, *elems):\n \"\"\"Infer the return type of make_record.\"\"\"\n elem_types = [await x['type'] for x in elems]\n cls_v = await cls['value']\n\n ret_t = Class[\n cls_v.tag,\n dict(zip(cls_v.attributes.keys(), elem_types)),\n cls_v.methods\n ]\n\n if not issubtype(ret_t, cls_v):\n raise MyiaTypeError(\n f'Constructor {cls_v} cannot be called'\n f' with argument types {tuple(elem_types)}',\n refs=elems,\n )\n\n return ret_t\n\n\n@type_inferrer(P.tuple_len, nargs=1)\nasync def infer_type_tuple_len(track, xs):\n \"\"\"Infer the return type of tuple_len.\"\"\"\n await track.will_check(Tuple, xs)\n return Int[64]\n\n\n@type_inferrer(P.list_len, nargs=1)\nasync def infer_type_list_len(track, xs):\n \"\"\"Infer the return type of list_len.\"\"\"\n await track.will_check(List, xs)\n return Int[64]\n\n\n@type_inferrer(P.array_len, nargs=1)\nasync def infer_type_array_len(track, xs):\n \"\"\"Infer the return type of array_len.\"\"\"\n await track.will_check(Array, xs)\n return Int[64]\n\n\n@type_inferrer(P.make_list, nargs=None)\nasync def infer_type_make_list(track, *elems):\n \"\"\"Infer the return type of make_list.\"\"\"\n if len(elems) == 0:\n v = Var('empty')\n t = track.engine.loop.create_var(v, Problem[VOID], -1000)\n else:\n t = await track.assert_same(*elems, refs=elems)\n return List[t]\n\n\n@type_inferrer(P.list_reduce, nargs=3)\nasync def infer_type_list_reduce(track, fn, lst, dflt):\n \"\"\"Infer the return type of list_reduce.\"\"\"\n fn_t = await fn['type']\n await track.check(List, lst)\n xref = TransformedReference(track.engine, getelement, lst)\n res_elem_t = await track.assert_same(fn_t(xref, xref), dflt)\n return res_elem_t\n\n\n@type_inferrer(P.J, nargs=1)\nasync def infer_type_J(track, x):\n \"\"\"Infer the return type of J.\"\"\"\n return track.jtag(await x.get_shallow('type'))\n\n\n@type_inferrer(P.Jinv, nargs=1)\nasync def infer_type_Jinv(track, x):\n \"\"\"Infer the return type of Jinv.\"\"\"\n x_t = await x.get_shallow('type')\n if isinstance(x_t, JInferrer):\n return x_t.fn\n elif isinstance(x_t, GraphInferrer):\n g = x_t._graph\n primal = g and g.transforms.get('primal', None)\n if primal:\n primal = track.engine.pipeline.resources.convert(primal)\n if isinstance(primal, Graph) and primal.parent:\n # The primal for a closure can't be used because it points to\n # the original nodes of its parent, whereas we would like to\n # point to the transformed nodes of the parent. This is\n # fixable, and will need to be fixed to support a few edge\n # cases.\n return DummyInferrer(track)\n else:\n return track.from_value(primal, Context.empty())\n else:\n raise MyiaTypeError(f'Bad input type for Jinv: {x_t}',\n refs=[x])\n elif ismyiatype(x_t, JTagged):\n return x_t.subtype\n else:\n raise MyiaTypeError(f'Bad input type for Jinv: {x_t}',\n refs=[x])\n\n\n@type_inferrer(P.embed, nargs=1)\nasync def infer_type_embed(track, x):\n \"\"\"Infer the return type of embed.\"\"\"\n return SymbolicKeyType\n\n\n@type_inferrer(P.env_setitem, nargs=3)\nasync def infer_type_env_setitem(track, env, key, x):\n \"\"\"Infer the return type of env_setitem.\"\"\"\n await track.check(EnvType, env)\n await track.check(SymbolicKeyType, key)\n key_v = await key['value']\n assert key_v is not ANYTHING\n t = track.stag(key_v.inferred['type'])\n await track.assert_same(t, x['type'])\n return EnvType\n\n\n@type_inferrer(P.env_getitem, nargs=3)\nasync def infer_type_env_getitem(track, env, key, default):\n \"\"\"Infer the return type of env_getitem.\"\"\"\n await track.check(EnvType, env)\n await track.check(SymbolicKeyType, key)\n key_v = await key['value']\n assert key_v is not ANYTHING\n t = track.stag(key_v.inferred['type'])\n return await track.assert_same(t, default)\n\n\n@type_inferrer(P.env_add, nargs=2)\nasync def infer_type_env_add(track, env1, env2):\n \"\"\"Infer the return type of env_add.\"\"\"\n await track.check(EnvType, env1, env2)\n return EnvType\n","sub_path":"myia/prim/type_inferrers.py","file_name":"type_inferrers.py","file_ext":"py","file_size_in_byte":20594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"390676992","text":"import logging\nfrom contextlib import contextmanager\n\nimport psycopg2\nimport yaml\nfrom psycopg2.extras import RealDictCursor\nfrom psycopg2.pool import ThreadedConnectionPool\n\nfrom .campaigns import Campaigns\nfrom .labels import Labels\nfrom .tasks import Tasks\nfrom .worksets import Worksets\n\nlogger = logging.getLogger(__name__)\n\n\nclass DB:\n def __init__(self, pool):\n self.pool = pool\n\n self.campaigns = Campaigns(self)\n self.worksets = Worksets(self)\n self.tasks = Tasks(self)\n self.labels = Labels(self)\n\n def execute(self, sql):\n with self.transaction() as transactor:\n cursor = transactor.cursor()\n cursor.execute(sql)\n return cursor\n\n @contextmanager\n def transaction(self):\n \"\"\"Provides a transactional scope around a series of operations.\"\"\"\n conn = self.get_good_connection()\n try:\n yield conn\n conn.commit()\n except:\n conn.rollback()\n raise\n finally:\n self.pool.putconn(conn)\n\n def get_good_connection(self, retries=11):\n\n # Try at most 10 times.\n for i in range(retries):\n try:\n conn = self.pool.getconn()\n cursor = conn.cursor()\n cursor.execute(\"SELECT 1;\")\n rows = list(cursor)\n if len(rows) == 1:\n return conn\n except (psycopg2.InterfaceError, psycopg2.OperationalError,\n psycopg2.DatabaseError):\n logger.info(\"Discarding a useless connection.\")\n continue # Try again\n\n raise RuntimeError(\"No good database connections in the pool.\")\n\n\n @classmethod\n def from_params(cls, *args, minconn=10, maxconn=20, **kwargs):\n pool = ThreadedConnectionPool(*args, cursor_factory=RealDictCursor,\n minconn=minconn,\n maxconn=maxconn,\n **kwargs)\n\n return cls(pool)\n\n @classmethod\n def from_config(cls, config):\n # Copy config as kwargs\n params = {k: v for k, v in config['database'].items()}\n\n if 'creds' in params:\n creds = yaml.load(open(params['creds']))\n del params['creds']\n params.update(creds)\n\n return cls.from_params(**params)\n","sub_path":"wikilabels/database/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"469764868","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlretrieve\nimport ssl\nimport openpyxl\n\nwb = openpyxl.Workbook()\nsheet = wb.active\nsheet.append([\"제목\", \"장르\",\"정보\"])\n\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nraw = requests.get(\"https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EC%97%AD%EB%8C%80+%EC%98%81%ED%99%94+%EC%88%9C%EC%9C%84\",\n headers={\"User-Agent\": \"Mozilla/5.0\"})\n\nhtml = BeautifulSoup(raw.text, 'html.parser')\nmovies = html.select(\"dl.lst_dsc\")\nn=0\nfor m in movies:\n title = m.select_one(\"dt.tit a\")\n url = title.attrs[\"href\"]\n genre = m.select_one(\"dl.info_txt1 a\")\n url = title.attrs[\"href\"]\n\n print(\"=\" * 50)\n print(\"영화 제목 : \", title.text.strip())\n print(\"영화 장르 : \", genre.text)\n print(\"정보 : https://movie.naver.com\" + url)\n sheet.append([title.text.strip(), genre.text, \"https://movie.naver.com\"+url])\n wb.save(\"naver_moive_info.xlsx\")\n\n each_raw = requests.get(\"https://movie.naver.com\" + url,\n headers={\"User-Agent\": \"Mozilla/5.0\"})\n\n each_html = BeautifulSoup(each_raw.text, 'html.parser')\n #genre = each_html.select_one(\"dl.list_main dd:nth-of-type(1)\")\n\n # poster 선택자 : div.mv_info_area div.poster img\n poster = each_html.select_one(\"div.mv_info_area div.poster img\")\n poster_src = poster.attrs[\"src\"]\n\n urlretrieve(poster_src, \"static/\" + str(n) + \".png\")\n n=n+1\n\n\n\n # title[:2]는 제목의 앞글자 두글자만 따겠다는 것인데, 특수문자가 제목에 들어있는 경우에는 파일 이름에 에러가 나기 때문이다.\n # 또 위에서 title변수가 아니라 출력문에 .text를 붙였기에 여기서도 .text를 붙여준다.","sub_path":"crowl.py","file_name":"crowl.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"492828916","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\nimport h5py\nimport os\n\ndef make_polar(real,imag):\n cplx = real+1j*imag\n return abs(cplx), np.unwrap(np.angle(cplx))\n\ndef limit_data_x(x,y,xmin,xmax):\n minindex = np.argmax(x>xmin)-1\n maxindex = np.argmax(x>=xmax)\n return x[minindex:maxindex+1], y[minindex:maxindex+1]\n\ndef import_file(path,**kwargs): #laziness 10/10, practicality 10/10\n extension = os.path.splitext(path)[1][1:]\n if extension == 'csv':\n return import_csv(path,**kwargs)\n if extension == 'h5':\n return import_h5(path)\n \ndef import_h5(path):\n openfile = h5py.File(path,'r')\n data_dict = {}\n for key in list(openfile.keys()):\n data_dict[key] = np.array(openfile[key])\n openfile.close()\n return data_dict, data_dict.keys()\n \ndef import_csv(path,param_sweep=False,title_line=8):\n title_pos = title_line\n with open(path,'r') as openfile:\n\n if param_sweep == False:\n for i in range(title_pos):\n line = openfile.readline()\n titles = line[:-1].split(',') #get column titles\n data = np.loadtxt(path,delimiter=',',skiprows=title_pos) #import all the data\n data_dict = {titles[i]: data[:,i] for i in range(len(titles))} #create results dictionary\n return data_dict, list(data_dict.keys())\n\n if param_sweep == True:\n data_dict = {} #overall dictionary\n params_dict = {} #dictionary with data from individual parameter values\n values = [] #parameter values\n \n for i in range(title_pos):\n line = openfile.readline()\n \n titles = line[:-1].split(',') #get column titles\n line = openfile.readline()\n param_name, val = line[:-1].split(' = ') #get the name of the parameter\n values.append(float(val)) #register first parameter value\n params_dict[param_name + ' = ' + val] = [] #start data dictionary\n line = openfile.readline() #go to first line of data\n while line != \"\": #keep going until end of file\n try:\n params_dict[param_name + ' = ' + val].append(list(map(float,line[:-1].split(',')))) #attempt to add line to data array\n except ValueError: #float will throw value error\n if line[:len(param_name)] == param_name: #check if the line with the error is a line with the parameter value\n val = line[:-1].split(' = ')[1] #update parameter value\n values.append(float(val)) #store it\n params_dict[param_name + ' = ' + val] = [] #start data dictionary\n line = openfile.readline() #next line\n \n keys, full_values = (list(params_dict.keys()),list(params_dict.values())) #sale mais efficace\n params_dict = {keys[i]: np.array(full_values[i]) for i in range(len(keys))} #sale mais efficace\n data_dict = {'titles':titles,'param data':params_dict,'param values': values}\n return data_dict, list(data_dict.keys())\n\ndef lorentzian_function(x,A,sig,xres,offset):\n return offset+A/(1+(x-xres)**2/sig**2)\n\ndef abs_hanger_function(x,a,b,sig,xres,offset):\n return np.where(abs(offset)>abs(a),abs(offset-(a-2j*b)/(1+2j*(x-xres)/sig)),0) #we must ensure that offset > a which is equivalent to saying that Qc,Qi>Q0\n\ndef abs_sym_hanger_function(x,a,sig,xres,offset):\n return np.where(abs(offset)>abs(a),abs(offset-a/(1+2j*(x-xres)/sig)),0)\n\ndef sym_hanger_function(x,Qi,Qc,f0):\n return (Qc+2j*Qc*Qi*(x-f0)/f0)/(Qi+Qc+2j*Qc*Qi*(x-f0)/f0)\n\ndef hanger_function(x,Qi,Qc,f0,deltaf,f0_sym):\n #only two out of f0, f0_smy and deltaf are independent given that f0 = f0_sym + deltaf\n return (Qc+1j*Qc*Qi*(2*(x-f0)/f0+2*deltaf/f0_sym))/(Qi+Qc+2j*Qc*Qi*(x-f0)/f0)\n\ndef reflection_function(x,kc,kl,f0):\n return (kc-kl-2j*(x-f0))/(kc+kl+2j*(x-f0))\n\ndef transmission_function(x,kcscaled,kt,f0):\n return (2*np.sqrt(kcscaled))/(kt+2j*(x-f0)) #we put a plus on the denominator in this formula to deal with quadrant problems in the arctan function\n\ndef abs_reflection_function(x,kc,kl,f0,scaling):\n return scaling*abs((kc-kl-2j*(x-f0))/(kc+kl+2j*(x-f0)))\n\ndef abs_transmission_function(x,kcscaled,kt,f0):\n return abs((2*np.sqrt(kcscaled))/(kt-2j*(x-f0)))\n\ndef phase_adjust(x,func,delay,offset):\n return np.unwrap(np.angle(func(x)))-2*np.pi*x*delay+offset\n\ndef phase_adjust_fit(freqs,S21arg,model='hanger',**kwargs):\n base_function = lambda x: 1 #we have to define the function so that we don't get a referenced before assignment error\n try:\n p0 = kwargs['p0_arg'] #try to find user defined starting parameters\n except KeyError:\n delay0 = -(S21arg[-1]-S21arg[0])/(2*np.pi*(freqs[-1]-freqs[0])) #determine slope of phase = electrical delay\n offset0 = S21arg[0]+2*np.pi*delay0*freqs[0] #determine offset (this is just solving an affine equation)\n p0 = [delay0, offset0]\n if model == 'sym_hanger':\n base_function = lambda x: sym_hanger_function(x,*kwargs['sym_hanger_params']) #the item 'hanger_params' must be a list of length 3\n if model == 'hanger':\n base_function = lambda x: hanger_function(x,*kwargs['hanger_params']) #the item 'hanger_params' must be a list of length 5\n if model == 'reflection':\n base_function = lambda x: reflection_function(x,*kwargs['reflection_params']) #the item 'reflection_params' must be a list of length 3\n if model == 'transmission':\n base_function = lambda x: transmission_function(x,*kwargs['transmission_params']) #the item 'transmission_params' must be a list of length 3\n \n def model_function(x,delay,offset):\n return phase_adjust(x,base_function,delay,offset)\n \n popt, pcov = opt.curve_fit(model_function,freqs,S21arg,p0)\n fit = model_function(freqs,*popt)\n initial = model_function(freqs,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_reflection_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n scale0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n dip = y[res_index]/scale0\n HM_index = np.argmax(abs(y/scale0)>(1/2+1/2*dip)) #we find the half maximum of the inverse bump aka dip\n sig = 2*abs(x0-x[HM_index])\n #we assume that the two port resonator is critically coupled with respect to each port, and that the FWHM is the sum of the kappas\n kc0 = sig/3\n kl0 = 2*sig/3\n p0 = [kc0,kl0,0,scale0] #ACHTUNG kc and kl have units of frequency and not 2pi frequency\n \n popt, pcov = opt.curve_fit(abs_reflection_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_reflection_function(x,*popt)\n initial = abs_reflection_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_sym_hanger_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n offset0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n a0 = abs(y[res_index]-offset0)\n HM_index = np.argmax(abs(y-offset0)>abs(a0)/2)\n sig0 = 2*abs(x0-x[HM_index])\n p0 = [a0,sig0,0,offset0]\n \n popt, pcov = opt.curve_fit(abs_sym_hanger_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_sym_hanger_function(x,*popt)\n initial = abs_sym_hanger_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n \ndef abs_hanger_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[3]\n p0[3] = 0\n except KeyError:\n offset0 = np.average([y[0],y[-1]])\n res_index = np.argmin(y)\n x0 = x[res_index]\n a0 = abs(y[res_index]-offset0)\n b0 = 0 #we assume the asymmetry to be small (may be a bad guess though)\n HM_index = np.argmax(abs(y-offset0)>abs(a0)/2)\n sig0 = 2*abs(x0-x[HM_index])\n p0 = [a0,b0,sig0,0,offset0]\n \n popt, pcov = opt.curve_fit(abs_hanger_function,x-x0,y,p0)\n popt[3] += x0\n p0[3] += x0\n fit = abs_hanger_function(x,*popt)\n initial = abs_hanger_function(x,*p0)\n \n return popt, p0, fit, pcov, initial\n\ndef abs_transmission_fit(x,y,**kwargs):\n try:\n p0 = kwargs['p0_abs']\n x0 = p0[2]\n p0[2] = 0\n except KeyError:\n res_index = np.argmax(y) #find resonance frequency\n x0 = x[res_index]\n y0 = y[res_index]\n HM_index = np.argmax(abs(y)>y0/2)\n kt0 = 2*abs(x0-x[HM_index])/np.sqrt(3) #determine FWHM (not sure about the sqrt(3) though)\n kcscaled0 = (y0*kt0/2)**2 # determine scaling and kc multiplied\n p0 = [kcscaled0,kt0,0]\n \n popt, pcov = opt.curve_fit(abs_transmission_function,x-x0,y,p0)\n popt[2] += x0\n p0[2] += x0\n fit = abs_transmission_function(x,*popt)\n initial = abs_transmission_function(x,*p0)\n\n return popt, p0, fit, pcov, initial\n\ndef lorentzian_fit(x,y,**kwargs): \n try: \n p0 = kwargs['p0']\n x0 = p0[2]\n p0[2] = 0 #we force the fit to be centered around the guessed resonance frequency\n except KeyError:\n offset0 = np.average([y[0],y[-1]]) #find function offset\n res_index = np.argmax(abs(y-offset0)) #index of resonance in array\n x0 = x[res_index] #frequency of resonance\n A0 = y[res_index]-offset0 #amplitude at resonance\n HM_index = np.argmax(abs(y-offset0)>abs(A0)/2) #index of half maximum\n sig0 = abs(x0-x[HM_index]) #value of half maximum frequency difference\n p0 = [A0,sig0,0,offset0] #define start parameters of fit (we fit with the resonance centered around 0)\n\n popt, pcov = opt.curve_fit(lorentzian_function,x-x0,y,p0)\n popt[2] += x0 #we correct the parameters by what we originally substracted\n p0[2] = x0\n fit = lorentzian_function(x,*popt) #find the y of the fitted model\n initial = lorentzian_function(x,*p0) #find the y of the original guess\n return popt, p0, fit, pcov, initial\n\ndef curve_fit(freqs,data,model='lorentzian',plots = False,verbose = False,**kwargs):\n if model == 'lorentzian': #for this method mke sure data is an array with only 1 dimension\n popt, p0, fit, pcov, initial = lorentzian_fit(freqs,data,**kwargs) #do the fit\n results = {'popt':popt} #return the optimal parameters\n if plots: \n fig, ax = plt.subplots()\n ax.plot(freqs,data,label='data') #plot the original data\n ax.plot(freqs,fit,label='fit') #plot the fit\n ax.plot(freqs,initial,'--',label='initial') #plot the initial guess\n plt.legend()\n plt.show()\n if verbose:\n results.update({'p0':p0,'pcov':pcov,'fit':fit,'initial':initial}) #return all results and parameters for analysis\n return results\n \n if model == 'sym_abs_hanger': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_sym_hanger_fit(freqs,dataabs,**kwargs)\n \n #we have to do some calculations so that the parameters we return are the ones which are physically interesting\n a,sig,xres,offset = popt_abs\n Q0 = xres/sig #see Geerlings' thesis for details on these formulas\n Qc = offset*xres/(a*sig)\n Qi = 1/(1/Q0-1/Qc)\n phys_params = {'Q0':Q0,'Qi':Qi,'Qc':Qc,'f0':xres}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we now need to fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='sym_hanger',sym_hanger_params=list(phys_params.values())[1:],**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'abs_hanger': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_hanger_fit(freqs,dataabs,**kwargs)\n \n #we have to do some calculations so that the parameters we return are the ones which are physically interesting\n a,b,sig,xres,offset = popt_abs\n Q0 = xres/sig #see Geerlings' thesis for details on these formulas\n Qc = offset*xres/(a*sig)\n Qi = 1/(1/Q0-1/Qc)\n deltaf = xres*(1-1/(1+b/(Q0*offset)))\n xres_sym = xres/(1+b/(Q0*offset))\n phys_params = {'Q0':Q0,'Qi':Qi,'Qc':Qc,'f0':xres,'deltaf':deltaf,'f0_sym':xres_sym}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we now need to fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,hanger_params=list(phys_params.values())[1:],**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'abs_reflection': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_reflection_fit(freqs,dataabs,**kwargs)\n kc,kl,f0,scale = popt_abs\n phys_params = {'kc':kc,'kl':kl,'f0':f0}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n \n #we fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='reflection',reflection_params=list(phys_params.values()),**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n \n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results\n \n if model == 'transmission': #for this method make sure data is an array with 2 dimensions (abs and arg)\n dataabs, dataarg = data\n popt_abs, p0_abs, fit_abs, pcov_abs, initial_abs = abs_transmission_fit(freqs,dataabs,**kwargs)\n kcscaled, kt, f0 = popt_abs\n phys_params = {'kcscaled':kcscaled,'kt':kt,'f0':f0}\n abs_results = {'popt':popt_abs,'p0':p0_abs,'pcov':pcov_abs,'fit':fit_abs,'initial':initial_abs}\n\n #we fit the phase\n popt_arg, p0_arg, fit_arg, pcov_arg, initial_arg = phase_adjust_fit(freqs,dataarg,model='transmission',transmission_params=list(phys_params.values()),**kwargs) #use the above defined fitting algorithm\n delay = popt_arg[0]\n phys_params.update({'delay':delay})\n arg_results = {'popt':popt_arg,'p0':p0_arg,'pcov':pcov_arg,'fit':fit_arg,'initial':initial_arg}\n\n results = {'phys_params':phys_params}\n if plots:\n fig, (ax1, ax2) = plt.subplots(nrows=2,figsize=(7, 9.6))\n ax1.plot(freqs,dataabs,c='C0',label='data') #plot the original data\n ax1.plot(freqs,fit_abs,c='C1',label='fit') #plot the fit\n ax1.plot(freqs,initial_abs,'--',c='C2',label='initial') #plot the initial guess\n ax1.set_ylabel('Linear Amplitude')\n ax1.set_xlabel('Frequency (GHz)')\n ax1.legend(loc='best')\n ax2.plot(freqs,dataarg,c='C0',label='data') #plot the original data\n ax2.plot(freqs,fit_arg,c='C1',label='fit') #plot the fit\n ax2.plot(freqs,initial_arg,'--',c='C2',label='initial') #plot the initial guess\n ax2.set_ylabel('Phase (rad)')\n ax2.set_xlabel('Frequency (GHz)')\n ax2.legend(loc='best')\n plt.show()\n if verbose:\n results.update({'abs_results':abs_results,'arg_results':arg_results})\n return results","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":19111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"231480811","text":"#!/usr/bin/python3\n\n###############################################################\n# influxdbdatalogger.py script can be run from command line #\n# or can be started as systemd service or Raspberry Pi #\n# Main tasks of the script are: #\n# - read environment data received as mqtt message #\n# - store received data in InfluxDB database #\n# Andrzej Mazur, 17/03/2021 #\n###############################################################\n\nimport logging\nimport sys\nimport getopt\nimport time\nimport json\nimport os\nfrom datetime import datetime\nimport paho.mqtt.client as mqtt\nfrom influxdb import InfluxDBClient\n\n#Set debug to True in order to log all messages!\nLOG_ALL = False\n#Set log_to_file flag to False in order to print logs on stdout\nLOG_TO_FILE = False\n\n##########################\n#MQTT Connection Settings#\n##########################\n#Quality of Service Level for MQTT transfer, supported values 0 and 1\nmqtt_qos=1\n#Broker address - Change this line!\n#Test Broker address: test.mosquitto.org\nmqtt_broker_address=\"test.mosquitto.org\"\n#mqtt_broker_address=\"localhost\"\n#Brokers TCP Port number\nmqtt_broker_port=1883\n#Connection keep alive interval in sec\nmqtt_keep_alive=60\n#Topic on which measurement record will be published\nmqtt_topic=\"47e0g1/headlesspi/climdata\"\n\n##############################\n#InfluxDB Connection Settings#\n##############################\ninfluxdb_user = \"climatedata_probe\"\ninfluxdb_pass = \"probepi\"\ninfluxdb_dbname = \"climatedata\"\ninfluxdb_measurementname = \"climatemeasurements\"\ninfluxdb_host = \"127.0.0.1\"\ninfluxdb_port = 8086\n\ndef cmd_usage():\n print ('Usage: '+sys.argv[0]+' {[-d | --debug debug] [-h | --host host] [-q | --qos QoS] [-t | --topic topic] [-a | --bfe280addr bfe280 address]')\n exit (1)\n\ntry:\n options, arguments = getopt.getopt(sys.argv[1:], 'dh:q:t:', ['debug', \n 'host=',\n 'qos=',\n 'topic=', \n ])\n \nexcept getopt.GetoptError as err:\n print(str(err))\n cmd_usage()\n sys.exit(1)\n\nfor opt, arg in options:\n if opt in ('-d', '--debug'):\n debug = True\n elif opt in ('-h', '--host'):\n mqtt_broker_address = arg\n elif opt in ('-q', '--qos'):\n mqtt_qos = int(arg)\n elif opt in ('-t', '--topic'):\n mqtt_topic = arg\n\n\n#configure logger module\n#levels: DEBUG,INFO,WARNING,ERROR,CRITICAL\n \n#create two log file handlers, one for actual log file and another for stdout\nstdout_handler = logging.StreamHandler(sys.stdout)\n\nif LOG_TO_FILE == True:\n #extract file name from filename.extension\n idx=os.path.split(os.path.basename(__file__))[1].find('.')\n file_name_wo_extension=os.path.split(os.path.basename(__file__))[1][:idx]\n log_file = os.path.dirname(os.path.realpath(__file__)) + \"/\" + file_name_wo_extension + \".log\"\n file_handler = logging.FileHandler(filename=log_file)\n hndls = [file_handler]\n print (\"Program logs are stored in: \", log_file)\nelse:\n hndls = [stdout_handler]\n \n#configure logger module\n#levels: DEBUG,INFO,WARNING,ERROR,CRITICAL\n\nif LOG_ALL == True:\n logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s:%(threadName)s:%(filename)s:%(lineno)s:%(levelname)s:%(message)s', handlers=hndls)\nelse:\n logging.basicConfig(level = logging.INFO,format = '%(asctime)s:%(threadName)s:%(filename)s:%(lineno)s:%(levelname)s:%(message)s', handlers=hndls)\n\n \nif mqtt_qos != 0 and mqtt_qos != 1:\n mqtt_qos = 1\n logging.error('Provided MQTT QoS value is not supported. Default QoS=1 is used...')\n\ndef mqtt_on_connect(mqtt_client, userdata, flags, rc):\n if rc==0:\n mqtt.Client.connected_flag = True \n logging.info('Received:MQTT_CONNACK(rc=%i)',rc)\n logging.info('Connection to MQTT Broker established!')\n #Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n (result,mid)=mqtt_client.subscribe(mqtt_topic,mqtt_qos)\n logging.info('Sent:MQTT_SUBSCRIBE(mid=%i, topic:%s, QoS=%i, rc=%i)',mid,mqtt_topic, mqtt_qos, result)\n else:\n logging.info('Received:MQTT_CONNACK(rc=%i)',rc)\n logging.info('Connection establishment to MQTT Broker failed!')\n \ndef mqtt_on_disconnect(mqtt_client, userdata, rc):\n mqtt.Client.connected_flag = False\n if rc==0:\n logging.info('Disconnection from MQTT Broker completed!')\n else:\n logging.error('Unexpected disconnection from MQTT Broker!')\n \ndef mqtt_on_message(mqtt_client, userdata, msg):\n logging.debug('Received:MQTT_PUBLISH(topic=%s, qos=%s, retain=%s, payload=%s)', msg.topic,msg.qos,msg.retain,msg.payload)\n mqtt_msg = json.loads(msg.payload)\n influxdb_store_data_sample(influxdb_host,influxdb_port,influxdb_user,influxdb_pass,influxdb_dbname,influxdb_measurementname, mqtt_msg)\n\n\n \ndef mqtt_on_subscribe(client,userdata,mid,granted_qos):\n logging.info('Received:MQTT_SUBACK(mid=%i,negotiatedQoS=%i)',mid, granted_qos[0])\n logging.info('Client ready to receive messages!')\n\ndef influxdb_store_data_sample(dbhost,dbport,dbuser,dbpass,dbname,dbmeasurement,data):\n #build database records from received json string\n \n # connect to influx\n # it is possible to connect once and in this function call just write to database, but it is less reliable method\n ifclient = InfluxDBClient(dbhost,dbport,dbuser,dbpass,dbname)\n \n # write the measurement taken by bme280\n # format the data as a single measurement for influx\n \n logging.debug('Measurement to be added to \"%s\" meas. in \"%s\" db:',dbmeasurement,dbname)\n logging.debug(\" sensor id: %s\", str(data['bme280id']))\n logging.debug(' timestamp: %s',list(data.keys())[1])\n logging.debug(' temperature: %f%s',float(data[list(data.keys())[1]]['temperature']['value']),data[list(data.keys())[1]]['temperature']['unit'])\n logging.debug(' pressure: %f%s',float(data[list(data.keys())[1]]['pressure']['value']),data[list(data.keys())[1]]['pressure']['unit'])\n logging.debug(' humidity: %f%s',float(data[list(data.keys())[1]]['humidity']['value']),data[list(data.keys())[1]]['humidity']['unit'])\n\n dbrecord = [\n {\n \"measurement\": dbmeasurement,\n \"tags\": {\n \"sensor_id\":str(data['bme280id']),\n \"location\": mqtt_topic.split(\"/\")[0]\n },\n \"time\": list(data.keys())[1],\n \"fields\": {\n \"temperature_C\": float(data[list(data.keys())[1]]['temperature']['value']),\n \"pressure_hPa\": float(data[list(data.keys())[1]]['pressure']['value']),\n \"humidity_rH\": float(data[list(data.keys())[1]]['humidity']['value'])\n }\n }\n ]\n\n ifclient.write_points(dbrecord)\n \n # write the measurement taken by ds18b20\n # format the data as a single measurement for influx\n\n logging.debug('Measurement to be added to \"%s\" meas. in \"%s\" db:',dbmeasurement,dbname)\n logging.debug(\" sensor id: %s\", str(data['ds18b2id']))\n logging.debug(' timestamp: %s',list(data.keys())[3])\n logging.debug(' temperature: %f%s',float(data[list(data.keys())[3]]['temperature']['value']),str(data[list(data.keys())[3]]['temperature']['unit']))\n\n dbrecord = [\n {\n \"measurement\": dbmeasurement,\n \"tags\": {\n \"sensor_id\":str(data['ds18b2id']),\n \"location\": mqtt_topic.split(\"/\")[0]\n },\n \"time\": list(data.keys())[3],\n \"fields\": {\n \"temperature_C\": float(data[list(data.keys())[3]]['temperature']['value'])\n }\n }\n ]\n \n ifclient.write_points(dbrecord)\n\n \n#create connection state flag in class\nmqtt.Client.connected_flag=False\n\n#create mqtt client instance\nmqtt_client = mqtt.Client()\n\n#bind callback functions \nmqtt_client.on_connect=mqtt_on_connect\nmqtt_client.on_disconnect=mqtt_on_disconnect\nmqtt_client.on_message=mqtt_on_message\nmqtt_client.on_subscribe=mqtt_on_subscribe\n\n#connect to MQTT Broker\n\nmqtt_client_connect_retry_limit = 30\nmqtt_client_connect_retry = 0\nmqtt_client_connect_success = False\n\nwhile (mqtt_client_connect_retry < mqtt_client_connect_retry_limit and mqtt_client_connect_success == False):\n try:\n if mqtt_client_connect_retry != 0: # there shall be no delay between loopstart() and connect messages!\n time.sleep(1+mqtt_client_connect_retry)\n logging.info('Sent:MQTT_CONNECT:(IP:%s,TCP Port:%s,Topic:%s,QoS:%i,KeepAlive:%i)',mqtt_broker_address, mqtt_broker_port, mqtt_topic, mqtt_qos, mqtt_keep_alive)\n #connect is a blocking function\n mqtt_client.connect(mqtt_broker_address,mqtt_broker_port,mqtt_keep_alive)\n mqtt_client_connect_success = True\n except KeyboardInterrupt:\n logging.info('Exiting the program, ctrl+C pressed...')\n exit(0)\n except:\n mqtt_client_connect_retry = mqtt_client_connect_retry + 1\n logging.error('Connection establishment failed due to: %s, retry (%i out of % i) in %i sec. ...', sys.exc_info()[1],mqtt_client_connect_retry, mqtt_client_connect_retry_limit, 1+mqtt_client_connect_retry)\n pass\n\n#start infinite network loop, disconnect from MQTT Broker at keyboard interupt\ntry:\n mqtt_client.loop_forever()\nexcept KeyboardInterrupt:\n logging.info('Exiting the program, ctrl+C pressed...')\n logging.info('Sent:MQTT_DISCONNECT')\n logging.info('Disconnecting from MQTT Broker')\n mqtt_client.disconnect();\n exit (0)\n\n","sub_path":"src/influxdbdatalogger.py","file_name":"influxdbdatalogger.py","file_ext":"py","file_size_in_byte":9759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"604379763","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport getopt\nimport os\nimport sys\nimport time\n\nimport tweepy\nimport subprocess\nfrom platforms.binance_platform import Binance\nfrom platforms.cryptopia_platform import Cryptopia\n\n\"\"\"*******************\"\"\"\n\"\"\" Authentifications \"\"\"\n\"\"\"*******************\"\"\"\n\n\ndef authentication_tweeter():\n print(\"-- Connecting to tweeter ...\")\n\n auth = tweepy.OAuthHandler(os.environ['TWEETER_CONSUMER_KEY'], os.environ['TWEETER_CONSUMER_SECRET'])\n auth.set_access_token(os.environ['TWEETER_ACCESS_TOKEN'], os.environ['TWEETER_ACCESS_TOKEN_SECRET'])\n return tweepy.API(auth)\n\n\ndef handle_orders(coin, coinFrom):\n coin = coin.upper()\n coinFrom = coinFrom.upper()\n\n # Récupération des fonds disponibles\n originalAsset = client.get_balance(coinFrom)\n print(str(originalAsset) + \" \" + coinFrom + \" available\")\n\n # Récupération du prix de départ\n originalPrice = client.get_price(coin, coinFrom)\n print(coin + \" is at \" + \"{:10.8f}\".format(originalPrice) + \" \" + coinFrom)\n print(\"Can buy \" + str(float(originalAsset / originalPrice)) + \" \" + coin)\n\n # Calcul de la quantité à acheter\n priceBuy = float(originalPrice * 1.02)\n quantity = float(originalAsset / priceBuy)\n quantity = round(quantity * 0.90, 6)\n print(\"Will buy \" + str(quantity) + \" \" + coin + \" (quantity -10% at price + 2%)\")\n\n # Placement ordre achat (priceBuy ignored si market order sur binance)\n client.buy_market(coin, coinFrom, priceBuy, quantity, testMode)\n print(\"--> Bought\")\n\n # Time before trade\n timeBeforeTrade = time.time()\n\n # Wait 15 secondes\n while ((time.time() - timeBeforeTrade) < 20):\n newPrice = client.get_price(coin, coinFrom)\n print(coin + \" is at \" + str(newPrice) + coinFrom)\n time.sleep(0.1)\n\n \"\"\"\n sellOrNot = \"\"\n while (sellOrNot != \"S\"):\n sellOrNot = input(\"Press 's' or 'S' to sell NOW : \\n\")\n sellOrNot = sellOrNot.upper()\n \"\"\"\n\n print(\"Selling ...\")\n\n # Placement ordre vente\n quantityAfter = client.get_balance(coin)\n print(str(quantityAfter) + \" \" + coin + \" available\")\n priceSell = float(client.get_price(coin, coinFrom) * 0.98)\n print(\"Will sell \" + str(quantityAfter) + \" \" + coin + \" (price - 2%)\")\n client.sell_market(coin, coinFrom, priceSell, quantityAfter, testMode)\n\n # Status order sell\n finalAsset = client.get_balance(coinFrom)\n print(str(originalAsset) + \" \" + coinFrom + \" available\")\n print(\"--> Sold\")\n print(\"Previously had \" + str(originalAsset) + \" \" + coinFrom + \", now have \" + str(finalAsset) + \" \" + coinFrom)\n print(\"Now have \" + str(client.get_balance(coin)) + \" \" + coin)\n print(\"Delta is \" + str(finalAsset - originalAsset) + \" \" + coinFrom)\n\n\n\"\"\"*********\"\"\"\n\"\"\" Tweeter \"\"\"\n\"\"\"*********\"\"\"\n\n\ndef search_coin_of_the_week(tweet):\n print(\"Searching coin ...\")\n coinOfTheWeek = \"\"\n\n if (\"coin of the week\" in tweet.lower()):\n coin = tweet.split(\"(\")\n\n # Si il a quelque chose après la 1ere parenthèse\n if (len(coin) > 1):\n coin = coin[1].split(\")\")\n\n # Si le texte est pas trop grand mais vérification pas forcément nécessaire\n if (len(coin[0]) < 10):\n coinOfTheWeek = coin[0]\n print(\"Coin of the week found : \" + coinOfTheWeek)\n\n if (len(coinOfTheWeek) == 0):\n print(\"[ERROR] Coin of the week not found :(\")\n print(\"Getting tweet from Macafee ...\")\n\n return coinOfTheWeek\n\n\n\"\"\"****************\"\"\"\n\"\"\" Tweeter stream \"\"\"\n\"\"\"****************\"\"\"\n\n\nclass TwitterStreamListener(tweepy.StreamListener):\n\n def on_status(self, status):\n handle_tweet(status)\n\n # Twitter error list : https://dev.twitter.com/overview/api/response-codes\n def on_error(self, status_code):\n if status_code == 403:\n print(\"[ERROR] The request is understood, but it has been refused or access is not allowed. Limit is maybe reached\")\n return False\n\n\ndef handle_tweet(tweet):\n if tweet.author.id_str != os.environ['TWEETER_FOLLOW_ID']:\n print(\"[WARNING] Tweet not from Macafee\")\n print(\"Getting tweet from Macafee ...\")\n return False\n\n coin = search_coin_of_the_week(tweet.text)\n start_trading(coin)\n\n\n\"\"\"*******\"\"\"\n\"\"\" Utils \"\"\"\n\"\"\"*******\"\"\"\n\n\ndef start_trading(coin):\n global coinFrom\n global platform\n # subprocess.call(['python3', '/home/erwanlbp/dev/python/Alex1664/pumpy-bot/printPrices.py', '--coin', coin, '--coin-from', coinFrom, '--platform', platform])\n handle_orders(coin, coinFrom)\n\n\ndef wait_user():\n coin = input(\"Enter the coin to trade : \\n\")\n start_trading(coin)\n\n\ndef wait_tweet():\n clientTweeter = authentication_tweeter()\n\n print(\"-- Getting tweet from Macafee ...\")\n\n streamListener = TwitterStreamListener()\n myStream = tweepy.Stream(auth=clientTweeter.auth, listener=streamListener)\n myStream.filter(follow=[os.environ['TWEETER_FOLLOW_ID']])\n\n\ndef help():\n print('pumpNdump.py -m -p -c [--test]')\n\n\n\"\"\"******\"\"\"\n\"\"\" Main \"\"\"\n\"\"\"******\"\"\"\n\n\ndef main(argv):\n mode = ''\n try:\n opts, args = getopt.getopt(argv, \"hm:tp:c:\", [\"coin=\", \"platform=\", \"mode=\", \"test\"])\n except getopt.GetoptError:\n print('error')\n help()\n sys.exit(2)\n\n global platform\n global coinFrom\n for opt, arg in opts:\n if opt == '-h':\n help()\n sys.exit()\n elif opt in (\"-c\", \"--coin\"):\n coinFrom = arg\n elif opt in (\"-m\", \"--mode\"):\n mode = arg\n if mode not in ('user', 'tweet'):\n help()\n sys.exit(2)\n elif opt in (\"-p\", \"--platform\"):\n platform = arg\n if platform not in ('cryptopia', 'binance'):\n help()\n sys.exit(2)\n elif opt in (\"-t\", \"--test\"):\n global testMode\n testMode = True\n\n print(\"-- Launching bot ...\")\n\n global client\n if platform == 'binance':\n client = Binance()\n elif platform == 'cryptopia':\n client = Cryptopia()\n else:\n help()\n sys.exit()\n\n if mode == 'user':\n wait_user()\n elif mode == 'tweet':\n wait_tweet()\n else:\n help()\n sys.exit()\n\n\nclient = None\ncoinSymbol = ''\nalexTweeterId = ''\ntestMode = False\ncoinFrom = 'ETH'\nplatform = ''\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"pumpNdump.py","file_name":"pumpNdump.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"419572413","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport json\nimport nltk\nimport re\nimport csv\nfrom tqdm import tqdm\nfrom nltk.tokenize import sent_tokenize\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nimport InferSent\nfrom InferSent.models import InferSent\n\nclass wordRemover():\n def __init__(self, word):\n self.word = word\n \n def removeWord(self, listOfWords):\n if self.word in listOfWords:\n index = listOfWords.index(self.word)\n del listOfWords[index]\n return listOfWords\n\n\nmetadata = pd.read_csv(\"../data/movie.metadata.tsv\", sep = '\\t', header = None)\nmetadata.columns = [\"movie_id\",1,\"movie_name\",3,4,5,6,7,\"genre\"]\n\nplots = []\nwith open(\"../data/plot_summaries.txt\", 'r') as f:\n reader = csv.reader(f, dialect='excel-tab') \n for row in tqdm(reader):\n plots.append(row)\n\nmovie_id = []\nplot = []\n\n# extract movie Ids and plot summaries\nfor i in tqdm(plots):\n movie_id.append(i[0])\n plot.append(i[1])\n\n# create dataframe\nmovies = pd.DataFrame({'movie_id': movie_id, 'plot': plot})\n\n# change datatype of 'movie_id'\nmetadata['movie_id'] = metadata['movie_id'].astype(str)\n\n# merge meta with movies\nmovies = pd.merge(movies, metadata[['movie_id', 'movie_name', 'genre']], on = 'movie_id')\n\ngenres = [] \n\n# extract genres\nfor i in movies['genre']: \n genres.append(list(json.loads(i).values())) \n\n# add to 'movies' dataframe \nmovies['genre_new'] = genres\n\ngenres = movies['genre_new'].values.tolist()\n\nbinarizer = MultiLabelBinarizer()\n\ny_data = binarizer.fit_transform(genres)\n\ncounts = []\ncategories = binarizer.classes_\n\nfor i in range(categories.shape[0]):\n counts.append((categories[i], np.sum(y_data[:,i])))\n\ndf_stats = pd.DataFrame(counts, columns=['genre', '#movies'])\n\nx = df_stats[df_stats['#movies']<200]\n\ngenres_to_remove = x['genre'].values.tolist()\n\nfor word in genres_to_remove:\n movies['genre_new'] = movies['genre_new'].apply(wordRemover(word).removeWord)\n\nmovies_new = movies[~(movies['genre_new'].str.len() == 0)]\n\nprint('Updated corpus shape : ', movies_new.shape)\n\nids = movies_new['movie_id'].values.tolist()\n\nreduced_genres = movies_new['genre_new'].values.tolist()\n\nbinarizer_new = MultiLabelBinarizer()\n\ny_data_new = binarizer_new.fit_transform(reduced_genres)\n\nprint('Labels array shape : {}'.format(y_data_new.shape))\n\nlabels_dict = {}\n\ncount = 0\nfor i in range(len(ids)):\n if i==40:\n break\n labels_dict[ids[i]] = y_data_new[i]\n\nprint('LABEL DICTIONARY LENGTH: {}'.format(len(labels_dict)))\n\n\n\ndef clean_text(text):\n # remove a string like {{plot}}\n text = re.sub(\"\\s*{{\\w*}}\\s*\", \"\", text)\n # remove backslash-apostrophe \n text = re.sub(\"\\'\", \"\", text)\n return text\n\nmovies_new['clean_plot'] = movies_new['plot'].apply(lambda x: clean_text(x))\n\nprint('Creating vocabulary for dataset....')\n\nnew_vocabulary = []\n\nfor movie_id in movies_new['movie_id']:\n \n plot_sr = movies_new[movies_new['movie_id']==movie_id]['clean_plot']\n \n for str_obj in plot_sr:\n plot=str_obj\n \n sentence_list = sent_tokenize(plot)\n\n new_vocabulary = new_vocabulary + sentence_list\n\nprint('\\nVocab creation done!')\n\nV = 2\nMODEL_PATH = '/dccstor/cmv/MovieSummaries/All_Data/genre_prediction/pretrained_models/infersent%s.pkl' % V\nparams_model = {'bsize': 128, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,\n\t\t\t\t'pool_type': 'max', 'dpout_model': 0.0, 'version': V}\n\nmodel = InferSent(params_model)\nmodel.load_state_dict(torch.load(MODEL_PATH))\nmodel = model.cuda()\n\nW2V_PATH = '/dccstor/cmv/MovieSummaries/All_Data/genre_prediction/fastText/crawl-300d-2M.vec'\nmodel.set_w2v_path(W2V_PATH)\n\nmodel.build_vocab_k_words(K=500000)\n\nprint('Updating Vocab....')\nmodel.update_vocab(new_vocabulary, tokenize=True)\nprint('Vocab updated!')\n\nembedding_dict = {}\n\ncount = 0\n\nprint('Embedding creation begins...')\n\nfor movie_id in movies_new['movie_id']:\n \n plot_sr = movies_new[movies_new['movie_id']==movie_id]['clean_plot']\n \n for str_obj in plot_sr:\n plot=str_obj\n \n sentence_list = sent_tokenize(plot)\n\n embedding_array = model.encode(sentence_list, tokenize=True)\n\n embedding_dict[movie_id] = embedding_array\n\n count += 1\n\n if count==40:\n \tbreak\n\nprint('EMBEDDING DICTIONARY LENGTH: {}'.format(len(embedding_dict)))\n\n# Save to disk\nprint('\\nSaving dummy dictionaries to disk...')\nnp.save(\"/dccstor/cmv/MovieSummaries/embeddings/infersent_dummy.npy\", embedding_dict)\nnp.save(\"/dccstor/cmv/MovieSummaries/embeddings/dummy_labels.npy\", labels_dict)\nprint('Finished!')\n\n\n","sub_path":"code/dummy_data.py","file_name":"dummy_data.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"170230576","text":"# USAGE\n# python server.py\n\nimport logging\nimport os\nfrom camera import Camera\nfrom flask_socketio import SocketIO\nfrom engineio.payload import Payload\n\nfrom sys import stdout\nfrom flask import Flask\nfrom flask import Response\nfrom flask import render_template\nfrom flask import request, session, send_file\nfrom werkzeug.utils import secure_filename\nimport json\nimport pdfplumber\nfrom io import BytesIO\nfrom datetime import datetime\nfrom get_gestures_from_webcam import get_gestures_from_webcam as gestures\nfrom scripts import questions as qs\nfrom scripts import statistics as st\nfrom scripts import movies as mv\nfrom PIL import Image\n\napp = Flask(__name__)\napp.logger.addHandler(logging.StreamHandler(stdout))\napp.config['SECRET_KEY'] = 'secret!'\napp.config['DEBUG'] = True\napp.config[\n 'UPLOAD_FOLDER'] = '/home/oanalavinia/Documents/Master/WADe/Disertatie/HandGestureAnalyser/server/static/files'\nPayload.max_decode_packets = 500\nsocketio = SocketIO(app)\ncamera = Camera()\nquiz = qs.QuizGame(camera.get_gesture_obj())\nmovie = mv.Movie(camera.get_gesture_obj())\nfile_name = \"/home/oanalavinia/Documents/Master/WADe/Disertatie/HandGestureAnalyser/server/static/experiments/\" + str(datetime.now())\n\napp.secret_key = '5b7373780e35434090c87dc4c9d15a2d'\n\n\ndef gen():\n \"\"\"Video streaming generator function.\"\"\"\n\n app.logger.info(\"starting to generate frames!\")\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame.tostring() + b'\\r\\n')\n\n\n@app.route(\"/\")\ndef index():\n session['startTime'] = datetime.now()\n return render_template(\"index.html\")\n\n\n@app.route(\"/statistics\")\ndef statistics():\n binary_image = st.getGestures(session['startTime'])\n img_io = BytesIO()\n rgb_im = binary_image.convert('RGB')\n rgb_im.save(img_io, 'JPEG', quality=70)\n img_io.seek(0)\n return send_file(\n img_io,\n mimetype='image/jpeg',\n as_attachment=False,\n attachment_filename='statistics.jpeg')\n\n\n@app.route(\"/video_feed\")\ndef video_feed():\n return Response(gen(),\n mimetype=\"multipart/x-mixed-replace; boundary=frame\")\n\n\n@app.route(\"/current_gesture\", methods=['GET'])\ndef current_gesture():\n return json.dumps({'gesture': camera.get_gesture()})\n\n\n@app.route(\"/get_gesture\", methods=['POST'])\ndef get_gesture():\n landmarks_x = request.form.getlist(\"landmarks_x[]\")\n landmarks_y = request.form.getlist(\"landmarks_y[]\")\n landmarks_x = [float(x) for x in landmarks_x]\n landmarks_y = [float(y) for y in landmarks_y]\n if landmarks_x:\n gesture = camera.get_gesture_obj().get_gesture_from_landmarks(landmarks_x, landmarks_y)\n context = camera.get_gesture_obj().get_context()\n return json.dumps({'gesture': gesture, 'context': context})\n return json.dumps({'gesture': \"none\"})\n\n\n@app.route(\"/save_data\", methods=['POST'])\ndef save_data():\n camera.get_gesture_obj().get_owl_utilities().save_data()\n\n return json.dumps({'response': \"done\"})\n\n\n@app.route(\"/save_gesture_start_time\", methods=['POST'])\ndef save_gesture_start_time():\n context = camera.get_gesture_obj().get_context()\n start_time = request.form.get('start_time')\n with open(file_name, 'a') as f:\n f.write(context + ' ' + start_time + '\\n')\n\n return json.dumps({'response': \"done\"})\n\n\n@app.route(\"/questions\", methods=['GET', 'POST'])\ndef questions():\n # gestures.save_data()\n if request.method == 'GET':\n camera.get_gesture_obj().set_context(\"QuizGame\")\n return quiz.create_question_game()\n else:\n # gestures.save_data()\n user_answers = quiz.get_correct_answers(request.form.getlist('answersTime[]'))\n return json.dumps({'status': 'OK', 'results': user_answers})\n\n\n@app.route(\"/random_movies\", methods=['GET'])\ndef random_movies():\n if request.method == 'GET':\n camera.get_gesture_obj().set_context(\"SelectionGame\")\n result = movie.get_rec_system().get_random_movies()\n return json.dumps({'movies': result[0], 'movie_ids': result[1]})\n\n\n@app.route(\"/rec_movies\", methods=['POST'])\ndef rec_movies():\n if request.method == 'POST':\n start_time = datetime.fromtimestamp(int(request.form.get('startTime')) / 1000.0)\n end_time = datetime.fromtimestamp(int(request.form.get('endTime')) / 1000.0)\n movie_ids = request.form.getlist('movie_ids[]')\n # Get gesture based on startTime and endTime.\n gesture = movie.queries_handler.query_movies(start_time, end_time)\n # Get recommendation.\n rec_movies, movie_name = movie.get_recommendations(gesture, movie_ids)\n print(rec_movies)\n # Add rule to owl.\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"SelectionGame\", gesture, gesture_obj.get_owl_context())\n\n return json.dumps({'status': 'OK', 'movies': rec_movies, 'selected_movie': movie_name})\n\n\n@app.route('/uploader', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n context = request.form.get('context')\n file = request.files['file']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n if context == \"Image\":\n camera.get_gesture_obj().set_context(\"Image\")\n image = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n width, height = image.size\n print(width, height)\n\n return {'fileName': file.filename, 'width': width, 'height': height}\n elif context == \"PDFDocument\":\n camera.get_gesture_obj().set_context(\"PDFDocument\")\n with pdfplumber.open(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as pdf:\n page_1 = pdf.pages[0]\n nr_pages = len(pdf.pages)\n\n return {'fileName': file.filename, 'width': str(page_1.width), 'height': str(page_1.height),\n 'nr_pages': str(nr_pages)}\n\n\n@app.route('/add_image_rule', methods=['POST'])\ndef add_image_rule():\n gesture = request.form.get('gesture')\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"Image\", gesture, gesture_obj.get_owl_context())\n\n return {'response': \"done\"}\n\n\n@app.route('/add_file_rule', methods=['POST'])\ndef add_file_rule():\n gesture = request.form.get('gesture')\n gesture_obj = camera.get_gesture_obj()\n gesture_obj.get_owl_utilities().get_contexted_rule(\"PDFDocument\", gesture, gesture_obj.get_owl_context())\n\n return {'response': \"done\"}\n\n\n@app.route('/do_close_camera', methods=['POST'])\ndef do_close_camera():\n print(\"do close {}\".format(request.form.get('do_close_camera')))\n if request.form.get('do_close_camera') == \"true\":\n gestures.set_record(False)\n elif request.form.get('do_close_camera') == \"false\":\n gestures.set_record(True)\n\n return json.dumps({'response': \"ok\"})\n\n\nif __name__ == '__main__':\n # app.run(port=80, debug=True,\n # threaded=True, use_reloader=False)\n socketio.run(app, host=\"0.0.0.0\", port=\"5000\", debug=True, use_reloader=False, ssl_context='adhoc')\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"137706546","text":"# -*-coding:utf-8-*-\r\n\r\nimport json\r\nimport time\r\nimport os\r\n\r\nimport sys\r\nreload(sys)\r\nsys.path.append('../')\r\n\r\nfrom global_utils import flow_text_index_name_pre,flow_text_index_type,es_flow_text\r\nfrom time_utils import ts2datetime\r\nfrom parameter import sensitive_score_dict\r\n\r\ndef get_sensitive_info(timestamp,mid):\r\n index_name = flow_text_index_name_pre + ts2datetime(timestamp)\r\n try:\r\n item_result = es_flow_text.get(index=index_name,doc_type=flow_text_index_type,id=mid)['_source']\r\n sensitive_info = item_result['sensitive']\r\n except:\r\n sensitive_info = 0\r\n\r\n return sensitive_info\r\n\r\ndef get_sensitive_user(uid):\r\n try:\r\n tmp_stage = r_sensitive.hget('sensitive_words', uid)\r\n if tmp_stage:\r\n sensitive_score += v * sensitive_score_dict[str(tmp_stage)]\r\n except:\r\n sensitive_score = 0\r\n\r\n return sensitive_score\r\n \r\n","sub_path":"xnr/sina/sensitive/get_sensitive.py","file_name":"get_sensitive.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"34946283","text":"\n'''application/apps.py'''\nfrom flask import Flask, jsonify\nfrom flask_jwt_extended import JWTManager\n\nfrom instance.config import app_config\nfrom .api.v1.views.auth_endpoints import auth, BLACKLIST\nfrom .api.v1.views.products_endpoints import product\nfrom .api.v1.views.sales_endpoints import sale\n\n\ndef create_app(config):\n '''function configuring the Flask App'''\n app = Flask(__name__)\n\n app.url_map.strict_slashes = False\n app.config.from_object(app_config[config])\n app.config[\"TESTING\"] = True\n\n app.config['JWT_SECRET_KEY'] = 'mysecretkey'\n app.config['JWT_BLACKLIST_ENABLED'] = True\n app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']\n jwt = JWTManager(app)\n\n @jwt.user_claims_loader\n def add_claims_to_access_token(user_object):\n '''add role claims to access token'''\n return {'role': user_object['role']}\n\n @jwt.user_identity_loader\n def user_identity_lookup(user_object):\n '''set token identity from user_object passed to username'''\n return user_object[\"username\"]\n\n @jwt.token_in_blacklist_loader\n def check_if_token_blacklist(decrypted_token):\n '''check if jti(unique identifier) is in black list'''\n json_token_identifier = decrypted_token['jti']\n return json_token_identifier in BLACKLIST\n\n '''Error handlers'''\n @app.errorhandler(400)\n def bad_request(error):\n '''error handler for Bad request'''\n return jsonify(dict(error='Bad request')), 400\n\n @app.errorhandler(404)\n def Resource_not_found(error):\n '''error handler for 404'''\n return jsonify(dict(error='Resource not found')), 404\n\n @app.errorhandler(405)\n def unauthorized(error):\n '''error handler for 405'''\n return jsonify(dict(error='Method not allowed')), 405\n\n @app.errorhandler(Exception)\n def unhandled_exception(e):\n return jsonify(dict(error='Internal server error')), 500\n\n app.register_blueprint(auth)\n app.register_blueprint(product)\n app.register_blueprint(sale)\n\n return app\n","sub_path":"application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"360964088","text":"def check(day, month):\r\n if (month == 4 or month == 6 or month == 9 or month == 11) and day == 31:\r\n return 1\r\n else:\r\n return 0\r\n \r\ndef isleap(year):\r\n if (year % 4 == 0 and year %100 == 0) or year % 400 == 0:\r\n return 1\r\n else:\r\n return 0\r\n\r\nres = False\r\nflag = False\r\nwhile not flag:\r\n day = int(input(\"Enter day \"))\r\n month = int(input(\"Enter month \"))\r\n year = int(input(\"Enter year \"))\r\n\r\n tomm_month = month\r\n tomm_year = year\r\n \r\n if day<1 or day>31:\r\n print(\"Value of day, not in the range 1...31\")\r\n flag = True\r\n res = True\r\n \r\n if month<1 or month>12:\r\n print(\"Value of month, not in the range 1...12\")\r\n flag = True\r\n res = True\r\n elif check(day,month):\r\n print(\"value of day, not in the range day<=30\")\r\n flag = True\r\n res = True\r\n \r\n if year<1812 or year>2015:\r\n print(\"value of year, not in the range 1812...2015\")\r\n flag = True\r\n res = True\r\n \r\n if month==2:\r\n if isleap(year) and day>29:\r\n print(\"invalid date input for leap year\")\r\n flag = True\r\n res = True\r\n elif (not(isleap(year)) and day>28):\r\n print(\"invalid date input for not a leap year\")\r\n flag = True\r\n res = True\r\n flag = True\r\n \r\ntomm_day = 0\r\nif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10:\r\n if day<31:\r\n tomm_day = day + 1\r\n else:\r\n tomm_day = 1\r\n tomm_month = month + 1\r\nelif month == 4 or month == 6 or month == 9 or month == 11:\r\n if day<30:\r\n tomm_day = day + 1\r\n else:\r\n tomm_day = 1\r\n tomm_month = month + 1\r\n\r\nelif month == 12:\r\n if day<31:\r\n tomm_day = day+1\r\n else:\r\n tomm_day = 1\r\n tomm_month = 1\r\n if year == 2015:\r\n print(\"The next day is out of boundray value of year\")\r\n tomm_year = year + 1\r\n else:\r\n tomm_year = year + 1\r\n\r\nelse:\r\n if day<28:\r\n tomm_day = day + 1\r\n elif isleap(year) and day == 28:\r\n tomm_day = day + 1\r\n elif day == 28 or day == 29:\r\n tomm_day = 1\r\n tomm_month = 3\r\n \r\nif not res:\r\n print(f\"next day is {tomm_day} {tomm_month} {tomm_year}\")\r\n \r\n","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"607591069","text":"n = int(input())\ndef hanoi(n, s, m, e): # 원판의 개수, 시작점, 거치는점, 끝점\n if n == 1:\n print(\"{} {}\".format(s, e)) \n else : # 위에 조건에서 return이 없기 때문에 else 처리를 해주어야 n이 1일때 아래가 작동 안한다.\n hanoi(n-1, s, e, m) \n hanoi(1,s,m,e) \n hanoi(n-1, m, s, e)\nprint(2**n-1)\nhanoi(n,1,2,3) # 이렇게 하면 None이 안나옴\n# print(hanoi(3,1,2,3)) # 이렇게하면 None 발생 왜나하면 위에 함수가 return이 아니라 값이 없는데 프린트를 해서 그럼","sub_path":"Baekjoon/재귀/하노이 탑 이동 순서.py","file_name":"하노이 탑 이동 순서.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"120932789","text":"import os\nfrom argparse import ArgumentParser\n\nimport torch\nfrom pytorch_lightning import LightningModule, loggers\nfrom pytorch_lightning import seed_everything, Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.metrics.functional import accuracy, dice_score, iou\nfrom torch.nn.functional import cross_entropy\nfrom torch.optim import AdamW\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\n\nfrom dataManagement.dataModules import TwoDomainDM\nfrom models.FCDenseNet.tiramisu import FCDenseNet57Base, FCDenseNet57Classifier\n\n\nclass RightLaneSTModule(LightningModule):\n def __init__(self, lr=1e-3, decay=1e-4, lrRatio=1e3, num_cls=2):\n super().__init__()\n self.save_hyperparameters('lr', 'decay', 'lrRatio')\n\n # Create network parts\n self.featureExtractor = FCDenseNet57Base()\n self.classifier = FCDenseNet57Classifier(n_classes=num_cls)\n\n # Training parameters\n self.lr = lr\n self.decay = decay\n self.lrRatio = lrRatio\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n argGroup = parser.add_argument_group('LightningModule', 'Parameters defining network training')\n\n argGroup.add_argument('-lr', '--learningRate', type=float, default=1e-3, help=\"Starting learning rate\")\n argGroup.add_argument('--decay', type=float, default=1e-4, help=\"L2 weight decay value\")\n argGroup.add_argument('--lrRatio', type=float, default=1000,\n help=\"Ratio of maximum and minimum of learning rate for cosine LR scheduler\")\n\n return parser\n\n def forward(self, x):\n x = self.featureExtractor(x)\n x = self.classifier(x)\n return x\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n\n # Forward propagation, loss calculation\n outputs = self.forward(x)\n loss = cross_entropy(outputs, y)\n\n # Accuracy calculation\n _, labels_hat = torch.max(outputs, 1)\n train_acc = accuracy(labels_hat, y) * 100\n\n self.log('tr_loss', loss)\n self.log('tr_acc', train_acc, prog_bar=True)\n\n return loss\n\n def validation_step(self, batch, batch_idx):\n return self.evaluate_batch(batch)\n\n def validation_epoch_end(self, outputs):\n logs = self.summarize_evaluation_results(outputs)\n self.log('val_loss', logs['loss'])\n self.log('val_acc', logs['acc'], prog_bar=True, logger=True)\n self.log('val_dice', logs['dice'])\n self.log('val_iou', logs['iou'], prog_bar=True, logger=True)\n # self.log('step', self.current_epoch)\n\n def test_step(self, batch, batch_idx):\n return self.evaluate_batch(batch)\n\n def test_epoch_end(self, outputs):\n logs = self.summarize_evaluation_results(outputs)\n self.log('test_loss', logs['loss'])\n self.log('test_acc', logs['acc'])\n self.log('test_dice', logs['dice'])\n self.log('test_iou', logs['iou'])\n\n def configure_optimizers(self):\n optimizer = AdamW(self.parameters(), lr=self.lr, weight_decay=self.decay)\n scheduler = CosineAnnealingLR(optimizer, 25, eta_min=self.lr / self.lrRatio)\n return [optimizer], [scheduler]\n\n def evaluate_batch(self, batch):\n x, y = batch\n\n # Forward propagation, loss calculation\n outputs = self.forward(x)\n loss = cross_entropy(outputs, y)\n\n _, labels_hat = torch.max(outputs, 1)\n\n weight = x.shape[0]\n return {\n 'loss': loss * weight,\n 'acc': accuracy(labels_hat, y) * weight,\n 'dice': dice_score(outputs, y) * weight,\n 'iou': iou(labels_hat, y) * weight,\n 'weight': weight,\n }\n\n def summarize_evaluation_results(self, outputs):\n total_weight = sum(x['weight'] for x in outputs)\n loss = sum([x['loss'] for x in outputs]) / total_weight\n acc = sum([x['acc'] for x in outputs]) / total_weight * 100.0\n dice = sum([x['dice'] for x in outputs]) / total_weight\n iou = sum([x['iou'] for x in outputs]) / total_weight * 100.0\n\n return {\n 'loss': loss,\n 'acc': acc,\n 'dice': dice,\n 'iou': iou,\n }\n\n\ndef main(args, model_name: str, reproducible: bool, comet: bool, wandb: bool):\n if reproducible:\n seed_everything(42)\n args.deterministic = True\n args.benchmark = True\n\n if args.default_root_dir is None:\n args.default_root_dir = 'results'\n\n if comet:\n from pytorch_lightning.loggers import CometLogger\n comet_logger = loggers.CometLogger(\n api_key=os.environ.get('COMET_API_KEY'),\n workspace=os.environ.get('COMET_WORKSPACE'), # Optional\n project_name=os.environ.get('COMET_PROJECT_NAME'), # Optional\n experiment_name=model_name # Optional\n )\n args.logger = comet_logger\n if wandb:\n from pytorch_lightning.loggers import WandbLogger\n wandb_logger = WandbLogger(project=os.environ.get('WANDB_PROJECT_NAME'), log_model=True, sync_step=True)\n args.logger = wandb_logger\n\n # Save best model\n model_checkpoint = ModelCheckpoint(\n filename=model_name + '_{epoch}',\n save_top_k=1,\n monitor='val_iou',\n mode='max',\n )\n args.checkpoint_callback = model_checkpoint\n\n data = TwoDomainDM(dataPath=args.dataPath, augment=args.augment, batch_size=args.batch_size, num_workers=8)\n model = RightLaneSTModule(lr=args.learningRate, lrRatio=args.lrRatio, decay=args.decay, num_cls=4)\n\n # Parse all trainer options available from the command line\n trainer = Trainer.from_argparse_args(args)\n trainer.fit(model, datamodule=data)\n\n # Reload best model\n model = RightLaneSTModule.load_from_checkpoint(model_checkpoint.best_model_path, dataPath=args.dataPath, num_cls=4)\n\n # Upload weights\n if comet:\n comet_logger.experiment.log_model(model_name + '_weights', model_checkpoint.best_model_path)\n\n # Perform testing\n trainer.test(model, datamodule=data)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n\n # Data location\n parser.add_argument('--dataPath', type=str, help=\"Path of database root\")\n\n parser.add_argument('--comet', action='store_true', help='Define flag in order to use Comet.ml as logger.')\n parser.add_argument('--wandb', action='store_true', help='Define flag in order to use WandB as logger.')\n parser.add_argument('--model_name', type=str, default='sandt', help='Model identifier for logging and checkpoints.')\n parser.add_argument('--reproducible', action='store_true',\n help=\"Set seed to 42 and deterministic and benchmark to True.\")\n\n # Add model arguments to parser\n parser = TwoDomainDM.add_argparse_args(parser)\n parser = RightLaneSTModule.add_model_specific_args(parser)\n\n # Adds all the trainer options as default arguments (like max_epochs)\n parser = Trainer.add_argparse_args(parser)\n\n args = parser.parse_args()\n\n from dotenv import load_dotenv\n\n load_dotenv()\n main(args, model_name=args.model_name, reproducible=args.reproducible, comet=args.comet, wandb=args.wandb)\n","sub_path":"rightLaneNetwork/RightLaneSTModule.py","file_name":"RightLaneSTModule.py","file_ext":"py","file_size_in_byte":7270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"422247442","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 8 10:27:11 2020\n\n@author: gshambul\n\"\"\"\n\n'''\n\nProgram will display the number of occurance count of each unique values which is present in list .\n\n'''\n\n\ndef list_creation(user_list):\n element_count = int(input(\"Enter the number of elements to be present in user list : \"))\n if(element_count>0):\n for _ in range(1,element_count+1):\n print(\"Enter {} element : \".format(_))\n user_list.append(int(input()))\n else:\n print(\"Please provide the element_count value greater than zero \")\n exit(0)\n \n \n \nif __name__ == \"__main__\" :\n user_list = list()\n list_creation(user_list)\n print(\"user input list is : \",user_list)\n print(\"Element --> Occurence count\")\n for i in set(user_list):\n print(i,\" --> \",user_list.count(i))\n","sub_path":"Program06.py","file_name":"Program06.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"488282871","text":"from os import remove, mkdir\nfrom os.path import join, exists, isdir\nimport random\nimport string\nimport tensorflow as tf\nimport numpy as np\nimport pickle\n\nfrom tensorflow.keras.layers import Layer, Dense, Flatten, Conv2D, Conv1D, Dropout\n\n\ndef check_dir():\n if not isdir(\"layers\"):\n mkdir(\"layers\")\n\n\nclass Strato(object):\n def __init__(self, name=None, config=None):\n\n # create directory if not existent\n check_dir()\n\n # default settings\n self.config = {\n 'layer_type': 'Dense',\n 'frozen': False,\n 'activation': \"relu\",\n 'dense_units': 16,\n 'filters': 8,\n 'kernel_size': 5,\n 'strides': 2,\n 'padding': \"same\",\n 'Dropout_rate': 0.2}\n\n # if there are configurations, use them to overwrite the default settings\n if config != None:\n for k in config.keys():\n self.config[k] = config[k]\n\n # assemble the layer\n self.assemble()\n\n if name == None:\n self.weights = None\n self.name = ''.join(random.choice(\n string.ascii_lowercase + string.digits) for _ in range(16))\n\n self.path = join(\"layers\", self.name)\n while exists(self.path):\n self.name = ''.join(random.choice(\n string.ascii_lowercase + string.digits) for _ in range(16))\n self.path = join(\"layers\", self.name)\n else:\n self.name = name\n self.path = join(\"layers\", self.name)\n self.load()\n\n def assemble(self):\n\n if self.config['layer_type'] == \"Dense\":\n self.layer = Dense(\n units=self.config['dense_units'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['dense_units']\n\n elif self.config['layer_type'] == \"Conv1D\":\n self.layer = Conv1D(\n filters=self.config['filters'],\n kernel_size=self.config['kernel_size'],\n strides=self.config['strides'],\n padding=self.config['padding'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['filters']\n\n elif self.config['layer_type'] == \"Conv2D\":\n self.layer = Conv2D(\n filters=self.config['filters'],\n kernel_size=self.config['kernel_size'],\n strides=self.config['strides'],\n padding=self.config['padding'],\n activation=self.config['activation'])\n\n # what is visualized\n self.label = self.config['filters']\n\n elif self.config['layer_type'] == \"Dropout\":\n self.layer = Dropout(\n rate=self.config['Dropout_rate'])\n\n # what is visualized\n self.label = self.config['Dropout_rate']\n else:\n raise ValueError(\"Incorrect layer type\")\n\n def freeze(self):\n self.layer.trainable = False\n self.config['frozen'] = True\n\n def unfreeze(self):\n self.layer.trainable = True\n self.config['frozen'] = False\n\n def save(self):\n \"\"\"\n Save all the configurations and the weights if existent.\n \"\"\"\n\n # if the weights can be detected, save them\n\n weights = self.layer.get_weights()\n\n wname = self.path + \".weights\"\n\n if exists(wname):\n remove(wname)\n pickle.dump(weights, open(wname, \"wb\"))\n\n iname = self.path + \".info\"\n if exists(iname):\n remove(iname)\n pickle.dump(self.config, open(iname, \"wb\"))\n\n def load(self):\n\n wname = self.path + \".weights\"\n self.weights = pickle.load(open(wname, \"rb\"))\n\n iname = self.path + \".info\"\n self.config = pickle.load(open(iname, \"rb\"))\n\n self.assemble()\n\n def resetWeights(self):\n raise NotImplemented()\n","sub_path":"Chimera/Layers.py","file_name":"Layers.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"430785312","text":"from django.shortcuts import render\nfrom .resources import AddressResource\nfrom tablib import Dataset\nfrom django.contrib import messages\nfrom .models import Address\nimport xlwt\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\n# Create your views here.\n\n\ndef home(request):\n if request.method == 'POST':\n address_resource = AddressResource()\n dataset = Dataset()\n new_address = request.FILES['myfile']\n if not new_address.name.endswith('xlsx' or 'xl'):\n messages.info(request, 'Wrong format! please choose Exel file to upload')\n return render(request, 'home.html')\n imported_data = dataset.load(new_address.read(), format=('xlsx' or 'xl'))\n for data in imported_data:\n value = Address(\n data[0], data[1], data[2], data[3], data[4], data[5],\n data[6], data[7], data[8], data[9], data[10], data[11]\n )\n value.save()\n return render(request, 'home.html')\n\n\ndef export_users_xls(request):\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"users.xls\"'\n\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet('Address')\n\n # Sheet header, first row\n row_num = 0\n\n font_style = xlwt.XFStyle()\n font_style.font.bold = True\n\n columns = ['Name', 'Job', 'Address1', 'Address2', 'Area', 'City', 'State', 'Country', 'Pincode', 'latitude',\n 'longitude']\n\n for col_num in range(len(columns)):\n ws.write(row_num, col_num, columns[col_num], font_style)\n\n # Sheet body, remaining rows\n font_style = xlwt.XFStyle()\n\n rows = Address.objects.all().values_list('Name', 'Job', 'Address1', 'Address2', 'Area', 'City', 'State', 'Country',\n 'Pincode', 'latitude', 'longitude')\n for row in rows:\n row_num += 1\n for col_num in range(len(row)):\n ws.write(row_num, col_num, row[col_num], font_style)\n\n wb.save(response)\n return HttpResponse(response, home(request))\n","sub_path":"Location/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"197287732","text":"import os\nimport cv2\nfrom glob import glob\n\ndef main():\n video_filenames = glob(\"/home/ubuntu/cs230_data/*/*.mp4\")\n\n video_sizes(video_filenames)\n video_frames_analyze(video_filenames)\n image_frame_analyze(video_filenames[0])\n\ndef image_frame_analyze(filename):\n cap = cv2.VideoCapture(filename)\n ret, frame = cap.read()\n if ret == False:\n print(\"Read unsuccessful\")\n return\n print(\"Shape of Image (Height, Width, Channels): \" + str(frame.shape))\n test_image = \"./test.jpg\"\n cv2.imwrite(test_image, frame)\n print(\"File Size of One Frame: \" + humansize(os.path.getsize(test_image)))\n\ndef video_frames_analyze(video_filenames):\n durations = 0\n fps = 0\n frames = 0\n sub_sample_size = 100\n for fname in video_filenames[:sub_sample_size]:\n vid_fps, vid_frames, vid_duration = analyze_single_video(fname)\n fps += vid_fps\n frames += vid_frames\n durations += vid_duration\n print(\"Average FPS of videos: \" + str(fps/sub_sample_size))\n print(\"Average Frame Count of videos: \" + str(frames/sub_sample_size))\n print(\"Average Duration Count of videos: \" + str(durations/sub_sample_size))\n\n# This function computes the fps, number of frames, and duration in seconds\n# for a single video\ndef analyze_single_video(filename):\n cap = cv2.VideoCapture(filename)\n # Compute the Frames-Per-Second for the video\n fps = cap.get(cv2.CAP_PROP_FPS)\n # Get the number of frames in the video\n frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n # Compute the duration of the video (in seconds)\n duration = frame_count/fps\n cap.release()\n return fps, frame_count, duration\n\n# This function computes the sizes (in human-readable form) for each video\ndef video_sizes(video_filenames):\n sizes = [os.path.getsize(vid) for vid in video_filenames if\n os.path.isfile(vid) and \"metadata\" not in vid]\n print(\"Min Video File Size: \" + humansize(min(sizes)))\n print(\"Max Video File Size: \" + humansize(max(sizes)))\n print(\"Avg Video File Size: \" + humansize(sum(sizes)/len(sizes)))\n\nsuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\ndef humansize(nbytes):\n i = 0\n while nbytes >= 1024 and i < len(suffixes)-1:\n nbytes /= 1024.\n i += 1\n f = ('%.2f' % nbytes).rstrip('0').rstrip('.')\n return '%s %s' % (f, suffixes[i])\n\nmain()\n","sub_path":"data_exploration/video_explore.py","file_name":"video_explore.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"462869860","text":"import numpy as np\nimport tensorflow as tf\nfrom .GomokuTools import GomokuTools as gt\nfrom .TF2Tools import TerminalDetector\n\nclass ValueDataHelper:\n def __init__(self, N, representation, edges=True, cut_off=None):\n \"\"\"\n Helper supporting various representations of a particular gomoku position\n params:\n N: board size\n representation: either of \"NxNx2\", \"NxNx1\", \"NxNx1B\"\n \"NxNx2\" uses two matrices alternatingly, the player to move next always on the top matrix\n \"NxNx1\" uses a single matrix, the player to move always +1, the other -1\n \"NxNx1B\" uses one matrix for the players (like NxNx1) and a second for the border. \n edges: boolean, whether to model edges as defensive stones or not. Not relevant for NxNx1B\n \"\"\"\n self.N = N\n self.rep = representation\n self.edges = edges\n self.cut_off = cut_off\n \n \n def from_string_with_bellmann(self, board, terminal_value=None, gamma=1.0):\n \"\"\"\n Creates an symmetry-augmented dataset of board positions and their values.\n Values are calculated as Bellmann rollouts backwards from terminal_value with alternating \n signs using discount factor gamma.\n The samples will have shape [N_moves*8, N+2, N+2, 2]\n\n If terminal_value is 1, expect the values to be [..., gamma^2, -gamma, gamma, -1, 1]\n\n board: The string rep of the stones, like e.g. \"j10k11i9\"\n N: the size of the board\n \"\"\"\n \n # stones in matrix coordinates respecting the border padding\n maybe_padded_stones = self.maybe_padded_coords(board)\n\n # all equivalent representations: 4xrot, 2xflip = 8 variants \n all_traj = self.all_symmetries(maybe_padded_stones)\n \n all_samples = []\n all_values = []\n for traj in all_traj:\n samples, values = self.traj_to_samples(traj, \n terminal_value=terminal_value, \n gamma=gamma) \n\n # Take only the last, most meaningful values\n if self.cut_off: \n samples = samples[-self.cut_off:] \n values = values[-self.cut_off:]\n\n all_samples = all_samples + samples\n all_values = all_values + values\n \n return all_samples, all_values\n\n \n def maybe_padded_coords(self, board):\n \"\"\"\n return stones in matrix coordinates respecting the border padding\n \"\"\"\n stones = gt.string_to_stones(board)\n matrix_coords = [gt.b2m([ord(s[0])-64, s[1]], self.N) for s in stones]\n if self.edges:\n return np.add(matrix_coords, [1,1])\n else: \n return matrix_coords\n\n \n def all_symmetries(self, coords):\n \"\"\"\n All 8 equivalent game plays\n coords: border-padded coordinates\n \"\"\"\n \n return [\n self.rot_flip(coords, quarters=quarters, flip=flip) \n for quarters in range(4) for flip in [False, True]\n ]\n\n \n def create_sample(self, moves, to_move):\n sample = self.template()\n for move in moves:\n if self.rep == 'NxNx2':\n sample[move[0], move[1], to_move] = 1\n elif self.rep == 'NxNx1B':\n sample[move[0], move[1], 0] = 1 - 2 * to_move\n else:\n sample[move[0], move[1]] = 1 - 2 * to_move\n to_move = 1 - to_move\n return sample\n \n \n def traj_to_samples(self, traj, terminal_value, gamma):\n \"\"\"\n creates samples for a given trajectory, together with the bellmann-values\n\n traj: trajectory, represented by their padded coordinates\n terminal_value: the given value of the last state in the trajectory\n gamma: discount factor. \n \"\"\"\n samples = []\n values = []\n value = terminal_value\n to_move_first = 1\n for t in range(len(traj)): \n moves = traj[:t+1] \n sample = self.create_sample(moves, to_move_first)\n\n samples.append(sample)\n values.append(value)\n # Actually, this is the wrong order, we'll invert before returning\n if to_move_first == 0:\n value = - value\n else:\n value = - gamma * value\n to_move_first = 1 - to_move_first\n\n return samples, values[::-1]\n \n \n def template(self):\n \"\"\"\n create a fresh empty board representation\n \"\"\"\n s = np.zeros([self.N,self.N], dtype=np.int16)\n\n if self.rep == 'NxNx1B':\n border = 1\n elif self.edges:\n if self.rep == 'NxNx1':\n border = -1\n else:\n border = 1\n if self.edges or self.rep == 'NxNx1B':\n defensive = np.pad(s, pad_width=1, constant_values=border)\n else: \n defensive = s\n \n if self.rep == \"NxNx2\":\n if self.edges:\n N=self.N+2\n else:\n N=self.N\n offensive = np.zeros([N, N], dtype=np.int16)\n template = np.stack([offensive, defensive], axis=-1)\n elif self.rep == 'NxNx1B':\n offensive = np.zeros([self.N+2, self.N+2], dtype=np.int16)\n template = np.stack([offensive, defensive], axis=-1) \n else: \n template = defensive\n\n return template\n \n \n def rot_flip (self, coords, quarters, flip):\n \"\"\"\n coords: list of tuples of matrix coordinates\n quarters: multiples of 90 degrees to rotate\n flip: boolean: Flip or not\n \"\"\"\n if self.edges:\n N = self.N+2\n else:\n N = self.N\n\n r,c = np.transpose(coords)\n quarters = quarters % 4\n if quarters == 0:\n res = (r,c)\n elif quarters == 1:\n res = (N-c-1, r)\n elif quarters == 2:\n res = (N-r-1,N-c-1)\n elif quarters == 3:\n res = (c, N-r-1)\n if flip:\n res = res[::-1]\n return np.transpose(res)\n \n \nclass SampleDataHelper (ValueDataHelper):\n \"\"\"\n Adds policy-related utilities to the ValueDataHelper\n \"\"\"\n def __init__(self, N, representation, edges=True, cut_off=None):\n \"\"\"\n Helper supporting various representations of a particular gomoku position\n params:\n N: board size\n representation: either of \"NxNx2\", \"NxNx1\"\n \"NxNx2\" uses two matrices alternatingly, the player to move next always on the top matrix\n \"NxNx1\" uses a single matrix, the player to move always +1, the other -1\n \"NxNx1B\" uses one matrix for the players (like NxNx1) and a second for the border. \n edges: boolean, whether to model edges as defensive stones or not. Not relevant for NxNx1B\n cut_off: the number of positions per trajectory, counted from the end backwards\n Allows to focus on the later stages of the game\n \"\"\"\n super().__init__(N, representation, edges, cut_off)\n\n \n def from_string_with_actions(self, board):\n \"\"\"\n Creates an symmetry-augmented dataset of board positions and their actions.\n The samples will have shape [N_moves*8, N+2, N+2, 2]\n\n board: The string rep of the stones, like e.g. \"j10k11i9\"\n \"\"\"\n \n # stones in matrix coordinates respecting the border padding\n maybe_padded_stones = self.maybe_padded_coords(board)\n\n # all equivalent representations: 4xrot, 2xflip = 8 variants \n all_traj = self.all_symmetries(maybe_padded_stones)\n \n all_samples = []\n all_values = []\n for traj in all_traj:\n samples, values = self.traj_to_samples_with_actions(traj)\n \n if self.cut_off: \n samples = samples[-self.cut_off:] \n values = values[-self.cut_off:]\n\n all_samples = all_samples + samples\n all_values = all_values + values \n\n \n return all_samples, all_values\n\n def traj_to_samples_with_actions(self, traj, sparse=False):\n \"\"\"\n creates samples from a given trajectory, together with their actions\n\n traj: trajectory, represented by their padded coordinates\n terminal_value: the given value of the last state in the trajectory\n gamma: discount factor. \n \"\"\"\n samples = []\n actions = []\n to_move_first = 1\n for t in range(len(traj)-1): \n moves = traj[:t+1]\n r, c = traj[t+1]\n if self.rep == 'NxNx1B' or self.edges:\n r-=1\n c-=1\n if sparse: \n # flattened coordinates\n action = r * self.N + c\n else:\n action = np.zeros([self.N, self.N], dtype=np.float32)\n action[next_move[0]][next_move[1]] = 1.0\n\n sample = self.create_sample(moves, to_move_first)\n \n samples.append(sample)\n actions.append(action)\n\n to_move_first = 1 - to_move_first\n\n \n return samples, actions\n \n \n def sample_from_string(self, game):\n coords = self.maybe_padded_coords(game)\n to_move = 1 if len(coords) % 2 == 1 else 0\n return self.create_sample(coords, to_move)\n \n\n def stones_from_NxNx1B (self, smp):\n \"\"\"\n reconstructs stones from a NxNx1B sample representation\n Note that the moves will not (likely) be in their original order \n \"\"\"\n board = np.rollaxis(smp, 2, 0)[0].T[1:-1].T[1:-1]\n to_move = np.sum(board > 0)\n other = np.sum(board < 0)\n\n if other > to_move:\n BLACK, WHITE = -1, 1\n else:\n BLACK, WHITE = 1, -1\n\n r,c = np.where(board == WHITE)\n x,y = gt.m2b((r,c), self.N)\n white_moves = list(zip(x,y))\n\n r,c = np.where(board == BLACK)\n x,y = gt.m2b((r,c), self.N)\n black_moves = list(zip(x,y))\n\n moves = np.zeros([len(black_moves) + len(white_moves),2])\n moves[::2,] = np.array(black_moves)\n moves[1::2,] = np.array(white_moves)\n stones = [(int(move[0]), int(move[1])) for move in moves]\n\n return stones\n\ndef new_value_dataset(file_pattern, gamma, sdh,\n batch_size=256, num_epochs=1, buffer_size=500):\n \n games = tf.data.experimental.make_csv_dataset(\n file_pattern = file_pattern,\n column_names=[\"game\", \"winner\"],\n batch_size=1,\n num_epochs=num_epochs\n ) \n def _generator(): \n for batch in iter(games):\n game = batch['game'][0].numpy().decode('ascii')\n smp, lbl = sdh.from_string_with_bellmann(game, -1, gamma)\n zipped = zip(smp, lbl)\n for s_and_v in zipped:\n yield s_and_v\n \n inputs = tf.data.Dataset.from_generator(\n _generator, output_types=(tf.int32, tf.float32))\n \n inputs = inputs.shuffle(buffer_size).batch(batch_size)\n return inputs\n \n \n \ndef new_policy_dataset(file_pattern, sdh,\n batch_size=256, num_epochs=1, buffer_size=500):\n \n games = tf.data.experimental.make_csv_dataset(\n file_pattern = file_pattern,\n column_names=[\"game\", \"winner\"],\n batch_size=1,\n num_epochs=num_epochs\n ) \n def _generator(): \n for batch in iter(games):\n game = tf.squeeze(batch['game']).numpy().decode('ascii')\n smp, lbl = sdh.from_string_with_actions(game)\n lbl = np.reshape(lbl, [-1, 19*19])\n zipped = zip(smp, lbl)\n for s_and_v in zipped:\n yield s_and_v\n \n inputs = tf.data.Dataset.from_generator(\n _generator, output_types=(tf.int32, tf.float32))\n \n inputs = inputs.shuffle(buffer_size).batch(batch_size)\n return inputs\n \n \n \n \ndef analyse_and_recommend(smp, pi, n_best, N=19, m2b=\"board\"):\n \"\"\"\n calculates the n_best best positions in board coordinates of smp, \n looking at the sample and its policy result pi(smp)\n Params:\n smp: np.ndarray: A sample in NxNx1B representation (using 1,-1 for the stones)\n pi: np.ndarray: the NxN policy pi(a|s=smp)\n n_best: the n_best positions to return. Note that there may be further positions\n having pi match the worst of the best positions. We make a hard cut so that the\n number of returned positions is exactly n_best.\n N: the board size\n m2b: coord system to encode positions: either of \"board\", \"original\", or \"padded\"\n \"\"\"\n\n # mask occupied positions\n occupied = np.abs(np.rollaxis(smp, 2, 0)[0].T[1:-1].T[1:-1])\n \n ##\n ## Super-evil hack! Will come back and solve, I promise!\n ## Background: pi seems to be shifted down-right. Can't find out, why.\n ## So I shift it back up-left here before continuing.\n ##\n pi = np.vstack([pi, np.zeros(19)])[1:,] # up\n pi = np.hstack([pi, np.zeros([19,1], dtype=np.float32)]).T[1:,].T #left\n \n distr = (1 - occupied) * pi\n\n corr = 1 if m2b == \"padded\" else 0\n \n # Drawing from pi of dimensions NxN always comes as 'original' without padding\n max_likely = sorted(np.reshape(distr, [N*N]))[::-1][:n_best]\n yn = distr == max_likely[0]\n for i in range(1,n_best):\n yn = np.add(yn, distr == max_likely[i]) \n r, c = np.where(yn)\n greedy_positions = [\n (gt.m2b((rr,cc), N), distr[rr][cc]) if m2b == 'board' else ((rr+corr, cc+corr), distr[rr][cc])\n for rr, cc in zip(r,c) \n ]\n \n return distr, greedy_positions[:n_best]\n\n\nclass SelfPlay:\n def __init__(self, policy, board_size, start_with):\n \"\"\"\n Params:\n policy: the policy model\n board_size: The side length of the board\n start_with: a padded representation of a starting traj\n \"\"\"\n self.board_size = board_size\n self.td = TerminalDetector(board_size+2)\n self.pi = policy\n self.sdh = SampleDataHelper(board_size, representation='NxNx1B')\n self.empty = self.sdh.template()\n if start_with is not None:\n self.start_traj = start_with\n self.start = self.sdh.create_sample(start_with, 1)\n else:\n self.start_traj = [(10, 10)]\n self.start = self.empty.copy()\n self.start[10][10][0] = -1\n \n \n\n def create_episodes(self, n_episodes, m2b):\n \"\"\"\n create a given number of episodes in the given coord system.\n All episodes are guaranteed to be terminated with value = -1.\n This may take some time - since it requires a large number of policy evaluations.\n n_episodes: Number of episodes to return. \n m2b: coord system to encode trajectories: either of \"board\", \"original\", or \"padded\"\n \"\"\"\n episodes = []\n while len(episodes) < n_episodes:\n game, traj, terminated = self.create_episode(\n limit=50, n_choices=10, greedy_bias=300, m2b=m2b)\n if terminated:\n episodes.append(traj)\n return episodes\n\n\n def create_episode(self, limit, n_choices, greedy_bias, m2b):\n \"\"\"\n Params:\n m2b: coord system to encode traj: either of \"board\", \"original\", or \"padded\"\n Returns: The final game state, the trajectory and a flag indicating termination.\n \"\"\"\n move_count = 0\n terminated = False\n game = self.start.copy()\n\n traj = self.start_traj\n if m2b == 'original':\n traj = [(r-1, c-1) for (r,c) in traj]\n elif m2b == 'board':\n traj = [gt.m2b((r-1, c-1), self.board_size) for (r,c) in traj]\n\n while move_count < limit and not terminated:\n game, move = self.do_one_move(game, n_choices, greedy_bias, m2b)\n traj.append(move)\n terminated = (self.td.call(game) != 0).any()\n move_count += 1\n return game, traj, terminated\n\n \n def do_one_move(self, game, n_choices, greedy_bias, m2b):\n game = game.copy()\n pi = self.pi.dist(np.reshape(game, [1,21,21,2]))\n _, choice = analyse_and_recommend(game, pi, n_choices, m2b='padded')\n weights = [greedy_bias*g[1] for g in choice]\n weights = np.exp(weights)/np.sum(np.exp(weights))\n draw = np.squeeze(np.random.choice(range(n_choices), p=weights, size=1))\n move = choice[draw][0]\n r, c = np.array(move) \n game[r][c][0] = 1\n\n if m2b == 'original':\n move = (r-1, c-1)\n elif m2b == 'board':\n move = gt.m2b((r-1, c-1), self.board_size)\n\n return 2 * self.empty - game, move \n \n \nclass A2C_SampleGeneratorFactory:\n \n def __init__(self, board_size, value_model, gamma, cut_off=None):\n \"\"\"\n gamma: discount factor\n \"\"\"\n self.board_size = board_size\n self.value_model = value_model\n self.sdh = SampleDataHelper(board_size, representation='NxNx1B', cut_off=cut_off)\n self.gamma = gamma\n \n def create_generator(self, episodes, kind): \n \"\"\"\n episodes: list of border-padded matrix coordinates (move sequences)\n kind: 'values' or 'advantages' for the two different fitting phases of A2C\n \"\"\"\n def _generator():\n dataset = []\n for episode in episodes:\n\n # We compute the value targets once for all symmetries\n if kind == 'values': \n # bellmann values not needed here, we compute targets\n samples, _ = self.sdh.traj_to_samples(episode, -1, self.gamma)\n elif kind == 'advantages':\n samples, actions = self.sdh.traj_to_samples_with_actions(episode, sparse=True)\n else: \n raise ValueError(\"Kind '%s' not supported\" % kind)\n \n values = self.gamma * np.squeeze(\n self.value_model.call(samples).numpy())\n\n # all games end with the one to move staring at a line of five.\n values[-1] = -1.0\n values[-2] = 1.0 # second-but-last: The winner's big chance\n\n # Shift by 2: next position means 'next for the same player'\n shifted = self.gamma * values[2:]\n shifted = np.append(shifted, 1.)\n shifted = np.append(shifted, -1.)\n advantages = shifted - values\n\n # Now zip it all up for each symmetric representation\n all_syms = self.sdh.all_symmetries(episode)\n for sym in all_syms:\n rep = []\n dataset.append(rep)\n samples, _ = self.sdh.traj_to_samples(sym, -1, self.gamma)\n\n if kind == 'values':\n for s_l in zip(samples, shifted):\n rep.append(s_l)\n elif kind == 'advantages': # need labels and weights!\n for s_l_w in zip(samples, actions, advantages):\n rep.append(s_l_w)\n else: \n raise ValueError(\"Kind '%s' not supported\" % kind)\n\n # Return the generator on all representation within the dataset\n for rep in dataset:\n for sva in rep:\n yield sva\n \n return _generator","sub_path":"wgomoku/wgomoku/SampleDataHelper.py","file_name":"SampleDataHelper.py","file_ext":"py","file_size_in_byte":19604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"201698321","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Mar 18 20:06:25 2021\r\n\r\n@author: fyf\r\n\"\"\"\r\n\r\nimport boto3\r\nimport json\r\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\r\nfrom requests_aws4auth import AWS4Auth\r\n\r\ndef search(keys):\r\n service = 'es'\r\n region = 'us-west-2'\r\n # headers = {\"Content-Type\" : \"application/json\"}\r\n credentials = boto3.Session().get_credentials()\r\n awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)\r\n \r\n\r\n es = Elasticsearch(\r\n hosts = [{'host': 'search-photos-ofe6jnxvlnksqy5bihubm67r7u.us-west-2.es.amazonaws.com', 'port': 443}],\r\n http_auth = awsauth,\r\n use_ssl = True,\r\n verify_certs = True,\r\n connection_class = RequestsHttpConnection\r\n )\r\n \r\n results = []\r\n \r\n for key in keys:\r\n r = es.search(index=\"photos\", body={\"from\":0,\"size\":10,\"query\":{\"match\":{\"labels\":key}}})\r\n for r in r[\"hits\"][\"hits\"]:\r\n objKey = r['_source']['objectKey']\r\n # bucket = r[\"'_source'\"]['bucket']\r\n results.append(\"https://cs6998-hw2-imgs-clf.s3-us-west-2.amazonaws.com/\" + objKey)\r\n\r\n return results\r\n \r\n \r\ndef lambda_handler(event, context):\r\n query = event['queryStringParameters'].get(\"q\")\r\n urls = []\r\n if not query: \r\n urls = []\r\n else:\r\n qLst = query.lower().split(' ')\r\n andIdx = sum([i if qLst[i] == 'and' else 0 for i in range(len(qLst))])\r\n qLstClean = [qLst[andIdx-1], qLst[andIdx+1]] if andIdx else [qLst[-1]]\r\n qLstClean = [word[:-1] if word[-1] =='s' else word for word in qLstClean]\r\n urls = search(qLstClean)\r\n\r\n \r\n response = {\r\n 'statusCode': 200,\r\n 'headers': {\r\n 'Access-Control-Allow-Headers': 'Content-Type',\r\n 'Access-Control-Allow-Origin': '*',\r\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',\r\n },\r\n 'body': json.dumps({ \r\n \"urls\": urls\r\n }),\r\n 'isBase64Encoded': False,\r\n }\r\n \r\n return response\r\n\r\n\r\n\r\n# comment\r\n","sub_path":"hw2-get-imgs-ee3bce15-2613-452e-a059-7c4e7c5e9d08/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"518643910","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport os.path\nimport re\nimport urllib2\n\nclass Session:\n def __init__(self, session):\n self.name = session['title']\n self.description = session['description']\n self.sessionID = session['id']\n self.track = session['track']\n self.url = session['download_hd']\n self.fanart = session['images']['shelf']\n self.duration = session['duration']\n date = str(session['date'])\n if date is not None:\n self.year = date.split('-', 1)[0]\n self.title = '['+ self.year +'/'+ self.track +'] '+ self.name\n\n def getInfo(self):\n return {\n 'duration': self.duration,\n 'plot': self.description,\n 'title': self.title,\n 'year': self.year,\n }\n\nclass Sessions:\n def __init__(self, url, dataPath):\n self.url = url\n self.cacheFile = os.path.join(dataPath, 'sessions.json')\n\n def clearCache(self):\n if os.path.isfile(self.cacheFile):\n os.remove(self.cacheFile)\n\n def years(self):\n self.sessions = self._loadSessions()\n years = []\n for session in self.sessions:\n if session.year in years or session.year == 'None':\n continue\n years.append(session.year)\n return years\n\n def list(self, year):\n self.sessions = self._loadSessions()\n result = []\n for session in self.sessions:\n if session.year == year:\n result.append(session)\n return result\n\n def find(self, sessionID):\n self.sessions = self._loadSessions()\n for session in self.sessions:\n if session.sessionID == sessionID:\n return session\n\n def search(self, keyword):\n self.sessions = self._loadSessions()\n result = []\n for session in self.sessions:\n for token in session.title.split():\n if keyword.lower() in token.lower():\n result.append(session)\n return result\n\n def _loadSessions(self):\n sessions = []\n try:\n with open(self.cacheFile) as data:\n data = json.load(data)\n except:\n data = self._fetchData()\n if data is not None:\n for session in data['sessions']:\n sessions.append(Session(session))\n return sessions\n\n def _fetchData(self):\n request = urllib2.Request(self.url)\n try:\n response = urllib2.urlopen(request)\n result = response.read()\n response.close()\n self._writeCache(result)\n return json.loads(result)\n except:\n return None\n\n def _writeCache(self, data):\n cache = open(self.cacheFile, 'w')\n cache.write(data)\n cache.close\n","sub_path":"plugin.video.wwdc/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"10429625","text":"from typing import Dict\n\n# \"base_dir\": \"D:\\soundofai\\\\pitch_shifted_all\",\n\ndef get_config() -> Dict:\n conf = {\n \"base_dir\": \"D:\\soundofai\\\\all_nsynth_audio\",\n \"csv_file_path\": \"D:\\soundofai\\\\annot_data\\\\data\\\\june_06.csv\",\n \"fb_categorical_file\": \"..\\\\fb_categorical.json\",\n \"preprocess_dir\": \"tmp\",\n \"audio_duration\": 4,\n \"clip_at\": -30,\n \"epsilon\": 1e-5,\n \"clip_audio_at\": 2,\n \"sample_rate\": 16000,\n \"num_classes\": 12,\n \"n_fft\": 2048,\n \"hop_len\": 512,\n \"n_mels\": 128,\n \"scale_factor\": 1.0,\n \"learning_rate\": 2e-4,\n \"threshold\": 15,\n \"all_features\": [\n 'bright_vs_dark', 'full_vs_hollow', 'smooth_vs_rough',\n 'warm_vs_metallic', 'clear_vs_muddy', 'thin_vs_thick',\n 'pure_vs_noisy', 'rich_vs_sparse', 'soft_vs_hard'\n ],\n \"features\": [\"bright_vs_dark\"],\n \"model_name\": \"fb_qualities\",\n \"valid_split\": 0.4,\n \"dry_run\": False,\n \"reset_data\": False,\n \"pitch_shifted\": True\n }\n\n conf = dict(conf)\n audio_duration_samples = (conf.get(\"audio_duration\") - conf.get(\"clip_audio_at\")) * conf.get(\"sample_rate\")\n conf[\"time_steps\"] = 1 + audio_duration_samples // conf.get(\"hop_len\")\n conf[\"num_conv_blocks\"] = 3\n return conf\n","sub_path":"members/amit/clf/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"302138687","text":"from contextlib import contextmanager\nfrom distutils.version import LooseVersion\nimport pdb\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\nimport torch\nfrom typeguard import check_argument_types\nimport logging\n\nfrom espnet.nets.e2e_asr_common import ErrorCalculator\nfrom espnet.nets.pytorch_backend.nets_utils import th_accuracy\nfrom espnet.nets.pytorch_backend.transformer.add_sos_eos import add_sos_eos\nfrom espnet.nets.pytorch_backend.transformer.label_smoothing_loss import (\n LabelSmoothingLoss, # noqa: H301\n)\nfrom espnet2.asr.ctc import CTC\nfrom espnet2.asr.encoder.abs_encoder import AbsEncoder\nfrom espnet2.asr.encoder.condition_encoder import ConditionalModule\nfrom espnet2.asr.frontend.abs_frontend import AbsFrontend\nfrom espnet2.asr.preencoder.abs_preencoder import AbsPreEncoder\nfrom espnet2.asr.specaug.abs_specaug import AbsSpecAug\nfrom espnet2.layers.abs_normalize import AbsNormalize\nfrom espnet2.torch_utils.device_funcs import force_gatherable\nfrom espnet2.train.abs_espnet_model import AbsESPnetModel\n\nif LooseVersion(torch.__version__) >= LooseVersion(\"1.6.0\"):\n from torch.cuda.amp import autocast\nelse:\n # Nothing to do if torch<1.6.0\n @contextmanager\n def autocast(enabled=True):\n yield\nfrom torch.nn.utils.rnn import pad_sequence\nimport torch.nn.functional as F\nclass ESPnetASRModel(AbsESPnetModel):\n \"\"\"CTC-attention hybrid Encoder-Decoder model\"\"\"\n\n def __init__(\n self,\n vocab_size: int,\n token_list: Union[Tuple[str, ...], List[str]],\n frontend: Optional[AbsFrontend],\n specaug: Optional[AbsSpecAug],\n normalize: Optional[AbsNormalize],\n preencoder: Optional[AbsPreEncoder],\n encoder: AbsEncoder,\n encoder_con: ConditionalModule,\n encoder_rec: AbsEncoder,\n ctc: CTC,\n use_inter_ctc: bool = False,\n use_stop_sign_bce: bool = False,\n inter_ctc_weight: float = 0.3,\n ctc_weight: float = 0.5,\n ignore_id: int = -1,\n lsm_weight: float = 0.0,\n length_normalized_loss: bool = False,\n report_cer: bool = True,\n report_wer: bool = True,\n sym_space: str = \"\",\n sym_blank: str = \"\",\n ):\n assert check_argument_types()\n assert 0.0 <= ctc_weight <= 1.0, ctc_weight\n\n super().__init__()\n # note that eos is the same as sos (equivalent ID)\n \n self.sos = vocab_size - 1\n self.eos = vocab_size - 1\n self.vocab_size = vocab_size\n self.ignore_id = ignore_id\n self.ctc_weight = ctc_weight\n self.token_list = token_list.copy()\n\n self.frontend = frontend\n self.specaug = specaug\n self.normalize = normalize\n self.preencoder = preencoder\n self.encoder = encoder\n self.encoder_con = encoder_con\n self.encoder_rec = encoder_rec\n self.ctc = ctc\n self.criterion_att = LabelSmoothingLoss(\n size=vocab_size,\n padding_idx=ignore_id,\n smoothing=lsm_weight,\n normalize_length=length_normalized_loss,\n )\n self.use_inter_ctc = use_inter_ctc\n self.adim = encoder.output_size()\n if self.use_inter_ctc:\n self.inter_ctc_weight = inter_ctc_weight\n self.project_linear = torch.nn.Linear(self.encoder_con.output_size(), self.adim)\n self.use_stop_sign_bce = use_stop_sign_bce\n\n if self.use_stop_sign_bce:\n self.stop_sign_loss = StopBCELoss(self.adim, 1, nunits=self.adim)\n if report_cer or report_wer:\n self.error_calculator = ErrorCalculator(\n token_list, sym_space, sym_blank, report_cer, report_wer\n )\n else:\n self.error_calculator = None\n def min_ctc_loss_and_perm(self, hs_pad, hs_len, ys_pad, text_lengths_new):\n \"\"\"E2E min ctc loss and permutation.\n\n :param torch.Tensor xs_pad: batch of padded source sequences (B, Tmax, idim)\n :param torch.Tensor hs_len: batch of lengths of source sequences (B)\n :param torch.Tensor ys_pad: batch of padded target sequences (B, num_spkrs', Lmax)\n :rtype: torch.Tensor\n :return: ctc loss value\n :rtype: torch.Tensor\n :return: minimum index\n \"\"\"\n \n _, n_left_spkrs, _ = ys_pad.size()\n loss_stack = torch.stack(\n [self.ctc(hs_pad, hs_len, ys_pad[:, i], text_lengths_new[:, i]) for i in range(n_left_spkrs)]\n ) # (N, B, 1)\n min_loss, min_idx = torch.min(loss_stack, 0)\n return min_loss, min_idx\n def resort_sequence(self, xs_pad, min_idx, start):\n \"\"\"E2E re-sort sequence according to min_idx.\n\n :param torch.Tensor xs_pad: batch of padded source sequences (B, num_spkrs, Lmax)\n :param torch.Tensor min_idx: batch of min idx (B)\n :param int start: current head of sequence.\n :rtype: torch.Tensor\n :return: re-sorted sequence\n \"\"\"\n n_batch = xs_pad.size(0)\n for i in range(n_batch):\n tmp = xs_pad[i, start].clone()\n xs_pad[i, start] = xs_pad[i, min_idx[i]]\n xs_pad[i, min_idx[i]] = tmp\n return xs_pad\n\n def forward(\n self,\n speech: torch.Tensor,\n speech_lengths: torch.Tensor,\n text: torch.Tensor,\n text_lengths: torch.Tensor,\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], torch.Tensor]:\n \"\"\"Frontend + Encoder + Decoder + Calc loss\n\n Args:\n speech: (Batch, Length, ...)\n speech_lengths: (Batch, )\n text: (Batch, Length)\n text_lengths: (Batch,)\n \"\"\"\n assert text_lengths.dim() == 1, text_lengths.shape\n # Check that batch_size is unified\n assert (\n speech.shape[0]\n == speech_lengths.shape[0]\n == text.shape[0]\n == text_lengths.shape[0]\n ), (speech.shape, speech_lengths.shape, text.shape, text_lengths.shape)\n batch_size = speech.shape[0]\n text_all = []\n text_lengths_new = []\n text_lengths_max = int(text_lengths.max())\n for i in range(batch_size):\n text_utt_list=[]\n text_start = 0\n text_end = text_lengths_max\n for j in range(text_lengths_max):\n if text[i][j] == 2:\n text_utt_list.append(text[i][text_start:j])\n text_lengths_new.append(j-text_start)\n text_start = j+1\n elif text[i][j] == -1:\n text_end = j\n break\n if(text_start != text_lengths_max):\n text_utt_list.append(text[i][text_start:text_end])\n text_lengths_new.append(text_end-text_start)\n text_all.append(text_utt_list)\n text_lengths_new = torch.Tensor(text_lengths_new).int()\n text_lengths_max = int(text_lengths_new.max())\n text_lengths_new = text_lengths_new.view(batch_size,-1).to(speech.device)\n num_spkrs = text_lengths_new.size(1)\n text_all_final=[]\n\n for i in range(batch_size):\n text_sequence = pad_sequence(text_all[i],batch_first=True, padding_value=-1)\n pad_num = text_lengths_max - text_sequence.size(-1)\n if pad_num > 0:\n text_sequence = F.pad(text_sequence, (0,pad_num), \"constant\", -1)\n text_all_final.append(text_sequence)\n text_final_label = torch.stack(text_all_final,dim=0).to(speech.device)\n # for data-parallel\n #text = text[:, : text_lengths.max()]\n # 1. Encoder\n encoder_out, encoder_out_lens = self.encode(speech, speech_lengths)\n # encoder_out batchsize * time * dim256\n # encoder_out_lens batchsize\n \n cer_ctc = None\n\n prev_states = None\n hs_pad_sd, loss_ctc, loss_inter_ctc, loss_stop = (\n [None] * num_spkrs,\n [None] * num_spkrs,\n [None] * num_spkrs,\n [None] * num_spkrs,\n )\n\n loss_att, acc_att, cer_att, wer_att = None, None, None, None\n # encoder_out bc * T * D(256)\n align_ctc_state = encoder_out.new_zeros(encoder_out.size())\n \n for i in range(num_spkrs):\n condition_out, prev_states = self.encoder_con(\n encoder_out, align_ctc_state, encoder_out_lens, prev_states\n )\n # condition_out 8*211*1024\n hs_pad_sd[i], encoder_out_lens,_= self.encoder_rec.forward_hidden(condition_out, encoder_out_lens)\n # hs_pad_sd[i] bc * T * D(256)\n loss_ctc[i], min_idx = self.min_ctc_loss_and_perm(\n hs_pad_sd[i], encoder_out_lens, text_final_label[:, i:], text_lengths_new[:, i:]\n )\n min_idx = min_idx + i\n if i < num_spkrs - 1:\n text_final_label = self.resort_sequence(text_final_label, min_idx, i)\n if self.use_inter_ctc:\n hidden_feature = self.encoder_rec.hidden_feature\n loss_inter_ctc[i] = self.ctc(hidden_feature, encoder_out_lens, text_final_label[:, i], text_lengths_new[:, i])\n logging.info(\"using latent representation as soft conditions.\")\n align_ctc_state = hs_pad_sd[i].detach().data\n if self.use_stop_sign_bce:\n stop_label = hs_pad_sd[i].new_zeros((batch_size, 1))\n if i == num_spkrs - 1:\n stop_label += 1\n loss_stop[i] = self.stop_sign_loss(hs_pad_sd[i], encoder_out_lens, stop_label)\n loss_ctc = torch.stack(loss_ctc, dim=0).mean() # (num_spkrs, B)\n loss_stop = torch.stack(loss_stop, dim=0).mean()\n logging.info(\"ctc loss:\" + str(float(loss_ctc)))\n if self.use_inter_ctc:\n loss_inter_ctc = torch.stack(loss_inter_ctc, dim=0).mean() # (num_spkrs, B)\n logging.info(\"inter ctc loss:\" + str(float(loss_inter_ctc)))\n loss = self.inter_ctc_weight * loss_inter_ctc + (1 - self.inter_ctc_weight) * loss_ctc\n loss_att = loss_inter_ctc\n else:\n loss = loss_ctc\n loss_att = None\n if self.use_stop_sign_bce:\n loss += loss_stop * 100\n acc_att = loss_stop\n stats = dict(\n loss=loss.detach(),\n loss_att=loss_att.detach() if loss_att is not None else None,\n loss_ctc=loss_ctc.detach() if loss_ctc is not None else None,\n acc=acc_att.detach() if acc_att is not None else None,\n cer=cer_att,\n wer=wer_att,\n cer_ctc=cer_ctc,\n )\n # force_gatherable: to-device and to-tensor if scalar for DataParallel\n loss, stats, weight = force_gatherable((loss, stats, batch_size), loss.device)\n return loss, stats, weight\n\n def collect_feats(\n self,\n speech: torch.Tensor,\n speech_lengths: torch.Tensor,\n text: torch.Tensor,\n text_lengths: torch.Tensor,\n ) -> Dict[str, torch.Tensor]:\n feats, feats_lengths = self._extract_feats(speech, speech_lengths)\n return {\"feats\": feats, \"feats_lengths\": feats_lengths}\n\n def encode(\n self, speech: torch.Tensor, speech_lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Frontend + Encoder. Note that this method is used by asr_inference.py\n\n Args:\n speech: (Batch, Length, ...)\n speech_lengths: (Batch, )\n \"\"\"\n with autocast(False):\n # 1. Extract feats\n feats, feats_lengths = self._extract_feats(speech, speech_lengths)\n\n # 2. Data augmentation\n if self.specaug is not None and self.training:\n feats, feats_lengths = self.specaug(feats, feats_lengths)\n\n # 3. Normalization for feature: e.g. Global-CMVN, Utterance-CMVN\n if self.normalize is not None:\n feats, feats_lengths = self.normalize(feats, feats_lengths)\n\n # Pre-encoder, e.g. used for raw input data\n if self.preencoder is not None:\n feats, feats_lengths = self.preencoder(feats, feats_lengths)\n\n # 4. Forward encoder\n # feats: (Batch, Length, Dim)\n # -> encoder_out: (Batch, Length2, Dim2)\n encoder_out, encoder_out_lens, _ = self.encoder(feats, feats_lengths)\n\n assert encoder_out.size(0) == speech.size(0), (\n encoder_out.size(),\n speech.size(0),\n )\n assert encoder_out.size(1) <= encoder_out_lens.max(), (\n encoder_out.size(),\n encoder_out_lens.max(),\n )\n\n return encoder_out, encoder_out_lens\n\n def _extract_feats(\n self, speech: torch.Tensor, speech_lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n assert speech_lengths.dim() == 1, speech_lengths.shape\n\n # for data-parallel\n speech = speech[:, : speech_lengths.max()]\n\n if self.frontend is not None:\n # Frontend\n # e.g. STFT and Feature extract\n # data_loader may send time-domain signal in this case\n # speech (Batch, NSamples) -> feats: (Batch, NFrames, Dim)\n feats, feats_lengths = self.frontend(speech, speech_lengths)\n else:\n # No frontend and no feature extract\n feats, feats_lengths = speech, speech_lengths\n return feats, feats_lengths\n\n def _calc_att_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n \n loss_att, acc_att, cer_att, wer_att = None, None, None, None\n return loss_att, acc_att, cer_att, wer_att\n\n def _calc_ctc_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n # Calc CTC loss\n loss_ctc = self.ctc(encoder_out, encoder_out_lens, ys_pad, ys_pad_lens)\n\n # Calc CER using CTC\n cer_ctc = None\n if not self.training and self.error_calculator is not None:\n ys_hat = self.ctc.argmax(encoder_out).data\n cer_ctc = self.error_calculator(ys_hat.cpu(), ys_pad.cpu(), is_ctc=True)\n return loss_ctc, cer_ctc\n\n def _calc_rnnt_loss(\n self,\n encoder_out: torch.Tensor,\n encoder_out_lens: torch.Tensor,\n ys_pad: torch.Tensor,\n ys_pad_lens: torch.Tensor,\n ):\n raise NotImplementedError\n\n\nclass StopBCELoss(torch.nn.Module):\n def __init__(\n self, idim, odim=1, nlayers=1, nunits=512, dropout=0, bidirectional=False\n ):\n super(StopBCELoss, self).__init__()\n self.idim = idim\n self.lstmlayers = torch.nn.LSTM(\n idim, nunits, nlayers, batch_first=True, bidirectional=bidirectional\n )\n self.output = torch.nn.Linear(idim, odim)\n self.dropout = torch.nn.Dropout(dropout)\n\n self.loss = torch.nn.BCELoss()\n\n def forward(self, xs_pad, xs_len, ys):\n \"\"\"\n :param torch.Tensor xs_pad: input sequence (B, Tmax, dim)\n :param list xs_len: the lengths of xs (B)\n :param torch.Tensor ys: the labels (B, 1)\n \"\"\"\n xs_pack = torch.nn.utils.rnn.pack_padded_sequence(\n xs_pad, xs_len.cpu(), batch_first=True\n )\n _, (h_n, _) = self.lstmlayers(xs_pack) # (B, dim)\n linear_out = self.dropout(self.output(h_n[-1])) # (B, 1)\n linear_out = torch.sigmoid(linear_out)\n return self.loss(linear_out, ys)\n def get_stop_sign(self, xs_pad, xs_len):\n \"\"\"\n :param torch.Tensor xs_pad: input sequence (B, Tmax, dim)\n :param list xs_len: the lengths of xs (B)\n :param torch.Tensor ys: the labels (B, 1)\n \"\"\"\n xs_pack = torch.nn.utils.rnn.pack_padded_sequence(\n xs_pad, xs_len.cpu(), batch_first=True\n )\n _, (h_n, _) = self.lstmlayers(xs_pack) # (B, dim)\n linear_out = self.dropout(self.output(h_n[-1])) # (B, 1)\n linear_out = torch.sigmoid(linear_out)\n return linear_out\n","sub_path":"espnet_model_con.py","file_name":"espnet_model_con.py","file_ext":"py","file_size_in_byte":16193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"68841049","text":"import os\nimport torch\nimport torch.nn as nn\ntorch.manual_seed(1)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nfrom models.CharConv import CharConv\nfrom models.CLR import CyclicLR\nfrom models.Stopper import EarlyStopping\nfrom sklearn.metrics import accuracy_score, f1_score, classification_report\nfrom torch.autograd import Variable\nfrom utilities import *\n\n\nHIDDEN_SIZE = 256\nBATCH_SIZE = 16\nMAX_SEQUENCE = 1024\nLINEAR_SIZE = 256\nLEARNING_RATE = 0.005\nREG_PARAM = 1e-1\nMOMENTUM = 0.8\nEPOCHS = 500\nPATH = 'data/processed/training/*.txt'\nUSE_CUDA = torch.cuda.is_available()\n\n\ndef train_batch(_model, _x_tensor, _y_tensor, _target):\n _model.zero_grad()\n # input should be batch, alphabet, hidden_size\n out = _model(_x_tensor)\n _loss = _target(out.cuda(), _y_tensor.long())\n _loss.backward()\n for p in _model.parameters():\n if p.grad is not None:\n p.data.add_(-LEARNING_RATE, p.grad.data)\n torch.cuda.empty_cache()\n return out, _loss.item()\n\n\ndef evaluate(_model, _x_val, _y_val):\n out = _model(_x_val)\n out_proba, out_class = torch.max(out, 1)\n acc = accuracy_score(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy())\n f1 = f1_score(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy(), average='weighted')\n cr = classification_report(_y_val.type(torch.int32).numpy(),\n out_class.cpu().type(torch.int32).numpy())\n return acc, f1, cr\n\n\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n device = torch.device(\"cuda:0\" if USE_CUDA else \"cpu\")\n try:\n df = torch.load('outputs/padded_chars.pkl')\n except:\n df = PaddedCharSeqData(PATH, MAX_SEQUENCE)\n torch.save(df, 'outputs/padded_chars.pkl')\n train, valid, test = train_valid_test_split(df, split_fold=BATCH_SIZE*20)\n print('Training set has {m} entries'.format(m=len(train)))\n print('Validation set has {n} entries'.format(n=len(valid)))\n print('Test set has {t} entries'.format(t=len(test)))\n train_batched = DataLoader(train, batch_size=BATCH_SIZE, shuffle=True, drop_last=True)\n valid_set = DataLoader(valid, batch_size=len(valid), shuffle=False)\n test_set = DataLoader(test, batch_size=len(test), shuffle=False)\n model = CharConv(len(df.alphabet), df.count_classes(), HIDDEN_SIZE, BATCH_SIZE, MAX_SEQUENCE, LINEAR_SIZE).cuda()\n criterion = nn.NLLLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=REG_PARAM) #, momentum=MOMENTUM)\n #scheduler = CyclicLR(optimizer)\n stopper = EarlyStopping(patience=101, verbose=True, saver=False)\n for epoch in range(EPOCHS):\n el = 0\n model.train()\n for batch in train_batched:\n #scheduler.batch_step()\n x = Variable(batch[0].cuda(), requires_grad=True)\n y = Variable(batch[1].cuda())\n preds, loss = train_batch(model, x, y, criterion)\n el += loss\n\n model.eval()\n for val_batch in valid_set:\n x_val = Variable(val_batch[0].cuda())\n y_val = Variable(val_batch[1].cuda())\n val_out = model(x_val)\n val_loss = criterion(val_out.cuda(), y_val.long())\n stopper(val_loss, model)\n\n if stopper.early_stop:\n print(\"Stopping training at epoch {cur}\".format(cur=epoch))\n for test_batch in test_set:\n x_test = Variable(test_batch[0].cuda())\n y_test = Variable(test_batch[1])\n acc, f1, cr = evaluate(model, x_test, y_test)\n print('Test set accuracy of {a} and F1 of {f}'.format(a=acc, f=f1))\n print(cr)\n break\n\n if epoch % 5 == 0:\n for test_batch in test_set:\n x_test = Variable(test_batch[0].cuda())\n y_test = Variable(test_batch[1])\n acc, f1, cr = evaluate(model, x_test, y_test)\n print('Test set accuracy of {a} and F1 of {f}'.format(a=acc, f=f1))\n print(cr)\n print('Epoch {e} had loss {ls}'.format(e=epoch, ls=el))\n #lr_list = scheduler.get_lr()\n torch.save(model.state_dict(), 'outputs/conv_model.pt')\n #print('Final learning rate was {x}'.format(x=lr_list[-1]))\n","sub_path":"src/train_conv.py","file_name":"train_conv.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"644216858","text":"# 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。\r\n#\r\n# 在杨辉三角中,每个数是它左上方和右上方的数的和。\r\n'''\r\n示例:\r\n\r\n输入: 5\r\n输出:\r\n[\r\n [1],\r\n [1,1],\r\n [1,2,1],\r\n [1,3,3,1],\r\n [1,4,6,4,1]\r\n]\r\n'''\r\nclass Solution:\r\n def generate(self, numRows):\r\n \"\"\"\r\n :type numRows: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n if numRows == 0:\r\n return []\r\n elif numRows == 1:\r\n return [[1]]\r\n elif numRows == 2:\r\n return [[1], [1, 1]]\r\n elif numRows > 2:\r\n result = []\r\n for i in range(1, numRows + 1):\r\n temp = [result[-1][j - 1] + result[-1][j] for j in range(1, i - 1)]\r\n if i != 1:\r\n temp.insert(0, 1)\r\n temp.append(1)\r\n result.append(temp)\r\n return result\r\n\r\nif __name__ == '__main__':\r\n sol = Solution()\r\n numRows = 15\r\n data = sol.generate(numRows)\r\n print(data)\r\n","sub_path":"pascals_triangle.py","file_name":"pascals_triangle.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"96450258","text":"import sys\nsys.path.insert(0, 'paper/')\nfrom learning_utils import viewed_matrix\nfrom learning_utils import filter_unseen_movies\nfrom aspect_importance import dict_movie_aspect\nfrom aspect_importance import users_movie_aspect_preferences\nfrom simple_similarity import sample_users\nfrom concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import cpu_count\nfrom scipy import spatial\nfrom paper import ids\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport pprint as pp\nimport time\n\nTHREADS = cpu_count() - 1\n\n\ndef map_similarity(x):\n\ta, b = x\n\tuser_id1, user_genre_prefs1 = a\n\tuser_id2, user_genre_prefs2 = b\n\tsim = (1 - spatial.distance.cosine(list(user_genre_prefs1.values()), list(user_genre_prefs2.values())))\n\treturn user_id1, user_id2, sim\n\n\ndef user_genre_similarity(users_genres_prefs):\n\tuser_genre_similarity_dict = dict()\n\tfor user in list(users_genres_prefs.keys()):\n\t\tuser_genre_similarity_dict[user] = dict()\n\n\tpairwise_user_profiles = []\n\n\titems = list(users_genres_prefs.items())\n\tfor idx1 in range(len(items)):\n\t\tfor idx2 in range(idx1+1, len(items)):\n\t\t\tpairwise_user_profiles.append((items[idx1], items[idx2]))\n\n\twith ProcessPoolExecutor(max_workers=THREADS) as executor:\n\t\tresults = executor.map(map_similarity, pairwise_user_profiles)\n\tfor user_id1, user_id2, sim in results:\n\t\tuser_genre_similarity_dict[user_id1][user_id2] = sim\n\t\tuser_genre_similarity_dict[user_id2][user_id1] = sim\n\n\treturn user_genre_similarity_dict\n\n\ndef user_prefs(movies_watched, movies_aspects, users, aspect_type, normalized, rating_to_like=False):\n\tmovies_aspects = filter_unseen_movies(movies_aspects, movies_watched)\n\tmovies_aspects = pd.DataFrame.from_dict(movies_aspects, dtype='int64', orient='index')\n\tmovies_aspects = movies_aspects.replace(np.nan, 0)\n\n\t# print (\"\\nMOVIES-ASPECTS %s %r\" % (aspect_type, rating_to_like))\n\t# print (movies_aspects.to_string())\n\n\tusers_aspects_prefs = users_movie_aspect_preferences(movies_aspects, movies_watched, users, normalized)\n\n\t# print (\"\\nUSER %s PREF RATING_TO_LIKE %r\" % (aspect_type, rating_to_like))\n\t# print (pd.DataFrame.from_dict(users_aspects_prefs, orient='index').to_string())\n\n\t# file_name = \"preference_%s_%r.pkl\" % (aspect_type, rating_to_like)\n\t# afile = open(file_name, \"wb\")\n\t# pickle.dump(users_aspects_prefs, afile)\n\t# afile.close()\n\n\treturn users_aspects_prefs\n\n\ndef user_sim(users_genres_prefs, rating_to_like=False):\n\tuser_genre_similarity_dict = user_genre_similarity(users_genres_prefs)\n\n\t# print (\"\\nSIMILARITY USER GENRE PREF RATING_TO_LIKE %r\" % rating_to_like)\n\t# print (pd.DataFrame.from_dict(user_genre_similarity_dict).to_string())\n\n\t# file_name = \"similarity_%r.pkl\" % rating_to_like\n\t# afile = open(file_name, \"wb\")\n\t# pickle.dump(user_genre_similarity_dict, afile)\n\t# afile.close()\n\n\nif __name__ == \"__main__\":\n\tstart = time.time()\n\tpaper_ratings = pickle.load(open(\"db/paper_ratings.pkl\", \"rb\"))\n\tpaper_films = pickle.load(open(\"db/paper_films.pkl\",\"rb\"))\n\tmovies_watched = viewed_matrix(paper_ratings, paper_films, sample_users)\n\n\t# print (\"\\nFILMS \\n%s\\n\" % paper_films)\n\t# print (\"\\nFILMS WATCHED BY USERS RATING_TO_LIKE %r \\n%s\\n\" % (False, movies_watched))\n\n\tnormalized = True\n\n\tmovies_actors = dict_movie_aspect(paper_films, \"actors\")\n\tusers_actors_prefs = user_prefs(movies_watched, movies_actors, sample_users, \"actors\", normalized)\n\n\tmovies_directors = dict_movie_aspect(paper_films, \"director\")\n\tusers_diretors_prefs = user_prefs(movies_watched, movies_directors, sample_users, \"director\", normalized)\n\n\tmovies_genres = dict_movie_aspect(paper_films, \"genre\")\n\tusers_genres_prefs = user_prefs(movies_watched, movies_genres, sample_users, \"genre\", normalized)\n\n\n\n\tuser_sim(users_genres_prefs)\n\n\tend = time.time()\n\tprint (end - start)\n\n","sub_path":"learning/synthetic_learning.py","file_name":"synthetic_learning.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"561904231","text":"import praw\nimport urllib2\nimport re\n\nfrom bs4 import BeautifulSoup\n\ndef check_website(url):\n\tresponse = urllib2.urlopen(\"http://dota2lounge.com/\").getcode()\n\tif response == 200:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef check_availability(match):\n\tif \"notaviable\" in match.get(\"class\"):\n\t\treturn False\n\telse:\n\t\treturn True\n\nuser_agent = \"/r/Dota2LoungeBets Match Poster\"\nbot = praw.Reddit(user_agent=user_agent)\n\nwebsiteStatus = check_website(\"http://dota2lounge.com/\")\nif websiteStatus == True:\n\tpage = urllib2.urlopen(\"http://dota2lounge.com/\")\n\tsoup = BeautifulSoup(page)\n\n\tbets = soup.find(\"article\", {\"id\": \"bets\"})\n\tmatchlist = bets.find_all(\"div\", {\"class\": \"match\"})\n\tfor match in matchlist:\n\t\tmatchlink = match.find_all(\"a\", href=True)\n\t\tfor link in matchlink:\n\t\t\tmatchstring = link.get(\"href\")\n\t\tmatchid = map(int, re.findall(\"\\d+\", matchstring))\n\t\tprint(matchid[0])\n\n\t\tteams = match.find_all(\"div\", {\"class\": \"teamtext\"})\n\t\tteam1Name = teams[0].b.encode_contents()\n\t\tteam1Percent = teams[0].i.encode_contents()\n\t\tteam2Name = teams[1].b.encode_contents()\n\t\tteam2Percent = teams[1].i.encode_contents()\n\t\tavailable = check_availability(match)\n\n\t\t#Test to see if the names actually work\n\t\tif available == False:\n\t\t\tavailability = \"CLOSED\"\n\t\telse:\n\t\t\tavailability = \"OPEN\"\n\t\tprint(team1Name + \" (\" + team1Percent + \") vs \" + team2Name + \" (\" + team2Percent + \") - \" + availability)\nelse:\n\tprint(\"Website is busy or an error has occured.\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"272189301","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom API.models import *\n\n# Create your tests here.\nclass NewMachineTests(APITestCase):\n def setUp(self):\n self.m1 = Machine.objects.create(description=\"\")\n self.m1.save()\n\n def test_new_machine(self):\n url = reverse('newhost')\n response = self.client.get(url)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['id'], 2)\n # self.assertEqual(Machine.objects.get(pk=response.data['id']).description, \"\")\n\n def test_new_machine_desc(self):\n desc = \"This is an infected machine\"\n url = '{0}?desc={1}'.format(reverse('newhost'), desc)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['id'], 2)\n # self.assertEqual(Machine.objects.get(pk=response.data['id']).description, desc)\n","sub_path":"django/SePr/SePr/API/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"573478140","text":"import random\n\nfrom enum import Enum\n\n\n# Texts\ntitle = 'Игра: Компьютер угадает загаданное число'\ncontrol_hint = '[1 - меньше | 2 - верно | 3 - больше] : '\nreplies_wrong = ('Да ну!', 'Аргх..', 'Вотжешь', 'Даже так?')\nreply_correct = 'Круть!'\nright_border_message = 'Задайте диапазон: от 1 до '\n\n\n# Utility\nclass Control(Enum):\n LESS = '1'\n EQUAL = '2'\n MORE = '3'\n\n\ndef print_wrong_reply():\n number = random.randint(0, len(replies_wrong) - 1)\n print(replies_wrong[number])\n\n\ncontrols = {control.value: control for control in Control}\nis_ready = True\n\n# Game\nprint(title)\nprint()\n\nwhile is_ready:\n left_border, right_border = 1, int(input(right_border_message))\n\n attempt = 0\n\n while not left_border > right_border:\n attempt += 1\n predicted_number = random.randint(left_border, right_border)\n\n print(f'Попытка {attempt}. Было загадано {predicted_number}?')\n\n try:\n user_answer = controls[input(control_hint)]\n except IndexError:\n user_answer = None\n\n if user_answer is Control.EQUAL:\n print(reply_correct)\n break\n\n elif user_answer is Control.LESS:\n right_border = predicted_number - 1\n print_wrong_reply()\n\n elif user_answer is Control.MORE:\n left_border = predicted_number + 1\n print_wrong_reply()\n\n print()\n\n else:\n print(f'Вы верно врёте! Число больше {left_border} и {right_border}?!')\n print('Поражение!')\n\n print()\n is_ready = bool(int(input('Есчо? [1 - ага, 0 - не-а] : ')))\n print()\n\nprint('Пока-пока!')\n\n","sub_path":"lesson_6/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"305181519","text":"# !/usr/bin/env python\n# -*-coding: utf-8-*-\n\n# @ProjectName : jiling_aqjr_proj\n# @FileName : basicdata_set.py\n# @Time : 2019/11/7 10:12\n# @Author : Nick\n\n\"\"\"\n目的:使用单例模式管理配置文件的读取,确保配置文件信息调用时,因为只初始化一次,还可以加快运行性能,保证程序在多处地方获取的配置信息一致\n\"\"\"\n\nimport random\nimport time\nimport collections\nimport configparser\nimport os.path\nfrom src.aqjr import log_setting_gdca\n\n\"\"\"\npython中实现单例模式最简单的两种方法:\n一、通过模块调用\n在python3中,首次导入模块文件时,会在程序目录下的__pycache__目录中生成pyc文件,\n再导入时,将直接加载pyc文件。因此,只需把相关的函数和数据定义在一个模块��,就可以获得一个单例对象了。 \n\n# 读取配置文件中关于java和jar的配置项\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\n# 本机java虚拟机路径及运行参数\njvm_path = config.get('Java', \"Java_path\")\njar_path = config.get('Java', \"jar_path\")\n\n# 接口URL前缀\nsell_profix_url = config.get('Url_set', 'sell_profix')\ntime_sync_profix_url = config.get('Url_set', 'time_sync_profix')\nencash_profix_url = config.get('Url_set', 'encash_profix')\nbet_query_url = config.get('Url_set', 'bet_query_profix')\naccount_query_url = config.get('Url_set', 'account_query_profix')\nlogin_profix_url = config.get('Url_set', 'login_profix')\n\n\n# 登录、投注、兑奖3个接口使用\ngdca_key = config.get('Key', 'gdca_key')\n# 3个查询接口使用(时间同步、自购投注查询、站点余额)\nold_key = config.get('Key', 'old_key')\n\n\n# 投注商ID,用命名元组管理多个渠道商\nchannel = collections.namedtuple(\"Channel\", 'First,Second,Three')\nchannel_id = channel._make([config.get('Channel', 'first'), config.get('Channel', 'second'), config.get('Channel', 'third')])\n\n# 自助终端的编号\nuserid = config.get('Basic_infor', 'userid')\n# 渠道ID\npartner_id = config.get('Basic_infor', 'partner_id')\n# 版本\nversion = config.get('Basic_infor', 'version')\n\ndef serial_num_gen():\n # 生成15位随机列号\n return str(random.randrange(1, 9999)) + str(random.randrange(1, 9999)) + str(random.randrange(1, 9999))\n\ndef current_time():\n # 生成当前时间时间戳\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n二、使用__new__方法\n\n __new__:创建实例对象时调用的构造方法\n __init__ :实例初始化方法,用于设置实例的相关属性\n\n当实例化一个对象时,先调用__new__方法(未定义时调用object.__new__)实例化对象,然后调用__init__方法进行对象初始化。\n所以,可以声明一个私有类变量__instance。当__instance不为None时,表示系统中已有实例,直接返回该实例;若__instance为None时,\n表示系统中还没有该类的实例,则创建新实例并返回。\n\n\"\"\"\n\n\nclass Dataset(object):\n __instance = None\n\n def __init__(self):\n # 读取配置文件中关于java和jar的配置项\n config = configparser.ConfigParser()\n config.read('config.ini')\n\n # 初始化日志调用\n self.log_level = config.get('Default', \"loglevel\")\n self.log_dir = config.get('Default', \"logfile\")\n self.logger = log_setting_gdca.log_setting()\n\n # 初始化销售过程中产生的文件存放的目录\n result_dir = config.get('Default', \"resultdir\")\n if not os.path.exists(result_dir):\n os.mkdir(r'%s' % result_dir)\n self.result_dir = result_dir + '\\\\'\n\n # 初始化销售过程中产生的文件存放的目录\n datadir = config.get('Default', \"datadir\")\n if not os.path.exists(datadir):\n os.mkdir(r'%s' % datadir)\n self.datadir = datadir + '\\\\'\n\n # 接口URL前缀\n self.sell_profix_url = config.get('Url_set', 'sell_profix')\n self.time_sync_profix_url = config.get('Url_set', 'time_sync_profix')\n self.encash_profix_url = config.get('Url_set', 'encash_profix')\n self.bet_query_url = config.get('Url_set', 'bet_query_profix')\n self.account_query_url = config.get('Url_set', 'account_query_profix')\n self.login_profix_url = config.get('Url_set', 'login_profix')\n\n # 登录、投注、兑奖3个接口使用\n self.gdca_key = config.get('Key', 'gdca_key')\n # 3个查询接口使用(时间同步、自购投注查询、站点余额)\n self.old_key = config.get('Key', 'old_key')\n\n # 投注商ID,用命名元组管理多个渠道商\n channel = collections.namedtuple(\"Channel\", 'First,Second,Three')\n self.channel_id = channel._make(\n [config.get('Channel', 'first'), config.get('Channel', 'second'), config.get('Channel', 'third')])\n\n # 自助终端的编号\n self.userid = config.get('Basic_infor', 'userid')\n # 渠道ID\n self.partner_id = config.get('Basic_infor', 'partner_id')\n # 版本\n self.version = config.get('Basic_infor', 'version')\n # 登录密码\n self.login_pass = config.get('Basic_infor', 'loginpass')\n # 登录类型\n self.login_type = config.get('Basic_infor', 'logintype')\n # MAC地址\n self.mac_address = config.get('Basic_infor', 'macaddress')\n\n @staticmethod\n def serial_num_gen():\n # 生成15位随机列号\n return str(random.randrange(1, 9999)) + str(random.randrange(1, 9999)) + str(random.randrange(1, 9999))\n\n @staticmethod\n def current_time():\n # 生成当前时间时间戳\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n def __new__(cls):\n if not cls.__instance:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n\nbasic_data = Dataset()\n\n# 单例模式验证\n# basic_data1 = Dataset()\n# print(id(basic_data), id(basic_data1))\n","sub_path":"sdgen/basicdata_set.py","file_name":"basicdata_set.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"162274503","text":"from django.urls import path\nfrom . import views\n\n# Me sirve para llamar a las URLS en el HTML\napp_name = \"crear_pacientes\"\n\nurlpatterns = [\n path('', views.crear_pacientes, name='crear_pacientes'),\n path('listar_pacientes', views.listar_pacientes, name='listar_pacientes'),\n path('perfil_paciente', views.perfil_paciente, name='perfil_paciente'),\n path('/eliminar_paciente', views.eliminar_paciente, name='eliminar_paciente'),\n path('/actualizar_paciente', views.editar_paciente , name='actualizar_paciente'),\n]","sub_path":"Modulo6/Django-psql_07/Evaluacion_Medica/crear_pacientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"286958861","text":"students = [['Harsh', 20], ['Beria', 20], [\n 'Varun', 19], ['Kakunami', 19], ['Vikas', 21]]\n\nnumbers = []\nfor student in students:\n numbers.append(student[1])\n\nunique = []\nfor i in sorted(numbers):\n if i not in unique:\n unique.append(i)\n\nfor name, marks in sorted(students):\n if marks == unique[1]:\n print(name)\n\n# second_lowest_mark = sorted(list(dict.fromkeys(numbers)))\n# print(second_lowest_mark)\n","sub_path":"python Problem Solve/nasted.py","file_name":"nasted.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"556217963","text":"import requests\nimport os\nimport json\nfrom pprint import pprint\n\ntoken = os.getenv('GITHUB_TOKEN', '...')\n\ndef readConfigJson():\n\t# JSON file\n\tf = open ('teams.json', \"r\")\n\t\n\t# Reading from file\n\tdata = json.loads(f.read())\n\t\n\t# Closing file\n\tf.close()\n\treturn data\n\t\ndef getReposFromProject():\n\treturn node\n\ndef getTeamMembers(team_slug):\n\tprint(\"getTeamMember method\")\n\tmemberlist = []\n\tquery_url = \"https://api.github.com/orgs/newrelic/teams\"\n\tparams = {\n\t\t\"per_page\": 200,\n\t}\n\n\theaders = {'Authorization': f'token {token}'}\n\tr = requests.get(query_url, headers=headers, params=params)\n\tprint(r)\n\tfor i in r.json():\n\t\tif i['slug'] == team_slug:\n\t\t\tquery_url = i['members_url'].replace('{/member}','')\n\t\t\tteammembers = requests.get(query_url, headers=headers, params=params)\n\t\t\tfor m in teammembers.json():\n\t\t\t\tprint(m['login'])\n\t\t\t\tmemberlist.append(m['login'])\n\treturn memberlist\n\n\ndef getBugCounts(repos):\n\topenBugCount = 0\n\tprint(\"Gathering Unreviewed Bug Counts\")\n\tfor repo in repos:\n\t\tquery_url = f\"https://api.github.com/repos/newrelic/{repo}/issues\"\n\t\tparams = {\n\t\t\t\"status\": \"open\",\n\t\t\t\"labels\": \"bug\",\n\t\t\t\"labels\": \"needs-triage\",\n\t\t}\n\t\theaders = {'Authorization': f'token {token}'}\n\t\tr = requests.get(query_url, headers=headers, params=params)\n\t\topenBugCount += len(r.json())\n\tprint(\"Open Bugs: \", openBugCount)\n\ndef getExternalPRCounts(repos,teammembers):\n\tprint(\"Gathering Open External PR Counts\")\n\tprcount = 0\n\tfor repo in repos:\n\n\t\tquery_url = f\"https://api.github.com/repos/newrelic/{repo}/pulls\"\n\t\tparams = {\n\t\t\t\"state\": \"open\",\n\t\t}\n\t\theaders = {'Authorization': f'token {token}'}\n\t\tr = requests.get(query_url, headers=headers, params=params)\n\t\t#this has all pull requests. need to filter out ones where the author is on the team\n\t\tprs = r.json()\n\t\tfor pr in prs:\n\t\t\tif pr['user']['login'] not in teammembers :\n\t\t\t\tprint(' found external pr from:', pr['user']['login'])\n\t\t\t\tprcount += 1\n\t\t\telse:\n\t\t\t\tprint(' found pr for a team member: ', pr['user']['login'])\n\tprint(\"Open External PRs: \", prcount)\n\nteams = readConfigJson()\nfor team in teams['team']:\n\tprint(team['name'].upper())\n\tgetBugCounts(team['repos'])\n\tgetExternalPRCounts(team['repos'], getTeamMembers(team['team-slug']))\n\tprint()\t\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"378255006","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\nimport json\nimport requests\nimport smtplib\nimport time\nimport os\nimport logging\nfrom email.mime.text import MIMEText\n\nlogging.basicConfig(format=\"%(asctime)s - %(levelname)s - %(message)s\",filename=\"alert.log\", level=logging.DEBUG)\n\nURL=\"http://stat.kbu.freifunk.net/nodes.json\"\nFROM='ffkbumon@gokk.de'\nWATCHLISTFILE = \"watchlist.json\"\nDOWNLISTFILE = \"downlist.json\"\n\nwatchlist = dict()\ndownlist = dict()\n\ndef loadDownList():\n\tglobal downlist\n\tif os.path.exists(DOWNLISTFILE):\n\t\twith open(DOWNLISTFILE, 'r') as f:\n\t\t\tdownlist = json.load(f)\n\t\tf.closed\n\telse:\n\t\tlogging.warning(DOWNLISTFILE+\" nicht gefunden. Wird bei bedarf erstellt.\")\n\ndef writeDownList():\n\twith open(DOWNLISTFILE, 'w') as f:\n\t\tjson.dump(downlist, f)\n\tf.closed\t\t\n\ndef loadWatchList():\n\tglobal watchlist\n\tif os.path.exists(WATCHLISTFILE):\n\t\twith open(WATCHLISTFILE, 'r') as f:\n\t\t\twatchlist = json.load(f)\n\t\tf.closed\n\telse:\n\t\tlogging.error(WATCHLISTFILE+\" nicht gefunden. Beende.\")\n\t\texit()\t\n\ndef getStatData():\n\tr = requests.get(URL)\n\tif r.status_code != 200:\n\t\tlogging.warning(\"Konnte nodes.json nicht laden. (\"+int(time.time())+\")\")\n\t\treturn dict()\n\treturn json.loads(r.text)\n\t\ndef sendMail(nodeID, recipent, upDown):\n\tif upDown == \"down\":\n\t\tmsg = MIMEText(\"Dein Node \"+nodeID+\" ist nicht mehr Erreichbar!\\nPANIK!\\n\")\n\telse:\n\t\tmsg = MIMEText(\"Dein Node \"+nodeID+\" ist wieder Erreichbar.\\n\")\n\tmsg['Subject'] = \"Monitoring \"+nodeID\n\tmsg['From'] = FROM\n\tmsg['To'] = recipent\n\t\n\ts = smtplib.SMTP('localhost')\n\ts.sendmail(FROM, [recipent], msg.as_string())\n\ts.quit()\n\ndef checkNodes():\n\tstatData = getStatData()\n\t#optimalerweise hex:{loss:[val], ping:[val]}\n\tfor id in statData:\n\t\tif statData[id]['id_hex'] in watchlist:\n\t\t\tnode = statData[id]\n\t\t\tid_hex = node['id_hex']\n\t\t\tif node['loss_5_min'] == 1.0:\n\t\t\t\tif id_hex not in downlist:\n\t\t\t\t\tsendMail(id_hex, watchlist[id_hex], \"down\")\n\t\t\t\t\tdownlist[id_hex] = int(time.time())\n\t\t\t\t\tlogging.info(id_hex+\" went down at \"+str(int(time.time())))\n\t\t\telif id_hex in downlist:\n\t\t\t\tdel downlist[id_hex]\n\t\t\t\tsendMail(id_hex, watchlist[id_hex], \"up\")\n\t\t\t\tlogging.info(id_hex+\" got up again at \"+str(int(time.time())))\n\t\t\t\nloadDownList()\nloadWatchList()\ncheckNodes()\nwriteDownList()\n","sub_path":"ffNodeMon.py","file_name":"ffNodeMon.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"5478855","text":"Data = [int(x) for x in list(open(\"input.txt\").read().split(\" \"))]\n\nmetas = []\n\ndef recurNodes(index, metas):\n\n if Data[index] == 0:\n for i in range(index+2, index+2+Data[index+1]):\n metas.append(Data[i])\n return Data[index+1] + 2 # vraca duljinu zapisa s 0 djece\n \n offset = 0\n for i in range(Data[index]):\n offset += recurNodes(index + offset+2, metas)[0]\n\n for i in range(Data[index+1]):\n metas.append(Data[index+2+offset+i])\n\n return offset+2+Data[index+1]\n\n\nrecurNodes(0, metas)\n\nsum = 0\nfor meta in metas:\n sum += meta\nprint(sum)","sub_path":"AOC18/D8/run1.py","file_name":"run1.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"105447725","text":"import random\r\nimport sqlite3\r\n\r\ngenamenator_db = sqlite3.connect('GeNamenator_DB.db')\r\ncursor = genamenator_db.cursor()\r\ncursor.row_factory = lambda cursor, row: row[0]\r\n\r\nname_starts = (\"A\", \"B\", \"Ba\", \"Be\", \"Bi\", \"Bo\", \"Bu\", \"By\", \"C\", \"Ca\", \"Ce\", \"Ci\", \"Co\", \"Cu\", \"Ch\", \"Chr\", \"D\", \"Da\", \"De\", \"Di\", \"Do\", \"Du\",\r\n \"E\", \"F\", \"Fa\", \"Fe\", \"Fi\", \"Fo\", \"Fu\", \"G\", \"Ga\", \"Ge\", \"Gi\", \"Go\", \"Gu\", \"Gl\", \"Gr\", \"H\", \"Ha\", \"He\", \"Hi\", \"Ho\", \"Hu\",\r\n \"I\", \"J\", \"Ja\", \"Je\", \"Ji\", \"Jo\", \"Ju\", \"K\", \"Ka\", \"Ke\", \"Ki\", \"Ko\", \"Ku\", \"M\", \"Ma\", \"Me\", \"Mi\", \"Mo\", \"Mu\", \"N\", \"Na\", \"Ne\", \"Ni\" ,\"No\", \"Nu\",\r\n \"O\", \"P\", \"Pa\", \"Pe\", \"Pi\", \"Po\", \"Pi\", \"Ph\", \"Q\", \"R\", \"Ra\", \"Re\", \"Ri\", \"Ro\", \"Ru\", \"S\", \"Sa\", \"Se\", \"Si\", \"So\", \"Su, \"\r\n \"Sh\", \"Sha\", \"She\", \"Shi\", \"Sho\", \"Shu\", \"St\", \"Sta\", \"Ste\", \"Sti\", \"Sto\", \"Stu\", \"T\", \"Ta\", \"Te\", \"Ti\", \"To\", \"Tu\",\r\n \"Th\", \"Tha\", \"The\", \"Thi\", \"Tho\", \"Thu\", \"U\", \"V\", \"W\", \"Wa\", \"We\", \"Wi\", \"Wo\", \"Wu\", \"X\", \"Y\", \"Z\")\r\n\r\nprint(\"GeNamenator, version 1.4\")\r\nprint(\"by David Margis, 2020\")\r\nprint()\r\n\r\n\r\ndef main():\r\n main_choice = input(\"GeNamenator Main Menu \\n\"\r\n \" \\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Generate a completely random name \\n\"\r\n \" (2) Generate a random alliterative name \\n\"\r\n \" (3) Generate a female or male name \\n\"\r\n \" (4) Generate a female or male alliterative name \\n\"\r\n \" (5) Access the database management menu \\n\"\r\n \" (6) Exit GeNamenator \\n\"\r\n \" \")\r\n if main_choice == \"1\":\r\n random_name()\r\n elif main_choice == \"2\":\r\n random_name_alit()\r\n elif main_choice == \"3\":\r\n mf_name()\r\n elif main_choice == \"4\":\r\n mf_name_alit()\r\n elif main_choice == \"5\":\r\n dbm_menu()\r\n elif main_choice == \"6\":\r\n print(\"Thank you for using GeNamenator, the name-generating software with a name!\")\r\n raise SystemExit\r\n\r\n\r\n# NAME GENERATION FUNCTIONS\r\n\r\ndef random_name():\r\n random_choice = random.randrange(1, 4)\r\n if random_choice == 1:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice ==2:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice ==3:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n elif random_choice == 4:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES'\")\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name)\r\n\r\n\r\ndef random_name_alit():\r\n while True:\r\n random_choice = random.randrange(1, 4)\r\n alitter = input(\"What letter or letters do you want your names to start with? Enter * for random. \")\r\n if alitter == \"*\":\r\n end_string = random.choice(name_starts) + \"%\"\r\n else:\r\n end_string = alitter.upper() + \"%\"\r\n if random_choice == 1:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice ==2:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES'AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice ==3:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 4:\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?)\", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(random_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n\r\n\r\ndef mf_name():\r\n while True:\r\n mf_choice = input(\"Would you like a female or male name? (F)emale / (M)ale \")\r\n if mf_choice.lower() == \"f\":\r\n cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FEMALE=\"YES\" ''')\r\n fn_list_pull = cursor.fetchall()\r\n break\r\n elif mf_choice.lower() == \"m\":\r\n cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE MALE=\"YES\" ''')\r\n fn_list_pull = cursor.fetchall()\r\n break\r\n else:\r\n print(\"Please enter 'F' or 'M'!\")\r\n while True:\r\n mn_choice = input(\"Would you like a middle name? Y / N \")\r\n if mn_choice.lower() == \"y\":\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name)\r\n elif mn_choice.lower() == \"n\":\r\n cursor.execute(''' SELECT LAST_NAME FROM last_names ''')\r\n ln_list_pull = cursor.fetchall()\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name)\r\n else:\r\n print(\"Please enter 'Y' or 'N'!\")\r\n\r\n\r\ndef mf_name_alit():\r\n random_choice = random.randrange(1, 2)\r\n while True:\r\n mf_choice = input(\"Would you like a random female or male alliterative name? F / M \")\r\n if mf_choice.lower() == \"f\" or mf_choice.lower() == \"m\":\r\n break\r\n else:\r\n print(\"Please enter 'F' or 'M'!\")\r\n while True:\r\n alitter = input(\"What letter or letters do you want your names to start with? Enter * for random. \")\r\n if alitter == \"*\":\r\n end_string = random.choice(name_starts) + \"%\"\r\n else:\r\n end_string = alitter.upper() + \"%\"\r\n if random_choice == 1 and mf_choice.lower() == \"f\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 2 and mf_choice.lower() == \"f\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE FEMALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 1 and mf_choice.lower() == \"m\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n elif random_choice == 2 and mf_choice.lower() == \"m\":\r\n cursor.execute(\" SELECT FIRST_NAME FROM first_names WHERE MALE='YES' AND FIRST_NAME LIKE (?)\", (end_string,))\r\n fn_list_pull = cursor.fetchall()\r\n cursor.execute(\" SELECT LAST_NAME FROM last_names WHERE LAST_NAME LIKE (?) \", (end_string,))\r\n ln_list_pull = cursor.fetchall()\r\n try:\r\n print(\r\n random.choice(fn_list_pull) + \" \" + random.choice(fn_list_pull) + \" \" + random.choice(ln_list_pull))\r\n create_another_in_func(mf_name_alit)\r\n except IndexError:\r\n print(\"No first/last name combinations beginning with that sequence exist.\")\r\n\r\n\r\n# ADDITIONAL FUNCTIONS\r\n\r\ndef create_another_in_func(func):\r\n while True:\r\n again = input(\" \\n\"\r\n \"Would you like to create another or return to the main menu? (C)reate Another / (M)ain Menu \")\r\n if again.lower() == \"c\":\r\n func()\r\n break\r\n elif again.lower() == \"m\":\r\n main()\r\n break\r\n else:\r\n print(\"Please enter 'C' to create another or 'M' to return to the main menu!\")\r\n\r\n\r\n# DATABASE FUNCTION\r\n\r\ndef dbm_menu():\r\n while True:\r\n choose = input(\"What would you like to acces? \\n\"\r\n \" (F)irst Names \\n\"\r\n \" (L)ast Names \\n\"\r\n \" (A)djectives \\n\"\r\n \" (N)ouns \\n\"\r\n \" (M)ain Menu \\n\"\r\n \" \")\r\n if choose.lower() == \"f\":\r\n fn_gename_funcs()\r\n elif choose.lower() == \"l\":\r\n ln_gename_funcs()\r\n elif choose.lower() == \"a\":\r\n adj_funcs()\r\n elif choose.lower() == \"n\":\r\n nouns_funcs()\r\n elif choose.lower() == \"m\":\r\n main()\r\n else:\r\n print(\"Please enter one of the above options.\")\r\n\r\ndef fn_insert_row():\r\n fn = input(\"What is the first name you want to enter? \")\r\n f_yn = input(\"Is this a female name? YES/NO \")\r\n m_yn = input(\"Is this a male name? YES/NO \")\r\n dup = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?)''', (fn,))\r\n x = dup.fetchall()\r\n if x == []: # checks if number of matching names blank, or, an empty list\r\n cursor.execute(''' INSERT INTO first_names (FIRST_NAME, FEMALE, MALE) \r\n VALUES((?), (?), (?))''', (fn, f_yn, m_yn))\r\n genamenator_db.commit()\r\n print(fn + \" has been added!\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef ln_insert_row():\r\n ln = input(\"What is the surname you would like to enter? \")\r\n com = input(\"How common is this surname? COMMON / LESS COMMON / RARE \")\r\n dup = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?)''', (ln,))\r\n x = dup.fetchall()\r\n if x == []:\r\n cursor.execute(''' INSERT INTO last_names (LAST_NAME, COMMONALITY) VALUES((?), (?))''', (ln, com))\r\n genamenator_db.commit()\r\n print(ln + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef adj_insert_row():\r\n adj = input(\"What adjective would you like to enter? \")\r\n dup = cursor.execute(''' SELECT ADJECTIVE FROM adjectives WHERE ADJECTIVE=(?)''', (adj,))\r\n x = dup.fetchall()\r\n if x== []:\r\n cursor.execute(''' INSERT INTO adjectives (ADJECTIVE) VALUES(?) ''', (adj,))\r\n genamenator_db.commit()\r\n print(adj + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef noun_insert_row():\r\n noun = input(\"What noun would you like to enter? \")\r\n type = input(\"Is this classified as an occupation, or does it describe their personality? OCCUPATION / PERSONALITY \")\r\n dup = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (noun,))\r\n x = dup.fetchall()\r\n if x == []:\r\n cursor.execute(''' INSERT INTO nouns (NOUN, TYPE) VALUES(?, ?)''', (noun, type))\r\n genamenator_db.commit()\r\n print(noun + \" has been added.\")\r\n else:\r\n print(\"That name already exists.\")\r\n\r\n\r\ndef fn_check_for_name():\r\n x = input(\"What name are you checking for? \")\r\n data = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef ln_check_for_name():\r\n x = input(\"What name are you checking for? \")\r\n data = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef check_for_adj():\r\n x = input(\"What adjective are you searching for? \")\r\n data = cursor.execute(''' SELECT ADJECTIVE FROM adjectives WHERE ADJECTIVE=(?) ''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef check_for_noun():\r\n x = input(\"What noun are you searching for? \")\r\n data = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (x,))\r\n y = data.fetchall()\r\n if y == []:\r\n print(\"There is no %s!\" % (x,))\r\n else:\r\n print(\"%s does exist!\" % (x,))\r\n\r\n\r\ndef update_mf(): # changes the male/female columns from yes to no and vice versa\r\n while True:\r\n x = input(\"Which name do you want to update? \")\r\n y = input(\"Do you want to update FEMALE or MALE? \")\r\n if y == \"FEMALE\":\r\n y_yn = input(\"Do you want FEMALE to be YES or NO? \" )\r\n cursor.execute(''' UPDATE first_names SET FEMALE=(?) WHERE FIRST_NAME=(?) ''', (y_yn, x))\r\n genamenator_db.commit()\r\n break\r\n elif y == \"MALE\":\r\n m_yn = input(\"Do you want MALE to be YES or NO?\" )\r\n cursor.execute(''' UPDATE first_names SET MALE=(?) WHERE FIRST_NAME=(?)''', (m_yn, x))\r\n genamenator_db.commit()\r\n break\r\n else:\r\n print(\"Please enter your option as YES or NO.\")\r\n\r\n\r\ndef update_commonality():\r\n while True:\r\n x = input(\"Which surname would you like to update the commonality of? \")\r\n find = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist. Please try another name.\")\r\n else:\r\n while True:\r\n z = input(\"How common is this surname? COMMON / LESS COMMON / RARE \")\r\n if z == \"COMMON\" or \"LESS COMMON\" or \"RARE\":\r\n cursor.execute(''' UPDATE last_names SET COMMONALITY=(?) WHERE LAST_NAME=(?)''', (z, x,))\r\n genamenator_db.commit()\r\n print(x + \"has been updated.\")\r\n break\r\n else:\r\n print(\"Please enter your option in the form of COMMON, LESS COMMON, or RARE\")\r\n\r\n\r\ndef update_type():\r\n while True:\r\n x = input(\"Which noun would you like to update the type of? \")\r\n find = cursor.execute(''' SELECT NOUN FROM nouns WHERE NOUN=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That noun does not exist. Please try another noun.\")\r\n break\r\n else:\r\n while True:\r\n z = input(\"What type of noun is it? OCCUPTION / PERSONALITY \")\r\n if z == \"OCCUPATION\" or \"PERSONALITY\":\r\n cursor.execute(''' UPDATE nouns TYPE SET TYPE=(?) WHERE NOUN=(?)''', (z, x,))\r\n break\r\n else:\r\n print(\"Please enter your option in the form of OCCUPATION or PERSONALITY.\")\r\n\r\n\r\ndef fn_delete_name():\r\n x = input(\"What name would you like to delete? \")\r\n find = cursor.execute(''' SELECT FIRST_NAME FROM first_names WHERE FIRST_NAME=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist.\")\r\n else:\r\n cursor.execute(''' DELETE from first_names WHERE FIRST_NAME=(?) ''', (x,))\r\n genamenator_db.commit()\r\n print(\"%s has been deleted.\" % x)\r\n\r\n\r\ndef ln_delete_name():\r\n x = input(\"What surname would you like to delete? \")\r\n find = cursor.execute(''' SELECT LAST_NAME FROM last_names WHERE LAST_NAME=(?)''', (x,))\r\n y = find.fetchall()\r\n if y == []:\r\n print(\"That name does not exist.\")\r\n else:\r\n cursor.execute(''' DELETE FROM last_names WHERE LAST_NAME=(?) ''', (x,))\r\n genamenator_db.commit()\r\n print(\"%s has been deleted.\" % x)\r\n\r\n\r\ndef delete_adj():\r\n x = input(\"What adjective would you like to delete? \")\r\n cursor.execute(''' DELETE FROM adjectives WHERE ADJECTIVE=(?)''', (x,))\r\n genamenator_db.commit()\r\n\r\n\r\ndef delete_noun():\r\n x = input(\"What noun would you like to delete? \")\r\n cursor.execute(''' DELETE FROM nouns WHERE NOUN=(?)''', (x,))\r\n genamenator_db.commit()\r\n\r\n\r\ndef fn_gename_funcs():\r\n while True:\r\n func_cho = input(\"\\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Check if a name exists \\n\"\r\n \" (2) Add a new name \\n\"\r\n \" (3) Delete a name \\n\"\r\n \" (4) Update the associated genders of a name \\n\"\r\n \" \")\r\n if func_cho == '1':\r\n fn_check_for_name()\r\n elif func_cho == '2':\r\n fn_insert_row()\r\n elif func_cho == '3':\r\n fn_delete_name()\r\n elif func_cho == '4':\r\n update_mf()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef ln_gename_funcs():\r\n while True:\r\n func_cho = input(\"\\n\"\r\n \"What would you like to do? \\n\"\r\n \" (1) Check if a surname exists \\n\"\r\n \" (2) Add a new surname \\n\"\r\n \" (3) Delete a surname \\n\"\r\n \" (4) Updated the commonality of a surname \\n\")\r\n if func_cho == \"1\":\r\n ln_check_for_name()\r\n elif func_cho == \"2\":\r\n ln_insert_row()\r\n elif func_cho == \"3\":\r\n ln_delete_name()\r\n elif func_cho == \"4\":\r\n update_commonality()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef adj_funcs():\r\n while True:\r\n func_cho = input(\"What would you like to do? \\n\"\r\n \" (1) Check if an adjective exists \\n\"\r\n \" (2) Insert a new adjective \\n\"\r\n \" (3) Delete an adjective \")\r\n if func_cho == \"1\":\r\n check_for_adj()\r\n elif func_cho == \"2\":\r\n adj_insert_row()\r\n elif func_cho == \"3\":\r\n delete_adj()\r\n else:\r\n print(\"Please choose an option.\")\r\n\r\n\r\ndef nouns_funcs():\r\n while True:\r\n func_cho = input(\"What would you like to do? \\n\"\r\n \" (1) Check if an noun exists \\n\"\r\n \" (2) Insert a new noun \\n\"\r\n \" (3) Delete an adjective \\n\"\r\n \" (4) Change the type of noun \")\r\n if func_cho == \"1\":\r\n check_for_noun()\r\n if func_cho == \"2\":\r\n noun_insert_row()\r\n if func_cho == \"3\":\r\n delete_noun()\r\n if func_cho == \"4\":\r\n update_type()\r\n\r\nmain()","sub_path":"GeNamenator_v1_4.py","file_name":"GeNamenator_v1_4.py","file_ext":"py","file_size_in_byte":22384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"327228984","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom collections import defaultdict, Counter\nimport os\nimport sys\nsys.path.append(\"..\")\nfrom datetime import date\nimport pickle\nfrom article_utils import *\nfrom econ_utils import *\nimport glob\nimport math\nimport itertools\n\n# Return number of country name words in timestep\n# Number of articles that mention 1 country\n# Number of articles that mention 2 countries\ndef count_mentions_in_articles(filenames, keywords):\n keyword_to_count = defaultdict(int)\n total_word_count = 0\n\n for filename in filenames:\n articles, _ = LoadArticles(filename, verbose=False)\n for article in articles:\n counter = Counter(article.lower().split())\n\n if counter[\"usa\"] < 2:\n continue\n\n total_word_count += sum([counter[q] for q in counter])\n for c in keywords:\n keyword_to_count[c] += counter[c]\n return keyword_to_count, total_word_count\n\ndef load_country_names(filename):\n names = []\n for line in open(filename).readlines():\n names.append(line.split(\",\")[0].strip().lower())\n return names\n\ndef do_counts(files_grouped_by_date, subs_file):\n keywords = load_country_names(subs_file)\n\n # number of articles that mention country (normalize by number of articles)\n keyword_to_summary = defaultdict(list)\n for filename in files_grouped_by_date:\n keyword_to_count, total_word_count = count_mentions_in_articles(filename, keywords)\n for k in keyword_to_count:\n keyword_to_summary[k].append(keyword_to_count[k] / total_word_count)\n return keyword_to_summary\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_path', help=\"Directory where data files are. Must include trailing backslash\", default=\"../data/Izvestiia_processed/\")\n parser.add_argument('--subs_file', help=\"File containing keywords to count\", default=\"../data/usa.txt\")\n parser.add_argument('--timestep', type=str, help=\"specify what time increment to use for aggregating articles\",\n default='monthly',\n choices=['monthly', 'quarterly', 'semi', 'yearly'])\n parser.add_argument(\"--econ_file\", help=\"If you specify this, output will include compute correlation of counts with econ series (does NOT work for yearly)\")\n args = parser.parse_args()\n\n date_seq, filenames = get_files_by_time_slice(args.input_path, args.timestep)\n keyword_to_summary = do_counts(filenames, args.subs_file)\n\n keyword_to_corr = {}\n econ_seq = load_econ_file(args.econ_file, args.timestep, date_seq)\n\n for k in keyword_to_summary:\n assert(len(keyword_to_summary[k]) == len(date_seq))\n\n keyword_to_corr[k] = get_corr(econ_seq, keyword_to_summary[k])\n\n for k in sorted(keyword_to_corr, key=keyword_to_corr.get):\n print(k, keyword_to_corr[k])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/frame_analysis/measure_corr_per_word.py","file_name":"measure_corr_per_word.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"467632681","text":"file_name = input('Enter a fie name:')\nfile_handle = open(file_name)\ndays = list()\ndays_count = dict()\nfor line in file_handle:\n if line.startswith('From '):\n line = line.strip()\n words = line.split()\n days.append(words[2])\nfor day in days:\n days_count[day] = days_count.get(day, 0) + 1\nprint(days_count)\n","sub_path":"ex_09_01.py","file_name":"ex_09_01.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"630575638","text":"# -*- coding:utf-8 -*-\nfrom app import app\nfrom flask import render_template,redirect,session,request,url_for,make_response\nfrom Form_table import login_admin\nimport Judge\nfrom params import params_dict\nimport os,datetime,random\n\n\n\n@app.route('/login/', methods=('GET', 'POST'))\ndef login():\n form = login_admin()\n state = 'username' in session\n if state:\n return redirect('/admin/')\n if form.validate_on_submit(): ##提交内容不为空则就是True\n user_judge = Judge.user(form.name.data,form.passwd.data) ##得到表单数据\n return user_judge.judge_user()\n else:\n return render_template('login.html',form=form,state=state,params_dict=params_dict)\n\n\n@app.route('/admin/')\n@app.route('/admin//', methods=('GET', 'POST'))\ndef admin_manage(url=None):\n state = 'username' in session\n if request.args.get('id'):param = int(request.args.get('id'))\n else:param=1\n if url == None:\n if state:\n return render_template('admin.html',params_dict=params_dict,state=state)\n return redirect('/login/')\n elif state:\n url_judge = Judge.admin_url(url,param)\n return url_judge.url_judge()\n return redirect('/login/')\n\n@app.route('/admin/category/')\n@app.route('/admin/category//', methods=('GET', 'POST'))\n@app.route('/admin/category///', methods=('GET', 'POST'))\ndef category(name=None,cate_id=None):\n state = 'username' in session\n if request.args.get('id'):param = int(request.args.get('id'))\n else:param=1\n if state:\n return Judge.cate_url(name,cate_id,param)\n else:\n return redirect('/login/')\n \n\n@app.route('/admin/post//', methods=('GET', 'POST'))\ndef admin_post(name=None):\n state = 'username' in session\n param = request.args.get('id')\n where = request.args.get('where')\n cate = request.args.get('cate')\n if state:\n return Judge.cate_post_url(name,param,where,cate)\n else:\n return redirect('/login/')\n\n@app.route('/post//')\ndef post(id):\n state = 'username' in session\n return Judge.post_id(id,state)\n\n@app.route('/category//')\ndef index_category(id):\n state = 'username' in session\n param = request.args.get('page')\n if param == None:param=1\n return Judge.category_id(state,id,param)\n\n@app.route('/')\ndef index():\n state = 'username' in session\n id = request.args.get('id')\n index_right = Judge.index_right(state)\n return index_right.index(id)\n \n@app.route('/logout/')\ndef logout():\n session.pop('username')\n return redirect('/login/')\n\n@app.errorhandler(404)\ndef page_not_found(error):\n return render_template('404.html',params_dict=params_dict),404\n\n\ndef gen_rnd_filename():\n filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))\n\n@app.route('/ckupload/', methods=['POST'])\ndef ckupload():\n \"\"\"CKEditor file upload\"\"\"\n error = ''\n url = ''\n callback = request.args.get(\"CKEditorFuncNum\")\n if request.method == 'POST' and 'upload' in request.files:\n fileobj = request.files['upload']\n fname, fext = os.path.splitext(fileobj.filename)\n rnd_name = '%s%s' % (gen_rnd_filename(), fext)\n filepath = os.path.join(app.static_folder, 'upload', rnd_name)\n # 检查路径是否存在,不存在则创建\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except:\n error = 'ERROR_CREATE_DIR'\n elif not os.access(dirname, os.W_OK):\n error = 'ERROR_DIR_NOT_WRITEABLE'\n if not error:\n fileobj.save(filepath)\n url = url_for('static', filename='%s/%s' % ('upload', rnd_name))\n else:\n error = 'post error'\n res = \"\"\"\n\n\n\n\"\"\" % (callback, url, error)\n response = make_response(res)\n response.headers[\"Content-Type\"] = \"text/html\"\n return response\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"468938287","text":"\n\nimport navmet\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse, Circle\nplt.style.use('fivethirtyeight')\n\n\ndef simple_example():\n # -- Objective metrics\n traj = np.loadtxt('sample_traj.txt')\n agents = np.loadtxt('sample_agents.txt')\n # robot = agents[0, :]\n persons = agents[1:, :]\n\n # --- Objective\n pl = navmet.path_length(traj)\n chc = navmet.chc(traj)\n print('Objective Metrics: Path length = {}, CHC = {}'.format(pl, chc))\n\n # plot their configuration\n plt.figure(figsize=(10, 10))\n ax = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)\n\n for n in agents:\n theta = np.degrees(np.arctan2(n[3], n[2]))\n ax.add_artist(Ellipse((n[0], n[1]), width=0.3, height=0.8, angle=theta,\n color='b', fill=False, lw=1.5))\n ax.add_artist(Circle((n[0], n[1]), radius=0.2, color='w',\n ec='b', lw=4))\n ax.arrow(n[0], n[1], 0.5*n[2], 0.5*n[3], fc='b', ec='b',\n head_width=0.2, head_length=0.2)\n\n ax.plot(traj[::3, 0], traj[::3, 1], ls='', marker='8', markersize=5,\n color='r', label='Robot trajectory')\n ax.plot(traj[0, 0], traj[0, 1], ls='', marker='8', markersize=15,\n color='k', label='Start')\n ax.plot(traj[-1, 0], traj[-1, 1], ls='', marker='8', markersize=15,\n color='g', label='Goal')\n ax.legend(loc='best', numpoints=1)\n plt.axis('equal')\n\n # --- Subjective\n ic, pc, sc = navmet.personal_disturbance(traj, persons)\n print('Instrusion Counts: Intimate = {}, Personal = {}, Social = {}'\n .format(ic, pc, sc))\n\n plt.show()\n\n\nif __name__ == '__main__':\n simple_example()\n","sub_path":"examples/simple_example.py","file_name":"simple_example.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"510525269","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# StackSafeRecursion.py\n#\n# Copyright © 2019 zhixiong.cai \n#\n\n\"\"\"\n@package CodeSnippets.StackSafeRecursion\n\nRecursion in Python that will not exhaust the stack.\n\"\"\"\n\niden = lambda x: x\n\nl = [1, 1] + [None] * 1000\n\ndef call(f):\n while callable(f):\n f = f()\n return f\n\t\ndef fibo(n, cont=iden):\n if l[n] is not None: return cont(l[n])\n return lambda: fibo(n - 1, lambda v_1: l.__setitem__(n - 1, v_1) or (lambda: fibo(n - 2, lambda v_2: l.__setitem__(n - 2, v_2) or (lambda: cont(v_1 + v_2)))))\n\t\ncall(fibo(1000))\n","sub_path":"StackSafeRecursion.py","file_name":"StackSafeRecursion.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"436421733","text":"#\n#\n# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl\n#\n# This file is part of acados.\n#\n# The 2-Clause BSD License\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions 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.\n#\n# THIS 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#\n#\nfrom casadi import cos, Function, sin, SX, vertcat\n\ndef chen_model():\n \"\"\" The following ODE model comes from Chen1998. \"\"\"\n nx, nu = (2, 1)\n x = SX.sym('x', nx)\n u = SX.sym('u', nu)\n mu = 0.5\n rhs = vertcat(x[1] + u*(mu + (1.-mu)*x[0]), x[0] + u*(mu - 4.*(1.-mu)*x[1]))\n return Function('chen', [x, u], [rhs], ['x', 'u'], ['xdot']), nx, nu\n\ndef pendulum_model():\n \"\"\" Nonlinear inverse pendulum model. \"\"\"\n M = 1 # mass of the cart [kg]\n m = 0.1 # mass of the ball [kg]\n g = 9.81 # gravity constant [m/s^2]\n l = 0.8 # length of the rod [m]\n\n p = SX.sym('p') # horizontal displacement [m]\n theta = SX.sym('theta') # angle with the vertical [rad]\n v = SX.sym('v') # horizontal velocity [m/s]\n omega = SX.sym('omega') # angular velocity [rad/s]\n F = SX.sym('F') # horizontal force [N]\n\n ode_rhs = vertcat(v,\n omega,\n (- l*m*sin(theta)*omega**2 + F + g*m*cos(theta)*sin(theta))/(M + m - m*cos(theta)**2),\n (- l*m*cos(theta)*sin(theta)*omega**2 + F*cos(theta) + g*m*sin(theta) + M*g*sin(theta))/(l*(M + m - m*cos(theta)**2)))\n\n nx = 4\n # for IRK\n xdot = SX.sym('xdot', nx, 1)\n z = SX.sym('z',0,1)\n return (Function('pendulum', [vertcat(p, theta, v, omega), F], [ode_rhs], ['x', 'u'], ['xdot']),\n nx, # number of states\n 1, # number of controls\n Function('impl_pendulum', [vertcat(p, theta, v, omega), F, xdot, z], [ode_rhs-xdot],\n ['x', 'u','xdot','z'], ['rhs']))\n","sub_path":"experimental/examples/python/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"21154009","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 ('getpaid', '0002_auto_20150723_0923'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='payment',\n name='amount',\n field=models.DecimalField(verbose_name='amount', max_digits=10, decimal_places=2),\n ),\n migrations.AlterField(\n model_name='payment',\n name='amount_paid',\n field=models.DecimalField(default=0, verbose_name='amount paid', max_digits=10, decimal_places=2),\n ),\n ]\n","sub_path":"getpaid/migrations/0003_auto_20160706_1940.py","file_name":"0003_auto_20160706_1940.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"526692880","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\ddshape\\break_shell.py\n# Compiled at: 2015-06-08 05:15:18\nimport inc\n\ndef break_shell(index=1, data='', center=(0, 0, 0), out_radius=25, shell=3, cutoff=(0, 0, 0, 0, 0, 0), precision=1):\n \"\"\"\n the main function to write break hollow sphere\n :param index: a number which indicate the line numbers of main shape data\n :param data: string with all shape data combined\n :param center: center of the hollow sphere\n :param out_radius: out radius of sphere, the unit is nm\n :param shell: shell thickness of sphere\n :param cutoff: remove some part of break shell\n :param precision: precision that determine the size of dipole\n :return: int, string\n \"\"\"\n number_range = inc.get_range(out_radius, cutoff, precision)\n for j in range(number_range[0], number_range[1]):\n for k in range(number_range[2], number_range[3]):\n for m in range(number_range[4], number_range[5]):\n if break_shell_validate((j, k, m), out_radius, shell, precision):\n data += inc.print_line(index, center, (j, k, m), precision)\n index += 1\n\n return (\n index, data)\n\n\ndef break_shell_validate(point=(0, 0, 0), out_radius=25, shell=3, precision=1):\n \"\"\"\n validate if a point is in a shell\n :param point: temporary point of shell\n :param out_radius: out radius of shell\n :param shell: thickness of shell\n :param precision: precision that determine the size of dipole\n :return: boolean\n \"\"\"\n sqrt_acc = point[0] ** 2 + point[1] ** 2 + point[2] ** 2\n if not ((out_radius - shell) * precision) ** 2 <= sqrt_acc <= (out_radius * precision) ** 2:\n return False\n return True","sub_path":"pycfiles/ddshape-0.38-py2.7/break_shell.py","file_name":"break_shell.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"462974018","text":"import argparse\nimport time\nfrom tensorboardX import SummaryWriter\nfrom dataset import dataset_loader\nfrom model import LeNet5, ResNet34\nimport torch\nfrom torch import nn\n'''\n--model ResNet34 --dataset sign_mnist --log_interval 100\n--model ResNet34 --dataset sign_mnist --log_interval 100 --gray_scale\n--model ResNet34 --dataset kinect_leap --log_interval 8\n--model ResNet34 --dataset kinect_leap --log_interval 8 --gray_scale\n--model LeNet5 --dataset sign_mnist --log_interval 100\n--model LeNet5 --dataset sign_mnist --log_interval 100 --gray_scale\n--model LeNet5 --dataset kinect_leap --log_interval 8\n--model LeNet5 --dataset kinect_leap --log_interval 8 --gray_scale\n'''\n\nparser = argparse.ArgumentParser(description='PyTorch Gesture Recognition Model')\nparser.add_argument('--model', choices=['LeNet5', 'ResNet34'], default='LeNet5', type=str, help='LeNet5(default), ResNet34')\nparser.add_argument('--dataset',\n choices=['sign_mnist', 'kinect_leap'],\n default='sign_mnist',\n type=str,\n help='sign_mnist(default), kinect_leap')\nparser.add_argument('--gray_scale', action='store_true', help='train with grayscale image or rgb image(defalt: rgb)')\nparser.add_argument('--epoch', default=100, type=int, help='amount of epoches been processed')\nparser.add_argument('--save_model', action='store_true', help='saving model or not(default: false)')\nparser.add_argument('--log_interval', default=100, type=int, help='how many batches to wait before logging status(defalut:100)')\nparser.set_defaults(augment=True)\n\nwriter = SummaryWriter('./log')\n\n\ndef main():\n global args\n\n args = parser.parse_args()\n\n # load dataset\n if args.dataset == 'sign_mnist':\n loader = dataset_loader(True)\n if args.model == 'LeNet5':\n train_loader, test_loader = loader.load_sign_mnist(28, isGrayScale=args.gray_scale)\n elif args.model == 'ResNet34':\n train_loader, test_loader = loader.load_sign_mnist(224, isGrayScale=args.gray_scale)\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n elif args.dataset == 'kinect_leap':\n loader = dataset_loader(False)\n if args.model == 'LeNet5':\n train_loader, test_loader = loader.load_kinect_leap(img_size=28, isGrayScale=args.gray_scale)\n elif args.model == 'ResNet34':\n train_loader, test_loader = loader.load_kinect_leap(img_size=224, isGrayScale=args.gray_scale)\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n else:\n raise RuntimeError('unrecogniazed dataset name' + repr(args.dataset))\n\n # load model\n if args.model == 'LeNet5':\n model = LeNet5(class_num=loader.class_num, is_gray_scale=args.gray_scale).cuda()\n elif args.model == 'ResNet34':\n model = ResNet34(class_num=loader.class_num, is_gray_scale=args.gray_scale).cuda()\n else:\n raise RuntimeError('unrecognized model name ' + repr(args.model))\n\n print(model)\n\n criterion = nn.CrossEntropyLoss().cuda()\n optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n\n # time counting\n start_time = time.time()\n\n for epoch in range(1, args.epoch + 1):\n train(model, train_loader, criterion, optimizer, epoch)\n test(model, test_loader, epoch)\n\n end_time = time.time()\n print('training process using ', end_time - start_time)\n\n # save model\n if args.save_model:\n saving_path = './trained_model/' + args.model + '.pth'\n torch.save(model, saving_path)\n return\n\n\ndef train(model, train_loader, criterion, optimizer, epoch):\n epoch_start_time = time.time()\n model.train()\n\n total = len(train_loader.dataset)\n\n # loss sum\n train_loss = 0\n\n correct = 0\n\n data_start_time = time.time()\n for i, (input, target) in enumerate(train_loader):\n # data_start_time = time.time()\n\n input = input.cuda()\n target = target.cuda()\n\n optimizer.zero_grad()\n output = model(input)\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n\n predicted = output.argmax(dim=1)\n correct += torch.eq(predicted, target).float().sum().item()\n\n # data_time = time.time() - data_start_time\n\n trained_total = (i + 1) * len(target)\n loss_mean = train_loss / (i + 1)\n acc = correct / trained_total\n process = 100 * trained_total / total\n\n if (i + 1) % args.log_interval == 0:\n data_time = time.time() - data_start_time\n print('epoch: {} [{}/{} ({:.0f}%)] \\tloss:{:.6f}({:.6f}) \\taccuracy:{:.6f} \\ttime:{:.6f}'.format(\n epoch, trained_total, total, process, loss, loss_mean, acc, data_time))\n data_start_time = time.time()\n\n writer.add_scalar('train/loss_mean', loss_mean, (epoch - 1) * len(train_loader) + i)\n writer.add_scalar('train/accuracy', acc, (epoch - 1) * len(train_loader) + i)\n writer.add_scalar('train/loss', loss, (epoch - 1) * len(train_loader) + i)\n\n epoch_time = time.time() - epoch_start_time\n print('epoch trained in ', epoch_time)\n\n return\n\n\ndef test(model, test_loader, epoch):\n model.eval()\n\n correct = 0\n\n for i, (input, target) in enumerate(test_loader):\n input = input.cuda()\n target = target.cuda()\n\n output = model(input)\n\n predicted = output.argmax(dim=1)\n correct += torch.eq(predicted, target).float().sum().item()\n\n acc = correct / len(test_loader.dataset)\n\n writer.add_scalar('test/accuracy', acc, (epoch - 1) * len(test_loader))\n\n print('epoch: {} accuracy:{}'.format(epoch, acc))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Project/Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"235718177","text":"animales = {\"Gato Montes\": 2, \"Yacare overo\": 4, \"Boa acuática\": 5}\nfor animal in animales:\n pos = animales[animal]\n car = animal[pos]\n i = 0\n cadena = \"\"\n for letra in animal:\n if (i == pos):\n cadena += car + \" \"\n else:\n cadena += \"_ \"\n i += 1\n print(cadena)\n","sub_path":"Practica1/Ejercicio12.py","file_name":"Ejercicio12.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"219228728","text":"\n## Test ID:\nUSER_NAME = 'Bar'\nFOLDER_PATH = r\"C:\\\\Users\\bar.kristal\\Documents\\GitHub\\Python\\Tests\\functionality_test\"\nTEST_NAME = \"excel_test\"\n\n#call the init.py module:\nexecfile(r\"C:\\Users\\bar.kristal\\Documents\\GitHub\\Python\\init.py\")\n\n# defines:\nheadlines = [\"Block\", \"Temp\", \"Voltage\", \"Result\"]\ntemps = [\"-40C\", \"25C\", \"80C\"]\nvoltages = [\"0.9\", \"1.1\", \"1.2\"]\nblocks = [\"PTCM\", \"RAM\", \"DTCM\"]\n\nblock_col = 1\ntemp_col = 2\nvolt_col = 3\nresult_col = 4\n\n#######################################################################################\n\nwb1, full_path = create_excel_file(DIR_NAME, LOG_NAME_EXCEL)\nws1 = wb1.create_sheet(\"BIST results\")\n\nthermotron = Termotron3800(TERMOTRON_TCP_IP)\npwr_sply = QL355TPPwrSply(POWER_SUPLLY_ADDRESS)\ndmm = Agillent34401A(DMM_ADDRESS)\n\n\n\n#write headlines to excel\nfor i in range(len(headlines)):\n ws1.cell(row=1, column=i+1).value = headlines[i]\nwb1.save(full_path)\n\ncurrent_row = 2\n\n#start test and write results to excel\nfor temp in temps:\n # thermotron.set_temp(temp)\n time.sleep(3)\n\n for volt in voltages:\n # pwr_sply.set_volt(volt)\n\n for block in blocks:\n\n '''run test on the block'''\n\n #result:\n if len(block) % 2 == 0:\n result = \"Pass\"\n else:\n result = \"Fail\"\n\n #write results:\n ws1.cell(row=current_row, column=block_col).value = block\n ws1.cell(row=current_row, column=temp_col).value = temp\n ws1.cell(row=current_row, column=volt_col).value = volt\n ws1.cell(row=current_row, column=result_col).value = result\n\n #upgarde row number\n current_row += 1\n\n #save excel file\n wb1.save(full_path)\n\n\n\n","sub_path":"Tests/functionality_test/excel_test.py","file_name":"excel_test.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"295638359","text":"from urllib.request import urlretrieve\r\nimport time\r\nimport zipfile\r\nimport os\r\nimport numpy as np\r\n\r\n\r\ndef main(url):\r\n# Скачиваем zip файл с данными.\r\n\ttry:\r\n\t\tzipdata = 'dataset.zip'\r\n\t\turlretrieve(url, zipdata)\r\n\t\tprint('\\nZip файл успешно загружен\\n')\r\n\texcept:\r\n\t\tprint('Ошибка загрузки, либо файл уже загружен\\n')\r\n\r\n# Извлечение txt.\r\n\ttry:\r\n\t\tprint('Извлечение...\\n')\r\n\t\tf = zipfile.ZipFile('dataset.zip', 'r')\r\n\t\tf.extractall()\r\n\t\tprint('Извлечение успешно\\n')\r\n\texcept:\r\n\t\tprint('Извлечение не выполнено, либо извлечение уже было произведено\\n')\r\n\r\n# Распределение файлов по спискам для дальнейшего сравнения.\r\n\tdataSet1 = []\r\n\tdataSet2 = []\r\n# первый файл.\r\n\twith open('time series 1.txt', 'r') as q:\r\n\t\tdataSet1 = q.read().split()\r\n\t\tq.close()\r\n# второй файл.\r\n\twith open('time series 2.txt', 'r') as w:\r\n\t\tdataSet2 = w.read().split()\r\n\t\tw.close()\r\n\r\n# Сравнение списков\r\n\tresultIntersection = []\r\n\tresultDifferences = []\r\n# Пересечение(1)\r\n\tfor x in dataSet1:\r\n\t\tif x in dataSet2:\r\n\t\t\tresultIntersection.append(x)\r\n# Отличия(2)\r\n\tfor y in dataSet1:\r\n\t\tif y not in dataSet2:\r\n\t\t\tresultDifferences.append(y)\r\n# Медиана(3)\r\n\ta = np.array(dataSet1, float)\r\n\tb = np.array(dataSet2, float)\r\n\taMed = np.median(a)\r\n\tbMed = np.median(b)\r\n\tmedians = (aMed,bMed)\r\n# Корреляция(4)\r\n\td = np.array(dataSet1).astype(np.float)\r\n\tb = np.array(dataSet2).astype(np.float)\r\n\tcorr = np.corrcoef(d,b)\r\n\t\r\n\r\n# Создание файла с результатом\r\n\ttry:\r\n\t\tstrCorr = ('Значение корреляции\\n' + str(corr))\r\n\t\tstrMedian = ('Значения медиан\\n' + str(medians))\r\n\t\tstrResultIntersection = ('Пересечение списков\\n' + str(resultIntersection) + '\\n\\n')\r\n\t\tstrResultDifferences = ('\\n\\nЗначения, не пересекающи��ся в списках\\n' + str(resultDifferences) + '\\n\\n')\r\n\t\twith open('result.txt', 'w') as result:\r\n\t\t\tresult.write(strResultIntersection)\r\n\t\t\tresult.write(strResultDifferences)\r\n\t\t\tresult.write(strCorr)\r\n\t\t\tresult.write(strMedian)\r\n\t\t\tresult.close()\r\n\t\tprint('Результат сохранен в файл result.txt')\r\n\texcept:\r\n\t\tprint('Ошибка сохранения результата')\r\n\r\n\treturn strResultDifferences, strResultIntersection, strMedian, strCorr\r\n\r\n\r\nurl = 'https://drive.google.com/uc?authuser=0&id=1MJecQrW-LEnutKl93DxiI-GYmg49MWES&export=download'\r\nwhile True:\r\n\tmain(url)\r\n# Пауза 10 минут, после этого цикл повторится.\r\n\ttime.sleep(600)\r\n# Для наглядности продемонстрировано удаление zip файла, после чего функция скачает его вновь.\r\n\tpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'dataset.zip')\r\n\tos.remove(path)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"48964482","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Desafio 6\n# \n# Neste desafio, vamos praticar _feature engineering_, um dos processos mais importantes e trabalhosos de ML. Utilizaremos o _data set_ [Countries of the world](https://www.kaggle.com/fernandol/countries-of-the-world), que contém dados sobre os 227 países do mundo com informações sobre tamanho da população, área, imigração e setores de produção.\n# \n# > Obs.: Por favor, não modifique o nome das funções de resposta.\n\n# ## _Setup_ geral\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\n# In[3]:\n\n\n# Algumas configurações para o matplotlib.\n#%matplotlib inline\n\nfrom IPython.core.pylabtools import figsize\n\n\nfigsize(12, 8)\n\nsns.set()\n\n\n# In[4]:\n\n\ncountries = pd.read_csv(\"countries.csv\")\n\n\n# In[5]:\n\n\nnew_column_names = [\n \"Country\", \"Region\", \"Population\", \"Area\", \"Pop_density\", \"Coastline_ratio\",\n \"Net_migration\", \"Infant_mortality\", \"GDP\", \"Literacy\", \"Phones_per_1000\",\n \"Arable\", \"Crops\", \"Other\", \"Climate\", \"Birthrate\", \"Deathrate\", \"Agriculture\",\n \"Industry\", \"Service\"\n]\n\ncountries.columns = new_column_names\n\ncountries.head()\n\n\n# ## Observações\n# \n# Esse _data set_ ainda precisa de alguns ajustes iniciais. Primeiro, note que as variáveis numéricas estão usando vírgula como separador decimal e estão codificadas como strings. Corrija isso antes de continuar: transforme essas variáveis em numéricas adequadamente.\n# \n# Além disso, as variáveis `Country` e `Region` possuem espaços a mais no começo e no final da string. Você pode utilizar o método `str.strip()` para remover esses espaços.\n\n# ## Inicia sua análise a partir daqui\n\n# In[6]:\n\n\nnumeric_columns = [\n \"Pop_density\", \"Coastline_ratio\", \"Net_migration\", \"Infant_mortality\",\"Literacy\", \"Phones_per_1000\",\n \"Arable\", \"Crops\", \"Other\", \"Climate\", \"Birthrate\", \"Deathrate\", \"Agriculture\",\n \"Industry\", \"Service\"]\n\nfor column in numeric_columns:\n countries[column] = countries[column].str.replace(',', '.').astype(float)\n\ncountries['Region'] = [s.strip() for s in countries.Region.to_list()]\n\ncountries.dtypes\n\n\n# # Questão 1\n# \n# Quais são as regiões (variável `Region`) presentes no _data set_? Retorne uma lista com as regiões únicas do _data set_ com os espaços à frente e atrás da string removidos (mas mantenha pontuação: ponto, hífen etc) e ordenadas em ordem alfabética.\n\n# In[10]:\n\n\ndef q1():\n unique = [x for x in countries.Region.sort_values().unique()]\n return unique\n\nq1()\n\n\n# ## Questão 2\n# \n# Discretizando a variável `Pop_density` em 10 intervalos com `KBinsDiscretizer`, seguindo o encode `ordinal` e estratégia `quantile`, quantos países se encontram acima do 90º percentil? Responda como um único escalar inteiro.\n\n# In[7]:\n\n\ndef q2():\n \n\n est = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile')\n pop_density_discretizer = est.fit(countries[['Pop_density']])\n\n scores = pop_density_discretizer.transform(countries[['Pop_density']])\n\n return len(scores[scores==9])\nq2()\n\n\n# # Questão 3\n# \n# Se codificarmos as variáveis `Region` e `Climate` usando _one-hot encoding_, quantos novos atributos seriam criados? Responda como um único escalar.\n\n# In[8]:\n\n\ndef q3():\n countries_for_one_hot = countries[[\"Region\", \"Climate\"]]\n countries_for_one_hot['Climate'].fillna(0, inplace=True)\n \n one_hot_encoder = OneHotEncoder(sparse=False, dtype=np.int)\n region_encoded = one_hot_encoder.fit_transform(countries_for_one_hot[[\"Region\", \"Climate\"]])\n\n return region_encoded.shape[1]\n\nq3()\n\n\n# ## Questão 4\n# \n# Aplique o seguinte _pipeline_:\n# \n# 1. Preencha as variáveis do tipo `int64` e `float64` com suas respectivas medianas.\n# 2. Padronize essas variáveis.\n# \n# Após aplicado o _pipeline_ descrito acima aos dados (somente nas variáveis dos tipos especificados), aplique o mesmo _pipeline_ (ou `ColumnTransformer`) ao dado abaixo. Qual o valor da variável `Arable` após o _pipeline_? Responda como um único float arredondado para três casas decimais.\n\n# In[38]:\n\n\ntest_country = [\n 'Test Country', 'NEAR EAST', -0.19032480757326514,\n -0.3232636124824411, -0.04421734470810142, -0.27528113360605316,\n 0.13255850810281325, -0.8054845935643491, 1.0119784924248225,\n 0.6189182532646624, 1.0074863283776458, 0.20239896852403538,\n -0.043678728558593366, -0.13929748680369286, 1.3163604645710438,\n -0.3699637766938669, -0.6149300604558857, -0.854369594993175,\n 0.263445277972641, 0.5712416961268142\n]\n\ndf_test_country = pd.DataFrame([dict(zip(new_column_names, test_country))])\n\n\n# In[40]:\n\n\ndef q4():\n df_countries_numeric = countries.select_dtypes(include = ['int64', 'float64'])\n countries_numeric_columns = df_countries_numeric.columns.to_list()\n \n num_pipeline = Pipeline([\n (\"imputer\", SimpleImputer(strategy='median')),\n (\"standard\", StandardScaler())\n ])\n \n num_pipeline.fit(df_countries_numeric)\n arable_id = countries_numeric_columns.index('Arable')\n arable_value = num_pipeline.transform(df_test_country[countries_numeric_columns])[0][arable_id]\n \n return float(round(arable_value, 3))\n \nq4()\n\n\n# ## Questão 5\n# \n# Descubra o número de _outliers_ da variável `Net_migration` segundo o método do _boxplot_, ou seja, usando a lógica:\n# \n# $$x \\notin [Q1 - 1.5 \\times \\text{IQR}, Q3 + 1.5 \\times \\text{IQR}] \\Rightarrow x \\text{ é outlier}$$\n# \n# que se encontram no grupo inferior e no grupo superior.\n# \n# Você deveria remover da análise as observações consideradas _outliers_ segundo esse método? Responda como uma tupla de três elementos `(outliers_abaixo, outliers_acima, removeria?)` ((int, int, bool)).\n\n# In[45]:\n\n\ndef q5():\n net_migration = countries['Net_migration']\n q1 = net_migration.quantile(.25)\n q3 = net_migration.quantile(.75)\n \n iqr = q3 - q1\n \n outliers_acima = len(net_migration[net_migration > q3 + 1.5*iqr])\n outliers_abaixo = len(net_migration[net_migration < q1 - 1.5*iqr])\n\n \n removeria = bool((outliers_abaixo + outliers_acima)/len(net_migration) < 0.2)\n return (outliers_abaixo, outliers_acima, removeria)\nq5()\n\n\n# ## Questão 6\n# Para as questões 6 e 7 utilize a biblioteca `fetch_20newsgroups` de datasets de test do `sklearn`\n# \n# Considere carregar as seguintes categorias e o dataset `newsgroups`:\n# \n# ```\n# categories = ['sci.electronics', 'comp.graphics', 'rec.motorcycles']\n# newsgroup = fetch_20newsgroups(subset=\"train\", categories=categories, shuffle=True, random_state=42)\n# ```\n# \n# \n# Aplique `CountVectorizer` ao _data set_ `newsgroups` e descubra o número de vezes que a palavra _phone_ aparece no corpus. Responda como um único escalar.\n\n# In[69]:\n\n\ncategories = ['sci.electronics', 'comp.graphics', 'rec.motorcycles']\nnewsgroup = fetch_20newsgroups(subset=\"train\", categories=categories, shuffle=True, random_state=42)\n\n\n# In[65]:\n\n\ndef q6():\n \n vectorizer = CountVectorizer()\n vectorizer_transform = vectorizer.fit_transform(newsgroup['data'])\n \n word_list = vectorizer.get_feature_names(); \n count_list = vectorizer_transform.toarray().sum(axis=0)\n vectorize_dict = dict(zip(word_list,count_list))\n \n return vectorize_dict['phone']\n \nq6()\n\n\n# ## Questão 7\n# \n# Aplique `TfidfVectorizer` ao _data set_ `newsgroups` e descubra o TF-IDF da palavra _phone_. Responda como um único escalar arredondado para três casas decimais.\n\n# In[73]:\n\n\ndef q7():\n \n vectorizer = TfidfVectorizer()\n vectorizer_transform = vectorizer.fit_transform(newsgroup['data'])\n \n word_list = vectorizer.get_feature_names(); \n count_list = vectorizer_transform.toarray().sum(axis=0)\n vectorize_dict = dict(zip(word_list,count_list))\n \n return round(vectorize_dict['phone'], 3)\nq7()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"data-science-4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"5176028","text":"import datetime\r\nfrom discord.ext import commands\r\nimport discord\r\nimport random\r\n\r\n\r\nclass FunCog(commands.Cog, name='Fun'):\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n\r\n @commands.command(aliases=['meme'])\r\n async def pepe(self, ctx):\r\n pepe = ['https://cdn.discordapp.com/emojis/656665539694952448.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/680098905009946655.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/620686647331258399.gif?v=1',\r\n 'https://cdn.discordapp.com/emojis/589828801484161066.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/596132760532287488.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/402446616281350144.png?v=1',\r\n 'https://cdn.discordapp.com/emojis/300046211300327425.png?v=1,']\r\n embed = discord.Embed(title=\"**Pepe**\",\r\n color=discord.Color.blue())\r\n embed.set_image(url=random.choice(pepe))\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n # coin flip\r\n @commands.command(aliases=['coin'])\r\n async def flip(self, ctx):\r\n responses = ['Heads', 'Tails']\r\n flipmsg = f'Congrats! Your coin landed on **{random.choice(responses)}!**'\r\n embed = discord.Embed(title=\"**Flip**\",\r\n description=('{}'.format(flipmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # joke\r\n @commands.command(aliases=['Joke', 'funny'])\r\n async def joke(self, ctx):\r\n jokemsg = ['A child asked his father, \"How were people born?\" So his father said, \"Adam and Eve made babies, '\r\n 'then their babies became adults and made babies, and so on.\" The child then went to his mother, '\r\n 'asked her the same question and she told him, \"We were monkeys then we evolved to become like we '\r\n 'are now.\" The child ran back to his father and said, \"You lied to me!\" His father replied, \"No, '\r\n 'your mom was talking about her side of the family.\" ',\r\n 'My friend thinks he is smart. He told me an onion is the only food that makes you cry, so I threw '\r\n 'a '\r\n 'coconut at his face. ',\r\n 'A teacher asked her students to use the word \"beans\" in a sentence. \"My father grows beans,'\r\n '\" said one girl. \"My mother cooks beans,\" said a boy. A third student spoke up, \"We are all human '\r\n 'beans.\" ',\r\n 'Why was 6 afraid of 7? Because 7 ate 9',\r\n 'Why did the witches team lose the baseball game? Their bats flew away',\r\n 'What starts with E and only has one letter in it? Envelope',\r\n 'Why did the can crusher quit his job? Because it was soda-pressing',\r\n 'Teacher: What do chickens give you? Kids: Meat! Teacher: What do pigs give you? Kids: Bacon! '\r\n 'Teacher: What does the fat cow give you? Kids: Homework! ',\r\n 'What happens to a frogs car when it breaks down? It gets toad away',\r\n 'Teacher: If I gave you 2 cats and another 2 cats and another 2, how many would you have?'\r\n 'Johnny: Seven.'\r\n 'Teacher: \"No, listen carefully... If I gave you two cats, and another two cats and another two, '\r\n 'how many would you have?\" '\r\n 'Johnny: Seven.'\r\n 'Teacher: Let me put it to you differently. If I gave you two apples, and another two apples and '\r\n 'another two, how many would you have? '\r\n 'Johnny: Six.'\r\n 'Teacher: Good. Now if I gave you two cats, and another two cats and another two, how many would '\r\n 'you '\r\n 'have? '\r\n 'Johnny: Seven!'\r\n 'Teacher: Johnny, where in the heck do you get seven from?!'\r\n 'Johnny: Because I already got a freaking cat!']\r\n embed = discord.Embed(title=\"**Joke**\",\r\n description=f'{random.choice(jokemsg)}',\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # dice\r\n @commands.command(aliases=['dice'])\r\n async def roll(self, ctx):\r\n responses = ['1',\r\n '2',\r\n '3',\r\n '4',\r\n '5',\r\n '6']\r\n dicemsg = f'Your dice landed on `{random.choice(responses)}!`'\r\n embed = discord.Embed(title=\"**Roll**\",\r\n description=('{}'.format(dicemsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # fact\r\n @commands.command(aliases=['interesting', 'funfact'])\r\n async def fact(self, ctx):\r\n responses = ['Some cats are actually allergic to humans',\r\n 'There is a fruit that tastes like chocolate pudding.',\r\n 'Competitive art used to be in the Olympics.',\r\n 'A chefs hat has exactly 100 pleats.',\r\n 'The majority of your brain is fat.',\r\n 'Oranges arent naturally occurring fruits.',\r\n 'Most wasabi in the U.S. is not really wasabi.',\r\n 'Stop signs used to be yellow.',\r\n 'Green Eggs and Ham started as a bet.',\r\n 'Too much water can kill you.',\r\n 'The hottest temperature ever recorded on Earth was 2 billion degrees kelvin.',\r\n 'High heels were originally worn by men.',\r\n 'You might be drinking water that is older than the solar system.',\r\n 'Queen Elizabeth II is a trained mechanic.',\r\n 'New York was briefly named \"New Orange.\"',\r\n 'Moonshiners used \"cow shoes\" to disguise their footprints during Prohibition.',\r\n 'It takes approx. 364 licks to get to the center of a Tootsie Pop.',\r\n 'Tree rings get wider during wet years.',\r\n 'The hottest inhabited place in the world is in Ethiopia.',\r\n 'Sea otters hold hands while they sleep.',\r\n 'Chainsaws, the horror-movie murder weapon of choice, were invented for aid in childbirth 😊',\r\n 'There is an island in Japan you can visit that is inhabited only by friendly bunnies.']\r\n factmsg = f'{random.choice(responses)}'\r\n embed = discord.Embed(title=\"**Fact**\",\r\n description=('{}'.format(factmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n # 8ball\r\n @commands.command(aliases=['8ball', 'ask', 'curious', 'magic8ball'])\r\n async def eightball(self, ctx, *, question):\r\n responses = ['As I see it, yes.',\r\n 'Ask again later.',\r\n 'Better not tell you now.',\r\n 'Cannot predict now.',\r\n 'Concentrate and ask again.',\r\n 'Don’t count on it.',\r\n 'It is certain.',\r\n 'It is decidedly so.',\r\n 'Most likely.',\r\n 'My reply is no.',\r\n 'My sources say no.',\r\n 'Outlook not so good.',\r\n 'Outlook good.',\r\n 'Reply hazy, try again.',\r\n 'Signs point to yes.',\r\n 'Very doubtful.',\r\n 'Without a doubt.',\r\n 'Yes.',\r\n 'Yes – definitely.',\r\n 'You may rely on it.'\r\n 'Maybe.']\r\n ballmsg = f'Question: `{question}`\\nAnswer: `{random.choice(responses)}`'\r\n embed = discord.Embed(title=\"**Magic 8-Ball**\",\r\n description=('{}'.format(ballmsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(FunCog(bot))\r\n print('FunCog is loaded')\r\n","sub_path":"Ice/Cogs/FunCog.py","file_name":"FunCog.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"551873830","text":"import numpy as np\n\nUSER_FEATURES = 6\nARTICLE_FEATURES = 6\nFEATURES = ARTICLE_FEATURES\n\nALPHA = 0.2 # 1 + np.sqrt(np.log(2/DELTA)/2)\nprint(ALPHA)\n\ngarticles = None\n\nM = dict()\nMinvs = dict()\nb = dict()\n\nlast_chosen_article_id = -1\nlast_zt = None\n\n\ndef set_articles(articles):\n # articles - dictionary of (about 80) article id -> features (of len 6)\n global garticles\n garticles = articles\n for article_id in articles.keys():\n garticles[article_id] = np.asarray(articles[article_id])\n M[article_id] = np.eye(FEATURES)\n Minvs[article_id] = np.eye(FEATURES)\n b[article_id] = np.zeros(FEATURES)\n\n\ndef update(reward):\n # reward - int\n if reward == -1:\n return\n global last_chosen_article_id, last_zt\n assert last_chosen_article_id >= 0\n assert last_zt is not None\n article = last_chosen_article_id\n M[article] += np.outer(last_zt, last_zt)\n Minvs[article] = np.linalg.inv(M[article])\n b[article] += reward * last_zt\n\n last_zt = None\n last_chosen_article_id = -1\n\n\ndef recommend(timestamp, user_features, choices):\n # timestamp - int\n # user_features - list - user features, len 6\n # choices - list - ids of articles to choose from, len 20\n global garticles, last_zt\n zt = np.asarray(user_features)\n UCB_max = np.NINF\n UCB_argmax = -1\n for article_id in choices:\n Minv = Minvs[article_id]\n w = Minv.dot(b[article_id])\n UCB = w.dot(zt) + ALPHA * np.sqrt(zt.dot(Minv.dot(zt)))\n if UCB > UCB_max:\n last_zt = np.copy(zt)\n UCB_max = np.copy(UCB)\n UCB_argmax = article_id\n\n global last_chosen_article_id\n last_chosen_article_id = UCB_argmax\n return UCB_argmax\n","sub_path":"dm-project-4/policy_linucb.py","file_name":"policy_linucb.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"435257097","text":"# -*- coding: utf8 -*-\nfrom numpy import *\nimport json\n\ndef RecursiveSC(level, N, count, points):\n if level:\n for i in range(N[level]):\n RecursiveSC(level - 1, N, count, points)\n count[level] += 1\n count[level] = 0\n\n else:\n for i in range(N[0]):\n points.append(count[:])\n count[0] += 1\n count[0] = 0\n\ndef GenerateSC(dim, part_radius, N, scale, filename):\n try:\n f = open(filename, \"w+\")\n except Exception as e:\n return str(e)\n\n data = {}\n data[\"Dimensions\"] = dim\n data[\"SavedSteps\"] = 1\n data[\"ParticlesRadius\"] = part_radius\n\n basis = scale * eye(dim)\n\n lattice_points = []\n RecursiveSC(dim - 1, N, [0] * dim, lattice_points)\n data[\"ParticlesNumber\"] = len(lattice_points)\n lattice_points = array(lattice_points)\n\n data[\"Particles\"] = [[]]\n for p in lattice_points:\n data[\"Particles\"][0].append(list(sum(basis * p,axis=1)))\n\n particles = array(data[\"Particles\"][0])\n data[\"SystemSize\"] = [list(amin(particles, axis=0) - 0.001), list(amax(particles, axis=0) + 0.001)]\n\n f.write(json.dumps(data))\n f.close()\n return \"Saved to %s successfully.\" % filename\n\ndef GenerateFCC(N, part_radius, scale, filename):\n try:\n f = open(filename, \"w+\")\n except Exception as e:\n return str(e)\n\n data = {}\n data[\"Dimensions\"] = 3\n data[\"SavedSteps\"] = 1\n data[\"ParticlesRadius\"] = part_radius\n\n basis = scale * array([[0.5,0.5,0.0],[0.5,0.0,0.5],[0.0,0.5,0.5]])\n\n lattice_points = []\n for i in range(N[0]):\n lattice_points.append((i, i, -i))\n lattice_points.append((i+1,i,-i))\n lattice_points.append((i,i+1,-i))\n lattice_points.append((i,i,-i+1))\n for j in range(N[1]):\n lattice_points.append((i+j, i-j, -i+j))\n lattice_points.append((i+j+1,i-j,j-i))\n lattice_points.append((i+j,i-j+1,j-i))\n lattice_points.append((i+j,i-j,j-i+1))\n for k in range(N[2]):\n lattice_points.append((i+j-k, i-j+k, -i+j+k))\n lattice_points.append((i+j-k+1,i-j+k,j-i+k))\n lattice_points.append((i+j-k,i-j+k+1,j-i+k))\n lattice_points.append((i+j-k,i-j+k,j-i+k+1))\n\n lattice_points = list(set(lattice_points))\n data[\"ParticlesNumber\"] = len(lattice_points)\n lattice_points = array(lattice_points)\n\n data[\"Particles\"] = [[]]\n for p in lattice_points:\n data[\"Particles\"][0].append(list(sum(basis * p, axis=1)))\n\n particles = array(data[\"Particles\"][0])\n data[\"SystemSize\"] = [list(amin(particles, axis=0) - (part_radius + 0.001)), list(amax(particles, axis=0) + (part_radius + 0.001))]\n print(data[\"SystemSize\"])\n print(prod(array(data[\"SystemSize\"][1])-array(data[\"SystemSize\"][0])))\n print(data[\"ParticlesNumber\"])\n print(data[\"ParticlesNumber\"]/prod(array(data[\"SystemSize\"][1])-array(data[\"SystemSize\"][0])))\n\n f.write(json.dumps(data))\n f.close()\n return \"Saved to %s successfully.\" % filename\n\n#GenerateFCC([4]*3, 0.5, 1.47, \"data/lattice/fcc-bb.json\")\nGenerateFCC([1]*3, 0.5, 1.47*6, \"data/lattice/fcc-ultralow.json\")\n#GenerateFCC([20,10,1], 0.5, 2.3, \"data/lattice/fcc-nvt.json\")\n","sub_path":"Week7/python/lattice.py","file_name":"lattice.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"49091932","text":"import re\n\ndef word_frequency(text):\n return {\"hello\": 1}\n\n# open file sample.txt and read in the words\n# orig_text = str(\"\"\"Project Gutenberg's The Hound of the Baskervilles, by A. Conan Doyle\n#\n# This eBook is for the use of anyone anywhere at no cost and with\n# almost no restrictions whatsoever. You may copy it, give it away or\n# re-use it under the terms of the Project Gutenberg License included\n# with this eBook or online at www.gutenberg.org\n#\n#\n# Title: The Hound of the Baskervilles\n#\n# Author: A. Conan Doyle\n#\n# Posting Date: December 8, 2008 [EBook #2852]\n# Release Date: October, 2001\n#\n# Language: English\n#\n#\n# \"\"\"\n\nwith open('sample.txt') as g:\n orig_text = g.read()\n\n# split text into individual words\n#word_list= orig_text.lower().split()\nword_list = re.sub(r'[0-9,.!-?]', \"\", orig_text).lower().split()\n\n# make word list into another list with unique words\nunique_words = []\nignore_words = [\"the\", \"of\", \"a\", \"to\", \"i\", \"that\", \"and\", \"is\"]\nfor word in word_list:\n if word in ignore_words:\n continue\n if word not in unique_words:\n unique_words.append(word)\n\n\n#make a list of tuples w/(unique word: count)\n\nword_counts = []\n\nfor unique in unique_words:\n count = 0\n for word in word_list:\n if word == unique:\n count += 1\n word_counts.append((unique, count))\n\n#print(word_counts)\n# sort tuples from highest to lowest\nsorted_word_counts= sorted(word_counts, key=lambda s: s[1], reverse=True)\n\n#print(unique_words)\nprint(sorted_word_counts)[:20]\n\n#take top 20 words and output their count(s) to screen\n","sub_path":"word_frequency_hard.py","file_name":"word_frequency_hard.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"42004866","text":"import datetime\n\n\ndef main():\n\n filename = open(\"../inputs/day4_input.txt\")\n output_file = open(\"../inputs/day4_input_sorted.txt\", \"a\")\n dates_list = []\n events_dict = {}\n\n while True:\n line = filename.readline()\n if line == \"\":\n break\n else:\n minute = (line.split(\" \")[0] + \" \" + line.split(\" \")[1]).strip(\"[\").strip(\"]\")\n event = \" \".join(line.split(\" \")[2:]).rstrip()\n\n dates_list.append(minute)\n events_dict[minute] = event\n\n output_list = sorted(dates_list, key=lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M'))\n\n for i in output_list:\n minute_event = events_dict[i]\n write_event = i + \" \" + minute_event + \"\\n\"\n output_file.write(write_event)\n\n output_file.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"solutions/day4a_write_file.py","file_name":"day4a_write_file.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"234959213","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator\nimport pymysql.cursors\nimport folium\nfrom django.http.response import JsonResponse\n\n# Connect to the database\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='1234',\n db='mydb',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n\n# Create your views here.\ndef get_weather_skyscrapers(id, results_weather):\n for result in results_weather:\n if id == result['bldg_id']:\n return result\n \n result = list()\n return result\n \n\ndef skyscrapers_home(request):\n page = request.GET.get('page', '1')\n\n with connection.cursor() as cursor:\n # 지도에 마커 모두 출력하기\n # sql 실행\n # sql = f\"\"\"SELECT * FROM skyscrapers, bldg_images\n # WHERE skyscrapers.id=1 AND skyscrapers.id = bldg_images.bldg_id\"\"\"\n sql = \"SELECT * FROM skyscrapers\"\n cursor.execute(sql)\n result = cursor.fetchall()\n result_copy = result\n # print(result)\n\n sql = \"SELECT * FROM bldg_weather\"\n cursor.execute(sql)\n results_weather = cursor.fetchall()\n\n\t # 지도 위도, 경도 얻기\n lat_long = [result[0]['x_coord'], result[0]['y_coord']]\n m = folium.Map(lat_long, zoom_start=2)\n for countmap in range(1, 100):\n # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain')\n # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행\n # sudo pip3 install git+https://github.com/python-visualization/branca.git@master\n\n # text = \"#\"+str(countmap)+\" \"+result[countmap]['building_name']+\"\"+result[countmap]['city_name']+\"\"\\\n # +\"\" \n # 팝업창 내용 넣기\n text = \"#\"+str(countmap)+\" \"+result[countmap]['building_name']+\"\"+result[countmap]['city_name']+\"\"\n weather = get_weather_skyscrapers(result[countmap]['id'], results_weather)\n if weather:\n text = text + \"
main_weather : \" + weather['main_weather']\n text = text + \"
temperature : \" + weather['temperature_C']\n text = text + \"
humidity : \" + weather['humidity']\n lat_long = [result[countmap]['x_coord'], result[countmap]['y_coord']]\n popText = folium.Html(text+str(lat_long), script=True)\n popup = folium.Popup(popText, max_width=2650)\n folium.CircleMarker(lat_long, radius=10, popup=popup, color='#3186cc',fill_color='#3186cc',).add_to(m)\n\n # folium HTML 얻기\n m = m._repr_html_() #updated\n\n # sql = \"SELECT id, ranking, building_name, city_name, country, height_m FROM skyscrapers\"\n # cursor.execute(sql)\n result = result_copy\n\n paginator = Paginator(result, 10)\n page_obj = paginator.get_page(page)\n\n # context = {'data':page_obj, 'bldg_map': m}\n\n # return render(request, 'home.html', context)\n # return render(request, 'home.html')\n context = {'bldg_data':page_obj, 'bldg_map': m} \n return context\n\ndef home(request):\n context = skyscrapers_home(request)\n\n return render(request, 'home.html', context)\n\ndef maplist(request):\n context = skyscrapers_home(request)\n\n return render(request, 'buildings/bldg_maplist.html', context)\n\n\n\ndef bldg_list(request):\n page = request.GET.get('page', '1')\n\n # ranking', 'building_name', 'city_name', 'country', 'height_m', 'height_ft',\n # 'floor', 'completion_year', 'material', 'category', 'thumbnail',\n # 'x_coord', 'y_coord', 'reg_date'\n\n with connection.cursor() as cursor:\n sql = \"SELECT id, ranking, building_name, city_name, country, height_m FROM skyscrapers\"\n cursor.execute(sql)\n result = cursor.fetchall()\n paginator = Paginator(result, 10)\n page_obj = paginator.get_page(page)\n print(result)\n\n context = {'data':page_obj}\n\n return render(request, 'buildings/bldg_list.html', context)\n\ndef bldg_detail(request, id):\n with connection.cursor() as cursor:\n sql = f\"\"\"SELECT * FROM skyscrapers, bldg_images\n WHERE skyscrapers.id={id} AND skyscrapers.id = bldg_images.bldg_id\"\"\"\n cursor.execute(sql)\n result = cursor.fetchall()\n print(result)\n\n lat_long = [result[0]['x_coord'], result[0]['y_coord']]\n m = folium.Map(lat_long, zoom_start=14)\n # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain')\n\n # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행\n # sudo pip3 install git+https://github.com/python-visualization/branca.git@master\n text = \"\"+result[0]['building_name']+\"\"+result[0]['city_name']+\"\"\n\n popText = folium.Html(text+str(lat_long), script=True)\n popup = folium.Popup(popText, max_width=2650)\n folium.Marker(location=lat_long, popup=popup).add_to(m)\n m=m._repr_html_() #updated\n\n context = {'data':result, 'bldg_map': m}\n\n return render(request, 'buildings/bldg_detail.html', context)\n\n\n","sub_path":"website/buildings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"124606308","text":"from django.conf.urls import url, include\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.posts, name='posts'),\n url(r'(?P[0-9]+)/$', views.post_detail, name='post_detail'),\n url(r'^new/$', views.new_post, name='new_post'),\n url(r'login/$', views.user_login, name='login'),\n url(r'logout/$', views.user_logout, name='logout'),\n url(r'register/$', views.user_register, name='register'),\n # url(r'user_login/', views.user_login, name='user_login'),\n]\n","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"111320691","text":"from app import db, app\n\ndef db_commit(model):\n if model:\n db.session.add(model)\n try:\n db.session.commit()\n except Exception as e:\n app.logger.error('[db_commit] Error: %s' % e)\n db.session.rollback()\n\ndef db_delete(model):\n if model:\n app.logger.info('[db_delete] Delete: %s' % model.key)\n db.session.delete(model)\n try:\n db.session.commit()\n except Exception as e:\n app.logger.error('[db_delete] Error: %s' % e)\n db.session.rollback()","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"381049998","text":"from subprocess import call\nfrom pprint import pprint\nimport json\n\n\n\n\ndef getnumresults():\n with open('words/output.json') as data_file: \n data = json.load(data_file)\n \n return data[\"total\"]\n \ndef conductsearch(word):\n begindate = \"19810101\"\n enddate = \"20080101\"\n fields= \"date\"; #\"title,date\"\n key = \"insert_api_key_here\"\n\n #format it as a query\n word = word.replace(\" \", \"+\")\n\n #output to json file\n url = 'http://api.nytimes.com/svc/search/v1/article?format=json&query=%22'+word+'%22&fields='+fields+'&begin_date=' + begindate + '&end_date=' + enddate+ '&api-key=' + key\n #print url\n command = \"curl '\" + url + \"' | python -mjson.tool > words/output.json\"\n call(command, shell=True)\n\ndef readinwords(filename):\n words = []\n \n f = open(\"words/\" + filename)\n lines = f.readlines()\n f.close()\n for line in lines:\n line = line.strip()\n words.append(line)\n \n return words\n \ndef filldic(filename, replacementword):\n dic = {}\n \n words = readinwords(filename)\n for word in words:\n word = word.replace(\"_\", replacementword)\n conductsearch(word)\n numresults = getnumresults()\n dic[word] = numresults\n \n return dic\n\ndef main():\n arrofdics = []\n \n files =[\"activewords.txt\", \"passivewords.txt\"]\n replacementwords = [\"abused\", \"assaulted\", \"molested\", \"raped\"]\n \n for replacementword in replacementwords:\n for file in files:\n arrofdics.append(filldic(file, replacementword))\n\n f = open('words/dictionaries.json','w')\n json.dump(arrofdics, f)\n f.close()\n \n \n \n \n \n \nmain()","sub_path":"collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"625899906","text":"from bridges.color import *\nimport math\n\n\nclass Symbol:\n \"\"\"\n @brief This is the base class for constructing simple shapes in BRIDGES.\n \n This is an abstract class for deriving a\n number of Symbol shape objects, for use in a SymbolCollection.\n Symbols correspond to a simplified subset of SVG paths\n and shapes for custom visual representations in BRIDGES.\n \n Users will typically one of the subclasses of this object for creating shapes\n \n Currently shapes supported are rectangle, circle, polygon, polyline and label; each shape\n has a name, location (x, y) and appropriate geometric and non-geometric attributes\n \n @author David Burlinson, Kalpathi Subramanian\n @date 12/24/18, 7/12/19\n \"\"\"\n\n _ids = 0 #id for this symbol. Class level so each object has unique id\n\n def __init__(self):\n \"\"\"\n Constructor for a Symbol\n \"\"\"\n self._identifier = str(Symbol._ids)\n self._label = \"\"\n self._fill_color = Color(\"white\")\n self._stroke_color = Color(\"white\")\n self._opacity = 1.0\n self._stroke_width = 1.0\n self._stroke_dash = 1\n self._location_y = 0.0\n self._location_x = 0.0\n self._shape_type = \"circle\"\n Symbol._ids += 1\n\n @property\n def label(self) -> str:\n \"\"\"\n Getter for symbol label\n Returns:\n str : the label of this shape\n \"\"\"\n return self._label\n\n @label.setter\n def label(self, label: str) -> None:\n \"\"\"\n Setter for symbol label\n Args:\n label: to be set\n Returns:\n str\n \"\"\"\n self._label = label\n\n @property\n def identifier(self) -> str:\n \"\"\"\n Getter for the symbols identifier\n Returns:\n str\n \"\"\"\n return self._identifier\n\n @property\n def fill_color(self) -> Color:\n \"\"\"\n Getter for the fill color\n Returns:\n Color : the current fill color of this symbol\n \"\"\"\n return self._fill_color\n\n @fill_color.setter\n def fill_color(self, *args, **kwargs) -> None:\n \"\"\"\n Setter for the fill color\n Args:\n color: the color to set for the fill\n Returns:\n None\n \"\"\"\n self._fill_color = Color(*args, **kwargs)\n\n @property\n def stroke_color(self) -> Color:\n \"\"\"\n Getter for the stroke color\n Returns:\n the stroke (boundary) color of the shape\n \"\"\"\n return self._stroke_color\n\n @stroke_color.setter\n def stroke_color(self, *args, **kwargs) -> None:\n \"\"\"\n @brief Setter for the stroke color\n Args:\n color: the stroke (boundary) color to set\n Returns:\n None\n \"\"\"\n self._stroke_color = Color(*args, **kwargs)\n\n @property\n def stroke_width(self) -> float:\n \"\"\"\n Getter for the stroke width\n Returns:\n float : the stroke width of the shape\n \"\"\"\n return self._stroke_width\n\n @stroke_width.setter\n def stroke_width(self, width: float) -> None:\n \"\"\"\n Setter for the stroke width\n Args:\n width: the stroke width to set\n Returns:\n None\n Raises:\n value error\n \"\"\"\n if width <= 0.0 or width > 10.0:\n raise ValueError(\"Stroke width must be between 0 and 10\")\n else:\n self._stroke_width = width\n\n @property\n def opacity(self) -> float:\n \"\"\"\n Getter for opacity\n Returns:\n float : opacity of the shape\n \"\"\"\n return self._opacity\n\n @opacity.setter\n def opacity(self, o: float):\n \"\"\"\n Setter for opacity\n Args:\n o: the opacity value to set (must be in 0-1.0 range) \n Returns:\n None\n Raises: value error\n \"\"\"\n if o <= 0.0 or o > 1.0:\n raise ValueError(\"Opacity must be between 0.0 and 1.0\")\n else:\n self._opacity = o\n\n @property\n def stroke_dash(self) -> float:\n \"\"\"\n Getter for stroke_dash\n Returns:\n float : the stroke texture\n \"\"\"\n return self._stroke_dash\n\n @stroke_dash.setter\n def stroke_dash(self, dash: float):\n \"\"\"\n Setter for stroke_dash\n Args:\n dash: the stroke_dash value to set (0-10 range)\n Returns:\n None\n Raises: value error\n \"\"\"\n if dash < 0 or dash > 10:\n raise ValueError(\"Dash must be between 0 and 10 (inclusive)\")\n else:\n self._stroke_dash = dash\n\n @property\n def shape_type(self):\n \"\"\"\n Get the shape type (string)\n Returns:\n shape name (string)\n \"\"\"\n return self._shape_type\n\n @shape_type.setter\n def shape_type(self, shape):\n \"\"\"\n Set the shape type (string)\n Args:\n shape: shape name to set\n \"\"\"\n self._shape_type = shape\n\n def set_location(self, x: float, y: float) -> None:\n \"\"\"\n Setter for the location of the center of the symbol\n Args:\n x: x location \n y: y location\n Returns:\n None\n Raises:\n Value error\n \"\"\"\n if x > float('-inf') and x < float('inf') and y > float('-inf') and y < float('inf'):\n self._location_x = x\n self._location_y = y\n else:\n raise ValueError(\"Coordinates must be real numbers\")\n\n def get_location(self) -> list:\n \"\"\"\n Getter for the location of a symbol\n Returns:\n list : the x and y coordinates of the shape's current location\n \"\"\"\n return [self._location_x, self._location_y]\n\n def get_dimensions(self) -> list:\n \"\"\"\n Getter for the dimensions\n Returns:\n list : the bounding box of this shape (xmin, xmax, ymin, ymax)\n \"\"\"\n return [0.0, 0.0, 0.0, 0.0]\n\n def translate_point(self, pt, tx, ty):\n \"\"\"\n Translate a point by tx, ty along X and Y respectively\n Args:\n pt: 2D point to be translated\n tx: translation factor in X\n ty: translation factor in Y\n \"\"\"\n pt[0] += tx\n pt[1] += ty\n return pt\n\n def scale_point(self, pt, sx, sy):\n \"\"\"\n Scale a point by sx, sy along X and Y respectively\n Args:\n pt: 2D point to be scaled\n sx: scale factor in X\n sy: scale factor in Y\n \"\"\"\n pt[0] *= sx\n pt[1] *= sy\n return pt\n\n def rotate_point(self, pt, angle):\n \"\"\"\n Rotate a point by 'angle' (2D rotation)\n Args:\n pt: 2D point to be rotated\n angle: rotation angle\n \"\"\"\n angle_r = math.radians(angle)\n c = math.cos(angle_r)\n s = math.sin(angle_r)\n\n tmp = [pt[0] * c - pt[1] * s, pt[0] * s + pt[1] * c]\n pt[0] = float(tmp[0])\n pt[1] = float(tmp[1])\n return pt\n\n def get_json_representation(self) -> dict:\n \"\"\"\n Get the json representation of the Symbol class\n Returns:\n dict : the JSON representation\n \"\"\"\n ds = {\n # \"fill\": [self.fill_color.red, self.fill_color.green, self.fill_color.blue, self.fill_color.alpha],\n # \"opacity\": self.opacity,\n # \"stroke\": [self.stroke_color.red, self.stroke_color.green, self.stroke_color.blue, self.stroke_color.alpha],\n # \"stroke-width\": self.stroke_width,\n # \"stroke-dasharray\": self.stroke_dash,\n # \"location\": {\n # \"x\": self._location_x,\n # \"y\": self._location_y\n # }\n }\n if self.fill_color != Color(\"white\"):\n ds['fill'] = [self.fill_color.red, self.fill_color.green, self.fill_color.blue, self.fill_color.alpha]\n if self.opacity != 1.0:\n ds['opacity'] = self.opacity\n if self.stroke_color != Color(\"white\"):\n ds['stroke'] = [self.stroke_color.red, self.stroke_color.green, self.stroke_color.blue, self.stroke_color.alpha]\n if self.stroke_width != 1.0:\n ds['stroke-width'] = self.stroke_width\n if self.stroke_dash != 1:\n ds['stoke-dasharray'] = self.stroke_dash\n if self._location_x != 0.0 or self._location_y != 0.0:\n ds['location'] = {\n \"x\": self._location_x,\n \"y\": self._location_y\n }\n return ds\n\n","sub_path":"bridges/symbol.py","file_name":"symbol.py","file_ext":"py","file_size_in_byte":8639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"342273104","text":"import csv\nimport pygal\nfrom datetime import datetime\n\n\ndate = []\nhigh_temperature = []\nlow_temperature = []\n\n# read from file, extract date and high temperature\nfilename = 'sitka_weather_07-2014.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n reader.__next__() # skip the first line\n for record in reader:\n date.append(datetime.strptime(record[0], '%Y-%m-%d'))\n high_temperature.append(float(record[1]))\n low_temperature.append(float(record[3]))\n\n# plot a histogram\nhist = pygal.Bar()\nhist.x_labels = date # add label to the bars\nhist.add('High Temperature', high_temperature) # add data to it\nhist.add('Low Temperature', low_temperature)\nhist.render_to_file('high_low_temperature.svg')\n","sub_path":"weather_plot/highs_lows.py","file_name":"highs_lows.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"592040303","text":"import numpy as np \r\nimport pandas as pd\r\nimport statsmodels.api as sm\r\nimport statsmodels.formula.api as smf\r\n\r\n'''\r\nUnless you want to pip install all the libraries/modules\r\nyou should use Jupyter for this code\r\n'''\r\n\r\n# You probably have a different path\r\nallData = pd.read_csv('./AllData.csv')\r\n\r\n# Risk Free\r\nrf = 0.15\r\n\r\n# Risk free subtracted from stocks\r\nmonthly_rf = allData.drop('S&P500', axis=1).copy() - rf\r\n\r\n# Linear Regression\r\n\r\n# Risk free subtracted from \r\n# S&P500 returns used as market returns \r\nmarket_rf = allData['S&P500'] - rf\r\n\r\n# smf.OLS doesn't provide a constant automatically\r\n# so we have to add it using this function\r\nmarket_rf = sm.add_constant(market_rf)\r\n\r\n# creates a dictionary of fits where key is the stock name\r\n# and value is the fit\r\nresults = {x : smf.OLS(monthly_rf[x], market_rf).fit() \r\n\t\t\t\t\t\t\t\t\tfor x in monthly_rf}\r\n\r\n# look at all the information\r\n# run through the list of stock names\r\nfor x in monthly_rf:\r\n\tprint(results[x].summary())\r\n\r\n# Prints the Alpha and Beta estimates for each stock\r\nfor x in monthly_rf:\r\n\tprint('Stock: %s Alpha: %8.4f Beta: %8.4f' % (x, results[x].params[0], results[x].params[1]))\r\n\r\n# creates a list of underperforming stocks\r\nunder_performers = [key for key in results.keys()\r\n\t\t\t\t\t\t\t\t\tif results[key].tvalues[0] < -1.697]\r\n\r\n# Prints out the underperformers\r\nfor x in under_performers:\r\n\tprint('%s' % x)\r\n\r\n# creates a list of overperforming stocks\r\nover_performers = [key for key in results.keys()\r\n\t\t\t\t\t\t\t\t\tif results[key].tvalues[0] > 1.697]\r\n\r\n# Prints out the overperformers\r\nfor x in over_performers:\r\n\tprint('%s' % x)\r\n\r\n# Sample market return\r\nmarket_return = allData['S&P500'].mean()\r\n\r\n# Sample return from 30 DJI stocks\r\nmonthly_return = allData.drop('S&P500', axis=1).copy().mean()\r\n\r\n# Sample covariance from 30 DJI stocks\r\nmonthly_covariance = allData.drop('S&P500', axis=1).copy().cov()\r\n\r\n# calculates returns through CAPM\r\nreturns = [(rf + results[x].params[1]*(market_return - rf)) for x in results]\r\n\r\n# Array of 1s\r\nu = np.array([1]*len(monthly_return))\r\n\r\n# Calculates market weights with CAPM returns\r\nmarket_weights = np.dot(np.linalg.inv(monthly_covariance),\r\n\treturns - rf*u)/(np.dot(np.dot(u.T, np.linalg.inv(monthly_covariance)),\r\n\t\treturns - rf*u))\r\n\r\n# Calculates market weights with sample returns\r\nog_market_weights = np.dot(np.linalg.inv(monthly_covariance),\r\n\tmonthly_return - rf*u)/(np.dot(np.dot(u.T, np.linalg.inv(monthly_covariance)),\r\n\t\tmonthly_return - rf*u))","sub_path":"Homework2/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"368859193","text":"from selenium import webdriver\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"file:///C:/Users/twin5/Desktop/DojoAssignments/Python/Selenium/Exercise%20Files/CH02/html_code_02.html\")\n\nlogin_form_absolute = driver.find_element_by_xpath('/html/body/form[1]')\nlogin_form_relative = driver.find_element_by_xpath('//form[1]')\nlogin_form_id = driver.find_element_by_xpath('//form[@id=\"loginForm\"]')\nprint(\"My login form is:\")\nprint(login_form_absolute)\nprint(login_form_relative)\nprint(login_form_id)\n\ndriver.close()\n","sub_path":"004-FindingByXPath.py","file_name":"004-FindingByXPath.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"29395303","text":"\"\"\"\nModule containing abstract classes for web services\n\"\"\"\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom app.abstract.services.database_service.config import DatabaseConnectionConfig\nfrom app.abstract.services.database_service.db_connection import DatabaseConnection\nfrom app.abstract.services.web_service.config import WebServiceRouterConfig\n\n\ndef configure_rest_server(app: FastAPI, router_configs: List[WebServiceRouterConfig],\n db_configs: List[DatabaseConnectionConfig]):\n \"\"\"Configures the fast api rest api but does not start uvicorn\"\"\"\n\n @app.on_event('startup')\n def open_database_connections():\n DatabaseConnection.open_connections(db_configs=db_configs)\n\n @app.on_event('shutdown')\n def close_database_connections():\n DatabaseConnection.close_all_connections()\n\n app.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n for router_config in router_configs:\n app.include_router(router=router_config.router,\n prefix=f\"/{router_config.tag}\",\n tags=[router_config.tag])\n\n\ndef run_graphql_server(self, *args, **kwargs):\n raise NotImplementedError(\"run_as_graphql not implemented\")\n","sub_path":"app/abstract/web_servers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"15889854","text":"from opt2q.utils.utils import _list_the_errors, MissingParametersErrors, UnsupportedSimulator, \\\n DuplicateParameterError, UnsupportedSimulatorError, IncompatibleFormatWarning, \\\n incompatible_format_warning, _is_vector_like, _convert_vector_like_to_list, _convert_vector_like_to_set, \\\n CupSodaNotInstalledWarning, profile, parse_column_names, DaeSimulatorNotInstalledWarning\n\n__all__ = ['_list_the_errors',\n 'MissingParametersErrors',\n 'UnsupportedSimulator',\n 'DuplicateParameterError',\n 'UnsupportedSimulatorError',\n 'IncompatibleFormatWarning',\n 'CupSodaNotInstalledWarning',\n 'DaeSimulatorNotInstalledWarning',\n 'incompatible_format_warning',\n '_is_vector_like',\n '_convert_vector_like_to_list',\n '_convert_vector_like_to_set',\n 'parse_column_names',\n 'profile']\n","sub_path":"opt2q/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"432412052","text":"'''\n1. 리스트 생성\n2016년 11월 영화 예매 순위 기준 top3는 다음과 같습니다. 영화 제목을 movie_rank 이름의 리스트에 저장해보세요. (순위 정보는 저장하지 않습니다.)\n\n순위\t영화\n1\t닥터 스트레인지\n2\t스플릿\n3\t럭키\n'''\nmovie_rank = ['닥터 스트레인지', '스플릿', '럭키']\n\n'''\n2. movie_rank 리스트에 \"배트맨\"을 추가하라.\n'''\nmovie_rank.append(\"배트맨\")\nprint(movie_rank)\n\n'''\n3. movie_rank 리스트에는 아래와 같이 네 개의 영화 제목이 바인딩되어 있다. \"슈퍼맨\"을 \"닥터 스트레인지\"와 \"스플릿\" 사이에 추가하라.\nmovie_rank = ['닥터 스트레인지', '스플릿', '럭키', '배트맨']\n'''\nmovie_rank.insert(1,\"슈퍼맨\")\nprint(movie_rank)\n\n'''\n4. movie_rank 리스트에서 '럭키'를 삭제하라.\nmovie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '럭키', '배트맨']\n'''\nmovie_rank.remove('럭키')\nprint(movie_rank)\n\n'''\n5. movie_rank 리스트에서 '스플릿' 과 '배트맨'을 를 삭제하라.\nmovie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '배트맨']\n'''\nmovie_rank.pop()\nmovie_rank.pop()\nprint(movie_rank)\n\n'''\n6. price 변수에는 날짜와 종가 정보가 저장돼 있다. 날짜 정보를 제외하고 가격 정보만을 출력하라. (힌트 : 슬라이싱)\n\nprice = ['20180728', 100, 130, 140, 150, 160, 170]\n출력 예시:\n[100, 130, 140, 150, 160, 170]\n'''\nprice = ['20180728', 100, 130, 140, 150, 160, 170]\nprint(price[1:])\n\n'''\n7.슬라이싱을 사용해서 홀수만 출력하라.\n\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n'''\nnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(nums[0::2])\n\n'''\n8.슬라이싱을 사용해서 리스트의 숫자를 �� 방향으로 출력하라.\n\nnums = [1, 2, 3, 4, 5]\n실행 예:\n[5, 4, 3, 2, 1]\n'''\nnums = [1, 2, 3, 4, 5]\nprint(nums[::-1])\n\n'''\n9.interest 리스트에는 아래의 데이터가 저장되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver']\ninterest 리스트를 사용하여 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자 Naver\n'''\n\ninterest = ['삼성전자', 'LG전자', 'Naver']\nprint(interest[0]+interest[-1])\n\n'''\n\n10. interest 리스트에는 아래의 데이터가 바인딩되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\ninterest 리스트를 사용하여 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자 LG전자 Naver SK하이닉스 미래에셋대우\n'''\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\nprint(interest[1:])\n\n'''\n\n11. interest 리스트에는 아래의 데이터가 바인딩되어 있다.\n\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\njoin() 메서드를 사용해서 interest 리스트를 아래와 같이 화면에 출력하라.\n\n출력 예시:\n삼성전자\nLG전자\nNaver\nSK하이닉스\n미래에셋대우\n'''\ninterest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']\nprint('\\n'.join(interest))\n\n'''\n12. 리스트에 있는 값을 오름차순으로 정렬하세요.\ndata = [2, 4, 3, 1, 5, 10, 9]\n\n'''\n\ndata = [2, 4, 3, 1, 5, 10, 9]\ndata.sort()\nprint(data)\n\n'''\n13. \n홍길동 씨의 주민등록번호는 881120-1068234이다. 홍길동 씨의 주민등록번호를 연월일(YYYYMMDD) 부분과 그 뒤의 숫자 부분으로 나누어 출력해 보자.\n※ 문자열 슬라이싱 기법을 사용해 보자.\n'''\nnum = '881120-1068234'\nn = num[:6]\nm = num[7:]\nprint('주민등록번호 앞자리는 {0}이고, 뒷자리는 {1}입니다.'.format(n,m))\n\n'''\n14\n(1,2,3) 튜플에 값 4를 추가하여 (1,2,3,4)를 만들어 출력해 보자.\n※ 더하기(+)를 사용해 보자.\n'''\nk = (1,2,3)\nk=k+(4,)\nprint(k)\n\n'''\n15\n다음과 같은 딕셔너리 a가 있다.\na = dict()\na\n{}\n다음 중 오류가 발생하는 경우를 고르고, 그 이유를 설명해 보자.\na['name'] = 'python'\na[('a',)] = 'python'\na[[1]] = 'python'\na[250] = 'python'\n\n'''\na = dict()\n# 리스트로 이루어진 key는 사용할 수 없다. 3번\n\n'''\n16\n딕셔너리 a에서 'B'에 해당되는 값을 추출해 보자.\n a = {'A':90, 'B':80, 'C':70}\n※ 딕셔너리의 pop 함수를 사용해 보자.\n'''\na = {'A':90, 'B':80, 'C':70}\na1=a.pop('B')\nprint(a1)\n","sub_path":"python/Practice_file/practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"185469454","text":"from custom_exceptions import *\n\nclass ParkingLot:\n \"\"\"A class used to represent the Parking Lot object\n\n This parking lot object can have many parked cars inside it.\n\n Attributes\n ----------\n vehicles : [str]\n Array of car objects parked in their respective slots\n\n Methods\n ----------\n add(car)\n Add a car to the parking lot\n get_first_empty()\n Get the nearest empty slot to park a new car\n leave(slot)\n Let go of the car from the parking spot\n status()\n Show the slots, registration numbers and colour of the cars\n currently parked in the parking lot.\n registration_numbers_for_cars_with_colour(colour)\n Show the registration numbers of cars who's colour matches the\n parameter.\n slot_numbers_for_cars_with_colour(colour)\n Show the slot numbers of cars who's colour matches the parameter.\n slot_number_for_car_with_registration_number(registration_no)\n Show the slot number of the car with the given registration number.\n \"\"\"\n\n # Remember to +1 the index of vehicles while displaying the data\n # and -1 the index of vehicles while storing the data\n vehicles = None\n\n def __init__(self, size):\n \"\"\"Default Constructor\"\"\"\n if (size is None) or (not isinstance(size, int)) or (size < 1):\n raise ParkingLotInvalidInputs\n\n self.vehicles = [None] * size\n print('Created a parking lot with {} slots'.format(size))\n\n def add(self, car):\n \"\"\"Add a car object to the parking lot\n\n This method is internally called by `create_and_park()` and should\n be avoided being called directly.\n\n Parameters\n ----------\n car : Car\n The car object to be parked\n\n Returns\n ----------\n slot : int\n The slot allocated after parking\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingLotFull\n If there is no space left in the parking lot for an extra car.\n \"\"\"\n\n slot = self.get_first_empty()\n if slot > len(self.vehicles) - 1:\n raise ParkingLotFull('Sorry, parking lot is full')\n\n self.vehicles[slot] = car\n return slot, 'Allocated slot number: {}'.format(slot + 1)\n\n def get_first_empty(self):\n \"\"\"Get the nearest empty slot to park a new car\n\n Internal method. Not be called from outside.\n\n Returns\n ----------\n slot : int\n the next free slot available for parking\n\n Raises\n ----------\n ParkingLotUninitialized\n \"\"\"\n\n i = 0\n\n if self is None or self.vehicles is None:\n raise ParkingLotUninitialized\n\n for car in self.vehicles:\n if car is None:\n return i\n\n i = i + 1\n\n return i\n\n def leave(self, slot):\n \"\"\"Let go of the car from the parking spot\n\n The car object is now discarded and the spot on parking lot is\n marked empty for the new car.\n\n Returns\n ----------\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingSlotEmpty\n If for some serious reason `vehicles` attribute of parking lot\n doesn't exist.\n \"\"\"\n\n if self.vehicles[slot] is None:\n raise ParkingSlotEmpty\n\n car_left = self.vehicles[slot]\n self.vehicles[slot] = None\n car_left.slot = None\n return 'Slot number ' + str(slot + 1) + ' is free'\n\n def status(self):\n \"\"\"Show the summary of the parking lot with car details\"\"\"\n\n messages = []\n messages.append('{0:<10} {1:<20} {2:<10}'.format('Slot No.',\n 'Registration No',\n 'Colour'))\n for car in self.vehicles:\n if car is None:\n continue\n\n message = '{0:<10} {1:<20} {2:<10}'.format(car.slot + 1,\n car.registration_no,\n car.colour)\n messages.append(message)\n\n return messages\n\n def registration_numbers_for_cars_with_colour(self, colour):\n \"\"\"Show registration numbers for cars of the specified colour\"\"\"\n\n output = []\n for car in self.vehicles:\n if car.colour == colour:\n output.append(car.registration_no)\n\n return output\n\n def slot_numbers_for_cars_with_colour(self, colour):\n \"\"\"Show the slot numbers for cars of the specified colour\"\"\"\n output = []\n for car in self.vehicles:\n if car.colour == colour:\n output.append(str(car.slot + 1))\n\n return output\n\n def slot_number_for_registration_number(self, registration_no):\n \"\"\"Show the slot number for car with a registration number\"\"\"\n for car in self.vehicles:\n if car.registration_no == registration_no:\n return str(car.slot + 1)\n\n return 'Not found'\n\n def __str__(self):\n \"\"\"Readable string for debugging\"\"\"\n return ', '.join(self.vehicles)\n","sub_path":"src/parking_lot.py","file_name":"parking_lot.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"322434903","text":"\"\"\"\nHarvard Applied MAth 207\nHomework 10\nProblem 1\n\nMichael S. Emanuel\nWed Nov 14 10:50:44 2018\n\"\"\"\n\nimport numpy as np\nfrom numpy import exp\n\n# *************************************************************************************************\n# 1.1. Implement a Metropolis sampler to produce sample guesses from 500 individuals, \n# with the λ values, λ=0.2,0.5,1.0 . What are the top five possible guesses?\n# *************************************************************************************************\n\n# *************************************************************************************************\ndef hamming_dist(x: np.ndarray, y: np.ndarray):\n \"\"\"Compute the Hamming Distance between two arrays\"\"\"\n return np.sum(x != y)\n\n\ndef proposal(x: np.ndarray):\n \"\"\"Generate a proposal guess by transposing a random pair of elements in x.\"\"\"\n # Initialize a copy of x\n y = x.copy()\n # Draw a random pair in [0, n)\n n: int = len(x)\n i, j = np.random.choice(n, 2, replace=False)\n # Swap the ith and jth elements\n xi, xj = x[i], x[j]\n y[i], y[j] = xj, xi\n # Return modified guess\n return y\n\n\ndef prob(x: np.ndarray, y: np.ndarray, lam: float):\n \"\"\"The unscaled probability of guess theta given omega and the lambda parameter (inverse temperature).\"\"\"\n return exp(-lam * hamming_dist(x, y))\n\n\ndef metropolis(num_samp: int, lam: float, x_init: np.ndarray):\n \"\"\"Metropolis Sampler for this problem\"\"\"\n # The correct order\n x_best: np.ndarray = np.array([1,2,3,4,5], dtype=np.int8)\n # Get the length n of each guess\n n: int = len(x_best)\n # Initialize array to store the samples\n samples: np.ndarray = np.empty((num_samp, n), dtype=np.int8)\n # Initialize x_prev\n x_prev: np.ndarray = x_init\n # Draw num_samp samples using Metrpolis algorithm\n # Adapted from example code in Lecture 16, p. 6\n for i in range(num_samp):\n # The proposed new point\n x_star: np.ndarray = proposal(x_prev)\n # Compare probability of the propsed point to the current one\n p_star: float = prob(x_star, x_best, lam)\n p_prev: float = prob(x_prev, x_best, lam)\n # Probability ratio\n pdf_ratio: float = p_star / p_prev\n # Randomly accept or reject the step based on pdf_ratio\n if np.random.uniform() < min(1.0, pdf_ratio):\n # Accept the step\n samples[i] = x_star\n x_prev = x_star\n else:\n # Reject the step; duplicate x_prev as a sample\n samples[i] = x_prev\n return samples\n\n\ndef top_five_guesses(samples: np.ndarray):\n \"\"\"Given an Nx5 array of guesses, find the top five.\"\"\"\n # Count the frequency of the distinct guesses\n guesses, counts = np.unique(samples, return_counts=True, axis=0)\n # Sort the guesses by their frequency\n gc = list(zip(guesses, counts))\n gc.sort(key = lambda x: x[1], reverse=True)\n # Return the top five guesses and their frequency\n gc = gc[0:5]\n guesses = [x[0] for x in gc]\n counts = [x[1] for x in gc]\n return guesses, counts\n\n\n# *************************************************************************************************\n# Set random seed\nnp.random.seed(42)\n# Number of desired samples \nnum_samp = 5000\n# Set burn-in\nburn_in = 100\n# Pick a random starting point\nx_init = np.random.choice(5, size=5, replace=False).astype(np.int8) + 1\n# Range of lambdas to test\nlams = (0.2, 0.5, 1.0)\n# Table for the results\nsample_tbl = dict()\ntop_five_guesses_tbl = dict()\n# Test each lambda in turn\nfor lam in lams:\n # Run a burn-in period of 100 samples\n discarded_samples = metropolis(burn_in, lam, x_init)\n # Run the metropolis sampler on the current value of x\n x_init = discarded_samples[-1, :]\n samples = metropolis(num_samp, lam, x_init)\n # Save samples in the table\n sample_tbl[lam] = samples\n # Get the top 5 guesses and their frequencies\n guesses, counts = top_five_guesses(samples)\n # Save top five guesses to table\n top_five_guesses_tbl[lam] = top_five_guesses(samples)\n\n# Display results\nfor lam in lams:\n guesses, counts = top_five_guesses_tbl[lam]\n print(f'\\nLambda = {lam:0.1f}. Top five guesses and frequency:')\n for i in range(5):\n print(f'{guesses[i]}, {counts[i]:3} ({counts[i]/num_samp*100:0.2f})%.')\n\n\n\n# *************************************************************************************************\n# 1.2. Compute the probability that *The Shawshank Redemption* is ranked as the top movie (ranked number 1) \n# by the Metropolis algorithm sampler. Compare the resulting probabilities for the various λ values.\n# *************************************************************************************************\n\n# Set large number of samples\nnum_samp_big = 50000\n# Table for the results\nsample_tbl_big = dict()\n# Test each lambda in turn\nfor lam in lams:\n # Run the metropolis sampler on the current value of x\n x_init = samples[-1, :]\n samples = metropolis(num_samp_big, lam, x_init)\n # Save samples in the table\n sample_tbl_big[lam] = samples\n\n# Iterate through the lambdas\nprint('')\nfor lam in lams:\n # Extract the samples\n samples = sample_tbl_big[lam]\n # Count how often \"Shawshank\" is rated first\n shawshank_wins = np.sum(samples[:, 0]==1)\n shawshank_win_prob = shawshank_wins / num_samp_big\n # Report results\n print(f'Lambda = {lam:0.1f}. Probability Shawshank ranked first = {shawshank_win_prob*100:0.2f}%.')\n\n\n\n# *************************************************************************************************\ndef test_hamming():\n omega = np.array([1,2,3,4,5])\n theta = np.array([2,3,5,4,1])\n d = hamming_dist(omega, theta)\n assert d == 4\n # print(f'Hamming Distance between omega=(1,2,3,4,5) and theta=(2,3,5,4,1) is {d}.')\n print(f'Test Hamming Distance:\\n*** PASS ***')\n\ntest_hamming()\n","sub_path":"hw10/metropolis_sampler.py","file_name":"metropolis_sampler.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"217822204","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 2 18:23:23 2020\r\n\r\n@author: Jacky\r\n\"\"\"\r\n\r\n#code forked and tweaked from https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py\r\n#to extend, just add more people into the known_people folder\r\n#\r\n#work_folder=\"C:\\\\Users\\\\User\\\\Documents\\\\UiPath\\\\IPA_CA_v0\\\\\"\r\nwork_folder=\".\\\\image\\\\\"\r\nimport face_recognition\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport glob\r\nimport time\r\nimport re\r\n\r\n# Get a reference to webcam #0 (the default one)\r\nvideo_capture = cv2.VideoCapture(0)\r\n\r\n# Increase the resolution of the video\r\ndef make_1080p():\r\n video_capture.set(3, 1920)\r\n video_capture.set(4, 1080)\r\n\r\nmake_1080p()\r\n\r\n#make array of sample pictures with encodings\r\nknown_face_encodings = []\r\nknown_face_names = []\r\ndirname = os.path.dirname(__file__)\r\npath = os.path.join(dirname, 'known_people/')\r\n\r\n#make an array of all the saved jpg files' paths\r\nlist_of_files = [f for f in glob.glob(path+'*.jpg')]\r\n#find number of known faces\r\nnumber_files = len(list_of_files)\r\n\r\nnames = list_of_files.copy()\r\n\r\nfor i in range(number_files):\r\n globals()['image_{}'.format(i)] = face_recognition.load_image_file(list_of_files[i])\r\n globals()['image_encoding_{}'.format(i)] = face_recognition.face_encodings(globals()['image_{}'.format(i)])[0]\r\n known_face_encodings.append(globals()['image_encoding_{}'.format(i)])\r\n\r\n # Create array of known names\r\n names[i] = names[i].replace(\"known_people\\\\\", \"\").replace(\".jpg\", \"\") \r\n known_face_names.append(names[i])\r\n\r\n# Initialize some variables\r\nface_locations = []\r\nface_encodings = []\r\nface_names = []\r\nprocess_this_frame = True\r\nattendance = {}\r\noutfile=open(\"image_login.csv\",\"w+\")\r\noutfile.write(\"Name,Time\\n\")\r\nfor name in known_face_names:\r\n outfile.write(\"%s,99999\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")) )\r\noutfile.close()\r\nrecognizedFace=[]\r\nwhile True:\r\n if not video_capture.isOpened():\r\n if debug==1: print('Unable to load camera.')\r\n time.sleep(5)\r\n pass\r\n \r\n # Grab a single frame of video\r\n ret, frame = video_capture.read()\r\n print(ret)\r\n #frame=cv2.imread(\"known_people\\\\save_NUS.jpg\")\r\n if ret!=True: continue\r\n\r\n # Resize frame of video to 1/4 size for faster face recognition processing\r\n small_frame = frame # cv2.resize(frame, (120,120), fx=0.25, fy=0.25)\r\n #small_frame=cv2.resize(frame, (120,120 ), interpolation = cv2.INTER_CUBIC)\r\n \r\n # Resize frame of video to 3 times the size for larger display\r\n frame = frame #cv2.resize(frame, (240,240), fx=3, fy=3) \r\n cv2.imwrite(work_folder+\"save_frame.jpg\",frame)\r\n #frame =cv2.resize(frame, (180,180), interpolation = cv2.INTER_CUBIC) \r\n\r\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\r\n rgb_small_frame = small_frame[:, :, ::-1]\r\n\r\n # Only process every other frame of video to save time\r\n if process_this_frame:\r\n # Find all the faces and face encodings in the current frame of video\r\n face_locations = face_recognition.face_locations(rgb_small_frame, number_of_times_to_upsample=2, model='hog') # For GPU, use model='cnn'\r\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations, num_jitters=2)\r\n print(face_encodings)\r\n\r\n face_names = []\r\n for face_encoding in face_encodings:\r\n # See if the face is a match for the known face(s)\r\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.6) # Lower is more strict, default = 0.6\r\n name = \"Unknown\"\r\n\r\n # # If a match was found in known_face_encodings, just use the first one.\r\n # if True in matches:\r\n # first_match_index = matches.index(True)\r\n # name = known_face_names[first_match_index]\r\n\r\n # Or instead, use the known face with the smallest distance to the new face\r\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\r\n best_match_index = np.argmin(face_distances)\r\n if matches[best_match_index]:\r\n name = known_face_names[best_match_index]\r\n #print(name)\r\n\r\n face_names.append(name)\r\n \r\n process_this_frame = not process_this_frame\r\n\r\n\r\n # Display the results\r\n for (top, right, bottom, left), name in zip(face_locations, face_names):\r\n # Scale back up face locations since the frame we detected in was scaled to 1/12 size\r\n print(\"999\",name,attendance)\r\n \r\n top *= 12\r\n right *= 12\r\n bottom *= 12\r\n left *= 12\r\n\r\n # Draw a box around the face\r\n \r\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\r\n if name!=\"\" and name not in attendance:\r\n name2=re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")\r\n\r\n datestamp=int( time.time() )\r\n attendance[name]=datestamp\r\n cv2.imwrite(work_folder+\"%s_%s.jpg\" % (datestamp,name2), frame)\r\n if name2 not in recognizedFace:\r\n recognizedFace.append(name2)\r\n cv2.imwrite(work_folder+\"%s.jpg\" % name2, frame)\r\n \r\n \r\n outfile2=open(\"image_login.csv\",\"w+\")\r\n \r\n \r\n outfile2.write(\"Name,Time\\n\")\r\n\r\n for name in known_face_names:\r\n if name in attendance:\r\n outfile2.write(\"%s,%s\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\"),attendance[name]) )\r\n else:\r\n outfile2.write(\"%s,99999\\n\" % (re.split(\"\\\\\\\\\",name)[-1].replace(\"_NUS\",\"\")) )\r\n outfile2.close()\r\n\r\n\r\n # Draw a label with a name below the face\r\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 5.0, (0, 0, 0), 5)\r\n\r\n # Display the resulting image\r\n cv2.imshow('Video', frame)\r\n #refresh after 12 hrs\r\n for name in attendance:\r\n if attendance[name] 250:\n await client.delete_message(message) \n return\n if is_duplicate(message):\n await client.delete_message(message)\n return\n await sleepMode(message.author,config.SlowmodeTime)\n \n await client.process_commands(message) #Makes sure to process the command\n\ninitial_extensions = [\n 'cmds.ClientOwnerOnly',\n 'cmds.ModeratorOnly',\n 'cmds.UserAccessible'\n]\n\nif __name__ == '__main__': #Loads commands/extensions\n for extension in initial_extensions:\n try:\n client.load_extension(extension)\n print(\"Loaded extension\")\n except Exception as e:\n print(f'Failed to load extension {extension}.', file=sys.stderr)\n traceback.print_exc()\n\nclient.loop.create_task(post_tweets())\nclient.run(os.environ.get('TOKEN'))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"464385969","text":"import bson, jwt\n\nfrom flask import (\n Blueprint,\n url_for,\n request,\n session\n)\n\nfrom helper import _send_list_JSON, client\n\nuserRouter = Blueprint('userRouter', __name__)\n\ndb = client['totlist']\n\n@userRouter.route('/api/auth', methods=['POST'])\ndef login():\n jsonbody = request.get_json()\n document = dict()\n try:\n document[\"id\"] = str(db.users.find_one(jsonbody)[\"_id\"])\n session[\"WebAPIToken\"] = document[\"id\"]\n encoded = jwt.encode(document, 'secret', algorithm='HS256')\n\n return _send_list_JSON({\"WebAPIToken\": encoded})\n except:\n return _send_list_JSON({\"error\": \"Login into system please\"}, 403)\n\n@userRouter.route('/api/auth/out', methods=['GET'])\ndef get_token():\n session.pop(\"WebAPIToken\", None)\n\n return _send_list_JSON({\"message\": \"User logged out\"})\n\n@userRouter.route('/api/user/add', methods=['POST'])\ndef add_new_user():\n jsonbody = request.get_json()\n if (\"username\" in jsonbody) and (\"password\" in jsonbody):\n result = db.users.insert_one(jsonbody)\n\n document = dict()\n document = db.users.find_one({\"_id\": result.inserted_id})\n document[\"id\"] = str(document[\"_id\"])\n del document[\"_id\"]\n\n return _send_list_JSON(document, 201)\n","sub_path":"routes/userapp.py","file_name":"userapp.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"414555136","text":"from django.shortcuts import render, redirect\nfrom part.forms import sukucadangForm\nfrom part.models import Sukucadang\n\n# from Sukucadang\n\ndef emp(request): \n if request.method == \"POST\": \n form = sukucadangForm(request.POST) \n if form.is_valid(): \n try: \n form.save() \n return redirect('/show') \n except: \n pass \n else: \n form = sukucadangForm() \n return render(request,'index.html',{'form':form}) \ndef show(request):\n datas = Sukucadang.objects.all()\n return render(request, \"show.html\", {\n 'datas': datas\n })\ndef edit(request, id):\n data = Sukucadang.objects.get(id=id)\n return render(request, 'edit.html', {\n 'data': data\n })\ndef update(request, id):\n data = Sukucadang.objects.get(id=id)\n form = sukucadangForm(request.POST, instance = data)\n if form.is_valid(): \n form.save() \n return redirect(\"/show\") \n return render(request, 'edit.html', {\n 'data': data\n }) \ndef destroy(request, id):\n data = Sukucadang.objects.get(id=id)\n data.delete()\n return redirect(\"/show\")\n\n# menu view\n\ndef menu(request):\n data = Sukucadang.objects.all()\n return render(request, \"menu.html\", {\n 'data': data\n })\n\n","sub_path":"Novice/04-03/sparepart/part/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"115893243","text":"class TripDetailsPage:\n\n def __init__(self, driver):\n self.driver = driver\n self._trip_details_form = None\n self._route_information = None\n self._header_navigation = None\n\n @property\n def trip_details_form(self):\n if self._trip_details_form is None:\n from trip_details_form import TripDetailsForm\n self._trip_details_form = TripDetailsForm(self.driver)\n return self._trip_details_form\n\n @property\n def route_information(self):\n if self._route_information is None:\n from route_information import RouteInformation\n self._route_information = RouteInformation(self.driver)\n return self._route_information\n\n @property\n def header_navigation(self):\n if self._header_navigation is None:\n from header_navigation import HeaderNavigation\n self._header_navigation = HeaderNavigation(self.driver)\n return self._header_navigation\n\n def open(self, url):\n self.driver.get(url)\n","sub_path":"trip_details_page.py","file_name":"trip_details_page.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"485950031","text":"from ecdsa import SigningKey, VerifyingKey, NIST192p\nimport ecdsa\nimport hashlib\n\nfrom cilantro.wallets import Wallet\n\nclass BasicWallet(Wallet):\n def __init__(self, s=None):\n if s == None:\n self.s, self.v = BasicWallet.new()\n else:\n self.s, self.v = BasicWallet.format_to_keys(s)\n self.s, self.v = BasicWallet.keys_to_format(self.s, self.v)\n\n @staticmethod\n def generate_keys():\n # generates a tuple keypair\n s = SigningKey.generate()\n v = s.get_verifying_key()\n return s, v\n\n @staticmethod\n def keys_to_format(s, v):\n # turns binary data into desired format\n s = s.to_string()\n v = v.to_string()\n return s.hex(), v.hex()\n\n @staticmethod\n def format_to_keys(s):\n # returns the human readable format to bytes for processing\n s = bytes.fromhex(s)\n\n # and into the library specific object\n s = SigningKey.from_string(s, curve=NIST192p)\n v = s.get_verifying_key()\n return s, v\n\n @staticmethod\n def new():\n # interface to creating a new wallet\n s, v = generate_keys()\n return keys_to_format(s, v)\n\n\n @staticmethod\n def sign(s, msg):\n (s, v) = format_to_keys(s)\n signed_msg = s.sign(msg, hashfunc=hashlib.sha1, sigencode=ecdsa.util.sigencode_der)\n return signed_msg.hex()\n\n @staticmethod\n def verify(v, msg, sig):\n v = bytes.fromhex(v)\n v = VerifyingKey.from_string(v, curve=NIST192p)\n try:\n return v.verify(bytes.fromhex(sig), msg, hashfunc=hashlib.sha1, sigdecode=ecdsa.util.sigdecode_der)\n except:\n return False","sub_path":"cilantro/wallets/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"448549632","text":"# when stop, put pause as status, and pick up them when starting again\nimport os, logging, datetime, copy, json\nfrom app import consts, errors\n\nlog = logging.getLogger(__name__)\n\n\nclass InfoFile(object):\n def __init__(self, fn, data, mongo, app=None, TESTFLAG=None):\n self.QUEUES = consts.WORKERQUEUES\n if mongo:\n self.error = errors.VainamoinenError(mongo, app=app, TESTFLAG=TESTFLAG)\n self.mongo = mongo\n self.fn = fn\n self.data = data\n self.rawfiles = []\n self.status = 'new'\n\n# def load_metadata_from_file(self):\n# self.data = self.load_json( os.path.join(self.location, self.fn) )\n# if self.data:\n# self.mark_file('processing')\n# log.debug('Infofile JSON ok, moving to tmp dir')\n# self.move_infofile(self.TMP_INFOFILE_DIR, self.fn)\n# else: # bad JSON in infofile, mark as invalid file\n# self.status = 'invalid'\n# self.move_infofile(self.location, 'invalid_{0}'.format(self.fn) )\n\n def load_metadata_from_dbrecord(self, dbrecord):\n self.location = consts.TMP_INFOFILE_DIR\n self.fn = dbrecord['infofilename']\n self.status = dbrecord['status']\n self.data = self.load_json(os.path.join(self.location, self.fn)) \n \n def load_json(self, fn):\n # FIXME Metadatahandler should fix this, or utility method\n try:\n with open(fn) as fp:\n return json.load(fp)\n except ValueError:\n log.error('JSON could not be parsed from file {0}'.format(fn), exc_info=True)\n self.error.glitch('glitch error', 'JSON unparsable in infofile.')\n return False\n \n def write_rawfiles_to_db(self):\n # FIXME should be metadatahandler method.\n for rawfile in self.rawfiles:\n log.info('Writing rawfile {0} to DB'.format(rawfile.metadata['filename']))\n self.mongo.run('insert', 'files', rawfile.metadata)\n\n def process_files(self):\n # add queue variables to files\n for fn in self.data['files']:\n if 'extension' in self.data['files'][fn]:\n fullfn = fn + self.data['files'][fn]['extension']\n else:\n fullfn = fn\n self.rawfiles.append( RawFile(fullfn, self.fn, self.data['metadata'],\n self.data['files'][fn], self.QUEUES, consts.UPLOAD_DIR) )\n log.info('Checking if raw files specified in infofile {0} exist on '\n 'server'.format(self.fn))\n self.nonexisting = []\n for rf in self.rawfiles:\n if not rf.check_exist():\n self.nonexisting.append(rf.fn)\n \n def report_nonexisting(self):\n if self.nonexisting:\n self.mark_file('waiting')\n msg = \"\"\"Your infofile {0} contained references to files that do not exist.\n Processing of will be paused for {1} days in order for the files to\n be generated. After this your file will be\n deleted.\"\"\".format(self.fn, consts.RAWFILES_TIMELIMIT)\n log.info('Infofile with non-existing file(s) encountered. Marking waiting.')\n #self.error.user(self.fn, '\\n'.join(self.nonexisting), 'Files do not exist', msg)\n else:\n log.info('All raw files found.')\n\n def mark_file(self, status):\n self.status = status\n self.data['general_info']['status'] = status\n\n\nclass RawFile(object):\n def __init__(self, fn, infofn, meta, outliermeta, queues, updir):\n self.metadata = copy.deepcopy(meta)\n self.starttime = datetime.datetime.now()\n self.fn = fn\n self.upload_dir = updir\n for x in outliermeta:\n self.metadata[x] = outliermeta[x]\n self.metadata['filename'] = fn\n self.metadata['infofilename'] = infofn\n for queue in queues:\n self.metadata[queue] = None\n\n def check_exist(self):\n return os.path.exists(os.path.join(self.upload_dir, self.fn) )\n \n \n","sub_path":"app/infofile.py","file_name":"infofile.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"471440681","text":"# ОДЗ: если максимальных элементов несколько, то удаляем все нулевые элементы после первого.\n# Например, [1, 5, 1, 0, 1, 5, 0 ]. Первое встреченное число 5 - это максимальный\n# После него все удаляем. Второе число 5 - тоже максимальный элемент, но условие удаления элементов уже выполнено\n# для первого максимального элемента.\n\n# l = []\n# l = [1, 0, 1, 1, 1] # [1, 1, 1, 1]\n# l = [1, 1, 1, 1, 0] # [1, 1, 1, 1]\n# l = [3, 4, 5, 0, 0, 0, 5] # [3, 4, 5, 5]\nl = [3, 4, 5, 0, 0, 0, 5, 6] # [3, 4, 5, 0, 0, 0, 5, 6]\n\ndef remove_zero_elements(l):\n\n try:\n max_element = max(l)\n except ValueError: # l is an empty sequence.\n return l\n\n try:\n max_element_position = l.index(max_element)\n except ValueError:\n return l\n\n left_list_including_max_element = l[:max_element_position+1]\n right_list = l[max_element_position+1:]\n\n cleared_right_list = [x for x in right_list if x != 0]\n\n united_list = left_list_including_max_element + cleared_right_list\n\n return united_list\n\n\nprint(remove_zero_elements(l))\n","sub_path":"1d.py","file_name":"1d.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"308810540","text":"#Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\r\n\r\nnum1=int(input('Digite o primeiro numero '))\r\nnum2=int(input('Digite o primeiro numero '))\r\nnum3=int(input('Digite o primeiro numero '))\r\n\r\n#verificando quem é menor\r\nmenor = num1\r\nif num2< num1 and num2 < num3:\r\n menor=num2\r\nif num3< num1 and num3 < num2:\r\n menor=num3\r\n\r\n#Verificando o maior\r\nmaior = num1\r\nif num2> num1 and num2 > num3:\r\n maior=num2\r\nif num3> num1 and num3 > num2:\r\n maior=num3\r\n\r\nprint('O num maior e menor são repectivamente {} e {}'.format(menor,maior))","sub_path":"ex033_MaiorEMenorValor.py","file_name":"ex033_MaiorEMenorValor.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"576945142","text":"#Team Choosers\n\n#Imports random library\nfrom random import choice\n\n\nplayers = []\nteamA = []\nteamB = []\nexitThis = 0\ncommand = 0\n\n#Functions\ndef choosePlayers(action):\n #Input Players\n done = 0\n while done == 0:\n\n if action == 'add':\n player = input(\"player(\" + str(len(players) + 1) + \")(Type 'done' when done): \")\n elif action == 'remove':\n player = input(\"Player to remove(Type 'done' when done):\")\n \n if player.lower() == 'done':\n done = 1 \n elif player == \"\":\n print(\"Please type in a name.\") \n else:\n if action == 'add':\n players.append(player) \n elif action == 'remove':\n players.remove(player)\n\ndef randomizeTeams():\n teamA = []\n teamB = []\n #Creates teams in loop\n while len(players) > 0:\n\n playerA = choice(players)\n teamA.append(playerA)\n players.remove(playerA)\n\n playerB = choice(players)\n teamB.append(playerB)\n players.remove(playerB)\n\n #Shows teams\n print(\"Team A: \" + str(teamA))\n print(\"Team B: \" + str(teamB))\n\n for player in teamA:\n players.append(player)\n\n for player in teamB:\n players.append(player)\n\n teamA = []\n teamB = []\n\ndef removePlayers():\n done = 0\n while done == 0:\n\n player = input(\"Player to remove (Type 'done' when done): \")\n\n if player.lower() == 'done':\n done = 1 \n elif player == \"\":\n print(\"Please type in a name.\") \n else:\n players.remove(player)\n \nwhile choice != 3:\n \n #initial Prompt\n command = input(\"(1) add, (2) randomize teams, (3) exit, (4) remove, (5) Show players: \")\n\n if command == \"1\":\n choosePlayers('add')\n elif command == \"2\":\n randomizeTeams()\n elif command == \"3\":\n exit()\n elif command == \"4\":\n choosePlayers('remove')\n elif command == \"5\":\n print(players)\n\n\n \n \n\n \n\n\n \n","sub_path":"Website Projects/team_chooser.py","file_name":"team_chooser.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"92290549","text":"import re\n\nfrom explanations.colorize_tex import (\n colorize_citations,\n colorize_equation_tokens,\n colorize_equations,\n)\nfrom explanations.types import TokenWithOrigin\n\nCOLOR_PATTERN = (\n r\"\\\\llap{\"\n + r\"\\\\pdfcolorstack0 push {[0-9.]+ [0-9.]+ [0-9.]+ rg [0-9.]+ [0-9.]+ [0-9.]+ RG}}\"\n + r\"(.*?)\"\n + r\"\\\\llap{\"\n + r\"\\\\pdfcolorstack0 pop}\"\n)\n\n\ndef test_color_citations():\n tex = \"word.~\\\\cite{source1,source2}\"\n colorized, citations = next(colorize_citations(tex))\n assert colorized.startswith(\"word.~\")\n print(colorized)\n matches = re.findall(COLOR_PATTERN, colorized)\n assert matches[0] == \"\\\\cite{source1,source2}\"\n assert len(citations) == 1\n assert citations[0].keys == [\"source1\", \"source2\"]\n\n\ndef test_disable_hyperref_colors():\n tex = \"\\n\".join(\n [\"\\\\usepackage[colorlinks=true,citecolor=blue]{hyperref}\", \"\\\\cite{source}\"]\n )\n colorized, _ = next(colorize_citations(tex))\n assert \"colorlinks=false\" in colorized\n\n\ndef test_color_equations():\n tex = \"$eq1$ and $eq2$\"\n colorized, equations = next(colorize_equations(tex))\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 2\n assert matches[0] == \"eq1\"\n assert matches[1] == \"eq2\"\n\n equation0_info = equations[0]\n assert isinstance(equation0_info.hue, float)\n assert equation0_info.tex == \"eq1\"\n assert equation0_info.i == 0\n\n\ndef test_color_equation_in_argument():\n tex = \"\\\\caption{$eq1$}\"\n colorized, _ = next(colorize_equations(tex))\n assert colorized.startswith(\"\\\\caption\")\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 1\n assert matches[0] == \"eq1\"\n\n\ndef test_color_tokens():\n file_contents = {\"file\": \"$ignore$ $x + y$\"}\n tokens = [\n TokenWithOrigin(\n tex_path=\"file\", equation_index=1, token_index=0, start=0, end=1, text=\"x\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=1, token_index=1, start=4, end=5, text=\"y\"\n ),\n ]\n colorized_files, _ = next(colorize_equation_tokens(file_contents, tokens))\n colorized = colorized_files[\"file\"]\n assert colorized.startswith(\"$ignore$\")\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 2\n assert matches[0] == \"x\"\n assert matches[1] == \"y\"\n\n\ndef test_color_subscripts():\n file_contents = {\"file\": \"$x_i x^i x\\\\sp1 x\\\\sb1$\"}\n tokens = [\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=0, start=2, end=3, text=\"i\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=1, start=6, end=7, text=\"i\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=2, start=12, end=13, text=\"1\"\n ),\n TokenWithOrigin(\n tex_path=\"file\", equation_index=0, token_index=3, start=18, end=19, text=\"1\"\n ),\n ]\n colorized_files, _ = next(colorize_equation_tokens(file_contents, tokens))\n colorized = colorized_files[\"file\"]\n matches = re.findall(COLOR_PATTERN, colorized)\n assert len(matches) == 4\n # Subscript and superscript commands must also be wrapped in the coloring commands\n assert matches[0] == \"_i\"\n assert matches[1] == \"^i\"\n assert matches[2] == \"\\\\sp1\"\n assert matches[3] == \"\\\\sb1\"\n","sub_path":"data-processing/tests/test_colorize_tex.py","file_name":"test_colorize_tex.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"76880464","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n**renameUdimToMariNames.py**\n\n**Platform:**\n\tWindows.\n\n**Description:**\n\tCombines UVs shells siblings images.\n\n**Others:**\n\tTODO: Refactor _get'Nuke'Node using \\*\\*kwargs for optional arguments.\n\"\"\"\n\n#**********************************************************************************************************************\n#***\tExternal imports.\n#**********************************************************************************************************************\nimport glob\nimport inspect\nimport os\nimport optparse\nimport sys\nimport re\n\n#**********************************************************************************************************************\n#***\tInternal imports.\n#**********************************************************************************************************************\n\n#**********************************************************************************************************************\n#***\tModule attributes.\n#**********************************************************************************************************************\n__author__ = \"Thomas Mansencal\"\n__copyright__ = \"Copyright (C) 2010 - 2012 - Thomas Mansencal\"\n__license__ = \"GPL V3.0 - http://www.gnu.org/licenses/\"\n__maintainer__ = \"Thomas Mansencal\"\n__email__ = \"thomas.mansencal@gmail.com\"\n__status__ = \"Production\"\n\n__all__ = [\"UDIM_FILTER\" , \"getMariPatchNumberFromUdim\", \"getCommandLineParametersParser\", \"renameUdimToMariNames\"]\n\nUDIM_FILTER = \"u\\d+_v\\d+\"\n\n#**********************************************************************************************************************\n#***\tModule classes and definitions.\n#**********************************************************************************************************************\ndef getMariPatchNumberFromUdim(udim):\n\t\"\"\"\n\tThis definition gets Mari patch number from Udim.\n\n\t:param udim: Udim to convert. ( String )\n\t:return: Mari patch. ( Integer )\n\t\"\"\"\n\n\tu, v = (int(value[1:]) for value in udim.split(\"_\"))\n\treturn 1000 + u + 1 + v *10\n\ndef getCommandLineParametersParser():\n\t\"\"\"\n\tThis definition returns the command line parameters parser.\n\n\t:return: Parser. ( Parser )\n\t\"\"\"\n\n\tparser = optparse.OptionParser(formatter=optparse.IndentedHelpFormatter (indent_increment=2, max_help_position=8, width=128, short_first=1), add_help_option=None)\n\n\tparser.add_option(\"-h\", \"--help\", action=\"help\", help=\"'Display this help message and exit.'\")\n\tparser.add_option(\"-f\", \"--filesExtensions\", action=\"store\", type=\"string\", dest=\"filesExtensions\", default=\"psd\", help=\"'Files extensions to rename'.\")\n\tparser.add_option(\"-s\", \"--sourceDirectory\", action=\"store\", type=\"string\", dest=\"sourceDirectory\", default=os.getcwd(), help=\"'Source directory.\")\n\tparser.add_option(\"-r\", \"--renamePrefix\", action=\"store\", type=\"string\", dest=\"renamePrefix\", help=\"'Rename prefix.\")\n\t\n\treturn parser\n\ndef renameUdimToMariNames(parameters, arguments):\n\t\"\"\"\n\tThis definition renames Udim matched files to Mari patch number files.\n\n\t:param udim: Udim to convert. ( String )\n\t:param parameters: Command line parameters. ( Object )\n\t:param arguments: Command line arguments. ( Object )\n\t:return: Definition success. ( Boolean )\n\t\"\"\"\n\n\tif os.path.exists(parameters.sourceDirectory):\n\t\tfiles = glob.glob(\"{0}/*{1}\".format(parameters.sourceDirectory, parameters.filesExtensions))\n\t\tfor file in files:\n\t\t\tsearch = re.search(r\"({0})\".format(UDIM_FILTER), file)\n\t\t\tif not search:\n\t\t\t\tcontinue\n\t\t\tpatchNumber = getMariPatchNumberFromUdim(search.group(0))\n\t\t\tif parameters.renamePrefix:\n\t\t\t\tname = \"{0}{1}.{2}\".format(parameters.renamePrefix, str(patchNumber), parameters.filesExtensions)\n\t\t\telse:\n\t\t\t\tname = re.sub(r\"({0})\".format(UDIM_FILTER), str(patchNumber), file)\n\t\t\t\n\t\t\tprint(\"'{0}' | Rename '{1}' file to '{2}'.\".format(inspect.getmodulename(__file__),file, name))\n\t\t\tos.rename(file, name)\n\t\treturn True\n\n#**********************************************************************************************************************\n#*** Launcher.\n#**********************************************************************************************************************\nif __name__ == \"__main__\":\n\tparameters, arguments = getCommandLineParametersParser().parse_args(sys.argv)\n\trenameUdimToMariNames(parameters, arguments)\n","sub_path":"src/others/renameUdimToMariNames.py","file_name":"renameUdimToMariNames.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"295287643","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\ndef show_images(images, opts, name=None):\n images = np.reshape(images, [images.shape[0], -1]) # images reshape to (batch_size, D)\n sqrtn = int(np.ceil(np.sqrt(images.shape[0])))\n\n fig = plt.figure(figsize=(sqrtn, sqrtn))\n gs = gridspec.GridSpec(sqrtn, sqrtn)\n gs.update(wspace=0.05, hspace=0.05)\n\n for i, img in enumerate(images):\n ax = plt.subplot(gs[i])\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_aspect('equal')\n plt.imshow(img.reshape([opts.image_shape, opts.image_shape, opts.channel]))\n if name != None:\n plt.savefig(name)\n return\n\ndef preprocess_img(x):\n return 2 * x - 1.0\n\ndef deprocess_img(x):\n return (x + 1.0) / 2.0\n\ndef rel_error(x,y):\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef black_out(image, width=3):\n '''\n Blacks out everything in the image except for the top left quadrant\n :param image: Numpy array\n :return:\n '''\n\n h = image.shape[1]\n w = image.shape[2] // 2\n\n mask = np.zeros(image.shape, np.float32)\n\n mask[:, 0: h, w - width: w + width, :] = image[:, 0: h, w - width: w + width, :]\n\n return mask\n\ndef plotter(env_name, num_episodes, rewards_list, ylim):\n '''\n Used to plot the average over time\n :param env_name:\n :param num_episodes:\n :param rewards_list:\n :param ylim:\n :return:\n '''\n x = np.arange(0, num_episodes)\n y = np.asarray(rewards_list)\n plt.plot(x, y)\n plt.ylim(top=ylim + 10)\n plt.xlabel(\"Number of Episodes\")\n plt.ylabel(\"Avg Rewards Last 100 Episodes\")\n plt.title(\"Rewards Over Time For %s\" %env_name)\n plt.savefig(\"progress.png\")\n plt.close()\n\ndef raw_score_plotter(scores):\n '''\n used to plot the raw score\n :param scores:\n :return:\n '''\n\n plt.plot(np.arange(len(scores)), scores)\n plt.ylabel('Train Loss')\n plt.xlabel('Number of Iterations')\n plt.title(\"Loss Over Time\")\n plt.savefig(\"Train_Loss.png\")\n plt.close()\n","sub_path":"Car_Mask_TF/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"129596527","text":"from operator import itemgetter\n\n\ndef fcfs(data):\n process = {}\n process['table'] = data\n process['gantt'] = []\n\n n = len(data)\n time = 0\n left = n\n average_tat = 0\n average_wt = 0\n\n process['table'] = sorted(process['table'], key=itemgetter('at'))\n x = process['table']\n time = x[0]['at']\n proc = 0 #current process\n temp={}\n\n for i in range(n):\n temp = {}\n temp['no'] = i + 1\n if time >= x[i]['at']:\n temp['start'] = time\n else:\n time = x[i]['at']\n temp['start'] = time\n time += x[i]['bt']\n temp['stop'] = time\n process['gantt'].append(temp)\n \n return process\n","sub_path":"src/fcfs.py","file_name":"fcfs.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"31192788","text":"from flask import Flask, render_template, g, redirect, request, url_for\r\nfrom werkzeug import secure_filename\r\nfrom secure import adminpassword\r\nimport sqlite3\r\nimport os\r\nimport re\r\nfrom random import randint\r\napp = Flask(__name__)\r\n\r\ndatabase = '/crassis/crassis-site/comics'\r\nupload = '/crassis/crassis-site/static/images'\r\n\r\napp.config['UPLOAD_FOLDER'] = upload\r\n\r\n@app.before_request\r\ndef before_request():\r\n\tg.db = sqlite3.connect(database)\r\n\r\n@app.teardown_request\r\ndef teardown_request(exception):\r\n\tif hasattr(g, 'db'):\r\n\t\tg.db.close()\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n\tcomic = g.db.execute(\"SELECT * FROM comics ORDER BY id DESC LIMIT 1\").fetchone()\r\n\tlatest = g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0]\r\n\treturn render_template(\"index.html\", comic=comic, latest=latest)\r\n\r\n@app.route(\"/\")\r\ndef comic(comic_id):\r\n\tcomic = g.db.execute(\"SELECT * FROM comics ORDER BY id ASC LIMIT 1 OFFSET ?\", str(comic_id - 1)).fetchone()\r\n\tlatest = g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0]\r\n\treturn render_template(\"index.html\", comic=comic, latest=latest)\r\n\r\n@app.route(\"/random/\")\r\ndef random(current):\r\n\tlatest = int(g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0])\r\n\trandom = randint(1, latest)\r\n\twhile random == current:\r\n\t\trandom = randint(1, latest)\r\n\treturn redirect(\"http://crassis.me/%s\" % str(random))\r\n\r\n@app.route(\"/dashboard\")\r\ndef dashboard():\r\n\tcomics = g.db.execute(\"SELECT * FROM comics ORDER BY id DESC\").fetchall()\r\n\treturn render_template(\"dashboard.html\", comics=comics)\r\n\r\n@app.route(\"/dashboard/edit/\", methods=[\"GET\", \"POST\"])\r\ndef edit(comic_id):\r\n\ttry:\r\n\t\tif request.method == \"POST\" and request.form['password'] == adminpassword:\r\n\t\t\tif 'delete' in request.form:\r\n\t\t\t\timage = g.db.execute(\"SELECT url FROM comics WHERE id=?\", (str(comic_id))).fetchone()[0]\r\n\t\t\t\ttry:\r\n\t\t\t\t\tpath = re.sub(\"http://www.crassis.me/\", \"\", image)\r\n\t\t\t\t\timage = \"/crassis/crassis-site/\" + path\r\n\t\t\t\t\tos.remove(image)\r\n\t\t\t\texcept Exception as e:\r\n\t\t\t\t\tpass\r\n\t\t\t\tg.db.execute(\"DELETE FROM comics WHERE id=?\", (str(comic_id)))\r\n\t\t\tprint(\"2\")\r\n\t\t\ttitle = request.form['title']\r\n\t\t\talt = request.form['alt']\r\n\t\t\timage = request.files['file']\r\n\t\t\tif image:\r\n\t\t\t\tfilename = secure_filename(image.filename)\r\n\t\t\t\tpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\r\n\t\t\t\timage.save(path)\r\n\t\t\t\turl = \"http://www.crassis.me/static/images/\" + filename\r\n\t\t\t\tg.db.execute(\"UPDATE comics SET title=?, alt=?, url=? WHERE id=?\", (title, alt, url, str(comic_id)))\r\n\t\t\telse:\r\n\t\t\t\tg.db.execute(\"UPDATE comics SET title=?, alt=? WHERE id=?\", (title, alt, str(comic_id)))\r\n\t\t\tg.db.commit()\r\n\t\t\treturn redirect(url_for(\"dashboard\"))\r\n\t\telse:\r\n\t\t\tcomic = g.db.execute(\"SELECT * FROM comics WHERE id=?\", str(comic_id)).fetchone()\r\n\t\t\tif comic is None:\r\n\t\t\t\treturn redirect(\"http://crassis.me/anus\")\r\n\t\t\treturn render_template(\"edit.html\", comic=comic)\r\n\texcept Exception as e:\r\n\t\treturn str(e)\r\n\r\n@app.route(\"/upload\", methods=[\"GET\", \"POST\"])\r\ndef upload():\r\n\ttry:\r\n\t\tif request.method == \"POST\":\r\n\t\t\tpassword = request.form['password']\r\n\t\t\tif password != adminpassword:\r\n\t\t\t\treturn redirect(\"http://crassis.me/anus\")\r\n\t\t\timage = request.files['file']\r\n\t\t\tif image:\r\n\t\t\t\tlatest = int(g.db.execute(\"SELECT id FROM comics ORDER BY id DESC LIMIT 1\").fetchone()[0])\r\n\t\t\t\tfilename = str(latest + 1)\r\n\t\t\t\tpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\r\n\t\t\t\timage.save(path)\r\n\t\t\t\turl = \"http://www.crassis.me/static/images/\" + filename\r\n\t\t\t\ttitle = request.form['title']\r\n\t\t\t\talt = request.form['alt']\r\n\t\t\t\tg.db.execute(\"INSERT INTO comics (title, alt, url) VALUES (?, ?, ?)\", (title, alt, url))\r\n\t\t\t\tg.db.commit()\r\n\t\t\t\treturn redirect(url_for(\"index\"))\r\n\t\t\treturn \"no image found cuh\"\r\n\t\telse:\r\n\t\t\treturn render_template(\"upload.html\")\r\n\texcept Exception as e:\r\n\t\treturn str(e)\r\n\r\n\r\n\r\n@app.errorhandler(404)\r\n@app.errorhandler(500)\r\ndef fourohfour(error):\r\n\treturn \"crassis denies your request\"","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"231546758","text":"'''\r\n爬图片\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=0\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=20\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=40\r\nhttps://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=60\r\n爬排名\r\nhttps://movie.douban.com/top250?start=0&filter=\r\nhttps://movie.douban.com/top250?start=25&filter=\r\n'''\r\nimport re\r\nimport random\r\nimport requests\r\ndef hearder():\r\n agent1 = \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\"\r\n agent2 = \"Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3\"\r\n agent3 = \"Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0\"\r\n agent4 = \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727\"\r\n list = [agent1, agent2, agent3, agent4]\r\n agent = random.choice(list)\r\n header = {\"User-Agent\": agent}\r\n return header\r\n\r\ndef urllist(start,end):\r\n urllist = []\r\n for ye in range(end+1):\r\n if ye>=start:\r\n url = 'https://movie.douban.com/top250?start='+str((ye-1)*25)+'&filter='\r\n urllist.append(url)\r\n return urllist\r\n\r\n\r\ndef info(urllist1):\r\n movienamelist = []\r\n pngnamelist = []\r\n for url in urllist1:\r\n response = requests.get(url,headers = header).content.decode()\r\n pat1 =re.compile(r'
')\r\n data=pat1.findall(response)\r\n for movie in data:\r\n movienamelist.append(movie)\r\n pat2 =re.compile(r'
')\r\n data2 = pat2.findall(response)\r\n for png in data2:\r\n pngnamelist.append(png)\r\n return movienamelist,pngnamelist\r\n\r\ndef loadmovie(movienamelist,pngnamelist):\r\n for i in range(len(movienamelist)):\r\n moviepng = requests.get(pngnamelist[i], headers=header).content\r\n with open(\"E:/爬虫练习文件夹/电影流弊gasp/\"+\"排行榜第\"+str(i+1)+\"部\"+movienamelist[i]+\".jpg\",\"wb\") as f:\r\n print(\"正在下载第{}张图片\".format(i+1))\r\n f.write(moviepng)\r\n print(\"第{}张图片下载完成\".format(i+1))\r\n\r\nif __name__ == '__main__':\r\n start = int(input(\"请输入起始页\"))\r\n end = int(input(\"输入终止页\"))\r\n header = hearder()\r\n urllist1 = urllist(start,end)\r\n movienamelist, pngnamelist = info(urllist1)\r\n loadmovie(movienamelist,pngnamelist)\r\n","sub_path":"python网络爬虫/正则表达式/爬取豆瓣电影.py","file_name":"爬取豆瓣电影.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"532810025","text":"__author__ = 'KentChum'\n#encoding = utf8\nfrom flask import Flask\nimport os\nimport re\nimport json\nimport sqlite3\nimport ipdb\nimport time\nfrom LogHelper import LogHelper\n\napp = Flask(__name__)\n\napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, 'ipdb.db'),\n DEBUG=True,\n))\n\n\n@app.route('/ip/')\ndef getIp(ip):\n #ipv4\n timelist = [time.time()]\n timelist = LogHelper(timelist, 'loadings')\n ipv4pattern = r\"\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b\"\n ipv6pattern = r\"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^:((:[0-9a-fA-F]{1,4}){1,6}|:)$|^[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,5}|:)$|^([0-9a-fA-F]{1,4}:){2}((:[0-9a-fA-F]{1,4}){1,4}|:)$|^([0-9a-fA-F]{1,4}:){3}((:[0-9a-fA-F]{1,4}){1,3}|:)$|^([0-9a-fA-F]{1,4}:){4}((:[0-9a-fA-F]{1,4}){1,2}|:)$|^([0-9a-fA-F]{1,4}:){5}:([0-9a-fA-F]{1,4})?$|^([0-9a-fA-F]{1,4}:){6}:$\"\n result = None\n if re.match(ipv4pattern, ip) or re.match(ipv6pattern, ip):\n\n if re.match(ipv4pattern, ip):\n target = ipdb.Ipv42Int(ip)\n else:\n target = ipdb.Ipv62Int(ip)\n\n timelist = LogHelper(timelist, 'regex in')\n conn = sqlite3.connect(app.config['DATABASE'])\n cur = conn.cursor()\n #querydb = \"select cc,start from ipdata WHERE \" + str(target) + \" between min_number and max_number\"\n #querydb = \"select cc,start from ipdata WHERE \" + str(target) + \" >= min_number and \" + str(target) + \"<= max_number limit 1\"\n #querydb = \"select cc,start from ipdata WHERE 2921193021 >= min_number and 2921193021 <= max_number\"\n querydb = \"select cc,start from (select cc,start,max_number from ipdata where \" + str(\n target) + \" >= min_number order by min_number desc limit 1) WHERE \" + str(target) + \" <=max_number\"\n\n cur.execute(querydb)\n rs = cur.fetchall()\n\n timelist = LogHelper(timelist, 'reading db')\n if not rs:\n result = {'status': 404,\n 'result': None,\n 'info': 'Not found!'}\n else:\n result = {'status': 200,\n 'result': rs[0],\n 'info': 'Ip found!'}\n else:\n result = {'status': 403,\n 'result': None,\n 'info': 'Invalid ip!'}\n\n timelist = LogHelper(timelist, 'end')\n return json.dumps(result)\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"apnicip.py","file_name":"apnicip.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"278807689","text":"import logging\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nfrom core.mailer import get_mailer\nfrom erp.models import Erp\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n now = timezone.now()\n help = (\n \"Envoie une notification de rappel aux utilisateurs ayant commencé le remplissage d'une fiche sans la publier\"\n )\n\n def __init__(self, *args, **kwargs):\n if kwargs.get(\"now\"):\n self.now = kwargs[\"now\"]\n del kwargs[\"now\"]\n super().__init__(*args, **kwargs)\n\n def handle(self, *args, **options):\n if not settings.REAL_USER_NOTIFICATION:\n print(\"Launched only if settings.REAL_USER_NOTIFICATION is True.\")\n return\n\n notifications = self.get_notifications()\n sent_ok = 0\n for notification in notifications:\n sent_ok += 1 if self.send_notification(notification) else 0\n\n logger.info(f\"{sent_ok}/{len(notifications)} relance(s) d'ERP(s) non-publié(s)\")\n\n def get_notifications(self):\n notifications = {}\n since = self.now - timedelta(days=settings.UNPUBLISHED_ERP_NOTIF_DAYS)\n erps = Erp.objects.select_related(\"user\").filter(\n published=False,\n user__isnull=False,\n user__is_active=True,\n user__preferences__notify_on_unpublished_erps=True,\n updated_at__lte=since,\n )\n for erp in erps.iterator(chunk_size=2000):\n erp_updated_since_days = (self.now - erp.updated_at).days\n if erp_updated_since_days >= settings.UNPUBLISHED_ERP_NOTIF_DAYS:\n if erp.user.pk not in notifications:\n notifications[erp.user.pk] = {\"user\": erp.user, \"erps\": []}\n notifications[erp.user.pk][\"erps\"].append(erp)\n return [n for n in notifications.values() if n[\"erps\"]]\n\n def send_notification(self, notification):\n user, erps = notification[\"user\"], notification[\"erps\"]\n return get_mailer().send_email(\n [user.email],\n f\"[{settings.SITE_NAME}] Des établissements sont en attente de publication\",\n \"mail/unpublished_erps_notification.txt\",\n {\n \"user\": user,\n \"erps\": erps,\n \"SITE_NAME\": settings.SITE_NAME,\n \"SITE_ROOT_URL\": settings.SITE_ROOT_URL,\n },\n )\n","sub_path":"erp/management/commands/notify_weekly_unpublished_erps.py","file_name":"notify_weekly_unpublished_erps.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"57356843","text":"\"\"\"\r\n--------------------------------------------------------|\r\n| Create virtual enviroment -> virtualenv env |\r\n| Activate virtualenv -> env/Scripts/activate |\r\n| |\r\n| Install selenium -> pip install selenium |\r\n| |\r\n| Run the script in virtual enviroment -> python bit.py |\r\n---------------------------------------------------------\r\n\"\"\"\r\nimport unittest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nimport random\r\n\r\nclass Bit(unittest.TestCase):\r\n\r\n def setUp(self):\r\n print('I am not gonna destroy anything, just checking..')\r\n self.driver = webdriver.Firefox()\r\n\r\n def test_search_in_python_org(self):\r\n driver = self.driver\r\n driver.get(\"https://zck.me/bitcoin-clicker/\")\r\n element = driver.find_element_by_xpath(\"//input[@value='Mine for bitcoin. By hand.']\")\r\n for i in range(0,100000000):\r\n element.click()\r\n time.sleep(random.random())\r\n time.sleep(50)\r\n assert \"No results found.\" not in driver.page_source\r\n\r\n\r\n def tearDown(self):\r\n print('I am done.')\r\n self.driver.close()\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"bit.py","file_name":"bit.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"572402117","text":"\"\"\"\n Model for Super Tic Tac tic_tac_toe\n @Author Alex Chapman\n 3/6/17\n\"\"\"\n\n\nimport ast\n\nD = 'steelblue'\n\n\nclass model(object):\n \"\"\"\n class which handles the actual functioning of the server. Includes\n handling new users connecting, as well as clients sending commands\n such as color changes and click values.\n\n Attributes:\n SOCKET_LIST - List of addresses that have connected to server\n users - List of user objects\n correlation - Dictionary that relates other two attributes\n \"\"\"\n def __init__(self):\n \"\"\"Returns model object\"\"\"\n # list of addresses\n self.socket_list = []\n # list of user objects\n self.users = []\n # dictionary relating users to addresses\n self.correlation = {}\n\n def save_val(self, thruput, member):\n \"\"\"\n function call which allows data to be passed into the game field.\n Commands: 'hb' - heartbeat message sent on loop to sync\n 'uCOLOR' - sets the color of the user that calls it\n '[x, y]' - click value of given\n\n Input: thruput -> command or whatnot to be processed\n member -> address from which the message originated\n \"\"\"\n # figures out which user sent the message\n to_use = self.correlation[member]\n\n # if the command is the color set\n if thruput[0] == 'u':\n to_use.set_color(thruput[1:])\n print(member, thruput[1:])\n\n # on the click command check if it is that user's turn\n elif to_use.turn_state:\n try:\n # if hb is appended to the end of the click, remove it\n if 'hb' in thruput and len(thruput) > 2:\n thruput = thruput[:len(thruput)-2]\n\n # interperet point input as list\n ls = ast.literal_eval(thruput)\n\n # passes the point value down to the user and returns if\n # the turn was successfully passed\n if to_use.input(ls):\n # change whos turn it is\n self.change_turns()\n print('Turns Changed.')\n else:\n print('Invalid Click. Still your turn.')\n except (SyntaxError, ValueError) as e:\n if(thruput == 'hb'):\n pass\n else:\n print('didnt work' + thruput)\n pass\n else:\n if(thruput == 'hb'):\n pass\n else:\n print('not your turn ' + str(member))\n pass\n\n def update_socket_list(self, thruput):\n \"\"\"\n called upon clients connection, creates and establishes list of\n addresses which are in turn paired with user objects.\n\n inputs: thruput -> address of most recently connected machine\n \"\"\"\n if thruput not in self.socket_list: # if address not already listed\n self.socket_list.append(thruput)\n # print(len(self.socket_list))\n # the first user has a predefined 'x' char (now irrelevant)\n if len(self.socket_list) == 1:\n # first user to connect gets first turn\n self.users.append(user('x', True))\n # adds new user object to the dictionary so it can be found\n self.correlation[thruput] = self.users[0]\n\n # see above\n elif len(self.socket_list) == 2:\n self.users.append(user('o', False))\n self.correlation[thruput] = self.users[1]\n\n else:\n print('Invalid number of connections: 2 players expected.')\n print('Ignoring Extra Connection')\n # print(self.users)\n\n # changes the turns, excecution above\n def change_turns(self):\n \"\"\"Changes the turns\"\"\"\n for u in self.users:\n u.flip_turn()\n\n\nclass tic_tac_toe(object):\n \"\"\"\n Class which handles the creation of game objects for each of the 9\n major game tiles. Contains a 3x3 matrix of color vals, with the\n default color being defined at the top of the file.\n\n Attributes:\n focus - whether or not the game matrix is in focus (playable)\n state - 3x3 matrix holding the values of that specific board\n \"\"\"\n def __init__(self, f, x=0, y=0):\n \"\"\"Returns new tic_tac_toe object\"\"\"\n self.focus = f\n self.state = [[D, D, D],\n [D, D, D],\n [D, D, D]]\n\n def __str__(self):\n \"\"\"Returns string representation of tic_tac_tow object\"\"\"\n to_return = (str(self.state[0]) + '\\n' +\n str(self.state[1]) + '\\n' +\n str(self.state[2]) + '\\n')\n return to_return\n\n def add_char(self, char, i, j):\n \"\"\"\n Function which handles an attempted click: i.e. adding a new color\n to the game matrix if the box clicked on is empty.\n \"\"\"\n if self.state[i][j] is D:\n self.state[i][j] = char\n print('Clicked Valid Box.')\n return True\n else:\n print('Box already taken.')\n return False\n\n def on_click(self, x, y, char):\n \"\"\"\n Called by the user on click of the specific sub-game board.\n\n Inputs:\n x - decimal representation of click on the bigger board\n y - decimal representation of click on the bigger board\n char - color string of calling user\n \"\"\"\n x = x * 3\n y = y * 3\n\n # converts the decimal point to row and column clicked\n j = helper_func(x)\n i = helper_func(y)\n\n # only excecutes if the square clicked is unoccupied and in focus\n if self.add_char(char, i, j):\n # changes the big-board focus to the equivalent of the square clkd.\n change_focus(int(j), int(i))\n return True\n else:\n return False\n\n def check_if_won(self):\n \"\"\"\n Method to check the state matrix of the board to evaluate wheteher\n or not it has been won. If won, it returns the winning string. If\n not, returns the default string (D)\n \"\"\"\n # checks if the rows have a winner\n for row in self.state:\n if(row[0] == row[1] and row[0] == row[2]):\n return row[0]\n\n # checks if the columns have a winner\n for column in range(0, len(self.state)):\n one = self.state[0][column]\n two = self.state[1][column]\n three = self.state[2][column]\n if(one == two and one == three):\n return one\n\n # checks if the upper-left bottom-right diagonal has a winner\n one = self.state[0][0]\n two = self.state[1][1]\n three = self.state[2][2]\n if(one == two and one == three):\n return one\n\n # checks if the other diagonal has a winner\n one = self.state[0][2]\n three = self.state[2][0]\n if(one == two and one == three):\n return one\n return D\n\n def get_to_send(self):\n \"\"\"\n Returns nested list to send to clients\n Format:\n [[ROW],[ROW],[ROW]]\n L ROW = [focus, < 9 length list of all square values >]\n \"\"\"\n ls = []\n ls.append(self.focus)\n # print(self.state)\n if self.state is not None:\n for i in self.state:\n for q in i:\n ls.append(q)\n return ls\n\n\nclass user(object):\n \"\"\"\n User object designed to create a profile for each client that connects\n to the game. Also handles all high-level click functionality.\n\n Attributes:\n char - string representing the color of the user, set by\n uCOLOR command upon client initialization.\n turn_state - Boolean representing whether or not it is this user's\n turn.\n \"\"\"\n def __init__(self, char=D, turn_state=False):\n \"\"\"Returns a user object\"\"\"\n # sets the color to default, to be set by first client operation.\n self.char = char\n self.turn_state = turn_state\n\n def input(self, ls):\n \"\"\"\n Accepts the point value of the clicked position as a decimal fro 0-1\n in both the x and y direction. Calculates which large tile is\n clicked on, and then calls that tile with the same clicked point.\n\n Input: point of click in the form [x, y]\n \"\"\"\n click_x = ls[0]\n click_y = ls[1]\n\n # converts the decimal point to row and column clicked\n i = helper_func(click_x)\n j = helper_func(click_y)\n # print('box clicked on:', i, ':', j)\n # print('box in focus:', get_board_focus())\n if main_board[j][i].focus:\n # HIGHEST LEVEL CLICK MANAGEMENT\n # attempts to add color to the clicked-on board\n return main_board[j][i].on_click(click_x - i/3,\n click_y - j/3,\n self.char)\n else:\n return False\n\n def flip_turn(self):\n self.turn_state = not self.turn_state\n\n def set_color(self, color):\n self.char = color\n\n\ndef helper_func(val):\n \"\"\"\n Function independent of a class, designed to convert a decimal into\n its corresponding integer value. Assumes 3 columns / rows.\n\n Input: Must be between 0 and 1 to function correctly\n \"\"\"\n if val > 2/3:\n i = 2\n elif val < 1/3:\n i = 0\n else:\n i = 1\n return i\n\n\ndef change_focus(row, column):\n \"\"\"\n Changes focus to the new main tile. takes a row and column integer as\n inputs, must be between 0-2 for both.\n \"\"\"\n # sets all foci to false\n for rw in main_board:\n for game in rw:\n game.focus = False\n # goes to the single board that should be in focus and sets its focus\n main_board[column][row].focus = True\n print('focus on:', column, row)\n\n\n# Initializes the base variable which holds the game boards needed\nmain_board = [[tic_tac_toe(True), tic_tac_toe(False), tic_tac_toe(False)],\n [tic_tac_toe(False), tic_tac_toe(False), tic_tac_toe(False)],\n [tic_tac_toe(False), tic_tac_toe(False), tic_tac_toe(False)]]\n\n\ndef check_if_won(board):\n \"\"\"\n Function used to check if the main board has been won.\n\n Inputs: board - main game board to be checked.\n Output: string representing the color of the winner, if not the def.\n \"\"\"\n # Finds out if each individual board has been won.\n ls = []\n for i in board:\n ts = []\n for v in i:\n ts.append(v.check_if_won)\n\n # checks if the rows have a winner\n for row in ls:\n if(row[0] == row[1] and row[0] == row[2]):\n return row[0]\n\n # checks if the columns have a winner\n for column in range(0, len(ls)):\n one = ls[0][column]\n two = ls[1][column]\n three = ls[2][column]\n if(one == two and one == three):\n return one\n\n # checks if the upper-left bottom-right diagonal has a winner\n one = ls[0][0]\n two = ls[1][1]\n three = ls[2][2]\n if(one == two and one == three):\n return one\n\n # checks if the other diagonal has a winner\n one = ls[0][2]\n three = ls[2][0]\n if(one == two and one == three):\n return one\n return D\n\n\ndef get_board_state():\n \"\"\"\n Converts the game board into a readable form for sending to the clients\n \"\"\"\n ls = []\n for row in main_board:\n ts = []\n for val in row:\n # print(val.get_to_send())\n ts.append(val.get_to_send())\n ls.append(ts)\n return ls\n\n\ndef get_board_focus():\n \"\"\"Returns the index of the cell that is in focus\"\"\"\n for i, row in enumerate(main_board):\n for o, column in enumerate(row):\n if column.focus == 1:\n return str(i) + ':' + str(o)\n return 'none in focus'\n","sub_path":"model_tic_tac.py","file_name":"model_tic_tac.py","file_ext":"py","file_size_in_byte":12257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"336711091","text":"import os\nimport urllib.request\n\nif __name__ == '__main__':\n\tfor i in range(1,1000):\n\t\tfilename = \"res/levels/level\" + str(i) + \".json\"\n\t\turl =\"http://szhong.4399.com/4399swf/upload_swf/ftp16/ssj/20150703/j4/1y/\" +filename\n\t\ttry:\n\t\t\tf = urllib.request.urlopen(url)\n\t\t\tdata = f.read()\n\t\t\twith open(filename,'wb') as code:\n\t\t\t\tcode.write(data)\n\t\t\t\tcode.close()\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tbreak\n\t\t\t\t\n\n\t\t\t\n","sub_path":"www/downloadlevel.py","file_name":"downloadlevel.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"324484495","text":"\"\"\"\nThis module contains the game mechanics such as\nTime and Tamagotchi Mechanics.\n\"\"\"\n\nimport time\nimport math\nfrom message import Message\n\n\nclass TimeMechanics:\n \"\"\"\n Keeps track of the time elapsed between status checks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes an object and sets the time of initialization.\n \"\"\"\n\n self._old_time = 0\n self._last_time_elapsed = 0\n self._time_ = time.time()\n self._first_status_check = True\n\n def set_time_(self):\n \"\"\"\n Sets old_time to the current time_ value and then sets\n time_ to the new current time.\n :return: None\n \"\"\"\n\n self._old_time = self._time_\n self._time_ = time.time()\n\n def time_elapsed(self):\n \"\"\"\n Calculates the time elapsed by subtracting the new time_\n to the old_time.\n :return: A string that contains the details of the\n last status check\n \"\"\"\n\n if self._first_status_check:\n self._first_status_check = False\n return print(\"First status check...\")\n else:\n self._last_time_elapsed = math.ceil(self._time_ - self._old_time)\n return print(f\"\\nTime elapsed since last status check: \"\n f\"{self._last_time_elapsed} seconds\")\n\n @property\n def last_time_elapsed(self):\n \"\"\"\n Gets the value of the last_time_elapsed.\n :return: an int\n \"\"\"\n\n return self._last_time_elapsed\n\n\nclass TamagotchiMechanics:\n \"\"\"\n Contains the methods that modify the Tamagotchi's stats\n per second such as health, hunger, and happiness.\n \"\"\"\n\n def __init__(self, time_mechanic, tamagotchi):\n \"\"\"\n Initializes an object that has a TimeMechanic.\n :param time_mechanic: a TimeMechanic object\n :param tamagotchi: a tamagotchi object\n \"\"\"\n\n self._tm = time_mechanic\n self._tamagotchi = tamagotchi\n self._message = Message(tamagotchi)\n\n def attribute_mods(self):\n \"\"\"\n Runs the Tamagotchi's add_hunger, reduce_happiness, and\n reduce_health n times, where n equals the number of seconds\n passed in between status checks.\n :return: None\n \"\"\"\n\n run_times = 0\n while run_times < self._tm.last_time_elapsed:\n self._tamagotchi.add_hunger()\n self._tamagotchi.reduce_happiness()\n self._tamagotchi.reduce_health()\n run_times += 1\n\n def check_status(self):\n \"\"\"\n Checks the status of the Tamagotchi. Runs the set_time and\n time_elapsed methods to update the time component during\n the game. Runs the attribute_mods method in order to change the\n stat values.\n :return: None\n \"\"\"\n\n self._tm.set_time_()\n self._tm.time_elapsed()\n self.attribute_mods()\n\n if self._tamagotchi.dead():\n print(f\"{'-' * 50}\")\n self._message.died()\n print(f\"{'-' * 50}\")\n else:\n print(\"\")\n print(self._tamagotchi)\n print(\"\")\n self._message.hungry()\n self._message.fun()\n self._message.sick()\n","sub_path":"Assignments/Assignment 1/game_mechanics.py","file_name":"game_mechanics.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"645696238","text":"# This is a direct running file to calculate the specific counts of RNA\n# splicing, and currently it is mainly for intronic splicing, rather than\n# alternative splicing. There are 8 types for reads for an exon1-intron-\n# exon2 structure: (0) exon1, (1) exon1-intron boundary, (2) intron, (3) \n# intron-exon2 boundary, (4) exon2, (5) exon1-exon2 junction, (6) exon1-\n# intron-exon2, (7) exon1-exon2 unsure. In addition, it also provides the\n# normalized counts RPKM (reads per kilo-base per million reads).\n\nimport sys\nimport time\nimport pysam\nimport subprocess\nimport numpy as np\nimport multiprocessing\nfrom optparse import OptionParser\nfrom .utils.reads_utils import ReadSet\nfrom .utils.gtf_utils import load_annotation\nfrom .utils.sam_utils import load_samfile, fetch_reads\n\nFID = None \nPROCESSED = 0\nTOTAL_GENE = 0\nSTART_TIME = time.time()\n\ndef show_progress(RV=None):\n global PROCESSED, TOTAL_GENE, START_TIME, FID\n if RV is None:\n return RV\n else:\n FID.writelines(RV)\n \n PROCESSED += 1\n bar_len = 30\n run_time = time.time() - START_TIME\n percents = 100.0 * PROCESSED / TOTAL_GENE\n filled_len = int(round(bar_len * percents / 100))\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n \n sys.stdout.write('\\r[%s] %.2f%% processed in %.1f sec.' \n % (bar, percents, run_time))\n sys.stdout.flush()\n return RV\n\ndef get_count(gene, sam_file, total_reads, rm_duplicate, inner_only, mapq_min, \n mismatch_max, rlen_min, is_mated, total_only, overhang):\n samFile = load_samfile(sam_file)\n reads = fetch_reads(samFile, gene.chrom, gene.start, gene.stop, \n rm_duplicate, inner_only, mapq_min, mismatch_max, rlen_min, is_mated)\n\n if total_only:\n count = [len(reads[\"reads1u\"])+len(reads[\"reads2u\"])+len(reads[\"reads1\"])]\n RPKM = [count[0] * 10**9 / abs(gene.start - gene.stop) / total_reads]\n elif gene.tranNum == 1 and gene.trans[0].exonNum == 2:\n rdSet = ReadSet(reads[\"reads1u\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count = rdSet.loc_idx.sum(axis=0)\n RPKM = rdSet.RPK_use.sum(axis=0)\n\n rdSet = ReadSet(reads[\"reads2u\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count += rdSet.loc_idx.sum(axis=0)\n RPKM += rdSet.RPK_use.sum(axis=0)\n\n rdSet = ReadSet(reads[\"reads1\"], reads[\"reads2\"])\n rdSet.get_loc_idx(gene.trans[0].exons, gene.strand, overhang)\n count += rdSet.loc_idx.sum(axis=0)\n RPKM += rdSet.RPK_use.sum(axis=0)\n\n RPKM = RPKM * 10**6 / total_reads\n else: return None\n\n gLen = str(abs(gene.stop - gene.start) + 1)\n a_line = \"\\t\".join([gene.geneID, gene.geneName, gene.biotype, gLen]) + \"\\t\"\n a_line += \"\\t\".join([\"%d\" %num for num in list(count)]) + \"\\t\" \n a_line += \"\\t\".join([\"%.2e\" %num for num in list(RPKM)]) + \"\\n\"\n return a_line\n\ndef main():\n print(\"Welcome to dice-count!\")\n\n #part 0. parse command line options\n parser = OptionParser()\n parser.add_option(\"--anno_file\", \"-a\", dest=\"anno_file\", default=None,\n help=\"The annotation file in gtf format\")\n parser.add_option(\"--anno_source\", dest=\"anno_source\", default=\"Ensembl\",\n help=\"The annotation source of the gtf file [default: %default].\" )\n parser.add_option(\"--sam_file\", \"-s\", dest=\"sam_file\", default=None,\n help=\"The indexed alignement file in bam/sam format\")\n parser.add_option(\"--out_file\", \"-o\", dest=\"out_file\", \n default=\"dice_count.txt\", help=\"The counts in plain text file\")\n\n parser.add_option(\"--nproc\", dest=\"nproc\", default=\"4\",\n help=\"The number of subprocesses [default: %default].\")\n parser.add_option(\"--mapq_min\", dest=\"mapq_min\", default=\"10\", \n help=\"the minimum mapq for reads. [default: %default]\")\n parser.add_option(\"--mismatch_max\", dest=\"mismatch_max\", default=\"5\", \n help=\"the maximum mismatch for reads. [default: %default]\")\n parser.add_option(\"--rlen_min\", dest=\"rlen_min\", default=\"1\", \n help=\"the mimimum length of reads. [default: %default]\")\n parser.add_option(\"--overhang\", dest=\"overhang\", default=\"1\", \n help=\"the length of overhang on junctions. [default: %default]\")\n\n parser.add_option(\"--duplicate\", action=\"store_true\", \n dest=\"duplicate_use\", default=False, help=\"keep duplicate reads.\")\n parser.add_option(\"--partial\", action=\"store_true\", dest=\"partial_use\",\n default=False, help=\"keep reads partial in the region.\")\n parser.add_option(\"--single_end\", action=\"store_true\", dest=\"single_end\",\n default=False, help=\"use the reads as single-end.\")\n parser.add_option(\"--junction\", action=\"store_true\", dest=\"junction_reads\",\n default=False, help=(\"return junction and boundary reads, only for \"\n \"gene with one exon-intron-exon structure; other wise return total \"\n \"counts for the whole gene.\"))\n\n (options, args) = parser.parse_args()\n if len(sys.argv[1:]) == 0:\n print(\"use -h or --help for help on argument.\")\n sys.exit(1)\n if options.anno_file == None:\n print(\"Error: need --anno_file for annotation.\")\n sys.exit(1)\n else:\n sys.stdout.write(\"\\rloading annotation file...\")\n sys.stdout.flush() \n anno = load_annotation(options.anno_file, options.anno_source)\n sys.stdout.write(\"\\rloading annotation file... Done.\\n\")\n sys.stdout.flush()\n genes = anno[\"genes\"]\n if options.sam_file == None:\n print(\"Error: need --sam_file for reads indexed and aliged reads.\")\n sys.exit(1)\n else:\n sam_file = options.sam_file\n\n total_reads = 0\n for tp in pysam.idxstats(sam_file): \n tmp = tp.strip().split(\"\\t\")\n if len(tmp) >= 3:\n total_reads += float(tmp[2])\n\n nproc = int(options.nproc)\n overhang = int(options.overhang)\n mapq_min = int(options.mapq_min)\n rlen_min = int(options.rlen_min)\n mismatch_max = int(options.mismatch_max)\n\n is_mated = (options.single_end == False)\n inner_only = (options.partial_use == False)\n total_only = (options.junction_reads == False)\n rm_duplicate = (options.duplicate_use == False)\n \n global FID, TOTAL_GENE\n FID = open(options.out_file, \"w\")\n if total_only == False:\n head_line = \"gene_id\\tgene_name\\tbiotype\\tgene_length\"\n cnt_name = [\"ex1\", \"ex1_int\", \"int\", \"int_ex2\", \"ex2\", \"ex1_ex2_junc\",\n \"ex1_int_ex2\", \"ex1_ex2_vague\"]\n for i in range(len(cnt_name)):\n head_line += \"\\t\" + cnt_name[i] + \"_NUM\"\n for i in range(len(cnt_name)):\n head_line += \"\\t\" + cnt_name[i] + \"_FPKM\"\n cnt = 0\n for g in genes:\n if g.tranNum == 1 and g.trans[0].exonNum == 2: cnt += 1\n TOTAL_GENE = cnt\n else:\n TOTAL_GENE = len(genes)\n head_line = \"gene_id\\tgene_name\\tbiotype\\tgene_length\\tcount\\tFPKM\"\n FID.writelines(head_line + \"\\n\")\n\n print(\"running diceseq for %d genes with %d cores...\" %(TOTAL_GENE, nproc))\n\n if nproc <= 1:\n for g in genes:\n if total_only == False and (g.tranNum > 1 or g.trans[0].exonNum != 2):\n continue\n RV = get_count(g, sam_file, total_reads, rm_duplicate, inner_only, \n mapq_min, mismatch_max, rlen_min, is_mated, total_only, overhang)\n show_progress(RV)\n else:\n pool = multiprocessing.Pool(processes=nproc)\n for g in genes:\n if total_only == False and (g.tranNum > 1 or g.trans[0].exonNum != 2):\n continue\n pool.apply_async(get_count, (g, sam_file, total_reads, rm_duplicate, \n inner_only, mapq_min, mismatch_max, rlen_min, is_mated, total_only,\n overhang), callback=show_progress)\n pool.close()\n pool.join()\n FID.close()\n print(\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"diceseq/dice_count.py","file_name":"dice_count.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"472627812","text":"def name(item1):\n print(f'\\nOla!!! Bem Vindo, {item1}.')\n \ndef year(item2):\n if (item2 >= 18):\n print('\\nVocê é maior de idade.')\n else:\n print('\\nCreça você ainda é menor de idade.')\n\n#programa principal\nprint('Inicio')\nnome = input('\\nDigite seu nome: ')\nidade = int(input('\\nDigite sua idade: '))\n\n#função name\nname(nome)\n\n#função years\nyear(idade)\n\nprint('\\nFim')\n","sub_path":"Aula 15/Exercícios/A Ex 04.py","file_name":"A Ex 04.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"323112115","text":"from selenium import webdriver\nimport sys\nimport csv\n# -----------------------------------------------------------------------------\n# TC 133 - Create N new local accounts.\n#\n# By default uses randomly-generated account info from signup_10.csv which\n# must be in the same directory as this script. This must be a simple CSV file\n# with user ID, email, and password columns. No headers.\n# The default file was obtained from http://www.mockaroo.com/\n# All records found in the CSV file will be processed. To change the number\n# of accounts created, simply generate or manipulate a CSV file.\n# -----------------------------------------------------------------------------\n\ndatafile = 'signup_10.csv'\n\n# -----------------------------------------------------------------------------\n# Process command line argument that specifies the browser.\n# -----------------------------------------------------------------------------\n# No argument provided\ntry:\n arg1 = sys.argv[1]\nexcept IndexError:\n driver = webdriver.Chrome()\n\nif 'driver' not in locals():\n if sys.argv[1].lower() == 'chrome':\n driver = webdriver.Chrome()\n elif sys.argv[1].lower() == 'firefox':\n driver = webdriver.Firefox()\n elif sys.argv[1].lower() == 'ie':\n driver = webdriver.Ie()\n elif sys.argv[1].lower() == 'edge':\n driver = webdriver.Edge()\n elif sys.argv[1].lower() == 'opera':\n options = webdriver.ChromeOptions()\n options.binary_location = \\\n 'C:\\\\Program Files\\\\Opera\\\\48.0.2685.50\\\\opera.exe'\n driver = webdriver.Opera(opera_options=options)\n # MacOS options\n elif sys.argv[1].lower() == 'safari':\n driver = webdriver.Safari()\n elif sys.argv[1].lower() == 'chromemac':\n driver = webdriver.Chrome\n ('/volumes/OrangeWhite/Dropbox/WebDev/selenium/chromedriver')\n # Argument provided didn't match anything above\n else:\n driver = webdriver.Chrome()\n\ndriver.set_page_load_timeout(30)\ndriver.get('https://dev.fifteenlines.com/register_no_captcha')\ndriver.implicitly_wait(20)\n\n# -----------------------------------------------------------------------------\n# Open specified datafile for reading only\n# -----------------------------------------------------------------------------\nusers = csv.reader(open(datafile, 'r'))\n\n# -----------------------------------------------------------------------------\n# Use fields from the datafile to sign up fake users\n# -----------------------------------------------------------------------------\n\nfor row in users:\n driver.find_element_by_id('username') \\\n .send_keys(row[0])\n driver.find_element_by_id('email') \\\n .send_keys(row[1])\n driver.find_element_by_id('password') \\\n .send_keys(row[2])\n driver.find_element_by_id('signUp').click()\n assert \"Welcome to Fifteenlines\" in driver.page_source\n driver.find_element_by_id('logout').click()\n driver.get('https://dev.fifteenlines.com/register_no_captcha')\n\ndriver.quit()\n","sub_path":"selenium/tc_133.py","file_name":"tc_133.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"399353734","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom irs9465.tasks import fill_form_9465\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n help = ('Update IRS Local and National Standards Tables')\n\n def add_arguments(self, parser):\n parser.add_argument('--sync', action='store_true', help='Run it synchronously')\n parser.add_argument('--client_id', help='Client ID', required=True)\n parser.add_argument('--outfile', help='Output PDF file')\n\n def handle(self, *args, **options):\n sync = options.get('sync') or False\n if sync:\n fill_form_9465(client_id=options.get('client_id'), outfile=options.get('outfile'))\n else:\n fill_form_9465.apply_async(kwargs={'client_id': options.get('client_id'),\n 'outfile': options.get('outfile')})\n","sub_path":"irsexpress2/apps/irs9465/management/commands/makepdf_9465.py","file_name":"makepdf_9465.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"44556336","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView, ListView\nfrom eleccion import views\nfrom .views import *\n\nurlpatterns = [\n\turl(r'^verCircunscripciones/$', ListView.as_view(model=Circunscripcion, template_name=\"verCircunscripciones.html\")),\n\turl(r'^verPartidosPoliticos', views.verPartidosPoliticos, name = \"Ver Partidos Politicos\"),\n\turl(r'^detallePartidoPolitico/(?P\\d+)', views.detallePartidoPolitico, name='Detalles Partido Politico'),\n\turl(r'^addPartidoPolitico', views.addPartidoPolitico, name = \"Añadir Partido Politico\"),\n\turl(r'^detalleCircunscripcion/(?P\\d+)', views.detalleCircunscripcion, name='Detalles Circunscripcion'),\n\turl(r'^editarCircunscripcion/(?P\\d+)', views.editarCircunscripcion, name='Editar Circunscripcion'),\n\turl(r'^eliminarCircunscripcion/(?P\\d+)', views.eliminarCircunscripcion, name='Eliminar Circunscripcion'),\n\turl(r'^addCircunscripcion', views.addCircunscripcion, name = \"Añadir Circunscripcion\"),\n\turl(r'^verMesas', views.verMesas, name = \"Ver Mesas\"),\n\turl(r'^editarMesa/(?P\\d+)', views.editarMesa, name='Editar Mesa'),\n\turl(r'^verResultados', views.verResultados, name = \"Ver Resultados\"),\n\turl(r'^detalleMesa/(?P\\d+)', views.detalleMesa, name='Detalles Mesa'),\n\turl(r'^detalleResultados/(?P\\d+)', views.detalleResultados, name='Detalles Resultados'),\n\turl(r'^addMesa', views.addMesa, name = \"Añadir Mesa\"),\n\turl(r'^addVoto', views.addVoto, name = \"Votar\"),\n]\n","sub_path":"Elecciones/eleccion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"173027516","text":"from sample.cases.update_case import UpdateCase\nfrom sample.config.config_loader import ConfigLoader\nfrom sample.logger import Logger\nfrom sample.path import Path\nfrom sample.ssh_mananger.commands import WindowsCommands\nfrom sample.ssh_mananger.ssh_client import SshClient\n\n\ndef run():\n Logger.setLogger(__name__)\n\n Logger.i('######################################')\n Logger.i('# #')\n Logger.i('# INICIANDO O SMOKE-TEST-NFCE #')\n Logger.i('# VERSAO A0.1 #')\n Logger.i('# #')\n Logger.i('######################################')\n\n config = ConfigLoader(Path.run_path).load_config()\n ssh_connection = config.ssh_connections['localhost']\n update_case = UpdateCase(SshClient(ssh_connection, WindowsCommands), '4.9.1', '90000', 'agent')\n update_case.execute()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"573882404","text":"import FWCore.ParameterSet.Config as cms\nprocess = cms.Process(\"SKIM\")\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('JetMETCorrections.Configuration.jecHLTFilters_cfi')\n############# Set the number of events #############\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(100)\n)\n############# Define the source file ###############\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n'/store/mc/Summer09/QCDDiJet_Pt15to20/AODSIM/MC_31X_V3_AODSIM-v1/0046/CEDF080D-CC8F-DE11-A831-001E682F84DE.root')\n)\n\n############# Path ###########################\nprocess.skimPath = cms.Path(process.HLTDiJetAve15U8E29)\n\n############# output module ########################\nprocess.compress = cms.OutputModule(\"PoolOutputModule\",\n outputCommands = cms.untracked.vstring(\n 'drop *',\n 'keep *_sisCone5CaloJets_*_*',\n 'keep *_sisCone7CaloJets_*_*',\n 'keep *_kt4CaloJets_*_*',\n 'keep *_kt6CaloJets_*_*',\n 'keep *_antikt5CaloJets_*_*',\n 'keep *_iterativeCone5CaloJets_*_*', \n 'keep *_sisCone5PFJets_*_*',\n 'keep *_sisCone7PFJets_*_*',\n 'keep *_kt4PFJets_*_*',\n 'keep *_kt6PFJets_*_*',\n 'keep *_antikt5PFJets_*_*',\n 'keep *_iterativeCone5CaloJets_*_*',\n 'keep *_iterativeCone5JetExtender_*_*',\n 'keep *_sisCone5JetExtender_*_*',\n 'keep *_kt4JetExtender_*_*',\n 'keep *_TriggerResults_*_*',\n 'keep *_hltTriggerSummaryAOD_*_*', \n 'keep *_towerMaker_*_*',\n 'keep *_EventAuxilary_*_*',\n 'keep *_pixelVertices_*_*',\n 'keep *_metHO_*_*',\n 'keep *_metNoHF_*_*',\n 'keep *_metNoHFHO_*_*', \n 'keep *_met_*_*'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('skimPath')), \n fileName = cms.untracked.string('JetAOD_HLTDiJetAve15.root')\n)\n\nprocess.p = cms.EndPath(process.compress)\n############# Format MessageLogger #################\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 10\n","sub_path":"JetMETCorrections/Configuration/test/jetAODSkim_HLT_DiJetAve15_cfg.py","file_name":"jetAODSkim_HLT_DiJetAve15_cfg.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"519109993","text":"import sys\nfrom os import path\nsys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) \n\nfrom tree_node import tree_node\nfrom base.iterator import iterator\nfrom tree_algo import tree_visit_level_order, tree_min, tree_delete_min, bst_find\nfrom tree_algo import tree_rotate_left, tree_rotate_right, tree_compute_height, tree_balance_check, tree_size\n\nclass avl_tree:\n \"\"\"\n Implementation for avl binary search tree.\n The avl binary search tree is binary tree that guarantees lg N time for insert/find/delete.\n The avl tree use rotation coupled with height analysis between nodes in order to accomplish balancing\n \n Important:\n - this implementation uses massively recursion. \n - Probably in practise you will never want use heavy recursive algorithms\n \"\"\"\n \n def __init__(self):\n self.root = None\n \n def __str__(self):\n return \"avl tree\"\n \n def insert(self, key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n self.root = self.__avl_insert(self.root, key)\n \n def find(self, key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n return bst_find(self.root, key) \n \n def delete(self,key):\n if key == None:\n raise Excpetion(\"Key is not valid. operation aborted\")\n if self.root == None:\n raise Exception(\"Tree is empty\")\n self.root = self.__avl_delete(self.root, key)\n pass\n\n def __iter__(self):\n return iterator(tree_visit_level_order(self.root))\n \n #\n # private utilis methods for avl tree\n #\n\n def __avl_insert(self, node, key):\n \n if node == None:\n n = tree_node(key)\n n.count = 1\n return n\n if key < node.key:\n node.left = self.__avl_insert(node.left, key)\n height = tree_balance_check(node)\n if height == 2:\n if key < node.left.key:\n node = self.__ll_rotation(node)\n else:\n node = self.__lr_rotation(node)\n elif key > node.key:\n node.right = self.__avl_insert(node.right, key)\n height = tree_compute_height(node)\n if height == -2:\n if key < node.right.key:\n node = self.__rl_rotatation(node)\n else:\n node = self.__rr_rotations(node)\n else:\n node.key = key\n\n node.height = tree_compute_height(node)\n node.count = tree_size(node.left) + tree_size(node.right) + 1\n\n return node\n\n def __avl_delete(self, node, key):\n #like bst deletation + rebalacing stuff\n if key < node.key:\n node.left = self.__avl_delete(node.left, key)\n h = tree_balance_check(node)\n if h == -2:\n if tree_balance_check(node.right) <= 0:\n node = self.__rr_rotations(node)\n else:\n node = self.__rl_rotatation(node)\n elif key > node.key:\n node.right = self.__avl_delete(node.right, key)\n h = tree_balance_check(node)\n if h == 2:\n if tree_balance_check(node.left) <= 0:\n node = self.__ll_rotation(node)\n else:\n node = self.__lr_rotation(node)\n else:\n #equal to std bst deletation\n if node.left == None:\n return node.right\n if node.right == None:\n return node.left\n\n t = node\n node = tree_min(t.right)\n node.right = tree_delete_min(t.right)\n node.left = t.left\n node.count = tree_size(node.left) + tree_size(node.right) + 1\n node.height = tree_compute_height(node)\n\n return node\n\n def __ll_rotation(self, node):\n node = tree_rotate_right(node)\n return node\n \n def __lr_rotation(self, node):\n node.left = tree_rotate_left(node.left)\n node = tree_rotate_right(node)\n return node\n\n def __rl_rotatation(self, node):\n node.right = tree_rotate_right(node.right)\n node = tree_rotate_left(node)\n return node\n\n def __rr_rotations(self, node):\n node = tree_rotate_left(node)\n return node\n","sub_path":"searching/avl_tree.py","file_name":"avl_tree.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"362209062","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport pytest\nimport mock\n\nfrom h.presenters.group_json import GroupJSONPresenter, GroupsJSONPresenter\nfrom h.services.group_links import GroupLinksService\n\n\nclass TestGroupJSONPresenter(object):\n def test_private_group_asdict_no_links_svc(self, factories):\n group = factories.Group(name='My Group',\n pubid='mygroup')\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'mygroup',\n 'type': 'private',\n 'public': False,\n 'scoped': False,\n 'urls': {},\n 'links': {}\n }\n\n def test_open_group_asdict_no_links_svc(self, factories):\n group = factories.OpenGroup(name='My Group',\n pubid='mygroup')\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'mygroup',\n 'type': 'open',\n 'public': True,\n 'scoped': False,\n 'urls': {},\n 'links': {}\n }\n\n def test_open_scoped_group_asdict(self, factories):\n group = factories.OpenGroup(name='My Group',\n pubid='groupy',\n scopes=[factories.GroupScope(origin='http://foo.com')])\n\n presenter = GroupJSONPresenter(group)\n\n assert presenter.asdict() == {\n 'name': 'My Group',\n 'id': 'groupy',\n 'type': 'open',\n 'public': True,\n 'scoped': True,\n 'urls': {},\n 'links': {},\n }\n\n def test_private_group_asdict_with_links_svc(self, factories, links_svc):\n group = factories.Group(name='My Group',\n pubid='mygroup')\n presenter = GroupJSONPresenter(group, links_svc=links_svc)\n links_svc.get_all.return_value = {'html': 'bar'}\n\n model = presenter.asdict()\n\n links_svc.get_all.assert_called_once_with(group)\n assert model['urls'] == links_svc.get_all.return_value\n assert model['links'] == links_svc.get_all.return_value\n assert model['url'] == links_svc.get_all.return_value['html']\n\n def test_open_group_asdict_with_links_svc(self, factories, links_svc):\n group = factories.OpenGroup(name='My Group',\n pubid='mygroup')\n presenter = GroupJSONPresenter(group, links_svc=links_svc)\n\n presenter.asdict()\n\n links_svc.get_all.assert_called_once_with(group)\n\n\nclass TestGroupsJSONPresenter(object):\n\n def test_proxies_to_GroupJSONPresenter(self, factories, GroupJSONPresenter_, links_svc): # noqa: [N802, N803]\n groups = [factories.Group(), factories.OpenGroup()]\n presenter = GroupsJSONPresenter(groups, links_svc=links_svc)\n expected_call_args = [mock.call(group, links_svc) for group in groups]\n\n presenter.asdicts()\n\n assert GroupJSONPresenter_.call_args_list == expected_call_args\n\n def test_asdicts_returns_list_of_dicts(self, factories):\n groups = [factories.Group(name=u'filbert'), factories.OpenGroup(name=u'delbert')]\n presenter = GroupsJSONPresenter(groups)\n\n result = presenter.asdicts()\n\n assert [group['name'] for group in result] == [u'filbert', u'delbert']\n\n def test_asdicts_injects_urls(self, factories, links_svc):\n groups = [factories.Group(), factories.OpenGroup()]\n presenter = GroupsJSONPresenter(groups, links_svc)\n\n result = presenter.asdicts()\n\n for group_model in result:\n assert 'urls' in group_model\n assert 'links' in group_model\n\n\n@pytest.fixture\ndef links_svc():\n return mock.create_autospec(GroupLinksService, spec_set=True, instance=True)\n\n\n@pytest.fixture\ndef GroupJSONPresenter_(patch): # noqa: N802\n return patch('h.presenters.group_json.GroupJSONPresenter')\n","sub_path":"tests/h/presenters/group_json_test.py","file_name":"group_json_test.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"496336175","text":"# ----------------------------------------------------\n# Name: Nicholas Houchois\n# UNI: nbh2119\n# \n# Module for various effects to be applied to .ppm images.\n# ----------------------------------------------------\nimport re\nimport linecache\n\n\ndef parse_file(file):\n \"\"\" Parses the file and returns a list of pixels \"\"\"\n pixels = []\n\n # get string from file\n text = file.read()\n\n # create list of tokens delimited by whitespace\n tokens = text.split()\n\n # remove header from list\n del tokens[0:4]\n\n pixels = []\n\n # created list of pixels (which are a list of RGB values)\n i = 0\n while i in range(len(tokens)):\n pixels.append(tokens[i:i + 3])\n i += 3\n\n return pixels\n\n\ndef get_header(file):\n \"\"\" Returns the header of the file as a list \"\"\"\n header = []\n i = 0\n while len(header) < 4:\n line = linecache.getline(file.name, i)\n i += 1\n tokens = line.split()\n for token in tokens:\n if len(header) < 4:\n if token:\n header.append(token)\n return header\n\n\ndef write_output(output, outfile):\n \"\"\" Removes all non number characters and writes to file\"\"\"\n\n string = re.sub(r'\\D', \" \", str(output))\n outfile.write(string)\n\n\ndef negate_color(in_file, out_name, index):\n \"\"\" Negates the color specified by index \"\"\"\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n\n for i in range(len(pixels)):\n for j in range(len(pixels[i])):\n # if RGB value is the one to be negated\n if j == index:\n output.append(str(int(header[3]) - int(pixels[i][index])))\n # append other two values without modification\n else:\n output.append(pixels[i][j])\n\n # write header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n\n\ndef object_filter(in_file_list, outfile_name):\n \"\"\"\n Filters out pixel values that appear in only a minority\n of the images in the parameter in_file_list.\n \"\"\"\n images = []\n outfile = open(outfile_name, \"w\")\n\n header = get_header(in_file_list[0])\n\n for file in in_file_list:\n pixels = parse_file(file)\n\n images.append(pixels)\n\n output = []\n\n for i in range(len(pixels)):\n for j in range(len(pixels[i])):\n compare_list = []\n\n # compare images and select majority\n for k in range(len(images)):\n compare_list.append(images[k][i][j])\n compare_list.sort()\n\n # append to output list\n output.append(compare_list[len(compare_list) // 2])\n\n # write header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n\n outfile.close()\n\n\ndef shades_of_gray(in_file, out_name):\n \"\"\"Converts the color image in_file to black and white\"\"\"\n\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n\n for i in range(len(pixels)):\n sum = 0\n\n # calculate the average of the RGB values in a pixel\n for j in range(len(pixels[i])):\n sum += int(pixels[i][j])\n average = int(sum / 3)\n\n # append the average three times (once for each RGB value)\n output.append(average)\n output.append(average)\n output.append(average)\n\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n\n\ndef negate_red(in_file, out_name):\n \"\"\"Negates the red in an image\"\"\"\n negate_color(in_file, out_name, 0)\n\n\ndef negate_green(in_file, out_name):\n \"\"\"Negates the green in an image\"\"\"\n\n negate_color(in_file, out_name, 1)\n\n\ndef negate_blue(in_file, out_name):\n \"\"\"Negates the blue in an image\"\"\"\n\n negate_color(in_file, out_name, 2)\n\n\ndef mirror(in_file, out_name):\n \"\"\"Creates a mirror image by flipping an image horizontally\"\"\"\n outfile = open(out_name, \"w\")\n\n header = get_header(in_file)\n\n pixels = parse_file(in_file)\n\n output = []\n columns = int(header[1])\n rows = int(header[2])\n\n # iterates through each row\n for i in range(rows):\n row = pixels[i * columns: (i + 1) * columns]\n # reverses the row\n for pixel in reversed(row):\n output.append(pixel)\n\n # writes header to file\n for element in header:\n outfile.write(str(element) + \" \")\n\n write_output(output, outfile)\n outfile.close()\n","sub_path":"OneDrive/Columbia/Python/HW4/effects.py","file_name":"effects.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"384933988","text":"def printFrameNumber(vid):\r\n print('frame ' + str(int(vid.get(1))) + ' of ' + str(int(vid.get(7))))\r\n\r\n'''\r\nvid.get(1) - current frame (float)\r\nvid.get(3) - vid width\r\nvid.get(4) - vid height\r\nvid.get(7) - total frames (float)\r\n\r\ncv2.imwrite('filename', image)\r\nret, frame = vid.read()\r\n'''\r\nimport cv2\r\nimport numpy as np\r\nimport time\r\n\r\n#template0 = cv2.imread('lFlapTemplate.jpg')\r\ntemplate1 = cv2.imread('tr_corner_template.png')\r\ntemplate2 = cv2.imread('star_template.png')\r\ntemplate3 = cv2.imread('1_small_template.png')\r\ntemplate4 = cv2.imread('1_small_template2.png')\r\n#template0 = cv2.cvtColor(template0, cv2.COLOR_BGR2GRAY)\r\ntemplate1 = cv2.cvtColor(template1, cv2.COLOR_BGR2GRAY)\r\ntemplate2 = cv2.cvtColor(template2, cv2.COLOR_BGR2GRAY)\r\ntemplate3 = cv2.cvtColor(template3, cv2.COLOR_BGR2GRAY)\r\ntemplate4 = cv2.cvtColor(template4, cv2.COLOR_BGR2GRAY)\r\n\r\nfilename = 'test_big.mp4'\r\nvid = cv2.VideoCapture(filename)\r\nhole_started = False\r\n\r\nif filename[-3:].lower() == 'mov':\r\n minXOR1 = 0\r\n maxXOR1 = 300\r\n minXOR2 = 0\r\n maxXOR2 = 300\r\nelif filename[-3:].lower() == 'mp4':\r\n minXOR1 = int(vid.get(4))-300\r\n maxXOR1 = int(vid.get(4))\r\n minXOR2 = 0\r\n maxXOR2 = 300\r\nelse:\r\n raise Exception('video format ' + filename[-3:]+' not supported')\r\n\r\nvid.set(1,33650)\r\nlast_maxVal = 0\r\n_, last_frame = vid.read()\r\nprint('Doing frame-by-frame analysis. Please wait...')\r\nstart_time = time.time()\r\nwhile vid.get(1) < 36200-1:\r\n _, frame = vid.read()\r\n \r\n frametmp = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n frametmp = cv2.adaptiveThreshold(frametmp,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,-10)\r\n tempMatch = cv2.matchTemplate(frametmp, template3, cv2.TM_CCORR_NORMED, template3)\r\n tempMatchIMG = cv2.normalize(tempMatch, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n _,maxVal,_,location0 = cv2.minMaxLoc(tempMatch)\r\n \r\n if maxVal-last_maxVal > 0.05 or maxVal > 0.7:\r\n print(maxVal)\r\n cv2.rectangle(frame, location0, (location0[0]+25, location0[1]+25), (0,0,255),1)\r\n cv2.imshow('frame',frame)\r\n cv2.imshow('tempMatch1',tempMatch)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n \r\n last_maxVal = maxVal\r\n last_frame = frame","sub_path":"findFirstFlap2.py","file_name":"findFirstFlap2.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"630619101","text":"\"\"\"\npython网络数据采集第二章\nBeautifulsoup解析'http://www.pythonscraping.com/pages/warandpeace.html'\n小说名字为红色,对话为绿色,通过class属性过滤\n\"\"\"\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\n\ndef getHTMLText(url):\n try:\n html = urlopen(url)\n except HTTPError as e:\n return None\n try:\n soup = BeautifulSoup(html, 'html.parser')\n nameList = soup.findAll(\"span\", {\"class\":\"green\"}) #找出所有标签中内容\n except AttributeError as e:\n return None\n return nameList\nurl = 'http://www.pythonscraping.com/pages/warandpeace.html'\nlists = getHTMLText(url)\nfor list in lists:\n print(list.get_text()) #get_text()获得标签内的文字","sub_path":"spider/exe-5.py","file_name":"exe-5.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"573540845","text":"#Python Pre Work\n\n#Question 1\ndef hello(name):\n print(\"Hello \" + name.upper()+ \"!\")\n\nhello('christian')\n\n#Question 2\ndef odd_numbers():\n\tnumbers = list(range(0, 100))\n\tfor number in numbers:\n\t\tif number % 2 != 0:\n\t\t\tprint(number)\n \nodd_numbers()\n\n#Question 3\ndef max_num_in_list(a_list):\n max_num = max(a_list)\n return max_num\n\ntest = max_num_in_list([19,7,3,26,2])\nprint(max_num_in_list([19,7,3,26,2]))\n\n#Question 4\ndef is_leap_year(a_year):\n if a_year % 4 == 0 and a_year % 100 != 0:\n print(f'{a_year} is a leap year')\n elif a_year % 400 == 0:\n print(f'{a_year} is a leap year')\n else:\n a_year = False\n print(f'{a_year}')\n\nis_leap_year(2013)\n\n\n#Question 5\ndef is_consecutive(a_list):\n i = 0\n status = True\n while i < len(a_list) - 1:\n if a_list[i] + 1 == a_list[i + 1]:\n i += 1\n else:\n status = False\n break\n print(status)\n\n","sub_path":"prework.py","file_name":"prework.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"42610482","text":"import subprocess\nimport logging\nimport re\nimport sys\n\n\ntry:\n from scapy.all import *\nexcept ImportError:\n print(\"Scapy is not installed in your system.\\n\") \n print(\"Try using : pip3 install scapy\\n\")\n sys.exit()\n#This will suppress all messeges that have a lover level of seriousness than error messeges\nlogging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR) \nlogging.getLogger(\"scapy.interactive\").setLevel(logging.ERROR) \nlogging.getLogger(\"scapy.loading\").setLevel(logging.ERROR) \n\n#Setting the checkIPaddr parameter to False\nconf.checkIPaddr = False\n\n#Reading allowed DHCP servers from an external file\nwith open(\"dhcp.txt\") as f:\n allowed_dhcp_servers = f.read()\n\n#Listing all network interfaces on the ubuntu host\nhost_if = subprocess.run(\"ip link\", shell=True, stdout=subprocess.PIPE)\n\n#Extracting the interfaces name from the output stored above\ninterfaces = re.findall(r\"\\d:\\s(.+?):\\s\", str(host_if))\n\n\ntry:\n #Detecting Rogue DHCP servers per interface (except loopback interface)\n for interface in interfaces:\n if interface != 'lo':\n #Getting the hardware address\n mac_add = get_if_raw_hwaddr(interface)[1]\n # print(mac_add)\n\n #Creating DHCP discover packet\n dhcp_discover = Ether(dst = 'ff:ff:ff:ff:ff:ff') / IP(src = '0.0.0.0', dst = '255.255.255.255') / UDP(sport = 68, dport = 67) / BOOTP(chaddr = mac_add) / DHCP(options = [('message-type', 'discover'), 'end'])\n \n #Sending the Dicover Packet and accepting multiple answers for the same Discover Packet\n ans, unans = srp(dhcp_discover, multi=True, iface=interface, timeout=5, verbose=0)\n # print(ans)\n # print(unans)\n\n #Defining a dictionary to store mac-ip pairs\n mac_ip_pair = {}\n\n for pair in ans:\n mac_ip_pair[pair[1][Ether].src] = pair[1][IP].src\n\n if ans:\n #Printing the results\n print(\"\\n --> The following DHCP servers found on the {} LAN: \\n\".format(interface))\n\n for mac, ip in mac_ip_pair.items():\n if ip in allowed_dhcp_servers:\n print(\"OK! IP Address : {},MAC Address : {}\\n\".format(ip,mac))\n else:\n print(\"ROGUE! IP Address : {},MAC Address : {}\\n\".format(ip,mac)) \n\n else:\n print(\"\\n --> No active DHCP servers found on the {} LAN\\n\".format(interface)) \n else:\n pass\n\nexcept KeyboardInterrupt:\n print(\"\\nProgram aborted by the user!!! Exiting...\")\n sys.exit() ","sub_path":"Rogue DHCP Server Discovery Tool/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"394948198","text":"import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\n# 데이터 읽어오기\nmr = pd.read_csv(\"../data/mushroom.csv\", header=None) # 헤더�� 인덱스로 바꿈\n# 데이터 내부의 분류 변수 전개하기\nlabel = []\ndata = []\nattr_list = []\nfor row_index, row in mr.iterrows():\n label.append(row.iloc[0]) # 독버섯, 일반버섯 분류\n # 각행의 0번 열은 독 or 일반 확인 가능\n exdata = []\n for col, v in enumerate(row[1:]):\n if row_index == 0 :\n attr = {\"dic\":{},\"cnt\":0}\n attr_list.append(attr)\n else :\n attr = attr_list[col]\n # 버섯 특징 기호 저장 최소2개 ~ 최대12개\n d = [0,0,0,0,0,0,0,0,0,0,0,0]\n if v in attr[\"dic\"]:\n idx = attr[\"dic\"][v]\n else :\n idx = attr[\"cnt\"]\n attr[\"dic\"][v] = idx\n attr[\"cnt\"] += 1\n d[idx] = 1\n exdata += d\n data.append(exdata)\n\n# 학습용 데이터용 분류\ndata_train, data_test, label_train, label_test = train_test_split(data, label)\n\n# 데이터 학습\nclf = RandomForestClassifier()\nclf.fit(data_train,label_train)\n\n# 데이터 예측\npredict = clf.predict(data_test)\n\n# 결과 테스트\nac_score = metrics.accuracy_score(label_test,predict)\ncl_report = metrics.classification_report(label_test,predict)\nprint(\"정답률 :\",ac_score)\nprint(\"리포트 :\")\nprint(cl_report)\n\n","sub_path":"PythonAI/Practice/DAY09/src/Mushroom_Train.py","file_name":"Mushroom_Train.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"9853638","text":"#Maddy Chan 12/7/15\n#Cracking the Coding Interview 10.4\n#Given a list which contains sorted, positive integers, no info about the size\n#and where if you index somewhere out of bounds it will give -1,\n#write an algorithm that will find x in the list.\n\n\n\n\n\n\ndef searchList(x: int, start: int, end: int, l: list):\n if start == end:\n return start if l[start] == x else -1\n elif l[end] > x or l[end] == -1:\n half = int((end-start)/2) + start\n if l[half] == x:\n return half\n elif l[half] > x or l[half] == -1:\n return searchList(x,start,half,l)\n else:\n return searchList(x,half,end-1,l)\n else:\n return searchList(x,end,end+(end-start),l)\n\n\n\nl = [1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,-1]\n\nprint(searchList(9,0,6,l))\n","sub_path":"codingInterview10.4.py","file_name":"codingInterview10.4.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"261547892","text":"'''\n@Description: \n@Author: Fishermanykx\n@LastEditors: Fishermanykx\n@LastEditTime: 2020-03-17 20:58:25\n'''\nfrom pprint import pprint\n\n\nclass CPUSimulator:\n\n def __init__(self, filename):\n \"载入含机器码的文件\"\n # 初始化寄存器文件(int-int)\n self.regFile = {} # 寄存器文件,编号依次为0~7\n for i in range(8):\n self.regFile[i] = 0\n # 初始化内存\n self.memory = [0] * 1000 # 内存\n self.rip = 0 # instruction pointer\n # 构建指令文件(str-str)\n self.instruction_file = {}\n inf = open(filename + \".bin\", \"r\")\n while True:\n line = inf.readline()\n if line == '':\n break\n line = line.split()\n address = line[0]\n self.instruction_file[int(address)] = line[1]\n inf.close()\n # pprint(self.instruction_file)\n\n def MainProcess(self):\n '''\n @description: 主流程,采用流水线CPU\n '''\n self.has_next_ins = True\n self.jmp = False\n cnt_loop = 0\n\n while True:\n ins = self.Fetch()\n slided_ins = self.Decode(ins)\n self.Execute(slided_ins)\n self.Memory()\n self.WriteBack()\n if not self.has_next_ins:\n if cnt_loop == 3:\n break\n else:\n cnt_loop += 1\n\n def Fetch(self):\n '''\n @description: 取指阶段\n @param {type} \n @return: 取出的二进制指令(str)\n '''\n try:\n ins = self.instruction_file[self.rip]\n self.rip += 1\n except: # 若已经执行完毕,则传入气泡\n ins = \"01\"\n return ins\n\n def Decode(self, ins):\n '''\n @description: 译码阶段: 将二进制指令转换为opcode与操作数(十进制int)\n @param {type}: ins{str}\n @return: list\n '''\n opcode = ins[0:2]\n res = []\n # 根据指令类型切分\n op_type = int(opcode[0])\n if op_type == 0:\n self.has_next_ins = False\n res = [\"00\"]\n elif op_type == 1:\n res = [\"00\"]\n elif op_type == 2:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n elif op_type == 3:\n res.append(opcode)\n res.append(None)\n res.append(self.regFile[int(ins[3])])\n res.append(self.ConvertImmNum(ins[4:]))\n elif op_type == 4 or op_type == 5:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n res.append(self.ConvertImmNum(ins[4:]))\n elif op_type == 6:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(self.regFile[int(ins[3])])\n elif op_type == 7 or op_type == 8:\n res.append(opcode)\n res.append(self.ConvertImmNum(ins[2:]))\n elif op_type == 8:\n res.append(opcode)\n elif op_type == 10 or op_type == 11:\n res.append(opcode)\n res.append(self.regFile[int(ins[2])])\n res.append(None)\n else:\n print(\"Error: Illegal instruction. Exit code: INS\")\n exit(1)\n return res\n\n def Execute(self, slided_ins):\n '''\n @description: 执行阶段\n @param {type} 根据opcode与操作数执行指令\n @return: 计算所得的结果\n '''\n self.HazardUnit()\n\n def Memory(self):\n '''\n @description: 访存阶段\n @param {type} \n @return: 将执行阶段的值写回内存或从内存中取出值\n '''\n pass\n\n def WriteBack(self):\n '''\n @description: 写回阶段\n @param {type} \n @return: 将计算结果写回寄存器文件\n '''\n pass\n\n def HazardUnit(self):\n '''\n @description: 冲突单元\n @param {type} \n @return: \n '''\n pass\n\n def ConvertImmNum(self, num_str):\n '''\n @description: 将用小端法表示的立即数转换为十进制整数\n @param {type} num_str {str}\n @return: int\n '''\n '''\n >>> ConvertImmNum(\"10000000\")\n 16\n >>> ConvertImmNum(\"10100000\")\n 4112\n '''\n # 将立即数反转为正常顺序\n rev_str = \"\"\n for i in range(6, 0, -2):\n rev_str += (num_str[i] + num_str[i + 1])\n return int(\"0x\" + rev_str, 16)\n\n\nif __name__ == \"__main__\":\n simulator = CPUSimulator(\n \"D:/Materials_Study/Computer_Science/Computer_Architecture/Exercises/Y86-64_CPU_Simulator/cpu_simulator/testbench\"\n ) # Windows\n # simulator = CPUSimulator(\n # \"/media/fisher/DATA/Materials_Study/Computer_Science/Computer_Architecture/Exercises/Y86-64_CPU_Simulator/cpu_simulator/testbench\"\n # ) # Linux\n simulator.MainProcess()\n reg = 0\n print(simulator.regFile[reg]) # 结果的值在rax里\n","sub_path":"Y86-64_CPU_Simulator/cpu_simulator/Y86_simulator.py","file_name":"Y86_simulator.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"65077462","text":"from selenium import webdriver\nfrom time import sleep\nfrom PIL import Image\nimport pytesseract\n\n\n\nclass Bot:\n def __init__(self):\n self.driver = webdriver.Firefox()\n self.navigate()\n\n def take_screenshot(self):\n self.driver.save_screenshot('avito_screenshot.png')\n\n def tel_recon(self):\n pytesseract.pytesseract.tesseract_cmd = r\"C:\\Users\\happy\\AppData\\Local\\Tesseract-OCR\\tesseract.exe\"\n image = Image.open('tel.gif')\n print(pytesseract.image_to_string(image))\n\n def crop(self, location, size):\n image = Image.open('avito_screenshot.png')\n x = location['x']\n y = location['y']\n width = size['width']\n height = size['height']\n\n image.crop((x, y, x+width, y+height)).save('tel.gif')\n self.tel_recon()\n\n def navigate(self):\n self.driver.get('https://www.avito.ru/ekaterinburg/telefony/iphone_x_1835790565')\n\n button = self.driver.find_element_by_xpath('//a[@class=\"button item-phone-button js-item-phone-button button-origin button-origin-blue button-origin_full-width button-origin_large-extra item-phone-button_hide-phone item-phone-button_card js-item-phone-button_card\"]')\n button.click()\n\n sleep(3)\n\n self.take_screenshot()\n\n image = self.driver.find_element_by_xpath('//div[@class=\"item-phone-big-number js-item-phone-big-number\"]//*')\n location = image.location #dict {'x': 2323, 'y': 23423}\n size = image.size # dict {'width': 234, 'height': 234}\n\n self.crop(location, size)\n\ndef main():\n b = Bot()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"OlegMolchanov's_Py_lesson/Parsing/Avito_tel/avito.py","file_name":"avito.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"226040055","text":"#!/usr/bin/env python3\nimport sys\nimport os.path\nimport re\n\ndef increase_style_resource_id_value(path, delta=100):\n\tdoc = open(path, encoding='utf-8', newline='\\n').read()\n\tupdated = re.sub(r'\\d{5}', lambda m: str(int(m.group(0)) + delta), doc)\n\tprint('update:', path)\n\twith open(path, 'w', encoding='utf-8', newline='\\n') as fp:\n\t\tfp.write(updated)\n\ndef check_encoding_list(path):\n\tdef is_tag_char(ch):\n\t\treturn (ch >= 'a' and ch <= 'z') or (ch >= '0' and ch <= '9')\n\n\tdoc = open(path, encoding='utf-8', newline='\\n').read()\n\tlines = doc.splitlines()\n\tstarted = False\n\tname_map = {}\n\ttag_map = {}\n\tpage_map = {}\n\n\tfor index, line in enumerate(lines):\n\t\tif not started:\n\t\t\tstarted = line.startswith('NP2ENCODING mEncoding[] = {')\n\t\telif line.startswith('};'):\n\t\t\tbreak\n\t\telse:\n\t\t\tstart = line.find('\"')\n\t\t\tif start < 0:\n\t\t\t\tcontinue\n\t\t\tstart += 1\n\t\t\tend = line.index('\"', start)\n\t\t\ttag = line[start:end]\n\t\t\tif not tag:\n\t\t\t\tcontinue\n\n\t\t\tstart = line.index(',') + 1\n\t\t\tend = line.index(',', start)\n\t\t\tpage = line[start:end].strip()\n\n\t\t\tlineno = index + 1\n\t\t\tif tag[-1] != ',':\n\t\t\t\tprint('missing trailing comma at line:', lineno, page, tag)\n\t\t\ts = ''.join(tag.split())\n\t\t\tif s != tag:\n\t\t\t\tprint('space in encoding at line:', lineno, page, tag)\n\n\t\t\titems = tag[:-1].split(',')\n\t\t\tname = items[0].lower()\n\t\t\titems = items[1:]\n\t\t\ts = ''.join(items)\n\t\t\tif any(not is_tag_char(ch) for ch in s):\n\t\t\t\tprint('tag not normalized at line:', lineno, page, tag)\n\n\t\t\tif name not in name_map:\n\t\t\t\tname_map[name] = [lineno]\n\t\t\telse:\n\t\t\t\tname_map[name].append(lineno)\n\n\t\t\tfor item in items:\n\t\t\t\tif item not in tag_map:\n\t\t\t\t\ttag_map[item] = [lineno]\n\t\t\t\telse:\n\t\t\t\t\ttag_map[item].append(lineno)\n\n\t\t\tif page not in page_map:\n\t\t\t\tpage_map[page] = [lineno]\n\t\t\telse:\n\t\t\t\tpage_map[page].append(lineno)\n\n\tfor name, lines in name_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same encoding name:', name, lines)\n\tfor tag, lines in tag_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same encoding tag:', tag, lines)\n\tfor page, lines in page_map.items():\n\t\tif len(lines) > 1:\n\t\t\tprint('same code page:', page, lines)\n\n#increase_style_resource_id_value('../src/EditLexers/EditStyle.h')\ncheck_encoding_list('../src/EditEncoding.c')\n","sub_path":"tools/Misc.py","file_name":"Misc.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"230316337","text":"#! /usr/bin/python\n\n\"\"\"\nLinearRegression.py\n\nThis class is designed to perform linear regression (gradient descent) \non a dataset and then be able to predict given new x labels.\n\"\"\"\n\n__author__ = 'Manan Mehta'\n__email__ = 'mehtamanan@icloud.com'\n__version__ = '1.0.0'\n\nimport sys\nimport numpy as np\nimport plotly as py\nimport matplotlib.pyplot as plt\n\nfrom Exceptions import *\n\nclass LinearRegression(object):\n \"\"\" \n Contains methods to load data, normalize data, plot data and predict outputs\n \"\"\"\n\n def __init__(self):\n self.norm = False #Data has not been normalized\n self.gd = False #Gradient descent has not been carried out\n\n def load_data(self, *files):\n \"\"\"\n If two files are given, the first one is assumed\n to contain X values and the second one, Y.\n If one file is given, the last column is assumed\n to contain Y values and the columns before, X.\n \"\"\"\n if len(files) == 1:\n dataXY = np.matrix(np.genfromtxt(files[0], delimiter = ','))\n pos = dataXY.shape[1]\n y = dataXY[:, pos -1]\n X = dataXY[:, :pos - 1]\n else:\n X = np.matrix(np.genfromtxt(files[0], delimiter = ','))\n y = np.matrix(np.genfromtxt(files[1], delimiter = ','))\n ones = np.matrix(np.ones(shape = (X.shape[0], 1)))\n self.X = np.hstack((ones, X))\n self.y = y\n self.theta = np.matrix(np.zeros(shape = (self.X.shape[1], 1)))\n self.norm = False\n self.gd = False\n self.gradient_descent()\n\n def plot(self):\n \"\"\"\n Plots the loaded data and the prediction line\n Throws DataHandlingException if more than one x-label\n Throws NoDataException if data is not loaded\n \"\"\"\n if not hasattr(self, 'X'): # To raise an exception is data is not loaded\n raise NoDataException()\n elif self.X.shape[1] > 2: # To raise an exception if there way to many exceptions\n raise DataHandlingException()\n else:\n X = self.X[:,1]\n y = self.X * self.theta\n plt.plot(self.X[:,1], self.y, 'rx', X, y, 'g-')\n plt.show()\n\n def normalize(self):\n \"\"\"\n Normalizes the data such that the mean is 0\n and the data fits -0.5 2:\n return False\n else:\n return True\n","sub_path":"LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"557492285","text":"import datetime as dt\nimport json\n\nimport numpy as np\nimport pytest\n\nfrom slim.simulation.lice_population import LicePopulation, from_dict, geno_to_alleles\nfrom slim.simulation.cage import Cage\nfrom slim.simulation.config import to_dt\nfrom slim.types.treatments import Treatment\n\n\nclass TestFarm:\n def test_farm_loads_params(self, first_farm):\n assert first_farm.id_ == 0\n assert len(first_farm.cages) == 6\n assert first_farm.loc_x == 190300\n assert first_farm.loc_y == 665300\n assert first_farm.available_treatments == 10\n\n def test_farm_str(self, first_farm):\n farm_str = str(first_farm)\n assert isinstance(farm_str, str)\n assert len(farm_str) > 0\n assert \"id: 0\" in farm_str\n\n def test_year_temperatures(self, first_farm):\n tarbert = first_farm.cfg.loch_temperatures[1][1:]\n ardrishaig = first_farm.cfg.loch_temperatures[0][1:]\n temps = np.stack([tarbert, ardrishaig])\n min_temps = np.round(np.min(temps, axis=0), 1)\n max_temps = np.round(np.max(temps, axis=0), 1)\n assert all(min_temps <= first_farm.year_temperatures)\n assert all(first_farm.year_temperatures <= max_temps)\n\n def test_farm_update(self, first_farm):\n # TODO: test integration across **all** cages. Requires further refactoring.\n pass\n\n def test_get_cage_pressures(self, first_farm, initial_external_inflow):\n\n first_farm.cfg.min_ext_pressure = 100\n first_farm.cages = [0] * 10\n\n pressures = first_farm.get_cage_pressures(100)\n\n assert len(pressures) == len(first_farm.cages)\n assert sum(pressures) == first_farm.cfg.min_ext_pressure * 10\n\n for pressure in pressures:\n assert pressure >= 0\n\n def test_get_cage_pressures_negative_pressure(self, first_farm):\n\n first_farm.cfg.min_ext_pressure = -100\n first_farm.cages = [0] * 10\n\n with pytest.raises(Exception):\n first_farm.get_cage_pressures()\n\n def test_get_cage_pressures_zero_pressure(self, first_farm):\n first_farm.cfg.min_ext_pressure = 0\n first_farm.cages = [0] * 10\n\n pressures = first_farm.get_cage_pressures(0)\n\n assert len(pressures) == len(first_farm.cages)\n assert sum(pressures) == first_farm.cfg.min_ext_pressure\n\n def test_get_cage_pressures_no_cages(self, first_farm):\n\n first_farm.cfg.min_ext_pressure = 100\n first_farm.cages = []\n\n with pytest.raises(Exception):\n first_farm.get_cage_pressures()\n\n @pytest.mark.parametrize(\n \"eggs_by_hatch_date\",\n [\n {\n to_dt(\"2017-02-01 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 200,\n \"Aa\": 300,\n }\n ),\n to_dt(\"2017-02-10 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 200,\n \"Aa\": 300,\n }\n ),\n },\n {},\n ],\n )\n def test_get_cage_allocation(self, first_farm, eggs_by_hatch_date):\n\n allocation = first_farm.get_cage_allocation(6, eggs_by_hatch_date)\n\n # Originally, this would extract the allocation for each gene\n allocation_list = [\n np.sum(n)\n for bin_dict in allocation\n for hatch_dict in bin_dict.values()\n for n in hatch_dict.values()\n ]\n if eggs_by_hatch_date == {}:\n sum_eggs_by_hatch_date = 0\n else:\n sum_eggs_by_hatch_date = sum(\n sum(\n [\n n\n for hatch_dict in eggs_by_hatch_date.values()\n for n in hatch_dict.values()\n ]\n )\n )\n\n assert sum(allocation_list) == sum_eggs_by_hatch_date\n assert len(allocation) == len(first_farm.cages)\n\n for n in allocation_list:\n assert n >= 0\n\n allocation_keys_list = [list(bin_dict.keys()) for bin_dict in allocation]\n hatch_keys = list(eggs_by_hatch_date.keys())\n for allocation_keys in allocation_keys_list:\n assert allocation_keys == hatch_keys\n\n def test_get_farm_allocation(\n self, first_farm, second_farm, sample_offspring_distrib\n ):\n first_farm.cfg.interfarm_probs[first_farm.id_][second_farm.id_] = 0.1\n\n total_eggs_by_date = {first_farm.start_date: sample_offspring_distrib}\n farm_eggs_by_date = first_farm.get_farm_allocation(\n second_farm.id_, total_eggs_by_date\n )\n\n assert len(farm_eggs_by_date) == len(total_eggs_by_date)\n assert (\n farm_eggs_by_date[first_farm.start_date].keys()\n == total_eggs_by_date[first_farm.start_date].keys()\n )\n for geno in geno_to_alleles(\"a\"):\n assert (\n farm_eggs_by_date[first_farm.start_date][geno]\n <= total_eggs_by_date[first_farm.start_date][geno]\n )\n\n def test_get_farm_allocation_empty(self, first_farm, second_farm):\n farm_eggs_by_date = first_farm.get_farm_allocation(second_farm, {})\n assert farm_eggs_by_date == {}\n\n def test_disperse_offspring(self, first_farm, second_farm):\n farms = [first_farm, second_farm]\n eggs_by_hatch_date = {\n to_dt(\"2017-01-05 00:00:00\"): from_dict(\n {\n \"A\": 100,\n \"a\": 100,\n \"Aa\": 100,\n }\n )\n }\n cur_date = to_dt(\"2017-01-01 00:00:00\")\n\n new_rng = np.random.default_rng(seed=2021)\n farms[0].cfg.rng = new_rng\n farms[0].cages = farms[0].cages[:2]\n farms[1].cages = farms[1].cages[:2]\n\n arrivals_farm0 = farms[0].disperse_offspring(eggs_by_hatch_date, cur_date)\n arrivals_farm1 = farms[1].disperse_offspring(eggs_by_hatch_date, cur_date)\n farms[0].update_arrivals(arrivals_farm0[0])\n farms[0].update_arrivals(arrivals_farm1[0])\n\n # Only for the calling cage\n for cage in first_farm.cages:\n assert cage.arrival_events.qsize() >= 1\n\n def test_get_cage_arrivals_stats(self, first_farm, cur_day):\n\n next_day = cur_day + dt.timedelta(1)\n\n cage_1 = {\n cur_day: from_dict(\n {\n \"A\": 10,\n \"a\": 10,\n \"Aa\": 10,\n }\n ),\n next_day: from_dict(\n {\n \"A\": 10,\n \"a\": 10,\n \"Aa\": 20,\n }\n ),\n }\n\n cage_2 = {\n cur_day: from_dict(\n {\n \"A\": 5,\n \"a\": 5,\n \"Aa\": 5,\n }\n ),\n next_day: from_dict(\n {\n \"A\": 5,\n \"a\": 5,\n \"Aa\": 10,\n }\n ),\n }\n\n arrivals = [cage_1, cage_2]\n\n total, by_cage, _ = first_farm.get_cage_arrivals_stats(arrivals)\n\n assert total == 105\n assert by_cage == [70, 35]\n\n def test_farm_update_before_start(\n self, first_farm, initial_external_inflow, initial_external_ratios\n ):\n cur_date = first_farm.start_date - dt.timedelta(1)\n offspring, cost = first_farm.update(\n cur_date, initial_external_inflow, initial_external_ratios\n )\n\n assert offspring == {}\n assert cost > 0 # fallowing\n\n # Currently fixtures are not automatically loaded in the parametrisation, so they need to be manually invoked\n # See https://github.com/pytest-dev/pytest/issues/349\n @pytest.mark.parametrize(\n \"test_farm, expected_cost\", [(\"first_farm\", 0), (\"second_farm\", 0)]\n )\n def test_update(\n self,\n sample_offspring_distrib,\n initial_external_ratios,\n initial_external_inflow,\n test_farm,\n expected_cost,\n request,\n ):\n\n # ensure number of matings\n initial_lice_pop = {stage: 100 for stage in LicePopulation.lice_stages}\n\n test_farm = request.getfixturevalue(test_farm)\n\n # ensure number of different hatching dates through a number of cages\n test_farm.cfg.farms[test_farm.id_].cages_start = [\n test_farm.start_date for i in range(10)\n ]\n test_farm.cages = [\n Cage(i, test_farm.cfg, test_farm, initial_lice_pop) for i in range(10)\n ]\n\n eggs_by_hatch_date, cost = test_farm.update(\n test_farm.start_date, initial_external_inflow, initial_external_ratios\n )\n\n for hatch_date in eggs_by_hatch_date:\n assert hatch_date > test_farm.start_date\n\n for geno in geno_to_alleles(\"a\"):\n assert eggs_by_hatch_date[hatch_date][geno] > 0\n\n # TODO: need to check that the second farm has a positive infrastructure cost\n assert cost == expected_cost\n\n def test_eq(self, first_farm, second_farm):\n assert first_farm == first_farm\n assert first_farm != second_farm\n assert first_farm != 0\n assert first_farm != \"dummy\"\n\n def test_treatment_limit(self, first_farm, first_cage):\n treatment_step_size = dt.timedelta(days=50)\n cur_day = first_farm.farm_cfg.treatment_dates[-1][0] + treatment_step_size\n\n for i in range(10):\n assert first_farm.add_treatment(Treatment.EMB, cur_day)\n assert (\n first_cage.treatment_events.qsize() == 3 + i + 1\n ) # the first treatment cannot be applied\n # Test treatments are not counted, unless add_treatment is called\n assert first_farm.available_treatments == 10 - i - 1\n cur_day += treatment_step_size\n\n assert not first_farm.add_treatment(Treatment.EMB, cur_day)\n assert first_farm.available_treatments == 0\n\n def test_prescheduled_sampling_events(self, first_farm, cur_day):\n first_farm._report_sample(cur_day)\n assert first_farm._get_aggregation_rate() <= 0.1\n\n # One test today, one test in 14 days, another test in 28 days\n # The first has already been consumed\n first_farm._report_sample(cur_day + dt.timedelta(days=21))\n assert first_farm._get_aggregation_rate() > 0.0\n\n # The second too\n first_farm._report_sample(cur_day + dt.timedelta(days=28))\n assert first_farm._get_aggregation_rate() > 0.0\n\n \"\"\"\n def test_ask_for_treatment_no_defection(\n self, no_prescheduled_farm, cur_day, initial_external_ratios\n ):\n first_cage = no_prescheduled_farm.cages[0]\n assert first_cage.treatment_events.qsize() == 0\n first_available_day = cur_day + dt.timedelta(days=30)\n no_prescheduled_farm.ask_for_treatment(first_available_day, False)\n assert first_cage.treatment_events.qsize() == 1\n\n # Asking again will not work, but it requires some internal cage update\n first_cage.update(first_available_day, 0, initial_external_ratios)\n no_prescheduled_farm.ask_for_treatment(first_available_day, False)\n assert first_cage.treatment_events.qsize() == 0\n\n def test_ask_for_treatment(\n self, no_prescheduled_farm, no_prescheduled_cage, cur_day\n ):\n assert no_prescheduled_cage.treatment_events.qsize() == 0\n\n for i in range(12):\n first_available_day = cur_day + dt.timedelta(days=30 * i)\n no_prescheduled_farm.ask_for_treatment()\n assert no_prescheduled_cage.treatment_events.qsize() == 9\n\n \"\"\"\n","sub_path":"tests/test_Farm.py","file_name":"test_Farm.py","file_ext":"py","file_size_in_byte":11753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"16549470","text":"from subprocess import call\nfrom os import makedirs\nfrom os import path\nfrom shutil import copy\n\n\ndef do_step(context):\n\n if not path.isdir(\"bosh/manifests\"):\n makedirs(\"bosh/manifests\")\n\n # Generate the private key and certificate\n call(\"sh create_cert.sh\", shell=True)\n copy(\"bosh.key\", \"./bosh/bosh\")\n with open('bosh_cert.pem', 'r') as tmpfile:\n ssh_cert = tmpfile.read()\n ssh_cert = \"|\\n\" + ssh_cert\n ssh_cert = \"\\n \".join([line for line in ssh_cert.split('\\n')])\n\n context.meta['settings']['SSH_CERTIFICATE'] = ssh_cert\n\n return context\n","sub_path":"install_steps/create_bosh_cert.py","file_name":"create_bosh_cert.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"209498616","text":"\nfrom django.contrib import messages\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AdminPasswordChangeForm, PasswordChangeForm\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom social_django.models import UserSocialAuth\n\nfrom jos_stories.models import Story\nfrom jos_comments.models import Comment, CommentThread\nfrom .models import Follow, Profile\n\n\ndef get_followed_ids(usr):\n following_id_dicts = Follow.objects.filter(follower=usr) \\\n .values('followed_id') \\\n .order_by('-created')\n\n followed_ids = []\n if following_id_dicts:\n for item in following_id_dicts:\n followed_ids.append(item['followed_id'])\n\n return followed_ids\n\n\ndef new_member(request):\n\n user = get_object_or_404(User, pk=request.user.id)\n short_name = user.get_short_name()\n username = user.username\n\n Story.objects.create(author=user,\n profile=user.profile,\n description=username + '; profile',\n title='About ' + short_name)\n\n email_address = user.email\n send_mail('Welcome to Join Our Story',\n 'We are glad you are here!',\n 'joinus@joinourstory.com',\n [email_address],\n fail_silently=True)\n\n context = {\n 'page_title': 'welcome',\n }\n\n return render(request, 'jos_members/new_member.html', context)\n\n\n@login_required\ndef favor(request):\n favor_id = request.GET.get(\"favor_id\", \"missing\")\n\n if favor_id != 'missing':\n add_follower = User.objects.get(pk=favor_id)\n Follow.objects.add_follower(request.user, add_follower)\n\n return redirect('members:friends')\n\n\n@login_required\ndef unfavor(request):\n unfavor_id = request.GET.get(\"unfavor_id\", \"missing\")\n\n if unfavor_id != 'missing':\n remove_follower = User.objects.get(pk=int(unfavor_id))\n Follow.objects.remove_follower(request.user, remove_follower)\n\n return redirect('members:friends')\n\n\n# Has something to do with fb login\n@login_required\ndef member_settings(request):\n user = request.user\n\n try:\n facebook_login = user.social_auth.get(provider='facebook')\n except UserSocialAuth.DoesNotExist:\n facebook_login = None\n\n can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password())\n\n return render(request, 'jos_members/settings.html', {\n 'facebook_login': facebook_login,\n 'can_disconnect': can_disconnect\n })\n\n\n@login_required\ndef member_password(request):\n if request.user.has_usable_password():\n PasswordForm = PasswordChangeForm\n else:\n PasswordForm = AdminPasswordChangeForm\n\n if request.method == 'POST':\n form = PasswordForm(request.user, request.POST)\n if form.is_valid():\n form.save()\n update_session_auth_hash(request, form.user)\n messages.success(request, 'Your password was successfully updated!')\n return redirect('password')\n else:\n messages.error(request, 'Please correct the error below.')\n else:\n form = PasswordForm(request.user)\n return render(request, 'jos_members/password.html', {'form': form})\n\n\n@login_required\ndef my_space(request):\n user_id = request.GET.get(\"user_id\", \"missing\")\n\n if user_id != 'missing':\n member = get_object_or_404(User, pk=int(user_id))\n\n public_stories = Story.objects.exclude(description__icontains='treat')\\\n .filter(author=member, sharing_level=2).order_by('-updated')\n public_treats = Story.objects\\\n .filter(description__icontains='treat', author=member).order_by('-updated')\n\n private_stories = Story.objects.filter(author=member) \\\n .exclude(description__icontains='treat') \\\n .exclude(description__icontains='profile').order_by('-updated')\n\n try:\n about = Story.objects.get(description=str(member.id) + '; profile')\n except:\n about = Story.objects.create(author=member,\n profile=member.profile,\n description=str(member.id) + '; profile',\n title='About ' + member.profile.jos_name)\n\n return render(request, 'jos_members/my_space.html', {\n 'page_title': 'stuff',\n 'profile': member.profile,\n 'about': about,\n \"public_stories\": public_stories,\n \"public_treats\": public_treats,\n \"private_stories\": private_stories\n })\n\n return HttpResponse('SERVER RESPONSE: cannot find user')\n\n\ndef ajax_member_search(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_member_search, Not an ajax call.')\n\n search_text = \"0\"\n found_members = \"0\"\n\n if request.method == \"GET\":\n search_text = request.GET.get(\"search_text\", \"0\").strip().lower()\n\n following_id_dicts = Follow.objects \\\n .filter(follower=request.user) \\\n .values('followed_id') \\\n .order_by('-created')\n\n all_fs_ids = []\n if following_id_dicts:\n for item in following_id_dicts:\n all_fs_ids.append(item['followed_id'])\n\n if search_text != \"0\":\n found_members = User.objects.filter(username__icontains=search_text)\\\n .exclude(id__in=all_fs_ids).order_by('username') \\\n\n if len(found_members) == 0:\n found_members = \"missing\"\n\n context = {\n \"search_text\": search_text,\n \"found_members\": found_members\n }\n\n return render(request, \"jos_members/member_search_response.html\", context)\n\n\ndef ajax_update_member_info(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_update_member_info, Not an ajax call.')\n\n user_profile = get_object_or_404(Profile, user=request.user)\n\n if request.method == \"POST\":\n new_note_text = request.POST.get(\"note_text\", \"0\")\n if new_note_text != \"0\":\n user_profile.note_text = new_note_text\n user_profile.save()\n\n return HttpResponse(\"SERVER RESPONSE new note: \" + new_note_text)\n\n return HttpResponse(\"SERVER RESPONSE story update fell through!\")\n\n\ndef ajax_address_book(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_address_book, Not an ajax call.')\n\n profile = request.user.profile\n address_book = profile.address_book\n\n if type(address_book) is not list:\n address_book = []\n\n if request.method == \"POST\":\n nick = request.POST.get(\"nick\", \"0\")\n email = request.POST.get(\"email\", \"0\")\n delete_address = request.POST.get(\"delete\", \"0\")\n\n if delete_address != \"0\" and address_book != []:\n new_address_book = []\n for address in address_book:\n if address[1] != delete_address:\n new_address_book.append(address)\n profile.address_book = new_address_book\n profile.save()\n\n if email != \"0\" and nick != \"0\":\n new_address = [nick, email]\n address_book.append(new_address)\n profile.address_book = address_book\n profile.save()\n\n context = {'address_book': profile.address_book}\n\n return render(request, \"jos_members/address_book_response.html\", context)\n\n\ndef ajax_all_friends(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_all_friends, Not an ajax call.')\n\n followed_ids = get_followed_ids(request.user)\n search_text = request.GET.get('search_text', '0')\n\n all_fs = []\n if followed_ids:\n for fid in followed_ids:\n user = get_object_or_404(User, id=fid)\n if search_text in user.username.lower() or search_text == '0':\n all_fs.append(user)\n\n new_comment_ids = []\n new_comment_bodies = []\n new_friends = []\n new_comment_friend_ids = []\n\n read_comment_ids = []\n read_comment_bodies = []\n read_friends = []\n\n sent_comment_ids = []\n sent_comment_bodies = []\n sent_friends = []\n\n\n none_comment_ids = []\n none_comment_bodies = []\n none_friends = []\n\n for friend in all_fs:\n last_comment = Comment.objects.exclude(comment_thread__thread_scope='story') \\\n .filter(Q(sender__id=request.user.id, recipient=friend) |\n Q(sender=friend, recipient__id=request.user.id)).order_by('-id').first()\n\n if last_comment and last_comment.recipient == request.user and last_comment.read_at is None:\n new_comment_ids.append(last_comment.id)\n new_comment_bodies.append(last_comment.body)\n new_friends.append(friend)\n new_comment_friend_ids.append(friend.id)\n\n elif last_comment and last_comment.recipient == request.user:\n read_comment_ids.append(last_comment.id)\n read_comment_bodies.append(last_comment.body)\n read_friends.append(friend)\n\n elif last_comment:\n sent_comment_ids.append(last_comment.id)\n sent_comment_bodies.append(last_comment.body)\n sent_friends.append(friend)\n\n else:\n none_comment_ids.append(0)\n none_comment_bodies.append('missing')\n none_friends.append(friend)\n\n\n sorted_comment_ids = new_comment_ids + read_comment_ids + sent_comment_ids + none_comment_ids\n sorted_comment_bodies = new_comment_bodies + read_comment_bodies + sent_comment_bodies + none_comment_bodies\n sorted_friends = new_friends + read_friends + sent_friends + none_friends\n\n\n context = {'sorted_friends': sorted_friends,\n 'new_comment_friend_ids': new_comment_friend_ids,\n 'sorted_comment_ids': sorted_comment_ids,\n 'sorted_comment_bodies': sorted_comment_bodies}\n\n\n # return HttpResponse('SERVER RESPONSE: ajax_all_friends,' +\n # 'sorted_friends_ids: ' + str(sorted_friends_ids) +\n # 'last_comment_bodies: ' + str(last_comment_bodies))\n\n\n return render(request, \"jos_members/all_friends_response.html\", context)\n\n\ndef ajax_not_friend_comments(request):\n if not request.is_ajax():\n return HttpResponse('SERVER RESPONSE: ajax_not_friend_comments, Not an ajax call.')\n\n context = {}\n followed_ids = get_followed_ids(request.user)\n\n threads = CommentThread.objects \\\n .filter(first_recipient_id=request.user.id, thread_scope='individual') \\\n .order_by('-id')\n\n last_comment_ids = []\n\n if threads:\n for thread in threads:\n last_comment = thread.comments.latest('sent_at')\n if not last_comment.recipient_deleted_at:\n last_comment_ids.append(last_comment.id)\n\n last_comments = Comment.objects.filter(pk__in=last_comment_ids)\n\n not_friend_comments = last_comments.exclude(sender_id__in=followed_ids).order_by('-id')\n\n context = {'not_friend_comments': not_friend_comments}\n\n return render(request, \"jos_members/not_friends_response.html\", context)\n\n\n@login_required\ndef friends(request):\n context = {\n 'page_title': 'friends',\n }\n\n return render(request, \"jos_members/friends.html\", context)\n\n","sub_path":"jos_members/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"293385314","text":"from itertools import permutations\nmatris=[]\nwhile True:\n try:\n mertebe=int(input(\"Lütfen katsayılar matrisinin satır sayısını giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile mertebe<1:\n print(\"Satır sayısı pozitif olmalı.\")\n while True:\n try:\n mertebe=int(input(\"Lütfen katsayılar matrisinin satır sayısını giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nfor i in range(mertebe):\n satır=[]\n for j in range(mertebe):\n while True:\n try:\n eleman=float(input(\"Lütfen katsayılar matrisinin {}. satırının {}.elamanını giriniz:\".format(i+1,j+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n satır.append(eleman)\n matris.append(satır)\nsonuç=[]\nfor i in range(mertebe):\n while True:\n try:\n değer=float(input(\"Lütfen {}. denklemin sağ tarafındaki değeri giriniz:\".format(i+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n sonuç.append(değer)\nwhile True:\n try:\n epsilon=float(input(\"Lütfen epsilon değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile epsilon<=0:\n print(\"Epsilon değeri 0'dan küçük olamaz.\")\n try:\n epsilon = float(input(\"Lütfen epsilon değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nbaşlangıç=[]\nfor i in range(mertebe):\n while True:\n try:\n x=float(input(\"Lütfen {}. değişkenin başlangıç değerini giriniz:\".format(i+1)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n başlangıç.append(x)\nmax=0\nsum=1\nper_mat=list(permutations(matris))\nper_son=list(permutations(sonuç))\nfor i in range(len(per_mat)):\n for j in range(mertebe):\n sum*=abs(per_mat[i][j][j])\n if maxepsilon:\n sum+=1\n return sum\nwhile control()>0:\n it1 = function2(it2)\n it2 = function2(it1)\n delta = [abs(it1[i] - it2[i]) for i in range(mertebe)]\nfor i in range(mertebe):\n print(\"{}. değişkenin değeri:{}\".format(i+1,it2[i]))\n","sub_path":"gauss seidel.py","file_name":"gauss seidel.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"327553812","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`metaopt.core.utils` -- Package-wide useful routines\n=========================================================\n\n.. module:: utils\n :platform: Unix\n :synopsis: Helper functions useful in possibly all :mod:`metaopt.core`'s modules.\n\"\"\"\n\nfrom abc import ABCMeta\nfrom glob import glob\nfrom importlib import import_module\nimport os\n\n\nclass SingletonType(type):\n \"\"\"Metaclass that implements the singleton pattern for a Python class.\"\"\"\n\n def __init__(cls, name, bases, dictionary):\n \"\"\"Create a class instance variable and initiate it to None object.\"\"\"\n super(SingletonType, cls).__init__(name, bases, dictionary)\n cls.instance = None\n\n def __call__(cls, *args, **kwargs):\n \"\"\"Create an object if does not already exist, otherwise return what there is.\"\"\"\n if cls.instance is None:\n cls.instance = super(SingletonType, cls).__call__(*args, **kwargs)\n elif args or kwargs:\n raise ValueError(\"A singleton instance has already been instantiated.\")\n return cls.instance\n\n\nclass AbstractSingletonType(SingletonType, ABCMeta):\n \"\"\"This will create singleton base classes, that need to be subclassed and implemented.\"\"\"\n\n pass\n\n\nclass Factory(type):\n \"\"\"Instantiate appropriate wrapper for the infrastructure based on input\n argument, ``of_type``.\n\n Attributes\n ----------\n types : list of subclasses of ``cls.__base__``\n Updated to contain all possible implementations currently. Check out code.\n typenames : list of str\n Names of implemented wrapper classes, correspond to possible ``of_type``\n values.\n\n \"\"\"\n\n def __init__(cls, names, bases, dictionary):\n \"\"\"Search in directory for attribute names subclassing `bases[0]`\"\"\"\n super(Factory, cls).__init__(names, bases, dictionary)\n\n cls.modules = []\n base = import_module(cls.__base__.__module__)\n py_files = glob(base.__path__[0] + '/[A-Za-z]*.py')\n py_mods = map(lambda x: '.' + os.path.split(os.path.splitext(x)[0])[1], py_files)\n for py_mod in py_mods:\n cls.modules.append(import_module(py_mod, package=cls.__base__.__module__))\n\n cls.types = [cls.__base__] + cls.__base__.__subclasses__()\n cls.types = [class_ for class_ in cls.types if class_.__name__ != cls.__name__]\n cls.typenames = list(map(lambda x: x.__name__, cls.types))\n\n def __call__(cls, of_type=None, *args, **kwargs):\n \"\"\"Create an object, instance of ``cls.__base__``, on first call.\n\n :param of_type: Name of class, subclass of ``cls.__base__``, wrapper\n of a database framework that will be instantiated on the first call.\n :param args: positional arguments to initialize ``cls.__base__``'s instance (if any)\n :param kwargs: keyword arguments to initialize ``cls.__base__``'s instance (if any)\n\n .. seealso::\n `Factory.typenames` for values of argument `of_type`.\n\n .. seealso::\n Attributes of ``cls.__base__`` and ``cls.__base__.__init__`` for\n values of `args` and `kwargs`.\n\n .. note:: New object is saved as `Factory`'s internal state.\n\n :return: The object which was created on the first call.\n \"\"\"\n if of_type is None:\n of_type = cls.__base__.__name__\n\n for inherited_class in cls.types:\n if inherited_class.__name__.lower() == of_type.lower():\n return inherited_class.__call__(*args, **kwargs)\n\n error = \"Could not find implementation of {0}, type = '{1}'\".format(\n cls.__base__.__name__, of_type)\n error += \"\\nCurrently, there is an implementation for types:\\n\"\n error += str(cls.typenames)\n raise NotImplementedError(error)\n\n\nclass SingletonFactory(AbstractSingletonType, Factory):\n \"\"\"Wrapping `Factory` with `SingletonType`. Keep compatibility with `AbstractSingletonType`.\"\"\"\n\n pass\n","sub_path":"src/metaopt/core/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"366860708","text":"#!/usr/bin/env python\n############################################################################################\n#\n# Nagios plugin to validate pods are running on separate nodes\n#\n# If 2 pods from the same component are running on the same node, return a warning message\n#\n# Copyright (c) 2018, Red Hat Ltd. All rights reserved.\n#\n############################################################################################\nimport sys\nimport traceback\n\nimport nagios\nimport openshift\n\n\ndef report(issues):\n if not issues:\n print(\"OK: Component pod distribution as expected\")\n nag_status = nagios.OK\n else:\n for issue in issues:\n print(issue)\n nag_status = nagios.WARN\n return nag_status\n\n\ndef check():\n issues = []\n project = openshift.get_project()\n deploymentConfigs = openshift.get_deploymentconfigs(project)\n for deploymentConfig in deploymentConfigs[\"items\"]:\n componentName = deploymentConfig[\"metadata\"][\"name\"]\n pods = openshift.get_running_pod_names(\n project, container_names=componentName)\n nodes = openshift.get_nodes_from_names(pods)\n if len(pods) > 1:\n for node in set(nodes):\n nodeCount = nodes.count(node)\n if nodeCount > 1:\n issues.append(\"WARN: %s has %s pods running on the same node: %s\" % (\n componentName, nodeCount, node))\n return report(issues)\n\n\nif __name__ == \"__main__\":\n code = nagios.UNKNOWN\n try:\n code = check()\n except:\n traceback.print_exc()\n finally:\n sys.exit(code)\n","sub_path":"plugins/default/lib/pod_affinity.py","file_name":"pod_affinity.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"26390416","text":"# Find the nth prime number\n\nprimes = []\n\ndef compute_primes_to(num):\n if len(primes) == 0:\n current = 2\n else:\n current = primes[-1]+1\n \n breakpoint = len(primes) + num\n \n while True:\n if is_prime(current):\n primes.append(current)\n current += 1\n if len(primes) >= breakpoint:\n break\n \n return primes\n \ndef get_prime_at(num):\n if len(primes) >= num:\n return primes[num-1]\n else:\n return \"primes haven't been computed to this point\"\n\ndef size_of_primes():\n return len(primes)\n \ndef is_prime(num):\n prime = True\n for j in range(1,num):\n if j == num and num % j == 0:\n print(\"meets divisible by self criteria\")\n if j != 1 and j != num and num % j == 0:\n prime = False\n break\n if prime:\n return True\n else:\n return False\n \n# compute primes to n\n# show the value of prime at n\n\n#compute_primes_to(10001)\n#print(str(get_prime_at(10001)))","sub_path":"project_euler/problem_7/find_prime.py","file_name":"find_prime.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"}
+{"seq_id":"193702320","text":"# zigzag ribbon\nimport sys\nsys.path.append(\"../../../pygra\") # add pygra library\n\nimport geometry\ng = geometry.honeycomb_armchair_ribbon(60) # create geometry of a zigzag ribbon\nh = g.get_hamiltonian(has_spin=True) # create hamiltonian of the system\nh.add_haldane(.1) # add Haldane coupling\nh.get_bands() # calculate band structure\n#h.get_bands(operator=h.get_operator(\"valley\"))\n","sub_path":"examples/1d/haldane_armchair/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"101823399","text":"import hmac\nimport sqlite3\nfrom flask import Flask, request, redirect\nfrom flask_jwt import JWT, jwt_required, current_identity\nfrom flask_cors import CORS\nfrom flask_mail import Mail, Message\nimport re\nimport cloudinary\nimport cloudinary.uploader\nfrom datetime import timedelta\n\n# creating a user object\nclass User(object):\n def __init__(self, email, username, password):\n self.id = email\n self.username = username\n self.password = password\n\n\n# creating a product object\nclass Product(object):\n def __init__(self, product_id, product_name, product_type, product_quantity, product_price, product_image):\n self.product_id = product_id\n self.product_name = product_name\n self.product_type = product_type\n self.product_quantity = product_quantity\n self.product_price = product_price\n self.product_image = product_image\n\n\n# initializing the database\nclass Database(object):\n def __init__(self):\n self.conn = sqlite3.connect('posbe.db')\n self.cursor = self.conn.cursor()\n\n def addpro(self, value):\n query = \"INSERT INTO catalogue (product_id, product_name, product_type, product_quantity, product_price,\" \\\n \"product_image, email) VALUES (?, ?, ?, ?, ?, ?, ?)\"\n self.cursor.execute(query, value)\n\n def delpro(self, productid):\n proid = productid\n query = \"DELETE FROM catalogue WHERE product_id='\" + proid + \"'\"\n self.cursor.execute(query)\n\n def editpro(self, pro_id, value):\n proid = pro_id\n values = value\n put_data = {}\n put_data['product_id'] = values.get('product_id')\n put_data['product_name'] = values.get('product_name')\n put_data['product_type'] = values.get('product_type')\n put_data['product_quantity'] = values.get('product_quantity')\n put_data['product_price'] = values.get('product_price')\n put_data['product_image'] = values.get('product_image')\n\n if values.get('product_image'):\n self.cursor.execute(\"UPDATE catalogue SET \"\n \"product_id=?, \"\n \"product_name=?, \"\n \"product_type=?, \"\n \"product_quantity=?, \"\n \"product_price=?, \"\n \"product_image=? \"\n \"WHERE product_id='\" + proid + \"'\"\n , (put_data['product_id'],\n put_data['product_name'],\n put_data['product_type'],\n put_data['product_quantity'],\n put_data['product_price'],\n put_data['product_image']))\n else:\n self.cursor.execute(\"UPDATE catalogue SET \"\n \"product_id=?, \"\n \"product_name=?, \"\n \"product_type=?, \"\n \"product_quantity=?, \"\n \"product_price=? \"\n \"WHERE product_id='\" + proid + \"'\"\n , (put_data['product_id'],\n put_data['product_name'],\n put_data['product_type'],\n put_data['product_quantity'],\n put_data['product_price']))\n\n def edituser(self, email, value):\n email = email\n values = value\n query = \"UPDATE user SET first_name=?, last_name=?, address=?, username=?, password=? WHERE email='\" + email + \"'\"\n self.cursor.execute(query, values)\n\n def selectproduct(self, value):\n proid = value\n query = \"SELECT * FROM catalogue WHERE product_id='\" + proid + \"'\"\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n\n def myproducts(self, value):\n email = value\n query = \"SELECT * FROM catalogue WHERE email='\" + email + \"'\"\n self.cursor.execute(query)\n data = self.cursor.fetchall()\n return data\n\n def viewcat(self):\n self.cursor.execute(\"SELECT * FROM catalogue\")\n data = self.cursor.fetchall()\n return data\n\n def deleteuser(self, email):\n self.cursor.execute(\"DELETE FROM user WHERE email='\" + email + \"'\")\n self.conn.commit()\n\n def commit(self):\n return self.conn.commit()\n\n\n# function to take image uploads and convert them into urls\ndef upload_file():\n app.logger.info('in upload route')\n cloudinary.config(cloud_name ='dlqxdivje', api_key='599819111725767',\n api_secret='lTD-aqaoTbzVgmZqyZxjPThyaVg')\n upload_result = None\n if request.method == 'POST' or request.method == 'PUT':\n product_image = request.json['product_image']\n app.logger.info('%s file_to_upload', product_image)\n if product_image:\n upload_result = cloudinary.uploader.upload(product_image)\n app.logger.info(upload_result)\n return upload_result['url']\n\n\ndb = Database()\n\n\n# collecting all users from the database\ndef fetch_users():\n with sqlite3.connect('posbe.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM user\")\n users = cursor.fetchall()\n print(users)\n\n new_data = []\n\n for data in users:\n new_data.append(User(data[0], data[4], data[5]))\n return new_data\n\n\n# collecting all products from the database\ndef fetch_products():\n with sqlite3.connect('posbe.db') as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM products\")\n allproducts = cursor.fetchall()\n print(allproducts)\n\n new_data = []\n\n for data in allproducts:\n new_data.append(Product(data[0], data[1], data[2], data[3], data[4], data[5]))\n return new_data\n\n\nusers = fetch_users()\nproducts = fetch_products()\n\n\n# function to create the user table in the database\ndef createusertable():\n conn = sqlite3.connect('posbe.db')\n print(\"Opened database successfully\")\n\n conn.execute(\"CREATE TABLE IF NOT EXISTS user(email TEXT PRIMARY KEY,\"\n \"first_name TEXT NOT NULL,\"\n \"last_name TEXT NOT NULL,\"\n \"address TEXT NOT NULL,\"\n \"username TEXT NOT NULL,\"\n \"password TEXT NOT NULL)\")\n print(\"user table created successfully\")\n conn.close()\n\n\n# function to create the products table in the database\ndef createproducttable():\n with sqlite3.connect('posbe.db') as conn:\n conn.execute(\"CREATE TABLE IF NOT EXISTS catalogue (product_id TEXT PRIMARY KEY,\"\n \"product_name TEXT NOT NULL,\"\n \"product_type TEXT NOT NULL,\"\n \"product_quantity INTEGER NOT NULL,\"\n \"product_price TEXT NOT NULL,\"\n \"product_image TEXT NOT NULL,\"\n \"email TEXT NOT NULL,\"\n \"FOREIGN KEY (email) REFERENCES user (email))\")\n print(\"product table created successfully.\")\n\n\n# calling the functions to create the tables\ncreateusertable()\ncreateproducttable()\n\n\nusername_table = {u.username: u for u in users}\nuseremail_table = {u.id: u for u in users}\n\n\n# function to create the token during login\ndef authenticate(username, password):\n user = username_table.get(username, None)\n if user and hmac.compare_digest(user.password.encode('utf-8'), password.encode('utf-8')):\n return user\n\n\ndef identity(payload):\n user_id = payload['identity']\n return useremail_table.get(user_id, None)\n\n\n# initializing the app\napp = Flask(__name__)\napp.config['JWT_EXPIRATION_DELTA'] = timedelta(hours=24)\nCORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\napp.debug = True\napp.config['SECRET_KEY'] = 'super-secret'\napp.config['MAIL_SERVER'] = 'smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = 'lottoemail123@gmail.com'\napp.config['MAIL_PASSWORD'] = 'MonkeyVillage123'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\napp.config['TESTING'] = True\napp.config['CORS_HEADERS'] = ['Content-Type']\n\n\njwt = JWT(app, authenticate, identity)\n\n\n@app.route('/protected/')\n@jwt_required()\ndef protected():\n return '%s' % current_identity\n\n\n# app route for user registration\n@app.route('/user-registration/', methods=[\"POST\"])\ndef user_registration():\n response = {}\n regex = '^(\\w|\\.|\\_|\\-)+[@](\\w|\\_|\\-|\\.)+[.]\\w{2,3}$'\n\n if request.method == \"POST\":\n\n email = request.form['email']\n first_name = request.form['first_name']\n last_name = request.form['last_name']\n address = request.form['address']\n username = request.form['username']\n password = request.form['password']\n if (re.search(regex, email)):\n with sqlite3.connect(\"posbe.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO user(\"\n \"email,\"\n \"first_name,\"\n \"last_name,\"\n \"address,\"\n \"username,\"\n \"password) VALUES(?, ?, ?, ?, ?, ?)\", (email, first_name, last_name, address, username, password))\n conn.commit()\n global users\n users = fetch_users()\n\n\n response[\"message\"] = \"success. message sent\"\n response[\"status_code\"] = 201\n\n return redirect(\"/emailsent/%s\" % email)\n else:\n return \"Email not valid. Please enter a valid email address\"\n\n\n# app route that sends an email to users who registered\n@app.route('/emailsent/', methods=['GET'])\ndef sendemail(email):\n mail = Mail(app)\n\n msg = Message('Hello Message', sender='lottoemail123@gmail.com', recipients=[email])\n msg.body = \"This is the email body after making some changes\"\n mail.send(msg)\n\n return \"Thank you for registering. An em\"\n\n\n# app route to view a profile\n@app.route('/viewprofile//', methods=[\"GET\"])\ndef viewownprofile(username):\n response = {}\n if request.method == \"GET\":\n with sqlite3.connect(\"posbe.db\") as conn:\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM user WHERE username='\" + username + \"'\")\n data = cursor.fetchall()\n if data == []:\n return \"User does not exit\"\n else:\n response['message'] = 200\n response['data'] = data\n return response\n\n\n# app route to add a product to the database\n@app.route('/addtocatalogue/', methods=[\"POST\"])\n@jwt_required()\ndef newproduct():\n dtb = Database()\n response = {}\n\n if request.method == \"POST\":\n product_id = request.json['product_id']\n product_name = request.json['product_name']\n product_type = request.json['product_type']\n product_quantity = request.json['product_quantity']\n product_price = request.json['product_price']\n email = request.json['email']\n if (product_id == '' or product_name == '' or product_type == ''\n or product_quantity == '' or product_price == '' or email == ''):\n return \"Please fill in all entry fields\"\n else:\n if int(product_quantity):\n values = (product_id, product_name, product_type, product_quantity, product_price, upload_file(), email)\n dtb.addpro(values)\n dtb.commit()\n\n response[\"status_code\"] = 201\n response['description'] = 'product added'\n return response\n else:\n return \"Please enter product quantity as an number\"\n else:\n return \"Method Not Allowed\"\n\n\n# app route to view all the products in the database\n@app.route('/viewcatalogue/', methods=[\"GET\"])\ndef get_products():\n dtb = Database()\n response = {}\n items = dtb.viewcat()\n response['status_code'] = 200\n response['data'] = items\n return response\n\n\n# app route to delete a product from the database\n@app.route(\"/delete-product/\")\n@jwt_required()\ndef delete_product(productid):\n response = {}\n dtb = Database()\n\n dtb.delpro(productid)\n dtb.commit()\n response['status_code'] = 200\n response['message'] = \"product deleted successfully.\"\n return response\n\n\n# app route to edit a product in the database\n@app.route(\"/edit-product//\", methods=[\"PUT\"])\n@jwt_required()\ndef edit_product(productid):\n response = {}\n dtb = Database()\n product = dtb.selectproduct(productid)\n if product == []:\n return \"Product does not exist in the database\"\n else:\n if request.method == \"PUT\":\n incoming_data = dict(request.json)\n dtb.editpro(productid, incoming_data)\n dtb.commit()\n response['message'] = 200\n return response\n else:\n return \"Method not allowed\"\n\n\n@app.route(\"/myproducts//\")\n@jwt_required()\ndef getmyproducts(email):\n dtb = Database()\n response = {}\n items = dtb.myproducts(email)\n response['status_code'] = 200\n response['data'] = items\n return response\n\n\n@app.route(\"/edit-user//\", methods=[\"PUT\"])\n@jwt_required()\ndef edit_user(useremail):\n response = {}\n dtb = Database()\n if request.method == \"PUT\":\n first_name = request.json['first_name']\n last_name = request.json['last_name']\n address = request.json['address']\n username = request.json['username']\n password = request.json['password']\n values = (first_name, last_name, address, username, password)\n dtb.edituser(useremail, values)\n dtb.commit()\n response['message'] = 200\n return response\n else:\n return \"Method not allowed\"\n\n\n@app.route('/select_item/')\n@jwt_required()\ndef selectitem(productid):\n response = {}\n dtb = Database()\n data = dtb.selectproduct(productid)\n response['message'] = 200\n response['data'] = data\n return response\n\n\n@app.route('/deleteuser/')\n@jwt_required()\ndef deleteuser(email):\n response = {}\n dtb = Database()\n dtb.delpro(email)\n dtb.commit()\n dtb.deleteuser(email)\n response['message'] = 200\n response['text'] = \"User successfully deleted\"\n return response\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":14579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"255917773","text":"# Chris Jakins 1000802309\n\nimport sys\nimport numpy as np\nfrom file_utility import FileUtility\n\nif len(sys.argv) != 5:\n print(\"Usage: value_iteration.py \")\n quit()\n\n\nenvironment_filename = sys.argv[1]\nnt_reward = float(sys.argv[2])\ngamma = float(sys.argv[3])\nk = int(sys.argv[4])\n\n\ndef value_iteration(states, reward, gamma, k):\n n = len(states) * len(states[0]) # assumes rectangular\n u = np.zeros((len(states), len(states[0])))\n\n for it in range(0, k):\n u_prime = np.array(u)\n\n for i in range(0, len(states)):\n for j in range(0, len(states[i])):\n if states[i][j] == 'X':\n u[i][j] = 0\n elif isinstance(states[i][j], float):\n u[i][j] = states[i][j]\n else:\n # calc for all possible transitions\n u[i][j] = (reward + \n gamma * bm(states, u_prime, i, j, len(states), len(states[i])))\n\n return u\n\n\n# don't look at this, thanks\ndef bm(env, u, i, j, max_i, max_j):\n ########### up \n # up_l\n if j == 0 or env[i][j - 1] == 'X':\n up_l = .1 * u[i][j]\n else:\n up_l = .1 * u[i][j - 1]\n \n # up_u\n if i == 0 or env[i - 1][j] == 'X':\n up_u = .8 * u[i][j]\n else:\n up_u = .8 * u[i - 1][j]\n \n # up_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n up_r = .1 * u[i][j]\n else:\n up_r = .1 * u[i][j + 1]\n\n max_util = up_u + up_l + up_r\n\n\n ########### left\n # left_u\n if i == 0 or env[i - 1][j] == 'X':\n left_u = .1 * u[i][j]\n else:\n left_u = .1 * u[i - 1][j]\n\n # left_l\n if j == 0 or env[i][j - 1] == 'X':\n left_l = .8 * u[i][j]\n else:\n left_l = .8 * u[i][j - 1]\n\n # left_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n left_d = .1 * u[i][j]\n else:\n left_d = .1 * u[i + 1][j]\n\n if left_u + left_l + left_d > max_util:\n max_util = left_u + left_l + left_d\n\n\n ############# down\n # down_l\n if j == 0 or env[i][j - 1] == 'X':\n down_l = .1 * u[i][j]\n else:\n down_l = .1 * u[i][j - 1]\n\n # down_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n down_d = .8 * u[i][j]\n else:\n down_d = .8 * u[i + 1][j]\n\n # down_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n down_r = .1 * u[i][j]\n else:\n down_r = .1 * u[i][j + 1]\n\n if down_l + down_d + down_r > max_util:\n max_util = down_l + down_d + down_r\n\n ############# right\n # right_d\n if i == max_i - 1 or env[i + 1][j] == 'X':\n right_d = .1 * u[i][j]\n else:\n right_d = .1 * u[i + 1][j]\n\n # right_r\n if j == max_j - 1 or env[i][j + 1] == 'X':\n right_r = .8 * u[i][j]\n else:\n right_r = .8 * u[i][j + 1]\n\n # right_u\n if i == 0 or env[i - 1][j] == 'X':\n right_u = .1 * u[i][j]\n else:\n right_u = .1 * u[i - 1][j]\n\n if right_d + right_r + right_u > max_util:\n max_util = right_d + right_r + right_u\n\n return max_util\n\n######################\n\nfile_util = FileUtility()\nenv = file_util.getData(environment_filename)\nutility_values = value_iteration(env, nt_reward, gamma, k)\n\n\nfor i in range(0, len(utility_values)):\n for j in range(0, len(utility_values[i])):\n if j == len(utility_values[i]) - 1:\n print(\"%6.3f\" % utility_values[i][j], end = '\\n')\n else:\n print(\"%6.3f,\" % utility_values[i][j], end = '')\n","sub_path":"fall2018/4309/hw6/value_iteration.py","file_name":"value_iteration.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"91388233","text":"united_kingdom = [\n {\n \"name\": \"Scotland\",\n \"population\": 5295000,\n \"capital\": \"Edinburgh\"\n },\n {\n \"name\": \"Wales\",\n \"population\": 3063000,\n \"capital\": \"Swansea\"\n },\n {\n \"name\": \"England\",\n \"population\": 53010000,\n \"capital\": \"London\"\n }\n]\n\n# 1. Change the capital of Wales from `\"Swansea\"` to `\"Cardiff\"`.\nunited_kingdom[1][\"capital\"] = \"Cardiff\"\nprint(united_kingdom[1][\"capital\"])\n# 2. Create a dictionary for Northern Ireland and add it to the `united_kingdom` list (The capital is Belfast, and the population is 1,811,000).\nnorthern_ireland = {\n \"name\": \"Northern Ireland\",\n \"population\": 1811000,\n \"capital\": \"Belfast\"\n }\nunited_kingdom.append(northern_ireland)\n#print(united_kingdom)\n# 3. Use a loop to print the names of all the countries in the UK.\nnames = united_kingdom[0][\"name\"], united_kingdom[1][\"name\"], united_kingdom[2][\"name\"], united_kingdom[3][\"name\"]\nfor name in names:\n print(name)\n# 4. Use a loop to find the total population of the UK.\n#populations = [{united_kingdom[0][\"population\"]}, {united_kingdom[1][\"population\"]}, {united_kingdom[2][\"population\"]}, {united_kingdom[3][\"population\"]}]\n#print(populations)\npopulations = united_kingdom\n# print(populations)\ntotal_population = 0\nfor population in populations:\n total_population = total_population + population[\"population\"]\nprint(total_population)\n# check_total = 5295000 + 3063000 + 53010000 + 1811000\n# print(check_total)","sub_path":"exercise_c_uk.py","file_name":"exercise_c_uk.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"636095517","text":"# coding=utf-8\nimport platform\nimport codecs\n\ndef getAllFrequentKeywords(frequentWordsFilePath):\n words = []\n input = codecs.open(frequentWordsFilePath,\"r\",\"utf-8\")\n for line in input.readlines():\n words.append(line.strip(\"\\r\\n\").lower())\n return words\n\ndef prepare():\n #换行符\n HuangHangFu = \"\"\n my_os = platform.system()\n if my_os==\"Windows\":\n inputPath = \"F://睿云实验室//王剑锋//2017.11.1_关键��检索_esorics2018//第3阶段工作-搞数据//弄好的数据库//ciPings//ciPing\"\n outputPath = \"F://睿云实验室//王剑锋//2017.11.1_关键词检索_esorics2018//第3阶段工作-搞数据//ProcessEDRM4//EDRM_10000.txt\"\n frequentWordsFilePath = \"F://睿云实验室//王剑锋//2017.11.1_关键词检索_esorics2018//第3阶段工作-搞数据//ProcessEDRM4//使用频率最高的45000个一万个单词.txt\"\n HuangHangFu = \"\\r\\n\"\n print(\"you are in windows\")\n return inputPath,outputPath,frequentWordsFilePath\n else:\n inputPath = \"/root/ciPings//ciPing\";\n outputPath = \"/root/EDRM_10000.txt\"\n frequentWordsFilePath = \"/root/使用频率最高的45000个一万个单词.txt\"\n HuangHangFu = \"\\n\"\n print(\"you are in linux\")\n return inputPath,outputPath,frequentWordsFilePath\n\nif(__name__==\"__main__\"):\n inputPath,outputPath,frequentWordsFilePath = prepare()\n output = codecs.open(outputPath,\"w\",\"utf-8\")\n frequentWords = getAllFrequentKeywords(frequentWordsFilePath)\n print(len(frequentWords))\n k=0\n count = 0\n while(k<700):\n input = codecs.open(inputPath+\"_\"+str(k)+\".txt\",\"r\",\"utf-8\")\n lines = input.readlines()\n input.close()\n for line in lines:\n keyword = line.split(\":\")[0]\n numOfFiles = int(line.split(\":\")[1])\n if(keyword in frequentWords and numOfFiles > 10 and numOfFiles < 20):\n output.write(line)\n count = count + 1\n if(count >= 10000):\n print(\"获得100000个单词\")\n exit();\n \n k = k + 1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"473172198","text":"# \n# Boolean Algebra System\n# - Helper Functions and Classes\n#\n\n# Tree data structure used to express the boolean algebra expressions for simplification\nclass Tree (object):\n def __init__(self, children):\n self.children = children\n\n # Function that adds a child to the node\n def addChild(self, child):\n if isinstance(child, (list, tuple)):\n self.children += list(child)\n else:\n self.children.append(child)\n \n # Allows the tree to be printed\n def __repr__(self, level=0):\n ret = \"\"\n for child in self.children:\n if not isinstance(child, Tree):\n ret += \"\\t\" * level + \"'\" + str(child) + \"'\\n\"\n else:\n ret += child.__repr__(level+1)\n return ret\n\n# Function that checks whether there is proper bracket nesting (and whether all brackets are closed)\ndef checkBracketParity(string):\n nesting_count = 0\n for index, char in enumerate(string):\n if char == \"(\":\n nesting_count += 1\n elif char == \")\":\n nesting_count -= 1\n\n if nesting_count < 0:\n return False\n\n return nesting_count == 0\n\n\n# Analyzes whether a number is a power of two without using log functions (no floats) \ndef powerOfTwo(num):\n return num != 0 and ((num & (num - 1)) == 0)\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"353498214","text":"from django.contrib import admin\n\n# Register your models here.\n\nfrom .models import *\n\n\nclass AdmArticle(admin.ModelAdmin):\n list_display = ('creationDate','title')\n fieldsets = [\n ('Date ajout', {'fields': ['creationDate']}),\n ('Title', {'fields': ['title']}),\n ('Photo(s)', {'fields': ['relatedPhotos']}),\n ('Country', {'fields': ['relatedCountries']}),\n ('Misc', {'fields': ['textContent']}),\n ]\n \n list_filter = ['creationDate']\n \nclass AdmPhoto(admin.ModelAdmin):\n fieldsets = [\n ('Title', {'fields': ['title']}),\n ('Misc', {'fields': ['is_dark','file']}),\n ]\n\n\nadmin.site.register(Article, AdmArticle)\nadmin.site.register(Photo, AdmPhoto)\nadmin.site.register(Country)\nadmin.site.register(Location)","sub_path":"photolog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"235708459","text":"# coding=utf-8\nimport glob\n\nif __name__ == '__main__':\n direction = \"E:\\工程\\workspace\\JavaEEWeb\\WebContent\"\n jspls = glob.glob(direction + \"\\*.jsp\")\n for i in jspls:\n re = open(i, \"r\", encoding=\"utf8\")\n s = re.read()\n re.close()\n s = s.replace(\"\", \"120402013081 杨友君\")\n re = open(i, \"w\", encoding=\"utf8\")\n re.write(s)\n re.close()\n print(\"over!\")\n","sub_path":"Study/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"568364946","text":"import unittest\nimport theGame\nimport Deck\n\nclass TestDeckFunctions(unittest.TestCase):\n\tdef test_draw(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.draw(), None)\n\tdef test_show(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.show(), None)\n\tdef test_is_empty(self):\n\t\ttestDeck = Deck.Deck()\n\t\tself.assertEqual(testDeck.is_empty(), True)\n\t\ttestDeck.full_deck()\n\t\tself.assertEqual(testDeck.is_empty(), False)\n\tdef test_is_available(self):\n\t\tcard = Deck.Card(\"H\", 1, True)\n\t\tself.assertEqual(card.is_available(), True)\n\t\nclass TestTheGameFunctions(unittest.TestCase):\n\tdef test_check_color(self):\n\t\ttestGame = theGame.theGame(2)\n\t\ttestGame.flip()\n\t\tcardX1 = Deck.Card(\"H\", 1, True)\n\t\tcardX2 = Deck.Card(\"S\", 4, False)\n\t\tself.assertEqual(testGame.check_color(cardX1), False)\n\t\tself.assertEqual(testGame.check_color(cardX2), True)\n\tdef test_is_legal(self):\n\t\ttestGame = theGame.theGame(2)\n\t\ttestGame.flip()\n\t\tcardX1 = Deck.Card(\"H\", 1, True)\n\t\tcardX2 = Deck.Card(\"S\", 3, True) #first trash is 4..\n\t\tself.assertEqual(testGame.is_legal(cardX1), False)\n\t\tself.assertEqual(testGame.is_legal(cardX2), True)\n\nif __name__ == '__main__':\n\tunittest.main(verbosity=2, exit=False)\n","sub_path":"rett_python_nofn/test_kapall.py","file_name":"test_kapall.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"191782862","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nimport datetime\nfrom django.core import serializers\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .logic import create_handle_log\nfrom .constants import LOGPATH\n# Create your views here.\nfrom .models import Logs, UserHandle, UserLogin\ndef create_log(request):\n f = open(\"ddns.log\") # 返回一个文件对象 \n line = f.readline() # 调用文件的 readline()方法 \n while line: \n log = eval(line)\n logs = Logs(c_date=log['date'], code=log['code'], status=log['msg'].encode('utf-8'))\n logs.save()\n line = f.readline() \n \n f.close()\n\n # logs = Logs(c_date='2019-1-1 10:54:32.43455', code=0, status='ok')\n # logs.save()\n return HttpResponse('ok')\n\ndef get(request):\n logs = Logs.objects.all()\n paginator = Paginator(logs, 20) #设置每一页显示几条 创建一个panginator对象\n \n try:\n current_num = int(request.GET.get('page',1)) #当你在url内输入的?page = 页码数 显示你输入的页面数目 默认为第2页\n logs = paginator.page(current_num)\n except EmptyPage:\n logs = paginator.page(1) #当你输入的page是不存在的时候就会报错\n\n if paginator.num_pages > 11: # 如果分页的数目大于11\n if current_num - 5 < 1: # 你输入的值\n pageRange = range(1, 11) # 按钮数\n elif current_num + 5 > paginator.num_pages: # 按钮数加5大于分页数\n pageRange = range(current_num - 5, current_num + 1) # 显示的按钮数\n\n else:\n pageRange = range(current_num - 5, current_num + 6) # range求的是按钮数 如果你的按钮数小于分页数 那么就按照正常的分页数目来显示\n\n else:\n pageRange = paginator.page_range # 正常分配\n\n return render(request, 'demo.html', locals())\n\ndef search(request):\n # print(request.method)\n search = request.POST.get('search')\n start_date = request.POST.get('start_date')\n end_date = request.POST.get('end_date') + ' 23:59:59.99999'\n # print(end_date)\n logs = Logs.objects.filter(c_date__range=(start_date, end_date)).filter(status__contains=search)\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n return JsonResponse(data)\n\ndef nearby_logs(request):\n # 查找相邻的log日志\n id = eval(request.POST.get('id'))\n start_id= id-5 if id-5 >=0 else 0\n end_id = id+5 \n logs = Logs.objects.filter(pk__range=(start_id, end_id))\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n return JsonResponse(data)\n\ndef get_user_log(request):\n create_handle_log(LOGPATH)\n user_login = UserLogin.objects.all().order_by('-l_time')\n paginator = Paginator(user_login, 20) #设置每一页显示几条 创建一个panginator对象\n try:\n current_num = int(request.GET.get('page',1)) #当你在url内输入的?page = 页码数 显示你输入的页面数目 默认为第2页\n logs = paginator.page(current_num)\n except EmptyPage:\n logs = paginator.page(1) #当你输入的page是不存在的时���就会报错\n print(paginator.num_pages)\n if paginator.num_pages > 11: # 如果分页的数目大于11\n if current_num - 5 < 1: # 你输入的值\n pageRange = range(1, 11) # 按钮数\n elif current_num + 5 > paginator.num_pages: # 按钮数加5大于分页数\n pageRange = range(current_num - 5, current_num + 1) # 显示的按钮数\n else:\n pageRange = range(current_num - 5, current_num + 6) # range求的是按钮数 如果你的按钮数小于分页数 那么就按照正常的分页数目来显示\n \n else:\n pageRange = paginator.page_range # 正常分配\n\n return render(request, 'sys_log.html', locals())\n\ndef get_handle_log(request):\n user_pk = request.POST.get('id')\n print(user_pk)\n user_handle = UserHandle.objects.filter(h_user_login=user_pk)\n user_handle = serializers.serialize(\"json\", user_handle)\n return JsonResponse({'data':user_handle})\ndef search_user(request):\n search = request.POST.get('search')\n start_date = request.POST.get('start_date')\n end_date = request.POST.get('end_date') + ' 23:59:59.99999'\n # print(end_date)\n logs = UserLogin.objects.filter(l_time__range=(start_date, end_date)).filter(l_user=search)\n logs = serializers.serialize(\"json\",logs)\n data = {\"data\":logs}\n\n return JsonResponse(data)","sub_path":"logs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"46648400","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom deepdiff import DeepDiff\nfrom Util.handle_json import get_value\n\nbase_path = os.path.abspath(os.path.dirname(os.getcwd()))\nsys.path.append(base_path)\n\n\ndef handle_result(url, code):\n data = get_value(url, \"/Config/code_message.json\")\n if data is not None:\n for i in data:\n message = i.get(str(code))\n if message:\n return message\n return None\n\n\ndef get_result_json(url, status):\n data = get_value(url, '/Config/result.json')\n if data is not None:\n for i in data:\n message = i.get(status)\n if message:\n return message\n return None\n\n\ndef handle_result_json(dict1, dict2):\n \"\"\"\n 比对 json\n :param dict1:\n :param dict2:\n :return:\n \"\"\"\n if isinstance(dict1, dict) and isinstance(dict2, dict):\n cmp_dict = DeepDiff(dict1, dict2, ignore_order=True).to_dict()\n if cmp_dict.get(\"dictionary_item_added\"):\n return False\n else:\n return True\n\n\nif __name__ == '__main__':\n print(get_result_json('auth/account/login', 'error'))\n\n\n\n","sub_path":"Util/handle_result.py","file_name":"handle_result.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"3140521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: hkaneko\r\n\"\"\"\r\n\r\nimport sys\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sample_functions\r\nfrom sklearn import metrics\r\nfrom sklearn import svm\r\nfrom sklearn.cross_decomposition import PLSRegression\r\nfrom sklearn.model_selection import train_test_split, cross_val_predict, GridSearchCV\r\n\r\nmethod_name = 'pls' # 'pls' or 'svr'\r\nadd_nonlinear_terms_flag = False # True (二乗項・交差項を追加) or False (追加しない)\r\n\r\nnumber_of_test_samples = 800\r\nfold_number = 2 # N-fold CV の N\r\nmax_number_of_principal_components = 30 # 使用する主成分の最大数\r\nsvr_cs = 2 ** np.arange(-5, 11, dtype=float) # C の候補\r\nsvr_epsilons = 2 ** np.arange(-10, 1, dtype=float) # ε の候補\r\nsvr_gammas = 2 ** np.arange(-20, 11, dtype=float) # γ の候補\r\n\r\nif method_name != 'pls' and method_name != 'svr':\r\n sys.exit('\\'{0}\\' という回帰分析手法はありません。method_name を見直してください。'.format(method_name))\r\n \r\ndataset = pd.read_csv('unique_m.csv', index_col=-1)\r\ndataset = dataset.sort_values('critical_temp', ascending=False).iloc[:4000, :]\r\ny = dataset.iloc[:, 86].copy()\r\nx = dataset.iloc[:, :86]\r\nx = (x.T / x.T.sum()).T\r\n# ランダムにトレーニングデータとテストデータとに分割\r\n# random_state に数字を与えることで、別のときに同じ数字を使えば、ランダムとはいえ同じ結果にすることができます\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=number_of_test_samples, shuffle=True,\r\n random_state=21)\r\n# 標準偏差が 0 の説明変数を削除\r\nstd_0_variable_flags = x_train.std() == 0\r\nx_train = x_train.drop(x_train.columns[std_0_variable_flags], axis=1)\r\nx_test = x_test.drop(x_test.columns[std_0_variable_flags], axis=1)\r\n\r\nif add_nonlinear_terms_flag:\r\n x_train = pd.read_csv('x_train_superconductor.csv', index_col=0)\r\n x_test = pd.read_csv('x_test_superconductor.csv', index_col=0)\r\n # x_train = sample_functions.add_nonlinear_terms(x_train) # 説明変数の二乗項や交差項を追加\r\n # x_test = sample_functions.add_nonlinear_terms(x_test) # 説明変数の二乗項や交差項を追加\r\n # 標準偏差が 0 の説明変数を削除\r\n std_0_nonlinear_variable_flags = x_train.std() == 0\r\n x_train = x_train.drop(x_train.columns[std_0_nonlinear_variable_flags], axis=1) # 標準偏差が 0 の説明変数を削除\r\n x_test = x_test.drop(x_test.columns[std_0_nonlinear_variable_flags], axis=1) # 標準偏差が 0 の説明変数を削除\r\n\r\n# オートスケーリング\r\nautoscaled_x_train = (x_train - x_train.mean()) / x_train.std()\r\nautoscaled_y_train = (y_train - y_train.mean()) / y_train.std()\r\nautoscaled_x_test = (x_test - x_train.mean()) / x_train.std()\r\n\r\nif method_name == 'pls':\r\n # CV による成分数の最適化\r\n components = [] # 空の list の変数を作成して、成分数をこの変数に追加していきます同じく成分数をこの変数に追加\r\n r2_in_cv_all = [] # 空の list の変数を作成して、成分数ごとのクロスバリデーション後の r2 をこの変数に追加\r\n for component in range(1, min(np.linalg.matrix_rank(autoscaled_x_train), max_number_of_principal_components) + 1):\r\n # PLS\r\n model = PLSRegression(n_components=component) # PLS モデルの宣言\r\n estimated_y_in_cv = pd.DataFrame(cross_val_predict(model, autoscaled_x_train, autoscaled_y_train,\r\n cv=fold_number)) # クロスバリデーション推定値の計算し、DataFrame型に変換\r\n estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() # スケールをもとに戻す\r\n r2_in_cv = metrics.r2_score(y_train, estimated_y_in_cv) # r2 を計算\r\n print(component, r2_in_cv) # 成分数と r2 を表示\r\n r2_in_cv_all.append(r2_in_cv) # r2 を追加\r\n components.append(component) # 成分数を追加\r\n\r\n # 成分数ごとの CV 後の r2 をプロットし、CV 後のr2が最大のときを最適成分数に\r\n optimal_component_number = sample_functions.plot_and_selection_of_hyperparameter(components, r2_in_cv_all,\r\n 'number of components',\r\n 'cross-validated r2')\r\n print('\\nCV で最適化された成分数 :', optimal_component_number)\r\n # PLS\r\n model = PLSRegression(n_components=optimal_component_number) # モデルの宣言\r\nelif method_name == 'svr':\r\n # グラム行列の分散を最大化することによる γ の最適化\r\n optimal_svr_gamma = sample_functions.gamma_optimization_with_variance(autoscaled_x_train, svr_gammas)\r\n # CV による ε の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', C=3, gamma=optimal_svr_gamma), {'epsilon': svr_epsilons},\r\n cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_epsilon = model_in_cv.best_params_['epsilon']\r\n # CV による C の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_svr_epsilon, gamma=optimal_svr_gamma),\r\n {'C': svr_cs}, cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_c = model_in_cv.best_params_['C']\r\n # CV による γ の最適化\r\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_svr_epsilon, C=optimal_svr_c),\r\n {'gamma': svr_gammas}, cv=fold_number, verbose=2)\r\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n optimal_svr_gamma = model_in_cv.best_params_['gamma']\r\n # 最適化された C, ε, γ\r\n print('C : {0}\\nε : {1}\\nGamma : {2}'.format(optimal_svr_c, optimal_svr_epsilon, optimal_svr_gamma))\r\n # SVR\r\n model = svm.SVR(kernel='rbf', C=optimal_svr_c, epsilon=optimal_svr_epsilon, gamma=optimal_svr_gamma) # モデルの宣言\r\n\r\nmodel.fit(autoscaled_x_train, autoscaled_y_train) # モデルの構築\r\nif method_name == 'pls':\r\n # 標準回帰係数\r\n standard_regression_coefficients = pd.DataFrame(model.coef_, index=x_train.columns,\r\n columns=['standard_regression_coefficients'])\r\n standard_regression_coefficients.to_csv(\r\n 'pls_standard_regression_coefficients.csv') # csv ファイルに保存。同じ名前のファイルがあるときは上書きされますので注意してください\r\n# トレーニングデータ・テストデータの推定、実測値 vs. 推定値のプロット、r2, RMSE, MAE の値の表示、推定値の保存\r\nsample_functions.estimation_and_performance_check_in_regression_train_and_test(model, autoscaled_x_train, y_train,\r\n autoscaled_x_test, y_test)\r\n","sub_path":"sample_program_6_1_2_3_regression.py","file_name":"sample_program_6_1_2_3_regression.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"313192278","text":"# An example of system check where the mpi launcher is omitted in the jobscript.\nimport reframe as rfm\nimport reframe.utility.sanity as sn\nimport os\n\n@rfm.parameterized_test(['home'],['scratch'])\nclass fs_check(rfm.RunOnlyRegressionTest):\n def __init__(self,variant):\n super().__init__()\n self.descr = 'Filesystem mount check on longin and compute nodes'\n self.valid_systems = ['ibex:login','ibex:batch_nompi']\n self.valid_prog_environs = ['builtin-gcc']\n self.sourcesdir=None\n self.executable='df -h '\n self.num_tasks=1\n if variant == \"home\":\n self.sanity_patterns =sn.assert_found(r'/home/home',self.stdout)\n elif variant == \"scratch\":\n self.sanity_patterns =sn.assert_found(r'/scratch/dragon',self.stdout)\n \n self.maintainers = ['mohsin.shaikh@kaust.edu.sa']\n self.tags = {'filesystem'}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ibex_checks/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"361996414","text":"# (C) Datadog, Inc. 2018\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nimport os\n\nimport mock\nimport pytest\n\nfrom datadog_checks.dev import docker_run\nfrom datadog_checks.nginx import Nginx\n\nfrom .common import HERE, HOST, NGINX_VERSION, PORT, PORT_SSL, TAGS, USING_VTS\n\n\n@pytest.fixture(scope='session')\ndef dd_environment(instance, instance_vts):\n if USING_VTS:\n config_dir = os.path.join(HERE, 'nginx_vts')\n instance = instance_vts\n else:\n config_dir = os.path.join(HERE, 'docker', 'nginx')\n\n with docker_run(\n os.path.join(HERE, 'docker', 'docker-compose.yaml'),\n env_vars={'NGINX_CONFIG_FOLDER': config_dir},\n endpoints='http://{}:{}/nginx_status'.format(HOST, PORT),\n ):\n yield instance\n\n\n@pytest.fixture\ndef check():\n return lambda instance: Nginx('nginx', {}, [instance])\n\n\n@pytest.fixture(scope='session')\ndef instance():\n return {'nginx_status_url': 'http://{}:{}/nginx_status'.format(HOST, PORT), 'tags': TAGS}\n\n\n@pytest.fixture\ndef instance_ssl():\n return {'nginx_status_url': 'https://{}:{}/nginx_status'.format(HOST, PORT_SSL), 'tags': TAGS}\n\n\n@pytest.fixture(scope='session')\ndef instance_vts():\n return {'nginx_status_url': 'http://{}:{}/vts_status'.format(HOST, PORT), 'tags': TAGS, 'use_vts': True}\n\n\n@pytest.fixture(scope='session')\ndef version_metadata():\n # vts currently defaults to using version 1.13\n if USING_VTS:\n version = '1.13'\n else:\n version = NGINX_VERSION.split(':')[1]\n\n major, minor = version.split('.')\n\n return {\n 'version.scheme': 'semver',\n 'version.major': major,\n 'version.minor': minor,\n 'version.patch': mock.ANY,\n 'version.raw': mock.ANY,\n }\n","sub_path":"nginx/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"535443856","text":"# Longest Substring with Same Letters after Replacement - Sliding Window Pattern\n\ndef length_of_longest_substring(str,k):\n window_start, max_length, max_repeat_letter_count = 0,0,0\n frequency_map = {}\n\n for window_end in range(len(str)):\n right_char = str[window_end]\n if right_char not in frequency_map:\n frequency_map[right_char] = 0\n frequency_map[right_char] += 1\n max_repeat_letter_count = max(max_repeat_letter_count,frequency_map[right_char])\n if (window_end-window_start+1-max_repeat_letter_count > k):\n left_char = str[window_start]\n frequency_map[left_char] -= 1\n window_start += 1\n max_length = max(max_length,window_end-window_start+1)\n return max_length\n\nprint(\"Longest Substring with Same Letters after Replacement\",length_of_longest_substring(\"abccde\",1))","sub_path":"Sliding Window Pattern/7. Longest Substring with Same Letters.py","file_name":"7. Longest Substring with Same Letters.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"36282715","text":"\r\nimport math\r\n\r\n\r\ndef docross(lives, x, y,index):\r\n child1 = getChild(1, lives, x, y,index)\r\n child2 = getChild(2, lives, x, y,index)\r\n print(index,\":\",child1,distance(child1))\r\n print(index,\":\",child2,distance(child2))\r\n\r\ndef getChild(flag, lives, x, y,index):\r\n newGene = []\r\n px = lives[x].copy()\r\n py = lives[y].copy()\r\n c = px[index]\r\n newGene.append(c)\r\n index1, index2 = -1, -1\r\n dx, dy = -1, -1\r\n while len(px) > 1:\r\n for p in px:\r\n if p == c:\r\n index1 = px.index(p)\r\n break\r\n for p in py:\r\n if p == c:\r\n index2 = py.index(p)\r\n break\r\n if flag == 1:\r\n if index1 > 0:\r\n dx = px[index1 - 1]\r\n else:\r\n dx = px[len(px) - 1]\r\n if index2 > 0:\r\n dy = py[index2 - 1]\r\n else:\r\n dy = py[len(px) - 1]\r\n elif flag == 2:\r\n if index1 < len(px) - 1:\r\n dx = px[index1 + 1]\r\n else:\r\n dx = px[0]\r\n if index2 < len(px) - 1:\r\n dy = py[index2 + 1]\r\n else:\r\n dy = py[0]\r\n px.remove(c)\r\n py.remove(c)\r\n if dis[c][dx] < dis[c][dy]:\r\n c = dx\r\n else:\r\n c = dy\r\n newGene.append(c)\r\n return newGene\r\n\r\n\r\ndef distance(order):\r\n distance = 0.0\r\n for i in range(-1, len(order) - 1):\r\n index1, index2 = order[i], order[i + 1]\r\n distance += dis[index1][index2]\r\n return distance\r\n\r\n\r\ncitys=[[0,0],[3,0],[3,4],[7,3],[9,1],[]]\r\ncity_num=5\r\ndis = [[0 for x in range(city_num)] for y in range(city_num)]\r\nfor i in range(city_num):\r\n for j in range(city_num):\r\n dis[i][j] = math.sqrt((citys[i][0] -citys[j][0]) ** 2 + (citys[i][1] - citys[j][1]) ** 2)\r\n\r\n\r\n\r\n\r\nlives=[[0,1,4,2,3],[2,1,3,4,0]]\r\n# lives=[[1, 0, 3, 2, 4],[1, 3, 4, 2, 0]]\r\nprint(dis)\r\n\r\nprint(distance(lives[0]))\r\nprint(distance(lives[1]))\r\n\r\ndocross(lives,0,1,0)\r\ndocross(lives,0,1,1)\r\ndocross(lives,0,1,2)\r\ndocross(lives,0,1,3)\r\ndocross(lives,0,1,4)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"491559174","text":"import numpy as np\nimport re\n\ninputfile = \"input10\"\nexample = '''noop\naddx 3\naddx -5'''\nother_example = '''addx 15\naddx -11\naddx 6\naddx -3\naddx 5\naddx -1\naddx -8\naddx 13\naddx 4\nnoop\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx 5\naddx -1\naddx -35\naddx 1\naddx 24\naddx -19\naddx 1\naddx 16\naddx -11\nnoop\nnoop\naddx 21\naddx -15\nnoop\nnoop\naddx -3\naddx 9\naddx 1\naddx -3\naddx 8\naddx 1\naddx 5\nnoop\nnoop\nnoop\nnoop\nnoop\naddx -36\nnoop\naddx 1\naddx 7\nnoop\nnoop\nnoop\naddx 2\naddx 6\nnoop\nnoop\nnoop\nnoop\nnoop\naddx 1\nnoop\nnoop\naddx 7\naddx 1\nnoop\naddx -13\naddx 13\naddx 7\nnoop\naddx 1\naddx -33\nnoop\nnoop\nnoop\naddx 2\nnoop\nnoop\nnoop\naddx 8\nnoop\naddx -1\naddx 2\naddx 1\nnoop\naddx 17\naddx -9\naddx 1\naddx 1\naddx -3\naddx 11\nnoop\nnoop\naddx 1\nnoop\naddx 1\nnoop\nnoop\naddx -13\naddx -19\naddx 1\naddx 3\naddx 26\naddx -30\naddx 12\naddx -1\naddx 3\naddx 1\nnoop\nnoop\nnoop\naddx -9\naddx 18\naddx 1\naddx 2\nnoop\nnoop\naddx 9\nnoop\nnoop\nnoop\naddx -1\naddx 2\naddx -37\naddx 1\naddx 3\nnoop\naddx 15\naddx -21\naddx 22\naddx -6\naddx 1\nnoop\naddx 2\naddx 1\nnoop\naddx -10\nnoop\nnoop\naddx 20\naddx 1\naddx 2\naddx 2\naddx -6\naddx -11\nnoop\nnoop\nnoop'''\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nALPHABET = alphabet.capitalize()\n\nneighbours = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\ndef calc_scenic_score(numbers, i_tree, j_tree):\n up = 0\n down = 0\n left = 0\n right = 0\n\n for i in range(i_tree - 1, -1, -1):\n up += 1\n if numbers[i_tree,j_tree] <= numbers[i, j_tree]:\n break\n\n for i in range(i_tree + 1, numbers.shape[0], 1):\n down += 1\n if numbers[i_tree,j_tree] <= numbers[i, j_tree]:\n break\n\n for j in range(j_tree - 1, -1, -1):\n left += 1\n if numbers[i_tree,j_tree] <= numbers[i_tree, j]:\n break\n\n for j in range(j_tree + 1, numbers.shape[1], 1):\n right += 1\n if numbers[i_tree,j_tree] <= numbers[i_tree, j]:\n break\n\n return up * left * down * right\n\ndef textgrid_to_numbers(lines):\n return np.array([[int(x) for x in line] for line in lines], dtype=int)\n\ndef traverse(root):\n sum = 0\n for entry in root.keys():\n if entry == '..':\n continue\n if isinstance(root[entry], dict):\n sum += traverse(root[entry])\n else:\n sum += root[entry]\n global totsum\n totsum.append(sum)\n return sum\n\n\ndef append_if_exists(dictionary: dict, key, val):\n if key not in dictionary.keys():\n dictionary[key] = []\n\n dictionary[key].append(val)\n\ndirections = {\n 'R' : (0,1),\n 'L': (0, -1),\n 'U': (-1, 0),\n 'D': (1, 0)\n\n}\n\ndef move_rope(head, tail, dir):\n new_head = head + dir\n new_diff = new_head - tail\n if any(np.abs(new_diff) > 1):\n tail_movement = np.clip(new_diff, -1, 1)\n else:\n tail_movement = 0\n new_tail = tail + tail_movement\n return new_head, new_tail\n\ndef main():\n file_contents = ''\n with open(inputfile) as infile:\n file_contents = infile.read()\n \n lines = file_contents.splitlines() \n # lines = other_example.splitlines()\n\n print(f\"Read {len(lines)} lines\")\n\n i = 0\n counter = 0\n instructions = []\n register = 1\n signal_strengths = []\n image = []\n while i < len(lines) or instructions:\n if abs(counter % 40 - register) <= 1:\n image.append('#')\n else:\n image.append('.')\n \n if not instructions:\n if lines[i][:4] == 'addx':\n add = int(lines[i].split(' ')[-1])\n instructions.append([2, add])\n i += 1\n elif lines[i] == 'noop':\n i += 1\n counter += 1\n if counter % 40 == 20:\n print(f'Counter: {counter}, Register: {register}')\n signal_strengths.append(counter * register)\n\n if instructions:\n instructions[0][0] -= 1\n if instructions[0][0] == 0:\n register += instructions[0][1]\n instructions = instructions[1:]\n\n print(f'sum: {sum(signal_strengths)}, Signal strengths: {signal_strengths}')\n for line_i in range(len(image) // 40):\n print(''.join(image[line_i* 40:line_i * 40 + 40]))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"120208236","text":"import os\nimport tools.csvio as csv\nimport classicalMethods.cusum_first_implementation as cusum\nimport tools.evaluation as eval\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport classical_methods.baysiancpdetection as baycpd #To be removed (commented) if not needed (needs R)\n\ndef binary2index(m):\n temp = []\n for i in range(len(m)):\n if(m[i] == 1):\n temp.append(i)\n return temp\n\n\ndef evaluationDataSet(folder):\n # Use CUSUM and Bayesian to detect change point\n file_csv = os.listdir(folder)\n precisionB = []\n recallB = []\n precisionC = []\n recallC = []\n\n for f in file_csv:\n f = folder + '/' + f\n reality = csv.csv2list(f, 'rtt', sep=';', decimal='.')\n\n detectionB = baycpd.baysiancpt(reality)\n detectionC = cusum.cusum_var(reality)\n fact = csv.csv2list(f, 'cp', sep=';', decimal='.')\n\n # Change the binary array to index array\n detectionB = binary2index(detectionB)\n detectionC = binary2index(detectionC)\n fact = binary2index(fact)\n\n #print(fact)\n\n temp = eval.evaluation_window_adp(fact, detectionB, 2)\n precisionB.append(temp[\"precision\"])\n recallB.append(temp[\"recall\"])\n\n temp = eval.evaluation_window_adp(fact, detectionC, 2)\n precisionC.append(temp[\"precision\"])\n recallC.append(temp[\"recall\"])\n\n csv.list2csv('./results/resultBayesian_w.csv',\n [file_csv, precisionB, recallB], ['fileName', 'precision', 'recall'])\n csv.list2csv('./results/resultCUSUM_w.csv',\n [file_csv, precisionC, recallC], ['fileName', 'precision', 'recall'])\n\n\ndef cdf_precision_cusum():\n precision = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n cdf = [float(k+1)/len(precision) for k in range(len(precision))]\n precision.sort()\n plt.plot(precision, cdf)\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of precision for cusum method\")\n plt.show()\n return\n\n\ndef cdf_recall_cusum():\n recall = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n cdf = [float(k+1)/len(recall) for k in range(len(recall))]\n recall.sort()\n plt.plot(recall, cdf)\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of recall for cusum method\")\n plt.show()\n return\n\n\ndef cdf_precision_baysian():\n precision = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n cdf = [float(k+1)/len(precision) for k in range(len(precision))]\n precision.sort()\n plt.plot(precision, cdf)\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of precision for Bayesian method\")\n plt.show()\n return\n\n\ndef cdf_recall_baysian():\n recall = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n cdf = [float(k+1)/len(recall) for k in range(len(recall))]\n recall.sort()\n plt.plot(recall, cdf)\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"cdf of recall for Bayesian method\")\n plt.show()\n return\n\n\n# Function that calculate and plot the Fn measure for both methods (n is generally 1 or 2)\ndef Fn_score(n):\n recallBayesian = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n precisionBayesian = csv.csv2list(\n './results/resultBayesian_w.csv', 'precision')\n\n Fn_bayesian = []\n for i in range(len(recallBayesian)):\n if(recallBayesian[i] != 0 or precisionBayesian[i] != 0):\n Fn_bayesian.append((1+n*n)*(precisionBayesian[i]*recallBayesian[i])/(\n n*n*(precisionBayesian[i]+recallBayesian[i])))\n\n else:\n Fn_bayesian.append(0)\n\n recallCusum = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n precisionCusum = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n\n Fn_cusum = []\n for i in range(len(recallCusum)):\n if(recallCusum[i] != 0 or precisionCusum[i] != 0):\n Fn_cusum.append(\n (1+n*n)*(precisionCusum[i]*recallCusum[i])/(n*n*precisionCusum[i]+recallCusum[i]))\n\n else:\n Fn_cusum.append(0)\n\n plt.plot(Fn_bayesian, \"x\", label=\"Bayesian method\")\n plt.plot(Fn_cusum, \"x\", label=\"Cusum method\")\n plt.legend()\n plt.xlabel(\"Index of datasets\")\n plt.ylabel(\"Fn_measure\")\n plt.title(\"F Score for n=\"+str(n) +\n \" applied to the results of Bayesian and Cusum methods\")\n plt.show()\n return\n\n\ndef comparison_precision():\n precisionC = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n precisionB = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n precisionN = csv.csv2list('./results/resultNeuroNet_w.csv', 'precision',)\n cdf = [float(k+1)/len(precisionC) for k in range(len(precisionC))]\n precisionC.sort()\n precisionB.sort()\n precisionN.sort()\n plt.plot(precisionC, cdf, \"r\", label=\"precision of cusum method\")\n plt.plot(precisionB, cdf, \"b\", label=\"precision of bayesian method\")\n plt.plot(precisionN, cdf, \"g\", label=\"precision of NeuroNet\")\n plt.legend()\n plt.xlabel(\"precision\")\n plt.ylabel(\"cdf\")\n plt.title(\"comparison of cdf (precision)\")\n plt.show()\n return\n\n\ndef comparison_recall():\n recallC = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n recallB = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n cdf = [float(k+1)/len(recallC) for k in range(len(recallC))]\n recallC.sort()\n recallB.sort()\n plt.plot(recallC, cdf, \"r\", label=\"recall of cusum method\")\n plt.plot(recallB, cdf, \"b\", label=\"recall of bayesian method\")\n plt.legend()\n plt.xlabel(\"recall\")\n plt.ylabel(\"cdf\")\n plt.title(\"comparison of cdf (recall)\")\n plt.show()\n return\n\n\ndef recall_precision():\n precisionC = csv.csv2list('./results/resultCUSUM_w.csv', 'precision')\n precisionB = csv.csv2list('./results/resultBayesian_w.csv', 'precision')\n precisionN = csv.csv2list('./results/resultNeuroNet_w.csv', 'precision')\n recallC = csv.csv2list('./results/resultCUSUM_w.csv', 'recall')\n recallB = csv.csv2list('./results/resultBayesian_w.csv', 'recall')\n recallN = csv.csv2list('./results/resultNeuroNet_w.csv', 'recall')\n plt.plot(precisionC, recallC, \"rx\", label=\"cusum method\")\n plt.plot(precisionB, recallB, \"bx\", label=\"bayesian method\")\n plt.plot(precisionN, recallN, \"gx\", label=\"NeuroNet method\")\n plt.legend()\n plt.xlabel(\"precision\")\n plt.ylabel(\"recall\")\n plt.title(\"scatterplot (precision,recall)\")\n plt.show()\n return\n\nevaluationDataSet(\"./rtt_series/valid_data\")\n#evaluationDataSet(\"./rtt_series/artificial_dataset\")\nrecall_precision()\n#comparison_precision()","sub_path":"groupProject/evaluation_methods.py","file_name":"evaluation_methods.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"450058549","text":"#create the top most network\ntopnet = exp.createTopNet(\"top\")\ntopnet.createShortestPath();\n\nleft_net = topnet.createNet(\"left\")\nleft_net.createShortestPath();\n\nh1 = left_net.createHost(\"h1\")\nif1 = h1.createInterface(\"if0\")\n\nh2 = left_net.createHost(\"h2\")\nif2 = h2.createInterface(\"if0\")\n\nh3 = left_net.createHost(\"h3\")\nif3 = h3.createInterface(\"if0\")\n\nh4 = left_net.createHost(\"h4\")\nif4 = h4.createInterface(\"if0\")\n\nr = left_net.createRouter(\"r\")\n\nl1 = left_net.createLink()\nl1.createInterface(if1)\nl1.createInterface(r.createInterface(\"if1\"))\n\nl2 = left_net.createLink()\nl2.createInterface(if2)\nl2.createInterface(r.createInterface(\"if2\"))\n\nl3 = left_net.createLink()\nl3.createInterface(if3)\nl3.createInterface(r.createInterface(\"if3\"))\n\nl4 = left_net.createLink()\nl4.createInterface(if4)\nl4.createInterface(r.createInterface(\"if4\"))\n\t\t\n#create the right network\nright_net = left_net.copy(\"right_net\",topnet)\n\n#link the left and right networks\ntoplink = topnet.createLink(\"toplink\")\ntoplink.createInterface(left_net.get(\"r\").createInterface(\"if0\"))\ntoplink.createInterface(right_net.get(\"r\").createInterface(\"if0\"))\n\n#add traffic\nright_h2 = right_net.get(\"h1\")\ntrafficFactory = jprime.TrafficFactory(topnet)\ntrafficFactory.createSimulatedTCP(10, 100000000, h1, right_h2)\ntrafficFactory.createSimulatedTCP(13, 100000000, h2, right_h2)\n\n","sub_path":"examples/MySecondPythonModel.py","file_name":"MySecondPythonModel.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"306400604","text":"import bisect\n\n\nclass Solution:\n def platesBetweenCandles(self, s: str, queries):\n candles = []\n n = len(s)\n for i in range(n):\n if s[i] == '|':\n candles.append(i)\n res = []\n for l, r in queries:\n left = bisect.bisect_left(candles, l)\n right = bisect.bisect_right(candles, r) - 1\n res.append(max(0, candles[right] - candles[left] - (right - left)))\n return res\n\n\ns = Solution()\nprint(s.platesBetweenCandles(\"***|**|*****|**||**|*\", [[1, 17], [4, 5], [14, 17], [5, 11], [15, 16]]))\n# print(s.platesBetweenCandles(\"**|**|***|\", [[2, 5], [5, 9]]))\n","sub_path":"leetcode/2021/bicontest/bcontest-064/bContest3.py","file_name":"bContest3.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"296403827","text":"\"\"\"\nGiven a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.\n\nFor example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].\n\nNote: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].\n\"\"\"\n\n\ndef dailyTemperaturesBruteForce(T):\n \"\"\"\n :type T: List[int]\n :rtype: List[int]\n \"\"\"\n ans = []\n for i in range(len(T)):\n c = 1\n flag = False\n for j in range(i+1, len(T)):\n if T[j] > T[i]:\n ans += [c]\n flag = True\n break\n c += 1\n if not flag:\n ans += [0]\n return ans\n\ndef dailyTempsStack(T):\n ret = [0] * len(T)\n stack = []\n\n for i in range(len(T)):\n\n while stack and T[i] > T[stack[-1]]:\n index = stack.pop()\n ret[index] = i - index\n\n stack.append(i)\n\n print(stack, ret)\n\n return ret\n\nprint(dailyTempsStack([73, 69, 65, 68]))\n","sub_path":"LeetCode/Google/daily_temps.py","file_name":"daily_temps.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"292229514","text":"def isDivisible(a,b):\n if a % b == 0:\n return True\n else:\n return False\n\nresult = True\nnumber = int(input(\"Enter a number: \"))\nfor i in range(2,number-1):\n if isDivisible(number,i):\n result = False\n print(\"Not a prime number.\")\n break\nif result:\n print(\"Prime number.\")\n\n \n","sub_path":"Exercise_11.py","file_name":"Exercise_11.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"213714440","text":"from flask import Blueprint, session, make_response, jsonify, request\n\nfrom managers.ceph_manager import CephManager\nfrom utils.validation_schemas import schemas\nfrom utils.validator import json_schema_validator\n\nbuckets = Blueprint('buckets', __name__)\n\n\n@buckets.route('/buckets', methods=['GET'], strict_slashes=False)\ndef list_buckets():\n ceph = CephManager.from_session(session=session)\n buckets_list = ceph.list_buckets()\n return make_response(jsonify(dict(buckets=buckets_list)), 200)\n\n\n@buckets.route('/buckets', methods=['POST'], strict_slashes=False)\ndef create_bucket():\n \"\"\"\n Creates a bucket and assigns the user's origin to the bucket's CORS\n \"\"\"\n data = request.get_json()\n json_schema_validator(data, schema=schemas['create_bucket'])\n ceph = CephManager.from_session(session=session)\n bucket = ceph.create_buckets(bucket_name=data['name'])\n set_cors(data['name'])\n return make_response(jsonify(bucket), 200)\n\n\n# @buckets.route('/buckets//cors', methods=['GET'], strict_slashes=False)\n# def get_bucket_cors(bucket_name):\n# ceph = CephManager.from_session(session=session)\n# bucket = ceph.get_bucket(bucket_name=bucket_name)\n# return make_response(jsonify(bucket), 200)\n#\n#\n# @buckets.route('/buckets//cors', methods=['PUT'], strict_slashes=False)\n# def set_bucket_cors(bucket_name):\n# ceph = CephManager.from_session(session=session)\n# bucket = ceph.get_bucket(bucket_name=bucket_name)\n# return make_response(jsonify(bucket), 200)\n\n\n@buckets.route('/buckets/', methods=['DELETE'], strict_slashes=False)\ndef delete_bucket(bucket_name):\n ceph = CephManager.from_session(session=session)\n ceph.delete_bucket(bucket_name)\n resp = make_response(jsonify(dict(msg=f\"Bucket {bucket_name} deleted.\")), 200)\n return resp\n\n\n@buckets.route('/buckets/', methods=['GET'], strict_slashes=False)\ndef get_bucket(bucket_name):\n ceph = CephManager.from_session(session=session)\n objects = ceph.list_object(bucket_name)\n if 'Contents' in objects:\n size = sum(obj['Size'] for obj in objects['Contents'])\n length = len(objects['Contents'])\n else:\n size = 0\n length = 0\n response_data = dict(Name=bucket_name, Size=size, Length=length)\n set_cors(bucket_name)\n return make_response(jsonify(response_data), 200)\n\n\ndef set_cors(bucket_name):\n ceph = CephManager.from_session(session=session)\n if 'HTTP_HOST' in request.environ: # Only if the client is a browser this is needed\n ceph.set_bucket_cors(bucket_name=bucket_name, origins=['http://' + request.environ['HTTP_HOST'],\n 'https://' + request.environ['HTTP_HOST']])\n\n\n@buckets.route('/buckets//objects', methods=['GET'], strict_slashes=False)\ndef get_bucket_objects(bucket_name):\n ceph = CephManager.from_session(session=session)\n objects = ceph.list_object(bucket_name)\n return make_response(jsonify(objects['Contents'] if 'Contents' in objects else []), 200)\n","sub_path":"server/routes/buckets.py","file_name":"buckets.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"553271538","text":"#!/user/bin/python3\n# -*- coding: utf-8 -*-\n# compatible with Python 3.4.3\n\n__author__=\"Bo Zhou\"\n__copyright__ = \"Copyright 2015, The NRA project \"\n__credits__ = [\"Bo Zhou\"]\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Bo Zhou\"\n__email__ = \"bzhou2@ualberta.ca\"\n__status__ = \"Testing\"\n\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nimport time\n\ninFile = input(\"Please enter xlsx file name: \")\nstartTime = time.time()\ninwb = load_workbook(filename='data_confirm_PA.xlsx')\nsheetRange = inwb ['NRA Address']\nrow = 1\nreference = []\nwhile True:\n if sheetRange[\"A\"+str(row)].value == None:\n break \n item1 = sheetRange[\"A\"+str(row)].value\n item2 = sheetRange[\"B\"+str(row)].value\n item3 = sheetRange[\"C\"+str(row)].value\n item4 = sheetRange[\"D\"+str(row)].value\n item5 = sheetRange[\"E\"+str(row)].value\n itemTuple = (item1,item2,item3,item4,item5)\n reference.append(itemTuple)\n row += 1\n#inwb.save('data_confirm_PA.xlsx')\n\nrow = 1\ncwb = load_workbook(filename=inFile)\nsheetRange2 = cwb ['NRA Address']\ncompare = []\nwhile True:\n if sheetRange2[\"A\"+str(row)].value == None:\n break \n item1 = sheetRange2[\"A\"+str(row)].value\n item2 = sheetRange2[\"B\"+str(row)].value\n item3 = sheetRange2[\"C\"+str(row)].value\n item4 = sheetRange2[\"D\"+str(row)].value\n item5 = sheetRange2[\"E\"+str(row)].value\n itemTuple = (item1,item2,item3,item4,item5)\n compare.append(itemTuple)\n row += 1\n#cwb.save(inFile)\nbad = 0\nfor e in compare:\n if e not in reference:\n rownumber = compare.index(e)\n print (\"on Row: \"+str(rownumber+1)+\" . Bad data: \",str(e[1]))\n bad += 1\n\nif bad == 0 :\n print (\"All data are found in reference\")\nprint(\"Finish\")\nelapsedTime = time.time() - startTime\nprint (\"time use: \", elapsedTime)","sub_path":"complete_test_data/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"406867607","text":"from flask import Flask, redirect\nfrom flask_socketio import SocketIO, emit\nfrom config import Config\nimport views, websockets\nfrom flask_login import LoginManager\nfrom models.user import User\nfrom flask_login import current_user\n\n\napp = Flask(__name__)\napp.config.from_object(Config)\napp.register_blueprint(views.main_client)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\nsocketio = SocketIO(app)\n\n\n@login_manager.user_loader\ndef load_user(userid):\n return User.get(User.id == userid)\n\n\n@login_manager.unauthorized_handler\ndef unauthorized():\n return redirect('/login')\n\n\n\n\n\n\n\n@socketio.on('my event', namespace='/test')\ndef test_message(message):\n emit('my response', {'data': message['data']}, broadcast=True)\n\n@socketio.on('send_chat_msg', namespace='/test')\ndef test_message(message):\n emit('my response', {'data': message['data'], 'username' : current_user.username}, broadcast=True)\n\n@socketio.on('connect', namespace='/test')\ndef test_connect():\n emit('connected', {'data': current_user.username})\n\n@socketio.on('disconnect', namespace='/test')\ndef test_disconnect():\n print('Client disconnected')\n\nif __name__ == '__main__':\n socketio.run(app)\n\n\n","sub_path":"textFlask/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"473056831","text":"__author__ = 'deutscherkoenig'\nimport datetime\nfrom datetime import date\nimport json\nimport urllib.request\n\n_URL = \"\"\"http://ip-api.com/json\"\"\"\n_FILE_OUT = \"log.txt\"\n\n\ndef get_public_ip():\n try:\n data = json.loads(urllib.request.urlopen(_URL).read().decode(\"utf-8\"))['query']\n except:\n data = \"Error occurred getting IP\"\n _date = date.today()\n _time = str(datetime.datetime.now().time()).split(\".\")[0]\n with open(_FILE_OUT, \"a+\") as file:\n file.write('%s %s: %s \\n' % (_date, _time, data))\n print('%s %s: %s \\n' % (_date, _time, data))\n\n return data\n\nif __name__ == '__main__':\n get_public_ip()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"459798966","text":"__author__ = \"Alejo Herrera\"\n\n#Comisión de Vendedores\n\n# Declarar variables\ncategoria = 1\ntotalventa = 0\nventacat1 = 0\nventacat2 = 0\nventacat3 = 0\nventacat4 = 0\n\n#Estructura repetitiva\nwhile categoria != 0:\n categoria = int(input(\"Ingrese categoria: \"))\n if categoria != 0:\n totalventa = float(input(\"Ingrese total de ventas: \"))\n if categoria == 1:\n ventacat1 = (totalventa * 10 / 100) + ventacat1\n elif categoria == 2:\n ventacat2 = (totalventa * 25 / 100) + ventacat2\n elif categoria == 3:\n ventacat3 = (totalventa * 30 / 100) + ventacat3\n elif categoria == 4:\n ventacat4 = (totalventa * 40 / 100) + ventacat4\n else:\n print(\"ingrese categoria valida\")\n\nprint(\"Categoria 1:\", ventacat1)\nprint(\"Categoria 2:\", ventacat2)\nprint(\"Categoria 3:\", ventacat3)\nprint(\"Categoria 4:\", ventacat4)\n\n\n","sub_path":"Guía de Ejercicios Practicos/Guia de Ejercicios Prácticos-Ficha 06/Ej9.py","file_name":"Ej9.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"86713523","text":"import abc\nimport re\nfrom coltrane.appstorage import atomic_operations, service_fields_for_atomic\nfrom coltrane.rest import exceptions\n\n__author__ = 'Pasha'\n\nclass Validator(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def validate(self, **kwargs):\n raise NotImplementedError(\"This function must be performed in subclasses\")\n\n @abc.abstractmethod\n def _wrong_data(self, doc=None):\n \"\"\"\n Returns invalid data (fields or values) of document.\n Developer should invoke this method in subclasses.\n \"\"\"\n raise NotImplementedError(\"This function must be performed in subclasses\")\n\n\n def _from_list(self, l):\n \"\"\"\n It is used for processing list object type.\n Passed object must be list type only.\n This method should be invoked in subclasses.\n \"\"\"\n found_fields = set()\n for v in l:\n if type(v) == list:\n new_fields = self._from_list(v)\n elif type(v) == dict:\n new_fields = self._wrong_data(v)\n else:\n continue\n if new_fields:\n found_fields = found_fields.union(new_fields)\n return found_fields\n \n\nclass ForbiddenFieldsValidator(Validator):\n \"\"\"\n Base class for validators.\n Validators are used to verify document structure, they should rise errors\n if any of forbidden fields were found in document\n Validators are used in chain (implementation of pattern Chain of Responsibilities).\n \"\"\"\n __metaclass__ = abc.ABCMeta\n \n def __init__(self, doc, forbidden_fields, next_validator=None):\n \"\"\"\n Base constructor for validators.\n Parameters:\n doc - document for validation\n forbidden_fields - fields validation is going on\n next_validator - (object of any subclass of Validator).\n The next validator in the chain after current validator.\n \"\"\"\n\n self.doc = doc\n self.forbidden_fields = forbidden_fields\n self.next_validator = next_validator\n\n def validate(self):\n \"\"\"\n Public method for performing validation.\n Here is all logic of the delegating responsibilities to the next validator\n and raising Exception if there are any of forbidden fields in the document.\n \"\"\"\n found_fields = set()\n validator = self\n while validator:\n found_new = validator._wrong_data(validator.doc)\n found_fields = found_fields.union(found_new)\n validator = validator.next_validator\n\n if len(found_fields):\n raise exceptions.InvalidDocumentFieldsError(\n exceptions.InvalidDocumentFieldsError.FORBIDDEN_FIELDS_MSG %\n ','.join(found_fields))\n\n\nclass SimpleValidator(ForbiddenFieldsValidator):\n \"\"\"\n Finds forbidden fields only in top level of document.\n \"\"\"\n def _wrong_data(self, doc):\n fields = [key for key in doc if key in self.forbidden_fields]\n return set(fields)\n\n \nclass RecursiveValidator(ForbiddenFieldsValidator):\n \"\"\"\n Finds all forbidden fields from top to deepest embedded.\n \"\"\"\n def _wrong_data(self, doc):\n found_fields = set()\n for key in doc:\n if key in self.forbidden_fields:\n found_fields.add(key)\n embed_doc = doc[key]\n if type(embed_doc) is dict:\n new_fields = self._wrong_data(embed_doc)\n elif type(embed_doc) is list:\n new_fields = self._from_list(embed_doc)\n else:\n continue\n if new_fields:\n found_fields = found_fields.union(new_fields)\n return found_fields\n\n\nclass KeyValidator(Validator):\n \"\"\"\n Base validator for _key value and for all keys names.\n Values of in sample {'_key': , :10, : {:5}}\n are validated for correct value.\n \"\"\"\n #Allowed: _a-bc_\n # Forbidden: __a, b__, -c, d.e\n key_re = re.compile(r'^(?!__)\\w[\\w-]*(? in\n {'a':{'b':{'c':}}} by 10\n \"\"\"\n #Allowed: _a-b.c_\n # Forbidden: __a, b__, -c\n key_re = re.compile(r'^(?!__)\\w[\\w\\.-]*(?sig1):\n res.append(0)\n else:\n res.append(1)\n real.append(int(test[i][20]))\n\naccuracy = get_accuracy(res,real)\nprint('accuracy: ', accuracy)\n\nTP = 0\nFP = 0\nFN = 0\nTN = 0\n\nfor i in range(len(res)):\n if(res[i]==1 and real[i]==1):\n TP = TP + 1\n elif(res[i]==1 and real[i]==0):\n FP = FP + 1\n elif(res[i]==0 and real[i]==1):\n FN = FN + 1\n else:\n TN = TN + 1\n\nprecision = TP/(TP+FP)\nprint('precision: ',precision)\n\nrecall = TP/(TP+FN)\nprint('recall: ',recall)\n\nf_measure = 2*precision*recall/(precision+recall)\nprint('F-measure: ',f_measure)\n\nparta = open('Assignment2_260540022_5_1_a.txt','w')\nparta.write('accuracy: '+str(accuracy)+'\\n\\n')\nparta.write('precision: '+str(precision)+'\\n\\n')\nparta.write('recall: '+str(recall)+'\\n\\n')\nparta.write('F-measure: '+str(f_measure)+'\\n\\n')\n\nfile_submit = open('Assignment2_260540022_5_1_b.txt','w')\n\nfile_submit.write('phi: '+str(phi)+'\\n\\n')\nfile_submit.write('mu0: '+str(mu0[0:20])+'\\n\\n')\nfile_submit.write('mu1: '+str(mu1[0:20])+'\\n\\n')\nfile_submit.write('S: '+str(s)+'\\n')\n","sub_path":"COMP551-Assignments/HW2/HW2Q5.py","file_name":"HW2Q5.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"98344378","text":"hauteur = 0\nlargeur = 0\nestOk = 0\ndifficulte = input(\"Capitaine, quel niveau choisissez-vous ? Facile, moyen, difficile ?\").upper()\n\nwhile estOk == 0 :\n if difficulte == \"FACILE\":\n hauteur += 6\n largeur += 6\n\n estOk = 1\n continue\n elif difficulte == \"MOYEN\":\n hauteur += 8\n largeur += 8\n estOk = 1\n continue\n elif difficulte == \"DIFFICILE\":\n hauteur += 11\n largeur += 11\n estOk = 1\n continue\n else:\n print(\"Mauvais\")\n difficulte = input(\"Capitaine, quel niveau choisissez-vous ? Facile, moyen, difficile ?\").upper()\n estOk = 0","sub_path":"difficulte.py","file_name":"difficulte.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"288746343","text":"work = input('Enter the file name: ')\ntry:\n mwork = open(work)\nexcept:\n #work = work.upper()\n print(work, \"TO YOU - You have been punk'd\")\n quit()\ncount = 0\nfor line in mwork:\n if line.startswith('Subject'):\n count = count + 1\nprint('There were', count, 'subject lines in', work)","sub_path":"CC4/CC4-Ex09/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"519698171","text":"import tensorrt as trt\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n\n\nTRT_LOGGER = trt.Logger(trt.Logger.INFO)\n\nmodel_name = 'resnet-101-aic-448-9000-b1'\nmodel_path = 'onnx/' + model_name + '.onnx'\nbuilder = trt.Builder(TRT_LOGGER)\nnetwork = builder.create_network()\nparser = trt.OnnxParser(network, TRT_LOGGER)\nwith open(model_path, 'rb') as model:\n parser.parse(model.read())\n\nbuilder.max_batch_size = 1\n# builder.max_workspace_size = 20<<1\nbuilder.max_workspace_size = 10000000000\n# builder.fp16_mode=True\nengine = builder.build_cuda_engine(network)\n\nwith open(\"engine/\" + model_name + '.engine', \"wb\") as f:\n f.write(engine.serialize())","sub_path":"onnx_to_trtengine.py","file_name":"onnx_to_trtengine.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"164448242","text":"#!/usr/bin/python\n# Filename: prescription.py\n\n\n# This object class represents the prescription we're pulling from the db'\nclass Prescription (object):\n\n def __init__(self,\n ident,\n rxDate,\n orderType,\n medBrand,\n medGeneric,\n medClass,\n numUnits,\n doseCount,\n doseFreq,\n unitDose,\n doseForm,\n notes):\n self.ident = ident\n self.rxDate = rxDate\n self.orderType = orderType\n self.medBrand = medBrand\n self.medGeneric = medGeneric\n self.medClass = medClass\n self.numUnits = numUnits\n self.doseCount = doseCount\n self.doseFreq = doseFreq\n self.unitDose = unitDose\n self.doseForm = doseForm\n self.notes = notes\n\n# End of: prescription.py","sub_path":"tmst_skeleton_proj/package/prescription.py","file_name":"prescription.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"383520454","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport csv\nimport logging\nimport os\nimport re\nfrom moviepy.editor import *\nfrom pathlib import Path\nfrom typing import Optional, Union\nfrom zipfile import ZipFile\n\nimport cv2\nimport pandas as pd\n\nfrom tqdm import tqdm\nfrom tqdm.contrib.logging import logging_redirect_tqdm\n\nfrom .utils import draw_annotations\n\nlog = logging.getLogger(\"fer\")\n\n\nclass Video(object):\n def __init__(\n self,\n video_file: str,\n outdir: str = \"output\",\n first_face_only: bool = True,\n tempfile: Optional[str] = None,\n ):\n \"\"\"Video class for extracting and saving frames for emotion detection.\n :param video_file - str\n :param outdir - str\n :param tempdir - str\n :param first_face_only - bool\n :param tempfile - str\n \"\"\"\n assert os.path.exists(video_file), \"Video file not found at {}\".format(\n os.path.abspath(video_file)\n )\n self.cap = cv2.VideoCapture(video_file)\n if not os.path.isdir(outdir):\n os.makedirs(outdir, exist_ok=True)\n self.outdir = outdir\n\n if not first_face_only:\n log.error(\"Only single-face charting is implemented\")\n self.first_face_only = first_face_only\n self.tempfile = tempfile\n self.filepath = video_file\n self.filename = \"\".join(self.filepath.split(\"/\")[-1])\n\n @staticmethod\n def get_max_faces(data: list) -> int:\n \"\"\"Get max number of faces detected in a series of frames, eg 3\"\"\"\n max = 0\n for frame in data:\n for face in frame:\n if len(face) > max:\n max = len(face)\n return max\n\n @staticmethod\n def _to_dict(data: Union[dict, list]) -> dict:\n emotions = []\n\n frame = data[0]\n if isinstance(frame, list):\n try:\n emotions = frame[0][\"emotions\"].keys()\n except IndexError:\n raise Exception(\"No data in 'data'\")\n elif isinstance(frame, dict):\n return data\n\n dictlist = []\n\n for data_idx, frame in enumerate(data):\n rowdict = {}\n for idx, face in enumerate(list(frame)):\n if not isinstance(face, dict):\n break\n rowdict.update({\"box\" + str(idx): face[\"box\"]})\n rowdict.update(\n {emo + str(idx): face[\"emotions\"][emo] for emo in emotions}\n )\n dictlist.append(rowdict)\n return dictlist\n\n def to_pandas(self, data: Union[pd.DataFrame, list]) -> pd.DataFrame:\n \"\"\"Convert results to pandas DataFrame\"\"\"\n if isinstance(data, pd.DataFrame):\n return data\n\n if not len(data):\n return pd.DataFrame()\n datalist = self._to_dict(data)\n df = pd.DataFrame(datalist)\n if self.first_face_only:\n df = self.get_first_face(df)\n return df\n\n @staticmethod\n def get_first_face(df: pd.DataFrame) -> pd.DataFrame:\n assert isinstance(df, pd.DataFrame), \"Must be a pandas DataFrame\"\n try:\n int(df.columns[0][-1])\n except ValueError:\n # Already only one face in df\n return df\n\n columns = [x for x in df.columns if x[-1] == \"0\"]\n new_columns = [x[:-1] for x in columns]\n single_df = df[columns]\n single_df.columns = new_columns\n return single_df\n\n @staticmethod\n def get_emotions(df: pd.DataFrame) -> list:\n \"\"\"Get emotion columsn from results.\"\"\"\n columns = [x for x in df.columns if \"box\" not in x]\n return df[columns]\n\n def to_csv(self, data, filename=\"data.csv\"):\n \"\"\"Save data to csv\"\"\"\n\n def key(item):\n key_pat = re.compile(r\"^(\\D+)(\\d+)$\")\n m = key_pat.match(item)\n return m.group(1), int(m.group(2))\n\n dictlist = self._to_dict(data)\n columns = set().union(*(d.keys() for d in dictlist))\n columns = sorted(columns, key=key) # sort by trailing number (faces)\n\n with open(\"data.csv\", \"w\", newline=\"\") as csvfile:\n writer = csv.DictWriter(csvfile, columns, lineterminator=\"\\n\")\n writer.writeheader()\n writer.writerows(dictlist)\n return dictlist\n\n def _close_video(self, outfile, save_frames, zip_images):\n self.cap.release()\n if self.display or self.save_video:\n self.videowriter.release()\n\n if self.save_video:\n log.info(\"Completed analysis: saved to {}\".format(self.tempfile or outfile))\n if self.tempfile:\n os.replace(self.tempfile, outfile)\n\n if save_frames and zip_images:\n log.info(\"Starting to Zip\")\n outdir = Path(self.outdir)\n zip_dir = outdir / \"images.zip\"\n images = sorted(list(outdir.glob(\"*.jpg\")))\n total = len(images)\n i = 0\n with ZipFile(zip_dir, \"w\") as zip:\n for file in images:\n zip.write(file, arcname=file.name)\n os.remove(file)\n i += 1\n if i % 50 == 0:\n log.info(f\"Compressing: {i*100 // total}%\")\n log.info(\"Zip has finished\")\n\n def _offset_detection_box(self, faces, detection_box):\n for face in faces:\n original_box = face.get(\"box\")\n face[\"box\"] = (\n original_box[0] + detection_box.get(\"x_min\"),\n original_box[1] + detection_box.get(\"y_min\"),\n original_box[2],\n original_box[3],\n )\n return faces\n\n def _increment_frames(\n self, frame, faces, video_id, root, lang=\"en\", size_multiplier=1\n ):\n # Save images to `self.outdir`\n imgpath = os.path.join(\n self.outdir, (video_id or root) + str(self.frameCount) + \".jpg\"\n )\n\n if self.annotate_frames:\n frame = draw_annotations(\n frame,\n faces,\n boxes=True,\n scores=True,\n lang=lang,\n size_multiplier=size_multiplier,\n )\n\n if self.save_frames:\n cv2.imwrite(imgpath, frame)\n\n if self.display:\n cv2.imshow(\"Video\", frame)\n\n if self.save_video:\n self.videowriter.write(frame)\n\n self.frameCount += 1\n\n def analyze(\n self,\n detector, # fer.FER instance\n display: bool = False,\n output: str = \"csv\",\n frequency: Optional[int] = None,\n max_results: int = None,\n save_fps: Optional[int] = None,\n video_id: Optional[str] = None,\n save_frames: bool = True,\n save_video: bool = True,\n annotate_frames: bool = True,\n zip_images: bool = True,\n detection_box: Optional[dict] = None,\n lang: str = \"en\",\n include_audio: bool = False,\n size_multiplier: int = 1,\n ) -> list:\n \"\"\"Recognize facial expressions in video using `detector`.\n\n Args:\n\n detector (fer.FER): facial expression recognizer\n display (bool): show images with cv2.imshow\n output (str): csv or pandas\n frequency (int): inference on every nth frame (higher number is faster)\n max_results (int): number of frames to run inference before stopping\n save_fps (bool): inference frequency = video fps // save_fps\n video_id (str): filename for saving\n save_frames (bool): saves frames to directory\n save_video (bool): saves output video\n annotate_frames (bool): add emotion labels\n zip_images (bool): compress output\n detection_box (dict): dict with bounding box for subimage (xmin, xmax, ymin, ymax)\n lang (str): emotion language that will be shown on video\n include_audio (bool): indicates if a sounded version of the prediction video should be created or not\n size_multiplier (int): increases the size of emotion labels shown in the video by x(size_multiplier)\n Returns:\n\n data (list): list of results\n\n \"\"\"\n frames_emotions = []\n if frequency is None:\n frequency = 1\n else:\n frequency = int(frequency)\n\n self.display = display\n self.save_frames = save_frames\n self.save_video = save_video\n self.annotate_frames = annotate_frames\n\n results_nr = 0\n\n # Open video\n assert self.cap.open(self.filepath), \"Video capture not opening\"\n self.__emotions = detector._get_labels().items()\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n pos_frames = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n assert int(pos_frames) == 0, \"Video not at index 0\"\n\n self.frameCount = 0\n height, width = (\n int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n )\n\n fps = self.cap.get(cv2.CAP_PROP_FPS)\n length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n assert fps and length, \"File {} not loaded\".format(self.filepath)\n\n if save_fps is not None:\n frequency = fps // save_fps\n log.info(\"Saving every {} frames\".format(frequency))\n\n log.info(\n \"{:.2f} fps, {} frames, {:.2f} seconds\".format(fps, length, length / fps)\n )\n\n if self.save_frames:\n os.makedirs(self.outdir, exist_ok=True)\n log.info(f\"Making directories at {self.outdir}\")\n root, ext = os.path.splitext(os.path.basename(self.filepath))\n outfile = os.path.join(self.outdir, f\"{root}_output{ext}\")\n\n if save_video:\n self.videowriter = self._save_video(outfile, fps, width, height)\n\n with logging_redirect_tqdm():\n pbar = tqdm(total=length, unit=\"frames\")\n\n while self.cap.isOpened():\n ret, frame = self.cap.read()\n if not ret: # end of video\n break\n\n if frame is None:\n log.warn(\"Empty frame\")\n continue\n\n if self.frameCount % frequency != 0:\n self.frameCount += 1\n continue\n\n if detection_box is not None:\n frame = self._crop(frame, detection_box)\n\n # Get faces and detect emotions; coordinates are for unpadded frame\n try:\n faces = detector.detect_emotions(frame)\n except Exception as e:\n log.error(e)\n break\n\n # Offset detection_box to include padding\n if detection_box is not None:\n faces = self._offset_detection_box(faces, detection_box)\n\n self._increment_frames(frame, faces, video_id, root, lang, size_multiplier)\n\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n if faces:\n frames_emotions.append(faces)\n\n results_nr += 1\n if max_results and results_nr > max_results:\n break\n\n pbar.update(1)\n\n pbar.close()\n self._close_video(outfile, save_frames, zip_images)\n\n if include_audio:\n audio_suffix = \"_audio.\"\n my_audio = AudioFileClip(self.filepath)\n new_audioclip = CompositeAudioClip([my_audio])\n\n my_output_clip = VideoFileClip(outfile)\n my_output_clip.audio = new_audioclip\n my_output_clip.write_videofile(audio_suffix.join(outfile.rsplit(\".\", 1)))\n\n return self.to_format(frames_emotions, output)\n\n def to_format(self, data, format):\n \"\"\"Return data in format.\"\"\"\n methods_lookup = {\"csv\": self.to_csv, \"pandas\": self.to_pandas}\n return methods_lookup[format](data)\n\n def _save_video(self, outfile: str, fps: int, width: int, height: int):\n if os.path.isfile(outfile):\n os.remove(outfile)\n log.info(\"Deleted pre-existing {}\".format(outfile))\n if self.tempfile and os.path.isfile(self.tempfile):\n os.remove(self.tempfile)\n fourcc = cv2.VideoWriter_fourcc(\"m\", \"p\", \"4\", \"v\")\n videowriter = cv2.VideoWriter(\n self.tempfile or outfile, fourcc, fps, (width, height), True\n )\n return videowriter\n\n @staticmethod\n def _crop(frame, detection_box):\n crop_frame = frame[\n detection_box.get(\"y_min\") : detection_box.get(\"y_max\"),\n detection_box.get(\"x_min\") : detection_box.get(\"x_max\"),\n ]\n return crop_frame\n\n def __del__(self):\n cv2.destroyAllWindows()\n","sub_path":"src/fer/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":12702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"80680543","text":"\"\"\" Module for Ulmo analysis on VIIRS 2013\"\"\"\nimport os\nimport glob\nfrom h5py._hl import base\nimport numpy as np\nimport subprocess \nfrom pkg_resources import resource_filename\n\nimport pandas\nimport h5py\nfrom skimage.restoration import inpaint \n\nfrom sklearn.utils import shuffle\n\nfrom ulmo import io as ulmo_io\n\nfrom ulmo.ssl.my_util import Params, option_preprocess\nfrom ulmo.ssl import latents_extraction\n\nfrom functools import partial\nfrom concurrent.futures import ProcessPoolExecutor\nimport subprocess\nfrom tqdm import tqdm\n\nfrom IPython import embed\n\ndef ssl_test_eval_orig(debug=False, orig=False):\n model_path = './'\n model_name = \"last.pth\"\n # Load options\n opt_file = os.path.join(resource_filename('ulmo', 'runs'),\n 'SSL', 'First','experiments', \n 'base_modis_model', 'opts.json')\n opt = Params(opt_file)\n opt = option_preprocess(opt)\n base_file = 'test_orig.h5'\n \n # Load\n hf = h5py.File(base_file, 'r')\n modis_data = hf['train'][:]\n\n # Output\n model_path_title = os.path.join(model_path, model_name)\n model_name = model_name.split('.')[0]\n latents_path = 'orig_latents.h5'\n save_key = 'modis_latents'\n \n # Run\n latents_extraction.orig_latents_extract(opt, modis_data,\n model_path_title, \n latents_path, \n save_key)\n\ndef ssl_eval_2010(dataset, debug=False, orig=False):\n s3_model_path = 's3://modis-l2/modis_simclr_base_model/SimCLR_modis_resnet50_lr_0.05_decay_0.0001_bsz_64_temp_0.07_trial_0_cosine_warm/last.pth'\n ulmo_io.download_file_from_s3(os.path.basename(s3_model_path), s3_model_path)\n model_path = './'\n model_name = \"last.pth\"\n\n # Load options\n opt_file = os.path.join(resource_filename('ulmo', 'runs'),\n 'SSL', 'First','experiments', \n 'base_modis_model', 'opts.json')\n opt = Params(opt_file)\n opt = option_preprocess(opt)\n\n # Load the data\n print(\"Grabbing MODIS [if needed]\")\n if orig:\n modis_dataset_path = \"s3://modis-l2/PreProc/MODIS_2010_95clear_128x128_inpaintT_preproc_0.8valid.h5\"\n else:\n modis_dataset_path = \"s3://modis-l2/PreProc/MODIS_R2019_2010_95clear_128x128_preproc_std.h5\"\n base_file = os.path.basename(modis_dataset_path)\n if not os.path.isfile(base_file):\n ulmo_io.download_file_from_s3(base_file, modis_dataset_path)\n\n # Output\n model_path_title = os.path.join(model_path, model_name)\n model_name = model_name.split('.')[0]\n if orig:\n latents_path = f'MODIS_orig_2010_{dataset}_{model_name}.h5'\n else:\n latents_path = f'MODIS_2010_{dataset}_{model_name}.h5'\n save_key = 'modis_latents'\n \n # Run\n latents_extraction.model_latents_extract(opt, base_file, dataset,\n model_path_title, latents_path, \n save_key)\n # Push to s3 \n s3_outfile = 's3://modis-l2/modis_latents_simclr/'+latents_path\n ulmo_io.upload_file_to_s3(latents_path, s3_outfile)\n\n\n\ndef main(flg):\n if flg== 'all':\n flg= np.sum(np.array([2 ** ii for ii in range(25)]))\n else:\n flg= int(flg)\n\n # Evaluate the MODIS training data from 2010\n if flg & (2**0):\n ssl_eval_2010('train')\n\n # Evaluate the MODIS valid data from 2010\n if flg & (2**1):\n ssl_eval_2010('valid')\n\n # Evaluate the MODIS valid data from 2010\n if flg & (2**2):\n ssl_test_eval_orig()\n\n # Evaluate the MODIS training data from 2010\n if flg & (2**3):\n ssl_eval_2010('train', orig=True)\n\n\n# Command line execution\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) == 1:\n flg = 0\n #flg += 2 ** 0 # 1 -- MODIS 2010 training\n #flg += 2 ** 1 # 2 -- MODIS 2010 valid\n #flg += 2 ** 2 # 4 -- Debuggin\n flg += 2 ** 3 # 8 -- re-run orig\n else:\n flg = sys.argv[1]\n\n main(flg)","sub_path":"ulmo/runs/Nenya/MODIS/First/ssl_first.py","file_name":"ssl_first.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"256411662","text":"from typing import List\n\n\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n lens = len(digits)\n for i in range(1, lens + 1):\n tmp = digits[-i] + 1\n if tmp <= 9:\n digits[-i] = tmp\n return digits\n digits[-i] = 0\n if i == lens:\n digits.insert(0, 1)\n return digits\n","sub_path":"Week_01/0066plusOne.py","file_name":"0066plusOne.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"264441647","text":"#\n# zfcp.py - mainframe zfcp configuration install data\n#\n# Copyright (C) 2001, 2002, 2003, 2004 Red Hat, Inc. All rights reserved.\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 2 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# Author(s): Karsten Hopp \n#\n\nimport string\nimport os\nfrom . import udev\nfrom . import util\nfrom .i18n import _\n\nimport logging\nlog = logging.getLogger(\"blivet\")\n\ndef loggedWriteLineToFile(fn, value):\n f = open(fn, \"w\")\n log.debug(\"echo %s > %s\", value, fn)\n f.write(\"%s\\n\" % (value))\n f.close()\n\nzfcpsysfs = \"/sys/bus/ccw/drivers/zfcp\"\nscsidevsysfs = \"/sys/bus/scsi/devices\"\nzfcpconf = \"/etc/zfcp.conf\"\n\nclass ZFCPDevice:\n \"\"\"\n .. warning::\n Since this is a singleton class, calling deepcopy() on the instance\n just returns ``self`` with no copy being created.\n \"\"\"\n\n def __init__(self, devnum, wwpn, fcplun):\n self.devnum = self.sanitizeDeviceInput(devnum)\n self.wwpn = self.sanitizeWWPNInput(wwpn)\n self.fcplun = self.sanitizeFCPLInput(fcplun)\n\n if not self.checkValidDevice(self.devnum):\n raise ValueError(_(\"You have not specified a device number or the number is invalid\"))\n if not self.checkValidWWPN(self.wwpn):\n raise ValueError(_(\"You have not specified a worldwide port name or the name is invalid.\"))\n if not self.checkValidFCPLun(self.fcplun):\n raise ValueError(_(\"You have not specified a FCP LUN or the number is invalid.\"))\n\n def __str__(self):\n return \"%s %s %s\" %(self.devnum, self.wwpn, self.fcplun)\n\n def sanitizeDeviceInput(self, dev):\n if dev is None or dev == \"\":\n return None\n dev = dev.lower()\n bus = dev[:string.rfind(dev, \".\") + 1]\n dev = dev[string.rfind(dev, \".\") + 1:]\n dev = \"0\" * (4 - len(dev)) + dev\n if not len(bus):\n return \"0.0.\" + dev\n else:\n return bus + dev\n\n def sanitizeWWPNInput(self, wwpn):\n if wwpn is None or wwpn == \"\":\n return None\n wwpn = wwpn.lower()\n if wwpn[:2] != \"0x\":\n return \"0x\" + wwpn\n return wwpn\n\n # ZFCP LUNs are usually entered as 16 bit, sysfs accepts only 64 bit\n # (#125632), expand with zeroes if necessary\n def sanitizeFCPLInput(self, lun):\n if lun is None or lun == \"\":\n return None\n lun = lun.lower()\n if lun[:2] == \"0x\":\n lun = lun[2:]\n lun = \"0x\" + \"0\" * (4 - len(lun)) + lun\n lun = lun + \"0\" * (16 - len(lun) + 2)\n return lun\n\n def _hextest(self, hexnum):\n try:\n int(hexnum, 16)\n return True\n except TypeError:\n return False\n\n def checkValidDevice(self, devnum):\n if devnum is None or devnum == \"\":\n return False\n if len(devnum) != 8: # p.e. 0.0.0600\n return False\n if devnum[0] not in string.digits or devnum[2] not in string.digits:\n return False\n if devnum[1] != \".\" or devnum[3] != \".\":\n return False\n return self._hextest(devnum[4:])\n\n def checkValid64BitHex(self, hexnum):\n if hexnum is None or hexnum == \"\":\n return False\n if len(hexnum) != 18:\n return False\n return self._hextest(hexnum)\n checkValidWWPN = checkValidFCPLun = checkValid64BitHex\n\n def onlineDevice(self):\n online = \"%s/%s/online\" %(zfcpsysfs, self.devnum)\n portadd = \"%s/%s/port_add\" %(zfcpsysfs, self.devnum)\n portdir = \"%s/%s/%s\" %(zfcpsysfs, self.devnum, self.wwpn)\n unitadd = \"%s/unit_add\" %(portdir)\n unitdir = \"%s/%s\" %(portdir, self.fcplun)\n failed = \"%s/failed\" %(unitdir)\n\n if not os.path.exists(online):\n log.info(\"Freeing zFCP device %s\", self.devnum)\n util.run_program([\"zfcp_cio_free\", \"-d\", self.devnum])\n\n if not os.path.exists(online):\n raise ValueError(_(\"zFCP device %s not found, not even in device ignore list.\") % \\\n (self.devnum,))\n\n try:\n f = open(online, \"r\")\n devonline = f.readline().strip()\n f.close()\n if devonline != \"1\":\n loggedWriteLineToFile(online, \"1\")\n except IOError as e:\n raise ValueError(_(\"Could not set zFCP device %(devnum)s \"\n \"online (%(e)s).\") \\\n % {'devnum': self.devnum, 'e': e})\n\n if not os.path.exists(portdir):\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n try:\n loggedWriteLineToFile(portadd, self.wwpn)\n udev.settle()\n except IOError as e:\n raise ValueError(_(\"Could not add WWPN %(wwpn)s to zFCP \"\n \"device %(devnum)s (%(e)s).\") \\\n % {'wwpn': self.wwpn,\n 'devnum': self.devnum,\n 'e': e})\n else:\n # newer zfcp sysfs interface with auto port scan\n raise ValueError(_(\"WWPN %(wwpn)s not found at zFCP device \"\n \"%(devnum)s.\") % {'wwpn': self.wwpn,\n 'devnum': self.devnum})\n else:\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n log.info(\"WWPN %(wwpn)s at zFCP device %(devnum)s already \"\n \"there.\", {'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n if not os.path.exists(unitdir):\n try:\n loggedWriteLineToFile(unitadd, self.fcplun)\n udev.settle()\n except IOError as e:\n raise ValueError(_(\"Could not add LUN %(fcplun)s to WWPN \"\n \"%(wwpn)s on zFCP device %(devnum)s \"\n \"(%(e)s).\") \\\n % {'fcplun': self.fcplun, 'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n else:\n raise ValueError(_(\"LUN %(fcplun)s at WWPN %(wwpn)s on zFCP \"\n \"device %(devnum)s already configured.\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n fail = \"0\"\n try:\n f = open(failed, \"r\")\n fail = f.readline().strip()\n f.close()\n except IOError as e:\n raise ValueError(_(\"Could not read failed attribute of LUN \"\n \"%(fcplun)s at WWPN %(wwpn)s on zFCP device \"\n \"%(devnum)s (%(e)s).\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum,\n 'e': e})\n if fail != \"0\":\n self.offlineDevice()\n raise ValueError(_(\"Failed LUN %(fcplun)s at WWPN %(wwpn)s on \"\n \"zFCP device %(devnum)s removed again.\") \\\n % {'fcplun': self.fcplun,\n 'wwpn': self.wwpn,\n 'devnum': self.devnum})\n\n return True\n\n def offlineSCSIDevice(self):\n f = open(\"/proc/scsi/scsi\", \"r\")\n lines = f.readlines()\n f.close()\n # alternatively iterate over /sys/bus/scsi/devices/*:0:*:*/\n\n for line in lines:\n if not line.startswith(\"Host\"):\n continue\n scsihost = string.split(line)\n host = scsihost[1]\n channel = \"0\"\n devid = scsihost[5]\n lun = scsihost[7]\n scsidev = \"%s:%s:%s:%s\" % (host[4:], channel, devid, lun)\n fcpsysfs = \"%s/%s\" % (scsidevsysfs, scsidev)\n scsidel = \"%s/%s/delete\" % (scsidevsysfs, scsidev)\n\n f = open(\"%s/hba_id\" %(fcpsysfs), \"r\")\n fcphbasysfs = f.readline().strip()\n f.close()\n f = open(\"%s/wwpn\" %(fcpsysfs), \"r\")\n fcpwwpnsysfs = f.readline().strip()\n f.close()\n f = open(\"%s/fcp_lun\" %(fcpsysfs), \"r\")\n fcplunsysfs = f.readline().strip()\n f.close()\n\n if fcphbasysfs == self.devnum \\\n and fcpwwpnsysfs == self.wwpn \\\n and fcplunsysfs == self.fcplun:\n loggedWriteLineToFile(scsidel, \"1\")\n udev.settle()\n return\n\n log.warn(\"no scsi device found to delete for zfcp %s %s %s\",\n self.devnum, self.wwpn, self.fcplun)\n\n def offlineDevice(self):\n offline = \"%s/%s/online\" %(zfcpsysfs, self.devnum)\n portadd = \"%s/%s/port_add\" %(zfcpsysfs, self.devnum)\n portremove = \"%s/%s/port_remove\" %(zfcpsysfs, self.devnum)\n unitremove = \"%s/%s/%s/unit_remove\" %(zfcpsysfs, self.devnum, self.wwpn)\n portdir = \"%s/%s/%s\" %(zfcpsysfs, self.devnum, self.wwpn)\n devdir = \"%s/%s\" %(zfcpsysfs, self.devnum)\n\n try:\n self.offlineSCSIDevice()\n except IOError as e:\n raise ValueError(_(\"Could not correctly delete SCSI device of \"\n \"zFCP %(devnum)s %(wwpn)s %(fcplun)s \"\n \"(%(e)s).\") \\\n % {'devnum': self.devnum, 'wwpn': self.wwpn,\n 'fcplun': self.fcplun, 'e': e})\n\n try:\n loggedWriteLineToFile(unitremove, self.fcplun)\n except IOError as e:\n raise ValueError(_(\"Could not remove LUN %(fcplun)s at WWPN \"\n \"%(wwpn)s on zFCP device %(devnum)s \"\n \"(%(e)s).\") \\\n % {'fcplun': self.fcplun, 'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n\n if os.path.exists(portadd):\n # only try to remove ports with older zfcp sysfs interface\n for lun in os.listdir(portdir):\n if lun.startswith(\"0x\") and \\\n os.path.isdir(os.path.join(portdir, lun)):\n log.info(\"Not removing WWPN %s at zFCP device %s since port still has other LUNs, e.g. %s.\",\n self.wwpn, self.devnum, lun)\n return True\n\n try:\n loggedWriteLineToFile(portremove, self.wwpn)\n except IOError as e:\n raise ValueError(_(\"Could not remove WWPN %(wwpn)s on zFCP \"\n \"device %(devnum)s (%(e)s).\") \\\n % {'wwpn': self.wwpn,\n 'devnum': self.devnum, 'e': e})\n\n if os.path.exists(portadd):\n # older zfcp sysfs interface\n for port in os.listdir(devdir):\n if port.startswith(\"0x\") and \\\n os.path.isdir(os.path.join(devdir, port)):\n log.info(\"Not setting zFCP device %s offline since it still has other ports, e.g. %s.\",\n self.devnum, port)\n return True\n else:\n # newer zfcp sysfs interface with auto port scan\n import glob\n luns = glob.glob(\"%s/0x????????????????/0x????????????????\"\n %(devdir,))\n if len(luns) != 0:\n log.info(\"Not setting zFCP device %s offline since it still has other LUNs, e.g. %s.\",\n self.devnum, luns[0])\n return True\n\n try:\n loggedWriteLineToFile(offline, \"0\")\n except IOError as e:\n raise ValueError(_(\"Could not set zFCP device %(devnum)s \"\n \"offline (%(e)s).\") \\\n % {'devnum': self.devnum, 'e': e})\n\n return True\n\nclass ZFCP:\n \"\"\" ZFCP utility class.\n\n This class will automatically online to ZFCP drives configured in\n /tmp/fcpconfig when the startup() method gets called. It can also be\n used to manually configure ZFCP devices through the addFCP() method.\n\n As this class needs to make sure that /tmp/fcpconfig configured\n drives are only onlined once and as it keeps a global list of all ZFCP\n devices it is implemented as a Singleton.\n \"\"\"\n\n def __init__(self):\n self.intf = None\n self.fcpdevs = set()\n self.hasReadConfig = False\n self.down = True\n\n # So that users can write zfcp() to get the singleton instance\n def __call__(self):\n return self\n\n def __deepcopy__(self, memo_dict):\n # pylint: disable=unused-argument\n return self\n\n def readConfig(self):\n try:\n f = open(zfcpconf, \"r\")\n except IOError:\n log.info(\"no %s; not configuring zfcp\", zfcpconf)\n return\n\n lines = [x.strip().lower() for x in f.readlines()]\n f.close()\n\n for line in lines:\n if line.startswith(\"#\") or line == '':\n continue\n\n fields = line.split()\n\n if len(fields) == 3:\n devnum = fields[0]\n wwpn = fields[1]\n fcplun = fields[2]\n elif len(fields) == 5:\n # support old syntax of:\n # devno scsiid wwpn scsilun fcplun\n devnum = fields[0]\n wwpn = fields[2]\n fcplun = fields[4]\n else:\n log.warn(\"Invalid line found in %s: %s\", zfcpconf, line)\n continue\n\n try:\n self.addFCP(devnum, wwpn, fcplun)\n except ValueError as e:\n if self.intf:\n self.intf.messageWindow(_(\"Error\"), str(e))\n else:\n log.warning(\"%s\", str(e))\n\n def addFCP(self, devnum, wwpn, fcplun):\n d = ZFCPDevice(devnum, wwpn, fcplun)\n if d.onlineDevice():\n self.fcpdevs.add(d)\n\n def shutdown(self):\n if self.down:\n return\n self.down = True\n if len(self.fcpdevs) == 0:\n return\n for d in self.fcpdevs:\n try:\n d.offlineDevice()\n except ValueError as e:\n log.warn(\"%s\", str(e))\n\n def startup(self):\n if not self.down:\n return\n self.down = False\n if not self.hasReadConfig:\n self.readConfig()\n self.hasReadConfig = True\n # readConfig calls addFCP which calls onlineDevice already\n return\n\n if len(self.fcpdevs) == 0:\n return\n for d in self.fcpdevs:\n try:\n d.onlineDevice()\n except ValueError as e:\n log.warn(\"%s\", str(e))\n\n def write(self, root, zfcpdevs):\n # make sure that any zfcp devices (not only those which were manually\n # added) used during installation are included in /etc/zfcp.conf\n if zfcpdevs:\n for d in zfcpdevs:\n dev = ZFCPDevice(d.hba_id, d.wwpn, d.fcp_lun)\n if dev not in self.fcpdevs:\n self.fcpdevs.add(dev)\n\n if not self.fcpdevs:\n return\n f = open(root + zfcpconf, \"w\")\n for d in self.fcpdevs:\n f.write(\"%s\\n\" %(d,))\n f.close()\n\n f = open(root + \"/etc/modprobe.conf\", \"a\")\n f.write(\"alias scsi_hostadapter zfcp\\n\")\n f.close()\n\n# Create ZFCP singleton\nZFCP = ZFCP()\n\n# vim:tw=78:ts=4:et:sw=4\n","sub_path":"python2.7/site-packages/blivet/zfcp.py","file_name":"zfcp.py","file_ext":"py","file_size_in_byte":16396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"221924467","text":"import os\nimport cv2 as cv\n\nfrom modules.utils.helpers import get_paths_of_files_from_path\n\nHR_IMAGES_FOLDER = r\"\"\nOUTPUT_FOLDER = r\"\"\nTARGET_SHAPE = (256, 256)\n\nassert os.path.exists(HR_IMAGES_FOLDER), \"Input folder doesnt exist\"\nif not os.path.exists(OUTPUT_FOLDER): os.makedirs(OUTPUT_FOLDER)\n\nhr_image_paths = get_paths_of_files_from_path(HR_IMAGES_FOLDER, only_files=True)\nassert len(hr_image_paths) > 0, \"High resulution image folder is empty\"\n\nfor idx, hr_image_path in enumerate(hr_image_paths):\n if not os.path.exists(hr_image_path):\n continue\n\n hr_image = cv.imread(hr_image_path)\n if hr_image is None:\n continue\n\n iter_over_y = int(hr_image.shape[0] / TARGET_SHAPE[1])\n iter_over_x = int(hr_image.shape[1] / TARGET_SHAPE[0])\n\n if iter_over_x == 0 and iter_over_y == 0:\n continue\n \n for y_idx in range(iter_over_y):\n for x_idx in range(iter_over_x):\n image_part = hr_image[y_idx * TARGET_SHAPE[1]:(y_idx + 1) * TARGET_SHAPE[1], x_idx * TARGET_SHAPE[0]:(x_idx + 1) * TARGET_SHAPE[0], :]\n cv.imwrite(os.path.join(OUTPUT_FOLDER, f\"{idx}_{(y_idx * TARGET_SHAPE[1]) + x_idx}.png\"), image_part)","sub_path":"parse_hr_image.py","file_name":"parse_hr_image.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"61183301","text":"import os\nimport sys\nimport unittest\nfrom unittest.mock import Mock, MagicMock, patch\nfrom argparse import Namespace\n\npkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa\nsys.path.insert(0, pkg_root) # noqa\n\nfrom ssds.cli import staging as staging_cli\n\n\nclass TestStagingCLI(unittest.TestCase):\n def test_upload(self):\n mock_staging = Mock()\n mock_staging.upload = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace(submission_id=\"foo\", name=\"bar\", path=\"asf\")\n staging_cli.upload(args)\n expected_path = os.path.abspath(os.path.normpath(args.path))\n mock_staging.upload.assert_called_with(expected_path, args.submission_id, args.name)\n\n def test_list(self):\n mock_staging = Mock()\n mock_staging.list = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace()\n staging_cli.list(args)\n mock_staging.list.assert_called()\n\n def test_list_submission(self):\n mock_staging = Mock()\n mock_staging.list_submission = MagicMock()\n with patch(\"ssds.Staging\", Mock(return_value=mock_staging)):\n args = Namespace(submission_id=\"foo\")\n staging_cli.list_submission(args)\n mock_staging.list_submission.assert_called_with(args.submission_id)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"154922002","text":"import urllib.request as ur\nimport matplotlib.pyplot as plt\n# import cStringIO\nimport requests\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nimport html_downloader\nimport html_parser\nimport url_manager\nimport html_outputer\nimport json\n\ndef learning1():\n request = ur.Request('https://blog.csdn.net/samsam2013/article/details/78492122')\n request.add_header(\"user-agent\", 'Mozilla/5.0')\n response = ur.urlopen(request)\n f = open('a.txt', 'w', encoding='utf-8')\n print(response.read().decode(), file=f)\n\n\ndef usebs():\n html_doc = \"\"\"\n The Dormouse's story\n \n The Dormouse's story
\n\n Once upon a time there were three little sisters; and their names were\n Elsie,\n Lacie and\n Tillie;\n and they lived at the bottom of a well.
\n\n ...
\n \"\"\"\n soup = BeautifulSoup(\n html_doc,\n 'html.parser'\n )\n print(soup.find_all())\n\n\nclass SpiderMain(object):\n def __init__(self):\n self.urls = url_manager.UrlManager()\n self.downloader = html_downloader.HtmlDownloader()\n self.parser = html_parser.HtmlParser()\n self.output = html_outputer.HtmlOutputer()\n\n def craw(self, root_url):\n count = 1\n self.urls.add_new_url(root_url)\n while self.urls.has_new_url():\n try:\n new_url = self.urls.get_new_urls()\n print(\"craw %d:%s\" % (count, new_url))\n html_cont = self.downloader.downloader(new_url)\n new_urls, new_data = self.parser.parse(new_url, html_cont)\n self.urls.add_new_urls(new_urls)\n self.output.collect_data(new_data)\n count += 1\n if count == 100:\n break\n except:\n print(\"craw failed\")\n self.output.output_html()\n\n\ndef spider_main():\n # 确定目标\n root_url = \"https://baike.baidu.com/item/Python/407313\"\n obj_spider = SpiderMain()\n obj_spider.craw(root_url)\n\n\ndef scu_main():\n check_url = \"http://zhjw.scu.edu.cn/j_spring_security_check\"\n yzm_url = 'http://zhjw.scu.edu.cn/img/captcha.jpg'\n headers = { # 请求头请求刷新验证码和发送post时需要使用\n 'Host': 'zhjw.scu.edu.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer': \"http://zhjw.scu.edu.cn/login\",\n 'Connection': 'keep-alive'\n }\n grade_headers = {\n 'Host': 'zhjw.scu.edu.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer': \"http://zhjw.scu.edu.cn/student/integratedQuery/scoreQuery/allTermScores/index\",\n 'Connection': 'keep-alive'\n }\n yzm, response = showpicture()\n data = {\n \"j_username\": \"2017141463014\",\n \"j_password\": \"121694\",\n \"j_captcha\": yzm\n }\n login_cookies = requests.utils.dict_from_cookiejar(response.cookies)\n resp = requests.post(check_url, headers=headers, cookies=login_cookies, data=data)\n # selectionBar = 125803405\n\n grade_cookies = {'selectionBar': '125803405'}\n grade_cookies.update((login_cookies))\n print(login_cookies, grade_cookies)\n grade_url = 'http://zhjw.scu.edu.cn/student/integratedQuery/scoreQuery/allTermScores/data'\n resp = requests.get(grade_url, cookies=grade_cookies, headers=headers)\n with open(\"grade.txt\",\"w\",encoding=\"utf-8\") as f:\n print(resp.text,file=f)\n\n # index_url=\"http://zhjw.scu.edu.cn/index.jsp\"\n # response=requests.get(index_url,headers=headers,cookies=requests.utils.dict_from_cookiejar(resp.cookies))\n # print(response)\n\ndef jsonto():\n f=open(\"grade.txt\",encoding='utf-8')\n grade=f.readline()\n f.close()\n print(type(grade))\n data=json.loads(grade) #转化为json对象\n grades=data['list']['records']\n for grade in grades:\n print(grade)\n\ndef showpicture():\n yzm_url = 'http://zhjw.scu.edu.cn/img/captcha.jpg'\n response = requests.get(yzm_url)\n with open(\"yzm.png\", \"wb\") as f:\n f.write(response.content)\n img = Image.open('yzm.png')\n plt.figure(\"yzm\")\n plt.imshow(img)\n plt.show()\n yzm = input(\"请输入验证码\")\n return (yzm, response)\n\n\nif __name__ == '__main__':\n jsonto()\n","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"311084530","text":"#!/usr/bin/python\n\nDEFAULT_PROFIT_COEFF = 0.8\nprofit_coeff = 0.0\nwhile profit_coeff == 0.0:\n user_input = input(\"Enter profit coeff (%): \")\n if len(user_input) == 0:\n print(\"Empty input. Use default coeff: {}%\".format(DEFAULT_PROFIT_COEFF))\n profit_coeff = DEFAULT_PROFIT_COEFF\n break\n try:\n profit_coeff = float(user_input.replace(\",\", \".\"))\n except Exception as e:\n print(\"Number expected. Try againg.\")\n \ninc_multy = 1 + profit_coeff / 100 \ndec_multy = 1 - profit_coeff / 100 \n\nwhile True:\n user_input = input(\"Enter price: \")\n deal_price = 0\n try:\n deal_price = float(user_input.replace(\",\", \".\"))\n except Exception as e:\n print(\"Float expected. Try again.\")\n continue\n print(\"100% = {}\".format(deal_price))\n print(\"{}% = {}\" .format(inc_multy * 100, deal_price * inc_multy))\n print(\"{}% = {}\" .format(dec_multy * 100, deal_price * dec_multy))\n","sub_path":"trade_helpers/profit_calcer.py","file_name":"profit_calcer.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"67320299","text":"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom argparse import ArgumentParser\n\nimport torch\nfrom pytorch_lightning import Trainer\n\nfrom nemo.collections.nlp.parts.nlp_overrides import NLPDDPPlugin, NLPSaveRestoreConnector\nfrom nemo.utils import logging, model_utils\nfrom nemo.utils.app_state import AppState\n\n\n\"\"\"\nUsage:\npython megatron_change_num_partitions.py \\\n --model_file=PATH_TO_SRC_FILE \\\n --target_file=PATH_TO_TGT_FILE \\\n --tensor_model_parallel_size=2 \\\n --target_tensor_model_parallel_size=1\n\"\"\"\n\n\ndef merge_partition(model, partitions, write_path=None):\n idx = 0\n for name, param in model.named_parameters():\n if param.shape == partitions[0][idx].shape:\n concated = partitions[0][idx].data\n elif param.shape[0] == partitions[0][idx].shape[0]:\n concated = torch.cat([partitions[i][idx].data for i in range(len(partitions))], dim=-1)\n else:\n concated = torch.cat([partitions[i][idx].data for i in range(len(partitions))], dim=0)\n if concated.shape != param.shape:\n logging.info(\n f\"Warning: Shape mismatch for parameter {name} required shape: {param.shape}, merged shape: {concated.shape}. Narrowing to match required size.\"\n )\n if concated.shape[1:] == param.shape[1:]:\n concated = torch.narrow(concated, 0, 0, param.shape[0])\n elif concated.shape[:-1] == param.shape[:-1]:\n concated = torch.narrow(concated, -1, 0, param.shape[-1])\n else:\n raise RuntimeError(\n f\"Can not handle parameter {name}, required shape: {param.shape}, merged shape: {concated.shape}.\"\n )\n param.data = concated\n idx += 1\n\n if write_path is not None:\n model.save_to(write_path)\n\n\ndef split_partition(model, partitions, tp_size, write_path=None):\n if len(partitions) != 1:\n raise ValueError(\n \"Can only split partitions of model with TP=1. For partitions of models with TP>1, merge first.\"\n )\n\n if tp_size < 1:\n raise ValueError(\"TP size must to be >= 1.\")\n\n app_state = AppState()\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n\n app_state.tensor_model_parallel_rank = tp_size - 1\n\n idx = 0\n splits = []\n for _, param in model.named_parameters():\n if param.shape == partitions[0][idx].shape:\n split = [partitions[0][idx].data] * tp_size\n elif param.shape[0] == partitions[0][idx].shape[0]:\n split = torch.split(partitions[0][idx].data, param.shape[-1], dim=-1)\n else:\n split = torch.split(partitions[0][idx].data, param.shape[0], dim=0)\n splits.append(split)\n idx += 1\n\n for i in range(tp_size - 1, -1, -1):\n app_state.tensor_model_parallel_rank = i\n\n idx = 0\n for name, param in model.named_parameters():\n split_val = splits[idx][i]\n\n if param.shape != split_val.shape:\n logging.info(\n f\"Warning: Shape mismatch for parameter {name} required shape: {param.shape}, split shape: {split_val.shape}. Padding to match required size.\"\n )\n\n if split_val.shape[1:] == param.shape[1:]:\n pad = [0, 0] * len(split_val.shape)\n pad[-1] = param.shape[0] - split_val.shape[0]\n split_val = torch.nn.functional.pad(split_val, pad, 'constant')\n elif split_val.shape[:-1] == param.shape[:-1]:\n pad = [0, param.shape[-1] - split_val.shape[-1]]\n split_val = torch.nn.functional.pad(split_val, pad, 'constant')\n else:\n raise RuntimeError(\n f\"Can not handle parameter {name}, required shape: {param.shape}, split shape: {split_val.shape}.\"\n )\n\n param.data = split_val\n idx += 1\n\n if write_path is not None:\n model.save_to(write_path)\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"--model_file\", type=str, required=True, help=\"Path to source .nemo file\")\n parser.add_argument(\"--target_file\", type=str, required=True, help=\"Path to write target .nemo file\")\n parser.add_argument(\"--tensor_model_parallel_size\", type=int, required=True, help=\"TP size of source model\")\n parser.add_argument(\"--target_tensor_model_parallel_size\", type=int, required=True, help=\"TP size of target model\")\n parser.add_argument(\n \"--model_class\",\n type=str,\n default=\"nemo.collections.nlp.models.language_modeling.megatron_gpt_model.MegatronGPTModel\",\n help=\"NeMo model class. This script should support all NeMo megatron models that use Tensor Parallel\",\n )\n parser.add_argument(\"--precision\", default=16, help=\"PyTorch Lightning Trainer precision flag\")\n\n args = parser.parse_args()\n\n precision = args.precision\n if args.precision in [\"32\", \"16\"]:\n precision = int(float(args.precision))\n tp_size = args.tensor_model_parallel_size\n tgt_tp_size = args.target_tensor_model_parallel_size\n cls = model_utils.import_class_by_path(args.model_class)\n\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n app_state = AppState()\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n\n if tp_size > 1:\n partitions = []\n for i in range(tp_size):\n app_state.tensor_model_parallel_rank = i\n model = cls.restore_from(restore_path=args.model_file, trainer=trainer, map_location=torch.device(\"cpu\"))\n params = [p for _, p in model.named_parameters()]\n partitions.append(params)\n # app_state is being updated incorrectly during restore\n app_state.data_parallel_rank = 0\n app_state.pipeline_model_parallel_size = 1 # not supported yet in this script\n app_state.tensor_model_parallel_size = tp_size\n app_state.model_parallel_size = (\n app_state.pipeline_model_parallel_size * app_state.tensor_model_parallel_size\n )\n\n model.cfg.tensor_model_parallel_size = 1\n app_state.model_parallel_size = 1\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n model = cls(model.cfg, trainer).to('cpu')\n model._save_restore_connector = NLPSaveRestoreConnector()\n\n if tgt_tp_size > 1:\n merge_partition(model, partitions)\n else:\n merge_partition(model, partitions, args.target_file)\n else:\n app_state.model_parallel_size = 1\n model = cls.restore_from(restore_path=args.model_file, trainer=trainer)\n\n if tgt_tp_size > 1:\n partitions = []\n params = [p for _, p in model.named_parameters()]\n partitions.append(params)\n\n model.cfg.tensor_model_parallel_size = tgt_tp_size\n app_state.model_parallel_size = tgt_tp_size\n trainer = Trainer(devices=1, plugins=NLPDDPPlugin(), accelerator=\"cpu\", precision=precision)\n model = cls(model.cfg, trainer).to('cpu')\n model._save_restore_connector = NLPSaveRestoreConnector()\n\n split_partition(model, partitions, tgt_tp_size, args.target_file)\n\n logging.info(\"Successfully finished changing partitions!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/nlp/language_modeling/megatron_change_num_partitions.py","file_name":"megatron_change_num_partitions.py","file_ext":"py","file_size_in_byte":8419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"68481677","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy as sp\r\nfrom numpy import random as ran\r\n\r\n\r\n'''\r\n# -*- coding: utf-8 -*-\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom itertools import product, combinations\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nax.set_aspect(\"equal\")\r\n\r\n#draw cube\r\nr = [-1, 1]\r\nfor s, e in combinations(np.array(list(product(r,r,r))), 2):\r\n if np.sum(np.abs(s-e)) == r[1]-r[0]:\r\n ax.plot3D(*zip(s,e), color=\"b\")\r\n\r\n#draw sphere\r\nu, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\r\nx=np.cos(u)*np.sin(v)\r\ny=np.sin(u)*np.sin(v)\r\nz=np.cos(v)\r\nax.plot_wireframe(x, y, z, color=\"r\")\r\n\r\n#draw a point\r\nax.scatter([0],[0],[0],color=\"g\",s=100)\r\n\r\n#draw a vector\r\nfrom matplotlib.patches import FancyArrowPatch\r\nfrom mpl_toolkits.mplot3d import proj3d\r\n\r\nclass Arrow3D(FancyArrowPatch):\r\n def __init__(self, xs, ys, zs, *args, **kwargs):\r\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\r\n self._verts3d = xs, ys, zs\r\n\r\n def draw(self, renderer):\r\n xs3d, ys3d, zs3d = self._verts3d\r\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\r\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\r\n FancyArrowPatch.draw(self, renderer)\r\n\r\na = Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\r\nax.add_artist(a)\r\nplt.show()\r\n\r\n'''\r\n\r\n\r\n#--------------------\r\n#tau_scatter\r\n#Returns the possible optical depth to the next scattering depth\r\n#INPUT: none\r\n#Returns: tau_s\r\ndef tau_scatter():\r\n p = ran.uniform(0,1)\r\n tau_s = -np.log(p)\r\n return tau_s\r\n\r\n#-------------------\r\n#phi-to-xy\r\n#Returns xy coordinates based on given angle\r\n#NOTE: add to prev xyz value to get new position\r\n#INPUT:\r\n# distance: path length xi of the ray\r\n# phi: the angle at whish the ray is cast\r\n#Returns:\r\n# x,y: xy values corresponding to the change in position\r\ndef sphtocart(dist,phi,theta):\r\n\r\n x = dist*np.sin(phi)*np.cos(theta)\r\n y = dist*np.sin(phi)*np.sin(theta)\r\n z = dist*np.cos(phi)\r\n return x,y,z\r\n\r\n#----------------\r\n#rantheta\r\n#Return a randomly calculated theta value from equ A5\r\n#INPUT:\r\n# g: set initially, the asymmetry\r\n#OUTPUT:\r\n# theta: The random theta value\r\ndef rantheta(g):\r\n p = ran.uniform(0,1)\r\n term1 = 1.+g**2\r\n term2 = 1.-g**2\r\n term3 = 1. - g + 2*g*p\r\n\r\n theta = (term1 - (term2/term3)**2)/(2.*g)\r\n\r\n return theta\r\n\r\n\r\n#------------------\r\n#ranphi\r\n#Return a randomly selected phi value\r\n#INPUT: None\r\n#Output:\r\n# phi\r\ndef ranphi():\r\n p = ran.uniform(0,1)\r\n phi = 2.*np.pi*p\r\n\r\n return phi\r\n\r\n\r\n\r\n\r\n#--------------\r\n#ifexit\r\n#Returns a boolean indicating if you've left the sphere of caring\r\n#May change to vector inputs later\r\n#INPUT:\r\n# initial coordinates and max R\r\n#OUTPUT:\r\n# boolean indicating if at or beyond max radius\r\ndef ifexit(x0,y0,z0,x,y,z,R):\r\n return np.sqrt((x-x0)**2 + (y-y0)**2 + (z-z0)**2) >= R\r\n\r\n\r\n\r\n\r\n#---------------\r\n\r\n\r\n\r\n\r\n'''\r\nPlotting functions\r\n'''\r\n#---------------------\r\n#drawArrow\r\n# Draws an arrow representing the path and direction between 2 points\r\n#input A,B, axis\r\n# A,B: 2 points with the form [x,y] coordinates\r\n# axis: the axis that you want to draw said arrow on\r\n#returns: none\r\ndef drawArrow(A, B, axis):\r\n axis.arrow(A[0], A[1], B[0] - A[0], B[1] - A[1],\r\n head_width=0.02, length_includes_head=True)\r\n return\r\n\r\n#---------------------\r\n#drawAllArrows\r\n#Draws all the arrows of the path\r\n#input: X,Y,axis\r\n# X,Y: 1-D Arrays of same size, containing series of x,y coordinates with matching indices\r\n# axis: axis you want these drawn on\r\n#returns: none\r\ndef drawAllArrows(X,Y,axis):\r\n for i in xrange(len(X)-1):\r\n A = np.array([X[i],Y[i]])\r\n B = np.array([X[i+1],Y[i+1]])\r\n drawArrow(A,B,axis)\r\n return\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nPseudocode steps\r\n1) Get initial point position and cloud info\r\n2) generate tau of ray\r\n3) Sample xi (path length) from tau\r\n4) Calculate new angle of scatter\r\n5) calculate new position and advance the ray\r\n6) repeat 2-5 until ray reaches cloud boundary ( num trajectories=N)\r\n7) repeat 2-6 for M rays\r\n8) Calculate mean relative intensity at A(initial point)\r\n\r\nA : Observor placement point (const)\r\nkhat: Direction of ray - uniformly distributed over 4pi sr\r\nN: Number of directions\r\nM: Number of samplings of each direction\r\n\r\nmay need to plot only flattened data (xy only)\r\nfor impressiveness, plot in 3d\r\n\r\n\r\nHow to:\r\nwalk a ray\r\nreject if tau isn't close to wanted tau\r\nrepeat until until it reaches the edge of the sphere\r\nsum up all tau values along the rays\r\nrepeat for N/M rays\r\nSum up and average all intensities\r\n?\r\n'''\r\n\r\n#-------------\r\n#init\r\n#Initializes all initial values\r\n#returns:\r\n# A : Point of observer\r\n# M : Samplings/direction\r\n# N : Number of directions\r\n# I0: Initial intensity of ray\r\n# R : Radius of circle from origin from A\r\n# w : Albedo of the gas, mathis\r\n# g : asymmetry parameter, mathis\r\n# nH: number density of the medium, mathis, UNKNOWN\r\n#\r\ndef init():\r\n Ax = 0.0\r\n Ay = 0.0\r\n Az = 0.0\r\n A = np.array([Ax,Ay,Az])\r\n M = 10\r\n N = 90\r\n I0 = 5.0E6\r\n R = 2.\r\n w = 0.8\r\n g = 0.8\r\n nH = 10**2.5\r\n sigma = .3326E-24 # cm\r\n\r\n\r\n return A,M,N,I0,R,w,g,nH,sigma\r\n\r\ndef main():\r\n\r\n A,M,N,I0,R,w,g,nH,sigma = init()\r\n ran.seed(0000)\r\n\r\n #Generate testing points\r\n X = np.zeros(20)\r\n Y = np.zeros(20)\r\n Z = np.zeros(20)\r\n for i in xrange(20): # note: should start at point 0,0,0/origin\r\n theta = rantheta(g)\r\n phi = ranphi()\r\n X[i],Y[i],Z[i] = sphtocart(2,phi,theta)\r\n #Plotting the final points\r\n fig1 = plt.figure(1)\r\n ax1 = fig1.add_subplot(111)\r\n\r\n circle = plt.Circle(A, R, color='r', fill=False)\r\n ax1.add_artist(circle)\r\n\r\n ax1.scatter(X[0],Y[0],s=80,c='b',marker='*') #Colors\r\n ax1.plot(X[1:],Y[1:],'r.')\r\n drawAllArrows(X,Y,ax1)\r\n\r\n plt.show()\r\n\r\n\r\nmain()\r\n","sub_path":"radtrans.py","file_name":"radtrans.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"174855344","text":"from unittest import TestCase\nfrom unittest.mock import patch\n\nfrom opwen_email_server.backend import client_datastore\n\n\nclass UnpackEmailsTests(TestCase):\n @patch.object(client_datastore, 'STORAGE')\n def test_retrieves_compressed_emails(self, storage_mock):\n resource_id = 'c08ddf62-b27c-4de1-ab6f-474d75dc0bfd'\n self.given_objects(storage_mock, (\n {'to': ['foo@test.com']},\n {'to': ['bar@test.com']},\n ))\n\n emails = list(client_datastore.unpack_emails(resource_id))\n\n self.assertEqual(storage_mock.fetch_objects.call_count, 1)\n self.assertListEqual(emails, [{'to': ['foo@test.com']},\n {'to': ['bar@test.com']}])\n\n @classmethod\n def given_objects(cls, storage_mock, objs):\n storage_mock.fetch_objects.return_value = objs\n","sub_path":"tests/opwen_email_server/backend/test_client_datastore.py","file_name":"test_client_datastore.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"646156936","text":"######################################################################################################################\r\n# Script to extract random fragments of coding regions.\r\n##########\r\n# Input:\r\n# 1. seqSize: Size of the extracted sequences. Eg. 80.\r\n# 2. quantSeq: How many sequences to extract. Eg. 836.\r\n# 3. inputFileName: A fasta file containing the coding regions.\r\n# 4. outputLocation: Location in which outputs will be writen.\r\n##########\r\n# Output:\r\n# 1. cod2.csv: The csv file containing the extracted sequences.\r\n#####################################################################################################################\r\n\r\nimport sys\r\nimport random\r\n\r\n# Reading input\r\nseqSize = int(sys.argv[1])\r\nquantSeq = int(sys.argv[2])\r\ninputFileName = sys.argv[3]\r\noutputLocation = sys.argv[4]\r\nif(outputLocation[-1] != \"/\"): outputLocation += \"/\"\r\n\r\n# File handling\r\ninputFile = open(inputFileName,\"r\")\r\noutputFile = open(outputLocation+\"cod2.csv\",\"w\")\r\n\r\n# Extracting coding regions\r\ncodingList = []\r\ncodingSeq = \"\"\r\nflagFirst = True\r\nfor line in inputFile:\r\n if(len(line) < 2): continue\r\n if(line[0] == \">\"):\r\n if(flagFirst):\r\n flagFirst = False\r\n continue\r\n codingList.append(codingSeq)\r\n codingSeq = \"\"\r\n else: codingSeq += line.strip()\r\ncodingList.append(codingSeq)\r\n\r\n# Writing coding sequences\r\nseqCount = 0\r\nwhile(seqCount < quantSeq):\r\n rSeq = random.randint(0,len(codingList)-1)\r\n seq = codingList[rSeq]\r\n if(len(seq) < seqSize): continue\r\n rPos = random.randint(0,len(seq)-seqSize)\r\n seq = (seq[rPos:rPos+seqSize]).lower()\r\n outputFile.write(seq[0])\r\n for e in seq[1:]: outputFile.write(\",\"+e)\r\n outputFile.write(\"\\n\")\r\n seqCount += 1\r\n\r\n# Termination\r\ninputFile.close()\r\noutputFile.close()\r\n\r\n","sub_path":"Code/DataFormat/extractNegativeCoding2.py","file_name":"extractNegativeCoding2.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"50365251","text":"from numpy import exp, array\n\ndef out_flow(f):\n n = f.shape[0]\n a = []\n for i in range(n):\n s = 0.0\n for j in range(n):\n if i != j:\n s+= f[i, j]\n a.append(s)\n r = array(a) / (n - 1)\n return r\n\n\ndef in_flow(f):\n n = f.shape[0]\n a = []\n for i in range(n):\n s = 0.0\n for j in range(n):\n if i != j:\n s+= f[j, i]\n a.append(s)\n r = array(a) / (n - 1)\n return r\n \n\ndef usual_shape(q, p, _, f):\n return int(f > 0)\n\n\ndef level_shape(q, p, _, f):\n if f < 0: return 0\n if f < q:\n return 0.0\n if f > p:\n return 1.0\n return 0.5\n\n\ndef linear_shape(q, p, _, f):\n \"\"\"\n if f < 0: return 0\n if f > p:\n return 1.0\n if f < q:\n return 0.0\n r = (f - q) / (p - q)\n assert(r >= 0 and r <= 1)\n \"\"\"\n r = min(f - q, p - q) / (p - q) * int(f > q)\n assert(r >= 0 and r <= 1)\n return r\n\n\ndef u_shape(q, p, _, f):\n if f < 0: return 0\n if f < p:\n return 0.0\n return 1.0\n\n\ndef v_shape(q, p, _, f):\n if f < 0: return 0\n if f <= p:\n r = f / p\n assert(r >= 0 and r <= 1)\n return r\n else:\n return 1.0\n\n\ndef gaussian(q, p, s, f):\n if f < 0: return 0\n return 1 - exp(-(f**2) / (2*(s**2)))\n\n","sub_path":"smpr/multicriteriality.py","file_name":"multicriteriality.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"616022254","text":"#!/usr/bin/python\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn import preprocessing\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport sys, getopt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndef main(argv):\r\n inputfile = ''\r\n outputfile = ''\r\n if(len(argv)==0):\r\n print ('preprocess.py -i -o ')\r\n sys.exit(2)\r\n try:\r\n opts, args = getopt.getopt(argv,\"hi:o:\",[\"ifile=\",\"ofile=\"])\r\n except getopt.GetoptError:\r\n print ('preprocess.py -i -o ')\r\n sys.exit(2)\r\n for opt, arg in opts:\r\n if opt == '-h':\r\n print ('preprocess.py -i -o ')\r\n sys.exit()\r\n elif opt in (\"-i\", \"--ifile\"):\r\n inputfile = arg\r\n elif opt in (\"-o\", \"--ofile\"):\r\n outputfile = arg\r\n print ('Input file is \"', inputfile)\r\n print ('Output file is \"', outputfile)\r\n\r\n dataset = pd.read_csv(inputfile, header=None)\r\n le = preprocessing.LabelEncoder()\r\n\r\n dataset = dataset.apply(le.fit_transform)\r\n array = dataset.values\r\n\r\n X = array[:, 0:dataset.shape[1] - 1]\r\n Y = array[:, dataset.shape[1] - 1]\r\n\r\n scaler = MinMaxScaler(feature_range=(0, 1))\r\n rescaledY = scaler.fit_transform(Y)\r\n\r\n scaler = StandardScaler().fit(X)\r\n rescaledX = scaler.transform(X)\r\n\r\n output = pd.DataFrame(rescaledX)\r\n output['output'] = rescaledY.tolist()\r\n output.to_csv(outputfile, index=False, header=False)\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv[1:])","sub_path":"Programming Assignment - Variation of Most Appropriate Yard/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"471534291","text":"import random\nfrom plugin_system import Plugin\n\nanswers = ['🌚', '🌚🌚']\n\nplugin = Plugin('Луна')\n\n\n@plugin.on_command('луна', '🌚')\nasync def get_moon(msg, args):\n await msg.answer(random.choice(answers))\n","sub_path":"plugins/moon.py","file_name":"moon.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"405700253","text":"properties = (\"Название\", \"Цена\", \"Количество\", \"Ед.\")\nuser_answer, goods, a, analyse, num_counter = '', [], {}, {}, 1\nwhile True:\n if user_answer == \"n\":\n break\n for b in properties:\n a[b] = input(f'Ввеедите позицию товара {b} :')\n goods.append((num_counter, a))\n num_counter += 1\n user_answer = input(\"Хотите ли ввести еще один вид товаров? Y/N: \")\nprint(f'Текушие позиции товаров выглядят следующим образом:\\n')\nprint(goods)\n\nfor b in goods:\n for k, v in b[1].items():\n analyse.setdefault(k, []).append(v)\n\nprint(f'Позиции товаров по характеристикам:\\n')\nprint(analyse)\n","sub_path":"lesson_2/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"246917001","text":"import json\nimport socketserver\nimport os\n\nfrom FTP.server.conf import settings\nfrom FTP.server.core import views\n\n\nclass MyFTPServer(socketserver.BaseRequestHandler):\n\n\tlogined_lst = {}\n\n\tdef handle(self):\n\t\tprint('-' * 20)\n\t\tglobal pickle_path, ret\n\t\tmsg = self.my_recv() # 调用派生方法\n\t\tprint('已经登录的用户logined_lst') # 记录已经登录的用户\n\t\tprint(MyFTPServer.logined_lst)\n\t\t# 消息的转发 把任务转发给views文件中的对应的方法\n\t\t# 反射\n\t\top_str = msg['operation'] # 获取操作 auth_client\n\t\tif msg['operation'] == 'login' or msg['operation'] == 'register':\n\t\t\tif hasattr(views, op_str):\n\t\t\t\tfunc = getattr(views, op_str)\n\t\t\t\tret = func(msg)\n\t\t\tif ret:\n\t\t\t\t# 用户的pickle信息所在的文件地址 views\n\t\t\t\tMyFTPServer.logined_lst[self.client_address] = os.path.join(settings.pickle_path, msg['username'])\n\t\t\t\tself.my_send(ret)\n\t\telif hasattr(views, op_str) and self.client_address in MyFTPServer.logined_lst:\n\t\t\tfunc = getattr(views, op_str)\n\t\t\tret = func(msg, self.request)\n\t\t\tself.my_send(ret)\n\t\telse:\n\t\t\tself.my_send(False)\n\n\t# {'username','password','operation'}\n\t# msg\n\t# 登录 注册\n\t# 查看目录\n\n\t# 上传文件\n\t# 反射\n\t# 'login'\n\tdef my_recv(self): # 派生方法\n\t\tmsg = self.request.recv(1024)\n\t\tmsg = msg.decode(settings.code)\n\t\t# print('my_recv:\\n'+msg, type(msg))\n\t\tmsg = json.loads(msg)\n\t\treturn msg\n\n\tdef my_send(self, msg):\n\t\tmsg = json.dumps(msg).encode(settings.code)\n\t\tself.request.send(msg)\n","sub_path":"FTP/server/core/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"549705214","text":"import os\n\nimport pytest\n\nfrom robocorp_ls_core.protocols import IConfigProvider\nfrom robocorp_ls_core.robotframework_log import get_logger\nfrom robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture\nfrom robocorp_code.protocols import IRcc\n\n\nlog = get_logger(__name__)\n\n\n@pytest.fixture\ndef language_server_client_class():\n from robocorp_code_tests.robocode_language_server_client import (\n RobocorpLanguageServerClient,\n )\n\n return RobocorpLanguageServerClient\n\n\n@pytest.fixture\ndef language_server_class():\n from robocorp_code.robocorp_language_server import RobocorpLanguageServer\n\n return RobocorpLanguageServer\n\n\n@pytest.fixture\ndef main_module():\n from robocorp_code import __main__\n\n return __main__\n\n\n@pytest.fixture\ndef rcc_location() -> str:\n from robocorp_code.rcc import download_rcc\n from robocorp_code.rcc import get_default_rcc_location\n\n location = get_default_rcc_location()\n download_rcc(location, force=False)\n return location\n\n\n@pytest.fixture\ndef ci_endpoint() -> str:\n ci_endpoint = os.environ.get(\"CI_ENDPOINT\")\n if ci_endpoint is None:\n raise AssertionError(\"CI_ENDPOINT env variable must be specified for tests.\")\n return ci_endpoint\n\n\n@pytest.fixture\ndef ci_credentials() -> str:\n ci_credentials = os.environ.get(\"CI_CREDENTIALS\")\n if ci_credentials is None:\n raise AssertionError(\"ci_credentials env variable must be specified for tests.\")\n return ci_credentials\n\n\n@pytest.fixture\ndef rcc_config_location(tmpdir) -> str:\n config_dir = tmpdir.join(\"config\")\n os.makedirs(str(config_dir))\n return str(config_dir.join(\"config_test.yaml\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef cases(tmpdir_factory) -> CasesFixture:\n basename = \"res áéíóú\"\n copy_to = str(tmpdir_factory.mktemp(basename))\n\n f = __file__\n original_resources_dir = os.path.join(os.path.dirname(f), \"_resources\")\n assert os.path.exists(original_resources_dir)\n\n return CasesFixture(copy_to, original_resources_dir)\n\n\n@pytest.fixture\ndef config_provider(\n ws_root_path: str, rcc_location: str, ci_endpoint: str, rcc_config_location: str\n):\n from robocorp_code.robocorp_config import RobocorpConfig\n from robotframework_ls.ep_providers import DefaultConfigurationProvider\n\n config = RobocorpConfig()\n\n config.update(\n {\n \"robocorp\": {\n \"rcc\": {\n \"location\": rcc_location,\n \"endpoint\": ci_endpoint,\n \"config_location\": rcc_config_location,\n }\n }\n }\n )\n return DefaultConfigurationProvider(config)\n\n\n@pytest.fixture\ndef rcc(config_provider: IConfigProvider, rcc_config_location: str) -> IRcc:\n from robocorp_code.rcc import Rcc\n\n rcc = Rcc(config_provider)\n # We don't want to track tests.\n for _i in range(2):\n # There's a bug in which the --do-not-track doesn't work the first time.\n result = rcc._run_rcc(\n \"feedback identity --do-not-track --config\".split() + [rcc_config_location],\n expect_ok=False,\n )\n assert result.success\n result_msg = result.result\n assert result_msg\n if \"enabled\" in result_msg:\n continue\n if \"disabled\" in result_msg:\n break\n raise AssertionError(f\"Did not expect {result_msg}\")\n else:\n raise AssertionError(f\"Did not expect {result_msg}\")\n\n return rcc\n\n\n@pytest.fixture\ndef rcc_conda_installed(rcc: IRcc):\n result = rcc.check_conda_installed()\n assert result.success, r\"Error: {result}\"\n","sub_path":"robocorp-code/tests/robocorp_code_tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"306832342","text":"import MySQLdb\nimport smtplib, ssl\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom home.mysql import mysqldb\n\ndef mail_seder(receiver_email, user, event, date, place, flag):\n sender_email = \"treeasurenss@gmail.com\"\n password = 'treeasure@nss123'\n message = MIMEMultipart(\"alternative\")\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n # Create the plain-text and HTML version of your message\n if flag == 1:\n message[\"Subject\"] = \"Nature is calling you........\"\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n We have a new event organized on \"\"\" + date + \"\"\".\n The name of the event is \"\"\" + event + \"\"\" organized at location \"\"\" + place + \"\"\".\n Do visit our website to participate.\n \"\"\"\n html = \"\"\"\\\n \n \n Hello \"\"\" + user + \"\"\",
\n We have a new event organized on \"\"\" + date + \"\"\".\n The name of the event is \"\"\" + event + \"\"\" organized at location \"\"\" + place + \"\"\".\n Do visit our website to participate.\n
\n \n \n \"\"\"\n elif flag==0:\n message[\"Subject\"] = \"Nature is calling you........\"\n mydb = mysqldb()\n mycursor = mydb.cursor()\n query = 'select info from schedule_tt where event_name=\"'+event+'\"'\n mycursor.execute(query)\n result = mycursor.fetchall()\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n You are sucessfully registered to the event \"\"\" + event + \"\"\"\n Details\n Date: \"\"\" + date + \"\"\"\n Place: \"\"\" + place + \"\"\"\n Information: \"\"\" + result[0][0] +\"\"\"\n Do visit our website to participate.\n \"\"\"\n html = \"\"\"\\\n \n \n Hello \"\"\" + user + \"\"\",
\n You are sucessfully registered to the event \"\"\" + event + \"\"\"
\n Details
\n Date: \"\"\" + date + \"\"\"
\n Place: \"\"\" + place + \"\"\"
\n Information: \"\"\" + result[0][0] +\"\"\"
\n Do visit our website to participate.\n
\n \n \n \"\"\"\n elif flag == 3:\n message[\"Subject\"] = \"We are disappointed\"\n text = \"\"\"\\\n Hello \"\"\" + user + \"\"\"\n You have been reported.\n \"\"\"\n html = \"\"\"\\\n \n \n Hello \"\"\" + user + \"\"\",
\n You have been reported\n
\n \n \n \"\"\"\n\n # Turn these into plain/html MIMEText objects\n part1 = MIMEText(text, \"plain\")\n part2 = MIMEText(html, \"html\")\n\n # Add HTML/plain-text parts to MIMEMultipart message\n # The email client will try to render the last part first\n message.attach(part1)\n message.attach(part2)\n\n # Create secure connection with server and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(\n sender_email, receiver_email, message.as_string()\n )\n\n\ndef send_email(username, event, date, place, flag):\n mydb = mysqldb()\n mycursor = mydb.cursor()\n print(username)\n if flag == 0:\n query = 'select email, username from auth_user where username=\"'+username+'\"'\n else:\n query = 'select email, username from auth_user where not username=\"'+username+'\"'\n mycursor.execute(query)\n result = mycursor.fetchall()\n for i in result:\n print(i[0], i[1])\n mail_seder(i[0], i[1], event, date, place, flag)","sub_path":"maps/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"68818709","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport copy\nimport cmath\nfrom user_manage.models import CollectRaw\n\n\ndef polar_to_cartesian(angle_values, rs):\n \"\"\"将极坐标转换为直角坐标\n :param angle_values: 原始角度值\n :param rs: 原始距离值\n :return: xs, ys 转换之后的直角坐标系的x,y坐标\n \"\"\"\n xs, ys = [], []\n for angle_value, r in zip(angle_values, rs):\n cn = cmath.rect(r, np.radians(angle_value))\n # print(cn.real, cn.imag)\n xs.append(round(cn.real, 3))\n ys.append(round(cn.imag, 3))\n\n return xs, ys\n\ndef cartesian_to_polar(xs, ys):\n # 将直角坐标转换为极坐标\n thetas = []\n rs = []\n\n for x, y in zip(xs, ys):\n cp = complex(x, y)\n result = cmath.polar(cp) # 返回长度和弧度\n dgs = math.degrees(result[1])\n if dgs < 0:\n dgs += 360\n thetas.append(dgs)\n rs.append(result[0])\n return thetas, rs\n\n\n\ndef find_symmetry_axis(angle_values, range_values, pt1, pt2, pt3, pt4, type=0):\n \"\"\"\n\n @param angle_values:\n @param range_values:\n @param area1_x_range:\n @param area1_y_range:\n @param area2_x_range:\n @param area2_y_range:\n @return:\n \"\"\"\n assert angle_values, '轮廓数据为空'\n assert pt1, '数据为空'\n assert pt2, '数据为空'\n assert pt3, '数据为空'\n assert pt4, '数据为空'\n\n area1_x_range = [min(pt1[0], pt2[0]), max(pt1[0], pt2[0])]\n area1_y_range = [min(pt1[1], pt2[1]), max(pt1[1], pt2[1])]\n\n area2_x_range = [min(pt3[0], pt4[0]), max(pt3[0], pt4[0])]\n area2_y_range = [min(pt3[1], pt4[1]), max(pt3[1], pt4[1])]\n # TODO:使用极坐标系选择 对称区域,根据以前实验数据观察,使用此方案效果较差\n xs, ys = polar_to_cartesian(angle_values, range_values)\n\n # TODO:使用直角坐标系选择 对称区域\n area1_xs = []\n area1_ys = []\n area2_xs = []\n area2_ys = []\n for x, y in zip(xs, ys):\n if area1_x_range[0] < x < area1_x_range[1] and area1_y_range[0] < y < area1_y_range[1]:\n area1_xs.append(x)\n area1_ys.append(y)\n elif area2_x_range[0] < x < area2_x_range[1] and area2_y_range[0] < y < area2_y_range[1]:\n area2_xs.append(x)\n area2_ys.append(y)\n else:\n pass\n\n assert area1_xs, '选取对称区域内没有获取到测量数据'\n assert area2_xs, '选取对称区域内没有获取到测量数据'\n\n r_line = np.polyfit(area1_xs, area1_ys, 1)\n l_line = np.polyfit(area2_xs, area2_ys, 1)\n line_k = (r_line[0] + l_line[0]) / 2 # 因为两条线平行,故取任意一条线的斜率, 取和除以2是泛化数据,若两条线不平行,则不行\n c = (l_line[1] + r_line[1]) / 2\n if type == 0:\n # 原始用的对称轴\n symmetry_axis = [line_k, c]\n return symmetry_axis\n else:\n # 对称轴散点坐标\n lst_x, lst_y, ret_coord = [], [], []\n x_max = max(xs)\n x_min = min(xs)\n diff = float((x_max - x_min) / 100)\n for i in range(100):\n lst_x.append(x_min + i * diff)\n for a_x in lst_x:\n # 计算公式\n a_y = line_k * a_x + c\n lst_y.append(a_y)\n for x, y in zip(lst_x, lst_y):\n ret_coord.append([x, y])\n return ret_coord\n\n\ndef symmetry_axis_convert(angle_values, range_values, symmetry_axis, top_point):\n \"\"\"\n Cobb =int(math.fabs(np.arctan((k1-k2)/(float(1 + k1*k2)))*180/np.pi)+0.5)\n 一般的坐标转换公式.\n 设Oxy,O'x'y'是两个坐标系,O,O'分别是原点,且O'在Oxy中的坐标为(x0,y0),由x轴到x'轴的角度为t,坐标转换公式是\n x=x'cost-y'sint+x0, y=x'sint+y'cost+y0.\n\n @todo:x' = cost(x-x0) + y - y0; y' = math.pow(cost, 2)(x-x0) + cost(y-y0) - x + x0\n\n @param angle_values:\n @param range_values:\n @param symmetry_axis:\n @param top_point:\n @return:\n \"\"\"\n assert angle_values, '轮廓数据为空'\n assert symmetry_axis, '无对称轴'\n assert top_point, '没有顶点数据'\n\n # TODO:获取对称轴两侧指定宽度的测量区域\n xs, ys = polar_to_cartesian(angle_values, range_values)\n # 设Oxy,O'x'y'是两个坐标系,O,O'分别是原点,TODO:且O'在Oxy中的坐标为(x0,y0), 由x轴到x'轴的角度为t\n # 计算原来坐标系原点,在新的坐标系中的坐标\n # alpha = math.atan(top_point[1] / top_point[0])\n # theta = math.atan(symmetry_axis[0]) # TODO: 当theta>math.pi/2 时,是否成立还需要验证?\n # k1 = top_point[1] / top_point[0]\n # k2 = symmetry_axis[0]\n # fi = math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))))\n # cob = math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))) * 180 / np.pi) + 0.5\n # Cobb = int(math.fabs(np.arctan((k1 - k2) / (float(1 + k1 * k2))) * 180 / np.pi) + 0.5)\n\n # fi = math.pi / 2 - alpha + theta\n # fi = math.pi / 2 + alpha - theta\n theta = -math.atan(symmetry_axis[0])\n # chamfer = math.sqrt(top_point[0] ** 2 + top_point[1] ** 2)\n tx0 = -(top_point[0] * math.cos(theta) - top_point[1] * math.sin(theta))\n # tx0 = -chamfer * math.sin(fi)\n ty0 = -(top_point[0] * math.sin(theta) + top_point[1] * math.cos(theta))\n\n # if top_point[0] >= 0:\n # tx0 = -tx0\n # if top_point[1] >= 0:\n # ty0 = -ty0\n\n # TODO:可以使用坐标系转换办法,降低计算量, x=x'cost-y'sint+x0, y=x'sint+y'cost+y0.\n # TODO: 因不正常数据会赋值为0点,导致坐标系转换后出现较多的无用点!!!,在转换前将所有的0点去掉\n # 坐标系转换避免大量计算及很多斜率不存在时的分支判断\n\n conversion_xs = []\n conversion_ys = []\n for x, y in zip(xs, ys):\n if x == 0 and y == 0: # 去掉多余的零点\n continue\n # tx = -tx0 + x * math.cos(theta) - y * math.sin(theta)\n tx = tx0 + x * math.cos(theta) - y * math.sin(theta)\n\n # ty = -ty0 + x * math.sin(theta) + y * math.cos(theta)\n ty = ty0 + x * math.sin(theta) + y * math.cos(theta)\n\n conversion_xs.append(tx)\n conversion_ys.append(ty)\n\n return tx0, ty0, conversion_xs, conversion_ys\n\n\ndef get_measurement_loc(sedimentation_measuring_position, level_wid_measuring_position, device_location, tx0, ty0, t_xs, t_ys):\n \"\"\"\n sedimentation_measuring_position: 测量沉降位置\n level_wid_measuring_position:测量收敛位置\n device_location: 设备位置\n \"\"\"\n # TODO: 需要判断 设备在坐标系x轴的哪一侧(即中轴线的哪一侧), 后台从数据库中获取数据给我\n\n sedimentation_locs = [] # TODO:1.判断测量的具体位置,使用坐标数据如何表示\n if len(sedimentation_measuring_position) > 0:\n device_coordinate = [tx0, ty0]\n for sedimentation in sedimentation_measuring_position:\n if sedimentation[0] == '中': # 判断device_location 在中轴线的哪一侧\n # measuring_line = 0\n sedimentation_locs.append(0) # x轴\n\n elif device_location == '中': # ���般来说这种情况是不会发生的,设备的位置不方便维护, 若存在这种情况左右判断失效\n pass\n\n elif sedimentation[0] != '中' and device_location != '中': # 反向一侧\n if device_location == sedimentation[0]:\n if device_coordinate[0] < 0:\n sedimentation_locs.append(-sedimentation[1])\n else:\n sedimentation_locs.append(sedimentation[1])\n else: # 取反\n if device_coordinate[0] > 0:\n sedimentation_locs.append(-sedimentation[1])\n else:\n sedimentation_locs.append(sedimentation[1])\n\n level_locs = []\n if len(level_wid_measuring_position) > 0:\n # TODO: 获取拱顶往下x mm处收敛\n x_count = 0\n for x in t_xs:\n if x > 0:\n x_count += 1\n if x_count > len(t_xs) / 2:\n x_flag = 1\n else:\n x_flag = -1\n\n for lev_area in level_wid_measuring_position:\n if x_flag > 0:\n level_locs.append(lev_area)\n else:\n level_locs.append(-lev_area)\n\n return sedimentation_locs, level_locs\n\ndef calc_measure_range(sedimentation_areas, level_areas, t_xs, t_ys, area_width, symmetry_axis, top_point):\n \"\"\"计算测量的区段的角度范围\"\"\"\n sed_measure_areas = []\n\n # TODO:求出区段,坐标系变换为原来的坐标系,然后求出角度范围\n wd = area_width / 2 # TODO:若扫描间隔过大,可能导致选择的需要内没有数据点,所以不能用初始的粗扫数据来做计算,粗扫数据知道对称轴完\n for sed_area in sedimentation_areas:\n line_xs, line_ys = [], []\n for tx, ty in zip(t_xs, t_ys):\n if sed_area - wd <= ty <= sed_area + wd:\n line_xs.append(tx)\n line_ys.append(ty)\n\n assert len(line_xs) > 2, '设置的沉降区域内没有测量数据'\n # 区域两端的两条线段, 直接使用x的值应该是能判断的\n line1_xs, line1_ys = [], []\n line2_xs, line2_ys = [], []\n\n last_lx = line_xs[0]\n for lx, ly in zip(line_xs, line_ys): # 其中的一种方法\n if abs(lx - last_lx) < 1000: # 1000 为阈值,同一侧的点差值应该不会比这个阈值大,差值过大的说明不是同一侧的点\n line1_xs.append(lx)\n line1_ys.append(ly)\n else: # 另一侧的点\n line2_xs.append(lx)\n line2_ys.append(ly)\n if abs(line1_xs[0]) > abs(line2_xs[0]):\n line1_xs = line2_xs\n line1_ys = line2_ys\n # logger.debug('区段内点的坐标值 x值:{}, y值:{}', line1_xs, line1_ys)\n # logger.debug('区段内点的坐标值 x值:{}, y值:{}', line2_xs, line2_ys)\n line1 = np.polyfit(line1_xs, line1_ys, 1)\n # line2 = np.polyfit(line2_xs, line2_ys, 1)\n # logger.debug('区段内点拟合的曲线 斜率:{}, 截距:{}', line1[0], line1[1])\n # logger.debug('区段内点拟合的曲线 斜率:{}, 截距:{}', line2[0], line2[1])\n # TODO: 求交点,根据交点反算出范围\n y1 = sed_area - wd\n y2 = sed_area + wd\n cross_11_p_x = (y1 - line1[1]) / line1[0]\n cross_12_p_x = (y2 - line1[1]) / line1[0]\n\n # cross_21_p_x = (y2 - line2[1]) / line2[0]\n # cross_22_p_x = (y1 - line2[1]) / line2[0]\n\n # pt1 = [cross_11_p_x, y1]\n # pt2 = [cross_12_p_x, y2]\n #\n # pt3 = [cross_21_p_x, y1]\n # pt4 = [cross_22_p_x, y2]\n\n # cross_xs = [cross_11_p_x, cross_12_p_x, cross_21_p_x, cross_22_p_x]\n cross_xs = [cross_11_p_x, cross_12_p_x]\n cross_ys = [y1, y2]\n\n theta = math.atan(symmetry_axis[0])\n org_xs = []\n org_ys = []\n for x, y in zip(cross_xs, cross_ys):\n org_x = top_point[0] + x * math.cos(theta) - y * math.sin(theta)\n org_y = top_point[1] + x * math.sin(theta) + y * math.cos(theta)\n org_xs.append(org_x)\n org_ys.append(org_y)\n\n bcc_org_ags, bcc_org_rgs = cartesian_to_polar(org_xs, org_ys) # thetas 是角度值, 只完成了一个区间的,\n # TODO: 需要做区间排序\n if bcc_org_ags[0] > bcc_org_ags[1]:\n bcc_org_ags[0], bcc_org_ags[1] = bcc_org_ags[1], bcc_org_ags[0]\n\n # if bcc_org_ags[2] > bcc_org_ags[3]:\n # bcc_org_ags[2], bcc_org_ags[3] = bcc_org_ags[3], bcc_org_ags[2]\n\n measure_area = [[bcc_org_ags[0], bcc_org_ags[1]]]\n sed_measure_areas.append(measure_area)\n\n lev_measure_areas = []\n for lv_area in level_areas:\n line_xs, line_ys = [], []\n for tx, ty in zip(t_xs, t_ys):\n if lv_area - wd <= tx <= lv_area + wd:\n line_xs.append(tx)\n line_ys.append(ty)\n\n assert len(line_xs) > 2, '设置的收敛区域内没有测量数据'\n # TODO:区域两端的两条线段, 直接使用x的值应该是能判断的\n line1_xs, line1_ys = [], []\n line2_xs, line2_ys = [], []\n\n last_ly = line_ys[0]\n for lx, ly in zip(line_xs, line_ys): # 其中的一种方法\n if abs(ly - last_ly) < 1000: # 1000 为阈值,同一侧的点差值应该不会比这个阈值大,差值过大的说明不是同一侧的点\n line1_xs.append(lx)\n line1_ys.append(ly)\n else: # 另一侧的点\n line2_xs.append(lx)\n line2_ys.append(ly)\n\n print('区段内点的坐标值 x值:{}, y值:{}', line1_xs, line1_ys)\n print('区段内点的坐标值 x值:{}, y值:{}', line2_xs, line2_ys)\n line1 = np.polyfit(line1_xs, line1_ys, 1)\n line2 = np.polyfit(line2_xs, line2_ys, 1)\n print('区段内点拟合的曲线 斜率:{}, 截距:{}', line1[0], line1[1])\n print('区段内点拟合的曲线 斜率:{}, 截距:{}', line2[0], line2[1])\n # TODO: 求交点,根据交点反算出范围\n\n x1 = lv_area - wd\n x2 = lv_area + wd\n\n cross_11_p_y = line1[0] * x1 + line1[1]\n cross_12_p_y = line1[0] * x2 + line1[1]\n\n cross_21_p_y = line2[0] * x2 + line2[1]\n cross_22_p_y = line2[0] * x1 + line2[1]\n\n cross_xs = [x1, x2, x2, x1]\n cross_ys = [cross_11_p_y, cross_12_p_y, cross_21_p_y, cross_22_p_y]\n\n theta = math.atan(symmetry_axis[0])\n org_xs = []\n org_ys = []\n for x, y in zip(cross_xs, cross_ys):\n org_x = top_point[0] + x * math.cos(theta) - y * math.sin(theta)\n org_y = top_point[1] + x * math.sin(theta) + y * math.cos(theta)\n org_xs.append(org_x)\n org_ys.append(org_y)\n\n bcc_org_ags, bcc_org_rgs = cartesian_to_polar(org_xs, org_ys)\n\n if bcc_org_ags[0] > bcc_org_ags[1]:\n bcc_org_ags[0], bcc_org_ags[1] = bcc_org_ags[1], bcc_org_ags[0]\n\n if bcc_org_ags[2] > bcc_org_ags[3]:\n bcc_org_ags[2], bcc_org_ags[3] = bcc_org_ags[3], bcc_org_ags[2]\n\n measure_area = [[bcc_org_ags[0], bcc_org_ags[1]], [bcc_org_ags[2], bcc_org_ags[3]]]\n # TODO:排序得出区间,append 到区间列表中存起来\n lev_measure_areas.append(measure_area)\n\n return sed_measure_areas, lev_measure_areas\n\n\n# @logger.catch\n# def re_part_area(meas_areas, tp, ags, rgs):\n# \"\"\"计算返回各区段与顶点围成的面积\"\"\"\n# area_part_area = []\n# for ara in meas_areas:\n# tmp_ara = copy.deepcopy(ara)\n# ara[0][0] = math.floor(ara[0][0])\n# ara[0][1] = math.ceil(ara[0][1])\n# ara[1][0] = math.floor(ara[1][0])\n# ara[1][1] = math.ceil(ara[1][1])\n#\n# tmp_ara[0][0] = round(tmp_ara[0][0], 1)\n# tmp_ara[0][1] = round(tmp_ara[0][1], 1)\n# tmp_ara[1][0] = round(tmp_ara[1][0], 1)\n# tmp_ara[1][1] = round(tmp_ara[1][1], 1)\n#\n# area_part_1_ag = []\n# area_part_1_rg = []\n# area_part_2_ag = []\n# area_part_2_rg = []\n#\n# for ag, rg in zip(ags, rgs):\n# if tmp_ara[0][0] <= ag < tmp_ara[0][1]:\n# area_part_1_ag.append(ag)\n# area_part_1_rg.append(rg)\n# elif tmp_ara[1][0] <= ag < tmp_ara[1][1]:\n# area_part_2_ag.append(ag)\n# area_part_2_rg.append(rg)\n# area_part_1_xs, area_part_1_ys = tools.polar_to_cartesian(area_part_1_ag, area_part_1_rg)\n# area_part_1_points = []\n# for x, y in zip(area_part_1_xs, area_part_1_ys):\n# p = [x, y]\n# area_part_1_points.append(p)\n# area_part_1_points.append(tp)\n# area_points = calc_area.coords_sort(area_part_1_points)\n# area_part_1_area = calc_area.getPolygonArea(area_points)\n# area_part_area.append(area_part_1_area)\n#\n# area_part_2_xs, area_part_2_ys = tools.polar_to_cartesian(area_part_2_ag, area_part_2_rg)\n# area_part_2_points = []\n# for x, y in zip(area_part_2_xs, area_part_2_ys):\n# p = [x, y]\n# area_part_2_points.append(p)\n# area_part_2_points.append(tp)\n# area_points = calc_area.coords_sort(area_part_2_points)\n# area_part_2_area = calc_area.getPolygonArea(area_points)\n#\n# area_part_area.append(area_part_2_area)\n#\n# return meas_areas\n\n\ndef re_mea_areas(ags, rgs, tp, sy_as, sed_areas, lev_areas, area_width):\n \"\"\"计算返回各区域的面积\"\"\"\n xs, ys = polar_to_cartesian(ags, rgs)\n out_line_all_points = []\n for x, y in zip(xs, ys):\n p = [x, y]\n out_line_all_points.append(p)\n # area_points = calc_area.coords_sort(out_line_all_points)\n # init_full_profile_area = calc_area.getPolygonArea(area_points)\n\n tx0, ty0, t_xs, t_ys = symmetry_axis_convert(ags, rgs, sy_as, tp) # 坐��系转换得目的是获取区域,将实际的数据与测量数据结合\n sed_meas_locs, lev_meas_locs = calc_measure_range(sed_areas, lev_areas, t_xs, t_ys, area_width, sy_as, tp)\n\n # sed_meas_locs = re_part_area(sed_meas_locs, tp, ags, rgs)\n # lev_meas_locs = re_part_area(lev_meas_locs, tp, ags, rgs)\n\n return sed_meas_locs, lev_meas_locs\n\n\n\n# 数据分圈\ndef gen_a_circle_data(device_sn):\n lst_angle = []\n lst_range = []\n # 获取device_sn\n try:\n res = CollectRaw.objects.filter(device_sn=device_sn).order_by('id').values('create_time', 'angle', 'range')[:3600]\n for i in range(len(res)):\n fflag = 1\n if i > 1 and res[i]['angle'] - res[i - 1]['angle'] < 0: # 到此,一圈数据结束\n lst_data = [] # 重新装下一圈数据\n return lst_angle, lst_range\n\n elif i == len(res) - 1 and fflag: # 防止最新的一圈数据获取不到,\n lst_angle.append(res[len(res) - 1]['angle'])\n lst_range.append(res[len(res) - 1]['range'])\n\n lst_angle.append(res[i]['angle'])\n\n if res[i]['range'] > 20000:\n lst_range.append(0)\n else:\n lst_range.append(res[i]['range'])\n # print(\"=========\", lst_data)\n except:\n pass\n finally:\n return lst_angle, lst_range\n\n","sub_path":"utils/init_configuration.py","file_name":"init_configuration.py","file_ext":"py","file_size_in_byte":18500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"307310793","text":"from django.conf import settings\nfrom django.shortcuts import render, redirect,get_object_or_404\nfrom django.contrib.auth.models import User,auth\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nimport random\nfrom django.db.models import Q\nfrom django.core.files.storage import FileSystemStorage\nimport requests\nfrom django.db import models\nfrom .models import Post\nfrom .models import blog\nfrom .models import Video\nfrom .models import Userprofile,Comment,SubComment,Categories,FeedBack\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render\nfrom .form import PostForm\nfrom .form import UserprofileForm\nfrom datetime import datetime\nfrom django_ckeditor_5.fields import CKEditor5Field\nimport os\nimport json\nfrom django.http import HttpResponse,JsonResponse\nfrom taggit.models import Tag\ndef homepage(request):\n \"\"\"\n post=Post.objects.all()\n post_list = Post.objects.all()\n print(post)\n query = request.GET.get(\"q\")\n print(query)\n if query:\n post_list = post_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query)\n ).distinct()\n\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n \"\"\"\n feed = FeedBack.objects.all()\n if request.user.is_authenticated:\n try:\n profile = get_object_or_404(Userprofile,user=request.user)\n except:\n user_profile = Userprofile(user=request.user,username=request.user)\n user_profile.save()\n if request.user.is_staff ==False :\n instanace = get_object_or_404(User,username=request.user)\n instanace.is_staff = True\n instanace.save()\n return render(request,'index2.html',{'feed':feed})\ndef blogs(request):\n post=Post.objects.filter(draft=False)\n post_list = Post.objects.filter(draft=False)\n query = request.GET.get(\"q\")\n query1 = request.GET.get(\"query\")\n if query1:\n categories = get_object_or_404(Categories,categories=query1)\n post=Post.objects.filter(draft=False,categories=categories)\n post_list = Post.objects.filter(draft=False,categories=categories)\n print(post)\n elif query:\n post_list = post_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query) \n ).distinct()\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef signup(request):\n if request.method == 'POST':\n first_name = request.POST['first']\n last_name = request.POST['last']\n email = request.POST['email']\n UserName = request.POST['username']\n globals()['first_name']=first_name\n globals()['last_name']=last_name\n globals()['email'] = email\n globals()['username'] = UserName\n if User.objects.filter(email=email).exists():\n messages.info(request,'Email Already exist')\n return redirect('signup')\n elif Userprofile.objects.filter(username=username).exists():\n messages.info(request,'UserName Already exist')\n return redirect('signup')\n else:\n otp = random.randint(100000,999999)\n #user = User.objects.create_user(username=phonenumber,password=password,email=email,first_name=first_name,last_name=last_name)\n #user.save()\n globals()['otp']=otp\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello ' + first_name+ ' thanks for registering to the website otp for login is'+ str(otp),\n 'noreply@gmail.com',\n [email,'dheerukreddy@gmail.com'],\n \n )\n\n return redirect('verification')\n return render(request,'signup.html')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n return render(request,'signup.html')\ndef verification(request):\n if request.method == 'POST':\n email_otp = int(request.POST['otp'])\n try:\n user=User.objects.filter(email=email).exists()\n print(otp)\n otp is not None\n except:\n return redirect('signup')\n print(user)\n if email_otp == otp or '12345' and user == False:\n password = request.POST['password']\n messages.info(request,'otp verified')\n user = User.objects.create_user(username=email,password=password,email=email,first_name=first_name,last_name=last_name)\n user.save()\n profile = get_object_or_404(User,email=email)\n print(profile)\n user_profile = Userprofile(user=profile,username=username)\n user_profile.save()\n return redirect('login')\n elif user == True:\n messages.info(request,'user already verified')\n return redirect('login')\n else:\n messages.info(request,'otp invalid')\n return redirect('verification')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n else:\n return render(request,'verification.html')\ndef login(request):\n if request.method == 'POST':\n password = request.POST['password']\n email = request.POST['email']\n user = auth.authenticate(username=email,password=password)\n if user is not None:\n auth.login(request,user)\n return redirect(\"/\")\n else:\n messages.info(request,'invalid phone or password')\n return redirect('/login')\n else:\n if request.user.is_authenticated:\n return redirect('/')\n else:\n return render(request,'login.html')\ndef logout(request):\n auth.logout(request)\n return redirect('homepage')\ndef createpost(request):\n if request.method == 'POST':\n form = PostForm(request.POST,request.FILES or None)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.user = request.user\n instance.save()\n form.save_m2m()\n \n return redirect('/myposts')\n else:\n print(request.user)\n form = PostForm()\n context = {\n \"form\":form,\n }\n return render(request,'test.html',context)\ndef style1(request):\n return redirect('/error')\ndef style2(request):\n return render(request,'style2.html')\ndef style3(request):\n return render(request,'style3.html')\ndef style4(request):\n return render(request,'style4.html')\ndef template1(request):\n return render(request,'template1.html')\ndef template2(request):\n return render(request,'template2.html')\ndef template3(request):\n return render(request,'template3.html')\ndef template4(request):\n return render(request,'template4.html')\n\ndef postdetail(request,slug=None):\n if slug == None:\n \n return redirect('signup')\n else:\n instance = get_object_or_404(Post,slug=slug)\n tag = Tag.objects.filter()\n is_liked =False\n print(instance.user)\n profile = get_object_or_404(Userprofile,user=instance.user)\n print(profile)\n post = get_object_or_404(Post,slug=slug)\n com = Comment.objects.filter(post=post).count\n if request.method=='POST':\n comm = request.POST.get('comm')\n comm_id = request.POST.get('comm_id')\n if comm_id:\n SubComment(\n post=instance,\n user=request.user,\n comm = comm,\n comment = Comment.objects.get(id=int(comm_id))\n ).save()\n return redirect('/'+str(slug)+'/post-detail')\n else:\n Comment(post=instance,user=request.user,comm=comm).save()\n return redirect('/'+str(slug)+'/post-detail')\n comments = []\n for c in Comment.objects.filter(post=instance):\n comments.append([c,SubComment.objects.filter(comment=c)])\n\n if instance.likes.filter(username=request.user).exists():\n is_liked = True\n common_tags = Post.tags.most_common()[:8]\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"comments\":comments,\n \"is_liked\" :is_liked,\n \"total_likes\":instance.total_likes(),\n \"profile\":profile,\n \"com\":com,\n 'common_tags':common_tags,\n }\n return render(request,\"detail1.html\",context)\n\"\"\"\ndef likes(request):\n slug=request.POST.get('like')\n post = get_object_or_404(Post,slug=request.POST.get('like'))\n is_liked =False\n \n if post.likes.filter(username=request.user).exists():\n \n post.likes.remove(request.user)\n \n is_liked = False\n else:\n post.likes.add(request.user)\n is_liked = True\n return HttpResponse('/' + str(slug)+'/post-detail' )\n\"\"\"\ndef likes(request):\n user = request.user\n if request.method == 'POST':\n pk = request.POST.get('post_pk')\n post_obj = Post.objects.get(pk=pk)\n post = get_object_or_404(Post,pk=pk)\n if user in post_obj.likes.all():\n post_obj.likes.remove(user)\n post.countlikes = post_obj.total_likes()\n post.save()\n else:\n post_obj.likes.add(user)\n post.countlikes = post_obj.total_likes()\n post.save()\n return HttpResponse()\ndef post_serialized_view(request,slug):\n data = list(Post.objects.filter(slug=slug).values())\n post =get_object_or_404(Post,slug=slug)\n return JsonResponse(data,safe=False)\ndef myposts(request):\n if request.user.is_authenticated:\n post=Post.objects.filter(user=request.user)\n user1 = get_object_or_404(Userprofile,user=request.user)\n context = {\n \"post\":post,\n \"user1\":user1,\n }\n print(post)\n return render(request,\"yourpost1.html\",context)\n else:\n return redirect('/error')\ndef othersposts(request,user=None):\n user1 = get_object_or_404(Userprofile,username=user)\n print(user1.user)\n post = Post.objects.filter(email=user1,draft=False)\n name = get_object_or_404(User,username=user1)\n print(post)\n use=User.objects.filter(email=user1)\n \n context = {\n \"name\":name,\n \"post\":post,\n \"use\":use,\n \"user1\":user1,\n }\n \n return render(request,\"others1.html\",context)\ndef editpost(request,slug=None):\n if request.method == 'POST':\n instance = get_object_or_404(Post,slug=slug)\n form = PostForm(request.POST or None,instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.slug = slug\n instance.save()\n form.save_m2m()\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"form\":form\n } \n return redirect('/myposts')\n else:\n return redirect('/error')\n\n \ndef edit(request,slug=None):\n if request.method == \"POST\":\n instance = get_object_or_404(Post,slug=slug)\n form = PostForm(instance=instance)\n context = {\n \"title\": instance.title,\n \"instance\": instance,\n \"form\":form\n } \n return render(request,'test1.html',context)\n else:\n return redirect('/error')\ndef deletepost(request,slug=None):\n if request.method == \"POST\":\n instance = get_object_or_404(Post,slug=slug)\n instance.delete()\n return redirect('/myposts')\n else:\n return redirect('/error')\ndef error(request):\n return render(request,'detail1.html')\n\ndef test(request):\n form = PostForm(request.POST or None)\n if form.is_valid():\n form.save()\n return render(request,'test.html',{'form':form})\n#def profile(request):\n# if request.user.is_authenticated:\n# profile = get_object_or_404(Profile,user=str(request.user))\n# print(profile)\n# instance = get_object_or_404(Profile,user=str(request.user))\n# form = ProfileForm(request.POST or None,instance=instance)\n# if form.is_valid():\n # instance = form.save(commit=False)\n # instance.save()\n # return redirect('/profile')\n # context={\n # 'profile':profile,\n # 'form':form\n # }\n # return render(request,'profile.html',context)\n #else:\n # return redirect('login')\ndef profileedit(request):\n if request.user.is_authenticated:\n instance = get_object_or_404(Userprofile,user=request.user)\n form = UserprofileForm(request.POST or None,request.FILES or None,instance=instance)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.save()\n return redirect('/myposts')\n context={\n 'form':form\n }\n return render(request,'profile-edit.html',context)\n else:\n return redirect('/error')\ndef profile(request):\n if request.user.is_authenticated:\n user1 = get_object_or_404(Userprofile,user=request.user)\n context = {\n \"user1\":user1,\n }\n return render(request,\"profile.html\",context)\n else:\n return redirect('/error')\ndef contact(request):\n if request.method == 'POST':\n name = request.POST['name']\n email = request.POST['email']\n message = request.POST['message']\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello '+' ' + name+' ' +'Your Query Has Been Recorded Our Team Will Contact You As Soon As Possible',\n 'noreply@gmail.com',\n [email,'dheerukreddy@gmail.com'],\n )\n send_mail('Regarding Login Into the WEBSITE',\n 'Hello Dheeraj '+' ' + 'There Is a Query REcorded By' + name+' '\n 'email:'+' '+ str(email)+' '\n 'message:'+' '+ str(message),\n 'noreply@gmail.com',\n ['dheerukreddy@gmail.com'],\n )\n messages.info(request,'Your Query Has been Sucessfully Recoded We will contact You soon')\n return redirect('/contact-us') \n return render(request,'contact.html')\ndef addemail(request):\n if request.method == 'POST':\n email = request.POST['email']\n if User.objects.filter(email=email).exists():\n messages.info(request,'EMAIL ALREADY EXISTS')\n return redirect('/add-email')\n else:\n instance = get_object_or_404(User,username=request.user)\n instance.email = email\n instance.save()\n return redirect('/profile')\n else:\n if request.user.is_authenticated:\n return render(request,'add-email.html')\n else:\n return redirect('/')\ndef tags(request):\n tags = request.GET['q']\n tags = tags.replace('#','')\n tag = get_object_or_404(Tag,slug=tags)\n print(tag)\n post=Post.objects.filter(draft=False,tags=tag)\n print(post)\n post_list = Post.objects.filter(draft=False,tags=tag)\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef tagsslug(request,slug):\n tag = get_object_or_404(Tag,slug=slug)\n print(tag)\n post=Post.objects.filter(draft=False,tags=tag)\n print(post)\n post_list = Post.objects.filter(draft=False,tags=tag)\n common_tags = Post.tags.most_common()[:8]\n paginator = Paginator(post_list, 10) # Show 25 contacts per page.\n \n page_number = request.GET.get('page')\n post = paginator.get_page(page_number)\n context = {\n 'post':post,\n 'common_tags':common_tags,\n }\n return render(request,'blog.html',context)\ndef feedback(request):\n if request.method == 'POST':\n name = request.POST['name']\n rating = request.POST['rate']\n feedback = request.POST['feedback']\n feed = FeedBack(name=name,rating=rating,feedback=feedback)\n feed.save()\n return redirect('/')\n else:\n return redirect('/')","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"206504863","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: DIYer22@github\n@mail: ylxx@live.com\nCreated on Wed Jan 9 23:24:20 2019\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\nclass Markdown(pd.DataFrame):\n '''\n Markdown class base on DataFrame\n '''\n def __round__(self, *l, **kv):\n redf = pd.DataFrame.__round__(self, *l, **kv)\n return Markdown(redf)\n \n def round(self, *l, **kv):\n redf = pd.DataFrame.round(self, *l, **kv)\n return Markdown(redf)\n \n def to_md(df, nblankBetweenCell=1, tableMidSymbol = \"---:\"):\n '''\n Transfer DataFrame to markdown\n \n Parameters\n ----------\n df : DataFrame\n pandas.DataFrame\n \n nblankBetweenCell : int, default 1\n How many blanks between 2 cells\n tableMidSymbol : str, default \"---:\"\n \"-:\", \":-\", \":-:\" for markdown \n \n '''\n blanks = nblankBetweenCell *\" \"\n betweenCell = blanks + \"|\" + blanks\n rowFormat = \"|%s%s%s|\" % (blanks, \"%s\", blanks)\n ncols = len(df.columns)\n strcols = df.columns.map(str)\n lencols = np.array(strcols.map(len))\n \n strdf = df.applymap(str)\n lendf = np.array(strdf.applymap(len))\n \n \n maxLens = np.array(list(zip(lendf.max(0), lencols, [len(tableMidSymbol)]*ncols))).max(1)\n \n vMulBlank = np.vectorize(lambda x:x * \" \")\n\n mdcols = vMulBlank(maxLens - lencols) + strcols\n mddf = vMulBlank(maxLens - lendf) + strdf\n \n headstr = rowFormat % betweenCell.join(mdcols)\n \n tableMidStr = rowFormat% betweenCell.join(map(lambda x: x + tableMidSymbol, vMulBlank(maxLens-len(tableMidSymbol))))\n \n bodystr = \"\\n\".join(map(lambda kv: rowFormat% betweenCell.join(kv[-1]), mddf.iterrows()))\n \n tablestr = '\\n'.join([headstr, tableMidStr, bodystr])\n return tablestr\n def __str__(self):\n return self.to_md()\n \n @staticmethod\n def test():\n df = pd.DataFrame([{\"a\":1, \"b\":1,}, {\"a\":1, \"bbbbbb\":1,}, {\"a\":1, \"bbbbbb\":1/2, \"c\":1/3}])\n md = Markdown(df)\n print(md)\n print(\"-\"*20)\n print(md.round(2))\n return df\nif __name__ == \"__main__\":\n pass\n \n \n \n","sub_path":"boxx/tool/toolMarkdown.py","file_name":"toolMarkdown.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"525313736","text":"from flask import Flask, render_template, request\nimport json\nimport pandas\nimport math\nimport random\n\napp = Flask(__name__)\napp.debug = True\n\nfilepathPoints = \"./results/points.csv\"\nfilepathClusters = \"./results/centers.csv\"\n\n\ndef max_cluster(list_points, key):\n max_c = 0\n for p in list_points : \n distance =math.sqrt(math.pow( p[0]-key[0],2) + (math.pow(p[1]- key[1],2) ))\n if distance > max_c :\n max_c = distance\n return p\n return 0\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/mapPoint\", methods = ['POST','GET'])\ndef generatePoints():\n if request.method == 'GET':\n points = pandas.read_csv(filepath_or_buffer=filepathPoints) # Read the file\n\n table_points = points[['longitude', 'latitude','hashtags','url' ,'cluster' ]]\n table_points = table_points.fillna('').values.tolist()\n\n points = pandas.read_csv(filepath_or_buffer=filepathClusters) # Read the file\n table_clusters = points[['longitude','latitude','cluster', 'tags']].fillna('').values.tolist()\n\n\n # now creating a list of objects in this form : [cluster_number, center point] , [list of the points contained in this cluster]\n result =[ [ [cluster,[clust for clust in table_clusters if clust[2] == cluster][0],10 ], [l for l in table_points if l[4] == cluster] ] for cluster in set([ p[4] for p in table_points])]\n \n for cluster in result :\n for point in cluster[1] :\n point[1] = point[1]+0.0005-(random.randint(0,10)/10000.0)#max_cluster(cluster[1],cluster[0][1])\n point[0] = point[0]+0.0005-(random.randint(0,10)/10000.0)#max_cluster(cluster[1],cluster[0][1])\n\n return json.dumps(result)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=8080, debug=True)\n","sub_path":"python/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"100857760","text":"#\n# SPDX-License-Identifier: MIT\n#\n\nfrom oeqa.selftest.case import OESelftestTestCase\nfrom oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars\n\nclass TestSyzkallerWR(OESelftestTestCase):\n def setUpSyzkallerConfig(self):\n syz_target_sysroot = get_bb_var('PKGD', 'syzkaller')\n syzkaller_native = get_bb_var('RECIPE_SYSROOT_NATIVE', 'syzkaller-native')\n self.logger.info(\"syz_target_sysroot %s\" % syz_target_sysroot)\n\n self.syz_manager_bin = os.path.join(syzkaller_native, 'usr/bin/syz-manager')\n self.syzkaller_target = os.path.join(syz_target_sysroot, 'usr')\n self.logger.info(\"self.syzkaller_target %s\" % self.syzkaller_target)\n self.syzkaller_workdir = os.path.join(self.topdir, 'syzkaller_workdir')\n self.syzkaller_cfg = os.path.join(self.syzkaller_workdir, 'wrl.cfg')\n\n bb_vars = get_bb_vars(['SYZ_FUZZTIME', 'SYZ_QEMU_MEM', 'SYZ_QEMU_CPUS'])\n self.syzkaller_fuzztime = int(bb_vars['SYZ_FUZZTIME'] or 30) * 60\n self.logger.info(\"self.syzkaller_fuzztime %s\" % self.syzkaller_fuzztime)\n self.syzkaller_qemu_mem = int(bb_vars['SYZ_QEMU_MEM'] or 1024)\n self.logger.info(\"self.syzkaller_qemu_mem %s\" % self.syzkaller_qemu_mem)\n self.syzkaller_qemu_cpus = int(bb_vars['SYZ_QEMU_CPUS'] or 2)\n self.logger.info(\"self.syzkaller_qemu_cpus %s\" % self.syzkaller_qemu_cpus)\n self.syzkaller_vms = self.nprocs // self.syzkaller_qemu_cpus or 1\n\n self.kernel_cmdline = \"dummy_hcd.num=%s\" % (self.syzkaller_qemu_cpus)\n\n if not os.path.exists(self.syzkaller_workdir):\n os.mkdir(self.syzkaller_workdir)\n\n with open(self.syzkaller_cfg, 'w') as f:\n f.write(\n\"\"\"\n{\n\t\"target\": \"linux/amd64\",\n\t\"http\": \"127.0.0.1:56741\",\n\t\"workdir\": \"%s\",\n\t\"kernel_obj\": \"%s\",\n\t\"kernel_src\": \"%s\",\n\t\"image\": \"%s\",\n\t\"syzkaller\": \"%s\",\n\t\"type\": \"qemu\",\n\t\"reproduce\" : false,\n\t\"sandbox\": \"none\",\n\t\"vm\": {\n\t\t\"count\": %s,\n\t\t\"kernel\": \"%s\",\n\t\t\"cmdline\": \"%s\",\n\t\t\"cpu\": %s,\n\t\t\"mem\": %s\n\t}\n}\n\"\"\"\n% (self.syzkaller_workdir, self.kernel_objdir, self.kernel_src, self.rootfs, \\\n self.syzkaller_target, self.syzkaller_vms, self.kernel, self.kernel_cmdline, \\\n self.syzkaller_qemu_cpus, self.syzkaller_qemu_mem)\n )\n\n def setUpLocal(self):\n super(TestSyzkallerWR, self).setUpLocal()\n\n self.image = 'wrlinux-image-glibc-core'\n self.machine = 'intel-x86-64'\n self.fstypes = \"ext4\"\n\n bb_vars = get_bb_vars(['TOPDIR', 'DEPLOY_DIR_IMAGE', 'STAGING_KERNEL_DIR'])\n\n self.topdir = bb_vars['TOPDIR']\n self.deploy_dir_image = bb_vars['DEPLOY_DIR_IMAGE']\n self.kernel_src = bb_vars['STAGING_KERNEL_DIR']\n\n self.nprocs = os.cpu_count() or 1\n self.kernel = os.path.join(self.deploy_dir_image, 'bzImage')\n self.rootfs = os.path.join(self.deploy_dir_image, '%s-%s.ext4' % (self.image, self.machine))\n self.kernel_objdir = self.deploy_dir_image\n\n self.setUpSyzkallerConfig()\n\n self.write_config(\n\"\"\"\nMACHINE = \"%s\"\nIMAGE_FSTYPES = \"%s\"\n\"\"\"\n% (self.machine, self.fstypes)\n )\n\n bitbake(self.image, output_log=self.logger)\n bitbake('syzkaller-native -c addto_recipe_sysroot', output_log=self.logger)\n bitbake('syzkaller', output_log=self.logger)\n\n def test_syzkaller_wr(self):\n runCmd([self.syz_manager_bin, '-config', self.syzkaller_cfg], timeout=self.syzkaller_fuzztime, output_log=self.logger, ignore_status=True, shell=False)\n","sub_path":"lib/oeqa/selftest/cases/syzkaller_wr.py","file_name":"syzkaller_wr.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"574982384","text":"# Write your solution for 1.2 here!b=0\nb=0\nfor i in range (101):\n if i%2==0:\n b=b+i\nprint (b)\ni=0\nwhile i<1000:\n if i%6==2 and i**3%5==3:\n print(i)\n i=i+1","sub_path":"exercises/conditionals.py","file_name":"conditionals.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"573744974","text":"from django.test import TestCase\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nfrom tickets.tests.factories import TicketFactory\nfrom tickets.constants.status import VERIFIED, COMPLETED, STARTED, ASSIGNED, UNASSIGNED\n\n\nclass TicketTestCase(TestCase):\n def test_status(self):\n t0 = timezone.now() - timedelta(days=2)\n t1 = timezone.now() - timedelta(days=1)\n t2 = timezone.now()\n ticket_unassigned = TicketFactory(assignee=None)\n ticket_assigned = TicketFactory()\n ticket_started = TicketFactory(started=t0)\n ticket_completed = TicketFactory(completed=t1)\n ticket_verified = TicketFactory(verified=t2)\n assert ticket_unassigned.status() == UNASSIGNED\n assert ticket_assigned.status() == ASSIGNED\n assert ticket_started.status() == STARTED\n assert ticket_completed.status() == COMPLETED\n assert ticket_verified.status() == VERIFIED\n","sub_path":"tickets/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"531961890","text":"\"\"\"\nAuthor: Mr.Jiang\nGithub: https://github.com/1642195610\nCSDN : https://blog.csdn.net/qq_43722162\n\"\"\"\n\n\nclass Student():\n def __init__(self, name, sex, age):\n \"\"\"\n\n :param name:姓名\n :type name: str\n :param sex: 性别\n :type sex: str\n :param age: 年龄\n :type age: int\n \"\"\"\n self.name = name\n self.sex = sex\n self.age = age\n\n def learn(self):\n print(\"%s能自主学习\" % self.name)\n\n def sleep(self):\n print(\"{}能自主休息\".format(self.name))\n\n\nl = Student(\"姜泽毓\", \"男\", 24)\nprint(l.name)\nprint(l.sex)\nprint(l.age)\nl.learn()\nl.sleep()\n","sub_path":"data_zgd/python进阶/10.6-链表/10.6.py","file_name":"10.6.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"244673100","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 ('controller', '0012_auto_20150119_1605'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='traffic',\n name='for_sta',\n field=models.ForeignKey(related_name='for_station', default=None, to='controller.Station', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"apps/controller/migrations/0013_auto_20150119_1810.py","file_name":"0013_auto_20150119_1810.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"609540775","text":"#coding=utf-8\nimport numpy as np\nimport cv2\nimport time\n\n\n\ndef cost(func):\n def __wrap__(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(\"-------------\", func.__name__, end - start)\n return result\n\n return __wrap__\n \n\nclass GMM:\n\n def __init__(self, height, width, model_per_pixl, channel=3):\n self.k = model_per_pixl\n self.channel = channel\n self.height, self.width = height, width\n self.means = np.zeros([height, width, model_per_pixl, channel], np.float64)\n self.variance = np.ones([height, width, model_per_pixl, channel])\n self.omega = np.ones([height, width, model_per_pixl]) / model_per_pixl # model_wight \n self.rol = np.zeros([height, width, model_per_pixl]) \n\n self.lr = self.alpha = 0.05\n self.init_weight = 0.1\n self.max_var = 255\n self.count = 0\n\n def norm_weight(self):\n self.omega = self.omega /np.sum(self.omega, axis=-1)[..., np.newaxis]\n\n @cost\n def pdf(self, img):\n # 多维高斯分布\n exp = -0.5 * np.sum(np.power(img - self.means, 2) / self.variance, axis=-1)\n c = np.power(2 * np.pi * np.sum(self.variance, axis=-1), self.channel / 2)\n return 1 / c * np.exp(exp)\n\n @cost\n def resorted(self):\n sort_idx = np.argsort(-self.omega, axis=-1)\n for r in range(self.height):\n for c in range(self.width):\n perm = sort_idx[r, c] # 降序\n self.omega[r, c] = self.omega[r, c, perm]\n self.means[r, c] = self.means[r, c, perm]\n self.variance[r, c] = self.variance[r, c, perm]\n\n @cost\n def background_mask(self, T=0.3):\n cum_weight = np.cumsum(self.omega, axis=-1)\n return cum_weight < T\n\n\n @cost\n def fit(self, img):\n new_img = np.tile(img[:,:, np.newaxis,:], [1, 1, self.k, 1])\n self.rol = self.alpha * self.pdf(new_img)\n\n update_var = (new_img - self.means) ** 2\n bgd_delta = np.sqrt(np.sum(update_var / self.variance, axis=-1))\n bgd_mask = bgd_delta < 2.5\n result = np.any(bgd_mask & self.background_mask(), axis=-1)\n self.count += 1\n \n self.alpha = 0.1 if self.count < 10 else 0.0001\n print(self.alpha)\n\n # update omega\n # min_dis_index = np.argmin(bgd_delta, axis=-1)\n for r in range(self.height):\n for c in range(self.width):\n min_dis_idx = None\n for idx, bgd in enumerate(bgd_delta[r][c]):\n if bgd:\n min_dis_idx = idx\n min_weight_idx = -1\n self.omega[r, c] = (1 - self.alpha) * self.omega[r, c]\n if min_dis_idx is not None and bgd_mask[r, c, min_dis_idx]: # 最小的高斯 小于2.5\n self.omega[r, c, min_dis_idx] += self.alpha # update weight\n self.means[r, c, min_dis_idx] += self.rol[r, c, min_dis_idx] * (img[r, c] - self.means[r, c, min_dis_idx])\n self.variance[r, c, min_dis_idx] += self.rol[r, c, min_dis_idx] * (update_var[r, c, min_dis_idx] - self.variance[r, c, min_dis_idx])\n\n else: # 都不是backgound\n self.omega[r, c, min_weight_idx] = self.init_weight\n self.means[r, c, min_weight_idx] = img[r, c]\n self.variance[r, c, min_weight_idx] = self.max_var\n\n self.norm_weight()\n self.resorted()\n return result\n\ndef main():\n cap = cv2.VideoCapture(0)\n cap.set(3, 300)\n cap.set(4, 300)\n _, img = cap.read()\n height, width, channel = img.shape\n start = time.time()\n gm = GMM(height, width, 5, channel)\n while(True):\n _, img = cap.read()\n mask = gm.fit(img)\n print(mask.shape, img.shape)\n mask = cv2.medianBlur(mask.astype(np.uint8), 5)\n img[mask.astype(np.bool)] = (255, 255, 255)\n cv2.imshow(\"test\", img)\n cv2.waitKey(100)\nmain()\n","sub_path":"gmm.py","file_name":"gmm.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"486254760","text":"def modify_eni(connection, vpc_id, module, eni):\n instance_id = module.params.get('instance_id')\n attached = module.params.get('attached')\n do_detach = (module.params.get('state') == 'detached')\n device_index = module.params.get('device_index')\n description = module.params.get('description')\n security_groups = module.params.get('security_groups')\n force_detach = module.params.get('force_detach')\n source_dest_check = module.params.get('source_dest_check')\n delete_on_termination = module.params.get('delete_on_termination')\n secondary_private_ip_addresses = module.params.get('secondary_private_ip_addresses')\n purge_secondary_private_ip_addresses = module.params.get('purge_secondary_private_ip_addresses')\n secondary_private_ip_address_count = module.params.get('secondary_private_ip_address_count')\n changed = False\n try:\n if (description is not None):\n if (eni.description != description):\n connection.modify_network_interface_attribute(eni.id, 'description', description)\n changed = True\n if (len(security_groups) > 0):\n groups = get_ec2_security_group_ids_from_names(security_groups, connection, vpc_id=vpc_id, boto3=False)\n if (sorted(get_sec_group_list(eni.groups)) != sorted(groups)):\n connection.modify_network_interface_attribute(eni.id, 'groupSet', groups)\n changed = True\n if (source_dest_check is not None):\n if (eni.source_dest_check != source_dest_check):\n connection.modify_network_interface_attribute(eni.id, 'sourceDestCheck', source_dest_check)\n changed = True\n if ((delete_on_termination is not None) and (eni.attachment is not None)):\n if (eni.attachment.delete_on_termination is not delete_on_termination):\n connection.modify_network_interface_attribute(eni.id, 'deleteOnTermination', delete_on_termination, eni.attachment.id)\n changed = True\n current_secondary_addresses = [i.private_ip_address for i in eni.private_ip_addresses if (not i.primary)]\n if (secondary_private_ip_addresses is not None):\n secondary_addresses_to_remove = list((set(current_secondary_addresses) - set(secondary_private_ip_addresses)))\n if (secondary_addresses_to_remove and purge_secondary_private_ip_addresses):\n connection.unassign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=list((set(current_secondary_addresses) - set(secondary_private_ip_addresses))), dry_run=False)\n changed = True\n secondary_addresses_to_add = list((set(secondary_private_ip_addresses) - set(current_secondary_addresses)))\n if secondary_addresses_to_add:\n connection.assign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=secondary_addresses_to_add, secondary_private_ip_address_count=None, allow_reassignment=False, dry_run=False)\n changed = True\n if (secondary_private_ip_address_count is not None):\n current_secondary_address_count = len(current_secondary_addresses)\n if (secondary_private_ip_address_count > current_secondary_address_count):\n connection.assign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=None, secondary_private_ip_address_count=(secondary_private_ip_address_count - current_secondary_address_count), allow_reassignment=False, dry_run=False)\n changed = True\n elif (secondary_private_ip_address_count < current_secondary_address_count):\n secondary_addresses_to_remove_count = (current_secondary_address_count - secondary_private_ip_address_count)\n connection.unassign_private_ip_addresses(network_interface_id=eni.id, private_ip_addresses=current_secondary_addresses[:secondary_addresses_to_remove_count], dry_run=False)\n if (attached is True):\n if (eni.attachment and (eni.attachment.instance_id != instance_id)):\n detach_eni(eni, module)\n eni.attach(instance_id, device_index)\n wait_for_eni(eni, 'attached')\n changed = True\n if (eni.attachment is None):\n eni.attach(instance_id, device_index)\n wait_for_eni(eni, 'attached')\n changed = True\n elif (attached is False):\n detach_eni(eni, module)\n except BotoServerError as e:\n module.fail_json(msg=e.message)\n eni.update()\n module.exit_json(changed=changed, interface=get_eni_info(eni))","sub_path":"Data Set/bug-fixing-5/fed4217fd75f5dd734ce48973c0eaadbb6060774--fix.py","file_name":"fed4217fd75f5dd734ce48973c0eaadbb6060774--fix.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"296603661","text":"import numpy as np\nfrom collections import Iterable\n\nfrom .form.utils import docval, getargs, popargs, call_docval_func\n\nfrom . import register_class, CORE_NAMESPACE\nfrom .base import TimeSeries, _default_conversion, _default_resolution\nfrom .core import NWBContainer, ElementIdentifiers, DynamicTable, DynamicTableRegion\n\n\n@register_class('AnnotationSeries', CORE_NAMESPACE)\nclass AnnotationSeries(TimeSeries):\n \"\"\"\n Stores text-based records about the experiment. To use the\n AnnotationSeries, add records individually through\n add_annotation() and then call finalize(). Alternatively, if\n all annotations are already stored in a list, use set_data()\n and set_timestamps()\n \"\"\"\n\n __nwbfields__ = ()\n\n _ancestry = \"TimeSeries,AnnotationSeries\"\n _help = \"Time-stamped annotations about an experiment.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames',\n 'default': list()},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': None},\n {'name': 'comments', 'type': str,\n 'doc': 'Human-readable comments about this TimeSeries dataset', 'default': 'no comments'},\n {'name': 'description', 'type': str, 'doc':\n 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)\n super(AnnotationSeries, self).__init__(name, data, 'n/a',\n resolution=-1.0, conversion=1.0,\n timestamps=timestamps, **kwargs)\n\n @docval({'name': 'time', 'type': float, 'doc': 'The time for the anotation'},\n {'name': 'annotation', 'type': str, 'doc': 'the annotation'})\n def add_annotation(self, **kwargs):\n '''\n Add an annotation\n '''\n time, annotation = getargs('time', 'annotation', kwargs)\n self.fields['timestamps'].append(time)\n self.fields['data'].append(annotation)\n\n\n@register_class('AbstractFeatureSeries', CORE_NAMESPACE)\nclass AbstractFeatureSeries(TimeSeries):\n \"\"\"\n Represents the salient features of a data stream. Typically this\n will be used for things like a visual grating stimulus, where\n the bulk of data (each frame sent to the graphics card) is bulky\n and not of high value, while the salient characteristics (eg,\n orientation, spatial frequency, contrast, etc) are what important\n and are what are used for analysis\n \"\"\"\n\n __nwbfields__ = ('feature_units',\n 'features')\n\n _ancestry = \"TimeSeries,AbstractFeatureSeries\"\n _help = \"Features of an applied stimulus. This is useful when storing the raw stimulus is impractical.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'feature_units', 'type': (str, Iterable), 'doc': 'The unit of each feature'},\n {'name': 'features', 'type': (str, Iterable), 'doc': 'Description of each feature'},\n\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames',\n 'default': list()},\n {'name': 'resolution', 'type': float,\n 'doc': 'The smallest meaningful difference (in specified unit) between values in data',\n 'default': _default_resolution},\n {'name': 'conversion', 'type': float,\n 'doc': 'Scalar to multiply each element in data to convert it to the specified unit',\n 'default': _default_conversion},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': None},\n {'name': 'starting_time', 'type': float, 'doc': 'The timestamp of the first sample', 'default': None},\n {'name': 'rate', 'type': float, 'doc': 'Sampling rate in Hz', 'default': None},\n {'name': 'comments', 'type': str, 'doc': 'Human-readable comments about this TimeSeries dataset',\n 'default': 'no comments'},\n {'name': 'description', 'type': str,\n 'doc': 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'control', 'type': Iterable,\n 'doc': 'Numerical labels that apply to each element in data', 'default': None},\n {'name': 'control_description', 'type': Iterable,\n 'doc': 'Description of each control value', 'default': None},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, features, feature_units = popargs('name', 'data',\n 'features', 'feature_units', kwargs)\n super(AbstractFeatureSeries, self).__init__(name, data, \"see 'feature_units'\", **kwargs)\n self.features = features\n self.feature_units = feature_units\n\n @docval({'name': 'time', 'type': float, 'doc': 'the time point of this feature'},\n {'name': 'features', 'type': (list, np.ndarray), 'doc': 'the feature values for this time point'})\n def add_features(self, **kwargs):\n time, features = getargs('time', 'features', kwargs)\n self.timestamps.append(time)\n self.data.append(features)\n\n\n@register_class('IntervalSeries', CORE_NAMESPACE)\nclass IntervalSeries(TimeSeries):\n \"\"\"\n Stores intervals of data. The timestamps field stores the beginning and end of intervals. The\n data field stores whether the interval just started (>0 value) or ended (<0 value). Different interval\n types can be represented in the same series by using multiple key values (eg, 1 for feature A, 2\n for feature B, 3 for feature C, etc). The field data stores an 8-bit integer. This is largely an alias\n of a standard TimeSeries but that is identifiable as representing time intervals in a machinereadable\n way.\n \"\"\"\n\n __nwbfields__ = ()\n\n _ancestry = \"TimeSeries,IntervalSeries\"\n _help = \"Stores the start and stop times for events.\"\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'data', 'type': ('array_data', 'data', TimeSeries),\n 'doc': '>0 if interval started, <0 if interval ended.', 'default': list()},\n {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),\n 'doc': 'Timestamps for samples stored in data', 'default': list()},\n {'name': 'comments', 'type': str,\n 'doc': 'Human-readable comments about this TimeSeries dataset', 'default': 'no comments'},\n {'name': 'description', 'type': str,\n 'doc': 'Description of this TimeSeries dataset', 'default': 'no description'},\n {'name': 'control', 'type': Iterable,\n 'doc': 'Numerical labels that apply to each element in data', 'default': None},\n {'name': 'control_description', 'type': Iterable,\n 'doc': 'Description of each control value', 'default': None},\n {'name': 'parent', 'type': NWBContainer,\n 'doc': 'The parent NWBContainer for this NWBContainer', 'default': None})\n def __init__(self, **kwargs):\n name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)\n unit = 'n/a'\n self.__interval_timestamps = timestamps\n self.__interval_data = data\n super(IntervalSeries, self).__init__(name, data, unit,\n timestamps=timestamps,\n resolution=-1.0,\n conversion=1.0,\n **kwargs)\n\n @docval({'name': 'start', 'type': float, 'doc': 'The name of this TimeSeries dataset'},\n {'name': 'stop', 'type': float, 'doc': 'The name of this TimeSeries dataset'})\n def add_interval(self, **kwargs):\n start, stop = getargs('start', 'stop', kwargs)\n self.__interval_timestamps.append(start)\n self.__interval_timestamps.append(stop)\n self.__interval_data.append(1)\n self.__interval_data.append(-1)\n\n @property\n def data(self):\n return self.__interval_data\n\n @property\n def timestamps(self):\n return self.__interval_timestamps\n\n\n@register_class('Units', CORE_NAMESPACE)\nclass Units(DynamicTable):\n \"\"\"\n Event times of observed units (e.g. cell, synapse, etc.).\n \"\"\"\n\n __columns__ = (\n {'name': 'spike_times', 'description': 'the spike times for each unit', 'vector_data': True},\n {'name': 'electrode', 'description': 'the electrode that each spike unit came from'},\n {'name': 'electrode_group', 'description': 'the electrode group that each spike unit came from'},\n {'name': 'waveform_mean', 'description': 'the spike waveform mean for each spike unit'},\n {'name': 'waveform_sd', 'description': 'the spike waveform standard deviation for each spike unit'}\n )\n\n @docval({'name': 'name', 'type': str, 'doc': 'Name of this Units interface', 'default': 'Units'},\n {'name': 'id', 'type': ('array_data', ElementIdentifiers),\n 'doc': 'the identifiers for the units stored in this interface', 'default': None},\n {'name': 'columns', 'type': (tuple, list), 'doc': 'the columns in this table', 'default': None},\n {'name': 'colnames', 'type': 'array_data', 'doc': 'the names of the columns in this table',\n 'default': None},\n {'name': 'description', 'type': str, 'doc': 'a description of what is in this table', 'default': None})\n def __init__(self, **kwargs):\n if kwargs.get('description', None) is None:\n kwargs['description'] = \"\"\n call_docval_func(super(Units, self).__init__, kwargs)\n if 'spike_times' not in self.colnames:\n self.__has_spike_times = False\n\n @docval({'name': 'spike_times', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'electrode', 'type': DynamicTableRegion, 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'electrode_group', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'waveform_mean', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'waveform_sd', 'type': 'array_data', 'doc': 'the spike times for the unit', 'default': None},\n {'name': 'id', 'type': int, 'help': 'the ID for the ROI', 'default': None},\n allow_extra=True)\n def add_unit(self, **kwargs):\n \"\"\"\n Add a unit to this table\n \"\"\"\n super(Units, self).add_row(**kwargs)\n\n @docval({'name': 'index', 'type': int,\n 'doc': 'the index of the unit in unit_ids to retrieve spike times for'})\n def get_unit_spike_times(self, **kwargs):\n index = getargs('index', kwargs)\n return np.asarray(self['spike_times'][index])\n","sub_path":"src/pynwb/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":11629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"304189952","text":"from Dataset import Dataset\nfrom Processing.Lungs import Lungs\nfrom Processing.LunglessCT import LunglessCT\nfrom Processing.Bones import Bones\nfrom Processing.Tissues import Tissues\nfrom Processing.Fats import Fats\n\nimport numpy as np\nfrom scipy.ndimage import median_filter\n\n\nclass PreProcess:\n \"\"\"PreProcessing by creating the label map from the binary maps.\"\"\"\n def __init__(self, emphysema_va1=50, ventilated_val=300, poorly_vent_val=700, atelectatic_val=1000, bones_val=1200,\n tissue_val=1050, fats_val=650):\n \"\"\"Initialize the parameters for the preprocessing of the label map.\n\n :param emphysema_va1: Weighted value for the lung binary map\n :param ventilated_val: Weighted value for the lung binary map\n :param poorly_vent_val: Weighted value for the lung binary map\n :param atelectatic_val: Weighted value for the lung binary map\n :param bones_val: Weighted value for the bones binary map\n :param tissue_val: Weighted value for the tissues binary map\n :param fats_val: Weighted value for the fats binary map\n \"\"\"\n self.bones_val = bones_val\n self.tissue_val = tissue_val\n self.fats_val = fats_val\n\n # Initialize default parameters for lungs label map\n self._emphysema_val = 50\n self._ventilated_val = 300\n self._poorly_vent_val = 700\n self._atelectatic_val = 1000\n\n # Initialize the parameters\n if emphysema_va1 is None:\n self.emphysema_va1 = self._emphysema_val\n else:\n self.emphysema_va1 = emphysema_va1\n if ventilated_val is None:\n self.ventilated_val = self._ventilated_val\n else:\n self.ventilated_val = ventilated_val\n if poorly_vent_val is None:\n self.poorly_vent_val = self._poorly_vent_val\n else:\n self.poorly_vent_val = poorly_vent_val\n if atelectatic_val is None:\n self.atelectatic_val = self._atelectatic_val\n else:\n self.atelectatic_val = atelectatic_val\n\n if emphysema_va1 != self._emphysema_val or ventilated_val != self._ventilated_val or \\\n poorly_vent_val != self._poorly_vent_val or atelectatic_val != self._atelectatic_val:\n self.recreate_lungs = True\n else:\n self.recreate_lungs = False\n\n def __repr__(self):\n return '{self.__class__.__name__}(emphysema_va1={self.emphysema_va1}, ventilated_val=' \\\n '{self.ventilated_val}, poorly_vent_val={self.poorly_vent_val}, atelectatic_val={self.atelectatic_val},'\\\n ' bones_val={self.bones_val}, tissue_val={self.tissue_val}, fats_val={self.fats_val})'.format(self=self)\n\n def LTRC_label_map(self, pat_obj):\n \"\"\"Creates the label map for LTRC dataset.\n\n :param pat_obj: The object of LTRC class\n :return: source_data (LTRC)\n \"\"\"\n # Initialize the parameters and empty dictionary\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n source_data, target_data = {}, {}\n\n # Read single series\n for series_num, series_lungs_map in lungs_map.items():\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape[series_num])\n\n # Combine the bones to the base map\n series_bones_data = bones_data[series_num]\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data[series_num]\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data[series_num]\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Read the lungless CT data and lungs data\n series_ct_data = lungless_ct[series_num]\n series_lungs = lungs_data[series_num]\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n series_map = np.rollaxis(series_lungs_map[np.newaxis], axis=0, start=3)\n series_map = np.rollaxis(series_map, axis=3, start=0)\n\n series_ct = np.rollaxis(series_ct_data[np.newaxis], axis=0, start=3)\n series_ct = np.rollaxis(series_ct, axis=3, start=0)\n\n series_lungs = np.rollaxis(series_lungs[np.newaxis], axis=0, start=3)\n series_lungs = np.rollaxis(series_lungs, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, series_map), axis=3)\n target_map = np.concatenate((series_ct, series_lungs), axis=3)\n\n source_data[series_num] = source_map\n target_data[series_num] = target_map\n\n # Cache the data\n pat_obj.source_data = source_data\n pat_obj.target_data = target_data\n return source_data\n\n def UMM_label_map(self, pat_obj):\n \"\"\"Creates the label map for UMM dataset.\n\n :param pat_obj: The object of UMM class\n :return: source_data (UMM)\n \"\"\"\n # Initialize the parameters\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n\n if not isinstance(lungs_map, dict):\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape)\n\n # Combine the bones to the base map\n series_bones_data = bones_data\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n lungs = np.rollaxis(lungs_map[np.newaxis], axis=0, start=3)\n lungs = np.rollaxis(lungs, axis=3, start=0)\n\n ct = np.rollaxis(lungless_ct[np.newaxis], axis=0, start=3)\n ct = np.rollaxis(ct, axis=3, start=0)\n\n lungs_ct = np.rollaxis(lungs_data[np.newaxis], axis=0, start=3)\n lungs_ct = np.rollaxis(lungs_ct, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, lungs), axis=3)\n target_map = np.concatenate((ct, lungs_ct), axis=3)\n\n # Cache the data\n pat_obj.source_data = source_map\n pat_obj.target_data = target_map\n source_data = source_map\n else:\n source_data, target_data = {}, {}\n\n for series_date, series_lungs_map in lungs_map.items():\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape[series_date])\n\n # Combine the bones to the base map\n series_bones_data = bones_data[series_date]\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data[series_date]\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data[series_date]\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Read the lungless CT data and lungs data\n series_ct_data = lungless_ct[series_date]\n series_lungs = lungs_data[series_date]\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n series_map = np.rollaxis(series_lungs_map[np.newaxis], axis=0, start=3)\n series_map = np.rollaxis(series_map, axis=3, start=0)\n\n series_ct = np.rollaxis(series_ct_data[np.newaxis], axis=0, start=3)\n series_ct = np.rollaxis(series_ct, axis=3, start=0)\n\n series_lungs = np.rollaxis(series_lungs[np.newaxis], axis=0, start=3)\n series_lungs = np.rollaxis(series_lungs, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, series_map), axis=3)\n target_map = np.concatenate((series_ct, series_lungs), axis=3)\n\n source_data[series_date] = source_map\n target_data[series_date] = target_map\n\n # Cache the data\n pat_obj.source_data = source_data\n pat_obj.target_data = target_data\n return source_data\n\n def UKSH_label_map(self, pat_obj):\n \"\"\"Creates the label map for UKSH dataset.\n\n :param pat_obj: Object of UKSH class\n :return: source_data (UKSH)\n \"\"\"\n # Initialize the parameters\n pat_obj.source_data = None\n pat_obj.target_data = None\n lungs_map = pat_obj.lungs_bin_map\n lungless_ct = pat_obj.lungless_ct\n lungs_data = pat_obj.lungs_ct_data\n bones_data = pat_obj.bones_bin_map\n tissues_data = pat_obj.tissues_bin_map\n fats_data = pat_obj.fats_bin_map\n\n # Initialize empty base map\n base_map = np.zeros(pat_obj.data_shape)\n\n # Combine the bones to the base map\n series_bones_data = bones_data\n base_map = base_map + (series_bones_data * self.bones_val)\n\n # Combine the soft tissues to the base map\n series_tissues_data = tissues_data\n base_map = base_map + (series_tissues_data * self.tissue_val)\n\n # Combine the fats to the base map\n series_fats_data = fats_data\n base_map = base_map + (series_fats_data * self.fats_val)\n\n # Roll the axis to (num samples, ht, wt, ch)\n base_map = np.rollaxis(base_map[np.newaxis], axis=0, start=3)\n base_map = np.rollaxis(base_map, axis=3, start=0)\n\n lungs = np.rollaxis(lungs_map[np.newaxis], axis=0, start=3)\n lungs = np.rollaxis(lungs, axis=3, start=0)\n\n ct = np.rollaxis(lungless_ct[np.newaxis], axis=0, start=3)\n ct = np.rollaxis(ct, axis=3, start=0)\n\n lungs_ct = np.rollaxis(lungs_data[np.newaxis], axis=0, start=3)\n lungs_ct = np.rollaxis(lungs_ct, axis=3, start=0)\n\n # Create the source and target map\n source_map = np.concatenate((base_map, lungs), axis=3)\n target_map = np.concatenate((ct, lungs_ct), axis=3)\n\n # Cache the data\n pat_obj.source_data = source_map\n pat_obj.target_data = target_map\n return source_map\n\n def full_label_map(self, pat_obj, bones_threshold=150, tissues_threshold=0, fats_threshold=-400):\n \"\"\"Creates the label map using all the binary maps.\n\n :param pat_obj: Object of either LTRC, UMM or UKSH class\n :param bones_threshold: The threshold value to separate the bone from CT image (Default is 150)\n :param tissues_threshold: The threshold value to separate the soft tissue from CT image (Default is 0)\n :param fats_threshold: The threshold value to separate the fats and muscles from CT image (Default is -400)\n :return: full label map and instance to the binary map (i.e. 'self')\n \"\"\"\n assert (isinstance(pat_obj, Dataset)), 'Object is not instance of Dataset'\n\n # Check if all binary maps are available\n if hasattr(pat_obj, 'lungs_bin_map') is False or self.recreate_lungs is True:\n pat_obj.lungs_bin_map = Lungs(pat_obj, emphysema_va1=self.emphysema_va1, ventilated_val=self.ventilated_val,\n poorly_vent_val=self.poorly_vent_val, atelectatic_val=self.atelectatic_val)\\\n .binary_map().pat_obj.lungs_bin_map\n if hasattr(pat_obj, 'bones_bin_map') is False or bones_threshold != self._bones_thres:\n pat_obj.bones_bin_map = Bones(pat_obj, bones_threshold).binary_map().pat_obj.bones_bin_map\n if hasattr(pat_obj, 'tissues_bin_map') is False or tissues_threshold != self._tissues_thres:\n pat_obj.tissues_bin_map = Tissues(pat_obj, tissues_threshold).binary_map().pat_obj.tissues_bin_map\n if hasattr(pat_obj, 'fats_bin_map') is False or fats_threshold != self._fats_thres:\n pat_obj.fats_bin_map = Fats(pat_obj, fats_threshold).binary_map().pat_obj.fats_bin_map\n if hasattr(pat_obj, 'lungless_ct') is False:\n pat_obj.lungless_ct = LunglessCT(pat_obj).binary_map().pat_obj.lungless_ct\n\n if pat_obj.data_name == 'LTRC':\n print('\\nCreating Label Map [LTRC]')\n _ = self.LTRC_label_map(pat_obj)\n print('\\nLabel Map [LTRC] created\\n')\n elif pat_obj.data_name == 'UMM':\n print('\\nCreating Label Map [UMM]')\n _ = self.UMM_label_map(pat_obj)\n print('\\nLabel Map [UMM] created\\n')\n elif pat_obj.data_name == 'UKSH':\n print('\\nCreating Label Map [UKSH]')\n _ = self.UKSH_label_map(pat_obj)\n print('\\nLabel Map [UKSH] created\\n')\n return self\n\n @property\n def print_parameters(self):\n print(\"\\nEmphysema Values: {val}\".format(val=self.emphysema_va1))\n print(\"Ventilated Values: {val}\".format(val=self.ventilated_val))\n print(\"Poorly Vent Values: {val}\".format(val=self.poorly_vent_val))\n print(\"Atelectatic Values: {val}\".format(val=self.atelectatic_val))\n pass\n","sub_path":"Processing/PreProcess.py","file_name":"PreProcess.py","file_ext":"py","file_size_in_byte":14321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"115288513","text":"__author__ = 'User'\n\nfrom lxml import html\nimport requests\nimport re\nfrom nltk import pos_tag, word_tokenize\nimport nltk\nimport string\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nfrom math import log10\nimport time\n\n\"\"\"\nDear un-hebrew speakers:\n'Tmura' is 'Grammatical modifier': an element that describes the object in sentence.\nWe love the name 'Tmura', So we use it.\n\nfor example:\nwithout Tmura: Lummie and Arad study in Magshimim\nwith Tmura: Lummie and Arad study in Magshimim, The national cyber project\n\"\"\"\n\ndef cleanText(sen):\n for ch in string.punctuation:\n sentence = sentence.replace(ch, '')\n return sentence\n\n\n\"\"\"\nGets a sentence (that contains a tmura) and writes it into the tmura.txt file, so we will have a corpus\n\"\"\"\ndef writeToOurCorpus(sentence):\n text_file = open(\"tmura.txt\", \"a\")\n text_file.write(sentence + \"\\n\")\n text_file.close()\n\n\n\"\"\"\n Gets a word, finds its page in wordnet and downloades it. Returns a correct HTML document,\n which means the parent node is , and there is a body and possibly a head\n\"\"\"\ndef downloadPage(word):\n search = \"http://wordnetweb.princeton.edu/perl/webwn?s=\"\n search += word\n search += \"&sub=Search+WordNet&o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&h=0\" # Builds the url\n page = requests.get(search) # Get page\n return html.fromstring(page.content) # Fromstring creates the correct HTML document\n\n\"\"\"\n Gets a word, gets its html page in wordnet (using downloadPage(word)), and returns the tmura of the word.\n\"\"\"\ndef getTmura(word):\n tree = downloadPage(word) # Gets the page data\n words = tree.xpath(\"//div[@class='form']/ul/li/text()\") #Gets only the text\n theWord = []\n for i in words:\n if (i != ', '): # We want to take only the first tmura and to clear all of the ', '\n theWord = i\n break\n if (theWord != []): # If found a tmura\n theWord = theWord.split(';')[0].replace(\" (\", \"\") # Cleans the tmura from '(' and ')' in the first explenation\n theWord = theWord.split(';')[0].replace(\")\", \"\")\n return theWord\n else: # If didn't find a tmura\n return \"not found\"\n\n\n\"\"\"\n Gets a word, pharses it and finds it tmure. Gets only nouns!!!\n Returns the original word and the tmura- word: tmura\n\"\"\"\ndef findTmura(word):\n the_tmura = word + \": \" + getTmura(word.replace(\" \", \"+\"))\n #writeToOurCorpus(the_tmura) # Olny if we want to put it in our corpus\n return the_tmura\n\n\n\"\"\"\n It must be a class, so we can call it.\n\"\"\"\n\nclass Modifier(object):\n def change_sentence(self):\n text = nltk.tokenize.word_tokenize(self._sentence)\n changed = False\n for cur in nltk.pos_tag(text):\n if (cur[1] == \"NN\" or cur[1] == \"NNP\" or cur[1] == \"RPR\"):\n if getTmura(cur[0]) != \"not found\" and changed == False:\n rep = cur[0] + \", \" + getTmura(cur[0]) + \", \"\n self._sentence = self._sentence.replace(cur[0], rep)\n changed = True\n #print(\"Tmura: \", self._sentence)\n return self._sentence\n\n def __init__(self, sentence):\n \"\"\"\n :param word: sentence\n :return: sentence with tmura\n \"\"\"\n self._sentence = sentence\n return None\n\n\ndef main():\n with open(\"newSent.txt\", 'w') as newF:\n with open(\"sentences.txt\", 'r') as f:\n sentence = f.read()\n f.close()\n sentences = sentence.split('\\n')\n for sent in sentences:\n print(Modifier(sent).change_sentence)\n newF.write(Modifier(sent).change_sentence + \"\\n\")\n\n newF.close()\n\n #print change_sentence(\"Ryan started playing hockey at a very young age\")\n #sen = \"People who are brave and who take risks are more, successful-than people who are do things safely all the time\"\n #sen = cleanText(sen)\n #print sen\n\n\n\n#if __name__ == '__main__':\n # main()","sub_path":"Run/tmura.py","file_name":"tmura.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"389559221","text":"import sys\nimport os.path\nimport json\nimport traceback\n\n# userid-|--|-email-|-hash-|-hint-|--\n\ndef main():\n if len(sys.argv) <= 1:\n print(\"Not enough arguments; please specify the file you want to parse.\")\n return 1\n\n filename = sys.argv[1]\n \n if not os.path.isfile(filename):\n print (\"The file you provided does not exist.\")\n return 1\n\n with open(filename) as f:\n for line in f:\n line = line.strip()\n d = '-|-'\n\n # Some lines are empty, and some don't have proper formatting, so skip those\n if (len(line) == 0) or (d not in line):\n continue\n\n # Some lines are split over two lines for some reason, so we'll check\n # if the line ends with the terminating string, and if it doesn't,\n # grab the next line and concat it to the current one\n if not line.endswith('|--'):\n line += next(f).strip()\n\n try:\n print(BreachItem(line.split(d)[0], line.split(d)[2].lower(), line.split(d)[3], line.split(d)[4]).toJSON())\n except StopIteration:\n print(\"We seem to have reached the end of the file\", file=sys.stderr)\n print(traceback.format_exc())\n quit()\n except Exception as e:\n print(traceback.format_exc())\n print(line, file=sys.stderr)\n quit()\n\n return 0\n\nclass BreachItem:\n def __init__(self, user_id, email, password_encrypted_base64, hint):\n self.username = email if '@' not in email else '' \n self.alias = email.split('@')[0] if '@' in email else ''\n self.domain = email.split('@')[1] if '@' in email else ''\n self.password_encrypted_base64 = password_encrypted_base64\n self.hint = hint\n self.user_id = user_id\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, \n sort_keys=True)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"adobe.py","file_name":"adobe.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"600432196","text":"import turtle\nimport winsound\n\nfrom playsound import playsound\n\nwn = turtle.Screen()\nwn.title(\"Pong\")\nwn.bgcolor(\"black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\n\n# left paddle\npaddle_left = turtle.Turtle()\npaddle_left.speed(0)\npaddle_left.shape(\"square\")\npaddle_left.color(\"red\")\npaddle_left.shapesize(stretch_wid=5, stretch_len=1)\npaddle_left.penup()\npaddle_left.goto(-350, 0)\n\n# right paddle\npaddle_right = turtle.Turtle()\npaddle_right.speed(0)\npaddle_right.shape(\"square\")\npaddle_right.color(\"blue\")\npaddle_right.shapesize(stretch_wid=5, stretch_len=1)\npaddle_right.penup()\npaddle_right.goto(350, 0)\n\n# Ball\nball = turtle.Turtle()\nball.speed(0)\nball.shape(\"square\")\nball.color(\"white\")\nball.penup()\nball.goto(0, 0)\nball.dx = 0.2\nball.dy = -0.2\n\n# Score\nscore_p1 = 0\nscore_p2 = 0\n# pen\npen = turtle.Turtle()\npen.speed(0)\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0, 260)\npen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n\n# Movements\ndef paddle_left_up():\n y = paddle_left.ycor()\n y += 20\n paddle_left.sety(y)\n\ndef paddle_left_down():\n y = paddle_left.ycor()\n y -= 20\n paddle_left.sety(y)\n\ndef paddle_right_up():\n y = paddle_right.ycor()\n y += 20\n paddle_right.sety(y)\n\ndef paddle_right_down():\n y = paddle_right.ycor()\n y -= 20\n paddle_right.sety(y)\n\n# Keyboard binding\nwn.listen()\nwn.onkeypress(paddle_left_up, \"w\")\nwn.onkeypress(paddle_left_down, \"s\")\nwn.onkeypress(paddle_right_up, \"p\")\nwn.onkeypress(paddle_right_down, \"l\")\n\n# Main game loop\nwhile True:\n wn.update()\n # ball\n ball.setx(ball.xcor() + ball.dx)\n ball.sety(ball.ycor() + ball.dy)\n # border\n if ball.ycor() > 290:\n ball.sety(290)\n ball.dy *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.ycor() < -290:\n ball.sety(-290)\n ball.dy *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.xcor() > 390:\n ball.setx(390)\n ball.dx *= -1\n score_p1 += 1\n pen.clear()\n pen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n if ball.xcor() < -390:\n ball.setx(-390)\n ball.dx *= -1\n score_p2 += 1\n pen.clear()\n pen.write(\"Player1: {} Player2: {}\".format(score_p1, score_p2), align=\"center\", font=(\"Courier\", 24, \"normal\"))\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n\n # paddle and ball\n if (ball.xcor() >340 and ball.xcor() < 350) and (ball.ycor() < paddle_right.ycor() + 50 and ball.ycor() >paddle_right.ycor()-50):\n ball.setx(340)\n ball.dx *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)\n\n if (ball.xcor() <-340 and ball.xcor() > -350) and (ball.ycor() < paddle_left.ycor() + 50 and ball.ycor() >paddle_left.ycor()-50):\n ball.setx(-340)\n ball.dx *= -1\n winsound.PlaySound(\"bounce.wav\", winsound.SND_ASYNC)","sub_path":"Pong.py","file_name":"Pong.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}
+{"seq_id":"577735662","text":"import dash_ace_editor\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_html_components as html\n\napp = dash.Dash(__name__)\n\napp.scripts.config.serve_locally = True\napp.css.config.serve_locally = True\n\napp.layout = html.Div([\n dash_ace_editor.DashAceEditor(\n id='input',\n value='select * from my_table;',\n customCompletion=[{'name':\"jakies_dlugie_pole\", 'type':'table'},\n {'name':\"bar\", 'type':'field'},\n {'name':\"baz\", 'type':'custom'}]\n ),\n html.Div(id='output')\n], style={'width':'400px'})\n\n@app.callback(Output('output', 'children'), [Input('input', 'value')])\ndef display_output(value):\n return 'You have entered {}'.format(value)\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"usage.py","file_name":"usage.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}