', start_introduction + 1)\r\n\r\n #If the page onl has introduction\r\n if '
' not in page:\r\n stop_introduction = page.find('', start_introduction + 1)\r\n else:\r\n pass\r\n\r\n raw_introduction = page[start_introduction : stop_introduction]\r\n return raw_introduction\r\n\r\n\r\n#Remove all the HTML tags from the introduction to get the pure text\r\n#Eliminate all the text inside '<' & '>'\r\ndef extract_pure_introduction(page):\r\n pure_introduction = (re.sub(r'<.+?>', '', page)) #From '<' to the next '>'\r\n return pure_introduction\r\n\r\n\r\n#Main Crawl function that calls all the above function and crawls the entire site sequentially\r\ndef get_introduction(url):\r\n raw_html = download_page(url)\r\n if raw_html == 'shabi':\r\n return \"None\"\r\n raw_introduction = extract_introduction(raw_html)\r\n pure_introduction = extract_pure_introduction(raw_introduction)\r\n return pure_introduction\r\n\r\n\r\ndf = pd.read_csv('label_foodtype.csv', header=None, names=['id', 'name'])\r\nrecipe_name = [re.sub(r'\\s+', '_', x.strip()) for x in df['name']]\r\nurl_prefix = \"https://en.wikipedia.org/wiki/\"\r\ntext = {}\r\nfor each in recipe_name:\r\n url = url_prefix + each\r\n intro = get_introduction(url)\r\n text[each] = intro\r\n time.sleep(2)\r\n\r\nwith open('wiki.json', 'w') as f:\r\n json.dump(text, f)\r\n\r\n","sub_path":"wiki-crawler.py","file_name":"wiki-crawler.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"488729515","text":"#a\n#b#せっかくなのでビットでフラグ管理してみる\na,b,c= map(int,input().split())\nflag =0\nif a+b==c:\n flag = flag | (1<<0)\nif a-b==c:\n flag = flag | (1<<1)\n\nif flag ==0b00:\n print(\"!\")\nif flag ==0b01:\n print(\"+\")\nif flag ==0b10:\n print(\"-\")\nif flag ==0b11:\n print(\"?\")\n\n#c\n# warshall_floyd法\ndef warshall_floyd(d):\n for k in range(n):\n for i in range(n):\n for j in range(n):\n d[i][j]= min(d[i][j],d[i][k]+d[k][j])\n return d\n\n# user n,pair m\nn,m = map(int,input().split())\nd = [[float(\"inf\") for i in range(n)] for i in range(n)]\n\nfor i in range(n):\n d[i][i] = 0\n\nfor i in range(m):\n a,b = map(int,input().split())\n a-=1\n b-=1\n d[a][b] = 1\n d[b][a] = 1\n\n# output 友達の友達=各ユーザの最��距離が2の数を数える\nfor i in warshall_floyd(d):\n print(i.count(2))","sub_path":"ABC016.py","file_name":"ABC016.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"260214054","text":"# Copyright 2020 Tier IV, Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport launch\nfrom launch_ros.actions import ComposableNodeContainer, LoadComposableNodes\nfrom launch_ros.descriptions import ComposableNode\nfrom launch.conditions import IfCondition, UnlessCondition\nfrom launch.actions import DeclareLaunchArgument\nfrom launch.substitutions import AnonName, LaunchConfiguration\n\n\ndef generate_launch_description():\n\n ns = 'euclidean_cluster'\n pkg = 'euclidean_cluster'\n\n # declare launch arguments\n input_pointcloud_param = DeclareLaunchArgument(\n 'input_pointcloud',\n default_value='/sensing/lidar/no_ground/pointcloud')\n\n input_map_param = DeclareLaunchArgument(\n 'input_map',\n default_value='/map/pointcloud_map')\n\n output_clusters_param = DeclareLaunchArgument(\n 'output_clusters',\n default_value='clusters')\n\n use_pointcloud_map_param = DeclareLaunchArgument(\n 'use_pointcloud_map',\n default_value='false')\n\n # set voxel grid filter as a component\n voxel_grid_filter_component = ComposableNode(\n package='voxel_grid_filter',\n plugin='pcl::VoxelGrid',\n name=AnonName('voxel_grid_filter'),\n remappings=[('input', LaunchConfiguration('input_pointcloud')),\n ('output', 'voxel_grid_filtered/pointcloud')],\n parameters=[\n {\n 'filter_field_name': 'z',\n 'filter_limit_min': 0.1,\n 'filter_limit_max': 2.5,\n 'filter_limit_negative': False,\n 'leaf_size': 0.1,\n 'input_frame': 'base_link',\n 'output_frame': 'base_link',\n }\n ]\n )\n\n # set compare map filter as a component\n compare_map_filter_component = ComposableNode(\n package='pointcloud_preprocessor',\n plugin='pointcloud_preprocessor::VoxelBasedCompareMapFilterComponent',\n name=AnonName('compare_map_filter'),\n remappings=[('input', 'voxel_grid_filtered/pointcloud'),\n ('map', LaunchConfiguration('input_map')),\n ('output', 'compare_map_filtered/pointcloud')]\n )\n\n use_map_euclidean_cluster_component = ComposableNode(\n package=pkg,\n plugin='euclidean_cluster::EuclideanClusterNodelet',\n name=AnonName('euclidean_cluster'),\n remappings=[('input', 'compare_map_filtered/pointcloud'),\n ('output', LaunchConfiguration('output_clusters'))],\n parameters=[\n {\n 'target_frame': 'base_link',\n 'use_height': False,\n 'tolerance': 0.7,\n 'min_cluster_size': 10,\n 'max_cluster_size': 1000\n }\n ]\n )\n\n disuse_map_euclidean_cluster_component = ComposableNode(\n package=pkg,\n plugin='euclidean_cluster::EuclideanClusterNodelet',\n name=AnonName('euclidean_cluster'),\n remappings=[('input', 'voxel_grid_filtered/pointcloud'),\n ('output', LaunchConfiguration('output_clusters'))],\n parameters=[\n {\n 'target_frame': 'base_link',\n 'use_height': False,\n 'tolerance': 0.7,\n 'min_cluster_size': 10,\n 'max_cluster_size': 1000\n }\n ]\n )\n\n container = ComposableNodeContainer(\n name='euclidean_cluster_container',\n namespace=ns,\n package='rclcpp_components',\n executable='component_container',\n composable_node_descriptions=[voxel_grid_filter_component],\n output='screen',\n )\n\n use_map_loader = LoadComposableNodes(\n composable_node_descriptions=[compare_map_filter_component,\n use_map_euclidean_cluster_component],\n target_container=container,\n condition=IfCondition(LaunchConfiguration('use_pointcloud_map')),\n )\n\n disuse_map_loader = LoadComposableNodes(\n composable_node_descriptions=[disuse_map_euclidean_cluster_component],\n target_container=container,\n condition=UnlessCondition(LaunchConfiguration('use_pointcloud_map')),\n )\n\n return launch.LaunchDescription([\n input_pointcloud_param,\n input_map_param,\n output_clusters_param,\n use_pointcloud_map_param,\n container,\n use_map_loader,\n disuse_map_loader\n ])\n","sub_path":"perception/object_recognition/detection/euclidean_cluster/launch/euclidean_cluster.launch.py","file_name":"euclidean_cluster.launch.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"558418752","text":"\n\nclass Dog:\n \"\"\"类\"\"\"\n def eat(self, food):\n \"\"\"行为\"\"\"\n print('小狗吃了', food)\n self.food = food\n\n def food_info(self):\n \"\"\"能否得到小狗上次吃的食物是什么\"\"\"\n print(self.food)\n\n\ndog1 = Dog()\ndog1.eat('骨头')\n\ndog2 = Dog()\ndog2.eat('包子')\n\ndog1.food_info()\ndog2.food_info()","sub_path":"pbase/day17/code/instance_method2.py","file_name":"instance_method2.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"429605347","text":"import re\nfrom re import sub\n\nclass RLEString(object):\n\n\tdef __init__(self, string):\n\t\t#check if the string is valid\n\t\tif not re.match('^[a-zA-Z]+$',string):\n\t\t\traise ValueError(\"Text has to consist of alphabetic characters (a-zA-Z))\")\n\t\telse:\n\t\t\tself.__mystring = string\n\t\t\tself.__iscompressed = False\n\n\n\tdef compress(self):\n\t\t#compress internal string\n\t\t#substitute function of regular expression in python\n\t\t#the (.)\\1* is the syntax for finding backreferences -> finding all equal charactes in a row\n\t\t#the sub() function substitutes for example: EEEEE -> 5E\n\t\tif self.__iscompressed:\n\t\t\traise RuntimeError(\"Mystring is already compressed!\")\n\t\telse:\n\t\t\tself.__mystring = sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), self.__mystring)\n\t\t\tself.__iscompressed = True\n\t\t\treturn self.__mystring\n\t\n\n\tdef decompress(self):\n\t\t#substitute function of regular expression in python\n\t\t#the caputuring groups (\\d+ = decimal digit group(1) and (\\D = any non digit character group(2)) has\n\t\t#to be placed in the resulting \"new\" mystring. group(0) would result in any kind of: (5E), group(1): 5, group(2): E\n\t\t#decompressed is the result: EEEEE\n\t\t#the sub() function, substitutes 5E with E*(int)5 -> EEEEE\n\t\tif not self.__iscompressed:\n\t\t\traise RuntimeError(\"Mystring is already decompressed!\")\n\t\telse:\n\t\t\tself.__mystring = sub(r'(\\d+)(\\D)', lambda m: m.group(2) * int(m.group(1)), self.__mystring)\n\t\t\tself.__iscompressed = False\n\t\t\treturn self.__mystring\n\n\n\tdef iscompressed(self):\n\t\tif self.__iscompressed:\n\t\t\treturn self.__iscompressed\n\n\tdef __str__(self):\n\t\treturn self.__mystring\n","sub_path":"ex9/RLEString.py","file_name":"RLEString.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"500432157","text":"\n\n#calss header\nclass _CHAMPION():\n\tdef __init__(self,): \n\t\tself.name = \"CHAMPION\"\n\t\tself.definitions = [u'someone or something, especially a person or animal, that has beaten all other competitors in a competition: ', u'a person who enthusiastically supports, defends, or fights for a person, belief, right, or principle: ']\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/_champion.py","file_name":"_champion.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"38460391","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 ('index', '0015_kontakt'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='kontakt',\n name='informacja',\n field=models.TextField(max_length=500, default=''),\n ),\n ]\n","sub_path":"index/migrations/0016_kontakt_informacja.py","file_name":"0016_kontakt_informacja.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"318334481","text":"# Problem: Implement a function to reverse a string (a list of characters), in-place.\n# Constraints\n# - Since we need to do this in place, it seems we cannot use the slice operator or reversed function?\n# - Correct\n# - Since Python strings are immutable, can we use a list instead?\n# - Yes\n\n\nclass ReverseString(object):\n\n def reverse(self, chars):\n if chars:\n size = len(chars)\n i = 0\n while i < size // 2:\n chars[i], chars[-1 - i] = chars[-1 - i], chars[i]\n i += 1\n return chars\n","sub_path":"arrays_strings/ReverseString/reverse_string.py","file_name":"reverse_string.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"499024930","text":"# =============================================================================\n# Minet Youtube Captions CLI Action\n# =============================================================================\n#\n# Action reading an input CSV file line by line and retrieving caption about\n# the given Youtube videos.\n#\nimport casanova\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nfrom minet.cli.utils import print_err\nfrom minet.utils import create_pool, request\n\nREPORT_HEADERS = [\n 'caption_text'\n]\n\nCAPTIONS_URL_TEMPLATE = 'https://www.youtube.com/api/timedtext?lang=%(lang)s&v=%(id)s'\n\n\ndef captions_action(namespace, output_file):\n\n enricher = casanova.enricher(\n namespace.file,\n output_file,\n keep=namespace.select,\n add=REPORT_HEADERS\n )\n\n loading_bar = tqdm(\n desc='Retrieving',\n dynamic_ncols=True,\n unit=' videos',\n )\n\n http = create_pool()\n\n for line, video_id in enricher.cells(namespace.column, with_rows=True):\n url_caption = CAPTIONS_URL_TEMPLATE % {'lang': namespace.lang, 'id': video_id}\n\n err, result_caption = request(http, url_caption)\n\n if err is not None:\n raise err\n elif result_caption.status >= 400:\n print_err('request error %s' % result_caption.status)\n enricher.writerow(line)\n else:\n soup = BeautifulSoup(result_caption.data, 'lxml')\n full_text = []\n\n caption_text = \" \".join(item.get_text() for item in soup.find_all('text'))\n\n enricher.writerow(line, [caption_text])\n\n loading_bar.update()\n","sub_path":"minet/cli/youtube/captions.py","file_name":"captions.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"563136217","text":"import pytest\nimport todo_app.view_model as view_model\nimport datetime\nimport todo_app.Task as task\n \n@pytest.fixture\ndef test_tasks():\n today = datetime.datetime.utcnow()\n yesterday = today - datetime.timedelta(days=1) \n task_list = [\n task.Task(1, 'To Do', 'Task1', today),\n task.Task(2, 'To Do', 'Task2', today),\n task.Task(3, 'Doing', 'Task3', today),\n task.Task(4, 'Doing', 'Task4', today),\n task.Task(5, 'Doing', 'Task5', today),\n task.Task(6, 'Done', 'Task6', today),\n task.Task(7, 'Done', 'Task7', today),\n task.Task(8, 'Done', 'Task8', today),\n task.Task(9, 'Done', 'Task8', today),\n task.Task(10, 'Done', 'Task10', yesterday),\n task.Task(11, 'Done', 'Task11', yesterday),\n task.Task(12, 'Done', 'Task12', yesterday)\n ]\n\n test_list = view_model.ViewModel(task_list)\n\n return test_list\n\n@pytest.fixture\ndef test_tasks_2():\n today = datetime.datetime.utcnow()\n yesterday = today - datetime.timedelta(days= 1)\n task_list = [ \n task.Task(1, 'To Do', 'Task1', today),\n task.Task(2, 'To Do', 'Task2', today),\n task.Task(3, 'Doing', 'Task3', today),\n task.Task(4, 'Doing', 'Task4', today),\n task.Task(5, 'Done', 'Task5', today),\n task.Task(6, 'Done', 'Task6', yesterday),\n task.Task(7, 'Done', 'Task7', yesterday),\n task.Task(8, 'Done', 'Task8', yesterday)\n ]\n \n test_list = view_model.ViewModel(task_list)\n\n return test_list\n\n@pytest.fixture\ndef test_tasks_3():\n today = datetime.datetime.utcnow()\n yesterday = today - datetime.timedelta(days= 1)\n task_list = [ \n task.Task(1, 'Doing', 'Task1', today),\n task.Task(2, 'Doing', 'Task2', today),\n task.Task(3, 'Done', 'Task3', today),\n task.Task(4, 'Done', 'Task4', today),\n task.Task(5, 'Done', 'Task5', today),\n task.Task(6, 'Done', 'Task6', yesterday),\n task.Task(7, 'Done', 'Task7', yesterday)\n ]\n\n test_list = view_model.ViewModel(task_list)\n\n return test_list\n\ndef test_to_do_items_count(test_tasks):\n todo = test_tasks.tasks_todo\n assert len(todo) == 2\n\ndef test_doing_items_count(test_tasks):\n doing = test_tasks.tasks_doing\n assert len(doing) == 3\n\ndef test_done_items_count(test_tasks):\n done = test_tasks.tasks_done\n assert len(done) == 7\n\ndef test_recent_done_tasks_count(test_tasks):\n today_tasks = test_tasks.tasks_recently_done\n assert len(today_tasks) == 4\n\ndef test_older_done_tasks_count(test_tasks):\n older_tasks = test_tasks.older_done_tasks\n assert len(older_tasks) == 3\n\ndef test_show_all_tasks_more_than_5(test_tasks):\n show_all = test_tasks.show_all_done_tasks\n assert len(show_all) == 4\n\ndef test_show_all_tasks_less_than_5(test_tasks_2):\n show_all = test_tasks_2.show_all_done_tasks\n assert len(show_all) == 4\n\ndef test_show_all_tasks_equal_to_5(test_tasks_3):\n show_all = test_tasks_3.show_all_done_tasks\n assert len(show_all) == 5","sub_path":"todo_app/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"109624232","text":"###\nimport sys\nimport time\nimport os\nimport binascii\nimport i2c\nimport sup\nimport struct\n\n##################################\n# VARIABLE DEFINITIONS\n## I2C address for the mcu \nMCU_ADDRESS = 0x53\n## i2c baudrate \nBAUDRATE = 100000\n## i2c bus that hosts the mcu \nBUSNUM = 2\n## unused \nMAX_RUNTIME = 120\n## delay between reading and writing \nREADWRITE_DELAY = 0.005\n## delay between writing and reading \nREAD_DELAY = 0.5\n\n\ndef initI2C():\n # initialize the I2C connection\n global MCU_I2C\n MCU_I2C = i2c.I2C(MCU_ADDRESS)\n\n\ndef get_sup_telem():\n print('SUPMCU TELEMETRY INITIATED')\n telem = []\n sendCMD('SUP:SELF START') # start selftest\n sendCMD('SUP:TEL? 5,DATA') # heartbeat\n time.sleep(READ_DELAY)\n temp = readI2C(13)\n time.sleep(READWRITE_DELAY)\n value = []\n if temp != -1:\n temp = temp[5:]\n value = struct.unpack('Q', temp)[0]\n else:\n temp = 'error'\n print('TELEM:HEARTBEAT: ' + str(value))\n telem.append(temp)\n sendCMD('SUP:TEL? 6,DATA') # context switches\n time.sleep(READ_DELAY)\n temp = readI2C(13)\n time.sleep(READWRITE_DELAY)\n value = []\n if temp != -1:\n temp = temp[5:]\n value = struct.unpack('Q', temp)[0]\n else:\n temp = 'error'\n print('TELEM:CONTEXT: ' + str(value))\n telem.append(temp)\n sendCMD('SUP:TEL? 7,DATA') # idle hooks\n time.sleep(READ_DELAY)\n temp = readI2C(13)\n time.sleep(READWRITE_DELAY)\n value = []\n if temp != -1:\n temp = temp[5:]\n value = struct.unpack('Q', temp)[0]\n else:\n temp = 'error'\n print('TELEM:IDLE: ' + str(value))\n telem.append(temp)\n sendCMD('SUP:TEL? 4,DATA') # selftest\n\n\ndef get_batt_telem():\n print('BATTERY TELEMETRY INITIATED')\n fields = [\n\t#[Field name, Field Number, Field Length, Field Type]\n ['at rate time to full',5,2,'H'],\n ['at rate time to empty',6,2,'H'],\n\n ['temperature',8,2,'H'],\n ['voltage',9,2,'H'],\n ['current',10,2,'h'],\n ['average current',11,2,'h'],\n \n ['relative state of charge',13,1,'B'],\n ['absolute state of charge',14,1,'B'],\n ['remaining capacity',15,2,'H'],\n ['full charge capacity',16,2,'H'],\n ['run time to empty',17,2,'H'],\n ['average time to empty',18,2,'H'],\n ['average time to full',19,2,'H'],\n ['charging current',20,2,'H'],\n ['charging voltage',21,2,'H'],\n ['battery status',22,2,'H'],\n ['cycle count',23,2,'H'],\n ['design capacity',24,2,'h'],\n ['design voltage',25,2,'h'],\n \n ['Extra Temp Sensor 1',48,2,'H'],\n ['Extra Temp Sensor 2',49,2,'H'],\n ['Extra Temp Sensor 3',50,2,'H'],\n ['Extra Temp Sensor 4',51,2,'H'],\n ['BM2 Status',52,1,'c'],\n # ['Permanent Failure Time',53,15,'c'],\n # ['Permanent Failure Registers',54,4,'c'],\n \n ['cell voltage 4',60,2,'H'],\n ['cell voltage 3',61,2,'H'],\n ['cell voltage 2',62,2,'H'],\n ['cell votlage 1',63,2,'H'],\n \n ['safety alert',80,2,'H'],\n ['safety status',81,2,'H'],\n ['pf alert',82,2,'H'],\n ['pf status',83,2,'H'],\n ['operation status',84,2,'H'],\n ['charging status',85,2,'H'],\n \n ['pack voltage',90,2,'H'],\n \n ['average voltage',93,2,'H'],\n ['ts1 temperature',94,2,'h'],\n ['ts2 temperature',95,2,'h'],\n \n ['safety alert 2',104,2,'H'],\n ['safety status 2',105,2,'H'],\n ['pf alert 2',106,2,'H'],\n ['pf status 2',107,2,'H'],\n\n ['temp range',114,2,'H']\n ]\n for each in fields:\n field_name = each[0]\n field_num = each[1]\n field_length = each[2]\n field_type = each[3]\n cmd = 'BM2:TEL? '+str(field_num)+',DATA'\n print(cmd)\n sendCMD(cmd) \n time.sleep(READ_DELAY)\n temp = readI2C(5 + field_length)\n time.sleep(READWRITE_DELAY)\n if temp != -1:\n print('hex: ' + binascii.hexlify(temp))\n print('binary: ' + bin(int(binascii.hexlify(temp[5:]), 16)))\n temp = temp[5:]\n temp = struct.unpack(field_type, temp)[0]\n else:\n temp = 'error'\n print(field_name+': ' + str(temp))\n\ndef get_pim_telem():\n print('PIM TELEMETRY INITIATED')\n fields = [\n\t#[Field name, Field Number, Field Length, Field Type]\n ['Channel Currents',0,8,'HHHH'],\n ['Channel Shunt Resister Values',1,8,'HHHH'],\n ['Channel Current Limits',2,8,'HHHH'],\n ['Channel Current Offsets for linear fit',3,8,'HHHH'],\n ['Channel Current Scaling Factors for linear fit',4,8,'HHHH'],\n ['PIM Status Register',5,1,'B'],\n ['PIM Overcurrent event log',6,8,'HHHH']\n ]\n for each in fields:\n field_name = each[0]\n field_num = each[1]\n field_length = each[2]\n field_type = each[3]\n cmd = 'PIM:TEL? '+str(field_num)+',DATA'\n print(cmd)\n sendCMD(cmd) \n time.sleep(READ_DELAY)\n temp = readI2C(5 + field_length)\n time.sleep(READWRITE_DELAY)\n if temp != -1:\n print('hex: ' + binascii.hexlify(temp))\n print('binary: ' + bin(int(binascii.hexlify(temp[5:]), 16)))\n temp = temp[5:]\n temp = struct.unpack(field_type, temp)\n else:\n temp = 'error'\n print(field_name+': ' + str(temp))\n \n \n \n \ndef sendCMD(cmd):\n initI2C()\n MCU_I2C.write(cmd)\n \n\ndef readI2C(length = 1):\n initI2C()\n telem = MCU_I2C.read(length)\n return telem\n\n\n\nget_sup_telem()\n\nget_pim_telem()\n\n# get_batt_telem()\n","sub_path":"SupMCU_Testing/test_sup.py","file_name":"test_sup.py","file_ext":"py","file_size_in_byte":5638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"653104170","text":"from django.conf.urls import patterns, url\nfrom . import views\n\nurlpatterns = patterns('',\n url(\n regex=r'^$',\n view=views.ExperienceListView.as_view(),\n name='list',\n ),\n url(\n regex=r'^(?P
[-\\w\\d]+)-(?P\\d+)/$',\n view=views.ExperienceDetailView.as_view(),\n name=\"detail\",\n ),\n)\n","sub_path":"experiences/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"33163765","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\"\"\"\n\ntime - nlogn\nspace- n to create a HEAP - NOT SURE ( Am i right ?)\n\"\"\"\n\n\nimport heapq\n\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n h = [] #list initialized to [] to create a heap\n head = dummy = ListNode(0) # dummy node\n for l in lists: # traverse all lists and create heap of n elements with logn height\n while l:\n heapq.heappush(h, l.val)\n l = l.next\n\n for i in range(len(h)): # pop elements 1 by 1 and create a new merged list\n dummy.next = ListNode(heapq.heappop(h))\n dummy = dummy.next\n return head.next\n\n\n\n\n\n","sub_path":"Problem-2.py","file_name":"Problem-2.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"383392753","text":"\"\"\"\nHere is the model for the Users App.\n\n\"\"\"\n#\ntry:\n import json\nexcept:\n import simplejson as json\n\n# Rammi imports\nfrom rammi.interface import DictableInstance, MongoJSONEncoder\n\nclass User(DictableInstance):\n _fields = (\"username\", \n \"first_name\", \n \"middle_name\", \n \"last_name\",\n \"email\",\n \"date_created\",\n \"open_id\",\n \"fav_courses\",\n )\n \n def to_json(self):\n return json.dumps(self.to_dict(), cls=MongoJSONEncoder)\n","sub_path":"resources/usersmodel.py","file_name":"usersmodel.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"478157623","text":"\nimport cv2\nimport numpy as np\n \npath = 'Small.png'\nimg = cv2.imread(path)\nimgContour = img.copy()\n \nimgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nimgBlur = cv2.GaussianBlur(imgGray,(7,7),1)\nimgCanny = cv2.Canny(imgBlur,50,50)\n\nhsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n#Blue color\nlower_blue = np.array([100,110,110])\nupper_blue = np.array([130,255,255])\nblue_mask = cv2.inRange(hsv_img, lower_blue, upper_blue)\nblue = cv2.bitwise_and(img, img, mask = blue_mask)\n\n# Red Color\nlower_red = np.array([0,100,20])\nupper_red = np.array([8,255,255])\nlower_red2 = np.array([175,100,20])\nupper_red2 = np.array([179,255,255])\n\nred_mask = cv2.inRange(hsv_img, lower_red, upper_red)\nred_mask2 = cv2.inRange(hsv_img, lower_red2, upper_red2)\nmask_red = cv2.add(red_mask, red_mask2)\nred = cv2.bitwise_and(img, img, mask = mask_red)\nmed = cv2.medianBlur(mask_red, 5)\ncv2.imwrite(\"ref_red.png\", med)\n\n#White color\nlower_white = np.array([250,250,250])\nupper_white = np.array([255,255,255])\nwhite_mask = cv2.inRange(hsv_img, lower_white, upper_white)\nwhite = cv2.bitwise_and(img, img, mask = white_mask)\n\ndef getContours(img):\n\n contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n tri=0\n sqr=0\n cir=0\n area_tri=0\n area_sqr=0\n area_cir=0\n\n for cnt in contours:\n area = cv2.contourArea(cnt)\n #print(area)\n\n if area>10:\n cv2.drawContours(imgContour, cnt, -1, (0, 255, 0), 1)\n peri = cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt,0.02*peri,True)\n #print(len(approx))\n x, y, w, h = cv2.boundingRect(approx)\n \n #if objCor >=3 and objCor <=3.5:\n if len(approx)==3: \n tri+=1\n area_tri+=area+area\n objectType=\"Tri\"\n\n elif len(approx)==4:\n sqr+=1\n area_sqr=area+area\n objectType=\"Squ\"\n\n elif len(approx)>5: \n cir+=1\n area_cir=area+area\n objectType=\"Cir\"\n\n else:objectType=\"None\"\n \n cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)\n #Put text\n cv2.putText(imgContour,objectType,\n (x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.4,\n (0,0,0),2)\n\n totaltri=(tri)\n totalsqr=(sqr)\n totalcir=(cir)\n totalfig=tri+sqr+cir\n total_area_tri=area_tri\n total_area_sqr=area_sqr\n total_area_cir=area_cir\n total_area = total_area_tri+total_area_sqr+total_area_cir\n print(\"--------------------------------- Number of figures ---------------------------------\")\n print(\"Total Number of Triangles: \", totaltri)\n print(\"Total Number of Squares: \", totalsqr)\n print(\"Total Number of Circles: \", totalcir)\n print(\"Total Number of Figures\", totalfig)\n print(\"--------------------------------- Number of areas ---------------------------------\")\n print(\"Total Area of Triangles: \", total_area_tri)\n print(\"Total Area of Squares: \", total_area_sqr)\n print(\"Total Area of Circles: \", total_area_cir)\n print(\"Total Area of Figures: \", total_area)\n\n\ncv2.imshow('Color Segmentation: Red', red)\ncv2.imshow('Color Segmentation: Blue', blue)\n\ngetContours(imgCanny)\nimgBlank = np.zeros_like(img)\ncv2.imshow(\"Final\", imgContour)\n\n#print(tri)\n#print(sqr)\n#print(cir)\ncv2.waitKey(0)\n","sub_path":"final_project/Code1.py","file_name":"Code1.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"315757741","text":"import csv\nimport json\nimport sys\nfrom datetime import datetime\nfrom os import path\n\nimport pandas as pd\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import QSize, Qt\nfrom PyQt5.QtGui import QColor, QDoubleValidator, QIcon, QPalette\nfrom PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog,\n QGroupBox, QHeaderView, QLabel, QLineEdit,\n QMessageBox, QPushButton, QTableWidget,\n QTableWidgetItem, QTabWidget, QVBoxLayout,\n QWidget)\n\n\ndef dark_mode(app):\n \"\"\"\n Set the colour palette of an app to a custom dark mode theme.\n\n Parameters\n ----------\n app : PyQt5.QtWidgets.QApplication\n The Qt App object\n\n Returns\n -------\n PyQt5.QtWidgets.QApplication\n The Qt app with the dark mode theme applied.\n \"\"\"\n palette = QPalette()\n palette.setColor(QPalette.Window, QColor(30, 30, 30))\n palette.setColor(QPalette.WindowText, QColor(225, 225, 225))\n palette.setColor(QPalette.Light, Qt.white)\n palette.setColor(QPalette.Midlight, QColor(225, 225, 225))\n palette.setColor(QPalette.Dark, QColor(65, 65, 65))\n palette.setColor(QPalette.Mid, QColor(160, 160, 160))\n palette.setColor(QPalette.BrightText, QColor(255, 51, 51))\n palette.setColor(QPalette.Button, QColor(40, 40, 40))\n palette.setColor(QPalette.Base, QColor(65, 65, 65))\n palette.setColor(QPalette.AlternateBase, QColor(50, 50, 50))\n palette.setColor(QPalette.ToolTipBase, Qt.white)\n palette.setColor(QPalette.ToolTipText, Qt.white)\n palette.setColor(QPalette.Text, QColor(225, 225, 225))\n palette.setColor(QPalette.ButtonText, QColor(225, 225, 225))\n palette.setColor(QPalette.Link, QColor(42, 130, 218))\n palette.setColor(QPalette.Highlight, QColor(42, 130, 218))\n palette.setColor(QPalette.HighlightedText, Qt.black)\n app.setPalette(palette)\n return app\n\n\nclass WeightLog():\n \"\"\"\n Main class for storing both the Qt app and database, with functions\n that act on both objects.\n \"\"\"\n\n def __init__(self, settings):\n self.settings = settings\n # self.df = pd.read_csv(self.settings['database_path'], encoding='utf-8')\n self.tabdialog = Tab(settings)\n self.tabdialog.show()\n\n\nclass Tab(QDialog):\n \"\"\"\n Child class of a Qt dialog window. Where a dialog window is a top-level\n window mostly used for short-term tasks and brief communications with\n the user.\n\n Parameters\n ----------\n QDialog : PyQt5.QtWidgets.QDialog\n The main Qt dialog window which stores the individual tabs of the\n programme.\n \"\"\"\n\n def __init__(self, settings):\n super().__init__()\n self.setWindowTitle(\"Body Weight Log\")\n self.setWindowIcon(QIcon(\"icon.png\"))\n vbox = QVBoxLayout()\n tabWidget = QTabWidget()\n\n font = tabWidget.font()\n font.setPointSize(settings['font_point_size'])\n tabWidget.setFont(font)\n self.setMinimumSize(\n QSize(\n settings['WindowWidth'],\n settings['WindowHeight']))\n\n tabWidget.addTab(TabAdd(settings), \"Add data\")\n tabWidget.addTab(TabCSV(settings), \"View table\")\n tabWidget.addTab(TabPlotting(settings), \"Plot data\")\n vbox.addWidget(tabWidget)\n self.setLayout(vbox)\n\n\nclass TabAdd(QWidget):\n \"\"\"\n Child class of Qt QWidget object. This class represents the first\n tab of the user interface which contains the database additional\n functionalilty.\n\n Parameters\n ----------\n QWidget : PyQt5.QtWidgets.QWidget\n The widget is the atom of the user interface.\n \"\"\"\n\n def __init__(self, settings):\n \"\"\"\n Setup the \"Add data\" applicaiton tab.\n\n Parameters\n ----------\n settings : dict\n Settings dict imported from the app settings.json file.\n \"\"\"\n super().__init__()\n self.settings = settings\n self.font_size = settings['font_point_size']\n weightlabel = QLabel(\"Weight (kg):\")\n self.weight_edit = QLineEdit()\n self.only_floats = QDoubleValidator()\n self.weight_edit.setValidator(self.only_floats)\n self.weight_edit.setPlaceholderText(self.last_measurement())\n\n date = QLabel(\"Date:\")\n self.date_edit = QLineEdit()\n self.date_edit.setText(datetime.today().strftime(\"%Y-%m-%d\"))\n\n addr = QLabel(\"Comment:\")\n self.comment_edit = QLineEdit()\n self.comment_edit.setPlaceholderText(\"Optional\")\n\n addval = QPushButton(\"Add value\")\n addval.clicked.connect(self.clickMethod)\n\n vbox = QVBoxLayout()\n vbox.setContentsMargins(30, 30, 30, 30)\n vbox.addWidget(weightlabel)\n vbox.addWidget(self.weight_edit)\n vbox.addWidget(date)\n vbox.addWidget(self.date_edit)\n vbox.addWidget(addr)\n vbox.addWidget(self.comment_edit)\n vbox.addStretch(30)\n vbox.addWidget(addval)\n self.setLayout(vbox)\n\n def last_measurement(self):\n \"\"\"\n Get the last weight value entered into the database.\n\n Returns\n -------\n str\n Last measured weight in kg.\n \"\"\"\n with open(self.settings['database_path'], newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\n for entry in reversed(data):\n if entry[1] != '':\n return str(entry[1])\n return ''\n\n def date_already_has_data(self):\n new_val = self.date_edit.text()\n with open(self.settings['database_path'], newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\n\n for entry in reversed(data):\n if entry[1] == new_val:\n True\n return False\n\n def date_format_correct(self):\n \"\"\"\n Check that date entered conforms to \"%Y-%m-%d\" format.\n\n Returns\n -------\n bool\n True if date is of a valid format, else False.\n \"\"\"\n valid_format = True\n try:\n new_val = self.date_edit.text()\n datetime_object = datetime.strptime(new_val, \"%Y-%m-%d\")\n except BaseException:\n valid_format = False\n return valid_format\n\n def date_temporal_paradox_free(self):\n \"\"\"\n Checks that the date entered is not after todays date. You can't know\n tommorrows weight if you haven't measured it yet.\n\n Returns\n -------\n bool\n True if date is not a temporal paradox, else False.\n \"\"\"\n valid_date = True\n new_val = self.date_edit.text()\n datetime_object = datetime.strptime(new_val, \"%Y-%m-%d\")\n\n if datetime_object > datetime.now():\n valid_date = False\n return valid_date\n\n def clickMethod(self):\n \"\"\"\n Defines the response to the \"Add value\" button.\n \"\"\"\n if not self.date_format_correct():\n msg = QMessageBox()\n msg.setWindowTitle(\"Warning\")\n msg.setWindowIcon(QIcon(\"icon.png\"))\n msg.setIcon(QMessageBox.Warning)\n\n font = msg.font()\n font.setPointSize(self.font_size)\n msg.setFont(font)\n\n msg.setText(\"Date entered in incorrect format.\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.setDefaultButton(QMessageBox.Ok)\n\n x = msg.exec_() # show our messagebox\n\n elif not self.date_temporal_paradox_free():\n msg = QMessageBox()\n msg.setWindowTitle(\"Warning\")\n msg.setWindowIcon(QIcon(\"icon.png\"))\n msg.setIcon(QMessageBox.Warning)\n\n font = msg.font()\n font.setPointSize(self.font_size)\n msg.setFont(font)\n\n msg.setText(\n \"Date entered is invalid since it is after today's date.\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.setDefaultButton(QMessageBox.Ok)\n\n x = msg.exec_() # show our messagebox\n\n elif not self.date_already_has_data():\n msg = QMessageBox()\n msg.setWindowTitle(\"Warning\")\n msg.setWindowIcon(QIcon(\"icon.png\"))\n msg.setIcon(QMessageBox.Warning)\n\n font = msg.font()\n font.setPointSize(self.font_size)\n msg.setFont(font)\n\n msg.setText(\"Date entered already has a weight value of \"\n f\"{self.weight_edit.text()} in the database. Do you \"\n \"wish to override this value?\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msg.setDefaultButton(QMessageBox.Ok)\n msg.buttonClicked.connect(self.okay_button2)\n x = msg.exec_() # show our messagebox\n\n else:\n msg = QMessageBox()\n msg.setWindowTitle(\"New entry\")\n msg.setWindowIcon(QIcon(\"icon.png\"))\n font = msg.font()\n font.setPointSize(self.font_size)\n msg.setFont(font)\n msg.setText(\"New entry added to weight log\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msg.setDefaultButton(QMessageBox.Ok)\n msg.buttonClicked.connect(self.okay_button1)\n x = msg.exec_() # show our messagebox\n\n def okay_button1(self, i):\n \"\"\"\n Execute if okay button is pressed from AddTab when no warnings are\n presented.\n\n Parameters\n ----------\n i : PyQt5.QtWidgets.QPushButton\n Button class object\n \"\"\"\n if i.text() == \"OK\":\n print(\"Entry added\")\n\n def okay_button2(self, i):\n \"\"\"\n Execute if okay button is pressed from AddTab when entry for given \"\n \"date already exists in the database.\n\n Parameters\n ----------\n i : PyQt5.QtWidgets.QPushButton\n Button class object\n \"\"\"\n if i.text() == \"OK\":\n print(\"Entry overwritten\")\n\n\nclass PandasWidget(QTableWidget):\n \"\"\"\n Redifinition of the Qt QTableWidget class to implement an editable table\n view of the database.\n\n Parameters\n ----------\n QTableWidget : PyQt5.QtWidgets.QTableWidget\n Table widgets provide standard table display facilities for\n applications.\n \"\"\"\n\n def __init__(self, df):\n super().__init__()\n self.df = df\n self.setStyleSheet('font-size: 28px;')\n self.insert_data(df)\n\n self.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n def insert_data(self, data):\n \"\"\"\n Populate the table with the data from the weight database.\n\n Parameters\n ----------\n data : Pandas DataFrame\n The data to be displayed in the table.\n \"\"\"\n # set table dimension\n self.df = data\n nRows, nColumns = data.shape\n self.setColumnCount(nColumns)\n self.setRowCount(nRows)\n self.setHorizontalHeaderLabels(data.columns)\n\n # data insertion\n for i in range(self.rowCount()):\n for j in range(self.columnCount()):\n self.setItem(i, j, QTableWidgetItem(str(data.iloc[i, j])))\n\n # Enable cell updates\n self.cellChanged[int, int].connect(self.updateDF)\n\n self.scrollToBottom()\n\n def updateDF(self, row, column):\n \"\"\"\n Updates a specificed cell in the database.\n\n Parameters\n ----------\n row : int\n The database row index.\n column : int\n The database column index.\n \"\"\"\n text = self.item(row, column).text()\n self.df.iloc[row, column] = text\n\n\nclass TabCSV(QWidget):\n \"\"\"\n Child class of Qt QWidget object. This class represents the second tab in\n the application which presents a table of the weight database which can be\n inspected and edited by the user.\n\n Parameters\n ----------\n QWidget : PyQt5.QtWidgets.QWidget\n The widget is the atom of the user interface.\n \"\"\"\n\n def __init__(self, settings):\n super().__init__()\n self.settings = settings\n self.load_csv()\n\n mainLayout = QVBoxLayout()\n self.tableView = PandasWidget(pd.DataFrame())\n # self.tableView = PandasWidget(self.database)\n\n self.pushButtonLoad = QPushButton(\"Load csv\")\n self.pushButtonLoad.clicked.connect(self.reload_csv)\n\n self.pushButtonWrite = QPushButton(\"Write to csv\")\n self.pushButtonWrite.clicked.connect(self.write_csv)\n\n mainLayout.addWidget(self.tableView)\n mainLayout.addWidget(self.pushButtonLoad)\n mainLayout.addWidget(self.pushButtonWrite)\n self.setLayout(mainLayout)\n\n def load_csv(self):\n \"\"\"\n Load in the weight databse from the location specified in the\n settings json file.\n \"\"\"\n self.database = pd.read_csv(\n self.settings['database_path'],\n encoding='utf-8')\n\n def write_csv(self):\n \"\"\"\n Write to the weight databse in the location specified in the settings\n json file.\n \"\"\"\n self.tableView.df.to_csv('Data export.csv', index=False)\n print('CSV file exported')\n\n @QtCore.pyqtSlot()\n def reload_csv(self):\n \"\"\"\n Full function to load csv data and populate the table with the new\n data.\n \"\"\"\n self.load_csv()\n self.tableView.insert_data(self.database)\n self.update()\n\n\nclass TabPlotting(QWidget):\n \"\"\"\n Child class of Qt QWidget object. This class represents the final tab of\n the application which is used for plotting values in the weight database.\n\n Parameters\n ----------\n QWidget : PyQt5.QtWidgets.QWidget\n The widget is the atom of the user interface.\n \"\"\"\n\n def __init__(self, settings):\n \"\"\"\n Initialse the layout and user iterface of the plotting tab.\n\n Parameters\n ----------\n settings : dict\n Settings from the json settings file.\n \"\"\"\n super().__init__()\n self.settings = settings\n groupBox = QGroupBox(\"Select data range\")\n list = [\"1M\", \"3M\", \"6M\", \"YTD\", \"1Y\", \"MAX\"]\n combo = QComboBox()\n combo.addItems(list)\n vbox = QVBoxLayout()\n vbox.addWidget(combo)\n groupBox.setLayout(vbox)\n groupBox2 = QGroupBox(\"Plot options\")\n av7day = QCheckBox(\"7 day average\")\n av7day.setChecked(1)\n lineplot = QCheckBox(\"Lineplot\")\n plotlbs = QCheckBox(\"Plot in lbs\")\n\n vboxp = QVBoxLayout()\n vboxp.addWidget(av7day)\n vboxp.addWidget(lineplot)\n vboxp.addWidget(plotlbs)\n\n plotvals = QPushButton(\"Plot data\")\n\n groupBox2.setLayout(vboxp)\n mainLayout = QVBoxLayout()\n mainLayout.setContentsMargins(30, 30, 30, 30)\n mainLayout.addWidget(groupBox)\n mainLayout.addWidget(groupBox2)\n mainLayout.addStretch(30)\n mainLayout.addWidget(plotvals)\n self.setLayout(mainLayout)\n\n\ndef make_database(name):\n \"\"\"\n Create database if no current database exists.\n\n Parameters\n ----------\n name : str\n Name of database (must have .csv extension)\n e.g. my_database.csv\n\n \"\"\"\n if path.exists(name):\n return True\n else:\n headers = [['Date', 'Weight(kg)', 'Notes']]\n with open(name, 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(headers)\n return False\n\n\n# The main attraction\nif __name__ == \"__main__\":\n\n # Import settings\n with open('settings.json', 'r') as f:\n settings = json.load(f)\n\n # Create database if one doesn't exist\n db_exists = make_database(settings['database_path'])\n\n # Start the app\n app = QApplication(sys.argv)\n app.setStyle(\"Fusion\") # Force the style to be the same on all OSs\n app = dark_mode(app)\n weightlog = WeightLog(settings)\n app.exec()\n","sub_path":"scale_app.py","file_name":"scale_app.py","file_ext":"py","file_size_in_byte":16070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"607264488","text":"\n#####VecDyn query\n\n\n\n\n@auth.requires_login()\ndef vec_dyn_query():\n \"\"\"\n Controller to serve a searchable grid view of the vector dynamics\n datasets with a download function. We want to be able to download\n individual records, selected sets of records and all records\n covered by a query.\n\n The individual row / selected sets is handled by a download controller\n that grabs ids from the request variables and send back the data as\n a csv.\n\n The complete set of rows in a grid query is accessible to the export\n buttons within the grid code, so the download all option uses that\n mechanism but expands the rows to the datasets for each row before\n returning. Currently, this won't let you Download All for more than\n 50 MainID records.\n \"\"\"\n\n # control which fields available\n [setattr(f, 'readable', False) for f in db.taxon\n if f.name not in ('db.taxon.tax_species,db.taxon.tax_genus,'\n 'db.taxon.tax_family,db.taxon.tax_order')]\n # [setattr(f, 'readable', False) for f in db.StudyLocation\n # if f.name not in ('db.StudyLocation.Country,db.StudyLocation.CountyStateProvince')]\n # MainID is not made unreadable, so that it can be accessed by the export controller\n [setattr(f, 'readable', False) for f in db.study_data\n if f.name not in ('db.study_data.id, db.study_data.location_description')]\n\n # Add selectability checkboxes\n select = [('Download selected',\n lambda ids : redirect(URL('queries', 'vec_dyn_download', vars=dict(ids=ids))),\n 'btn btn-default')]\n\n # Adding an exporter that grabs all the data from a query,\n # the name _with_hidden_cols is needed to expose the MainID in the\n # rows passed to the exporter class. Note that nothing unreadable\n # can be exposed.\n export = dict(data_with_hidden_cols=(ExporterAll, 'Export All'),\n csv_with_hidden_cols=False,\n csv=False, xml=False, html=False, json=False,\n tsv_with_hidden_cols=False, tsv=False)\n\n # turn the MainID into a download link\n db.study_data.id.represent = lambda value, row: A(value, _href=URL(\"queries\",\"vec_dyn_download\",\n vars={'ids': row.study_data.id}))\n\n # get the grid\n grid = SQLFORM.grid((db.taxon.taxonID == db.study_data.taxon_id)&\n (db.gaul_admin_layers.ADM_CODE == db.study_data.location_ID),\n exportclasses=export,\n ignore_common_filters=True,\n field_id=db.study_data.id,\n fields= [db.study_data.id,\n db.taxon.tax_species, db.taxon.tax_genus,\n db.taxon.tax_family, db.taxon.tax_order,\n db.taxon.tax_class, db.taxon.tax_phylum,\n db.gaul_admin_layers.ADM0_NAME, db.gaul_admin_layers.ADM1_NAME,\n db.study_data.location_description],\n headers={'taxon.tax_species' : 'Taxon Name',\n 'taxon.tax_genus' : 'Genus',\n 'taxon.tax_family' : 'Family',\n 'taxon.tax_order' : 'Order',\n 'taxon.tax_class' : 'Class',\n 'taxon.tax_phylum' : 'Phylum',\n 'gaul_admin_layers.ADM0_NAME' : 'Country',\n 'gaul_admin_layers.ADM1_NAME' : 'Region',\n 'gaul_admin_layers.ADM2_NAME': 'County',\n 'study_data.id' : 'Dataset ID' },\n maxtextlength=100,\n selectable=select,\n deletable=False, editable=False, details=False, create=False)\n\n # The final bit of untidiness is the location of the buttons.\n # - The export 'menu' (a single button here) is at the bottom of the page.\n # This button doesn't submit a form, just calls the page again with _export_type\n # set, so we can simply move it.\n # - The Download selected button is more tricky: selectable turns the grid\n # table into a form, which the download selected button needs to be inside.\n # I've simply hidden it and added a fake button in the right location that\n # uses JS to press the real submit. Having a fake submit and using JS to submit\n # the form directly wasn't getting the request right, so this is easier!\n\n # The script we're setting up for is this:\n\n # \n\n # Create some buttons to add (one is just a link, masquerading\n # as a button, the other presses the hidden submit on the real form).\n # This code shouldn't run if no records are found by a search, since then\n # the export menu and the selectable form don't exist.\n exp_menu = grid.element('.w2p_export_menu')\n if exp_menu is not None:\n\n exp_menu = grid.element('.w2p_export_menu')\n exp_all = A(\"Download all\", _class=\"btn btn-default\",\n _href=exp_menu[1].attributes['_href'],\n _style='padding:6px 12px;line-height:20px')\n fake_exp_sel = INPUT(_value='Download selected', _type='submit',\n _class=\"btn btn-default\", _id='fake_exp_sel',\n _style='padding:6px 12px;line-height:20px')\n\n # add the buttons after the end of the web2py console form\n console = grid.element('.web2py_console')\n console[1].insert(1, CAT(exp_all, fake_exp_sel))\n\n # add an ID to the selection form, to allow JS to link the\n # new button to form submission\n sel_form = grid.element('.web2py_table form')\n sel_form['_id'] = 'select_form'\n\n\n # Delete the original export menu\n export_menu_idx = [x.attributes['_class'] for x in grid].index('w2p_export_menu')\n del grid[export_menu_idx]\n\n # hide the real export selected button and add an ID\n exp_sel = grid.element('.web2py_table .btn')\n exp_sel['_style'] = 'display:none;'\n exp_sel['_id'] = 'exp_sel'\n\n return dict(grid=grid)\n\ndef _get_data_csv(ids):\n \"\"\"\n Internal function that gets the required fields for downloading datasets\n for a given set of MainID ids and returns the data formatted as csv.\n\n This compilation is needed by both the dataset download controller\n and the Exporter class, so define here once and call from each.\n \"\"\"\n\n rows = db((db.study_data.id.belongs(ids) &\n (db.taxon.taxonID == db.study_data.taxon_id) &\n (db.gaul_admin_layers.ADM_CODE == db.study_data.location_ID) &\n (db.collection_info.id == db.study_data.collection_info_id) &\n (db.sample_data.study_data_id == db.study_data.id)),ignore_common_filters=True).select(\n db.study_data.title, db.gaul_admin_layers.ADM0_NAME, db.gaul_admin_layers.ADM1_NAME,db.gaul_admin_layers.ADM2_NAME,\n db.gaul_admin_layers.centroid_latitude, db.gaul_admin_layers.centroid_longitude,\n db.study_data.location_description,db.study_data.location_environment,\n db.study_data.study_lat_DD, db.study_data.study_long_DD, db.study_data.geo_datum,\n db.study_data.spatial_accuracy,db.study_data.location_extent,db.study_data.species_id_method,\n db.study_data.study_design,db.study_data.sampling_strategy,db.study_data.sampling_method,\n db.study_data.sampling_protocol,db.study_data.measurement_unit,db.study_data.study_collection_area,\n db.study_data.value_transform,db.taxon.tax_species, db.taxon.tax_genus, db.taxon.tax_family,\n db.taxon.tax_order, db.taxon.tax_class, db.taxon.tax_phylum,\n db.study_data.location_description,db.sample_data.sample_start_date, db.sample_data.sample_start_time,\n db.sample_data.sample_end_date, db.sample_data.sample_end_time, db.sample_data.value,\n db.sample_data.sample_info, db.sample_data.sample_name,db.sample_data.sample_sex,\n db.sample_data.sample_lat_DD, db.sample_data.sample_long_DD, db.collection_info.title,\n db.collection_info.collection_authority,db.collection_info.DOI,db.collection_info.publication_date,\n db.collection_info.description,db.collection_info.contact_name,db.collection_info.contact_email)\n return rows.as_csv()\n\n\ndef vec_dyn_download():\n\n \"\"\"\n Function to return the data of records matching the ids\n \"\"\"\n\n # Get the ids. If there are multiple ids, then we get a list,\n # and we need an iterable for belongs, so all we have to trap\n # is a single ID which comes in as a string\n ids = request.vars['ids']\n if isinstance(ids, str):\n ids = [ids]\n\n data = _get_data_csv(ids)\n\n # and now poke the text object out to the browser\n response.headers['Content-Type'] = 'text/csv'\n attachment = 'attachment;filename=vec_dyn_download_{}.txt'.format(datetime.date.today().isoformat())\n response.headers['Content-Disposition'] = attachment\n\n raise HTTP(200, data,\n **{'Content-Type':'text/csv',\n 'Content-Disposition':attachment + ';'})\n\n\nclass ExporterAll(object):\n\n \"\"\"\n Used to export all the data associated with rows in the grid\n \"\"\"\n\n file_ext = \"csv\"\n content_type = \"text/csv\"\n\n def __init__(self, rows):\n self.rows = rows\n\n def export(self):\n\n if self.rows:\n # expand rows to get full data and return that\n request.vars._export_filename = \"yourname\"\n ids = [rw.study_data.id for rw in self.rows]\n\n # currently simple check that we aren't trying to export too much\n if len(ids) > 50:\n return 'Download all is currently restricted to searches including fewer than 50 records.'\n else:\n data = _get_data_csv(ids)\n return data\n else:\n return\n","sub_path":"controllers/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":10357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"146881479","text":"\"\"\"Command line interface for semantic segmentation.\"\"\"\nfrom __future__ import annotations\n\nimport click\n\nfrom tiatoolbox.cli.common import (\n cli_batch_size,\n cli_file_type,\n cli_img_input,\n cli_masks,\n cli_mode,\n cli_num_loader_workers,\n cli_on_gpu,\n cli_output_path,\n cli_pretrained_model,\n cli_pretrained_weights,\n cli_verbose,\n cli_yaml_config_path,\n prepare_ioconfig_seg,\n prepare_model_cli,\n tiatoolbox_cli,\n)\n\n\n@tiatoolbox_cli.command()\n@cli_img_input()\n@cli_output_path(\n usage_help=\"Output directory where model predictions will be saved.\",\n default=\"semantic_segmentation\",\n)\n@cli_file_type(\n default=\"*.png, *.jpg, *.jpeg, *.tif, *.tiff, *.svs, *.ndpi, *.jp2, *.mrxs\",\n)\n@cli_mode(\n usage_help=\"Type of input file to process.\",\n default=\"wsi\",\n input_type=click.Choice([\"patch\", \"wsi\", \"tile\"], case_sensitive=False),\n)\n@cli_pretrained_model(default=\"fcn-tissue_mask\")\n@cli_pretrained_weights(default=None)\n@cli_on_gpu()\n@cli_batch_size()\n@cli_masks(default=None)\n@cli_yaml_config_path()\n@cli_num_loader_workers()\n@cli_verbose()\ndef semantic_segment(\n pretrained_model: str,\n pretrained_weights: str,\n img_input: str,\n file_types: str,\n masks: str | None,\n mode: str,\n output_path: str,\n batch_size: int,\n yaml_config_path: str,\n num_loader_workers: int,\n *,\n on_gpu: bool,\n verbose: bool,\n) -> None:\n \"\"\"Process an image/directory of input images with a patch classification CNN.\"\"\"\n from tiatoolbox.models import IOSegmentorConfig, SemanticSegmentor\n from tiatoolbox.utils import save_as_json\n\n files_all, masks_all, output_path = prepare_model_cli(\n img_input=img_input,\n output_path=output_path,\n masks=masks,\n file_types=file_types,\n )\n\n ioconfig = prepare_ioconfig_seg(\n IOSegmentorConfig,\n pretrained_weights,\n yaml_config_path,\n )\n\n predictor = SemanticSegmentor(\n pretrained_model=pretrained_model,\n pretrained_weights=pretrained_weights,\n batch_size=batch_size,\n num_loader_workers=num_loader_workers,\n verbose=verbose,\n )\n\n output = predictor.predict(\n imgs=files_all,\n masks=masks_all,\n mode=mode,\n on_gpu=on_gpu,\n save_dir=output_path,\n ioconfig=ioconfig,\n )\n\n save_as_json(output, str(output_path.joinpath(\"results.json\")))\n","sub_path":"tiatoolbox/cli/semantic_segment.py","file_name":"semantic_segment.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"60410759","text":"#!/usr/bin/python\n\n\"\"\"\n\nTODO:\n Put more care into what sort of data is inputted in the calculation of the fwhm. Maybe it's not a peak at all...\n Put all the comments above the functions as docstrings within the functions\n Think of how to deal with L: get from the size of the coefficients_vector or pass as parameter?\n Plotting routines should have control over x, y axis?\n Test convert_to_gnuplot and steady_pdf and stablish consistent functionality: write to file or plot? or both?\n When using np.max to get peak, maybe it's better to interpolate...\n Make plot_eigenfunction and plot_steady_pdf the same function\n\n Approach qualified as \"MINE\" does not work so far...\n HARDCODED size of stats[] output (i.e. number of statistics)\n\nREMARKS:\n Note commented out lines: import lmfit and the whole function fwhm_from_lorentzian() because computer in the office has\n an old version of scipy (0.10.6, and need minimum 0.11...) \n\n\"\"\"\n\nimport numpy as np\nfrom scipy.interpolate import UnivariateSpline\nimport lmfit \nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport scipy as sp\n\nimport math\nimport sys\nimport time \n\n# The following function is not very elegant: number of parameters hardcoded and initialization weird. Alternatives?\n# Use named tuple?\n# TODO: When I add a new statistic, I have to change here:\n# stats initialization (first line) and assignment of values\n# when called from run_over_L, we need to change there:\n# nump_output_stats, which has to be the same as the size of stats in get_stats\n# the format of the stats_summary_file, where we have to add a string (moreover, note that there 'L' also appears)\n# Maybe I could add L as well, since we can know it from the size of eigenvalues?\n\ndef get_stats(freq, power_spectrum, eigenvectors, eigenvalues):\n stats = np.zeros(7)\n L = int((np.sqrt(eigenvectors.shape[0]) - 1)/2)\n eigenvector1, eigenvalue1 = get_slowest_mode(eigenvectors, eigenvalues)\n peak_position, peak_value = get_peak_from_lorentzian_fit(freq, power_spectrum)\n stats[0] = L\n stats[1] = get_fwhm_from_lorentzian_fit(freq, power_spectrum) \n stats[2] = peak_position\n stats[3] = peak_value \n stats[4] = get_quality_factor(freq, power_spectrum)\n stats[5] = np.abs(np.real(eigenvalue1))\n stats[6] = np.abs(np.imag(eigenvalue1))\n\n # In case we want to use the data not obtained from the fit\n #stats[0] = get_fwhm(freq, power_spectrum) \n #stats[2] = get_peak_value(power_spectrum)\n return stats\n\n#def get_eigenvalues\n\ndef get_peak_value(y):\n \"\"\"Return the value of y at the peak for data containing a single peak\n TODO:\n This assumes there is a single maximum in y, which is usually the case for the power spectra seen so far. Need to be\n made more robust by finding local extrema. A possible solution can be found in\n http://stackoverflow.com/questions/4624970/finding-local-maxima-minima-with-numpy-in-a-1d-numpy-array\n\n Used only to get some sort of normalization to compare to rtol\n \"\"\"\n return np.max(y)\n\ndef get_peak_from_lorentzian_fit(x, y):\n \"\"\"Return the value of y at the peak for data containing a single peak using a double Lorentzian fit\"\"\"\n fit_result = fit_double_lorentzian(x, y)\n peak_position = fit_result.params.valuesdict()['positive_center']\n # Looks a little hacky but x only admits numpy arrays (we cannot simply do x=peak_position)\n peak_value = fit_result.eval(x=np.array([peak_position]))[0]\n return peak_position, peak_value \n\ndef get_quality_factor(x, y):\n \"\"\"Return the quality factor for data containing a single peak\"\"\"\n #return x[np.argmax(y)]/get_fwhm(x,y)\n return x[np.argmax(y)]/get_fwhm_from_lorentzian_fit(x,y)\n\ndef get_fwhm(x, y):\n \"\"\" Return FWHM for data containing a single peak\n Based on http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak\n It uses interpolation to find the right x-values for the half-maximum (even if they don't exist in the original array.\n\n Another possible implementation would be something like (google \"radpy fwhm\")\n truncated_data = x[where(y > np.max(y)/2)]\n fwhm = truncated_data[-1] - truncated_data[0]\n ... but will suffer if not too many data, interpolation is better\n\n It breaks for large values of the noise where a peak is barely visible. Included a small hack that works for\n intermediate values of the noise (0.5 < D < 1.0), but for larger noise the peak is at f = 0, and we are not talking\n any more of the fwhm of a peak in the power spectrum\n It will give error if the frequency window is not big enough to include the whole peak\n In general, fitting a Lorentzian is more robust!!\n \"\"\"\n\n # create a spline of x and y-np.max(y)/2 \n spline = UnivariateSpline(x, y - np.max(y)/2, s=0)\n x_peak = x[np.argmax(spline(x))]\n if len(spline.roots()) == 2:\n r1, r2 = spline.roots() # find the roots\n fwhm = r2 - r1\n elif len(spline.roots()) == 1 and x_peak < spline.roots()[0]:\n # Assume symmetry along peak, which is not always true...\n hwhm = spline.roots()[0] - x_peak\n fwhm = 2 * hwhm\n else:\n sys.exit(\"window not big enough\")\n\n #plt.plot(x,y)\n #plt.axvspan(r1, r2, facecolor='g', alpha=0.5)\n\n return fwhm\n\n\ndef get_fwhm_from_lorentzian_fit(x, y):\n \"\"\"\n Return FWHM for data containing a single peak using a double-Lorentzian fit\n\n It is thought for a one-sided power spectrum (which is real&even), so that values in x > 0\n \"\"\"\n fit_result = fit_double_lorentzian(x, y)\n\n return fit_result.params.valuesdict()['positive_fwhm']\n\ndef plot_double_lorentzian_fit(x, y):\n fit_result = fit_double_lorentzian(x, y)\n x, y = extend_to_even(x, y)\n positive_x = x > 0 # Determine positive side for plot\n plt.plot(x, y, 'bo', label = 'data')\n #plt.plot(x, fit_result.best_fit, 'r-', label = 'fit', linewidth = 2)\n plt.plot(x[positive_x], fit_result.best_fit[positive_x], 'r-', label = 'fit', linewidth = 2)\n plt.xscale('log')\n plt.yscale('log')\n\ndef extend_to_even(x, y):\n # Mirror (w.r.t. vertical axis) the one-sided spectrum that is passed to the function\n x = np.concatenate((-np.flipud(x),x))\n y = np.concatenate((np.flipud(y),y))\n return x, y\n\ndef fit_double_lorentzian(x, y):\n \"\"\"\n It is thought for a one-sided power spectrum (which is real&even), so that values in x > 0\n\n Args:\n x: e.g. frequencies\n y: e.g. power spectrum\n\n Comments:\n The fit to a single Lorentzian is only good for the vecinity of the peak.\n On the contrary, the double-Lorentzian fit suffers if we have only one-side of the spectrum.\n Fixing amplitude of the Lorentzian on negative side gives good visual agreement, but parameters on (-) side bad.\n Solution: mirror the spectrum with respect to y-axis since we know it is a real and even function\n I could also do here a first round fitting to a single Lorentzian and a second run fitting to 2 Lorentzians\n using as initial values for the parameters the result from the first fit.\n \"\"\"\n ###########\n ## Fit to a single Lorentzian\n #gmod = lmfit.models.LorentzianModel()\n #pars = gmod.guess(y, x=x, center=x[np.argmax(y)])\n #pars = gmod.guess(y, x=x)\n #result = gmod.fit(y, x=x, amplitude=0.5, center=0.07, sigma=0.03)\n #result = gmod.fit(y, pars, x=x)\n #return result.params.valuesdict()['fwhm']\n ########### Comment out until here to do the double-Lorentzian\n\n ##########\n # Fit to two Lorentzians\n # Need to check if frequency 0 is included in the array or not\n if x[0] < 0:\n sys.exit(\"Cannot mirror the data with respect to the y axis; first x-value is negative\")\n elif x[0] == 0:\n print(\"freq[0] = 0.0, removing such a value...\")\n x = x[1:]\n y = y[1:]\n\n x, y = extend_to_even(x, y)\n\n # mod 1 refers to the positive part of the power spectrum, mirror of mod2 (negative part)\n mod1 = lmfit.models.LorentzianModel(prefix=\"positive_\")\n mod2 = lmfit.models.LorentzianModel(prefix=\"negative_\")\n combined_model = mod1 + mod2 \n # Guess parameters for the positive part given the position of the center\n # Note the \"-\" sign, since np.argmax(y) only returns first occurence, which refers to the peak in the negative part\n pars = mod1.guess(y, x=x, positive_center=-x[np.argmax(y)])\n # After guessing, need to reset the value of the center to that of the max. Otherwise everything centered at 0 and\n # routine gives a fit to a function centered at 0 (need to somehow make the system \"unstable\" in order to converge)\n pars['positive_center'].value = -x[np.argmax(y)]\n # Example of how to set constraints on parameters\n #mod2.set_param_hint('negative_amplitude', vary=False)\n # Add parameters for the negative side based on the guesses from the positive \n pars += mod2.make_params(negative_center=-pars.valuesdict()['positive_center'],\n negative_amplitude=pars.valuesdict()['positive_amplitude'],\n negative_sigma=pars.valuesdict()['positive_sigma'] )\n\n result = combined_model.fit(y, pars, x=x)\n ########## Comment out until here to do the single-Lorentzian\n\n # For debugging\n #print(result.fit_report())\n #import matplotlib.pyplot as plt \n #plt.plot(x, y, 'bo')\n #plt.plot(x, result.init_fit, 'k--')\n #plt.plot(x, result.best_fit, 'r-')\n #plt.yscale('log')\n\n return result\n\ndef get_function_arguments():\n \"\"\"Returns tuple containing dictionary of calling function's\n named arguments and a list of calling function's unnamed\n positional arguments (the ones without default value? and \n the ones where the function call has as argument *list)\n\n TODO:\n needs some tweaking to get a proper parameter list\n since it resorts to locals(), it is not a good idea to use it for scripts that are run, since there is a lot of\n metadata and useless objects created by the interpreter there, I think\n\n From: http://kbyanc.blogspot.de/2007/07/python-aggregating-function-arguments.html\n \"\"\"\n from inspect import getargvalues, stack\n posname, kwname, args = getargvalues(stack()[1][0])[-3:]\n posargs = args.pop(posname, [])\n args.update(args.pop(kwname, []))\n return args, posargs\n\n# Print parameters to file at the top of the file, obtained from get_function_arguments()\n# need modification to get the other output (unnamed parameters) \ndef print_params_file(filename, params):\n with open(filename, 'w') as f_handle:\n for key, value in params.iteritems():\n f_handle.write(' '.join(['#',key,str(value),'\\n']))\n\n# Print parameters to stdout\n# TODO: this is just printing a dictionary... Is there a better way to do so?\ndef print_params(params):\n for key, value in params.iteritems():\n print(' '.join(['#',key,str(value),'\\n']))\n\ndef print_stats_format_file(filename):\n \"\"\"TODO: associate with get_stats by using a dictionary or named tuple there and automatically generate format here\"\"\"\n\n################################################################################\n\n# Helper functions to always control the size of vectors and matrices\n# Should I have one for big_c_odd and big_c_even?\n# TODO: I need one that does something like write_to_even_vector(n, L), same for odd\n# TODO: or maybe something like get_odd_index(m, l)\ndef get_size_even_matrices(L):\n return (2*L+1, 2*L+1)\n\ndef get_size_odd_matrices(L):\n return (2*L, 2*L)\n\ndef get_size_even_vector(L):\n return 2*L+1\n\ndef get_size_odd_vector(L):\n return 2*L\n\n\ndef get_number_c_vectors(L):\n return 2*L+1\n\ndef get_L_even_matrix(even_coeffs):\n # Remember: size of each even vector is 2*L+1, and vectors are stacked as column vectors in the big matrix of coeffs\n return int((even_coeffs.shape[0] - 1)/2)\n\ndef get_L_odd_matrix(odd_coeffs):\n # Remember: size of each odd vector is 2*L1, and vectors are stacked as column vectors in the big matrix of coeffs\n return int(odd_coeffs.shape[0]/2)\n\n# Get zero-th column (i.e. c_0) in big_c\ndef get_id_zero_column_big_c(L):\n return L\n\ndef get_id_center_element_even_c(L):\n return L\n# The following is not exactly the center of the vector since it has an even number of elements:\n# I just chose (for a vector c_n) the element that has as first index n, i.e. c_{n,n+1}\ndef get_id_center_element_odd_c(L):\n return L-1\n\n# TODO: GENERAL PROBLEM!! I SHOULD ONLY HAVE 2L ODD VECTORS AND NOT 2L+1.\n# In the current setting, more wave numbers appear on one side that on the other... (positive vs negative I mean)\n# This leads to problems when it comes to finding the conditions for the boundaries of the coefficients\n# (see weird conditions for the odd coefficients)\n\n# Extract a specific coefficient c_{m,k}, with those indices referring to the expansion\n# Rewrite using a function find_index (i.e. given (m, l), find index in odd or even coefficients matrices\n# TODO: Also write the other way round (given index in odd/even, find (m,l) from expansion\ndef get_coefficient(m, l, even_coefficients, odd_coefficients):\n if (even_coefficients.shape[1] != odd_coefficients.shape[1]):\n sys.exit(\"even and odd coefficient matrices have different number of columns\")\n else:\n L = (even_coefficients.shape[1] - 1)/2\n # The following is common to both even and odd coefficients\n id_column_zero = get_id_zero_column_big_c(L)\n \n if np.logical_and(np.logical_and( (m+l) % 2 == 0, np.abs(m+l) <= 2*L), np.abs(m-l) <= 2*L ):\n n = (m+l)/2\n id_center_vector = get_id_center_element_even_c(L)\n return even_coefficients[id_center_vector + m - n, id_column_zero + n]\n\n elif np.logical_and(np.logical_and( (m+l) % 2 != 0, (-2*L+1) < (m+l) <= (2*L+1)), np.abs(m-l) <= (2*L-1) ):\n n = (m+l-1)/2\n id_center_vector = get_id_center_element_odd_c(L)\n \n return odd_coefficients[id_center_vector + m - n, id_column_zero + n]\n\n else:\n return 0.0\n\n# The following function has testing purposes: given a inhomogeneity obtained from full matrix problem, obtain the\n# corresponding mcf inhomogeneity for odd coefficients. The parameter \"full_inhomogeneity\" should have obtained with an\n# L larger than 2*L+1 here in order for all the coefficients to be (in principle) different from zero\ndef set_inhomogeneity_odd_from_full(full_inhomogeneity, L):\n b = np.zeros((2*L,2*L+1), dtype=np.complex128)\n for k in range(-L,L+1):\n for i in range(-L+1, L):\n b[i+L-1, k+L] = full_matrix.get_coefficient(k + i,k+1-i, full_inhomogeneity)\n\n return b \n\n# In its simplest way, we only need a function to set inhomogeneity for matrices of odd coefficients, and we just need\n# to pass even coefficients of the stationary function since the odd ones are all 0\ndef set_inhomogeneity_odd_n(n, stationary_even_coeffs, stationary_odd_coeffs, p=1):\n L_even = get_L_even_matrix(stationary_even_coeffs)\n L_odd = get_L_odd_matrix(stationary_odd_coeffs)\n if L_even != L_odd:\n sys.exit(\"Dimensions of even and odd matrices of coefficients are not coherent\")\n else:\n L = L_even\n\n # To avoid cumbersome notation\n even_coeffs = stationary_even_coeffs\n odd_coeffs = stationary_odd_coeffs\n\n id_0 = get_id_center_element_odd_c(L)\n\n v = np.zeros(get_size_odd_vector(L), dtype=np.complex128)\n\n for i in range(-L+1, L+1):\n v[id_0+i] = 4. * 0.5 * (1j) * ((2*math.pi)**2 * \\\n get_coefficient(n+i, n-i+1, even_coeffs, odd_coeffs) * \\\n (get_coefficient(p, 0, even_coeffs, odd_coeffs) - get_coefficient(-p, 0, even_coeffs, odd_coeffs)) -\\\n (get_coefficient(n+i-p, n-i+1, even_coeffs, odd_coeffs) - get_coefficient(n+i+p, n-i+1, even_coeffs, odd_coeffs)))\n\n return v \n\ndef set_inhomogeneity_odd(stationary_even_coeffs, stationary_odd_coeffs, p=1):\n L_even = get_L_even_matrix(stationary_even_coeffs)\n L_odd = get_L_odd_matrix(stationary_odd_coeffs)\n if L_even != L_odd:\n sys.exit(\"Dimensions of even and odd matrices of coefficients are not coherent\")\n else:\n L = L_even\n\n number_c_vectors = get_number_c_vectors(L)\n size_odd = get_size_odd_vector(L)\n inhomogeneities = np.zeros((size_odd, number_c_vectors), dtype=np.complex128)\n\n # To avoid cumbersome notation\n even_coeffs = stationary_even_coeffs\n odd_coeffs = stationary_odd_coeffs\n\n zero_big_c = get_id_zero_column_big_c(L) \n for n in range(-L, L+1):\n id_n = zero_big_c + n\n inhomogeneities[:, id_n] = set_inhomogeneity_odd_n(n, even_coeffs, odd_coeffs, p)\n\n return inhomogeneities\n\ndef set_inhomogeneity_even_n(n, stationary_even_coeffs, stationary_odd_coeffs, p=1):\n L_even = get_L_even_matrix(stationary_even_coeffs)\n L_odd = get_L_odd_matrix(stationary_odd_coeffs)\n if L_even != L_odd:\n sys.exit(\"Dimensions of even and odd matrices of coefficients are not coherent\")\n else:\n L = L_even\n\n # To avoid cumbersome notation\n even_coeffs = stationary_even_coeffs\n odd_coeffs = stationary_odd_coeffs\n\n id_0 = get_id_center_element_even_c(L)\n\n v = np.zeros(get_size_even_vector(L), dtype=np.complex128)\n\n for i in range(-L, L+1):\n v[id_0+i] = 4. * 0.5 * (1j) * ((2*math.pi)**2 * \\\n get_coefficient(n+i, n-i, even_coeffs, odd_coeffs) * \\\n (get_coefficient(p, 0, even_coeffs, odd_coeffs) - get_coefficient(-p, 0, even_coeffs, odd_coeffs)) -\\\n (get_coefficient(n+i-p, n-i, even_coeffs, odd_coeffs) - get_coefficient(n+i+p, n-i, even_coeffs, odd_coeffs)))\n\n return v \n\ndef set_inhomogeneity_even(stationary_even_coeffs, stationary_odd_coeffs, p=1):\n L_even = get_L_even_matrix(stationary_even_coeffs)\n L_odd = get_L_odd_matrix(stationary_odd_coeffs)\n if L_even != L_odd:\n sys.exit(\"Dimensions of even and odd matrices of coefficients are not coherent\")\n else:\n L = L_even\n\n number_c_vectors = get_number_c_vectors(L)\n size_even = get_size_even_vector(L)\n inhomogeneities = np.zeros((size_even, number_c_vectors), dtype=np.complex128)\n\n # To avoid cumbersome notation\n even_coeffs = stationary_even_coeffs\n odd_coeffs = stationary_odd_coeffs\n\n zero_big_c = get_id_zero_column_big_c(L) \n for n in range(-L, L+1):\n id_n = zero_big_c + n\n inhomogeneities[:, id_n] = set_inhomogeneity_even_n(n, even_coeffs, odd_coeffs, p)\n\n return inhomogeneities\n\n# I should have a single function for even and odd matrices\ndef set_odd_matrices(L=15, D=0.1, alpha=0.1):\n\n number_c_vectors = get_number_c_vectors(L)\n #size_c = get_size_even_vector(L)\n #size_big_Q = (number_c_vectors, size_c, size_c)\n size_odd_matrix = get_size_odd_matrices(L)\n size_big_Q = (number_c_vectors, ) + size_odd_matrix \n\n Q_minus = np.zeros(size_big_Q)\n Q_0 = np.zeros(size_big_Q)\n Q_plus = np.zeros(size_big_Q)\n \n zero_big_c = get_id_zero_column_big_c(L) \n\n #for n in range(number_c_vectors):\n for n in range(-L, L+1):\n id_n = zero_big_c + n\n (Q_minus[id_n,:,:], Q_0[id_n,:,:], Q_plus[id_n,:,:]) = set_odd_matrices_n(n, L, D, alpha)\n\n return (Q_minus, Q_0, Q_plus)\n\ndef set_odd_matrices_n(n, L=15, D=0.1, alpha=0.1):\n size_An = get_size_odd_matrices(L) \n\n # Change these lines for sparse matrices\n Am1 = np.zeros(size_An)\n A0 = np.zeros(size_An)\n Ap1 = np.zeros(size_An)\n\n # It would be cleaner to use in the following something like Am1[id_n, id_n + 1] for the centervalue, for example\n # where id_n = L \n\n # REMEMBER THE SHIFTS IN THE INDICES (my notes use negative indices to indicate row,column, here only positive)\n # Set outer rows and columns for Am1 and Ap1\n Am1[0,0] = -2*L+1\n Am1[0,1] = 2*alpha*(n+L)\n Am1[-1,-1] = 2*L-1 \n Am1[-1,-2] = 2*alpha*(n+L)\n Ap1[0,0] = 2*L-1\n Ap1[0,1] = -2*alpha*(n-L+1) \n Ap1[-1,-1] = -2*L+1\n Ap1[-1,-2] = -2*alpha*(n-L+1) \n #Set rest of the matrices Am1 and Ap1\n # Note the modifications of the call to range. HARDCODED, VERY UGLY\n for k in range(1,(size_An[0]-1)):\n Am1[k,k+1] = 2*alpha*(n+L-k)\n Am1[k,k] = -2*(L-k)+1 \n Am1[k,k-1] = 2*alpha*(n+(k-L)+1)\n Ap1[k,k+1] = -2*alpha*(n+(k-L)+1) \n Ap1[k,k] = 2*(L-k)-1\n Ap1[k,k-1] = -2*alpha*(n-(k-L)) \n\n # Set outer rows and columns for A0\n A0[0,1] = 2*n+1\n A0[0,0] = 4*D*((n-L+1)*(n-L+1)+(n+L)*(n+L))\n A0[-1,-2] = -(2*n+1)\n A0[-1,-1] = 4*D*((n-L+1)*(n-L+1)+(n+L)*(n+L))\n\n # Set rest of matrices Am1 and Ap1\n # Note the modifications of the call to range. HARDCODED, VERY UGLY\n for k in range(1,(size_An[0]-1)):\n A0[k,k+1] = +(2*n+1)\n A0[k,k] = 4*D*((n+(k-L)+1)**2+(n-(k-L))**2)\n A0[k,k-1] = -(2*n+1)\n\n return (Am1, A0, Ap1)\n\ndef set_even_matrices(L=15, D=0.1, alpha=0.1):\n\n number_c_vectors = get_number_c_vectors(L)\n #size_c = get_size_even_vector(L)\n #size_big_Q = (number_c_vectors, size_c, size_c)\n size_even_matrix = get_size_even_matrices(L)\n size_big_Q = (number_c_vectors, ) + size_even_matrix \n\n Q_minus = np.zeros(size_big_Q)\n Q_0 = np.zeros(size_big_Q)\n Q_plus = np.zeros(size_big_Q)\n \n zero_big_c = get_id_zero_column_big_c(L) \n\n #for n in range(number_c_vectors):\n for n in range(-L, L+1):\n id_n = zero_big_c + n\n (Q_minus[id_n,:,:], Q_0[id_n,:,:], Q_plus[id_n,:,:]) = set_even_matrices_n(n, L, D, alpha)\n\n return (Q_minus, Q_0, Q_plus)\n\n\ndef set_even_matrices_n(n, L=15, D=0.1, alpha=0.1):\n size_An = get_size_even_matrices(L) \n\n # Change these lines for sparse matrices\n Am1 = np.zeros(size_An)\n A0 = np.zeros(size_An)\n Ap1 = np.zeros(size_An)\n\n # REMEMBER THE SHIFTS IN THE INDICES (my notes use negative indices to indicate row,column, here only positive)\n # Set outer rows and columns for Am1 and Ap1\n Am1[0,0] = -2*(0-L)\n Am1[0,1] = -2*alpha*(n+L)\n Am1[-1,-1] = -2*(L) \n Am1[-1,-2] = -2*alpha*(n+L)\n Ap1[0,0] = -2*L \n Ap1[0,1] = 2*alpha*(n-L) \n Ap1[-1,-1] = 2*L \n Ap1[-1,-2] = 2*alpha*(n-L) \n #Set rest of the matrices Am1 and Ap1\n # Note the modifications of the call to range. HARDCODED, VERY UGLY\n for k in range(1,(size_An[0]-1)):\n Am1[k,k+1] = -2*alpha*(n-(k-L))\n Am1[k,k] = -2*(k-L) \n Am1[k,k-1] = -2*alpha*(n+(k-L))\n Ap1[k,k+1] = 2*alpha*(n+(k-L)) \n Ap1[k,k] = 2*(k-L) \n Ap1[k,k-1] = 2*alpha*(n-(k-L)) \n\n # Set outer rows and columns for A0\n A0[0,1] = -2*n \n A0[0,0] = -4*D*((n-L)*(n-L)+(n+L)*(n+L))\n A0[-1,-2] = 2*n\n A0[-1,-1] = -4*D*((n-L)*(n-L)+(n+L)*(n+L))\n\n # Set rest of matrices Am1 and Ap1\n # Note the modifications of the call to range. HARDCODED, VERY UGLY\n for k in range(1,(size_An[0]-1)):\n A0[k,k+1] = -2*n \n A0[k,k] = -4*D*((n+(k-L))*(n+(k-L))+(n-(k-L))*(n-(k-L)))\n A0[k,k-1] = +2*n\n\n\n # Set the corresponding Q_minus, Q_plus, Q_0\n # Play with adding a new dimension for block matrix Q_minus, etc.? That way assigment would be automatic\n #Q_minus[n,:,:] = Am1[:,:] \n #Q_0[n,:,:] = A0[:,:]\n #Q_plus[n,:,:] = Ap1[:,:]\n Am1 = -Am1\n A0 = -A0\n Ap1 = -Ap1\n \n return (Am1, A0, Ap1)\n\n# The nasty trick of getting 2L+1 vectos of coefficients for the odd ones allows us to use same function for both?\n# Note that in these 3D arrays \"Q_0[i+1, :, :]\" is equivalent to \"Q_0[i+1]\"\n# Wrap into a function the long statement to calculate S_plus[i], etc.\n# The indices here could be much more informative: iterate from -N to N \n# If detuning = 0, system is singular (row full of zeros in Q_0[0]). I did I dirty trick by finding n=0 and stopping\n# loop, but I guess the right thing to do would be to catch the exception of singular matrix and leave the loop then\n# That dirty trick also uses a dirty way to obtain L from the data\n# TODO: change Q_0 by Q0_detuned!!!!\ndef get_Splus(Q_minus, Q_0, Q_plus, detuning):\n S_plus = np.zeros_like(Q_minus, dtype=np.complex128)\n\n S_plus[-1] = 0.0\n\n # N represents cut-off for big c_n, i.e. c_{-L}... c_{0} .... c_{+L}\n id_N = S_plus.shape[0] - 1\n # TODO: Very dirty way to deal with the indices!!\n L = (S_plus.shape[0] - 1) / 2\n #N = number_big_c_vectors - 1\n\n for i in range(id_N-1,-1,-1): # goes N-1, N-2 ... 0\n #print(modify_diagonal(Q_0[i+1], detuning)+np.dot(Q_plus[i+1],S_plus[i+1]))\n S_plus[i] = -np.dot(np.linalg.inv((modify_diagonal(Q_0[i+1], detuning)+np.dot(Q_plus[i+1],S_plus[i+1]))), Q_minus[i+1])\n # Handle special case of detuning = 0.0 for even coeffs by getting out of the loop (so that error doesn't happen)\n if np.logical_and(detuning == 0.0, i == L):\n break\n \"\"\"\n print(S_plus[i,:,:])\n print(\"\\n\")\n \"\"\"\n return S_plus\n\n# id_N is inconsistent with respect to the one defined for get_Splus()\ndef get_Sminus(Q_minus, Q_0, Q_plus, detuning):\n S_minus = np.zeros_like(Q_minus, dtype=np.complex128)\n\n S_minus[0] = 0.0\n\n #N = number_big_c_vectors - 1\n # get_number_c_vectors() = number_S_matrices\n # TODO: Very dirty way to deal with the indices!!\n L = (S_minus.shape[0] - 1) / 2\n id_N = S_minus.shape[0]\n\n for i in range(1, id_N): # goes N-1, N-2 ... 0\n S_minus[i] = -np.dot(np.linalg.inv((modify_diagonal(Q_0[i-1], detuning) +np.dot(Q_minus[i-1],S_minus[i-1]))), Q_plus[i-1])\n # Handle special case of detuning = 0.0 for even coeffs, which leads to singular matrix.\n if np.logical_and(detuning == 0.0, i == L):\n break\n \"\"\"\n print(S_minus[i,:,:])\n print(\"\\n\")\n \"\"\"\n return S_minus\n\n\n# In the case we are interested, detuning = -i\\omega, or detuning = eigenvalue (with negative real part)\n# Fundamental here is not to modify M within the function!!\n# Distinguish between complex and real detuning to control memory?\ndef modify_diagonal(M, detuning):\n # Think of a better way to deal with the following three lines... global variables?\n #A = np.copy(M)\n # The following copies array and casts it to complex values\n # For in-place type conversion, see\n # http://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array\n A = M.astype(np.complex128)\n rows_A = np.shape(A)[1]\n #print(sp.sparse.issparse(A))\n \n # It works because of some broadcasting magic, possible source of BUGS...\n A = M + 4 * np.eye(rows_A) * detuning\n\n return A \n\n# The following could just be a lambda function? As it is now it doesn't make sense, exactly the same as modify_diagonal\n#def Q0_detuned(Q0_eo, detuning):\n# return modify_diagonal(Q0_eo, detuning)\n\ndef get_indices_expansion(row, column, L, flag_even): \n # Not completely clean, but so far so good \n\n if flag_even == True:\n k = column - get_id_zero_column_big_c(L)\n m = k + (row - get_id_center_element_even_c(L))\n l = k - (row - get_id_center_element_even_c(L))\n else:\n k = column - get_id_zero_column_big_c(L)\n m = k + (row - get_id_center_element_odd_c(L))\n l = k - (row - get_id_center_element_odd_c(L)) + 1\n\n return (m, l)\n\ndef rebuild_eigenfunction_mcf(x, y, even_coeffs, odd_coeffs):\n aux_sum = 0.0+1j*0.0\n \n L_even = get_L_even_matrix(even_coeffs)\n L_odd = get_L_odd_matrix(odd_coeffs)\n if L_even != L_odd:\n sys.exit(\"Dimensions of even and odd matrices of coefficients are not coherent\")\n else:\n L = L_even\n\n for (i, j), value in np.ndenumerate(even_coeffs):\n m, l = get_indices_expansion(i, j, L, flag_even = True)\n aux_sum += even_coeffs[i, j] * np.exp(1j * (m*x+l*y))\n\n for (i, j), value in np.ndenumerate(odd_coeffs):\n m, l = get_indices_expansion(i, j, L, flag_even = False)\n aux_sum += odd_coeffs[i, j] * np.exp(1j * (m*x+l*y))\n \n return aux_sum\n\n# Plot steady pdf\ndef plot_steady_pdf_mcf(even_coeffs, odd_coeffs):\n plot_factor = 1.0\n boundary = np.pi/2\n step = 0.1\n x, y = np.mgrid[-plot_factor*boundary:plot_factor*boundary:step,-plot_factor*boundary:plot_factor*boundary:step]\n #x, y = np.mgrid[0:np.pi:0.01,0:np.pi:0.01]\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n #ax = fig.add_subplot(211,projection='3d')\n #ax1 = fig.add_subplot(212,projection='3d')\n #ax.plot_surface(x, y, np.log(steady_prob_density(x,y,c)))\n # Factor 4 in the following line to obtained the normalized pdf in -pi/2,pi/2: nothing to do with factor 4 from\n # eigenvalue problem\n steady_pdf = 4*np.real(rebuild_eigenfunction_mcf(x,y, even_coeffs, odd_coeffs))\n #ax.plot_surface(x,y, steady_pdf)\n ax.scatter(x, y, steady_pdf) \n #ax1.plot_surface(simulation[:,0],simulation[:,1],simulation[:,2])\n #v = np.linspace(-np.pi,np.pi,100)\n #plt.plot(v,steady_prob_density(v,0,c))\n plt.show()\n\n return x, y, steady_pdf \n\ndef power_spectrum_from_coefficients_mcf(Hml_even, Hml_odd, p, q):\n # TODO: need to adapt this function for the cosine (not only p and q are involved, but also the sign in the line):\n #sum_coefficients = get_coefficient(-q,0,Hml_even, Hml_odd) - get_coefficient(q,0,Hml_even, Hml_odd)\n sum_coefficients = -2.0*get_coefficient(q,0,Hml_even, Hml_odd)\n #sum_coefficients = 2.0*get_coefficient(-q,0,Hml_even, Hml_odd)\n\n #print(get_coefficient(-q,0,Hml_even, Hml_odd) + get_coefficient(q,0,Hml_even, Hml_odd))\n #print(get_coefficient(q, 0, Hml_even, Hml_odd))\n #print(get_coefficient(-q, 0, Hml_even, Hml_odd))\n #print(sum_coefficients)\n\n return (2*math.pi)**2*np.real(-1j*sum_coefficients)\n\n# NEED TO MODIFY all the following function to do the whole range -L to +L, when lambda != 0, no symmetry arguments...\ndef up_iteration_coefficients(S_plus, c_0, L):\n # Iterate with matrices {S_n} to obtain the sequence of vectors {c_n=[c_{2n}, c_{2n+1}]}\n c = np.zeros((c_0.shape[0], L+1), dtype=np.complex128)\n #c = np.zeros((2*L+1, L+1), dtype=np.complex128)\n c[:, [0]] = c_0\n for i in range(1,L+1):\n c[:,i] = np.dot(S_plus[i-1,:,:], c[:,i-1])\n return c\n\ndef down_iteration_coefficients(S_minus, c_0, L):\n # Iterate with matrices {S_n} to obtain the sequence of vectors {c_n=[c_{2n}, c_{2n+1}]}\n c = np.zeros((c_0.shape[0], L+1), dtype=np.complex128)\n #c = np.zeros((2*L+1, L+1), dtype=np.complex128)\n c[:, [L]] = c_0\n for i in range(L-1,-1, -1):\n c[:,i] = np.dot(S_minus[i+1,:,:], c[:,i+1])\n return c\n\n\n\n# This is the modification I was talking about. I could have done it on the same function but in this way the tests \n# from the notebook are still OK\n# Note this doesn't work if lambda=0\n# TODO: inconsistency: some functions ask for L whether others \"know\" how to get it from within the function\n# VERY NASTY: I COPIED SOME THINGS FROM get_Splus and get_Sminus, in particular how to do the loop. However, in that\n# case id_N is correctly obtained from the first dimension of S_minus. Here, however, the vectors are stacked in columns\n# in a_plus/minus and c, and therefore id_L has to be obtained from the columns!!\ndef full_up_iteration_coefficients(S_plus, a_plus, L):\n c = np.zeros_like(a_plus)\n c[:, 0] = a_plus[:, 0] \n id_L = a_plus.shape[1]\n\n for i in range(1,id_L):\n c[:,i] = np.dot(S_plus[i-1,:,:], c[:,i-1]) + a_plus[:, i]\n return c\n\ndef full_down_iteration_coefficients(S_minus, a_minus, L):\n c = np.zeros_like(a_minus)\n id_L = a_minus.shape[1] - 1\n c[:, id_L] = a_minus[:, id_L] \n\n for i in range(id_L-1,-1, -1):\n c[:,i] = np.dot(S_minus[i+1,:,:], c[:,i+1]) + a_minus[:, i]\n return c\n\n# TODO: as it stands the arguments aren't passed consistently to the following functions::\n# Q0 is passed unmodified (i.e. without detuning), whereas Sp is passed already with detuning\n# Solutions: either pass Q0 already modified or calculate the Sp(detuned) from within the function (pass detunin)\ndef get_a_plus(Qm, Q0, Qp, Sp, inhomogeneity, L):\n a = np.zeros_like(inhomogeneity)\n a[:, -1] = np.dot(np.linalg.inv(Q0[-1]), inhomogeneity[:, -1])\n id_L = a.shape[1]-1\n\n for i in range(id_L-1,-1,-1): # goes N-1, N-2 ... 0\n a[:, i] = np.dot(np.linalg.inv(Q0[i]+np.dot(Qp[i],Sp[i])), inhomogeneity[:, i] - np.dot(Qm[i],a[:, i+1] ))\n\n return a \n\ndef get_a_minus(Qm, Q0, Qp, Sm, inhomogeneity, L):\n a = np.zeros_like(inhomogeneity)\n a[:, 0] = np.dot(np.linalg.inv(Q0[0]), inhomogeneity[:,0])\n id_L = a.shape[1]\n\n for i in range(1,id_L): \n a[:, i] = np.dot(np.linalg.inv(Q0[i]+np.dot(Qm[i],Sm[i])), inhomogeneity[:, i] - np.dot(Qp[i],a[:, i-1] ))\n\n return a \n\n################################################################################\n# LAST TRIAL, starting from the center: THIS IS THE APPROACH IT WORKS\ndef get_c0(Qm, Q0, Qp, Sm, Sp, a_minus, a_plus, inhomogeneity, L):\n id_0 = get_id_zero_column_big_c(L) \n #M = np.dot(Qm[id_0], Sm[id_0]) + Q0[id_0] + np.dot(Qp[id_0], Sp[id_0])\n #c0 = np.linalg.solve(M, inhomogeneity[:, id_0] - (np.dot(Qm[id_0], a_minus[:, id_0-1]) + np.dot(Qp[id_0], a_plus[:,id_0+1]))) \n\n # Using the symmetries we know...\n UD_m = -np.fliplr(np.eye(Sm[id_0].shape[0]))\n M = np.dot(Qm[id_0], UD_m) + Q0[id_0] + np.dot(Qp[id_0], Sp[id_0])\n c0 = np.linalg.solve(M, inhomogeneity[:, id_0] - (np.dot(Qp[id_0], a_plus[:,id_0+1]))) \n\n #return c0\n #return c0, np.linalg.cond(M)\n return c0, np.linalg.det(M)\n \ndef half_up_iteration_coefficients(S_plus, a_plus, c0, L):\n id_0 = get_id_zero_column_big_c(L) \n c = np.zeros_like(a_plus)\n id_L = a_plus.shape[1]\n\n c[:, id_0] = c0\n\n for i in range(id_0+1,id_L):\n c[:,i] = np.dot(S_plus[i-1,:,:], c[:,i-1]) + a_plus[:, i]\n return c\n\ndef half_down_iteration_coefficients(S_minus, a_minus, c0, L):\n id_0 = get_id_zero_column_big_c(L) \n c = np.zeros_like(a_minus)\n id_L = a_minus.shape[1] - 1\n\n c[:, id_0] = c0\n\n for i in range(id_0-1,-1, -1):\n c[:,i] = np.dot(S_minus[i+1,:,:], c[:,i+1]) + a_minus[:, i]\n return c\n################################################################################\n## NAIVE TEST SUITE\n\ndef test_set_up_steady_pdf(D=0.1, alpha=0.1, L=15):\n detuning = 0.0\n id_0 = get_id_zero_column_big_c(L)\n (Qm_e, Q0_e, Qp_e) = set_even_matrices(L=L, alpha=alpha, D=D)\n (Qm_o, Q0_o, Qp_o) = set_odd_matrices(L=L, alpha=alpha, D=D)\n S_plus_e = get_Splus(Qm_e, Q0_e, Qp_e, detuning)\n S_minus_e = get_Sminus(Qm_e, Q0_e, Qp_e, detuning)\n S_plus_o = get_Splus(Qm_o, Q0_o, Qp_o, detuning)\n S_minus_o = get_Sminus(Qm_o, Q0_o, Qp_o, detuning)\n\n c0_mixed = determine_start_vector(Qm_e[id_0], Q0_e[id_0], Qp_e[id_0], S_plus_e[id_0], S_minus_e[id_0], L,flag_up=0)\n c0_up = determine_start_vector(Qm_e[id_0], Q0_e[id_0], Qp_e[id_0], S_plus_e[id_0], S_minus_e[id_0], L,flag_up=1)\n c0_down = determine_start_vector(Qm_e[id_0], Q0_e[id_0], Qp_e[id_0], S_plus_e[id_0], S_minus_e[id_0], L,flag_up=2)\n\n c_up = up_iteration_coefficients(S_plus_e[L:], c0_mixed, L)\n c_down = down_iteration_coefficients(S_minus_e[:L+1], c0_mixed, L)\n\n # Run tests\n \n assert (compare_Spm_steady(S_plus_e, S_minus_e, 2, L)),\"S_plus and S_minus not related\"\n assert (compare_methods_c0(c0_mixed, c0_up, c0_down)),\"Different c0's for different methods\"\n assert (compare_pos_neg_coefficients_steady(c_up, c_down)),\"Different results up/down iteration\"\n\n return \"Tests passed\"\n \ndef test_mcf_steady_pdf():\n # Tests to compare with known results: textfiles with coefficients obtained in the other module steady_pdf_mcf\n # If coefficients are obtained from main(), they are real arrays and can be accessed as the first example here\n # If coefficients obtaind from savetxt_simple...., then they are complex arrays and can be accessed as second example\n # It is fundamental that the coefficients saved are known to be correct: for that reason a comparison with\n # simulations is provided in module steady_pdf_mcf\n\n #c_even, c_odd = get_stationary_coefficients(Qm_e, Q0_e, Qp_e, Qm_o, Q0_o, Qp_o, L)\n L_test = 15\n c_even, c_odd = get_steady_pdf(D=0.1, alpha=0.1, L=L_test)\n data = np.loadtxt(\"test/D_0.1_alpha_0.1/mcf_coefficients_D_0.1_L_15.dat\")\n assert (np.allclose(c_even[:, L_test:], data)), \"Wrong steady pdf coefficients\"\n\n L_test = 30\n c_even, c_odd = get_steady_pdf(D=0.01, alpha=0.1, L=L_test)\n data = np.loadtxt(\"test/D_0.01_alpha_0.1/mcf_coefficients_D_0.01_L_30.dat\").view(complex)\n assert (np.allclose(c_even[:, L_test:], data)), \"Wrong steady pdf coefficients\"\n\n return \"Tests passed\"\n\n# Given a one-sided (positive) matrix of coefficients, find the negative ones for the stationary case, where they must\n# satisfy c_{k,l} = c_{-k,-l}\ndef transform_positive_coefficients(c_positive):\n return np.flipud(np.fliplr(c_positive)) \n\n# The following is equivalent to multiplying by UD = np.fliplr(np.eye(size_odd/even)) as follows: UD*c_positive*UD^-1,\n# i.e. a \"similarity transformation\". This similarity transformation also relates negative and positive\n# coefficients for the stationary case, so that: c_{-k} = UD c{+k}\ndef transform_matrix(matrix):\n invert_mat = np.fliplr(np.eye(matrix.shape[0]))\n return np.dot(invert_mat, np.dot(matrix, np.linalg.inv(invert_mat)))\n\n# Compare S_plus_even(n) to UD * S_minus_even(-n) UD^-1 (stationary case, even coefficients)\ndef compare_Spm_steady(Sp_e, Sm_e, n, L):\n id_0 = get_id_zero_column_big_c(L) \n transformed_matrix = transform_matrix(Sm_e[id_0-n])\n return np.allclose(Sp_e[id_0+n], transformed_matrix)\n\n# c_up and c_down are obtained from up and down iteration\ndef compare_pos_neg_coefficients_steady(c_up, c_down):\n c_up_transformed = transform_positive_coefficients(c_up)\n return np.allclose(c_down, c_up_transformed)\n \ndef compare_methods_c0(c0_mixed, c0_up, c0_down):\n return np.logical_and(np.allclose(c0_up, c0_down), np.allclose(c0_mixed, c0_up))\n\n################################################################################\n# CHANGE NAME OF THE FOLLOWING FUNCTION\ndef get_steady_pdf(D=0.1, alpha=0.1, L=15):\n \n (Qm_e, Q0_e, Qp_e) = set_even_matrices(L=L, D=D, alpha=alpha)\n (Qm_o, Q0_o, Qp_o) = set_odd_matrices(L=L, D=D, alpha=alpha)\n\n c_even, c_odd = get_stationary_coefficients(Qm_e, Q0_e, Qp_e, Qm_o, Q0_o, Qp_o, L)\n\n #plot_steady_pdf_mcf(c_even, c_odd)\n return c_even, c_odd\n\n\ndef get_stationary_coefficients(Qm_e, Q0_e, Qp_e, Qm_o, Q0_o, Qp_o, L):\n id_0 = get_id_zero_column_big_c(L)\n detuning = 0.0 # This indicates we are dealing with steady pdf\n\n S_plus_e = get_Splus(Qm_e, Q0_e, Qp_e, detuning)\n S_minus_e = get_Sminus(Qm_e, Q0_e, Qp_e, detuning)\n\n c0_e = determine_start_vector(Qm_e[id_0], Q0_e[id_0], Qp_e[id_0], S_plus_e[id_0], S_minus_e[id_0], L,flag_up=0)\n c_up_e = up_iteration_coefficients(S_plus_e[L:], c0_e, L)\n c_down_e = down_iteration_coefficients(S_minus_e[:L+1], c0_e, L)\n\n full_c_e = get_full_from_half_coefficients(c_up_e, c_down_e)\n\n############################################################\n # The following part is only included in case we'd be dealing with non-zero odd coefficients (but still symmetric!)\n # c_odd has to be zero in the end!!\n # Odd coefficients\n S_plus_o = get_Splus(Qm_o, Q0_o, Qp_o, detuning)\n S_minus_o = get_Sminus(Qm_o, Q0_o, Qp_o, detuning)\n\n aux_M_o = get_aux_M(Qm_o[id_0], Q0_o[id_0], Qp_o[id_0], S_plus_o[id_0], S_minus_o[id_0], L,flag_up=0)\n c0_o = np.dot(np.linalg.inv(aux_M_o), np.zeros((get_size_odd_vector(L), 1))) # up_iteration... needs c0_o (2*L(+1) x 1)\n c_up_o = up_iteration_coefficients(S_plus_o[L:], c0_o, L)\n c_down_o = down_iteration_coefficients(S_minus_o[:L+1], c0_o, L)\n full_c_o = get_full_from_half_coefficients(c_up_o, c_down_o)\n############################################################\n\n return full_c_e, full_c_o \n\ndef get_full_from_half_coefficients(c_up, c_down):\n half_c = np.delete(c_down,-1,1)\n full_c = np.hstack((half_c, c_up))\n return full_c\n\n################################################################################\n\n# Maybe in the following functions it would be better to pass the whole series of matrices Qm, Qp, etc. and select then\n# the corresponding 0 matrix (probably better to pass n as an argument)\n# flag_up = 0 (determine from S_m(0) and S_p(0) together), 1 (from S_p(0) and trick) and 2 (from S_m(0) and trick)\ndef get_aux_M(Qm_0,Q0_0, Qp_0, S_plus_0, S_minus_0, L, flag_up=0):\n if flag_up == 0:\n # The auxiliary matrix is determined from both S_plus[0] and S_minus[0] matrices\n return Q0_0+np.dot(Qp_0, S_plus_0)+np.dot(Qm_0, S_minus_0) \n elif flag_up == 1:\n # The auxiliary matrix is determined solely from both S_plus[0] matrices + additional trick with U_D\n return Q0_0+np.dot((Qp_0+np.fliplr(Qm_0)),S_plus_0)\n elif flag_up == 2:\n # The auxiliary matrix is determined solely from both S_minus[0] matrices + additional trick with U_D\n return Q0_0+np.dot((Qm_0+np.fliplr(Qp_0)),S_minus_0)\n else:\n sys.exit(\"the passed flag does not correspond to any valid form of aux_M\")\n\n# This is only valid when det(aux_M) == 0 (as in the steady state probability density), i.e. underdetermined system\n# flag_up = 0 (determine from S_m(0) and S_p(0) together), 1 (from S_p(0) and trick) and 2 (from S_m(0) and trick)\ndef determine_start_vector(Qm_0,Q0_0, Qp_0, S_plus_0, S_minus_0, L, flag_up=0):\n # Obtain initial vector c_0 = [c_{0,-L} ... c_{0,+L} c_{1,-L} ... c_{1,+L} ] from c_{0,0}\n # Note row with index L is the row corresponding to c_{0,0} and is full of zeros for aux_M\n\n aux_M = get_aux_M(Qm_0,Q0_0, Qp_0, S_plus_0, S_minus_0, L, flag_up)\n\n normalization_coefficient = 1./((2*np.pi)*(2*np.pi))\n\n #print(aux_M)\n \"\"\"\n print(aux_M)\n print(aux_M[L,:]) # print row full of zeros\n print(aux_M[:,[L]])\n print(\"\\n\")\n print(aux_M[:,[L]])\n \"\"\"\n # The following should be a call like get_id_center_element_even_c(L):\n id_0 = L\n\n aux_M = np.delete(aux_M, (L), axis=0) #Delete row L from aux_M\n aux_v = aux_M[:,[L]] # With this syntax, I keep it as a column vector\n aux_M = np.delete(aux_M, (L), axis=1) #Delete column L from aux_M\n\n #print(aux_v)\n #print(\"\\n\")\n #c0 = - np.dot(np.linalg.inv(aux_M),aux_v)*normalization_coefficient COMPLETELY WRONG!!!!!!!!!\n\n c0 = - np.dot(np.linalg.inv(aux_M),aux_v*normalization_coefficient)\n \"\"\"\n print(c0)\n print(\"\\n\")\n \"\"\"\n #c[:,[0]] = np.insert(c0, L, normalization_coefficient, axis=0) #Insert in row (axis=0) L of our column vector c0 the number \"normalization coefficient\"\n #print(c[:,[0]])\n c0 = np.insert(c0, L, normalization_coefficient, axis=0) #Insert in row (axis=0) L of our column vector c0 the number \"normalization coefficient\"\n return c0\n################################################################################\n\n# I just have the following as an example for the sparse problem later on\ndef solve_sparse_eigenproblem(D=0.1, alpha = 0.1, L = 15):\n \n M = set_coefficient_matrix(D, alpha, L)\n M_sp = sp.sparse.csr_matrix(M) \n\n # Note division by 4 (provides the correct eigenvalues)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigs(-M_sp/4, k = 3, which = 'LR')\n\n return eigenvalues, eigenvectors\n\n# Translate x,y vectors as generated by np.mgrid (i.e. for pyplot's 3d routine) to gnuplot's format\n# TODO: how to deal with where to store the file... Maybe it's better to return just the np.array?\n# TODO: need to write a function that does the inverse job!!\ndef convert_to_gnuplot_3d(x, y, steady_pdf):\n ux = np.ravel(x)\n uy = np.ravel(y)\n usteady_pdf = np.ravel(steady_pdf)\n \"\"\"\n # Save data to a file so that it can be plotted by gnuplot\n #ux = ux[:, np.newaxis]\n #uy = uy[:, np.newaxis]\n steady_pdf = 4*np.real(rebuild_eigenfunction(ux,uy,stationary_coeffs))\n #output_array = (ux, uy,(np.log(steady_prob_density(ux,uy,c))/(np.log(10))) )\n \"\"\"\n np.savetxt('steady_pdf_gnuplot.dat', np.c_[ux,uy,steady_pdf])\n return ux, uy, usteady_pdf\n\n# The following function is a quick way to get a scatter plot of xyz data in a file\n# If we need a surface plot, have to reformat the data as explained in:\n# http://stackoverflow.com/questions/15118939/fill-2d-numpy-array-from-three-1d-numpy-arrays?answertab=active#tab-top\n# See also the last lines of power_spectrum_sin.py\ndef plot_xyz(filename):\n data = np.loadtxt(filename)\n x = data[:,0]\n y = data[:,1]\n z = data[:,2]\n\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n #ax.plot_surface(x, y, np.log(steady_prob_density(x,y,c)))\n ax.scatter(x, y, z) \n plt.show()\n\n# Function that finds the closest element within an array to a certain value (I think now only deals with real part)\n# Need to improve it: at the moment I think it doesn't work with complex values? Be careful! abs indeed works with complex values\ndef find_nearest(array,value):\n idx = (np.abs(array-value)).argmin() \n return idx\n\nif __name__ == '__main__':\n import timeit \n","sub_path":"numerics/matrix-methods/matrix-continued-fraction/utils_mcf.py","file_name":"utils_mcf.py","file_ext":"py","file_size_in_byte":43437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"542360624","text":"import os\nimport numpy as np\nimport torch\nimport random\nfrom torch.utils.data import Dataset\n\ndef create_dataset(data_path: str, data_index_path: str, config):\n local_conditioning = config[\"model\"][\"local_conditioning\"]\n if local_conditioning == \"mel\":\n return MelDataset(data_path, data_index_path, config)\n raise ValueError(local_conditioning)\n\n\nclass MelDataset(Dataset):\n def __init__(self, data_path: str, data_index_path: str, config):\n self.config = config\n self.data_path = data_path\n self.mel_path = os.path.join(data_path, \"mel\")\n self.wav_path = os.path.join(data_path, \"wav\")\n self.hop_length = config[\"data\"][\"hop_length\"]\n self.data_index_path = data_index_path\n with open(self.data_index_path, 'rt') as f:\n self.data_index = f.readlines()\n\n def __getitem__(self, index):\n mel_win = self.config[\"train\"][\"sequence_length\"]\n fileid = self.data_index[index]\n x = np.load(os.path.join(self.wav_path, '{}.npy'.format(fileid)))\n m = np.load(os.path.join(self.mel_path, '{}.npy'.format(fileid)))\n # file too short, pick another one\n while (m.shape[-1] < mel_win or\n x.shape[-1] != m.shape[-1] * self.hop_length):\n print(\"WARNING: %s has mel len of %d, needing at least %d, wave length is %d with hop size %d\"\n % (fileid, m.shape[-1], mel_win, x[-1], self.hop_length))\n index = random.randint(0, len(self.data_index) - 1)\n file = self.data_index[index]\n x = np.load(os.path.join(self.wav_path, '{}.npy'.format(fileid)))\n m = np.load(os.path.join(self.mel_path, '{}.npy'.format(fileid)))\n\n # randomly pick a segment\n max_mel_start = m.shape[-1] - mel_win - 1\n mel_start = random.randint(0, max_mel_start)\n mel = m[:, mel_start:mel_start + mel_win]\n audio_start = mel_start * self.hop_length\n audio = x[audio_start:audio_start + mel_win * self.hop_length]\n return (torch.from_numpy(mel).float(), torch.from_numpy(audio).float())\n\n def __len__(self):\n return len(self.data_index)\n","sub_path":"narv/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"142175061","text":"# Python 2 Compatibility\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\n# Imports \r\nimport math\r\nimport time\r\nimport tensorflow as tf\r\n\r\n\r\ndef evaluation_function_scale(sess, eval_op, initializable_iterator, handle, data_handle, data_size, steps_per_epoch, mode, reg_param):\r\n\r\n\t# Start timer\r\n\tstart_time = time.time()\r\n\t\t\t\r\n\t# Initialize iterator\r\n\tsess.run(initializable_iterator.initializer)\r\n\r\n\t# Initialize loss counter\r\n\teval_loss = 0\t\t\r\n\r\n\t# Iterate over training dataset\r\n\tfor _ in range(steps_per_epoch):\r\n\t\teval_loss += sess.run(eval_op, feed_dict={handle: data_handle})\r\n\r\n\t# Calculate average training data evaluation loss\r\n\teval_loss_avg = eval_loss/(data_size*reg_param)\r\n\teval_loss_avg = math.sqrt(2*eval_loss_avg)\r\n\r\n\t# Print training data evaluation results\r\n\tduration = time.time() - start_time\r\n\tif mode=='TRAINING':\r\n\t\tprint('TRAIN DATA EVALUATION: Num examples: %d Avg scale loss: %.10f Time for evaluation: %.2f sec' % (data_size, eval_loss_avg, duration))\r\n\telif mode=='VALIDATION':\r\n\t\tprint('VALIDATION DATA EVALUATION: Num examples: %d Avg scale loss: %.10f Time for evaluation: %.2f sec' % (data_size, eval_loss_avg, duration))\r\n\t\t\t\r\n\t\t\t\r\ndef inference_fun_scale(sess, eval_op, eval_train_iterator, validation_iterator, handle, eval_train_handle, validation_handle, train_size, validation_size, eval_train_steps_per_epoch, validation_steps_per_epoch):\r\n\r\n\t# EVALUATION RUN ON TRAINING SET\r\n\tevaluation_function_scale(sess, eval_op, eval_train_iterator, handle, eval_train_handle, train_size, eval_train_steps_per_epoch, 'TRAINING', 1)\r\n\r\n\t# EVALUATION RUN ON VALIDATION SET\r\n\tevaluation_function_scale(sess, eval_op, validation_iterator, handle, validation_handle, validation_size, validation_steps_per_epoch, 'VALIDATION', 1)","sub_path":"Networks/ScaleNet/Standalone/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"253310379","text":"# Copyright 2015 Hewlett-Packard Development Company, L.P. All Rights Reserved.\n#\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.\nimport itertools\nimport uuid\nimport eventlet\nfrom flanker import mime as flanker_mime\nfrom flanker.mime.message.headers import encoding\nfrom oslo_config import cfg\nfrom oslo_log import log\nfrom oslo_utils import timeutils\nfrom pidgey.common import context\nfrom pidgey.common import exceptions\nfrom pidgey.common import rpc\nfrom pidgey.common import service\nfrom pidgey.processor import rpcapi\nfrom pidgey.smtp import server\nfrom pidgey.smtp.policies import headers\nfrom pidgey.smtp.policies import split\nfrom pidgey import objects\nfrom pidgey import utils\nfrom pidgey import persistence\nCONF = cfg.CONF\nLOG = log.getLogger(__name__)\n\n\nclass SmtpValidators(object):\n \"\"\"Base class for implementing SMTP command validators.\n\n Sub-classes may implement some or all of the following functions. Leaving\n the `reply` argument untouched will return the default, successful reply\n from the command.\n\n - ``handle_banner(reply, address)``: Validate connecting address before\n sending the SMTP banner.\n - ``handle_ehlo(reply, ehlo_as)``: Validate the EHLO string.\n - ``handle_helo(reply, helo_as)``: Validate the HELO string.\n - ``handle_mail(reply, sender, params)``: Validate the sender address.\n - ``handle_rcpt(reply, recipient, params)``: Validate one recipient\n address.\n - ``handle_data(reply)``: Any remaining validation before receiving data.\n - ``handle_have_data(reply, data)``: Validate the received message data.\n - ``handle_rset(reply)``: Called before replying to an RSET command.\n - ``handle_tls()``: Called after a successful TLS handshake. This may be at\n the beginning of the session or after a `STARTTLS` command.\n\n :param session: When sub-classes are instantiated, instances are passed\n this object, stored and described in :attr:`session` below,\n that have useful information about the current session.\n\n \"\"\"\n\n def __init__(self, session):\n self.session = session\n\n\nclass Validators(SmtpValidators):\n \"\"\"Custom validators doing stuff like validation of domains etc.\"\"\"\n\n def __init__(self, session):\n super(Validators, self).__init__(session)\n\n def handle_rcpt(self, reply, address, params):\n domain = address.split('@')[1]\n try:\n ctxt = context.make_context(is_admin=True)\n objects.Domain.get(ctxt, domain)\n except exceptions.NotFound:\n reply.code = '550'\n reply.enhanced_status_code = '5.7.1'\n reply.message = 'Recipient <%s> Not allowed' % address\n except Exception as e:\n LOG.exception(e)\n\n\nclass SmtpSession(object):\n\n def __init__(self, address, validator_class, handoff):\n self.extended_smtp = False\n self.security = None\n self.address = address\n self.reverse_address = None\n self.handoff = handoff\n self.validators = validator_class(self) if validator_class else None\n self.message = None\n self.ehlo_as = None\n self.auth_result = None\n\n def _call_validator(self, command, *args):\n method = 'handle_' + command\n if hasattr(self.validators, method):\n getattr(self.validators, method)(*args)\n\n @property\n def protocol(self):\n proto = 'SMTP'\n if self.extended_smtp:\n proto = 'ESMTP'\n if self.security == 'TLS':\n proto += 'S'\n if self.auth_result is not None:\n proto += 'A'\n return proto\n\n def banner_(self, reply):\n self._call_validator('banner', reply, self.address)\n\n def ehlo(self, reply, ehlo_as):\n self._call_validator('ehlo', reply, ehlo_as)\n self.extended_smtp = True\n if reply.code == '250':\n self.ehlo_as = ehlo_as\n self.message = None\n\n def helo(self, reply, helo_as):\n self._call_validator('helo', reply, helo_as)\n if reply.code == '250':\n self.ehlo_as = helo_as\n self.message = None\n\n def tlshandshake(self):\n self._call_validator('tls')\n self.security = 'TLS'\n\n def auth(self, reply, result):\n self.auth_result = result\n\n def rset(self, reply):\n self.message = None\n\n def mail(self, reply, address, params):\n try:\n self._call_validator('mail', reply, address, params)\n except TypeError:\n self._call_validator('mail', reply, address)\n\n if reply.code == '250':\n self.message = objects.Message(\n id=str(uuid.uuid4()), sender=address, recipients=[])\n self.message.metadata = {}\n self.message.headers = objects.Headers()\n self.message.headers.obj_set_defaults()\n self.message.content = {}\n self.message.content_map = {}\n self.message.attachments = [\n objects.Attachment(\n size=5, name='foo', url='fooo', content_type='text')]\n\n def rcpt(self, reply, address, params):\n try:\n self._call_validator('rcpt', reply, address, params)\n except TypeError:\n self._call_validator('rcpt', reply, address)\n\n if reply.code == '250':\n self.message.recipients.append(address)\n\n def data(self, reply):\n self._call_validator('data', reply)\n\n def have_data(self, reply, data, err):\n if isinstance(err, exceptions.MessageTooBig):\n reply.code = '552'\n reply.message = '5.3.4 Message exceeded size limit'\n return\n if err:\n raise err\n self._call_validator('have_data', reply, data)\n if reply.code != '250':\n return\n self.message.metadata['client.ip'] = self.address[0]\n self.message.metadata['client.host'] = self.reverse_address\n self.message.metadata['client.name'] = self.ehlo_as\n self.message.metadata['client.protocol'] = self.protocol\n self.message.metadata['client.auth'] = self.auth_result\n\n msg = flanker_mime.from_string(data)\n for hk, hv in msg.headers.iteritems(raw=True):\n if not isinstance(hv, basestring):\n hv = encoding.to_mime(hk, hv)\n self.message.headers.append(hk, hv)\n\n self.message.subject = msg.subject\n if not msg.content_type.is_multipart():\n self.message.content[str(msg.content_type)] = msg.body\n results = self.handoff(self.message, data)\n if isinstance(results[0][1], exceptions.QueueError):\n reply.code = '550'\n reply.message = '5.6.0 Error queuing message'\n elif isinstance(results[0][1], exceptions.RelayError):\n relay_reply = results[0][1].reply\n reply.copy(relay_reply)\n else:\n reply.message = '2.6.0 Message accepted for delivery'\n self.message = None\n\n\nclass MTAService(service.Service):\n\n def __init__(self, *args, **kwargs):\n super(MTAService, self).__init__(*args, **kwargs)\n rpc.init(cfg.CONF)\n listen = (self._service_config.host, self._service_config.port)\n self.socket = eventlet.listen(listen)\n LOG.info('Listening on: %s:%s' % listen)\n self.store = persistence.get_persister(CONF.persistence_driver)\n self.queue_policies = []\n self.validator_class = Validators\n self.auth_class = None\n self.auth_obj = None\n\n @property\n def process_api(self):\n return rpcapi.ProcessorAPI.get_instance()\n\n @property\n def service_name(self):\n return 'mta'\n\n def start(self):\n self.queue_policies.extend([\n headers.AddDateHeader(),\n headers.AddReceivedHeader(),\n headers.AddMessageIdHeader(),\n split.RecipientDomainSplit()])\n super(MTAService, self).start()\n self.tg.add_thread(self.handle)\n\n def _run_policies(self, message):\n results = [message]\n\n def recurse(current, i):\n try:\n policy = self.queue_policies[i]\n except IndexError:\n return\n\n ret = policy.apply(current)\n if ret:\n results.remove(current)\n results.extend(ret)\n for env in ret:\n recurse(env, i + 1)\n\n else:\n recurse(current, i + 1)\n\n recurse(message, 0)\n return results\n\n def handle(self):\n LOG.debug('Handling thread is started..')\n while True:\n client, addr = self.socket.accept()\n self.tg.add_thread(self.dispatch, client, addr)\n\n def dispatch(self, client, addr):\n \"\"\"\n Dispatch a SMTP\n \"\"\"\n s = None\n try:\n session = SmtpSession(addr, self.validator_class, self.handoff)\n s = server.Server(\n client,\n session,\n auth_class=self.auth_class,\n auth_obj=self.auth_obj)\n s.handle()\n except exceptions.ConnectionLost:\n pass\n except Exception as e:\n LOG.exception(e)\n finally:\n if s:\n s.io.close()\n\n def handoff(self, message, data):\n now = timeutils.utcnow()\n message.time = now\n message.metadata[\"receiver\"] = self._host\n try:\n return self.enqueue(message, data)\n except Exception as e:\n LOG.exception(e)\n raise\n\n def enqueue(self, message, data):\n ctxt = context.make_context(is_admin=True)\n\n messages = self._run_policies(message)\n\n ids = utils.pool_imap(\n self.store.write, (messages, itertools.repeat(data), ))\n\n for msg in messages:\n self.process_api.process(ctxt, msg)\n\n results = zip(messages, ids)\n return results\n","sub_path":"pidgey/mta/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"362548180","text":"# Version 1.0 - 12/10/2018\n\nimport csv\n\nclass CSVHandler:\n \"\"\"Pass in an array of objects of the same type and handle to csv creation\"\"\"\n\n keys = []\n objects = []\n\n def __init__(self, objects):\n \"\"\"Uses the first object passed in to define keys. Checks that all objects contain keys\n\n Arguments:\n objects -- Any object of the same type ( object array expected )\n \"\"\"\n\n for key in objects[0].keys():\n self.keys.append(key)\n\n self.add_objects(objects)\n\n def add_objects(self, objects):\n \"\"\"Stores objects in objects if object has correct keys\n \n Arguments:\n objects -- Valid objects to add (object array expected)\"\"\"\n\n for obj in objects:\n if not self.is_valid_object(obj):\n raise Exception(\"Object {0} invalid. Requires keys {1}\".format(obj, self.keys))\n\n for obj in objects:\n self.objects.append(obj)\n\n\n def is_valid_object(self, obj):\n \"\"\"Uses stored keys to check if object is valid\n \n Arguments:\n obj -- The object you want to check\n \"\"\"\n\n for key in self.keys:\n if key not in obj:\n return False\n\n return True\n\n\n def write_csv(self, file_name):\n \"\"\"Write the objects stoored to CSV\n \n Arguments\n file_name -- name of file to write to\n \"\"\"\n\n with open(file_name, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=\",\", lineterminator=\"\\n\")\n \n writer.writerow( self.keys )\n\n for ob in self.objects:\n row = []\n\n for key in self.keys:\n row.append( ob[key] )\n \n writer.writerow( row )","sub_path":"tobias_py/basic/csv/csv_handler.py","file_name":"csv_handler.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"583363156","text":"import csv\nfrom datetime import datetime\n\n\nclass Bill:\n def __init__(self, client_name,\n date, number, sum):\n self.client_name = client_name\n self.date = datetime.strptime(date, \"%d.%m.%Y\")\n self.number = number\n self.sum = float(sum)\n\n def __str__(self):\n return f'{self.client_name} {self.date} {self.number} {self.sum}'\n\n\ndef csv_reader(file):\n bills = []\n with open(file) as f:\n reader = csv.reader(f)\n for row in reader:\n bills.append(row[0])\n\n for i in range(len(bills)):\n bills[i] = bills[i].replace('\\t', ' ')\n\n csv_objects = []\n for i in range(len(bills)-1):\n CSV = Bill(bills[i+1].partition(' ')[0],\n bills[i + 1].partition(' ')[2].partition(' ')[0],\n bills[i + 1].partition(' ')[2].partition(' ')[2].partition(' ')[0],\n bills[i + 1].partition(' ')[2].partition(' ')[2].partition(' ')[2])\n csv_objects.append(CSV)\n\n return csv_objects\n\n\ndef sum_of_payment(payments):\n return sum([float(x.sum) for x in payments])\n\n\ndef sort_by_name(amounts):\n for i in range(len(amounts) - 1):\n for j in range(len(amounts) - i - 1):\n if amounts[j].client_name < amounts[j + 1].client_name:\n amounts[j], amounts[j + 1] = amounts[j + 1], amounts[j]\n\n return amounts\n\n\ndef sort_by_date_after_sort_by_name(amounts):\n for i in range(len(amounts) - 1):\n for j in range(len(amounts) - i - 1):\n if amounts[j].date > \\\n amounts[j + 1].date and \\\n amounts[j].client_name == \\\n amounts[j + 1].client_name:\n amounts[j], amounts[j + 1] = \\\n amounts[j + 1], amounts[j]\n return amounts\n","sub_path":"bills/bills_reworked/csv_script.py","file_name":"csv_script.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"387098645","text":"import re \nlanuage='PythonC#JavaC#PHPC#'\ndef convert(value):\n matched=value.group()\n return '!!'+matched+'!!'\n#4~8\n# r=re.findall('c#.{3}',lanuage,re.I|re.S)\nr=re.sub('C#',convert,lanuage,1)\n# r=lanuage.replace('C#','GO')\nprint(r)\n\n","sub_path":"python学习/实训/ten/c8.py","file_name":"c8.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"281809639","text":"# Remove every negative value from `numbers', without changing the list itself.\n\nnumbers = [1, -7, 2, -9, 3, -1, 4, -2, 5, -9, 6, -1, 7, -4, 8, -8, 9]\n\n# Simple Solution\n\nresult = []\nfor value in numbers:\n if value < 0:\n result.append(value)\n\n# Advanced Solution: Filter() Function\n\nis_positive = lambda x: x >= 0\nresults = filter(is_positive, numbers)\n","sub_path":"solutions/remove-negatives.py","file_name":"remove-negatives.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"331056246","text":"\"\"\"Logsforhumans pretends logs all models changes to human beings.\"\"\"\n# coding: utf-8\nimport threading\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\nfrom django.db.models.fields.related import ManyToManyField\nfrom django.db.models.signals import post_delete, m2m_changed\nfrom django.dispatch import receiver\nfrom django.db.models.fields.related_descriptors import ManyToManyDescriptor\nfrom six import text_type as unicode\n\nDEFAULT_DELETE_MESSAGE = u'The {model_name} \"{instance_str}\" (id={instance_id}) was deleted'\nDEFAULT_CREATION_MESSAGE = u'The {model_name} \"{instance_str}\" was created'\nDEFAULT_FIELD_CHANGE_MESSAGE = u'The field {field_verbose_name} was changed from \"{old_value}\" to \"{new_value}\"'\nDEFAULT_M2M_FIELDS_MESSAGE = u'The {item_model_name} \"{item}\" was {action} in the field {m2m_table}'\nDEFAULT_GENERIC_CHANGE = u'The field {field_verbose_name} was changed'\n\n\ndef get_delete_format_message():\n return getattr(\n settings,\n 'LOGSFORHUMANS_DELETE_MESSAGE',\n DEFAULT_DELETE_MESSAGE)\n\n\ndef get_creation_format_message():\n return getattr(\n settings,\n 'LOGSFORHUMANS_CREATION_MESSAGE',\n DEFAULT_CREATION_MESSAGE)\n\n\ndef get_field_change_format_message():\n return getattr(\n settings,\n 'LOGSFORHUMANS_FIELD_CHANGE_MESSAGE',\n DEFAULT_FIELD_CHANGE_MESSAGE)\n\n\ndef get_m2m_fields_change_format_message():\n return getattr(\n settings,\n 'LOGSFORHUMANS_M2M_FIELDS_CHANGE_MESSAGE',\n DEFAULT_M2M_FIELDS_MESSAGE)\n\n\ndef get_generic_change_format_message():\n return getattr(\n settings,\n 'LOGSFORHUMANS_GENERIC_CHANGE_MESSAGE',\n DEFAULT_GENERIC_CHANGE)\n\n\nclass HumanLog(models.Model):\n description = models.TextField(blank=False)\n\n app_label = models.CharField(max_length=255)\n model_name = models.CharField(max_length=255)\n object_id = models.CharField(max_length=512)\n\n creation_date = models.DateTimeField(\n auto_now_add=True, verbose_name=u'Created in')\n updated_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n null=True,\n blank=True,\n editable=False,\n verbose_name=u'Updated by',\n on_delete=models.CASCADE)\n\n class Meta:\n ordering = ('-creation_date', )\n\n def __str__(self):\n return self.description\n\n\nLOGSFORHUMAN_THREAD = threading.local()\n\n\ndef get_models_changelogs(self):\n to_ignore = getattr(self, 'LOGSFORHUMANS_IGNORE_DETAILS', [])\n ignore_changes = getattr(self, 'LOGSFORHUMANS_IGNORE_CHANGES', [])\n model_name = self._meta.verbose_name\n instance_str = unicode(self)\n instance_id = self.pk\n\n tem_pk = bool(instance_id)\n if not tem_pk:\n return get_creation_format_message().format(**locals())\n\n old_instance = self.__class__.objects.filter(pk=self.pk).first()\n if not old_instance:\n return u''\n\n description = u''\n for field in self._meta.get_fields():\n field_name = field.name\n if field_name in ignore_changes:\n continue\n\n if not isinstance(field, ManyToManyField):\n if not hasattr(self, field_name):\n continue\n\n new_value = getattr(self, field_name)\n if hasattr(self, 'get_{}_display'.format(field_name)):\n new_value = getattr(\n self, 'get_{}_display'.format(field_name))()\n\n old_value = getattr(old_instance, field_name)\n if hasattr(old_instance, 'get_{}_display'.format(field_name)):\n old_value = getattr(\n old_instance, 'get_{}_display'.format(field_name))()\n\n if new_value != old_value:\n field_verbose_name = field.verbose_name\n if field_name in to_ignore:\n description += get_generic_change_format_message().format(\n **locals()) + '\\n'\n else:\n description += get_field_change_format_message().format(\n **locals()) + '\\n'\n return description\n\n\ndef can_have_changelog(self):\n if not hasattr(self, 'skip_changelog') or not self.skip_changelog:\n return True\n return False\n\n\ndef get_logs(self):\n return HumanLog.objects.filter(\n model_name=self._meta.model_name,\n app_label=self._meta.app_label,\n object_id=self.pk)\n\n\ndef add_log(self, log):\n user = self.get_current_user()\n if isinstance(user, get_user_model()):\n human_log = HumanLog.objects.create(\n description=log,\n app_label=self._meta.app_label,\n model_name=self._meta.model_name,\n object_id=self.pk,\n updated_by=user\n )\n else:\n human_log = HumanLog.objects.create(\n description=log,\n app_label=self._meta.app_label,\n model_name=self._meta.model_name,\n object_id=self.pk)\n if hasattr(self, 'logsforhumans_onchange'):\n self.logsforhumans_onchange(human_log)\n\n\ndef add_delete_log(self, kwargs):\n if not self.can_have_changelog():\n return\n\n model_name = self._meta.verbose_name\n instance_str = unicode(self)\n instance_id = self.pk\n\n message = get_delete_format_message().format(**locals())\n self.add_log(message)\n\n\ndef get_save_method(original_save):\n def save(self, *args, **kwargs):\n description = None\n if self.can_have_changelog():\n description = self.get_models_changelogs()\n original_save(self, *args, **kwargs)\n if description:\n self.add_log(description)\n\n return save\n\n\ndef get_current_user(*args):\n \"\"\"Return the current user configured in middleware.\"\"\"\n if hasattr(LOGSFORHUMAN_THREAD, 'request'):\n return getattr(LOGSFORHUMAN_THREAD.request, 'user', None)\n\n\ndef generate_m2m_change_logs(**kwargs):\n if not hasattr(kwargs['instance'], 'add_log'):\n return\n\n sender = kwargs['sender']\n create_logs = False\n action = u''\n if kwargs.get('action') == 'post_remove':\n create_logs = True\n action = 'removido'\n elif kwargs.get('action') == 'post_add':\n create_logs = True\n action = 'adicionado'\n if not create_logs:\n return\n log = u''\n for pk in kwargs.get('pk_set', list()):\n item = kwargs.get('model').objects.filter(pk=pk).first()\n item_model_name = kwargs.get('model')._meta.verbose_name\n m2m_table = kwargs.get('sender')._meta.db_table\n\n # getting the m2m field name/verbose_name\n class_obj = kwargs['instance'].__class__\n m2m_field_verbose_name = ''\n for field in dir(class_obj):\n if isinstance(getattr(class_obj, field), ManyToManyDescriptor):\n if getattr(class_obj, field).through == sender:\n m2m_field_verbose_name = getattr(class_obj, field).field.verbose_name\n\n log += get_m2m_fields_change_format_message().format(**locals())\n log += '\\n'\n if log:\n kwargs['instance'].add_log(log)\n\n\ndef generate_humanlogs(class_obj):\n\n class_obj.can_have_changelog = can_have_changelog\n class_obj.get_logs = get_logs\n class_obj.get_models_changelogs = get_models_changelogs\n class_obj.add_log = add_log\n class_obj.add_delete_log = add_delete_log\n class_obj.save = get_save_method(class_obj.save)\n class_obj.get_current_user = get_current_user\n class_obj.generate_m2m_change_logs = generate_m2m_change_logs\n\n @receiver(post_delete, sender=class_obj, weak=False)\n def class_instance_post_delete(**kwargs):\n instance = kwargs['instance']\n instance.add_delete_log(kwargs)\n class_obj.class_instance_post_delete = class_instance_post_delete\n for field in dir(class_obj):\n if isinstance(getattr(class_obj, field), ManyToManyDescriptor):\n through = getattr(class_obj, field).through\n\n # the \"dispatch_uid\" argument is to avoid bind function twice\n # in m2m fields the two classes involved may have the same field\n # in the list \"dir(obj)\"\n @receiver(m2m_changed, sender=through, weak=False, dispatch_uid=unicode(through))\n def class_instance_m2m_changed(**kwargs):\n class_obj.generate_m2m_change_logs(**kwargs)\n\n return class_obj\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"259618753","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 14 11:53:45 2019\n\n@author: hugomeyer\n\"\"\"\n\n\nimport numpy as np\nfrom scipy.signal import butter, lfilter\nimport matplotlib.pyplot as plt\nimport os\n\n\n\n\nclass Similarity_cut(object):\n def __init__(self, index, time, label, score=-1):\n self.index=index\n self.score=score\n self.label=label\n self.time = time\n \n def info(self):\n return {'index': self.index, 'time': self.time, 'score': self.score, 'label': self.label}\n\n\n\n \nclass Similarity(object):\n def __init__(self, start, end, data, fps):\n if start > len(data) or end > len(data):\n raise ValueError(\"The defined subscene is out of the scene boundaries.\")\n\n self.start=start\n self.end=end\n self.values = data\n self.indices=np.arange(start, end+1, 1)\n self.tops = []\n self.pits = []\n self.fps = fps\n self.features = []\n self.feature_labels = {\n 'valley_pit': 1, \n 'plateau_start': 2, \n 'plateau_end': 3, \n 'hill_start': 4, \n 'hill_end': 5, \n 'hill_top': 6\n }\n \n \n\n \n def processing(self):\n #if sum(self.values) != 0:\n self.remove_discontinuities(mu=0.12, eps=0.25, nb_pts=5)\n self.butter_lowpass_filter(2.5)\n self.find_tops_pits(nb_pts=6)\n # return 1\n #else:\n # return 0\n \n \n \n def remove_discontinuities(self, mu=0.12, eps=0.25, nb_pts=5):\n\n signal = np.asarray(self.values).copy()\n \n \n scores = []\n for i in range(len(signal)-nb_pts+1):\n packet = signal[i:i+nb_pts]\n for j in range(nb_pts-1, 2, -1):\n if abs(packet[0]-packet[j]) < mu and min(packet[0], packet[j])-min(packet[:j+1]) > eps:\n score = np.argmin(packet)+i+1\n if score not in scores:\n #scores.append(score)\n signal[i:i+j+1] = np.linspace(packet[0], packet[j], j+1).tolist()\n\n self.values = signal.tolist()\n \n \n \n\n\n def butter_lowpass_filter(self, freq):\n\n data = np.asarray(self.values).copy()\n if len(data)>10:\n order = 6\n ratio_pts_used_for_side=0.1\n fs = 30\n shift={1: 27, 2: 12, 2.5: 8, 3: 7, 4: 5, 5: 4, 6: 3}\n \n #Avoid side effects\n ext_size = max(round(ratio_pts_used_for_side*data.size), 1)#, shift[freq]+1)\n sig_shift = min(shift[freq], ext_size-1)\n x1 = np.flipud(data[1:ext_size+1])\n x2 = np.flipud(data[-1-ext_size:-1])\n data = np.insert(data, 0, x1)\n data = np.append(data, x2)\n \n #filtering\n b, a = self.butter_lowpass(freq, fs, order=order)\n y = lfilter(b, a, data)\n inf, sup = ext_size+sig_shift, -ext_size+sig_shift\n self.values = y[inf : sup]\n\n \n \n \n def butter_lowpass(self, cutoff, fs, order=5):\n \"\"\"\n PARAMETERS: \n - cutoff: cutoff frequency determining the boudary of the low pass band o the filter\n - fs: sampling frequency\n - order: order of the filter\n \n DESCRIPTION:\n Compute the filtering coefficients given the chosen parameters\n \n RETURN:\n - b, a: filter coefficients \n \"\"\"\n nyq = 0.5 * fs\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\n return b, a\n \n \n \n def extract_features(self):\n if self.tops.any() or self.pits.any():\n \n pits_tops, labels = self.detect_pits_tops()\n \n \n #features = [Similarity_cut(int(el[0]), int(el[0])/self.fps, labels=[], score=self.compute_score_top(el))\n # for el, label in zip(pits_tops, labels) if label=='top']\n \n \n features = self.find_labels(pits_tops, labels)\n \n self.features = np.asarray(features)[np.argsort([cut.index for cut in features])].tolist()\n #self.pit_cuts = self.score_pits(pits_tops, labels)\n \n \n featured_pits_labels = ['hill_start', 'hill_end', 'valley_pit']\n indices_of_featured_pits = [feat.index for feat in self.features if any(elem in feat.label for elem in featured_pits_labels)]\n indices_to_rm = [i for i in range(self.pits.shape[0]) if self.pits[i, 0] in indices_of_featured_pits]\n\n self.pits = np.delete(self.pits, indices_to_rm, axis=0)\n\n \n \n \n \n \n \n def find_labels(self, pits_tops, labels):\n features = []\n double_tops = [i for i, (el1, el2) in enumerate(zip(labels[:-1], labels[1:])) if [el1, el2] == ['top', 'top']]\n double_pits = [i for i, (el1, el2) in enumerate(zip(labels[:-1], labels[1:])) if [el1, el2] == ['pit', 'pit']]\n\n for i in double_tops:\n front_top = pits_tops[i]\n back_top = pits_tops[i+1]\n if i-1 >= 0:\n front_pit = pits_tops[i-1]\n else:\n local_min_left, ind_left = self.find_next_min_local(front_top, 'left', nb_pts=6)\n front_pit = [ind_left, local_min_left]\n if i+2 < len(pits_tops):\n back_pit = pits_tops[i+2]\n else:\n local_min_right, ind_right = self.find_next_min_local(back_top, 'right', nb_pts=6)\n back_pit = [ind_right, local_min_right]\n \n if self.plateau_shaped(front_top, back_top, front_pit, back_pit, spread_factor=1.5):#The higher the spread_factor, the spreader we allow the hill to be\n ## Back top\n front_score = self.compute_score_top(front_top)\n back_score = self.compute_score_top(back_top)\n features.append(Similarity_cut(int(front_top[0]), int(front_top[0])/self.fps, \n label='plateau_start', score=front_score))\n features.append(Similarity_cut(int(back_top[0]), int(back_top[0])/self.fps, \n label='plateau_end', score=back_score))\n '''\n if i-1 >= 0:\n features.append(Similarity_cut(int(pits_tops[i-1][0]), int(pits_tops[i-1][0])/self.fps, \n label='hill_start', score=front_score))\n if i+2 < len(pits_tops):\n features.append(Similarity_cut(int(pits_tops[i+2][0]), int(pits_tops[i+2][0])/self.fps, \n label='hill_end', score=back_score))\n '''\n for i in double_pits:\n if i-1 >= 0:\n features.append(Similarity_cut(int(pits_tops[i-1][0]), int(pits_tops[i-1][0])/self.fps, \n label='valley_start', score=self.compute_score_top(pits_tops[i-1])))\n if i+2 < len(pits_tops):\n features.append(Similarity_cut(int(pits_tops[i+2][0]), int(pits_tops[i+2][0])/self.fps, \n label='valley_end', score=self.compute_score_top(pits_tops[i+2])))\n \n already_visited = [i for i, el in enumerate(pits_tops) if el[0] in [feat.index for feat in features]]\n single_tops = [i for i, label in enumerate(labels) if label == 'top' and i not in already_visited]\n \n for i in single_tops:\n single_top = pits_tops[i]\n if i > 0:\n # Replace top by its previous pit if the slope is low \n right_min_local, _ = self.find_next_min_local(single_top, 'right')\n ratio = (single_top[1]-right_min_local)/(single_top[1]-pits_tops[i-1][1])\n time_ratio = (single_top[1]-pits_tops[i-1][1])*100/(single_top[0]-pits_tops[i-1][0])\n if ratio < 0.25 and ratio > 0 and labels[i-1] != 'top' and time_ratio<2:\n\n features.append(Similarity_cut(int(pits_tops[i-1][0]), int(pits_tops[i-1][0])/self.fps, \n label='valley_pit', score=self.compute_score_top(single_top)))\n \n # if not pit_replaced_top:\n features.append(Similarity_cut(int(single_top[0]), int(single_top[0])/self.fps, \n label='hill_top', score=self.compute_score_top(single_top)))\n return features\n \n \n def find_tops_pits(self, nb_pts):\n tops = []\n pits = []\n\n data =self.values\n nb_pts = min(nb_pts, int(len(data)/2))\n going_down = data[0] > data[nb_pts]\n old_moving_avg = data[0]\n for i in range(len(data)-nb_pts+1):\n new_moving_avg = sum(data[i:i+nb_pts])/len(data[i:i+nb_pts])\n if going_down and new_moving_avg>old_moving_avg:\n pits.append(i+np.argmin(data[i:i+nb_pts])+1)\n going_down = False\n if not going_down and new_moving_avg 0.1]\n else:\n pits = [pit for pit in pits \n if max(data[pit] - self.find_next_max_local([pit, data[pit]], 'right')[0], \n data[pit] - self.find_next_max_local([pit, data[pit]], 'left')[0]) \n > 0.1]\n \n \n pits=np.asarray([(pit_ind, data[pit_ind-1]) for pit_ind in pits])\n tops=np.asarray([(top_ind, data[top_ind-1]) for top_ind in tops])\n\n self.tops, self.pits = tops, pits\n \n \n\n \n def keep_meaningful_tops_pits(self, tops, pits):\n\n data =self.values\n seq = np.sort(tops+pits)\n remove=[]\n start=0\n treshold=0.1\n if pits[0]= 0 and (seq[back] in remove or (seq[back] in tops and data[seq[back]]tresh2:\n remove.append(pits[i+1])\n \n pits = [pit for pit in pits if pit not in remove]\n return [el for el in pits_tops if el not in remove], pits\n \n \n \n \n def respawn_first_top_of_deleted_serie(self, tops_pits, tops, remove, nb_min_el_in_serie):\n if len(remove) < 2:\n return remove\n \n indices = np.asarray([i for i, el in enumerate(tops_pits) if el in remove])\n indices_shifted = np.append(indices[1:], indices[-1]+1)\n diff = indices_shifted-indices-1\n counter = 0\n respawned_indices=[]\n first_index=0\n for i, el in enumerate(diff):\n if el:\n if counter >= nb_min_el_in_serie-1 and indices[i]+1 < len(tops_pits):\n if tops_pits[indices[i]+1] in tops:\n tops_pits[indices[i]]\n respawned_indices.append(first_index)\n counter=0\n else:\n if counter == 0:\n first_index=i\n counter+=1\n if counter >= nb_min_el_in_serie-1 and indices[i]+1 < len(tops_pits):\n if tops_pits[indices[i]+1] in tops:\n respawned_indices.append(first_index)\n respawned_indices = [ind if remove[ind] in tops else ind+1 for ind in respawned_indices]\n return np.delete(remove, respawned_indices).tolist()\n \n \n \n \n \n def rm_more_than_2_consec_tops(self, tops_pits, tops):\n rm_consec = [tops_pits[i] for i in range(1, len(tops_pits)-1) \n if tops_pits[i-1] in tops and tops_pits[i] in tops and tops_pits[i+1] in tops]\n\n return[top for top in tops if top not in rm_consec]\n \n\n \n \n \n \n def detect_pits_tops(self):\n\n if not self.tops.any():\n pits_tops=self.pits\n elif not self.pits.any():\n pits_tops=self.tops\n else:\n pits_tops = np.concatenate((self.tops, self.pits))\n \n indices = np.argsort(pits_tops[:, 0])\n pits_tops = pits_tops[indices]\n labels = np.asarray(['top']*self.tops.shape[0] + ['pit']*self.pits.shape[0])[indices]\n \n \n return pits_tops, labels\n \n \n \n \n def score_pits(self, pits_tops, labels):\n pits = [pits_tops[i] for i in range(len(pits_tops)) if labels[i]=='pit']\n return [Similarity_cut(int(pit[0]), pit[0]/self.fps, [], score=self.compute_score_pit(pit)) for pit in pits]\n \n \n\n \n def compute_score_top(self, top):\n left_min_local, _ = self.find_next_min_local(top, 'left', nb_pts=6)\n right_min_local, _ = self.find_next_min_local(top, 'right', nb_pts=6)\n\n return ((abs(left_min_local-right_min_local)**2*(top[1]-min(left_min_local, right_min_local)))**(1./3))*2\n \n \n \n def compute_score_pit(self, pit):\n left_max_local, _ = self.find_next_max_local(pit, 'left')\n right_max_local, _ = self.find_next_max_local(pit, 'right')\n\n return ((abs(left_max_local-right_max_local)**2*(max(left_max_local, right_max_local)-pit[1]))**(1./3))*2\n \n \n \n def find_next_min_local(self, top, side, nb_pts=10):\n nb_pts = min(nb_pts, int(len(self.values)/2))\n i = int(top[0])-self.start\n old_moving_avg = self.values[i]\n if side == 'right':\n while i+nb_pts < len(self.values)+1:\n new_moving_avg = sum(self.values[i:i+nb_pts])/len(self.values[i:i+nb_pts])\n if new_moving_avg>old_moving_avg:\n min_index=i+np.argmin(self.values[i:i+nb_pts])+1+self.start\n min_value=self.values[min_index-self.start]\n return min_value, min_index#[min_index, min_value]\n\n i+=1\n old_moving_avg = new_moving_avg\n \n return self.values[-1], len(self.values)\n else:\n while i-nb_pts+1 >= 0:\n new_moving_avg = sum(self.values[i-nb_pts+1:i+1])/len(self.values[i-nb_pts+1:i+1])\n if new_moving_avg>old_moving_avg:\n min_index=i-np.argmin(self.values[i-nb_pts+1:i+1][::-1])+self.start\n min_value=self.values[min_index-self.start]\n return min_value, min_index#[min_index, min_value]\n\n i-=1\n old_moving_avg = new_moving_avg\n \n return self.values[0], self.start#[self.start, ]\n \n\n\n def find_next_max_local(self, pit, side, nb_pts=10):\n nb_pts = min(nb_pts, int(len(self.values)/2))\n i = int(pit[0])-self.start\n old_moving_avg = self.values[i]\n if side == 'right':\n while i+nb_pts < len(self.values)+1:\n new_moving_avg = sum(self.values[i:i+nb_pts])/len(self.values[i:i+nb_pts])\n if new_moving_avg= 0:\n new_moving_avg = sum(self.values[i-nb_pts+1:i+1])/len(self.values[i-nb_pts+1:i+1])\n if new_moving_avgspread_factor:\n return False\n elif abs(back_top[1]-front_top[1])<0.1:\n return True\n else:\n return False\n \n \n \n \n \n def lineplot_analog(self, clip_ID, yticks=0.1, duration=None, fps=None, title=None,\n tops_pits=True, save=False, path='../'):\n #plt.figure(num=None, , dpi=80, facecolor='w', edgecolor='k')\n if title is None:\n title = ''\n if duration is None:\n x_label='Frames'\n else:\n x_label = 'Time'\n y_label='Similarity'\n\n \n factor = 1\n if duration is not None:\n factor = 1/self.fps\n elif fps is not None:\n factor = fps/self.fps\n \n x = np.asarray(self.indices)*factor#+self.offset\n y = np.asarray(self.values)\n \n if save:\n dpi = 80\n else:\n dpi = 80\n \n fig, ax = plt.subplots(figsize=(10, 4), dpi=dpi)\n \n if x.shape[0] > 400:\n step = round(50*factor)\n elif x.shape[0] > 200:\n step = round(20*factor)\n elif x.shape[0] > 100:\n step = round(10*factor)\n elif x.shape[0] > 30:\n step = max(round(5*factor, 1), 0.1)\n else:\n step = max(round(1*factor, 1), 0.1)\n \n X_ticks_maj = np.arange(max(int(x[0])-factor, 0), int(x[-1])+2, step)\n y_ticks = np.arange(int(y.min()), round(y.max(), 1), yticks)\n X_ticks_min = np.arange(x[0]-factor, x[-1]+1, step*0.2)\n X_ticks_min[0] = int(x[0])\n \n if duration is not None:\n X_ticks_maj[0] = 0\n else:\n X_ticks_maj[0] = 1\n \n ax.spines['top'].set_color('white')\n ax.spines['right'].set_color('white')\n \n ax.set_xticks(X_ticks_maj)\n ax.set_xticks(X_ticks_min, minor=True)\n ax.set_yticks(y_ticks)\n ax.grid(which='both')\n ax.grid(which='minor', alpha=0.4)\n ax.grid(which='major', alpha=1)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n \n\n \n plt.title(title)\n \n plt.plot(x, y)\n \n if tops_pits:\n if self.features:\n for feat in self.features:\n if any(elem in feat.label for elem in ['hill_start', 'hill_end']):\n color='k'\n elif any(elem in feat.label for elem in ['plateau_start', 'plateau_end']):\n color='b'\n elif any(elem in feat.label for elem in ['valley_start', 'valley_end']):\n color='m'\n else:\n color='g'\n \n plt.scatter(feat.time, self.values[feat.index-1], color=color, s=180, alpha=0.2)\n plt.scatter(feat.time, self.values[feat.index-1], color=color, s=40, alpha=1)\n score = '{:.2f}' .format(feat.score)\n ax.annotate(score, (feat.time, self.values[feat.index-1]))\n \n if self.pits.any():\n\n pits_ind = self.pits[:, 0].astype(int)-1\n\n indices = self.indices[pits_ind]*factor\n plt.scatter(indices, self.pits[:, 1], color='r', s=180, alpha=0.2)\n plt.scatter(indices, self.pits[:, 1], color='r', s=40, alpha=1)\n \n \n string = ''\n\n \n if save == True:\n plt.savefig(os.path.join(path, 'Clip_{}_similarity2' .format(clip_ID)+string+'.png'))\n else:\n plt.show()\n \n \n ","sub_path":"src/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":24086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238946299","text":"#!python3 \n\n\"\"\"\n##### Task 1\nAsk the user to enter an integer.\nPrint the multiplication tables up to 12 for that number\nusing a for loop instead of a while loop.\n(2 points)\n\ninputs:\nint number\n\noutputs:\nmultiples of that number\n\nexample:\nEnter number:4\n4 8 12 16 20 24 28 32 36 40 44 48\n\"\"\"\n\na = int(input(\"Enter an integer: \"))\n\nfor i in range(1,13):\n print(a * i, end=\" \")\n","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"334054680","text":"from sense_hat import SenseHat\nimport random\nfrom math import floor, ceil\nimport time\nimport sys\nimport os\n\nclass MatrixRect:\n\n def __init__(self, w, h, ledc_on, filled):\n self.matrix = []\n self.ledc_black = (0, 0, 0)\n self.ledc_on = ledc_on\n self.w = w\n self.h = h\n self.filled = filled\n self.createBlackMatrix();\n self.createPattern()\n\n def createBlackMatrix(self):\n for p in range(0,64):\n self.matrix.append(self.ledc_black)\n\n def createPattern(self):\n for r in range(0,self.w):\n for c in range(0, self.h):\n if self.filled == False:\n ledc = self.ledc_black\n if r == 0 or (r == self.w - 1):\n ledc = self.ledc_on\n elif c == 0 or c == self.h - 1:\n ledc = self.ledc_on\n\n self.matrix[r*8+c] = ledc\n else:\n self.matrix[r*8+c] = ledc_on\n\nsense = SenseHat()\ni = 0\ndir = 1\nledc_on = (255, 0, 0)\n\nwhile True:\n try:\n m = MatrixRect(i, i, ledc_on, False)\n sense.set_pixels(m.matrix)\n\n temp_i = i+1*dir\n if temp_i <= 8 and temp_i >= 0:\n i = temp_i\n else:\n ledc_on = (round(random.random()*255), round(random.random()*255), round(random.random()*255))\n dir = dir*-1\n\n time.sleep(0.1)\n except KeyboardInterrupt:\n print('Interrupted')\n sense.clear()\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)","sub_path":"sensehat/rect_animated.py","file_name":"rect_animated.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612277339","text":"import requests\nfrom order.models import Order\n\n\nclass BaseConnector(object):\n def __init__(self, instance, server_url):\n self.server_url = server_url\n self.instance = Order.objects.get(id=instance)\n\n def sync_status(self):\n data = self.get_serializer(self.instance)\n data_status = {\n 'status': data['status'],\n }\n url = f'{self.server_url}/order/item/{self.instance.number}/'\n self.send(url, data_status, method='patch')\n\n def create_order(self):\n url = f'{self.server_url}/order/create/'\n data = self.get_serializer(self.instance)\n for i in ['id', 'synced']:\n del data[i]\n self.send(url, data, method='post')\n\n def send(self, url, data, method):\n request = {\n 'post': requests.post,\n 'patch': requests.patch,\n }\n resp = request[method](url, data=data)\n print(resp.status_code, resp.text)\n if resp.status_code == 200 or resp.status_code == 201:\n self.instance.synced = True\n else:\n self.instance.synced = False\n self.instance.save()\n\n @staticmethod\n def get_serializer(instance):\n from order.serializers import OrderSerializer\n serializer = OrderSerializer(instance)\n return serializer.data\n","sub_path":"apps/exchange/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"411615650","text":"# Copyright (c) 2013 Nexedi SA and Contributors. All Rights Reserved.\nimport transaction\nfrom Products.SlapOS.tests.testSlapOSMixin import \\\n testSlapOSMixin\nfrom zExceptions import Unauthorized\nfrom DateTime import DateTime\nfrom functools import wraps\nfrom Products.ERP5Type.tests.utils import createZODBPythonScript\nimport difflib\n\nclass TestSlapOSSoftwareInstance_requestValidationPayment(testSlapOSMixin):\n\n def beforeTearDown(self):\n transaction.abort()\n\n def createCloudContract(self):\n new_id = self.generateNewId()\n contract = self.portal.cloud_contract_module.newContent(\n portal_type='Cloud Contract',\n title=\"Contract %s\" % new_id,\n reference=\"TESTCONTRACT-%s\" % new_id,\n )\n self.portal.portal_workflow._jumpToStateFor(contract, 'invalidated')\n return contract\n\n def createPaymentTransaction(self):\n new_id = self.generateNewId()\n return self.portal.accounting_module.newContent(\n portal_type='Payment Transaction',\n title=\"Payment %s\" % new_id,\n reference=\"TESTPAY-%s\" % new_id,\n )\n\n def createInvoiceTransaction(self):\n new_id = self.generateNewId()\n return self.portal.accounting_module.newContent(\n portal_type='Sale Invoice Transaction',\n title=\"Invoice %s\" % new_id,\n reference=\"TESTINV-%s\" % new_id,\n created_by_builder=1,\n )\n\n def createNeededDocuments(self):\n new_id = self.generateNewId()\n person = self.portal.person_module.newContent(\n portal_type='Person',\n title=\"Person %s\" % new_id,\n reference=\"TESTPERS-%s\" % new_id,\n )\n subscription = self.portal.hosting_subscription_module.newContent(\n portal_type='Hosting Subscription',\n title=\"Subscription %s\" % new_id,\n reference=\"TESTSUB-%s\" % new_id,\n destination_section_value=person,\n )\n instance = self.portal.software_instance_module.newContent(\n portal_type='Software Instance',\n title=\"Instance %s\" % new_id,\n reference=\"TESTINST-%s\" % new_id,\n specialise_value=subscription,\n )\n return person, instance, subscription\n\n def test_requestValidationPayment_REQUEST_disallowed(self):\n person, instance, subscription = self.createNeededDocuments()\n self.assertRaises(\n Unauthorized,\n instance.SoftwareInstance_requestValidationPayment,\n REQUEST={})\n\n def test_prevent_concurrency(self):\n person, instance, subscription = self.createNeededDocuments()\n tag = \"%s_requestValidationPayment_inProgress\" % person.getUid()\n person.reindexObject(activate_kw={'tag': tag})\n transaction.commit()\n\n result = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(result, None)\n\n def test_addCloudContract(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = instance.SoftwareInstance_requestValidationPayment()\n\n # Default property\n self.assertEquals(contract.getPortalType(), 'Cloud Contract')\n self.assertEquals(contract.getValidationState(), 'invalidated')\n self.assertEquals(contract.getDestinationSection(), person.getRelativeUrl())\n self.assertEquals(contract.getTitle(),\n 'Contract for \"%s\"' % person.getTitle())\n\n def test_addCloudContract_do_not_duplicate_contract_if_not_reindexed(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = instance.SoftwareInstance_requestValidationPayment()\n transaction.commit()\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertNotEquals(contract, None)\n self.assertEquals(contract2, None)\n\n def test_addCloudContract_existing_invalidated_contract(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = instance.SoftwareInstance_requestValidationPayment()\n transaction.commit()\n self.tic()\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertNotEquals(contract, None)\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n\n def test_addCloudContract_existing_validated_contract(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = instance.SoftwareInstance_requestValidationPayment()\n contract.validate()\n transaction.commit()\n self.tic()\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertNotEquals(contract, None)\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n\n def test_do_nothing_if_validated_contract(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n contract.edit(destination_section_value=person)\n contract.validate()\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), \"\")\n self.assertEquals(contract2.getValidationState(), \"validated\")\n\n def test_validate_contract_if_payment_found(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n contract.edit(destination_section_value=person)\n payment = self.createPaymentTransaction()\n payment.edit(\n default_destination_section_value=person,\n )\n self.portal.portal_workflow._jumpToStateFor(payment, 'stopped')\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), \"\")\n self.assertEquals(contract2.getValidationState(), \"validated\")\n\n def test_create_invoice_if_needed_and_no_payment_found(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n contract.edit(destination_section_value=person)\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n before_date = DateTime()\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n after_date = DateTime()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertNotEquals(contract2.getCausality(\"\"), \"\")\n self.assertEquals(contract2.getValidationState(), \"invalidated\")\n\n invoice = contract2.getCausalityValue()\n self.assertEquals(invoice.getPortalType(), 'Sale Invoice Transaction')\n self.assertEquals(len(invoice.contentValues()), 1)\n self.assertEquals(invoice.getSimulationState(), 'confirmed')\n self.assertEquals(invoice.getCausalityState(), 'building')\n self.assertEquals(invoice.getTitle(), 'Account validation')\n self.assertEquals(invoice.getSource(), person.getRelativeUrl())\n self.assertEquals(invoice.getDestination(), person.getRelativeUrl())\n self.assertEquals(invoice.getDestinationSection(), person.getRelativeUrl())\n self.assertEquals(invoice.getDestinationDecision(), person.getRelativeUrl())\n self.assertTrue(invoice.getStartDate() >= before_date)\n self.assertTrue(invoice.getStartDate() <= after_date)\n self.assertEquals(invoice.getStartDate(), invoice.getStopDate())\n\n def test_do_nothing_if_invoice_is_ongoing(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n invoice = self.createInvoiceTransaction()\n self.portal.portal_workflow._jumpToStateFor(invoice, 'confirmed')\n contract.edit(\n destination_section_value=person,\n causality_value=invoice,\n )\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), invoice.getRelativeUrl())\n self.assertEquals(contract2.getValidationState(), \"invalidated\")\n\n def test_forget_current_cancelled_invoice(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n invoice = self.createInvoiceTransaction()\n self.portal.portal_workflow._jumpToStateFor(invoice, 'cancelled')\n contract.edit(\n destination_section_value=person,\n causality_value=invoice,\n )\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), \"\")\n self.assertEquals(contract2.getValidationState(), \"invalidated\")\n\n def test_forget_current_grouped_invoice(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n invoice = self.createInvoiceTransaction()\n line = invoice.newContent(\n portal_type=\"Sale Invoice Transaction Line\",\n source=\"account_module/receivable\", \n grouping_reference=\"foo\",\n )\n line.getSourceValue().getAccountType()\n self.portal.portal_workflow._jumpToStateFor(invoice, 'stopped')\n contract.edit(\n destination_section_value=person,\n causality_value=invoice,\n )\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), \"\")\n self.assertEquals(contract2.getValidationState(), \"invalidated\")\n\n def test_do_nothing_if_invoice_is_not_grouped(self):\n person, instance, subscription = self.createNeededDocuments()\n contract = self.createCloudContract()\n invoice = self.createInvoiceTransaction()\n invoice.newContent(\n portal_type=\"Sale Invoice Transaction Line\",\n source=\"account_module/receivable\", \n )\n self.portal.portal_workflow._jumpToStateFor(invoice, 'stopped')\n contract.edit(\n destination_section_value=person,\n causality_value=invoice,\n )\n self.assertEquals(contract.getValidationState(), \"invalidated\")\n self.tic()\n\n contract2 = instance.SoftwareInstance_requestValidationPayment()\n self.assertEquals(contract2.getRelativeUrl(), contract.getRelativeUrl())\n self.assertEquals(contract2.getCausality(\"\"), invoice.getRelativeUrl())\n self.assertEquals(contract2.getValidationState(), \"invalidated\")\n\nclass TestSlapOSPerson_isAllowedToAllocate(testSlapOSMixin):\n\n def beforeTearDown(self):\n transaction.abort()\n\n def createPerson(self):\n new_id = self.generateNewId()\n return self.portal.person_module.newContent(\n portal_type='Person',\n title=\"Person %s\" % new_id,\n reference=\"TESTPERS-%s\" % new_id,\n )\n\n def createCloudContract(self):\n new_id = self.generateNewId()\n return self.portal.cloud_contract_module.newContent(\n portal_type='Cloud Contract',\n title=\"Contract %s\" % new_id,\n reference=\"TESTCONTRACT-%s\" % new_id,\n )\n\n def test_not_allowed_by_default(self):\n person = self.createPerson()\n result = person.Person_isAllowedToAllocate()\n self.assertEquals(result, False)\n\n def test_allowed_if_has_a_validated_contract(self):\n person = self.createPerson()\n contract = self.createCloudContract()\n contract.edit(\n destination_section_value=person\n )\n self.portal.portal_workflow._jumpToStateFor(contract, 'validated')\n self.tic()\n result = person.Person_isAllowedToAllocate()\n self.assertEquals(result, True)\n\n def test_not_allowed_if_has_an_invalidated_contract(self):\n person = self.createPerson()\n contract = self.createCloudContract()\n contract.edit(\n destination_section_value=person\n )\n self.portal.portal_workflow._jumpToStateFor(contract, 'invalidated')\n self.tic()\n result = person.Person_isAllowedToAllocate()\n self.assertEquals(result, False)\n\n def test_not_allowed_if_no_related_contract(self):\n person = self.createPerson()\n contract = self.createCloudContract()\n self.portal.portal_workflow._jumpToStateFor(contract, 'validated')\n self.tic()\n result = person.Person_isAllowedToAllocate()\n self.assertEquals(result, False)\n","sub_path":"master/bt5/slapos_accounting/TestTemplateItem/portal_components/test.erp5.testSlapOSContractSkins.py","file_name":"test.erp5.testSlapOSContractSkins.py","file_ext":"py","file_size_in_byte":12267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"285830902","text":"\r\nimport urllib.request\r\nimport json\r\nime = input(\"Input the name of a youtuber with over 5k subscribers: \")\r\n\r\nkey = '' # input your own key cause i am not going to leak mine\r\n\r\n\r\ntry: \r\n data = urllib.request.urlopen(\"https://www.googleapis.com/youtube/v3/channels?part=statistics&key=\"+key+\"&forUsername=\"+ime).read()\r\n sub = json.loads(data)[\"items\"][0][\"statistics\"][\"subscriberCount\"]\r\n if int(sub) > 5000:\r\n print(ime+\" has \"+\"{:,d}\".format(int(sub)) + \" subscribers\")\r\n else:\r\n print(\"The specified youtuber does not exceed 5,000 subscribers!\")\r\nexcept:\r\n print(\"Channel was not found (try to input original channel name)\")\r\n\r\n ","sub_path":"sourceCode.py","file_name":"sourceCode.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"405453468","text":"import os.path\n\nfrom data.base_dataset import BaseDataset, get_params\nfrom data.image_folder import make_dataset\nimport torchvision.transforms as transforms\nimport glob\n\nfrom PIL import Image\n\n\nclass TextureDataset(BaseDataset):\n \"\"\"A dataset class for paired image dataset.\n\n It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.\n During test time, you need to prepare a directory '/path/to/data/test'.\n \"\"\"\n\n def __init__(self, opt):\n \"\"\"Initialize this dataset class.\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n BaseDataset.__init__(self, opt)\n\n assert opt.data_class_a is not None, \"--data-class-a is required\"\n assert opt.data_class_b is not None, \"--data-class-b is required\"\n\n self.data_dir_a = opt.data_class_a\n self.data_dir_b = opt.data_class_b\n\n self.data_paths_a = glob.glob(os.path.join(opt.data_class_a, '*'))\n self.data_paths_b = glob.glob(os.path.join(opt.data_class_b, '*'))\n\n # assert(self.opt.load_size >= self.opt.crop_size) # crop_size should be smaller than the size of loaded image\n self.input_nc = self.opt.output_nc if self.opt.direction == 'BtoA' else self.opt.input_nc\n self.output_nc = self.opt.input_nc if self.opt.direction == 'BtoA' else self.opt.output_nc\n\n def __getitem__(self, index):\n \"\"\"Return a data point and its metadata information.\n\n Parameters:\n index - - a random integer for data indexing\n\n Returns a dictionary that contains A, B, A_paths and B_paths\n A (tensor) - - an image in the input domain\n B (tensor) - - its corresponding image in the target domain\n A_paths (str) - - image paths\n B_paths (str) - - image paths\n \"\"\"\n # read a image given a random integer index\n a_path = self.data_paths_a[index]\n b_path = self.data_paths_b[index]\n\n a_image = Image.open(a_path).convert('RGB')\n b_image = Image.open(b_path).convert('RGB')\n\n # apply the same transform to both A and B\n transform_params = get_params(self.opt, a_image.size)\n\n a_transform = get_transform(self.opt, transform_params, grayscale=(self.input_nc == 1))\n b_transform = get_transform(self.opt, transform_params, grayscale=(self.output_nc == 1))\n\n a = a_transform(a_image)\n b = b_transform(b_image)\n\n return {'A': a, 'B': b, 'A_paths': a_path, 'B_paths': b_path}\n\n def __len__(self):\n \"\"\"Return the total number of images in the dataset.\"\"\"\n return min(len(self.data_paths_a), len(self.data_paths_b))\n\n\ndef get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True):\n transform_list = []\n if grayscale:\n transform_list.append(transforms.Grayscale(1))\n\n if not opt.no_flip:\n if params is None:\n transform_list.append(transforms.RandomHorizontalFlip())\n elif params['flip']:\n transform_list.append(transforms.Lambda(lambda img: __flip(img, params['flip'])))\n\n transform_list.append(transforms.Lambda(lambda img: __crop(img)))\n\n if 'resize' in opt.preprocess:\n osize = [opt.load_size, opt.load_size]\n transform_list.append(transforms.Resize(osize, method))\n\n if convert:\n transform_list += [transforms.ToTensor()]\n if grayscale:\n transform_list += [transforms.Normalize((0.5,), (0.5,))]\n else:\n transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n\n return transforms.Compose(transform_list)\n\n\ndef __flip(img, flip):\n if flip:\n return img.transpose(Image.FLIP_LEFT_RIGHT)\n return img\n\n\ndef __crop(img, texture_size=512):\n s = texture_size * 400 / 512\n return img.crop((texture_size/2 - s/2, texture_size - s, texture_size/2 + s/2, texture_size))\n","sub_path":"data/texture_dataset.py","file_name":"texture_dataset.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"335078740","text":"\r\nimport os, sys, os.path\r\nimport glob\r\nimport time\r\nimport shutil\r\n\r\ndef debug(str):\r\n\tglobal debugon\r\n\tif debugon==1: print (\"DEBUG: %s\" % str)\r\n\r\ndebugon=1\t\t\t\t\t\t \t\t\t\t\t\t\t\t\r\nheadersize=1\r\nsrcfolder = sys.argv[0][:-15]\r\ntgtfolder = sys.argv[0][:-15] + \"\\Mergedfiles\"\t\r\ndestfolder = sys.argv[0][:-15] + \"\\Processedfiles\"\r\n\r\ndef process():\r\n\tsuffix=\"merged%s\" % time.strftime(\"-%m-%d-%y~RJ\")\t\r\n\toutfilename=\"%s\\\\%s\" % (tgtfolder, suffix)\r\n\tcount = 0\r\n\tfileslist = next(os.walk(srcfolder))[2];\r\n\tprint (fileslist)\r\n\tif(len(fileslist)) > 0:\r\n\t\tmergedfile = open(outfilename, \"w\")\r\n\t\tfor files in fileslist:\r\n\t\t\tfilename = files;\r\n\t\t\t\r\n\t\t\tfiles = \"\\\\\".join([srcfolder,files])\t\t\r\n\t\t\tif (count == 0 ):\r\n\t\t\t\twith open(files) as f1:\r\n\t\t\t\t\tfor lines in f1.readlines():\r\n\t\t\t\t\t\tmergedfile.write(lines)\r\n\t\t\telse:\r\n\t\t\t\twith open(files) as f2:\r\n\t\t\t\t\tfor line in f2.readlines()[headersize:]:\r\n\t\t\t\t\t\tmergedfile.write(line)\r\n\t\t\tcount = count+1\r\n\t\t\tshutil.move( files, \"%s\\\\%s\" %(destfolder, filename))\r\nprocess()\r\n\r\ndebug (\"SUCCESS\")\t\t\r\n","sub_path":"Scriptss/scripts/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"603890462","text":"from flask import Flask, render_template, request, redirect, url_for, flash, session, escape, jsonify\nimport os, smtplib, pyrebase\nfrom firebase import firebase \n\napp = Flask(__name__)\n\n# settings\napp.secret_key = 'mysecretkey'\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\ntarget = os.path.join(APP_ROOT, 'static/')\ntotal = 0\n\n# firebase\ndb = firebase.FirebaseApplication(\"https://apapachatestore.firebaseio.com\")\n\n# storage\nstorageConfig = {\n \"apiKey\": \"AIzaSyBAnc0Oz9Y5WEyjqyH385ue6L_UpkvLtew\",\n \"authDomain\": \"apapachatestore.firebaseapp.com\",\n \"databaseURL\": \"https://apapachatestore.firebaseio.com\",\n \"projectId\": \"apapachatestore\",\n \"storageBucket\": \"apapachatestore.appspot.com\",\n \"messagingSenderId\": \"529842451934\",\n \"appId\": \"1:529842451934:web:9a29de330667b9727ad94f\"\n}\nfirebase = pyrebase.initialize_app(storageConfig)\nstorage = firebase.storage()\npathCloud = \"Productos/\"\n\n# descarga de archivos\ndata = db.get(\"Productos\", \"\")\nif(data):\n for key in data:\n pathCloud = \"Productos/\"+data[key][\"Imagen\"]\n pathLocal = \"static/\"+data[key][\"Imagen\"]\n storage.child(pathCloud).download(pathLocal)\n\n#email smtp\nemaillist = ['rayma9829@gmail.com',]\nserver = smtplib.SMTP('smtp.gmail.com', 587)\nserver.starttls()\n\n#storeManager\n@app.route(\"/storeManager\", methods =['POST','GET']) \ndef storeManager():\n if \"username\" in session:\n data = db.get(\"Productos\", \"\")\n name = escape(session[\"username\"])\n if(data):\n return render_template(\"storeManager.html\", it = data, opc = True, name = name )\n else:\n return render_template(\"storeManager.html\", opc = True, name = name )\n else:\n if request.method == 'POST':\n user = request.form['usuario']\n password = request.form['contrasena']\n usuarios = db.get(\"Usuarios\", \"\")\n auten = False\n for key in usuarios:\n if usuarios[key][\"Usuario\"]==user and usuarios[key][\"Contraseña\"]==password:\n session[\"username\"] = user\n auten = True\n break\n \n if auten == True: \n data = db.get(\"Productos\", \"\")\n name = escape(session[\"username\"])\n if(data):\n for key in data:\n print(data[key][\"Imagen\"])\n pathCloud = \"Productos/\"+data[key][\"Imagen\"]\n pathLocal = \"static/\"+data[key][\"Imagen\"]\n storage.child(pathCloud).download(pathLocal)\n flash('Bienvenido')\n return render_template(\"storeManager.html\", it = data, opc = True, name = name)\n else:\n return render_template(\"storeManager.html\", opc = True, name = name)\n else:\n flash('El usuario o la contraseña son incorrectos')\n return render_template(\"autenticar.html\")\n else:\n return render_template(\"autenticar.html\")\n\n@app.route('/storeManager/logout')\ndef storeLogout():\n session.pop(\"username\")\n flash('Has cerrado tu sesión')\n return redirect(url_for('storeManager'))\n\n@app.route(\"/add\", methods = ['POST'])\ndef add():\n if not os.path.isdir(target):\n os.mkdir(target)\n if request.method == 'POST':\n producto = request.form['producto']\n imagen = request.files['imagen']\n descripcion = request.form['descripcion']\n precio = request.form['precio']\n inventario = request.form['inventario']\n etiquetas = request.form['etiquetas']\n filename = imagen.filename\n destination = \"/\".join([target, filename])\n if producto == \"\" or precio == \"\" or descripcion==\"\" or (imagen==None) or inventario == None or etiquetas == \"\":\n flash('Llena todos los campos correctamente')\n return redirect(url_for('storeManager'))\n else:\n filename = imagen.filename\n destination = \"/\".join([target, filename])\n precioFormat = int(precio)\n imagen.save(destination)\n pathCloud = \"Productos/\"+filename\n pathLocal = destination\n storage.child(pathCloud).put(pathLocal)\n data = {\n \"Producto\": producto,\n \"Imagen\": filename,\n \"Descripcion\": descripcion,\n \"Precio\": precio,\n \"Inventario\": inventario,\n \"Etiquetas\": etiquetas\n }\n db.post(\"Productos\", data)\n server.login('apapachatestore@gmail.com','apapachatecontrasena')\n message = 'Se ha agregado un producto satisfactoriamente\\nCorreo enviado desde apapachatestore.herokuapp.com'\n subject = 'Producto agregado'\n message = 'Subject: {}\\n\\n{}'.format(subject, message)\n for email in emaillist:\n server.sendmail('apapachatestore@gmail.com', email, message)\n flash('Producto agregado satisfactoriamente')\n return redirect(url_for('storeManager'))\n\n@app.route(\"/delete/\")\ndef delete(id):\n img = db.get(\"Productos\", id)[\"Imagen\"]\n print(img)\n db.delete(\"Productos\", id)\n server.login('apapachatestore@gmail.com','apapachatecontrasena')\n message = 'El producto ha sido eliminado satisfactoriamente\\nCorreo enviado desde apapachatestore.herokuapp.com'\n subject = 'Producto eliminado'\n message = 'Subject: {}\\n\\n{}'.format(subject, message)\n for email in emaillist:\n server.sendmail('apapachatestore@gmail.com', email, message)\n flash('Producto eliminado satisfactoriamente')\n return redirect(url_for('storeManager'))\n\n@app.route(\"/edit/\")\ndef edit(id):\n data = db.get(\"Productos\", id)\n print(data)\n return render_template(\"edit.html\", producto = data, id = id)\n\n@app.route(\"/update/\", methods = ['POST'])\ndef update(id):\n if request.method == 'POST':\n producto = request.form['producto']\n imagen = request.files['imagen']\n descripcion = request.form['descripcion']\n precio = request.form['precio']\n inventario = request.form['inventario']\n etiquetas = request.form['etiquetas']\n filename = imagen.filename\n destination = \"/\".join([target, filename])\n pa = \"Productos/\"+id\n pathCloud = \"Productos\"\n pathLocal = destination\n if imagen:\n img = db.get(\"Productos\", id)[\"Imagen\"]\n os.remove('static/'+img)\n db.put(pa, \"Imagen\", filename)\n imagen.save(destination)\n storage.child(pathCloud).put(pathLocal)\n if producto:\n db.put(pa, \"Producto\", producto)\n if descripcion:\n db.put(pa, \"Descripcion\", descripcion)\n if precio:\n precioFormat = int(precio)\n db.put(pa, \"Precio\", precioFormat)\n if inventario:\n db.put(pa, \"Inventario\", inventario)\n if etiquetas:\n db.put(pa, \"Etiquetas\", etiquetas)\n server.login('apapachatestore@gmail.com','apapachatecontrasena')\n message = 'El producto ha sido actualizado satisfactoriamente\\nCorreo enviado desde apapachatestore.herokuapp.com'\n subject = 'Producto actualizado'\n message = 'Subject: {}\\n\\n{}'.format(subject, message)\n for email in emaillist:\n server.sendmail('apapachatestore@gmail.com', email, message)\n flash('Producto actualizado satisfactoriamente')\n return redirect(url_for('storeManager'))\n\n@app.route(\"/signup\", methods=['GET','POST'])\ndef signup():\n if request.method == 'POST': \n usuario = request.form['usuario']\n contrasena = request.form['contrasena']\n confirmcontrasena = request.form['confirmcontrasena']\n correo = request.form['email']\n users = db.get(\"Usuarios\", \"\")\n registrar = False\n if contrasena == confirmcontrasena:\n for user in users:\n if users[user][\"Usuario\"] == usuario:\n flash('El usuario ya existe, intente con otro')\n return render_template('signup.html')\n else:\n data = {\n \"Usuario\": usuario,\n \"Contraseña\": contrasena,\n \"email\": correo\n }\n db.post(\"Usuarios\", data)\n server.login('apapachatestore@gmail.com','apapachatecontrasena')\n message = 'Se ha registrado un nuevo usuario\\nCorreo enviado desde apapachatestore.herokuapp.com'\n subject = 'Alta de usuario'\n message = 'Subject: {}\\n\\n{}'.format(subject, message)\n for email in emaillist:\n server.sendmail('apapachatestore@gmail.com', email, message)\n flash('Usuario registrado exitosamente')\n return redirect(url_for('storeManager'))\n else:\n flash('Las contraseñas deben coincidir')\n return render_template('signup.html')\n else:\n return render_template('signup.html')\n\n@app.route(\"/adduser\", methods=['POST'])\ndef adduser():\n flash('Usuario registrado satisfactoriamente')\n return redirect(url_for('storeManager'))\n\n\n#apapachateStore\n@app.route(\"/\")\ndef index():\n productos = db.get(\"Productos\", \"\")\n return render_template('index.html', productos = productos)\n\n@app.route(\"/productos\")\ndef product():\n data = db.get(\"Productos\", \"\")\n return render_template(\"productos.html\", productos = data)\n\n@app.route(\"/vaciarCarrito\")\ndef vaciarCarrito():\n session.pop(\"total\")\n flash(\"Has vaciado el carrito\")\n return render_template('carrito.html')\n\n@app.route(\"/addproduct/\")\ndef agregar(precio):\n if 'total' in session:\n session['total'] = int(escape(session['total']))+precio\n else:\n session['total'] = precio\n flash('El total es {}'.format(escape(session['total'])))\n return redirect(url_for('product'))\n\n\n@app.route(\"/successful\")\ndef successful():\n return render_template(\"successful.html\")\n\n@app.route(\"/carrito\")\ndef carrito():\n if 'total' in session:\n return render_template('carrito.html', total = escape(session['total']))\n else:\n return render_template('carrito.html')\n\n@app.route(\"/producto/\")\ndef producto(id):\n producto = db.get(\"Productos\", id)\n return render_template(\"producto.html\", productos = producto, id = id)\n\n\nif __name__ == '__main__': \n app.run(debug=True, port=5500)","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":10609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"335428544","text":"from gzip import GzipFile\nimport io\nimport yaml\nimport threading\nfrom contextlib import closing\nimport json\nfrom typing import Optional\nimport pandas as pd\nfrom .bundles.managed_content.content import ManagedContentClient\nfrom .bundles.managed_content.cortex_helpers import load_token, load_api_endpoint\nfrom aistac.handlers.abstract_handlers import AbstractSourceHandler, ConnectorContract, AbstractPersistHandler\n\ntry:\n import cPickel as pickle\nexcept ImportError:\n import pickle\n\n\n__author__ = 'Omar Eid'\n\n\nclass ManagedContentSourceHandler(AbstractSourceHandler):\n \"\"\" A Managed Content Source handler\"\"\"\n\n def __init__(self, connector_contract: ConnectorContract):\n \"\"\" Initialise the handler passing the source_contract dictionary \"\"\"\n super().__init__(connector_contract)\n self.token = self._load_token()\n self.api_endpoint = self._load_api_endpoint()\n self.cortex_mc_client = ManagedContentClient(self.api_endpoint, \"2\", self.token)\n self._file_state = 0\n self._changed_flag = True\n\n def mc_key(self, connector_contract: Optional[ConnectorContract]=None):\n _cc = connector_contract if connector_contract is not None else self.connector_contract\n key = _cc.path\n return key[1:] if key.startswith(\"/\") else key\n\n def _load_token(self):\n return load_token(token=self.connector_contract.kwargs.get(\"token\"))\n\n def _load_api_endpoint(self):\n return load_api_endpoint(endpoint=self.connector_contract.kwargs.get(\"api_endpoint\"))\n\n def supported_types(self) -> list:\n \"\"\" The source types supported with this module\"\"\"\n return ['pickle', \"csv\"] # , \"json\" , \"tsv\"\n\n def _download_key_from_mc(self, key):\n return self.cortex_mc_client.download(key, retries=2)\n\n def _load_dict_from_json_in_mc(self, mc_key: str, load_as_df=None, **json_options) -> pd.DataFrame:\n if not self.exists():\n return pd.DataFrame()\n content = self._download_key_from_mc(mc_key).read()\n data = json.load(io.StringIO(content.decode('utf-8')), **json_options)\n if load_as_df:\n data = pd.DataFrame(data)\n return data\n\n def _load_dict_from_yaml_in_mc(self, mc_key: str) -> pd.DataFrame:\n if not self.exists():\n return pd.DataFrame()\n content = self._download_key_from_mc(mc_key).read()\n return yaml.safe_load(io.StringIO(content.decode('utf-8')))\n\n def _load_df_from_csv_in_mc(self, mc_key: str, **pandas_options) -> pd.DataFrame:\n if not self.exists():\n return pd.DataFrame()\n content = self._download_key_from_mc(mc_key).read()\n return pd.read_csv(io.StringIO(content.decode('utf-8')), **pandas_options)\n\n def _load_df_from_pickle_in_mc(self, mc_key: str, **kwargs) -> pd.DataFrame:\n \"\"\" loads a pickle file \"\"\"\n if not self.exists():\n return pd.DataFrame()\n fix_imports = kwargs.pop('fix_imports', True)\n encoding = kwargs.pop('encoding', 'ASCII')\n errors = kwargs.pop('errors', 'strict')\n with threading.Lock():\n with closing(io.BytesIO(self._download_key_from_mc(mc_key).read())) as f:\n return pickle.load(f, fix_imports=fix_imports, encoding=encoding, errors=errors)\n\n def _load_gz_from_mc(self, mc_key: str) -> [GzipFile, None]:\n if not self.exists():\n return None\n return GzipFile(None, 'rb', fileobj=self._download_key_from_mc(mc_key))\n\n def load_canonical(self) -> [pd.DataFrame, dict, GzipFile]:\n \"\"\" returns the canonical dataset based on the connector contract. This method utilises the pandas\n 'pd.read_' methods and directly passes the kwargs to these methods.\n Extra Parameters in the ConnectorContract kwargs:\n - file_type: (optional) the type of the source file. if not set, inferred from the file extension\n \"\"\"\n if not isinstance(self.connector_contract, ConnectorContract):\n raise ValueError(\"The Managed Content Connector Contract has not been set\")\n _cc = self.connector_contract\n load_params = _cc.kwargs\n load_params.update(_cc.query) # Update kwargs with those in the uri query\n load_params.pop('token', None)\n load_params.pop('api_endpoint', None)\n _, _, _ext = _cc.address.rpartition('.')\n file_type = load_params.get('file_type', _ext if len(_ext) > 0 else 'csv')\n with threading.Lock():\n if file_type.lower() in ['csv']:\n rtn_data = self._load_df_from_csv_in_mc(mc_key=self.mc_key(), **load_params)\n elif file_type.lower() in ['pkl ', 'pickle']:\n rtn_data = self._load_df_from_pickle_in_mc(mc_key=self.mc_key(), **load_params)\n # elif file_type.lower() in ['tsv']:\n # rtn_data = self._load_df_from_csv_in_mc(self.mc_key(, delimiter='\\t', **load_params)\n elif file_type.lower() in ['json']:\n rtn_data = self._load_dict_from_json_in_mc(self.mc_key(), **load_params)\n elif file_type.lower() in ['yaml']:\n rtn_data = self._load_dict_from_yaml_in_mc(self.mc_key())\n elif file_type.lower() in [\"gz\"]:\n rtn_data = self._load_gz_from_mc(self.mc_key())\n else:\n raise LookupError('The source format {} is not currently supported'.format(file_type))\n return rtn_data\n\n def exists(self) -> bool:\n \"\"\" returns True if the file in mc exists \"\"\"\n _cc = self.connector_contract\n mc_key = self.mc_key()\n return self.cortex_mc_client.exists(mc_key)\n\n def get_modified(self) -> [int, float, str]:\n \"\"\" returns the amount of documents in the collection\n ... if the counts change ... then the collection was probably modified ...\n ... this assumes that records are never edited/updated ... nor deleted ...\n \"\"\"\n # Cortex Does Not Currently send back any meta data regarding the file version when checking if it exists ...\n # https://bitbucket.org/cognitivescale/cortex-connections-service/src/d1d2fdae3fc9db398d7873cac58c2dc7db6fb5ff/lib/controllers/content.js#lines-287\n mc_key = self.mc_key()\n uri = f\"content/details/{mc_key}\"\n resp = self.cortex_mc_client.serviceconnector.request('GET', uri)\n response = resp.json()\n return (response or {}).get(\"LastModified\", 0)\n\n\nclass ManagedContentPersistHandler(ManagedContentSourceHandler, AbstractPersistHandler):\n # A Managed Content persist handler\n\n def _persist_df_as_pickle(self, canonical: pd.DataFrame, mc_key: str, **kwargs) -> None:\n \"\"\"dumps a pickle file\"\"\"\n protocol = kwargs.pop('protocol', pickle.HIGHEST_PROTOCOL)\n fix_imports = kwargs.pop('fix_imports', True)\n with threading.Lock():\n # https://stackoverflow.com/questions/13223855/what-is-the-http-content-type-to-use-for-a-blob-of-bytes\n pickle_byte_stream = pickle.dumps(canonical, protocol=protocol, fix_imports=fix_imports)\n self.cortex_mc_client.upload_streaming(mc_key, pickle_byte_stream, \"application/python-pickle\")\n\n def _persist_df_as_csv(self, canonical: pd.DataFrame, mc_key: str, **kwargs):\n return self.cortex_mc_client.upload_streaming(mc_key, canonical.to_csv(**kwargs), \"text/csv\", retries=2)\n\n def _persist_dict_as_json(self, canonical: dict, mc_key: str):\n return self.cortex_mc_client.upload_streaming(mc_key, json.dumps(canonical), \"application/json\", retries=2)\n\n def _persist_dict_as_yaml(self, canonical: dict, mc_key: str):\n return self.cortex_mc_client.upload_streaming(mc_key, yaml.dump(canonical), \"application/yaml\", retries=2)\n\n def persist_canonical(self, canonical: pd.DataFrame, **kwargs) -> bool:\n \"\"\" persists the canonical dataset\n Extra Parameters in the ConnectorContract kwargs:\n - file_type: (optional) the type of the source file. if not set, inferred from the file extension\n \"\"\"\n if not isinstance(self.connector_contract, ConnectorContract):\n return False\n _uri = self.connector_contract.uri\n return self.backup_canonical(uri=_uri, canonical=canonical)\n\n def backup_canonical(self, canonical: [dict, pd.DataFrame], uri: str, ignore_kwargs: bool = False) -> bool:\n \"\"\" creates a backup of the canonical to an alternative URI \"\"\"\n if not isinstance(self.connector_contract, ConnectorContract):\n return False\n _cc = self.connector_contract\n _uri_cc = ConnectorContract(uri, module_name=_cc.module_name, handler=_cc.handler)\n load_params = _cc.kwargs\n load_params.update(_cc.query) # Update kwargs with those in the uri query\n load_params.pop('token', None)\n load_params.pop('api_endpoint', None)\n mc_key = self.mc_key(_uri_cc)\n _, _, _ext = _uri_cc.address.rpartition('.')\n file_type = load_params.get('file_type', _ext if len(_ext) > 0 else 'csv')\n with threading.Lock():\n if file_type.lower() in ['csv']:\n self._persist_df_as_csv(canonical, mc_key=mc_key, **load_params)\n elif file_type.lower() in ['pkl', 'pickle']:\n self._persist_df_as_pickle(canonical, mc_key=mc_key, **load_params)\n # elif file_type.lower() in ['tsv']:\n # rtn_data = self._load_df_from_csv_in_mc(mc_key, delimiter='\\t', **load_params)\n elif file_type.lower() in ['json']:\n self._persist_dict_as_json(canonical=canonical, mc_key=mc_key)\n elif file_type.lower() in ['yaml']:\n self._persist_dict_as_yaml(canonical=canonical, mc_key=mc_key)\n else:\n raise LookupError('The source format {} is not currently supported'.format(file_type))\n\n return True\n\n def remove_canonical(self) -> bool:\n if not isinstance(self.connector_contract, ConnectorContract):\n return False\n _cc = self.connector_contract\n raise NotImplementedError(\"remove_canonical for ManagedContentPersistHandler not yet implemented.\")\n","sub_path":"ds_connectors/handlers/managed_content_handlers.py","file_name":"managed_content_handlers.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"96193145","text":"#!/usr/bin/env python3\nfrom PIL import Image\n\ndef fill_image(image):\n width,height = image.size\n new_length = 0\n if width > height: \n new_length = width \n else:\n new_length = height\n imageNew = Image.new(image.mode,(new_length,new_length),color='white')\n# if width > height:\n #imageNew.paste(image,(0,int((new_length-height)/2)))\n# else:\n #imageNew.paste(image,(int((new_length-width)/2,0))\n imageNew.paste(image,(0,int((new_length-height)/2)))\n return imageNew\n\ndef cut_image(image):\n width, height = image.size\n item_width = int(width/3)\n box_list = []\n image_list = []\n for i in range(0,3):\n for j in range(0,3):\n box = (j*item_width, i*item_width,(j+1)*item_width, (i+1)*item_width)\n box_list.append(box) \n for box in box_list:\n image_list.append(image.crop(box))\n return image_list\n\ndef save_images(image_list):\n index=1\n for image in image_list:\n image.save('./result/python'+str(index)+'.png','PNG')\n index += 1\n\nif __name__=='__main__':\n file_path='python.JPG'\n image=Image.open(file_path)\n new_image=fill_image(image)\n image_list=cut_image(new_image)\n save_images(image_list)\n","sub_path":"Python_Def_9Grids.py","file_name":"Python_Def_9Grids.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"487387154","text":"from django.urls import path\nfrom .views import login, internView, logout\n\napp_name = 'user_auth'\nurlpatterns = [\n # wenn eine Anfrage an / reinkommt, dann übergebe das der Funkt. Index aus der views.py\n path('', internView, name='internView'),\n path('login/', login, name='login'),\n path('logout/', logout, name='logout'),\n]","sub_path":"apps/user_auth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"85911373","text":"from PyQt5.QtCore import (Qt, pyqtSlot)\nfrom PyQt5.QtWidgets import (QWidget, QPushButton, QVBoxLayout, QHBoxLayout,\n QTreeWidget, QLineEdit, QLabel)\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n\n\nclass TabSingle(QWidget):\n def __init__(self):\n QWidget.__init__(self, flags=Qt.Widget)\n\n self.lbl = QLabel('일시 입력')\n self.ledt_datetime = QLineEdit()\n self.btn_drawPlot = QPushButton(\"차트그리기\")\n self.btn_drawPlot.clicked.connect(self.drawSp)\n\n self.tree_entitymap = QTreeWidget()\n\n self.fig = plt.Figure()\n self.canvas = FigureCanvas(self.fig)\n\n # Left Layout\n self.leftLayout = QVBoxLayout()\n self.leftLayout.addWidget(self.canvas)\n\n # Right Layout\n self.rightLayout = QVBoxLayout()\n self.rightLayout.addWidget(self.lbl)\n self.rightLayout.addWidget(self.ledt_datetime)\n self.rightLayout.addWidget(self.btn_drawPlot)\n self.rightLayout.addStretch(1)\n\n # Main Layout\n self.mainLayout = QHBoxLayout()\n self.mainLayout.addLayout(self.leftLayout)\n self.mainLayout.addLayout(self.rightLayout)\n self.mainLayout.setStretchFactor(self.leftLayout, 1)\n self.mainLayout.setStretchFactor(self.rightLayout, 0)\n\n self.setLayout(self.mainLayout)\n\n # get PySparkManager\n # self.pysparkmgr = PySparkManager()\n\n def getSpectra(self, datehm):\n import happybase\n connection = happybase.Connection('210.102.142.14')\n print(connection.tables())\n table = connection.table('natural_light')\n return table.row(datehm, ['sp_ird'])\n\n @pyqtSlot(name='drawSpectra')\n def drawSp(self):\n # date = '2017-04-13'\n # time = '1240'\n strdt = self.ledt_datetime.text()\n\n plt.close()\n self.fig.clear()\n\n dict_sp = self.getSpectra(strdt)\n wl = list(dict_sp.keys())\n ird = list(dict_sp.values())\n\n for i in range(len(wl)):\n wl[i] = float(wl[i].decode('utf-8').split(':')[1])\n ird[i] = float(ird[i].decode('utf-8'))\n\n print(wl)\n print(ird)\n print('max ird = %f' % max(ird))\n\n ax = self.fig.add_subplot(111)\n\n ax.scatter(wl, ird, color='blue', s=3, label='%s' % strdt)\n ax.set_ylim(0, max(ird))\n ax.set_xlabel('wavelength [nm]')\n ax.set_ylabel('spectral irradiance [W/m2nm]')\n\n ax.legend(loc='upper right', fontsize=10)\n # plt.show()\n\n self.canvas.draw()\n","sub_path":"tabs/single/tab_single.py","file_name":"tab_single.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"90373188","text":"import requests\r\nimport json\r\nimport csv\r\nfrom pymongo import MongoClient \r\nfrom constant_women_owned_RAPI_API import gendr\r\nimport gender_guesser.detector as gender\r\ndetector_gender = gender.Detector()\r\nclient = MongoClient()\r\ndb = client['ticker']\r\n \r\n\r\nheaders = {\r\n 'x-rapidapi-host': \"apidojo-yahoo-finance-v1.p.rapidapi.com\",\r\n 'x-rapidapi-key': \"6b1091072bmsh9684ba0675c7b7ep1f8852jsn6c5d63df5caf\"\r\n }\r\nurl = \"https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-profile\"\r\n\r\n \r\n\r\n\r\n\r\n# querystring = {\"symbol\":\"ASML\"}\r\n# response = requests.request(\"GET\", url, headers=headers, params=querystring)\r\n# response = json.loads(response.text)\r\n\r\n \r\n\r\n# response[\"defaultKeyStatistics\"][\"beta\"][\"fmt\"]\r\n\r\n\r\ndef papoulate_data():\r\n with open('/home/fintech/Ahsan/NEW_stocks_BETA_industries_values_with_dereived_industries.csv', 'r') as csv_file:\r\n csv_reader = csv.DictReader(csv_file)\r\n with open('/home/fintech/Ahsan/new_1_stocks_industries_values_with_dereived_industries.csv', 'w') as new_file:\r\n fieldnames = ['Ticker','Industry','Derived Industry','Environment score','Social score','Governance score','Percentile','Controversy','Adult entertainment - negative','Firearms','Animal welfare','Nuclear power','Alcohol','Tobacco','Gambling','Palm oil','Controversial weapons','Fur leather','Gmo','Catholic','Coal','Pesticides','Military Contract','Vegan','Climate change','Alignment with UN SDGs','Labor rights','Diversity','Civil liberties','Water','Wind power - positive','Clean energy','Carbon emissions','Child labor','Stem cell research','Interest bearing instruments','Minority owned','Millennial owned','Gender equity','LGBTQ','Immigration','Family values','Maternity leave (rights)','Abortion','Contraceptives','Beta', \"total_men\", \"total_women\", \"unpredicted_names\", \"all_names\", \"women_percentage\"]\r\n\r\n\r\n csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)\r\n\r\n\r\n csv_writer.writeheader()\r\n # for rows in csv_reader:\r\n # print(\"------------------------------------------\")\r\n # print(rows)\r\n for rows in csv_reader:\r\n try:\r\n # print(\"------------------------------------------\")\r\n # time.sleep(5)\r\n ticker = rows[\"Ticker\"]\r\n querystring = {\"symbol\":str(ticker)}\r\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\r\n response = json.loads(response.text)\r\n man = 0\r\n women = 0\r\n unpredicted_names = []\r\n all_names = []\r\n for record in response[\"assetProfile\"][\"companyOfficers\"]:\r\n name = record['name']\r\n # print(name)\r\n all_names.append(record['name'])\r\n if \"Mr.\" in name:\r\n man += 1\r\n elif \"Ms.\" in name:\r\n women += 1\r\n else:\r\n\r\n if \"Dr.\" in name:\r\n # print(\"in doctor\")\r\n # print(name)\r\n name = record['name'].split(\"Dr. \")[1]\r\n # print(name)\r\n name = name.split(\" \")[0]\r\n # print(str(name.upper()))\r\n # print(name)\r\n try:\r\n gen = str(gendr[str(name.upper())])\r\n # print(gen)\r\n except:\r\n gen = \"unknown\"\r\n if gen == 'male':\r\n man += 1\r\n elif gen == 'female':\r\n women += 1\r\n else:\r\n if detector_gender.get_gender(str(name)) == 'male':\r\n man += 1\r\n elif detector_gender.get_gender(str(name)) == 'female':\r\n women += 1\r\n else:\r\n unpredicted_names.append(record['name'])\r\n\r\n elif \"Dr.\" not in name and \"Mr.\" not in name and \"Ms.\" not in name:\r\n name = record['name'].split(\" \")[0]\r\n # print(name)\r\n try:\r\n gen = str(gendr[str(name.upper())])\r\n # print(gen)\r\n except:\r\n gen = \"unknown\"\r\n if gen == 'male':\r\n man += 1\r\n elif gen == 'female':\r\n women += 1\r\n else:\r\n if detector_gender.get_gender(str(name)) == 'male':\r\n man += 1\r\n elif detector_gender.get_gender(str(name)) == 'female':\r\n women += 1\r\n else:\r\n unpredicted_names.append(record['name'])\r\n women_owned_percentage = 0.0\r\n if not unpredicted_names:\r\n women_owned_percentage = (women) / (man + women)\r\n women_owned_percentage = round(float(women_owned_percentage * 100) ,2)\r\n\r\n if str(rows['Controversy']) == \"FALSE\":\r\n rows['Controversy'] = 0\r\n\r\n if str(rows['Beta']) == \"NaN\":\r\n rows['Beta'] = 0\r\n\r\n rows[\"total_men\"] = man\r\n rows[\"total_women\"] = women\r\n rows[\"unpredicted_names\"] = unpredicted_names\r\n rows[\"all_names\"] = all_names\r\n rows[\"women_percentage\"] = women_owned_percentage\r\n csv_writer.writerow(rows)\r\n\r\n x={}\r\n # print(ticker,man,women,unpredicted_names,all_names)\r\n x[\"ticker\"] = ticker\r\n x[\"total_men\"] = man\r\n x[\"total_women\"] = women\r\n x[\"unpredicted_names\"] = unpredicted_names\r\n x[\"all_names\"] = all_names\r\n x[\"women_percentage\"] = women_owned_percentage\r\n db.ticker_executives_officers.insert_one(x)\r\n except Exception as e:\r\n if str(rows['Beta']) == \"NaN\":\r\n rows['Beta'] = 0\r\n\r\n rows[\"total_men\"] = 0\r\n rows[\"total_women\"] = 0\r\n rows[\"unpredicted_names\"] = []\r\n rows[\"all_names\"] = []\r\n rows[\"women_percentage\"] = 0.0\r\n csv_writer.writerow(rows)\r\n # rows[\"Beta\"] = str(e)\r\n # print(\"Exception in test_beta1 :\",e)\r\n # break\r\n # csv_writer.writerow(rows)\r\n pass\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n papoulate_data()\r\n\r\n\r\n","sub_path":"women_owned_rapid_API.py","file_name":"women_owned_rapid_API.py","file_ext":"py","file_size_in_byte":7540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"390210569","text":"import bpy\nimport bmesh\nfrom .capify import (capify, is_cap)\n\nclass ObjectCapifier(bpy.types.Operator):\n bl_idname = \"object.capify\"\n bl_label = \"Capify\"\n bl_context = \"objectmode\"\n bl_description = \"Add proper topology to cylinder object caps\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n @classmethod\n def poll(cls, context):\n ob = context.active_object\n return (ob and ob.type == 'MESH' and context.mode == 'OBJECT')\n\n def execute(self, context):\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bm = bmesh.from_edit_mesh(context.active_object.data)\n sel = [f for f in bm.faces if is_cap(f)]\n for f in sel:\n capify(f, bm)\n bpy.ops.object.mode_set(mode=\"OBJECT\")\n return {'FINISHED'}","sub_path":"ui/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"108928026","text":"\"\"\"\nSettings overrides for development environment.\n\"\"\"\n\nfrom settings import *\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = [\n '.ucdavis.edu',\n '54.243.53.70'\n]\n\n\nMIDDLEWARE_CLASSES += (\n# 'utils.middleware.multiport.MultiPortMiddleware', # this is just an attempt to be able to connect to multiple django servers by different people ~/svn/private/python/utils/\n)\n\nCORS_ORIGIN_WHITELIST = (\n 'meamdev.ucdavis.edu'\n )\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'meamcore',\n 'USER': 'ec2-user',\n 'PASSWORD': 'tr1ad',\n 'HOST': '127.0.0.1',\n 'PORT': '',\n }\n}\n\n","sub_path":"meamstream/settings-dev.py","file_name":"settings-dev.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"308333957","text":"from src2.syslog_ng.options_and_drivers.option_data_provider import OptionDataProvider\n\nclass SlngConfigGlobalOptionGenerator(object):\n def __init__(self, option_properties):\n self.option_properties = option_properties\n self.global_option_data_provider = OptionDataProvider(option_properties)\n self.global_option_collector = []\n\n def generate_global_options_for_actual_option(self):\n if self.global_option_data_provider.is_actual_option_in_target_statement_option(target_statement=\"global\"):\n self.add_actual_option_to_global_option_collector()\n\n if self.global_option_data_provider.get_additional_further_options(further_option_type=\"global\"):\n self.add_further_global_options_to_global_option_collector()\n\n return self.global_option_collector\n\n def add_actual_option_to_global_option_collector(self):\n if self.global_option_data_provider.is_option_value_default():\n ### Note: in this case we don't want to generate global option\n pass\n elif self.global_option_data_provider.is_option_value_empty():\n self.global_option_collector.append({\"option_name\": self.option_properties['option_name'], \"option_value\": \"\"})\n else:\n self.global_option_collector.append(self.global_option_data_provider.format_option_properties_for_config())\n\n def add_further_global_options_to_global_option_collector(self):\n further_global_options = self.global_option_data_provider.get_additional_further_options(further_option_type=\"global\")\n for further_global_option in further_global_options:\n self.global_option_collector.append(further_global_option)\n","sub_path":"src2/syslog_ng/config_generator/config_global_options_generator.py","file_name":"config_global_options_generator.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10631484","text":"import re\nfrom urllib.parse import urlparse\n\nimport numpy as np\n\nfrom util_core.util.url_analysis import is_social_url\nfrom util_core.util.urls_util import normalise_href_url, url_host, url_type\nfrom util_core.util.html_util import (\n get_start_tag, get_tag_names, get_inner, get_tag_name,\n get_text, get_normalised_attrs\n)\n# from selenium_data_extraction.create_data.create_element_descriptions_util import get_spatial_visibility\n# from selenium_data_extraction.create_data.create_element_descriptions_util import (\n# find_common_features, calculate_computed_style_weights, add_hashes, add_computed_style_weights,\n# get_spatial_visibility, get_tag_desc, get_ancestor_tag_info, get_ancestor_tag_info_bs4\n# )\n\nfrom webextractor.clustering.comparisons.computed_styles import EXPECTED_COMPUTED_STYLE_KEYS\nfrom webextractor.element_descriptions.util import get_spatial_visibility\nfrom webextractor.element_descriptions.feature_set import create_feature_set\nfrom util_core.util.url_analysis import is_social_url, is_google_calendar_link\nfrom util_core.util.html_analysis import create_outer_summary\nfrom util_core.util.html_util import (\n get_xpath_attrs_condition, get_img_url, remove_html_content, get_href\n # normalise_outer\n)\n\nEVENTBRITE_EVENT_REGEX = r'eventbrite\\.[a-z\\.]{2,6}/e/'\nGOOGLE_MAPS_REGEX = r'google\\.[a-z\\.]{2,6}/maps/'\n\nEXPECTED_CSS_DISPLAY_VALS = (\n 'inline', 'block', 'inline-flex', 'flex', 'inline-block', '-webkit-box',\n 'table', 'inline-table', 'table-cell', 'list-item'\n)\n\n\ndef is_eventbrite_event(u):\n return bool(re.search(EVENTBRITE_EVENT_REGEX, u))\n\n\ndef is_google_map(u):\n if 'maps.google.co' in u:\n return True\n if re.search(GOOGLE_MAPS_REGEX, u) or 'maps.google' in u: # todo: this is too simple\n return True\n return False\n\n\ndef is_meetup_event(u):\n pass # todo\n\n\nALL_VISIBLE = {'cssComputed__visibility': 'visible', 'jquery__is_hidden': False, 'driver__is_displayed': True, 'spatial_visibility': 'IN_PAGE'} # 'cssComputed__display': 'block'}\n\n\n# r'[day_num_optword] [month_W]'\nDAY_NUM_OPTWORD_MONTH = '(?P01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|1|2|3|4|5|6|7|8|9)(st|nd|rd|th)? (of )?(?Pjanuary|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec)'\n# r'[month_W] [day_num_word]'\nMONTH_DAY_NUM_WORD = '(?Pjanuary|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec) (?P01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|1|2|3|4|5|6|7|8|9)(st|nd|rd|th)'\n# r'[month_W] [year_4]\nMONTH_YEAR = '(?Pjanuary|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec) (?P2010|2011|2012|2013|2014|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024)'\n# r'[time]'\nTIME = '((?P00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|0|1|2|3|4|5|6|7|8|9)(:|\\\\.)(?P(0|1|2|3|4|5)(0|5))\\\\s?(?Pa\\\\.m\\\\.|p\\\\.m\\\\.|am|pm)?|(?P00|01|02|03|04|05|06|07|08|09|10|11|12|1|2|3|4|5|6|7|8|9)\\\\s?(?Pa\\\\.m\\\\.|p\\\\.m\\\\.|am|pm))'\n# r'[day_name]'\nDAY_NAME = '(?Pmonday|tuesday|wednesday|thursday|friday|saturday|sunday|mon|tue|wed|thu|thur|thurs|fri|sat|sun)'\n\nTEXT_DATE_REGEXPS = [\n (DAY_NUM_OPTWORD_MONTH, 'DAY_NUM_OPTWORD_MONTH'),\n (MONTH_DAY_NUM_WORD, 'MONTH_DAY_NUM_WORD'),\n (MONTH_YEAR, 'MONTH_YEAR'),\n (TIME, 'TIME'),\n (DAY_NAME, 'DAY_NAME')\n]\n\n\ndef get_url_data(outer_html, context):\n from webextractor.element_descriptions.descriptions import (\n is_eventbrite_event, is_google_calendar_link, is_google_map\n )\n page_url = context['page_url']\n page_url_host = context['page_url_host']\n page_host_base = context['page_host_base']\n\n url = get_href(outer_html)\n url = normalise_href_url(url, page_url, page_host_base)\n url = (url or '').strip()\n\n di = {\n 'url': url,\n 'url_type': url_type(url) or '',\n 'url_host': '',\n 'url_lower': url.lower(),\n }\n\n if '..' in url: # sometimes happens for some reason\n import pdb; pdb.set_trace()\n print()\n\n if url:\n\n if url and is_social_url(url):\n di['url_host'] = 'SOCIAL_URL_HOST'\n elif di['url_type'] == 'WEBPAGE':\n di['url_host'] = url_host(url)\n\n #di['url_no_nums'] = re.sub(r'\\d+', 'N', di['url']) if di['url'] else None\n #di['url_no_args'] = url.split('?')[0] if '?' in url else url\n #url_params, url_param_names = _get_url_params(url, page_url_host, di['url_host'])\n #di['url_params'], di['url_param_names'] = url_params, url_param_names\n di['url__is_google_map'] = is_google_map(url)\n di['url__is_eventbrite_event'] = is_eventbrite_event(url)\n di['url__google_calendar'] = is_google_calendar_link(url)\n di['url__is_social'] = is_social_url(url)\n url_no_params = url.split('?')[0].rstrip('/')\n di['url__contains_event'] = 'event' in url and not url_no_params.endswith('events')\n\n else:\n di.update({\n 'url__is_google_map': False,\n 'url__is_eventbrite_event': False,\n 'url__google_calendar': False,\n 'url__is_social': False,\n 'url__contains_event': False\n })\n\n return di\n\n\ndef _get_url_params(url, page_url_host, url_host_val):\n url_params, url_param_names = {}, []\n\n if url_host_val == page_url_host and '?' in url:\n query = urlparse(url).query.strip().rstrip('&')\n if query:\n if '=' not in query:\n url_params = {query: ''}\n url_param_names = query\n else:\n try:\n url_params = dict([\n (s.split('=', 1) if '=' in s else (s, 'NO_EQUALS'))\n for s in query.split('&') if s\n ])\n except:\n import pdb; pdb.set_trace()\n url_param_names = list(sorted(url_params.keys()))\n return url_params, url_param_names\n\n\nclass ElemDescription(object):\n\n def __init__(self, elem_node, index, context):\n self.elem_node = elem_node\n self.context = context\n self.index = index\n self.page_url_host = context['page_url_host']\n #self.ancestor_path = None\n\n @classmethod\n def create(cls, elem_node, index, context):\n e = cls(elem_node, index, context)\n if elem_node.tag_name == 'a':\n e.__class__ = LinkElemDescription\n return e\n\n def _get_computed_styles(self):\n styles = self.elem_node.all_computed_styles\n styles_array = np.array([\n # clip at 100 characters\n styles.get(k, '')[:100] for k in EXPECTED_COMPUTED_STYLE_KEYS\n ])\n return {\n 'all_computed_styles': styles,\n 'all_computed_styles_str': [\n k + '___' + v for (k, v) in styles.items()\n ],\n 'all_computed_styles__array': styles_array\n }\n\n def _get_html_content(self):\n\n outerL = self.elem_node.outer_htmlL\n txt = self.elem_node.text\n\n def has_date():\n if not txt:\n return None\n for reg, key in TEXT_DATE_REGEXPS:\n if re.search(reg, txt, flags=re.I):\n return key\n return None\n\n di = {\n 'outer_html': self.elem_node.outer_html,\n 'outer_htmlL': self.elem_node.outer_htmlL,\n #'outer_html_normalised': normalise_outer(self.elem_node.outer_htmlL, l=False),\n 'inner_html': get_inner(self.elem_node.outer_html),\n #'outer_desc': get_tag_desc(self.elem_node.outer_html, prepare=True),\n 'outer_html_no_content': remove_html_content(outerL, l=False),\n 'text': txt, # todo: can we do something to minimise calls to this in preload script?\n 'num_tags': round(self.elem_node.outer_html.count('<') / 2), # todo: move this to another method?\n }\n if di['text'] == \"What's On\" and 'visually-hidden' in di['outer_html']:\n import pdb; pdb.set_trace()\n print()\n\n di['text_has_date'] = has_date()\n\n return di\n\n def _get_self_tag_info(self):\n outer = self.elem_node.outer_html\n parent_elem = self.elem_node.ancestor_path.get(1, 'elem')\n parent_outer = parent_elem.outer_html if parent_elem else None\n parent_outerL = parent_outer.lower() if parent_outer else None\n\n return {\n # todo: we should batch-load outer_html for nodes in parent path\n 'parent_tag_name': get_tag_name(parent_outerL) if parent_outerL else None,\n 'parent_outer_html': parent_outer,\n 'parent_outer_htmlL': parent_outerL if parent_elem else None,\n 'parent_outer_html_no_content': remove_html_content(parent_outerL, l=False) if parent_elem else None,\n #'parent_outer_html_normalised': normalise_outer(parent_outerL, l=False) if parent_elem else None,\n 'parent_start_tag': get_start_tag(parent_outer, normalise=True) if parent_elem else None,\n 'start_tag': get_start_tag(outer, normalise=True),\n 'tag_name': self.elem_node.tag_name,\n 'tags_key': self.elem_node.get_tags_key()\n }\n\n def _get_visibility_info(self):\n # is_displayed__full = True\n # is_displayed__fast = True\n # if self.elem_node.get_is_visible_fast() is False:\n # is_displayed__full = False\n # is_displayed__fast = False\n # elif self.elem_node.driver_elem.is_displayed() is False: # bypassing wrapper method here for certainty when gather ground truth\n # is_displayed__full = False\n\n # if is_displayed__fast is False or is_displayed__full is False:\n # import pdb; pdb.set_trace()\n\n if self.elem_node.driver_elem.is_displayed() is False and self.elem_node.is_displayed():\n print('warning: is_displayed() discrepancy detection disabled')\n #import pdb; pdb.set_trace()\n\n di = {\n 'spatial_visibility': get_spatial_visibility(self.elem_node.rect),\n\n 'driver__is_displayed': self.elem_node.is_displayed(),\n 'cssComputed__display': self.elem_node.value_of_css_property('display'),\n 'cssComputed__visibility': self.elem_node.value_of_css_property('visibility'), # usually 'visible'\n 'jquery__is_hidden': self.elem_node.is_hidden_jquery,\n\n #'is_displayed__fast': is_displayed__fast,\n #'is_displayed__full': is_displayed__full,\n\n # also: self.elem_node.is_displayed and elem_node.is_visible but I think\n # these may be redundant or not worth the cost\n }\n #print(self.elem_node.value_of_css_property('display'))\n #if di['jquery__is_hidden'] != (not di['driver__is_displayed']):\n # import pdb; pdb.set_trace() # if this continues to never catch, we can stop using is_displayed()\n\n di['visibility__ALL_VISIBLE'] = True\n for key, visible_val in ALL_VISIBLE.items():\n if di[key] != visible_val:\n di['visibility__ALL_VISIBLE'] = False\n break\n if di['visibility__ALL_VISIBLE'] and di['cssComputed__display'] not in EXPECTED_CSS_DISPLAY_VALS:\n print('cssComputed__display___'+di['cssComputed__display'])\n import pdb; pdb.set_trace()\n di['visibility__ALL_VISIBLE'] = False\n\n return di\n\n def _get_img_info(self, ed):\n\n img_type = None\n if '
')\ndef server_static(filename):\n return static_file(filename, root='./public_html')\n\n@route('/api/students')\ndef students():\n pass\n\n@route('/api/clean_students')\ndef clean_students():\n Student_Clean.clean()\n return json.dumps({\n 'message': \"OK\"\n })\n\n\n@route('/api/student/deliver_taskset', method='POST')\ndef deliver_taskset():\n name = request.json[\"name\"]\n taskset = request.json[\"taskset\"]\n\n data = req.post(\"http://localhost:27000/student/\" + name + \"/deliver_taskset\", json={\n 'taskset': taskset\n })\n\n print(data)\n return data.json()\n\n\n\n\n@route('/api/student//taskset')\ndef taskset(student):\n\n data = req.get(\"http://localhost:27000/student/{0}/taskset\".format(student))\n return data.json()\n\n\n\n@route('/api/students')\ndef create_students():\n return json.dumps(StudentEngine.get_students())\n\n@route('/api/create_students')\ndef create_students():\n Student_Create.generate()\n\n\n return json.dumps({\n 'message': \"OK\",\n 'students': StudentEngine.get_students()\n })\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n run(host='0.0.0.0', port=8080)\n\n","sub_path":"AI/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"396402974","text":"from api.views_helper import *\nfrom api.email_helper import *\n\nfrom django.contrib.auth.models import User, AnonymousUser\nfrom rest_framework import viewsets, filters\nfrom api.models import *\nfrom api.healthfiles.models import *\nfrom api.serializers import *\nfrom api.healthfiles.serializers import *\n\nimport hashlib, os\n\nfrom rest_framework.authtoken.models import Token\n\nfrom rest_framework.views import APIView\nfrom rest_framework.authtoken.serializers import AuthTokenSerializer\nfrom rest_framework import permissions, renderers, parsers, status\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\n\n\nfrom rest_framework.response import Response\n\nfrom django.http import HttpResponse\nfrom itertools import chain\n\nfrom datetime import datetime, timedelta\nfrom django.shortcuts import get_object_or_404\n\n#from django.core import exceptions\nfrom django.contrib.auth.hashers import *\n\nimport boto\nfrom boto.s3.key import Key\nfrom django.conf import settings\n\n\n\n\n\n@api_view(['GET',])\n@permission_classes((permissions.AllowAny,))\n#@authentication_classes()\ndef heartbeat(request):\n return HttpResponse(status=204)\n\n@api_view(['POST',])\ndef share_healthfile(request, healthfile_id):\n serializer = FileShareSerializer(data=request.DATA, context={'request': request})\n if serializer.is_valid():\n try:\n m = Healthfile.objects.get(pk=healthfile_id,is_deleted=False)\n\n has_permission = False\n if request.user.is_authenticated():\n pass\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n user_id = int(request.user.id)\n\n if request.user == m.user:\n has_permission = True\n else:\n qqueryset = UserGroupSet.objects.filter(user_id__in=[user_id,m.user_id],group_id__in=[user_id,m.user_id],status='ACTIVE',is_deleted=False)\n for p in qqueryset:\n if(p.user_id != p.group_id):\n has_permission = True\n if has_permission:\n mm = {}\n mm['url'] = 'media/'+str(m.file)\n mm['name'] = m.name\n share_healthfile_email(request.user,serializer.object.get('email'),mm)\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Healthfile.DoesNotExist:\n return Response(content, status=status.HTTP_404_NOT_FOUND)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET',])\ndef handles3downloads(request, healthfile_id):\n LOCAL_PATH = settings.S3_LOCAL_DOWNLOAD_LOCATION\n\n try:\n m = Healthfile.objects.get(id=healthfile_id,is_deleted=False)\n\n has_permission = False\n if request.user.is_authenticated():\n pass\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n user_id = int(request.user.id)\n\n if request.user == m.user:\n has_permission = True\n else:\n qqueryset = UserGroupSet.objects.filter(user_id__in=[user_id,m.user_id],group_id__in=[user_id,m.user_id],status='ACTIVE',is_deleted=False)\n for p in qqueryset:\n if(p.user_id != p.group_id):\n has_permission = True\n \n if has_permission:\n try:\n conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)\n \n key = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME).get_key('media/'+str(m.file))\n # delete file first and after wards\n if os.path.exists(LOCAL_PATH+str(m.id)+'-'+m.name):\n os.remove(LOCAL_PATH+str(m.id)+'-'+m.name)\n key.get_contents_to_filename(LOCAL_PATH+str(m.id)+'-'+m.name)\n \n response = HttpResponse(file(LOCAL_PATH+str(m.id)+'-'+m.name), content_type = m.mime_type)\n response['Content-Length'] = os.path.getsize(LOCAL_PATH+str(m.id)+'-'+m.name)\n return response\n except:\n return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n else:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Healthfile.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n\n\n@api_view(['GET',])\ndef api_root(request, format=None):\n return Response({})\n\nclass ObtainAuthToken(APIView):\n throttle_classes = ()\n permission_classes = ()\n parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)\n renderer_classes = (renderers.JSONRenderer,)\n serializer_class = AuthTokenSerializer\n model = Token\n\n def post(self, request):\n access_token = request.POST.get(\"access_token\",None)\n email = request.POST.get(\"email\",None)\n mobile = request.POST.get(\"mobile\",None)\n if access_token is not None:\n serializer = SocialAuthTokenSerializer(data=request.DATA)\n elif email is not None:\n serializer = EmailAuthTokenSerializer(data=request.DATA)\n elif mobile is not None:\n serializer = MobileAuthTokenSerializer(data=request.DATA)\n else:\n serializer = self.serializer_class(data=request.DATA)\n if serializer.is_valid():\n token, created = Token.objects.get_or_create(user=serializer.object['user'])\n return Response({'token': token.key})\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n\n\"\"\"\nfrom data_importer import XLSImporter, BaseImporter\nimport pprint\nfrom api.diet.models import *\nimport fractions\n\n\nclass FoodItemXlsImporterModel(BaseImporter):\n class Meta:\n model = FoodItem\n ignore_first_line = True\n raise_errors = True\n delimiter = ','\n exclude = ['display_image','quantity','calories_unit', 'total_fat_unit', 'saturated_fat_unit', 'polyunsaturated_fat_unit', 'monounsaturated_fat_unit', 'trans_fat_unit', 'cholesterol_unit', 'sodium_unit', 'potassium_unit', 'total_carbohydrates_unit', 'dietary_fiber_unit', 'sugars_unit', 'protein_unit', 'vitamin_a_unit', 'vitamin_c_unit', 'calcium_unit', 'iron_unit',\n 'created_at','updated_at','updated_by',\n ]\n\ndef upload_fdb_files(filename):\n #LOCAL_DIR = os.path.dirname(__file__)\n LOCAL_DIR = '/home/kunalr/codebase/portal/vapi/api/csvs/c'\n #xls_file = os.path.join(LOCAL_DIR, 'csvs/'+filename)\n #xls_file = 'csvs/'+filename\n xls_file = os.path.join(LOCAL_DIR, filename)\n print xls_file\n print filename\n #return\n my_csv_list = FoodItemXlsImporterModel(source=xls_file)\n pprint.pprint(my_csv_list.cleaned_data[1])\n user = User.objects.get(id=1)\n import string\n i = 0\n for k,m in my_csv_list.cleaned_data:\n \n i = i + 1\n #print i\n try:\n m['quantity_unit'] = filter(lambda x: x in string.printable, m['quantity_unit'])\n m['name'] = filter(lambda x: x in string.printable, m['name'])\n\n qstr = m['quantity_unit']\n m['quantity'],abc,m['quantity_unit'] = qstr.partition(\" \")\n #print m['quantity']\n if m['quantity'] == '1/2':\n m['quantity'] = 0.5\n elif m['quantity'] == '1/3':\n m['quantity'] = 0.33;\n elif m['quantity'] == '3/4':\n m['quantity'] = 0.75;\n elif m['quantity'] == '1/4':\n m['quantity'] = 0.25;\n elif m['quantity'] == '2/3':\n m['quantity'] = 0.66;\n elif m['quantity'] == '1/8':\n m['quantity'] = 0.125;\n else:\n try:\n m['quantity'] = float(m['quantity'])\n except:\n m['quantity'] = float(fractions.Fraction(m['quantity']))\n m['updated_by'] = user\n m['status'] = 'ACTIVE'\n except:\n pprint.pprint(my_csv_list.cleaned_data[i-1])\n continue\n fi = FoodItem(**m)\n fi.save(force_insert=True,)\n\n \n\n@api_view(['GET',])\ndef upload_food_items(request, format=None):\n path= os.path.dirname(os.path.abspath(__file__))\n csvs = os.path.join(path, 'csvs')\n os.chdir('/home/kunalr/codebase/portal/vapi/api/csvs/c/')\n for files in os.listdir(\".\"):\n upload_fdb_files(files)\n #upload_fdb_files('fdb3.xls')\n #upload_fdb_files('fdb4.xls')\n\n\"\"\"\n","sub_path":"vapi/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"253103258","text":"from aocd import get_data\n\ndef part_one(input):\n areas=input.splitlines()\n print(\"Part One: \", areas)\n\ndef part_two(input):\n res=''\n print(\"Part Two: \", res)\n\n\ndata = get_data(day=6)\ndata = \"\"\"1, 1\n1, 6\n8, 3\n3, 4\n5, 5\n8, 9\"\"\"\npart_one(data)\npart_two(data)\n","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"433386154","text":"import matplotlib.pyplot as plt\nfrom model_fpn import I2D\nfrom threading import Thread\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\nimport argparse, time\nimport cv2\nimport numpy as np\nimport os, sys\nimport timeit\nimport torch, time\nimport imageio\nimport PIL\nfrom torchvision import transforms\nimport open3d as o3d\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Normal image estimation from ToF depth image')\n parser.add_argument('--cuda', dest='cuda',\n help='whether use CUDA',\n default=True,\n action='store_true')\n parser.add_argument('--num_workers', dest='num_workers',\n help='num_workers',\n default=1, type=int) \n parser.add_argument('--input_image_path', dest='input_image_path',\n help='path to a single input image for evaluation',\n # default='/media/rambo/ssd2/Szilard/nyu_v2_filter/comparison/depth3_/', type=str)\n default='/media/rambo/ssd2/Szilard/pico_tofnest/4bag_unfiltered/depth3/', type=str)\n parser.add_argument('--eval_folder', dest='eval_folder',\n help='evaluate only one image or the whole folder',\n default=True, type=bool)\n parser.add_argument('--model_path', dest='model_path',\n help='path to the model to use',\n default='saved_models/dfilt_1_9_v33.pth', type=str)\n\n args = parser.parse_args()\n return args\n\ndef point_cloud(depth1):\n \"\"\"Transform a depth image into a point cloud with one point for each\n pixel in the image, using the camera transform for a camera\n centred at cx, cy with field of view fx, fy.\n\n depth is a 2-D ndarray with shape (rows, cols) containing\n depths from 1 to 254 inclusive. The result is a 3-D array with\n shape (rows, cols, 3). Pixels with invalid depth in the input have\n NaN for the z-coordinate in the result.\n\n \"\"\"\n # depth is of shape (1,480,640)\n # K = [460.58518931365654, 0.0, 334.0805877590529, 0.0, 460.2679961517268, 169.80766383231037, 0.0, 0.0, 1.0] # pico zense\n K = [460.585, 0.0, 334.081, 0.0, 460.268, 169.808, 0.0, 0.0, 1.0] # pico zense\n # K = [582.62448167737955, 0.0, 313.04475870804731, 0.0, 582.69103270988637, 238.44389626620386, 0.0, 0.0, 1.0] # nyu_v2_dataset\n # K = [582.624, 0.0, 313.045, 0.0, 582.691, 238.444, 0.0, 0.0, 1.0] # nyu_v2_dataset\n fx = K[0]\n fy = K[4]\n cx = K[2]\n cy = K[5]\n\n depth = depth1.clone()\n # open3d_img = o3d.t.geometry.Image(depth[0])#/1000.0)\n # intrinsics = o3d.camera.PinholeCameraIntrinsic(640,360,fx,fy,cx,cy)\n # pcd = o3d.geometry.create_point_cloud_from_depth_image(open3d_img,intrinsic=intrinsics)\n \n rows, cols = depth[0].shape\n c, _ = torch.meshgrid(torch.arange(cols), torch.arange(cols))\n c = torch.meshgrid(torch.arange(cols))\n new_c = c[0].reshape([1,cols]).to('cuda')\n r = torch.meshgrid(torch.arange(rows))\n new_r = r[0].unsqueeze(-1).to('cuda')\n valid = (depth[0] > 0) & (depth[0] < 65535)\n nan_number = torch.tensor(np.nan).to('cuda')\n zero_number = torch.tensor(0.).to('cuda')\n z = torch.where(valid, depth[0]/1000.0, nan_number) # allways divide with 1000.0\n x = torch.where(valid, z * (new_c - cx) / fx, nan_number)\n y = torch.where(valid, z * (new_r - cy) / fy, nan_number)\n \n\n dimension = rows * cols\n z_ok = z.reshape(dimension)\n x_ok = x.reshape(dimension)\n y_ok = y.reshape(dimension)\n\n return torch.stack((x_ok,y_ok,z_ok),dim=1) \n\nif __name__ == '__main__':\n\n args = parse_args()\n\n if torch.cuda.is_available() and not args.cuda:\n print(\"WARNING: You might want to run with --cuda\")\n \n # network initialization\n print('Initializing model...')\n i2d = I2D(fixed_feature_weights=False)\n if args.cuda:\n i2d = i2d.cuda()\n \n print('Done!')\n \n \n load_name = os.path.join(args.model_path)\n print(\"loading checkpoint %s\" % (load_name))\n state = i2d.state_dict()\n checkpoint = torch.load(load_name)\n checkpoint = {k: v for k, v in checkpoint['model'].items() if k in state}\n state.update(checkpoint)\n i2d.load_state_dict(state)\n if 'pooling_mode' in checkpoint.keys():\n POOLING_MODE = checkpoint['pooling_mode']\n print(\"loaded checkpoint %s\" % (load_name))\n del checkpoint\n torch.cuda.empty_cache()\n\n i2d.eval()\n\n img = Variable(torch.FloatTensor(1))\n\n print('evaluating...')\n if args.eval_folder:\n dlist=os.listdir(args.input_image_path)\n dlist.sort()\n time_sum = 0\n counter = 0\n max_depth=7000.\n min_depth=300.\n nan_number = torch.tensor(np.nan).to('cuda')\n eps_number = torch.tensor(1e-7).to('cuda')\n zero_number = torch.tensor(0.).to('cuda')\n for filename in dlist:\n if filename.endswith(\".png\"):\n path=args.input_image_path+filename\n print(\"Predicting for:\"+filename)\n depth = cv2.imread(path,cv2.IMREAD_UNCHANGED).astype(np.float32)\n if len(depth.shape) < 3:\n print(\"Got 1 channel depth images, creating 3 channel depth images\")\n combine_depth = np.empty((depth.shape[0],depth.shape[1], 3))\n combine_depth[:,:,0] = depth\n combine_depth[:,:,1] = depth\n combine_depth[:,:,2] = depth\n depth = combine_depth\n depth2 = np.moveaxis(depth,-1,0)\n img = torch.from_numpy(depth2).float().unsqueeze(0).cuda()\n \n start = timeit.default_timer()\n # img2=img.clone()\n # img[img>max_depth] = max_depth\n # img[img 0) & (imgmask < max_depth+1)\n # img2=img2-min_depth\n # m_depth=torch.max(img)\n img=img/max_depth \n z_fake = i2d(img)\n # z_fake = torch.where(valid, z_fake*max_depth, zero_number)\n stop = timeit.default_timer()\n time_sum=time_sum+stop-start\n counter=counter+1\n save_path=path[:-4]\n\n # plt.imshow(z_fake[0].cpu().detach().numpy().transpose((1,2,0))*max_depth, vmin=0, vmax=max_depth)\n # plt.colorbar()\n # plt.savefig(save_path +'_pred.png',bbox_inches='tight')\n # plt.close()\n o3d_pcd = o3d.geometry.PointCloud()\n z_fake_pcd = point_cloud(z_fake[0]).cpu().detach().numpy()\n o3d_pcd.points = o3d.utility.Vector3dVector(z_fake_pcd*max_depth)\n o3d.io.write_point_cloud(save_path +'_pred.pcd', o3d_pcd)\n # npimage=(z_fake[0]/max_depth).squeeze(0).cpu().detach().numpy().astype(np.uint16)\n # cv2.imwrite(save_path +'_pred.png', npimage)\n\n else:\n continue\n print('Predicting '+str(counter)+' images took ', time_sum/counter) \n else:\n depth = cv2.imread(args.input_image_path,cv2.IMREAD_UNCHANGED).astype(np.float32)\n if len(depth.shape) < 3:\n print(\"Got 1 channel depth images, creating 3 channel depth images\")\n combine_depth = np.empty((depth.shape[0],depth.shape[1], 3))\n combine_depth[:,:,0] = depth\n combine_depth[:,:,1] = depth\n combine_depth[:,:,2] = depth\n depth = combine_depth\n depth2 = np.moveaxis(depth,-1,0)\n img = torch.from_numpy(depth2).float().unsqueeze(0)\n start = timeit.default_timer()\n z_fake = i2d(img.cuda())\n stop = timeit.default_timer()\n zfv=z_fake*2-1\n z_fake_norm=zfv.pow(2).sum(dim=1).pow(0.5).unsqueeze(1)\n zfv=zfv/z_fake_norm\n z_fake=(zfv+1)/2\n save_path=args.input_image_path[:-4]\n save_image(z_fake[0], save_path +\"_pred\"+'.png')\n print('Predicting the image took ', stop-start)\n \n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":8246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"98814793","text":"from datasets import load_dataset\n\n\ndata_files = {}\ntrain_file = '../naver_news/naver_news_train.txt'\nvalidation_file = '../naver_news/naver_news_eval.txt'\ndata_files[\"train\"] = train_file\ndata_files[\"validation\"] = validation_file\n\n\ndatasets = load_dataset('text', data_files=data_files)\ndatasets.save_to_disk('/data/aicc1/datasets')\n","sub_path":"data/save_datasets.py","file_name":"save_datasets.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"50897538","text":"# Autor: Oscar Macias Rodríguez\r\n# Descripción: Lee el número de paquetes comprados y despliega la cantidad descontada(si la hay) y el total a pagar.\r\n\r\n\r\n# Función principal. Imprime el total a pagar y recibe la cantidad de paquetes.\r\ndef main():\r\n cantidadPaquetes = int(input(\"Cantidad de paquetes: \"))\r\n print(\"Total: $\", totalPagar(cantidadPaquetes))\r\n\r\n\r\n# Calcula el precio con descuento.\r\ndef totalPagar(cantidadPaquetes):\r\n precioFijo = 1500\r\n\r\n if 0 >= cantidadPaquetes:\r\n print(\"Error\")\r\n main()\r\n else:\r\n if 1 <= cantidadPaquetes < 9:\r\n return(precioFijo)\r\n if 10 <= cantidadPaquetes < 19:\r\n return(precioFijo*1.20)\r\n if 20 <= cantidadPaquetes < 49:\r\n return(precioFijo*1.30)\r\n if 50 <= cantidadPaquetes < 99:\r\n return(precioFijo*1.40)\r\n if 100 <= cantidadPaquetes:\r\n return(precioFijo*1.50)\r\n return\r\n\r\n\r\nmain()","sub_path":"Software.py","file_name":"Software.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"251766569","text":"import numpy as np\r\nimport nltk\r\nimport os\r\nfrom nltk.corpus import stopwords\r\ndataroot = os.path.abspath('../../Data')\r\n\r\ndef importData(data_type=0, is_rm=True):\r\n if data_type == 0:\r\n ## training data\r\n files = (\r\n './processed/SQuAD1.0/train/sentences.npz', './processed/SQuAD1.0/train/questions.npy',\r\n './processed/SQuAD1.0/train/answers.npy', './processed/SQuAD1.0/train/answers_start.npy')\r\n elif data_type == 1:\r\n ## validation date\r\n files = (\r\n './processed/SQuAD1.0/val/sentences.npz', './processed/SQuAD1.0/val/questions.npy',\r\n './processed/SQuAD1.0/val/answers.npy', './processed/SQuAD1.0/val/answers_start.npy')\r\n else:\r\n ## test data\r\n if not is_rm:\r\n files = (\r\n './processed/SQuAD1.0/test/sentences.npz', './processed/SQuAD1.0/test/questions.npy',\r\n './processed/SQuAD1.0/test/answers.npy', './processed/SQuAD1.0/test/answers_start.npy')\r\n else:\r\n files = (\r\n './processed/SQuAD1.0/test/rm_sentences.npz', './processed/SQuAD1.0/test/rm_questions.npy',\r\n './processed/SQuAD1.0/test/rm_answers.npy', './processed/SQuAD1.0/test/rm_answers_start.npy')\r\n sentences = np.load(os.path.join(dataroot, files[0]))['sent']\r\n questions = np.load(os.path.join(dataroot, files[1]))\r\n answers = np.load(os.path.join(dataroot, files[2]))\r\n answers_start = np.load(os.path.join(dataroot, files[3]))\r\n return sentences, questions, answers, answers_start\r\n\r\n\r\ndef import_entity_data(data_type=0, is_connected=False, is_span_bounds=False):\r\n if is_connected:\r\n if data_type == 0:\r\n entity_file = './processed/SQuAD1.0/train/connected_entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/train/connected_entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/train/connected_entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/train/connected_entity_type.npy'\r\n elif data_type == 1:\r\n entity_file = './processed/SQuAD1.0/val/connected_entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/val/connected_entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/val/connected_entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/val/connected_entity_type.npy'\r\n else:\r\n entity_file = './processed/SQuAD1.0/test/connected_entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/test/connected_entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/test/connected_entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/test/connected_entity_type.npy'\r\n else:\r\n if data_type == 0:\r\n entity_file = './processed/SQuAD1.0/train/entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/train/entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/train/entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/train/entity_type.npy'\r\n elif data_type == 1:\r\n entity_file = './processed/SQuAD1.0/val/entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/val/entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/val/entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/val/entity_type.npy'\r\n else:\r\n entity_file = './processed/SQuAD1.0/test/entity.npy'\r\n entity_location_file = './processed/SQuAD1.0/test/entity_location.npy'\r\n entity_span_bounds_file = './processed/SQuAD1.0/test/entity_span_bounds.npy'\r\n entity_type_file = './processed/SQuAD1.0/test/entity_type.npy'\r\n\r\n entities = np.load(os.path.join(dataroot, entity_file))\r\n entities_location = np.load(os.path.join(dataroot, entity_location_file))\r\n entities_type = np.load(os.path.join(dataroot, entity_type_file))\r\n if not is_span_bounds:\r\n return entities, entities_location, entities_type\r\n else:\r\n entities_span_bounds = np.load(os.path.join(dataroot, entity_span_bounds_file))\r\n return entities, entities_location, entities_span_bounds, entities_type\r\n\r\n\r\ndef save_entity_data(entities, entities_location, entities_type, data_type=0):\r\n if data_type == 0:\r\n save_entity_file = './processed/SQuAD1.0/train/entity'\r\n save_location_file = './processed/SQuAD1.0/train/entity_location'\r\n save_type_file = './processed/SQuAD1.0/train/entity_type'\r\n elif data_type == 1:\r\n save_entity_file = './processed/SQuAD1.0/val/entity'\r\n save_location_file = './processed/SQuAD1.0/val/entity_location'\r\n save_type_file = './processed/SQuAD1.0/val/entity_type'\r\n else:\r\n save_entity_file = './processed/SQuAD1.0/test/entity'\r\n save_location_file = './processed/SQuAD1.0/test/entity_location'\r\n save_type_file = './processed/SQuAD1.0/test/entity_type'\r\n\r\n np.save(os.path.join(dataroot, save_entity_file), entities)\r\n np.save(os.path.join(dataroot, save_location_file), entities_location)\r\n np.save(os.path.join(dataroot, save_type_file), entities_type)\r\n\r\n\r\ndef combine_connected_entities(data_type=0):\r\n sentences, questions, answers_text, _ = importData(data_type=data_type)\r\n entities, entities_location, entities_type = import_entity_data(data_type=data_type)\r\n special_types = ['PERSON', 'ORGANIZATION', 'LOCATION', 'MONEY', 'TRANSPORTATION', 'NUMBER', 'HOLIDAY', 'DATE', 'TIME', 'NORP', 'QUANTITY', 'PERCENT', 'EVENT', 'WORK']\r\n for i, each_sent_entities in enumerate(entities):\r\n j = 1\r\n while j < len(each_sent_entities):\r\n if (entities_type[i][j-1] == special_types[1] and entities_type[i][j] == 'DATE') or (\r\n entities_type[i][j-1] == 'DATE' and entities_type[i][j] == special_types[1]):\r\n j = j + 1\r\n elif (entities_type[i][j-1] == 'DATE' and entities_type[i][j] == 'PERCENT') or (\r\n entities_type[i][j - 1] == 'PERCENT' and entities_type[i][j] == 'DATE'):\r\n j = j + 1\r\n elif (entities_type[i][j - 1] == 'PERCENT' and entities_type[i][j] == special_types[1]) or (\r\n entities_type[i][j - 1] == special_types[1] and entities_type[i][j] == 'PERCENT'):\r\n j = j + 1\r\n elif entities_type[i][j-1] == special_types[1] and entities_type[i][j] == 'QUANTITY':\r\n j = j + 1\r\n elif (entities_type[i][j-1] == 'QUANTITY' and entities_type[i][j] == special_types[-2]) or (\r\n entities_type[i][j - 1] == special_types[-2] and entities_type[i][j] == 'QUANTITY'):\r\n j = j + 1\r\n elif (entities_type[i][j-1] == special_types[-2] and entities_type[i][j] == 'DATE') or (\r\n entities_type[i][j - 1] == 'DATE' and entities_type[i][j] == special_types[-2]):\r\n j = j + 1\r\n elif entities_type[i][j-1] == 'DATE' and entities_type[i][j] == 'NORP':\r\n j = j + 1\r\n elif entities_type[i][j - 1] == 'DATE' and entities_type[i][j] == 'HOLIDAY':\r\n j = j + 1\r\n elif entities_type[i][j-1] == 'HOLIDAY' and entities_type[i][j] == 'DATE':\r\n j = j + 1\r\n elif entities_type[i][j-1] == 'NORP' and entities_type[i][j] == 'PERCENT':\r\n j = j + 1\r\n elif each_sent_entities[j] in each_sent_entities[j-1]:\r\n each_sent_entities.pop(j)\r\n entities_location[i].pop(j)\r\n entities_type[i].pop(j)\r\n elif (entities_location[i][j-1][1] + 1) >= entities_location[i][j][0]:\r\n x = each_sent_entities.pop(j-1)\r\n y = each_sent_entities.pop(j-1)\r\n combined_start_index = entities_location[i].pop(j-1)[0]\r\n combined_end_index = entities_location[i].pop(j-1)[1]\r\n first_type = entities_type[i].pop(j - 1)\r\n second_type = entities_type[i].pop(j - 1)\r\n\r\n if combined_start_index < combined_end_index:\r\n each_sent_entities.insert(j-1, sentences[i][combined_start_index: combined_end_index])\r\n entities_location[i].insert(j-1, (combined_start_index, combined_end_index))\r\n\r\n if first_type == second_type:\r\n entities_type[i].insert(j-1, first_type)\r\n elif first_type == 'CONCEPT' and second_type in special_types:\r\n entities_type[i].insert(j-1, second_type)\r\n elif first_type in special_types and second_type == 'CONCEPT':\r\n entities_type[i].insert(j-1, first_type)\r\n else:\r\n if first_type == special_types[0] or second_type == special_types[0]:\r\n entities_type[i].insert(j-1, special_types[0])\r\n elif first_type == special_types[2] or second_type == special_types[2]:\r\n entities_type[i].insert(j-1, special_types[2])\r\n elif first_type == special_types[3] or second_type == special_types[3]:\r\n entities_type[i].insert(j-1, special_types[3])\r\n elif first_type == special_types[4] or second_type == special_types[4]:\r\n entities_type[i].insert(j-1, special_types[4])\r\n elif (first_type == special_types[1] and second_type == special_types[-1]) or (\r\n first_type == special_types[-1] and second_type == special_types[1]):\r\n entities_type[i].insert(j-1, special_types[1])\r\n # elif (first_type == special_types[1] and second_type == special_types[-2]) or (\r\n elif first_type == special_types[-2] and second_type == special_types[1]:\r\n entities_type[i].insert(j-1, special_types[-2])\r\n elif first_type == special_types[-2] and second_type == special_types[8]:\r\n entities_type[i].insert(j-1, special_types[-2])\r\n elif (first_type == special_types[1] and second_type == special_types[8]) or (\r\n first_type == special_types[8] and second_type == special_types[1]):\r\n entities_type[i].insert(j-1, special_types[8])\r\n elif (first_type == special_types[5] and second_type in (special_types[1:2]+special_types[6:])) or (\r\n first_type in (special_types[1:2]+special_types[6:]) and second_type == special_types[5]):\r\n entities_type[i].insert(j-1, special_types[5])\r\n elif (first_type == 'DATE' and second_type == 'TIME') or (first_type == 'TIME' and second_type == 'DATE'):\r\n entities_type[i].insert(j-1, 'TIME')\r\n elif first_type == special_types[-1]:\r\n entities_type[i].insert(j-1, second_type)\r\n elif second_type == special_types[-1]:\r\n entities_type[i].insert(j-1, first_type)\r\n elif first_type in (special_types[1:2]+special_types[9:10]) and second_type == special_types[-2]:\r\n entities_type[i].insert(j-1, second_type)\r\n elif first_type == special_types[-2] and second_type == special_types[9]:\r\n entities_type[i].insert(j-1, first_type)\r\n elif first_type == 'QUANTITY' and second_type == 'DATE':\r\n entities_type[i].insert(j-1, second_type)\r\n elif (first_type == 'NORP' and second_type in (special_types[1:2] + special_types[7:8])) or (\r\n first_type in (special_types[1:2] + special_types[7:8]) and second_type == 'NORP'):\r\n entities_type[i].insert(j-1, 'NORP')\r\n elif first_type == special_types[8] and second_type == special_types[6]:\r\n entities_type[i].insert(j-1, special_types[8])\r\n elif first_type == special_types[-3] and second_type == special_types[9]:\r\n entities_type[i].insert(j-1, special_types[9])\r\n elif first_type == special_types[9] and second_type == special_types[6]:\r\n entities_type[i].insert(j-1, special_types[6])\r\n elif first_type == special_types[6] and second_type == special_types[8]:\r\n entities_type[i].insert(j-1, special_types[6])\r\n elif first_type == special_types[8] and second_type == special_types[-2]:\r\n entities_type[i].insert(j-1, special_types[-2])\r\n elif first_type == special_types[6] and second_type == special_types[-2]:\r\n entities_type[i].insert(j-1, special_types[-2])\r\n elif first_type == special_types[-3] and second_type == special_types[8]:\r\n entities_type[i].insert(j-1, special_types[-3])\r\n elif first_type == special_types[7] and second_type == special_types[10]:\r\n entities_type[i].insert(j-1, special_types[7])\r\n else:\r\n print(sentences[i])\r\n print(questions[i])\r\n print(answers_text[i])\r\n print(x, '\\t', y, '\\t')\r\n print(each_sent_entities[j-1], first_type, second_type)\r\n entities_type[i].insert(j - 1, special_types[1])\r\n print('#'*80)\r\n else:\r\n j = j - 1\r\n else:\r\n j = j + 1\r\n\r\n if len(each_sent_entities) > 0 and each_sent_entities[-1] == 'rrb':\r\n each_sent_entities.pop()\r\n entities_location[i].pop()\r\n entities_type[i].pop()\r\n\r\n # print(sentences[i])\r\n # print(entities[i])\r\n # print(entities_location[i])\r\n # print('#'*100)\r\n\r\n if i % 1000 == 0:\r\n print(i)\r\n\r\n if data_type == 0:\r\n connected_entity_file = './processed/SQuAD1.0/train/connected_entity.npy'\r\n connected_entity_location_file = './processed/SQuAD1.0/train/connected_entity_location.npy'\r\n connected_entity_type_file = './processed/SQuAD1.0/train/connected_entity_type.npy'\r\n elif data_type == 1:\r\n connected_entity_file = './processed/SQuAD1.0/val/connected_entity.npy'\r\n connected_entity_location_file = './processed/SQuAD1.0/val/connected_entity_location.npy'\r\n connected_entity_type_file = './processed/SQuAD1.0/val/connected_entity_type.npy'\r\n else:\r\n connected_entity_file = './processed/SQuAD1.0/test/connected_entity.npy'\r\n connected_entity_location_file = './processed/SQuAD1.0/test/connected_entity_location.npy'\r\n connected_entity_type_file = './processed/SQuAD1.0/test/connected_entity_type.npy'\r\n\r\n np.save(os.path.join(dataroot, connected_entity_file), entities)\r\n np.save(os.path.join(dataroot, connected_entity_location_file), entities_location)\r\n np.save(os.path.join(dataroot, connected_entity_type_file), entities_type)\r\n\r\n\r\ndef remove_unoverlap_data(sentences, questions, answers, answers_start):\r\n rm_sentences, rm_questions, rm_answers, rm_answers_start = list(), list(), list(), list()\r\n\r\n for i,sent in enumerate(sentences):\r\n sent_words = nltk.word_tokenize(sent)\r\n rm_sent_words = [w for w in sent_words if(w not in stopwords.words('english'))]\r\n rm_sent_words_set = set(rm_sent_words)\r\n\r\n cur_questions, cur_answers, cur_answers_start = list(), list(), list(),\r\n for j,ques in enumerate(questions[i]):\r\n ques_words = nltk.word_tokenize(ques)\r\n rm_ques_words = [w for w in ques_words if(w not in stopwords.words('english'))]\r\n if len(rm_sent_words_set & set(rm_ques_words)) > 0:\r\n cur_questions.append(ques)\r\n cur_answers.append(answers[i][j])\r\n cur_answers_start.append(answers_start[i][j])\r\n if len(cur_questions) > 0:\r\n rm_sentences.append(sent)\r\n rm_questions.append(cur_questions)\r\n rm_answers.append(cur_answers)\r\n rm_answers_start.append(cur_answers_start)\r\n if i % 100 == 0:\r\n print(i)\r\n print('length', len(rm_sentences))\r\n np.savez_compressed('../processed/SQuAD1.0/test/rm_sentences', sent=rm_sentences)\r\n np.save('../processed/SQuAD1.0/test/rm_questions', rm_questions)\r\n np.save('../processed/SQuAD1.0/test/rm_answers', rm_answers)\r\n np.save('../processed/SQuAD1.0/test/rm_answers_start', rm_answers_start)\r\n\r\n\r\ndef tag_answers(sentences, answers, answers_start):\r\n sentences_taggings = list()\r\n for i, each_sent in enumerate(sentences):\r\n sent_length = len(nltk.word_tokenize(each_sent))\r\n for j in range(len(answers[i])):\r\n BIO_tagging = ['O', ] * sent_length\r\n start = len(nltk.word_tokenize(each_sent[:answers_start[i][j]]))\r\n answer_length = len(nltk.word_tokenize(answers[i][j]))\r\n BIO_tagging[start] = 'B'\r\n if answer_length > 1:\r\n BIO_tagging[start+1 : start+answer_length] = ['I', ] * (answer_length - 1)\r\n\r\n sentences_taggings.append(BIO_tagging)\r\n sentences_taggings = np.array(sentences_taggings)\r\n return sentences_taggings\r\n\r\n\r\ndef get_tagging_data(answers_BIO, index=None):\r\n tag_dict = {'B': 1, 'I': 2, 'O': 0}\r\n all_answers_tag = []\r\n for answer_bio in answers_BIO:\r\n vector = list()\r\n for each_tag in answer_bio:\r\n idx = tag_dict.get(each_tag)\r\n vector.append(idx)\r\n all_answers_tag.append(vector)\r\n all_answers_tag = np.array(all_answers_tag)\r\n if index is None:\r\n shuffle_all_answer_tag = all_answers_tag\r\n else:\r\n shuffle_all_answer_tag = all_answers_tag[index]\r\n return shuffle_all_answer_tag, tag_dict\r\n\r\n\r\ndef save_answer_tagging(data_type=0):\r\n if data_type == 0:\r\n answer_taggings_file = './processed/SQuAD1.0/train/answer_labels.npy'\r\n elif data_type ==1:\r\n answer_taggings_file = './processed/SQuAD1.0/val/answer_labels.npy'\r\n else:\r\n answer_taggings_file = './processed/SQuAD1.0/test/answer_labels.npy'\r\n\r\n sentences, _, answers, answers_start = importData(data_type=data_type)\r\n answer_taggings = tag_answers(sentences, answers, answers_start)\r\n all_answer_taggings = get_tagging_data(answer_taggings)[0]\r\n np.save(os.path.join(dataroot, answer_taggings_file), all_answer_taggings)\r\n\r\n\r\nif __name__ == '__main__':\r\n test_sentences, test_questions, test_answers, test_answers_start = importData(data_type=2, is_rm=False)\r\n remove_unoverlap_data(test_sentences, test_questions, test_answers, test_answers_start)\r\n\r\n save_answer_tagging(data_type=0)\r\n save_answer_tagging(data_type=1)\r\n save_answer_tagging(data_type=2)\r\n\r\n\r\n pass\r\n\r\n\r\n","sub_path":"Data/Preprocess/Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":19447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"384535942","text":"#Nombre: Alejandro Cadena\r\n#Correo: Dobleaduo@gmail.com\r\n# En un supermercado se hace una promoción mediante la cual el cliente obtiene un descuento dependiendo de un número que se escoge al azar. Si el número escogido \r\n# es menor que 74, se aplicará un descuento del 15% en relación al total de la compra, si es mayor e igual a 74 el descuento aplicado será del 20%. \r\n# Obtener cuanto dinero se le descuenta.\r\n\r\nnumero=int(input(\"Ingrese el numero obtenido \"))\r\ncompra=float(input(\"Ingrese el valor de la compra \"))\r\nif numero>=74:\r\n descuento=compra*0.2\r\n total=compra-descuento\r\n print(\"Felicidades ud obtuvo un descuento del 20% en su compra \",total)\r\nelse:\r\n Descuento=compra*0.15\r\n Total=compra-Descuento\r\n print(\"Felicidades ud obtuvo un descuento del 15% en su compra \",Total)","sub_path":"algoritmo26.py","file_name":"algoritmo26.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"265929131","text":"import unittest\nimport DataSet as ds\nimport numpy as np\n\n\nclass Testing(unittest.TestCase):\n\n def test_subset(self):\n print(\"TEST - DataSet - Creating Subset\")\n data_set_1 = np.array([['No', 'Sunny', 'Hot', 'High', 'Weak'],\n ['No', 'Sunny', 'Hot', 'High', 'Strong'],\n ['Yes', 'Overcast', 'Hot', 'High', 'Weak'],\n ['Yes', 'Rain', 'Mild', 'High', 'Weak'],\n ['Yes', 'Rain', 'Cool', 'Normal', 'Weak'],\n ['No', 'Rain', 'Cool', 'Normal', 'Strong'],\n ['Yes', 'Overcast', 'Cool', 'Normal', 'Strong'],\n ['No', 'Sunny', 'Mild', 'High', 'Weak'],\n ['Yes', 'Sunny', 'Cool', 'Normal', 'Weak'],\n ['Yes', 'Rain', 'Mild', 'Normal', 'Weak'],\n ['Yes', 'Sunny', 'Mild', 'Normal', 'Strong'],\n ['Yes', 'Overcast', 'Mild', 'High', 'Strong'],\n ['Yes', 'Overcast', 'Hot', 'Normal', 'Weak'],\n ['No', 'Rain', 'Mild', 'High', 'Strong']\n ])\n print('\\n DATASET')\n print(data_set_1)\n\n print('\\n LABELS')\n data_labels_1 = ['PlayTennis', 'Outlook', 'Temperature', 'Humidity', 'Wind']\n print(data_labels_1)\n\n dataset = ds.DataSet(data_set_1, data_labels_1)\n\n print('\\n TEST CASE 1')\n print('\\n Class: Outlook')\n print(' Value: Sunny')\n print('\\n\\n RESULT SUBSET')\n result = dataset.create_subset('Outlook', 'Sunny')\n print(result.data)\n print('\\n RESULT LABELS')\n print(result.labels)\n\n expected_labels = ['PlayTennis', 'Temperature', 'Humidity', 'Wind']\n expected_data = [['No', 'Hot', 'High', 'Weak'],\n ['No', 'Hot', 'High', 'Strong'],\n ['No', 'Mild', 'High', 'Weak'],\n ['Yes', 'Cool', 'Normal', 'Weak'],\n ['Yes', 'Mild', 'Normal', 'Strong']\n ]\n\n np.testing.assert_array_equal(expected_labels, result.labels)\n np.testing.assert_array_equal(expected_data, result.data)\n\n print('\\n TEST CASE 2')\n print('\\n Class: Humidity')\n print(' Value: High')\n print('\\n\\n RESULT SUBSET')\n result = dataset.create_subset('Humidity', 'High')\n print(result.data)\n print('\\n RESULT LABELS')\n print(result.labels)\n\n expected_labels = ['PlayTennis', 'Outlook', 'Temperature', 'Wind']\n expected_data = [['No', 'Sunny', 'Hot', 'Weak'],\n ['No', 'Sunny', 'Hot', 'Strong'],\n ['Yes', 'Overcast', 'Hot', 'Weak'],\n ['Yes', 'Rain', 'Mild', 'Weak'],\n ['No', 'Sunny', 'Mild', 'Weak'],\n ['Yes', 'Overcast', 'Mild', 'Strong'],\n ['No', 'Rain', 'Mild', 'Strong']\n ]\n\n np.testing.assert_array_equal(expected_labels, result.labels)\n np.testing.assert_array_equal(expected_data, result.data)\n\n print('\\n TEST CASE 3')\n print('\\n Class: Wind')\n print(' Value: NonExistant Value')\n print('\\n\\n RESULT SUBSET')\n result = dataset.create_subset('Wind', 'NonExistant')\n print(result.data)\n print('\\n RESULT LABELS')\n print(result.labels)\n\n expected_labels = ['PlayTennis', 'Outlook', 'Temperature', 'Humidity']\n expected_data = np.array([])\n\n np.testing.assert_array_equal(expected_labels, result.labels)\n self.assertEquals(expected_data.size, 0)\n\n print('\\n TEST CASE 4')\n print('\\n Class: NonExistant Class')\n print(' Value: N/A')\n print('\\n\\n RESULT SUBSET')\n with self.assertRaises(ValueError):\n dataset.create_subset('N/A', 'N/A')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"DataSetTest.py","file_name":"DataSetTest.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"136621474","text":"import numpy as np\nimport cv2\nimport imutils\nimport pytesseract\n\nimg = cv2.imread('14.jpg') # Read input image\n\n# Convert to hsv\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\ns = hsv[:, :, 1]\n\nret, thresh = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n# Find contours\ncnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncnts = imutils.grab_contours(cnts)\n\nc = max(cnts, key=cv2.contourArea)\nx, y, w, h = cv2.boundingRect(c)\nthresh_card = thresh[y:y+h, x:x+w].copy()\n\n# OCR\nresult = pytesseract.image_to_string(thresh_card)\nprint(f\"OCR Results:\\n {result}\")\n\n# Show image\ncv2.imshow('s', s)\ncv2.imshow('thresh', thresh)\ncv2.imshow('thresh_card', thresh_card)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"ocr-2.py","file_name":"ocr-2.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"270622212","text":"import fcntl\nimport json\nimport logging\nimport psycopg2\n\nfrom six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nfrom six.moves.socketserver import ThreadingMixIn\nfrom threading import Thread\n\nlogger = logging.getLogger(__name__)\n\n\nclass RestApiHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n response = self.get_postgresql_status()\n\n path = '/master' if self.path == '/' else self.path\n status_code = 200 if response['running'] and 'role' in response and response['role'] in path else 503\n\n self.send_response(status_code)\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n self.wfile.write(json.dumps(response).encode('utf-8'))\n\n def get_postgresql_status(self):\n try:\n row = self.server.query(\"\"\"SELECT to_char(pg_postmaster_start_time(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),\n pg_is_in_recovery(),\n CASE WHEN pg_is_in_recovery()\n THEN null\n ELSE pg_current_xlog_location() END,\n pg_last_xlog_receive_location(),\n pg_last_xlog_replay_location(),\n pg_is_in_recovery() AND pg_is_xlog_replay_paused()\"\"\")[0]\n return {\n 'running': True,\n 'postmaster_start_time': row[0],\n 'role': 'slave' if row[1] else 'master',\n 'xlog': ({\n 'received_location': row[3],\n 'replayed_location': row[4],\n 'paused': row[5]} if row[1] else {\n 'location': row[2]\n })\n }\n except (psycopg2.OperationalError, psycopg2.InterfaceError):\n logger.exception('get_postgresql_status')\n return {'running': self.server.patroni.postgresql.is_running()}\n\n\nclass RestApiServer(ThreadingMixIn, HTTPServer, Thread):\n\n def __init__(self, patroni, config):\n self.connection_string = 'http://{}/patroni'.format(config.get('connect_address', None) or config['listen'])\n host, port = config['listen'].split(':')\n HTTPServer.__init__(self, (host, int(port)), RestApiHandler)\n Thread.__init__(self, target=self.serve_forever)\n self._set_fd_cloexec(self.socket)\n self.patroni = patroni\n self.daemon = True\n\n def query(self, sql, *params):\n cursor = self.patroni.postgresql.connection().cursor()\n cursor.execute(sql, params)\n ret = [r for r in cursor]\n cursor.close()\n return ret\n\n @staticmethod\n def _set_fd_cloexec(fd):\n flags = fcntl.fcntl(fd, fcntl.F_GETFD)\n fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)\n","sub_path":"helpers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"443969612","text":"from django.conf import settings\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.template import loader\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import MailTemplate\n\n\ndef find_template(template_name):\n template, created = MailTemplate.objects.get_or_create(template_type=template_name, defaults={\n 'subject': get_subject(template_name),\n 'body': get_body(template_name)\n })\n\n return template\n\n\ndef get_subject(template_name):\n config = settings.MAIL_EDITOR_CONF\n\n template_config = config.get(template_name)\n if template_config:\n subject = template_config.get('subject_default')\n if subject:\n return subject\n\n return _('Please fix this template')\n\n\ndef get_body(template_name):\n config = settings.MAIL_EDITOR_CONF\n\n template_config = config.get(template_name)\n default = _('Your content here...')\n if template_config:\n body = template_config.get('body_default')\n if body:\n default = body\n\n template = loader.get_template('mail/_outer_table.html')\n current_site = get_current_site(None)\n return template.render({'domain': current_site.domain, 'default': mark_safe(default)}, None)\n","sub_path":"mail_editor/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"302213011","text":"# File Overlap\n\n\ndef read_to_list(file):\n a = []\n\n with open(file, \"r\") as f:\n data = f.readlines()\n for line in data:\n num = int(line.strip())\n a.append(num)\n\n return a\n\n\nif __name__ == '__main__':\n a1 = read_to_list(\"data/happynumbers.txt\")\n a2 = read_to_list(\"data/primenumbers.txt\")\n\n print(set(a1) & set(a2))\n","sub_path":"ex23.py","file_name":"ex23.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"38419400","text":"\"\"\"\nTests scikit-imputer converter.\n\"\"\"\nimport unittest\nimport numpy as np\nfrom sklearn.preprocessing import Imputer\nfrom onnxmltools import convert_sklearn\nfrom onnxmltools.convert.common.data_types import FloatTensorType, Int64TensorType\n\n\nclass TestSklearnImputerConverter(unittest.TestCase):\n\n def test_model_imputer(self):\n model = Imputer(missing_values='NaN', strategy='mean', axis=0)\n model.fit([[1, 2], [np.nan, 3], [7, 6]])\n model_onnx = convert_sklearn(model, 'scikit-learn imputer', [('input', Int64TensorType([1, 2]))])\n self.assertTrue(model_onnx is not None)\n\n def test_imputer_int_inputs(self):\n model = Imputer(missing_values='NaN', strategy='mean', axis=0)\n model.fit([[1, 2], [np.nan, 3], [7, 6]])\n\n model_onnx = convert_sklearn(model, 'scikit-learn imputer', [('input', Int64TensorType([1, 2]))])\n self.assertEqual(len(model_onnx.graph.node), 2)\n\n # Last node should be Imputer\n outputs = model_onnx.graph.output\n self.assertEqual(len(outputs), 1)\n\n self.assertEqual(outputs[0].type.tensor_type.shape.dim[-1].dim_value, 2)\n\n def test_imputer_float_inputs(self):\n model = Imputer(missing_values='NaN', strategy='mean', axis=0)\n model.fit([[1, 2], [np.nan, 3], [7, 6]])\n\n model_onnx = convert_sklearn(model, 'scikit-learn imputer', [('input', FloatTensorType([1, 2]))])\n self.assertTrue(model_onnx.graph.node is not None)\n\n # should contain only node\n self.assertEqual(len(model_onnx.graph.node), 1)\n\n # last node should contain the Imputer\n outputs = model_onnx.graph.output\n self.assertEqual(len(outputs), 1)\n self.assertEqual(outputs[0].type.tensor_type.shape.dim[-1].dim_value, 2)\n","sub_path":"tests/sklearn/test_ImputerConverter.py","file_name":"test_ImputerConverter.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477269142","text":"#---------------------------------------------#\n# Base Class #\n# -------------------------- #\n# start: 2020-06-26 #\n# -------------------------- #\n# #\n# Base(진영) class #\n#---------------------------------------------#\nimport sys\nsys.path.insert(0,'C:/Users/user/IndProj/Project-Game/Common')\nimport cmmlib\nimport pygame\nimport random\n#run 모듈의 screen을 global로 쓰고 싶지만 run에서 base import 하고 base에서 run import 하면 충돌일어나는 듯\n#screen은 초기화에서 매개변수로 받아오기\n\nscreen = cmmlib.screen\n\n#org_pos을 전역변수로 사용하기 위해 임시로 베이스 이미지 하나 꺼내서 사이즈 설정해줌\nbase_img = pygame.image.load('C:/Users/user/IndProj/Project-Game/Img/base1.PNG')\nbase_size = pygame.transform.scale(base_img,(int(screen.get_width()/15),int(screen.get_height()/12)))\n\n#기본 위치 -----> 11시 / 1시 / 5시 / 7시 (각 모퉁이)\norg_x_pos = [0,screen.get_width() - base_size.get_width()]\norg_y_pos = [0,screen.get_height() - base_size.get_height()]\n\n#기본 위치에서 랜덤으로 x좌표 y좌표 하나씩 얻어온 것을 pos으로 지정 (진영 위치 랜덤 생성)\norg_pos = [\n [org_x_pos[0],org_y_pos[0]],\n [org_x_pos[0],org_y_pos[1]],\n [org_x_pos[1],org_y_pos[0]],\n [org_x_pos[1],org_y_pos[1]]\n]\n\n#base는 HP와 고유의 랜덤 위치\n#base에 들어가야될 정보\n#너비 높이 / 팀 / 위치\nclass Base:\n def __init__(self,team):\n global screen\n #기본 베이스\n self.base_info = ['team','hp','pos']\n\n #진영에 따른 베이스 이미지 로드\n if team == 'Blue':\n blue_base = pygame.image.load('C:/Users/user/IndProj/Project-Game/Img/base1.PNG')\n #blue진영 이미지 resize (임시로 screen의 가로 15분의 1 / 세로 10분의 1크기)\n base_size = pygame.transform.scale(blue_base,(int(screen.get_width()/15),int(screen.get_height()/12)))\n elif team == 'Red':\n red_base = pygame.image.load('C:/Users/user/IndProj/Project-Game/Img/base2.PNG')\n #red진영 이미지 resize (임시로 screen의 가로 15분의 1 / 세로 10분의 1크기)\n base_size = pygame.transform.scale(red_base,(int(screen.get_width()/15),int(screen.get_height()/12)))\n\n\n global org_pos\n cur_pos = random.sample(org_pos,1)\n print('org_pos : ',org_pos)\n print('cur_pos : ',cur_pos)\n\n self.base_info[0] = team\n self.base_info[1] = 500\n self.base_info[2] = cur_pos\n\n #self.base_info[3]=size(type : surface) / self.base_info[2]=랜덤 위치(type : surface)에 삽입\n screen.blit(base_size, self.base_info[2][0])\n","sub_path":"GameRun/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"369001336","text":"def criar_faixa(musica,artista,album):\n faixa= {'musica':musica,'artista':artista,'album':album}\n return faixa\n\n\n\ndef salvar_faixa(faixa):\n arquivo= open('aula16/faixas.txt','a')\n arquivo.write(f'{faixa[\"musica\"]};{faixa[\"artista\"]};{faixa[\"album\"]}\\n')\n arquivo.close()\n\ndef ler_faixa():\n arquivo= open('aula16/faixas.txt','r')\n lista_faixa= []\n for linha in arquivo:\n linha= linha.strip()\n dados_faixa= linha.split(';')\n faixa= criar_faixa(dados_faixa[0],dados_faixa[1],dados_faixa[2])\n lista_faixa.append(faixa)\n arquivo.close()\n return lista_faixa\n \n\n\n","sub_path":"aula16/faixa.py","file_name":"faixa.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"153179957","text":"def check(A,H,W):\n for h in range(H):\n for w in range(W-1):\n if A[h][w] >= A[h][w+1]:\n return False\n for w in range(W):\n for h in range(H-1):\n if A[h][w] >= A[h+1][w]:\n return False\n return True\n\ndef solve():\n H,W = map(int,input().split())\n A = [list(map(int,input().split())) for i in range(H)]\n B = [list(map(int,input().split())) for i in range(H)]\n if check(A,H,W) and check(B,H,W):\n return 'Possible'\n for h in range(H):\n for w in range(W):\n if A[h][w] > B[h][w]:\n A[h][w], B[h][w] = B[h][w], A[h][w]\n if check(A,H,W) and check(B,H,W):\n return 'Possible'\n return 'Impossible'\n\nprint(solve())\n","sub_path":"codeforces/cr557_2/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"216852857","text":"# Copyright (c) SenseTime. All Rights Reserved.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nimport cv2\n# import cv2.cv2\nimport numpy as np\nfrom pysot.core.config import cfg\nfrom pysot.models.loss import select_cross_entropy_loss, select_iou_loss\nfrom pysot.models.backbone import get_backbone\nfrom pysot.models.head import get_ban_head\nfrom pysot.models.neck import get_neck\nfrom pysot.utils.misc import NestedTensor\nfrom pysot.models.head.trans_module import transmodule\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\nclass ModelBuilder(nn.Module):\n def __init__(self):\n super(ModelBuilder, self).__init__()\n\n # build backbone\n self.backbone = get_backbone(cfg.BACKBONE.TYPE,\n **cfg.BACKBONE.KWARGS)\n\n # build adjust layer\n if cfg.ADJUST.ADJUST:\n self.neck = get_neck(cfg.ADJUST.TYPE,\n **cfg.ADJUST.KWARGS)\n\n # build ban head\n if cfg.BAN.BAN:\n self.head = get_ban_head(cfg.BAN.TYPE,\n **cfg.BAN.KWARGS)\n\n self.trans_module = transmodule(256)\n self.nan_to_val = 1e-10, 1e-10\n\n\n def template(self, z):\n zf = self.backbone(z)\n if cfg.ADJUST.ADJUST:\n zf = self.neck(zf)\n self.zf = zf\n\n def track(self, x):\n xf = self.backbone(x)\n if cfg.ADJUST.ADJUST:\n xf = self.neck(xf)\n cls, loc = self.head(self.zf, xf)\n return {\n 'cls': cls,\n 'loc': loc\n }\n\n def log_softmax(self, cls):\n if cfg.BAN.BAN:\n cls = cls.permute(0, 2, 3, 1).contiguous()\n cls = F.log_softmax(cls, dim=3)\n return cls\n\n def forward(self, data, idx):\n \"\"\" only used in training\"\"\"\n template = data['template'].cuda()\n update = data['update'].cuda()\n search = data['search'].cuda()\n label_cls = data['label_cls'].cuda()\n label_loc = data['label_loc'].cuda()\n\n\n\n feat_t_list = self.backbone(template)\n feat_s_list = self.backbone(search)\n feat_u_list = self.backbone(update)\n\n if cfg.ADJUST.ADJUST:\n zf = self.neck(feat_t_list) # 3, 32,256,7,7\n xf = self.neck(feat_s_list) # 3, 32,256,31,31\n uf = self.neck(feat_u_list) # 3, 32,256,7,7\n\n update_f = []\n for i in range(len(zf)):\n if i == 0:\n out = self.trans_module(u=uf[i], z=zf[i])\n else:\n out = self.trans_module(u=uf[i], z=zf[i], pre_uf=update_f[i - 1])\n update_f.append(out)\n\n # get feature\n cls, loc = self.head(update_f, xf)\n cls_u, loc_u = self.head(uf, xf)\n\n cls_u = self.log_softmax(cls_u)\n cls_loss_u = select_cross_entropy_loss(cls_u, label_cls)\n loc_loss_u = select_iou_loss(loc_u, label_loc, label_cls)\n\n # get loss\n # cls loss with cross entropy loss # loc loss with iou loss\n cls_ = self.log_softmax(cls)\n cls_loss = select_cross_entropy_loss(cls_, label_cls)\n loc_loss = select_iou_loss(loc, label_loc, label_cls)\n\n outputs = {}\n outputs['total_loss'] = cfg.TRAIN.CLS_WEIGHT * cls_loss + cfg.TRAIN.LOC_WEIGHT * loc_loss \\\n + cfg.TRAIN.CLS_WEIGHT * cls_loss_u + cfg.TRAIN.LOC_WEIGHT * loc_loss_u\n outputs['cls_loss'] = cls_loss + cls_loss_u\n outputs['loc_loss'] = loc_loss + loc_loss_u\n\n return outputs\n","sub_path":"pysot/models/model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"340624331","text":"import numpy as np\nimport numpy.linalg as alg\n\n\ndef find_mod_inverse_matrix(input_matrix, mod):\n\tn = len(input_matrix)\n\tmatrix = np.matrix(input_matrix)\n\tadj = np.zeros(shape=(n, n))\n\tfor i in range(0, n):\n\t\tfor j in range(0, n):\n\t\t\tadj[i][j] = ((-1) ** (i + j) * int(round(alg.det(_get_co_factor(matrix, j, i))))) % mod\n\treturn (_mod_inv(int(round(alg.det(matrix))), mod) * adj) % mod\n\n\ndef _mod_inv(a, p):\n\tfor i in range(1, p):\n\t\tif (i * a) % p == 1:\n\t\t\treturn i\n\traise ValueError(str(a) + \" has no inverse mod \" + str(p))\n\n\ndef _get_co_factor(matrix, i, j):\n\tmatrix = np.array(matrix)\n\tminor = np.zeros(shape=(len(matrix) - 1, len(matrix) - 1))\n\tp = 0\n\tfor s in range(0, len(minor)):\n\t\tif p == i:\n\t\t\tp = p + 1\n\t\tq = 0\n\t\tfor t in range(0, len(minor)):\n\t\t\tif q == j:\n\t\t\t\tq = q + 1\n\t\t\tminor[s][t] = matrix[p][q]\n\t\t\tq = q + 1\n\t\tp = p + 1\n\treturn minor\n","sub_path":"DataProtection/util/matrix_inv.py","file_name":"matrix_inv.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"324177627","text":"\n\nfrom xai.brain.wordbase.nouns._birdcage import _BIRDCAGE\n\n#calss header\nclass _BIRDCAGES(_BIRDCAGE, ):\n\tdef __init__(self,): \n\t\t_BIRDCAGE.__init__(self)\n\t\tself.name = \"BIRDCAGES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"birdcage\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_birdcages.py","file_name":"_birdcages.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"69878527","text":"import os\nimport sys\nimport argparse\nimport matplotlib.pyplot as plt\n\ndef graph_field(file_name):\n \n infile = open(file_name+\".txt\", 'r')\n matrix = []\n temp = []\n temp_numb = []\n for word in infile:\n temp_numb.clear()\n temp = word.rstrip('\\n').split(':')\n for i in temp:\n temp_numb.append(float(i))\n matrix.append(temp_numb[:])\n \n plt.imshow(matrix, cmap='gray', interpolation='nearest')\n plt.show()\n \ndef main():\n \n # Create the parser to deal with the arguments\n parser = argparse.ArgumentParser(\"Plot room states\")\n \n # Set the positional arguments\n parser.add_argument('--RESLT_PATH', dest='RESLT_PATH', type=str, required=True, help='The path with the results')\n \n # parse args\n args = parser.parse_args()\n \n # RESLT folder\n RESLT = args.RESLT_PATH\n\n print(f\"Path to folder: {RESLT}\")\n \n graph_field(RESLT + \"staticField\")\n graph_field(RESLT + \"initialPosition\")\n graph_field(RESLT + \"finalPosition\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/field_grapher.py","file_name":"field_grapher.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"448437038","text":"# Owner(s): [\"oncall: distributed\"]\n\nimport sys\n\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed._sharded_tensor import (\n shard_parameter,\n)\nfrom torch.distributed._sharded_optim import (\n ShardedOptimizer,\n named_params_with_sharded_tensor,\n)\nfrom torch.testing._internal.common_distributed import (\n requires_nccl,\n skip_if_lt_x_gpu,\n)\nfrom torch.testing._internal.common_utils import (\n TEST_WITH_DEV_DBG_ASAN,\n run_tests,\n)\nfrom torch.testing._internal.distributed._sharded_tensor import (\n TEST_GPU_NUM,\n ShardedTensorTestBase,\n with_comms,\n)\nfrom torch.testing._internal.distributed._sharded_tensor._test_ops_common import (\n generate_chunk_sharding_specs_for_test,\n generate_local_weight_sharding_params_for_test,\n)\n\nif TEST_WITH_DEV_DBG_ASAN:\n print(\n \"Skip dev-asan as torch + multiprocessing spawn have known issues\",\n file=sys.stderr,\n )\n sys.exit(0)\n\n\nclass TestShardedTensorOpsLinear(ShardedTensorTestBase):\n def _run_sharded_linear(self, spec, input_size, linear_size, sharded_dim):\n # Use same seed.\n torch.manual_seed(0)\n local_linear = torch.nn.Linear(*linear_size).cuda(self.rank)\n\n sharded_linear = torch.nn.Linear(*linear_size)\n\n # Copy the weights and bias from local linear\n sharded_linear.weight = torch.nn.Parameter(local_linear.weight.detach().clone())\n sharded_linear.bias = torch.nn.Parameter(local_linear.bias.detach().clone())\n\n # Shard the parameter.\n shard_parameter(sharded_linear, \"weight\", spec)\n\n # Run sharded computation\n torch.manual_seed(self.rank) # inputs different on each rank\n inp = torch.rand(*input_size).cuda(self.rank)\n sharded_output = sharded_linear(inp)\n\n # Run local computation\n local_output = local_linear(inp)\n\n # Verify\n self.assertEqual(local_output, sharded_output)\n\n # Validate for torch.nn.functional.linear version.\n local_output = torch.nn.functional.linear(\n inp, local_linear.weight, local_linear.bias\n )\n sharded_output = torch.nn.functional.linear(\n inp, sharded_linear.weight, sharded_linear.bias\n )\n self.assertEqual(local_output, sharded_output)\n\n # Compute loss and run backward pass.\n local_output.sum().backward()\n sharded_output.sum().backward()\n local_grad = local_linear.weight.grad\n\n # Verify that both weight and bias in the sharded linear has non-None grad.\n sharded_weight = sharded_linear.weight.local_shards()[0].tensor\n self.assertNotEqual(sharded_linear.bias.grad, None)\n self.assertNotEqual(sharded_weight.grad, None)\n\n # Shard the local linear's weight grad so that we can compare.\n dist.all_reduce(local_grad)\n (start_pos, chunk_size) = generate_local_weight_sharding_params_for_test(\n local_linear.weight, sharded_dim, TEST_GPU_NUM, spec, self.rank\n )\n local_grad_narrowed = local_grad.narrow(sharded_dim, start_pos, chunk_size)\n\n # Test backward gradient calculation.\n self.assertEqual(sharded_linear.bias.grad, local_linear.bias.grad)\n self.assertEqual(sharded_weight.grad, local_grad_narrowed)\n\n # Test optimizer.\n previous = local_linear.weight.clone().detach()\n optim = torch.optim.SGD(local_linear.parameters(), lr=0.1)\n optim.step()\n self.assertNotEqual(previous, local_linear.weight)\n previous_sharded_weight = sharded_weight.clone()\n previous_sharded_bias = sharded_linear.bias.clone()\n sharded_optim = ShardedOptimizer(dict(named_params_with_sharded_tensor(sharded_linear)), torch.optim.SGD, lr=0.1)\n sharded_optim.step()\n sharded_weight = sharded_linear.weight.local_shards()[0].tensor\n local_weight_narrowed = local_linear.weight.narrow(\n sharded_dim, start_pos, chunk_size\n )\n self.assertEqual(sharded_weight.size(), local_weight_narrowed.size())\n self.assertNotEqual(previous_sharded_weight, sharded_weight)\n self.assertEqual(sharded_weight, local_weight_narrowed)\n self.assertNotEqual(previous_sharded_bias, sharded_linear.bias)\n self.assertEqual(sharded_linear.bias, local_linear.bias)\n\n @with_comms(init_rpc=False)\n @skip_if_lt_x_gpu(TEST_GPU_NUM)\n @requires_nccl()\n def test_sharded_linear_colwise(self):\n for spec in generate_chunk_sharding_specs_for_test(0):\n self._run_sharded_linear(spec, [2, 17], [17, 12], 0)\n self._run_sharded_linear(spec, [8, 21], [21, 11], 0)\n self._run_sharded_linear(spec, [7, 23], [23, 13], 0)\n self._run_sharded_linear(spec, [4, 15], [15, 14], 0)\n\n @with_comms(init_rpc=False)\n @skip_if_lt_x_gpu(TEST_GPU_NUM)\n @requires_nccl()\n def test_sharded_linear_rowwise(self):\n for spec in generate_chunk_sharding_specs_for_test(1):\n # Test even split.\n self._run_sharded_linear(spec, [8, 16], [16, 11], 1)\n\n # Test uneven split.\n self._run_sharded_linear(spec, [5, 19], [19, 11], 1)\n self._run_sharded_linear(spec, [10, 21], [21, 11], 1)\n\n\nif __name__ == \"__main__\":\n run_tests()\n","sub_path":"test/distributed/_sharded_tensor/ops/test_linear.py","file_name":"test_linear.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288474652","text":"# -*- coding: utf-8 -*-\n'''this code is to read latest yeastGEM, estabolish the gene-protein-reaction relation, then the protein information can be merged into this dataframe\nbased on the geneID mapping\n12th, Nov, 2018\nHongzhong Lu\n'''\n\n# Import packages\nimport pandas as pd\nimport os ##for directory\nfrom cobra.io import read_sbml_model\n\nos.chdir('/Users/luho/PycharmProjects/model/cobrapy/code')\n\n\n# import self function\ndef getRXNgeneMapping(rxn0, gpr0):\n '''this function is used to split the GPR;\n input, for example rxn0=['r1','g2']\n gpr0=['a or c','a and b']\n output, each rxn related with each gene'''\n s1 = rxn0\n s2 = gpr0\n s2 = s2.str.replace('and','@')\n s2 = s2.str.replace('or','@')\n s2 = s2.str.replace('\\\\( ','')\n s2 = s2.str.replace('\\\\(\\\\( ','')\n s2 = s2.str.replace('\\\\(', '')\n s2 = s2.str.replace('\\\\(\\\\(', '')\n s2 = s2.str.replace(' \\\\)','')\n s2 = s2.str.replace(' \\\\)\\\\) ','')\n s2 = s2.str.replace('\\\\)', '')\n s2 = s2.str.replace('\\\\)\\\\) ', '')\n s3 = splitAndCombine(s2,s1,sep0=\"@\")\n s3['V2'] = s3['V2'].str.strip()\n s3.columns = ['rxnID', 'gene']\n return s3\n\ndef correctSomeWrongFormat(model0):\n \"\"\"\n This function is used to correct some wrong format when read yeastGEM model from cobratoolbox\n \"\"\"\n # Correct metabolite ids:\n for met in model0.metabolites:\n met.id = met.id.replace('__91__', '_')\n met.id = met.id.replace('__93__', '')\n #for reaction in model0.reactions:\n # reaction.gene_reaction_rule = reaction.gene_reaction_rule.replace('__45__','-')\n for gene in model0.genes:\n gene.id = gene.id.replace('__45__', '-')\n\n return model0\n\n\n\ndef saveExcel(infile, outfile):\n '''\n function to save the dataframe into xlsx format\n :param infile:\n :param outfile:\n :return:\n '''\n writer = pd.ExcelWriter(outfile)\n infile.to_excel(writer,'Sheet1')\n writer.save()\n\n\n\n# input the subsystem information\ngem_dataframe = pd.read_excel('/Users/luho/PycharmProjects/model/model_correction/result/yeastGEM_with subsystem.xlsx')\n\n# input yeast8 for every update from yeastGEM repo\nGEM_nov = read_sbml_model('../data/yeastGEM_nov.xml')\nGEM_nov= correctSomeWrongFormat(GEM_nov)\n#produce the dataframe for the metabolites and the rxn\n\ngem_rxn_nov = produceRxnList(GEM_nov)\n\n\n#establish rxn-gene mapping\nproYeast_DataFrame = getRXNgeneMapping(gem_rxn_nov['rxnID'], gem_rxn_nov['GPR'])\nproYeast_DataFrame0 = pd.merge(proYeast_DataFrame, gem_rxn_nov, on='rxnID')\nsaveExcel(proYeast_DataFrame0, '../result/proYeast_DataFrame_from_yeastGEM_november.xlsx')\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"PDB parameter collection/Connection_between_yeastGEM_and_proYeastDB.py","file_name":"Connection_between_yeastGEM_and_proYeastDB.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"449352629","text":"\nclass Solution:\n res = 0\n leftmost_pos = {}\n def widthOfBinaryTree(self, root: TreeNode) -> int:\n global res,leftmost_pos\n res = 0\n leftmost_pos = {}\n Solution.maxWidth(self,root,0,0)\n return res\n \n\n def maxWidth(self,treeNode, depth,position):\n global res,leftmost_pos\n if treeNode is None:\n return\n\n if depth not in leftmost_pos:\n leftmost_pos[depth] = position\n\n res = max(res,position-leftmost_pos[depth]+1)\n Solution.maxWidth(self,treeNode.left,depth+1,position*2)\n Solution.maxWidth(self,treeNode.right,depth+1,position*2+1)","sub_path":"Challenges/2020/July Challenge/Week 2/2. Maximum Width of Binary Tree - (IMP).py","file_name":"2. Maximum Width of Binary Tree - (IMP).py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602204909","text":"\"\"\"\n Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this\n software and associated documentation files (the \"Software\"), to deal in the Software\n without restriction, including without limitation the rights to use, copy, modify,\n merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom cfnlint import CloudFormationLintRule\nfrom cfnlint import RuleMatch\n\n\nclass Policy(CloudFormationLintRule):\n \"\"\"Check if IAM Policy JSON is correct\"\"\"\n id = 'E2507'\n shortdesc = 'Check if IAM Policies are properly configured'\n description = 'See if there elements inside an IAM policy ' + \\\n 'are correct'\n tags = ['base', 'properties', 'iam']\n\n def _check_policy_document(self, branch, policy):\n \"\"\"Check policy document\"\"\"\n matches = list()\n\n valid_keys = [\n 'Version',\n 'Id',\n 'Statement',\n ]\n\n if not isinstance(policy, dict):\n message = \"IAM Policy Documents needs to be JSON\"\n matches.append(\n RuleMatch(branch[:], message))\n return matches\n\n for parent_key, parent_value in policy.items():\n if parent_key not in valid_keys:\n message = \"IAM Policy key %s doesn't exist.\" % (parent_key)\n matches.append(\n RuleMatch(branch[:] + [parent_key], message))\n if parent_key == 'Statement':\n if isinstance(parent_value, (list)):\n for index, statement in enumerate(parent_value):\n matches.extend(\n self._check_policy_statement(\n branch[:] + [parent_key, index],\n statement\n )\n )\n else:\n message = \"IAM Policy statement should be of list.\"\n matches.append(\n RuleMatch(branch[:] + [parent_key], message))\n return matches\n\n def _check_policy_statement(self, branch, statement):\n \"\"\"Check statements\"\"\"\n matches = list()\n statement_valid_keys = [\n 'Effect',\n 'Principal',\n 'NotPrincipal',\n 'Action',\n 'NotAction',\n 'Resource',\n 'NotResource',\n 'Condition',\n 'Sid',\n ]\n\n for key, _ in statement.items():\n if key not in statement_valid_keys:\n message = \"IAM Policy statement key %s isn't valid\" % (key)\n matches.append(\n RuleMatch(branch[:] + [key], message))\n if 'Effect' not in statement:\n message = \"IAM Policy statement missing Effect\"\n matches.append(\n RuleMatch(branch[:], message))\n else:\n effect = statement.get('Effect')\n if effect not in ['Allow', 'Deny']:\n message = \"IAM Policy Effect should be Allow or Deny\"\n matches.append(\n RuleMatch(branch[:] + ['Effect'], message))\n if 'Action' not in statement and 'NotAction' not in statement:\n message = \"IAM Policy statement missing Action or NotAction\"\n matches.append(\n RuleMatch(branch[:], message))\n if 'Principal' in statement:\n message = \"IAM Policy statement shouldn't have Principal\"\n matches.append(\n RuleMatch(branch[:] + ['Principal'], message))\n if 'NotPrincipal' in statement:\n message = \"IAM Policy statement shouldn't have NotPrincipal\"\n matches.append(\n RuleMatch(branch[:] + ['NotPrincipal'], message))\n if 'Resource' not in statement and 'NotResource' not in statement:\n message = \"IAM Policy statement missing Resource or NotResource\"\n matches.append(\n RuleMatch(branch[:], message))\n\n return(matches)\n\n def _check_policy(self, branch, policy):\n \"\"\"Checks a policy\"\"\"\n matches = list()\n policy_document = policy.get('PolicyDocument', {})\n matches.extend(\n self._check_policy_document(\n branch + ['PolicyDocument'], policy_document))\n\n return matches\n\n def match(self, cfn):\n \"\"\"Check IAM Policies Properties\"\"\"\n\n matches = list()\n\n iam_types = [\n 'AWS::IAM::Group',\n 'AWS::IAM::ManagedPolicy',\n 'AWS::IAM::Policy',\n 'AWS::IAM::Role',\n 'AWS::IAM::User',\n ]\n\n resources = cfn.get_resources(iam_types)\n for resource_name, resource_values in resources.items():\n tree = ['Resources', resource_name, 'Properties']\n properties = resource_values.get('Properties', {})\n if properties:\n policy_document = properties.get('PolicyDocument', None)\n if policy_document:\n matches.extend(\n self._check_policy_document(\n tree[:] + ['PolicyDocument'], policy_document))\n policy_documents = properties.get('Policies', [])\n for index, policy_document in enumerate(policy_documents):\n matches.extend(\n self._check_policy(\n tree[:] + ['Policies', index],\n policy_document))\n\n return matches\n","sub_path":"src/cfnlint/rules/resources/iam/Policy.py","file_name":"Policy.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"206897931","text":"#\n# Author: Kris Swann\n#\n\nclass Zillion:\n \"\"\"\n A class which represents an unbounded positive number by using a list.\n\n Attributes:\n list - A list where each element represents a single digit in an element.\n Initialized to []. Leading 0's are not trimmed.\n Ex. 12345 would be implemented as [1, 2, 3, 4, 5].\n Ex. 01242 would be implemented as [0, 1, 2, 4, 2].\n \"\"\"\n list = []\n\n\n def __init__(self, digits):\n \"\"\"\n Create a Zillion object with the arg digits. Commas and Spaces will be ignored.\n Will remove leading 0's.\n\n Args:\n digits - The string of the number which the Zillion object is created with.\n Can contain spaces, digits or commas. Must be a non-empty string\n and contain at least one digit. If any of these conditions are\n not met, will throw a RuntimeError.\n \"\"\"\n\n # Create sublists of digits & spaces and commas.\n self.list = [int(char) for char in digits if char in map(str, list(range(0, 10)))]\n allowed_extras = [char for char in digits if char == ' ' or char == ',']\n\n # If there were no digits or if there were extra chars that were not digits\n # or spaces or commas, throw an error.\n if self.list == [] or len(digits) > len(self.list) + len(allowed_extras):\n raise RuntimeError\n\n # Remove leading 0's\n # while self.list[0] == 0 and len(self.list) > 1:\n # self.list = self.list[1:]\n\n\n def increment(self):\n \"\"\"\n Increments the number zillion represents by 1. (Works with leading 0's.)\n \"\"\"\n for index in range(len(self.list) - 1, -1, -1):\n if self.list[index] == 9:\n self.list[index] = 0\n else: # The base case.\n self.list[index] += 1\n return None # Exit before hitting next case.\n\n # If no base case was reached, add an additional digit place to the front of\n # the list.\n self.list = [1] + self.list\n\n\n def isZero(self):\n \"\"\"\n Returns if the number that Zillion represents is 0. (Works with Leading 0's.)\n \"\"\"\n return self.list.count(0) == len(self.list)\n\n\n def toString(self):\n response = ''\n for digit in self.list:\n response += str(digit)\n return response\n\n\n\n\n\n#\n# TESTS\n#\ncases = ['', ',, ', '-19224', '9sPfrJj0t9', '343 53 j', '{89489}', 'p', ',,,', ' ',\n '0', '000', '12345', '132 32 23 44', '132,43902,00', '129320,', '341348 ',\n ',13342 ', '9', '999', '99999999999999999999999']\n\nfor case in cases:\n try:\n z = Zillion(case)\n print('toString: ' + z.toString())\n print('\\tisZero: ' + str(z.isZero()))\n z.increment()\n print('\\tincremented by 1: ' + z.toString())\n z.increment()\n print('\\tincremented by 2: ' + z.toString())\n except:\n print('Error')\n\n\n\n\n\n#\n# RESULTS\n#\n# Error\n# Error\n# Error\n# Error\n# Error\n# Error\n# Error\n# Error\n# Error\n# toString: 0\n# \tisZero: True\n# \tincremented by 1: 1\n# \tincremented by 2: 2\n# toString: 000\n# \tisZero: True\n# \tincremented by 1: 001\n# \tincremented by 2: 002\n# toString: 12345\n# \tisZero: False\n# \tincremented by 1: 12346\n# \tincremented by 2: 12347\n# toString: 132322344\n# \tisZero: False\n# \tincremented by 1: 132322345\n# \tincremented by 2: 132322346\n# toString: 1324390200\n# \tisZero: False\n# \tincremented by 1: 1324390201\n# \tincremented by 2: 1324390202\n# toString: 129320\n# \tisZero: False\n# \tincremented by 1: 129321\n# \tincremented by 2: 129322\n# toString: 341348\n# \tisZero: False\n# \tincremented by 1: 341349\n# \tincremented by 2: 341350\n# toString: 13342\n# \tisZero: False\n# \tincremented by 1: 13343\n# \tincremented by 2: 13344\n# toString: 9\n# \tisZero: False\n# \tincremented by 1: 10\n# \tincremented by 2: 11\n# toString: 999\n# \tisZero: False\n# \tincremented by 1: 1000\n# \tincremented by 2: 1001\n# toString: 99999999999999999999999\n# \tisZero: False\n# \tincremented by 1: 100000000000000000000000\n# \tincremented by 2: 100000000000000000000001\n","sub_path":"Lab02/lab_02.py","file_name":"lab_02.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"353266867","text":"# coding=gbk\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk,ImageEnhance,ImageFilter,ImageChops\r\nfrom tkinter import filedialog,font,messagebox\r\nimport numpy as np\r\nimport random\r\nimport math\r\nimport cv2,os\r\n\r\nmaster=Tk()\r\nmaster.title('图像数据增强系统v1.0')\r\nw1=Frame(height=50,width=50,bg='dark grey')\r\nw2=Frame(height=50,width=50,bg='dark grey')\r\nw5=Frame(height=450,width=520,bg='dark grey')\r\nw6=Frame(height=450,width=520,bg='dark grey')\r\n\r\n#利用padx和pady,可以将框架边界区分开\r\nw5.grid(row=0,column=0,columnspan=2, rowspan=3,padx=5, pady=5,sticky=E+S+N+W)\r\nw6.grid(row=0,column=2,columnspan=2, rowspan=3,padx=5, pady=5,sticky=E+S+N+W)\r\nw1.grid(row=3,column=0,columnspan=2, rowspan=3,padx=16, pady=45,sticky=E+S+N+W)\r\nw2.grid(row=3,column=2,columnspan=2, rowspan=3,padx=16, pady=45,sticky=E+S+N+W)\r\nt1=Text(w1,bg='gray')\r\nt2=Text(w2,bg='gray')\r\nt5=Text(w5,bg='gray')\r\nt6=Text(w6,bg='gray')\r\n\r\nt1.grid(padx=2, pady=3)\r\nt2.grid(padx=2, pady=3)\r\nt5.grid(padx=2, pady=3)\r\nt6.grid(padx=2, pady=3)\r\n\r\n# //////////////创建菜单项//////////////\r\nmenubar=Menu(t1)\r\nfmenu1=Menu(t1,tearoff=0)\r\nfmenu1.add_command(label=\"新建\",accelerator='Ctrl+N')\r\nfmenu1.add_separator()# 在两个菜单选项中间添加一条横线\r\nfmenu1.add_command(label=\"打开\",accelerator='Ctrl+O')\r\nfmenu1.add_separator()\r\nfmenu1.add_command(label=\"保存\",accelerator='Ctrl+S')\r\nfmenu1.add_separator()\r\nfmenu1.add_command(label=\"另存为\",accelerator='Alt+F2')\r\nfmenu1.add_separator()\r\nfmenu1.add_command(label=\"退出\",accelerator='Exit')\r\n\r\nfmenu2=Menu(t1,tearoff=0)\r\nfmenu2.add_command(label=\"复制\",accelerator='Ctrl+C')\r\nfmenu2.add_separator()# 在两个菜单选项中间添加一条横线\r\nfmenu2.add_command(label=\"粘贴\",accelerator='Ctrl+复制')\r\nfmenu2.add_separator()\r\nfmenu2.add_command(label=\"剪切\",accelerator='Ctrl+S')\r\nfmenu2.add_separator()\r\nfmenu2.add_command(label=\"全选\",accelerator='Ctrl+A')\r\n\r\nfmenu3=Menu(t1,tearoff=0)\r\nfor item in ['工具栏','状态栏','列表','详细信息']:\r\n fmenu3.add_command(label=item)\r\n fmenu3.add_separator()\r\n\r\nfmenu4=Menu(t1,tearoff=0)\r\nfor item in ['放大','缩小']:\r\n fmenu4.add_command(label=item)\r\n fmenu4.add_separator()\r\n\r\nfmenu5=Menu(t1,tearoff=0)\r\nfor item in ['关于']:\r\n fmenu5.add_command(label=item)\r\n fmenu5.add_separator()\r\n\r\nmenubar.add_cascade(label=\"文件\",menu=fmenu1)\r\nmenubar.add_cascade(label=\"编辑\",menu=fmenu2)\r\nmenubar.add_cascade(label=\"查看\",menu=fmenu3)\r\nmenubar.add_cascade(label=\"工具\",menu=fmenu4)\r\nmenubar.add_cascade(label=\"帮助\",menu=fmenu5)\r\nmenubar.configure(font='Times, 8')\r\nmaster['menu']=menubar\r\n\r\nlabel_txt1 = Label(t5, height='2', text=\"原始图像\",font = \"Helvetica 15 bold\").grid(row=1, column=6, columnspan=2, rowspan=3, padx=5, pady=3, sticky=E + S + N + W)\r\nlabel_txt1 = Label(t6, height='2', text=\"数据增强后的图像\",font = \"Helvetica 15 bold\").grid(row=1, column=6, columnspan=2, rowspan=3, padx=5, pady=3, sticky=E + S + N + W)\r\n\r\n# button_upload_photo1 = Button(t1, text='选择需要增强的图像',font = \"Helvetica 15 bold\", height='2', width='38')\r\n# button_upload_photo1.grid(row=0, column=1, sticky=S, padx=10, pady=3)\r\n\r\n\r\npy = Button(t1, text='平移',font = \"Helvetica 15 bold\", height='1', width='11')\r\npy.grid(row=0, column=0, sticky=S, padx=10, pady=3)\r\n\r\nxzh = Button(t1, text='镜像',font = \"Helvetica 15 bold\", height='1', width='11')\r\nxzh.grid(row=0, column=1, sticky=S, padx=10, pady=3)\r\n\r\nmh = Button(t1, text='模糊',font = \"Helvetica 15 bold\", height='1', width='11')\r\nmh.grid(row=0, column=2, sticky=S, padx=10, pady=3)\r\n\r\nshb = Button(t2, text='颜色抖动',font = \"Helvetica 15 bold\", height='1', width='11')\r\nshb.grid(row=1, column=0, sticky=S, padx=10, pady=3)\r\n\r\nhd = Button(t2, text='灰度拉伸',font = \"Helvetica 15 bold\", height='1', width='11')\r\nhd.grid(row=1, column=1, sticky=S, padx=10, pady=3)\r\n\r\ncc = Button(t2, text='随机擦除',font = \"Helvetica 15 bold\", height='1', width='11')\r\ncc.grid(row=1, column=2, sticky=S, padx=10, pady=3)\r\n\r\ndef RandomErasing(img):\r\n probability = 1\r\n sl = 0.02\r\n sh = 0.4\r\n r1 = 0.3\r\n mean = [0.4914, 0.4822, 0.4465]\r\n\r\n if random.uniform(0, 1) > probability:\r\n return img\r\n\r\n for attempt in range(100):\r\n area = img.size[0] * img.size[1]\r\n target_area = random.uniform(sl, sh) * area\r\n aspect_ratio = random.uniform(r1, 1 / r1)\r\n\r\n h = int(round(0.8*math.sqrt(target_area * aspect_ratio)))\r\n w = int(round(0.8*math.sqrt(target_area / aspect_ratio)))\r\n\r\n if w < img.size[1] and h < img.size[0]:\r\n x1 = random.randint(0, img.size[0] - h)\r\n y1 = random.randint(0, img.size[1] - w)\r\n img = np.array(img)\r\n if img.shape[2] == 3:\r\n img[x1:x1 + h, y1:y1 + w,0] = mean[0]\r\n img[x1:x1 + h, y1:y1 + w,1] = mean[1]\r\n img[x1:x1 + h, y1:y1 + w,2] = mean[2]\r\n else:\r\n img[ x1:x1 + h, y1:y1 + w,0] = mean[0]\r\n return Image.fromarray(np.uint8(img))\r\n return img\r\n\r\ndef one_image_upload():\r\n # global fname\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n return im\r\n\r\ndef fpy():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n out = ImageChops.offset(im,150,150)\r\n showImg_detect(out)\r\n\r\ndef fxzh():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n # out = im.rotate(25) # 逆时针旋转45度\r\n out = im.transpose(Image.FLIP_LEFT_RIGHT)\r\n # region = region.transpose(Image.ROTATE_180)\r\n showImg_detect(out)\r\n\r\ndef fmh():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n out = im.filter(ImageFilter.BLUR)\r\n showImg_detect(out)\r\n\r\ndef fshb():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n random_factor = np.random.randint(0, 31) / 10. # 随机因子\r\n color_image = ImageEnhance.Color(im).enhance(random_factor) # 调整图像的饱和度\r\n random_factor = np.random.randint(10, 21) / 10. # 随机因子\r\n brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # 调整图像的亮度\r\n random_factor = np.random.randint(10, 21) / 10. # 随机因1子\r\n contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # 调整图像对比度\r\n random_factor = np.random.randint(0, 31) / 10. # 随机因子\r\n out = ImageEnhance.Sharpness(contrast_image).enhance(random_factor)\r\n showImg_detect(out)\r\n\r\ndef fhd():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n out = im.point(lambda i: i * 1.5)\r\n showImg_detect(out)\r\n\r\ndef fcc():\r\n name_ = filedialog.askopenfilename()\r\n if name_ != '':\r\n fname = name_\r\n # print(fname)\r\n im = Image.open(fname)\r\n showImg_yuan(im)\r\n out = RandomErasing(im)\r\n\r\n showImg_detect(out)\r\n\r\ndef showImg_yuan(im):\r\n im = im.resize((500, 350), Image.ANTIALIAS)\r\n photo = ImageTk.PhotoImage(im)\r\n label = Label(t5, image=photo)\r\n label.image = photo\r\n label.grid(row=4, column=6, columnspan=2, rowspan=3, padx=5, pady=5, sticky=E + S + N + W)\r\n\r\ndef showImg_detect(im):\r\n im = im.resize((500, 350), Image.ANTIALIAS)\r\n photo = ImageTk.PhotoImage(im)\r\n label = Label(t6, image=photo)\r\n label.image = photo\r\n label.grid(row=4, column=6, columnspan=2, rowspan=3, padx=5, pady=5, sticky=E + S + N + W)\r\n\r\nif __name__ == '__main__':\r\n\r\n global fname,fname1,fname2\r\n fname2 = 'm.jpg'\r\n im = Image.open(fname2)\r\n showImg_yuan(im)\r\n fname1 = 'h.jpg'\r\n im1 = Image.open(fname1)\r\n showImg_detect(im1)\r\n py['command'] = fpy\r\n xzh['command'] = fxzh\r\n mh['command'] = fmh\r\n shb['command'] = fshb\r\n hd['command'] = fhd\r\n cc['command'] = fcc\r\n\r\n master.mainloop()\r\n","sub_path":"gui_datagenerator.py","file_name":"gui_datagenerator.py","file_ext":"py","file_size_in_byte":8368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"143512898","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n p1 = p2 = ListNode(-1) # ues sentinel, so that p1 ends up at the tail and generalizes head = None case\n p1.next = head\n while p2 and p2.next and p2.next.next:\n p1 = p1.next\n p2 = p2.next.next\n # p2 will arrive at either the last node or the last but one node\n head2 = p1.next.next if p2.next else p1.next\n p1.next = None\n head2 = self.reverseList(head2)\n p1, p2 = head, head2\n while p1 and p2:\n if p1.val != p2.val:\n return False\n p1 = p1.next\n p2 = p2.next\n return True\n\n def reverseList(self, head):\n if not head: return None\n p0 = senti = ListNode(-1)\n p1 = p0.next = head\n while p1:\n p2 = p1.next\n p1.next = p0\n p0 = p1\n p1 = p2\n senti.next = None # end last node of reversed list\n return p0","sub_path":"palindrome_linked_list/prac.py","file_name":"prac.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"73323325","text":"#!/usr/bin/env py_kp\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/12 14:22\n# @Author : song\n# @File : ckpt_pd.py\n\n\nimport tensorflow as tf\nimport pickle\nfrom model.text_cnn import TextCnn\nfrom classification.data_helper import *\n\nconfig = {\n 'n_class': 2,\n 'embed_size': 128,\n 'kernel_size': [3, 4, 5],\n 'n_filters': 50,\n 'top_k': 1,\n 'lr': 1e-3\n}\nif __name__ == '__main__':\n\n # =============================to pd===================================#\n\n ckpt_dir = \"./output/ckpt\"\n word_id = pickle.load(open(\"./word_id.pkl\", 'rb'))\n\n config['vocab_size'] = len(word_id)\n with tf.Session() as sess:\n model = TextCnn(**config)\n cpkt = tf.train.get_checkpoint_state(ckpt_dir)\n if cpkt and cpkt.model_checkpoint_path:\n print(cpkt.model_checkpoint_path)\n model.saver.restore(sess, cpkt.model_checkpoint_path)\n\n constant_graph = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,\n ['acc/pred', \"fc/logits/BiasAdd\"])\n\n # 写入序列化的 PB 文件\n with tf.gfile.FastGFile(\"./output/pd/\" + 'txt_clf.pb', mode='wb') as f:\n f.write(constant_graph.SerializeToString())\n #\n # =============================predict===================================#\n\n sess = tf.Session()\n with tf.gfile.FastGFile(\"./output/pd/\" + 'txt_clf.pb', 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n sess.graph.as_default()\n tf.import_graph_def(graph_def, name='') # 导入计算图\n\n # 需要有一个初始化的过程\n sess.run(tf.global_variables_initializer())\n\n # 输入\n input_x = sess.graph.get_tensor_by_name('input_x:0')\n\n pred = sess.graph.get_tensor_by_name('acc/pred:0')\n BiasAdd = sess.graph.get_tensor_by_name('fc/logits/BiasAdd:0')\n\n content = \"超级好的卖家!之前不小心拍错了,客服非常耐心的帮我解答问题,快递也非常给力,必须赞!!!\"\n\n cut = ' '.join(list(content))\n\n sent = [get_x(cut, word_id, max_len=50)]\n\n pred, BiasAdd = sess.run([pred, BiasAdd], feed_dict={input_x: sent})\n print(pred)\n print(BiasAdd)\n","sub_path":"nlp_prj/app/classification/ckpt_pd.py","file_name":"ckpt_pd.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"604460785","text":"import csv\nimport numpy as np\nimport statsmodels.api as sm\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import average_precision_score\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import plot_precision_recall_curve\n\n# Logistic regression code for real-world credit card data\n# iterations - controls the number of models fit\n# APs - stores the AP scores\n#\n# Additionally, generates historgrams of AP scores\n\niterations = 30\nAPs = np.zeros((iterations, 2))\n\nresult = pd.read_csv(\"creditcard.csv\")\nY = result.values[:, -1].astype(int)\nTime = result.values[:, 0].astype(int)\nX = result.values[:, 1:-1]\n\nfor i in range(iterations):\n print(i)\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)\n lr = LogisticRegression(max_iter = 2000)\n lr.fit(X_train, y_train)\n # Uncomment to plot PR curve\n# disp = plot_precision_recall_curve(clf, X_test, y_test)\n# plt.show()\n APs[i, 0] = average_precision_score(y_train, lr.predict(X_train))\n APs[i, 1] = average_precision_score(y_test, lr.predict(X_test))\n\nprint(APs)\nprint(np.mean(APs, axis=0))\nprint(np.std(APs, axis=0))\n\nfig, ((ax0), (ax1)) = plt.subplots(nrows=1, ncols=2)\nax0.title.set_text('AP of Logistic Regression on training data')\nax1.title.set_text('AP of Logistic Regression on testing data')\nax0.hist(APs[:,0], alpha=.8, edgecolor='blue')\nax1.hist(APs[:,1], alpha=.8, edgecolor='red')\nplt.show()\n","sub_path":"Project/Logistic.py","file_name":"Logistic.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"401632384","text":"\"\"\"\n-------------------------------------------------------------------------------\nMODULE\n acs_funding_portfolio_report\n\nDESCRIPTION\n Purpose : Interdesk funding\n Department and Desk : ACS Post Trade Services\n Requester : Jennitha Jugnath and Martin Wortmann\n Developer : Jakub Tomaga\n\nHISTORY\n===============================================================================\nDate CR number Developer Description\n-------------------------------------------------------------------------------\n2019-04-17 CHG1001639975 Jakub Tomaga Initial implementation.\n\"\"\"\n\nimport os\nimport logging\nimport acm\nfrom at_logging import getLogger\nfrom at_ael_variables import AelVariableHandler\nfrom at_report import CSVReportCreator\n\n\n# Logging\nLOGGER = getLogger(__name__)\nLOGGER.setLevel(logging.DEBUG)\nVERSION = \"1.0\"\n\n\nclass ACSFundingPortfolioReport(CSVReportCreator):\n \"\"\"Report displaying portfolio level.\"\"\"\n def __init__(self, full_file_path, compound):\n self.compound = compound\n # Split full path into individual parameters of the parent class.\n file_name_only, file_suffix = os.path.splitext(full_file_path)\n # Remove a dot from the extension\n file_suffix = file_suffix[1:]\n file_path = os.path.dirname(full_file_path)\n super(ACSFundingPortfolioReport, self).__init__(\n file_name_only,\n file_suffix,\n file_path)\n\n def _collect_data(self):\n \"\"\"Collect data relevant for the report.\"\"\"\n for portfolio in self.compound.AllPhysicalPortfolios():\n row = [\n portfolio.Oid(),\n portfolio.Name(),\n portfolio.AdditionalInfo().Prt_BDA_AccountNum(),\n portfolio.AdditionalInfo().CostCenter(),\n portfolio.AdditionalInfo().FundingIndicator()\n ]\n self.content.append(row)\n\n def _header(self):\n \"\"\"Return columns of the header.\"\"\"\n header = [\n \"Portfolio Number\",\n \"Portfolio Name\",\n \"prt_BDA AccountNum\",\n \"CostCenter\",\n \"FundingIndicator\"\n ]\n return header\n\n\nael_variables = AelVariableHandler()\nael_variables.add(\"output_file\",\n label=\"Output file\")\nael_variables.add(\"compound\",\n label=\"Compound portfolio\",\n cls=acm.FCompoundPortfolio,\n default=acm.FCompoundPortfolio[\"ABSA CAPITAL SECURITIES\"])\n\n\ndef ael_main(config):\n \"\"\"Entry point of the script.\"\"\"\n compound = config[\"compound\"]\n output_file = config[\"output_file\"]\n \n # Generate the report\n report = ACSFundingPortfolioReport(output_file, compound)\n try:\n report.create_report()\n LOGGER.info(\"Secondary output wrote to %s\", output_file)\n except Exception as ex:\n LOGGER.exception(\"Failed to generate the report %s\", ex)\n raise ex\n","sub_path":"Python modules/acs_funding_portfolio_report.py","file_name":"acs_funding_portfolio_report.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"550108966","text":"# Set of possible knight moves\npossible_moves = [(-2, -1), (-2, 1),\n (-1, -2), (-1, 2),\n (1, -2), (1, 2),\n (2, -1), (2, 1)]\n\nN = int(input())\n\nb = []\n\nempty = \".\"\nblocked = \"#\"\nknight = \"K\"\n\nfor x in range(N):\n b.append(input())\n\noriginal_board = []\n\nfor row in range(N):\n index = []\n\n for col in range(N):\n # Gets the position of the knight\n if b[row][col] == knight:\n starting_position = (row, col)\n\n # Appends the string at the spot to the index's array\n index.append(b[row][col])\n\n # Appends the index row to the original board\n original_board.append(index)\n\nprint(starting_position)\n","sub_path":"February 6/Knight_Jump_1.01.py","file_name":"Knight_Jump_1.01.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"594509818","text":"import numpy as np\nimport eagerpy as ep\nfrom functools import partial\n\nfrom ..utils import flatten\nfrom ..utils import atleast_kd\n\n\nclass L2CarliniWagnerAttack:\n \"Carlini Wagner L2 Attack\"\n\n def __init__(self, model):\n self.model = model\n\n def __call__(\n self,\n inputs,\n labels,\n *,\n target_classes=None,\n binary_search_steps=9,\n max_iterations=10000,\n confidence=0,\n learning_rate=1e-2,\n initial_const=1e-3,\n abort_early=True,\n ):\n x = ep.astensor(inputs)\n N = len(x)\n\n targeted = target_classes is not None\n if targeted:\n labels = None\n target_classes = ep.astensor(target_classes)\n assert target_classes.shape == (N,)\n is_adv = partial(\n targeted_is_adv, target_classes=target_classes, confidence=confidence\n )\n else:\n labels = ep.astensor(labels)\n assert labels.shape == (N,)\n is_adv = partial(untargeted_is_adv, labels=labels, confidence=confidence)\n\n bounds = self.model.bounds()\n to_attack_space = partial(_to_attack_space, bounds=bounds)\n to_model_space = partial(_to_model_space, bounds=bounds)\n\n x_attack = to_attack_space(x)\n reconstsructed_x = to_model_space(x_attack)\n\n rows = np.arange(N)\n\n def loss_fun(delta: ep.Tensor, consts: ep.Tensor) -> ep.Tensor:\n assert delta.shape == x_attack.shape\n assert consts.shape == (N,)\n\n x = to_model_space(x_attack + delta)\n logits = ep.astensor(self.model.forward(x.tensor))\n\n if targeted:\n c_minimize = best_other_classes(logits, target_classes)\n c_maximize = target_classes\n else:\n c_minimize = labels\n c_maximize = best_other_classes(logits, labels)\n\n is_adv_loss = logits[rows, c_minimize] - logits[rows, c_maximize]\n assert is_adv_loss.shape == (N,)\n is_adv_loss = is_adv_loss + confidence\n is_adv_loss = ep.maximum(0, is_adv_loss)\n is_adv_loss = is_adv_loss * consts\n\n squared_norms = flatten(x - reconstsructed_x).square().sum(axis=-1)\n loss = is_adv_loss.sum() + squared_norms.sum()\n return loss, (x, logits)\n\n loss_aux_and_grad = ep.value_and_grad_fn(x, loss_fun, has_aux=True)\n\n consts = initial_const * np.ones((N,))\n lower_bounds = np.zeros((N,))\n upper_bounds = np.inf * np.ones((N,))\n\n best_advs = ep.zeros_like(x)\n best_advs_norms = ep.ones(x, (N,)) * np.inf\n\n # the binary search searches for the smallest consts that produce adversarials\n for binary_search_step in range(binary_search_steps):\n if (\n binary_search_step == binary_search_steps - 1\n and binary_search_steps >= 10\n ):\n # in the last iteration, repeat the search once\n consts = np.minimum(upper_bounds, 1e10)\n\n # create a new optimizer find the delta that minimizes the loss\n delta = ep.zeros_like(x_attack)\n optimizer = AdamOptimizer(delta)\n\n found_advs = np.full(\n (N,), fill_value=False\n ) # found adv with the current consts\n loss_at_previous_check = np.inf\n\n consts_ = ep.from_numpy(x, consts.astype(np.float32))\n\n for iteration in range(max_iterations):\n loss, (perturbed, logits), gradient = loss_aux_and_grad(delta, consts_)\n delta += optimizer(gradient, learning_rate)\n\n if abort_early and iteration % (np.ceil(max_iterations / 10)) == 0:\n # after each tenth of the iterations, check progress\n if not (loss <= 0.9999 * loss_at_previous_check):\n break # stop Adam if there has been no progress\n loss_at_previous_check = loss\n\n found_advs_iter = is_adv(logits)\n found_advs = np.logical_or(found_advs, found_advs_iter.numpy())\n\n norms = flatten(perturbed - x).square().sum(axis=-1).sqrt()\n closer = norms < best_advs_norms\n new_best = closer.float32() * found_advs_iter.float32()\n\n best_advs = (\n atleast_kd(new_best, best_advs.ndim) * perturbed\n + (1 - atleast_kd(new_best, best_advs.ndim)) * best_advs\n )\n best_advs_norms = new_best * norms + (1 - new_best) * best_advs_norms\n\n upper_bounds = np.where(found_advs, consts, upper_bounds)\n lower_bounds = np.where(found_advs, lower_bounds, consts)\n\n consts_exponential_search = consts * 10\n consts_binary_search = (lower_bounds + upper_bounds) / 2\n consts = np.where(\n np.isinf(upper_bounds), consts_exponential_search, consts_binary_search\n )\n\n return best_advs.tensor\n\n\nclass AdamOptimizer:\n def __init__(self, x):\n self.m = ep.zeros_like(x)\n self.v = ep.zeros_like(x)\n self.t = 0\n\n def __call__(self, gradient, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-8):\n self.t += 1\n\n self.m = beta1 * self.m + (1 - beta1) * gradient\n self.v = beta2 * self.v + (1 - beta2) * gradient ** 2\n\n bias_correction_1 = 1 - beta1 ** self.t\n bias_correction_2 = 1 - beta2 ** self.t\n\n m_hat = self.m / bias_correction_1\n v_hat = self.v / bias_correction_2\n\n return -learning_rate * m_hat / (ep.sqrt(v_hat) + epsilon)\n\n\ndef untargeted_is_adv(logits: ep.Tensor, labels: ep.Tensor, confidence) -> ep.Tensor:\n logits = logits + ep.onehot_like(logits, labels, value=confidence)\n classes = logits.argmax(axis=-1)\n return classes != labels\n\n\ndef targeted_is_adv(\n logits: ep.Tensor, target_classes: ep.Tensor, confidence\n) -> ep.Tensor:\n logits = logits - ep.onehot_like(logits, target_classes, value=confidence)\n classes = logits.argmax(axis=-1)\n return classes == target_classes\n\n\ndef best_other_classes(logits, exclude):\n other_logits = logits - ep.onehot_like(logits, exclude, value=np.inf)\n return other_logits.argmax(axis=-1)\n\n\ndef _to_attack_space(x: ep.Tensor, *, bounds: tuple) -> ep.Tensor:\n min_, max_ = bounds\n a = (min_ + max_) / 2\n b = (max_ - min_) / 2\n x = (x - a) / b # map from [min_, max_] to [-1, +1]\n x = x * 0.999999 # from [-1, +1] to approx. (-1, +1)\n x = x.arctanh() # from (-1, +1) to (-inf, +inf)\n return x\n\n\ndef _to_model_space(x: ep.Tensor, *, bounds) -> ep.Tensor:\n min_, max_ = bounds\n x = x.tanh() # from (-inf, +inf) to (-1, +1)\n a = (min_ + max_) / 2\n b = (max_ - min_) / 2\n x = x * b + a # map from (-1, +1) to (min_, max_)\n return x\n","sub_path":"foolbox/ext/native/attacks/carlini_wagner.py","file_name":"carlini_wagner.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"231574299","text":"import simpy\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\nclass Part:\r\n def __init__(self, id):\r\n self.id = id\r\n self.step = 0\r\n self.process_list = ['process1', 'process2', 'process3', 'sink']\r\n\r\nclass Source:\r\n def __init__(self, env, monitor, model, name, IAT):\r\n self.env = env\r\n self.monitor = monitor\r\n self.model = model\r\n self.name = name\r\n self.IAT = IAT\r\n self.part_id = 0\r\n self.env.process(self.processing())\r\n\r\n def processing(self):\r\n while True:\r\n self.part_id += 1\r\n part = Part(self.part_id)\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='part created')\r\n yield self.env.process(self.to_next_process(part))\r\n\r\n IAT = self.IAT\r\n yield self.env.timeout(IAT)\r\n\r\n def to_next_process(self,part):\r\n yield self.model[part.process_list[part.step]].store.put(part)\r\n\r\n\r\n\r\nclass Process:\r\n def __init__(self, env, monitor, model, name, setup_time, service_time, capacity):\r\n self.env = env\r\n self.monitor = monitor\r\n self.model = model\r\n self.name = name\r\n self.setup_time = setup_time\r\n self.service_time = service_time\r\n self.store = simpy.Store(env)\r\n self.machines = simpy.Store(env, capacity=capacity)\r\n for i in range(capacity):\r\n self.machines.put('resource'+str(i))\r\n self.env.process(self.processing())\r\n\r\n def processing(self):\r\n while True:\r\n machine = yield self.machines.get()\r\n part = yield self.store.get()\r\n self.env.process(self.servicing(part, machine))\r\n\r\n def servicing(self, part, machine):\r\n setup_time = self.setup_time\r\n\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='process1 start', resource=machine)\r\n yield self.env.timeout(setup_time)\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='process1 finish', resource=machine)\r\n\r\n service_time = self.service_time\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='process2 start', resource=machine)\r\n yield self.env.timeout(service_time)\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='process2 finish', resource=machine)\r\n\r\n self.env.process(self.to_next_process(part, machine))\r\n\r\n def to_next_process(self, part, machine):\r\n part.step += 1\r\n yield self.model[part.process_list[part.step]].store.put(part)\r\n self.machines.put(machine)\r\n\r\n\r\nclass Sink:\r\n def __init__(self, env, monitor, model, name):\r\n self.env = env\r\n self.monitor = monitor\r\n self.model = model\r\n self.name = name\r\n self.store = simpy.Store(env)\r\n self.env.process(self.processing())\r\n\r\n def processing(self):\r\n while True:\r\n part = yield self.store.get()\r\n self.monitor.record(time=self.env.now, part=part.id, process=self.name, event='part finish')\r\nclass Monitor:\r\n def __init__(self, filepath):\r\n self.filepath = filepath\r\n self.time = list()\r\n self.part = list()\r\n self.process = list()\r\n self.event = list()\r\n self.resource = list()\r\n\r\n def record(self, time, process=None, part=None, event=None, resource=None):\r\n self.time.append(time)\r\n self.part.append(part)\r\n self.process.append(process)\r\n self.event.append(event)\r\n self.resource.append(resource)\r\n\r\n def save_event_tracer(self):\r\n event_tracer = pd.DataFrame(columns=['Time', 'Part', 'Process', 'Event', 'Resource'])\r\n event_tracer['Time'] = self.time\r\n event_tracer['Part'] = self.part\r\n event_tracer['Process'] = self.process\r\n event_tracer['Event'] = self.event\r\n event_tracer['Resource'] = self.resource\r\n\r\n event_tracer.to_csv(self.filepath)\r\n return event_tracer\r\n\r\n\r\nif __name__ == '__main__':\r\n IAT = random.expovariate(1.0 / 3)\r\n process1_time = random.expovariate(1.0 / 30)\r\n process2_time = random.expovariate(1.0 / 40)\r\n process3_time = random.expovariate(1.0 / 50)\r\n capacity = 1\r\n\r\n env = simpy.Environment()\r\n monitor = Monitor('eventlog.csv')\r\n model = {}\r\n model['source'] = Source(env, monitor, model, 'source', IAT)\r\n model['process1'] = Process(env, monitor, model, 'process1', process1_time, capacity)\r\n model['process2'] = Process(env, monitor, model, 'process2', process2_time, capacity)\r\n model['process3'] = Process(env, monitor, model, 'process3', process3_time, capacity)\r\n\r\n model['sink'] = Sink(env, monitor, model, 'sink')\r\n\r\n env.run(until=100)\r\n\r\n monitor.save_event_tracer()","sub_path":"exam/2022-28385_prob4.py","file_name":"2022-28385_prob4.py","file_ext":"py","file_size_in_byte":4876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"507428941","text":"import numpy as np\nfrom ase import Atoms\nfrom ase.neighborlist import neighbor_list\nfrom itertools import permutations\nfrom helper_functions import veclen\nfrom scipy.special import sph_harm\n\ndef BehParCutOff(r, r_c):\n return (r<=r_c)*0.5*(1+np.cos(np.pi*r/r_c))\n\ndef BehParRadial(atoms, eta, r_c):\n num_atoms = A.get_number_of_atoms()\n num_params = len(eta)\n F = np.zeros((num_atoms, num_params))\n \n r_ij = atoms.get_all_distances()\n for ii in range(num_atoms):\n R = r_ij[ii, r_ij[ii, :] > 0].reshape(num_atoms-1, 1)\n F[ii, :] = np.sum(np.exp(-eta*R**2/r_c**2)*BehParCutOff(R, r_c), axis=0)\n return F\n\ndef BehParAngular(atoms, eta, xi, r_c, lambd=[1, -1]):\n num_atoms = A.get_number_of_atoms()\n num_params = 2*(len(eta)*len(xi))\n F = np.zeros((num_atoms, num_params))\n \n fc = BehParCutOff\n\n r_ij = atoms.get_all_distances()\n for ii in range(num_atoms):\n for jj in range(num_atoms):\n for kk in range(num_atoms):\n if kk != ii and jj != kk and ii != jj:\n theta = atoms.get_angle(jj, ii, kk)*np.pi/180\n c = 0\n fac = fc(r_ij[ii, jj], r_c)*fc(r_ij[ii, kk], r_c)*fc(r_ij[jj, kk], r_c)\n for e in eta:\n for x in xi:\n for lamb in lambd:\n F[ii, c] += 2**(1-x)*(1-lamb*np.cos(theta))**x*np.exp(-e*(r_ij[ii, jj]**2+r_ij[ii, kk]**2+r_ij[jj, kk]**2)/r_c**2)*fac\n c += 1\n return F \n\ndef BehPar(atoms, eta, xi, rc):\n# print(eta)\n# print(xi)\n# print(rc)\n I, J, dists, D = neighbor_list('ijdD', atoms, rc)\n dists = dists[:, np.newaxis]\n\n num_radial = len(eta)\n num_angular = len(xi)*2\n num_atoms = len(atoms)\n F = np.zeros((num_atoms, num_radial+num_angular))\n \n # Adjust angular parameters:\n lamb = np.zeros((num_angular))\n Xi = np.zeros((num_angular))\n c = 0\n for x in xi:\n for ii in [-1, 1]:\n Xi[c] = x\n lamb[c] = ii\n c += 1\n\n # Radial functions given by:\n for i, j, d in zip(I, J, dists):\n F[i, 0:num_radial] += np.exp(-eta*d**2/rc**2)*BehParCutOff(d, rc)\n \n # Angular functions:\n eta_ang = 0.005\n for i in range(num_atoms):\n neigh_mask = I==i\n for Rij, rij, j in zip(D[neigh_mask], dists[neigh_mask].ravel(), J[neigh_mask]):\n for Rik, rik, k in zip(D[neigh_mask], dists[neigh_mask].ravel(), J[neigh_mask]):\n if j < k:\n Rjk = Rik-Rij\n rjk = np.sqrt(Rjk@Rjk)\n theta = (Rij@Rik)/(np.sqrt(Rij@Rij)*np.sqrt(Rik@Rik))\n F[i, num_radial::] += (1+lamb*theta)**Xi*np.exp(-eta_ang*(rij**2+rik**2+rjk**2)/rc**2)*BehParCutOff(rij, rc)*BehParCutOff(rik, rc)*BehParCutOff(rjk, rc)\n F[:, num_radial::] *= 2**(1-Xi)\n \n # Atomic number as last entry:\n Fz = atoms.get_atomic_numbers().reshape(num_atoms, 1)\n \n \n #F[: -1] = [atom.get_atomic_number() for atom in atoms]\n\n F = np.concatenate((Fz, F), axis=1)\n\n return F\n\ndef SivaDescriptor(atoms, eta, xi, rc, L=2):\n \"\"\"\n Calculates the descriptors of an atoms object according to \n 'S. Jindal, S. Chiriki, Spherical Harmonics based descriptor..'\n -- atoms: Atoms objects\n -- eta: Parameters for radial functions\n -- xi: Parameters for angular functions\n -- rc: Cutoff\n -- L: Maximum l used in expansion of spherical harmonics.\n\n Returns local feature vectors of each atom in the structure:\n 1st entry: Chemical species.\n Middle: Radial functions\n Last: Angular functions\n \"\"\"\n\n\n # Obtain data from atoms object\n I, J, dists, Dvecs = neighbor_list('ijdD', atoms, rc)\n num_atoms = atoms.get_number_of_atoms()\n num_eta = len(eta)\n num_xi = len(xi)\n num_l = L+1; Ls = [l for l in range(num_l)]\n num_m = 2*L+1\n\n # Setup storage arrays:\n Fr = np.zeros((num_atoms, num_eta)) # Radial\n Fa = np.zeros((atoms.get_number_of_atoms(), num_xi, num_l)) # Angular\n\n # Calculate radial functions:\n for i, d in zip(I, dists):\n Fr[i, :] += np.exp(-eta*d**2)\n \n # Calculate angular functions:\n c = np.zeros((num_atoms, num_xi, num_l, num_m), dtype=np.complex)\n for i, d, r in zip(I, dists, Dvecs):\n\n pol = np.arccos(r[2]/d) # Polar angle\n azi = np.arctan(r[1]/r[0]) # Azimuthal angle\n fc = BehParCutOff(d, rc)\n\n for xidx, x in enumerate(xi):\n ans = np.exp(-x*d**2)*fc\n for lidx, l in enumerate(range(L+1)):\n for midx, m in enumerate(range(-l, l+1)): \n c[i, xidx, lidx, midx] = ans*sph_harm(m, l, azi, pol)\n\n for i in range(num_atoms):\n for lidx in range(num_l):\n for xidx in range(num_xi):\n Fa[i, xidx, lidx] += 4*np.pi/(2*Ls[lidx]+1)*(np.vdot(c[i, xidx, lidx, :],c[i, xidx, lidx, :])).real\n \n Fa = Fa.reshape(num_atoms, num_xi*num_l)\n Z = atoms.get_atomic_numbers()[:, np.newaxis]\n return np.append(Z, np.append(Fr, Fa, axis=1), axis=1)\n\n\n\n\n\n\n\n","sub_path":"main_files/descriptors.py","file_name":"descriptors.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"496551949","text":"from array import array\nfrom enum import Enum\n\nwith open('data.txt') as f:\n data = list(map(int, f.read().split(',')))\n\n\nclass Opcode(Enum):\n ADD = 1\n MUL = 2\n IN = 3\n OUT = 4\n JNZ = 5\n JZ = 6\n LT = 7\n EQ = 8\n REL = 9\n HALT = 99\n\n\nclass ParamMode(Enum):\n MEMORY = 0\n IMMEDIATE = 1\n RELATIVE = 2\n\n\nclass Halt(Exception):\n pass\n\n\nclass Memory:\n def __init__(self, initial):\n self.data = array('q', initial)\n\n def __getitem__(self, index):\n return self.data[index] if index < len(self.data) else 0\n\n def __setitem__(self, index, value):\n if index >= len(self.data):\n self.data.extend([0] * (index - len(self.data)))\n self.data.append(value)\n else:\n self.data[index] = value\n\n\nclass Interpreter:\n def __init__(self, inp):\n self.pc = 0\n self.rel = 0\n self.memory = Memory(data)\n self.input = inp\n self.output = []\n\n def _param(self, index):\n mode = ParamMode(self.memory[self.pc] // 10 ** (index + 1) % 10)\n if mode == ParamMode.MEMORY:\n return self.memory[self.pc + index]\n if mode == ParamMode.IMMEDIATE:\n return self.pc + index\n if mode == ParamMode.RELATIVE:\n return self.rel + self.memory[self.pc + index]\n\n def param(self, index):\n return self.memory[self._param(index)]\n\n def store(self, index, value):\n self.memory[self._param(index)] = value\n\n def step(self):\n op = Opcode(self.memory[self.pc] % 100)\n if op == Opcode.ADD:\n self.store(3, self.param(1) + self.param(2))\n self.pc += 4\n elif op == Opcode.MUL:\n self.store(3, self.param(1) * self.param(2))\n self.pc += 4\n elif op == Opcode.IN:\n self.store(1, self.input.pop(0))\n self.pc += 2\n elif op == Opcode.OUT:\n self.output.append(self.param(1))\n self.pc += 2\n elif op == Opcode.JNZ:\n self.pc = self.param(2) if self.param(1) else self.pc + 3\n elif op == Opcode.JZ:\n self.pc = self.pc + 3 if self.param(1) else self.param(2)\n elif op == Opcode.LT:\n self.store(3, self.param(1) < self.param(2))\n self.pc += 4\n elif op == Opcode.EQ:\n self.store(3, self.param(1) == self.param(2))\n self.pc += 4\n elif op == Opcode.REL:\n self.rel += self.param(1)\n self.pc += 2\n elif op == Opcode.HALT:\n raise Halt()\n\n def run_until_output(self):\n length = len(self.output)\n while len(self.output) == length:\n self.step()\n return self.output[-1]\n\n def run_until_halt(self):\n try:\n while 1:\n self.step()\n except Halt:\n return\n\n\ninterpreter = Interpreter([1])\ninterpreter.run_until_halt()\nprint(interpreter.output)\n\ninterpreter = Interpreter([2])\ninterpreter.run_until_halt()\nprint(interpreter.output)\n","sub_path":"python/09/day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"109565617","text":"# python modules\r\nimport pymysql\r\nimport pyodbc\r\nfrom datetime import datetime\r\n\r\n\r\ndef etl(query, source_cnx, target_cnx):\r\n # extract data from source db\r\n\r\n source_cursor = source_cnx.cursor()\r\n start_time = datetime.now()\r\n source_cursor.execute(query.extract_query)\r\n data = source_cursor.fetchall()\r\n # ------QQ\r\n # I think FETCHALL is non-deterministic and you might fail based on \r\n # number of records you are fetching & resource availabilty on your target server\r\n # It is better to go with deterministic model FETCHMANY(size)\r\n # So that you know your tested limits/resource utilization and can adjust as needed \r\n # --------\r\n source_cursor.close()\r\n # -------QQ:\r\n # It is good to catch and log duration for getting the data from source\r\n # -------\r\n\r\n # load data into warehouse db\r\n if data:\r\n # --------------QQ:\r\n # Is this a good model to use between SET or PROCEDURAL operation\r\n # https://www.codeproject.com/Articles/34142/Understanding-Set-based-and-Procedural-approaches\r\n # --------------\r\n target_cursor = target_cnx.cursor()\r\n # target_cursor.execute(\"USE {}\".format(datawarehouse_name))\r\n target_cursor.executemany(query.load_query, data)\r\n # -----QQ\r\n # I think you have right choice above. \r\n # By calling the executemany() method of the MySQLCursor object, \r\n # the MySQL Connector/Python translates the INSERT statement into \r\n # the one that contains multiple lists of values\r\n # -------\r\n target_cnx.commit()\r\n # -------QQ:\r\n # Measure duration elapsed in milliseconds for Target write operation\r\n # So that you know where you are spending mode of your time\r\n # ------- \r\n end_time = datetime.now()\r\n print('data loaded to warehouse db')\r\n target_cursor.execute('''SELECT highest_id FROM log_table WHERE job_status='success' ORDER BY batch_id DESC LIMIT 1''')\r\n lowest_id = target_cursor.fetchone()\r\n lowest_id = lowest_id[0]\r\n target_cursor.execute('''SELECT bookinginfoid FROM roxy_datawarehouse ORDER BY id DESC LIMIT 1''')\r\n highest_id = target_cursor.fetchone()\r\n log_table_insert_query = ('''INSERT INTO log_table (`job_name`, `job_start_date`, `job_end_date`, \r\n `lowest_id`, `highest_id`, `job_status`) VALUES (%s, %s, %s, %s, %s, %s)''')\r\n log_table_insert_params = ('roxy', start_time,\r\n end_time, (lowest_id+1), highest_id, 'success')\r\n target_cursor.execute(log_table_insert_query, log_table_insert_params)\r\n target_cnx.commit()\r\n # --------QQ\r\n # I'm not a MySQL expert. Is that every insert/update has to use CURSOR\r\n # In TSQL world, CURSOR is bad choice for the reasons discussed above\r\n # --------\r\n target_cursor.close()\r\n else:\r\n print('data empty')\r\n target_cursor = target_cnx.cursor()\r\n data_empty_insert = ('''INSERT INTO log_table (`job_name`, `job_start_date`, `job_status`, `failure_reason`) VALUES (%s, %s, %s, %s)''')\r\n data_empty_params = ('roxy', start_time, 'failed', 'data empty')\r\n target_cursor.execute(data_empty_insert, data_empty_params)\r\n target_cnx.commit()\r\n\r\n\r\ndef etl_process(queries, target_cnx, source_db_config, db_platform):\r\n # establish source db connection\r\n # -------QQ:\r\n # Check for input params are not null\r\n # Throw specic err so you know which input is not valid\r\n # ------- \r\n if db_platform == 'mysql':\r\n source_cnx = pymysql.connect(**source_db_config)\r\n elif db_platform == 'sqlserver':\r\n source_cnx = pyodbc.connect(**source_db_config)\r\n elif db_platform == 'firebird':\r\n source_cnx = fdb.connect(**source_db_config)\r\n elif db_platform == 'sqlite':\r\n source_cnx = sqlite3.connect(**source_db_config)\r\n else:\r\n return 'Error! unrecognised db platform'\r\n # -------QQ:\r\n # You don't want to throw exception? Why string return value?\r\n # I haven't done Python and more of a learning question\r\n # -------\r\n \r\n # loop through sql queries\r\n for query in queries:\r\n etl(query, source_cnx, target_cnx)\r\n\r\n # close the source db connection\r\n # -------QQ:\r\n # After closing the cursor, can't immed. close source connection?\r\n # Do you have to keep it open until Target write Op. is complete?\r\n # -------\r\n source_cnx.close()\r\n","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"103606728","text":"# Author: Mingyu Ding\n# Time: 2/1/2020 7:02 PM\n# Copyright 2019. 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 importlib import import_module\nfrom getopt import getopt\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nimport numpy as np\nimport pprint\nimport sys\nimport os\nimport cv2\nimport math\nimport shutil\nimport re\nfrom easydict import EasyDict as edict\nimport json\nimport pickle\nimport mmcv\n\n# stop python from writing so much bytecode\nsys.dont_write_bytecode = True\nsys.path.append(os.getcwd())\nnp.set_printoptions(suppress=True)\n\nmean_3d = [ 1.5319942, 1.6342136, 3.8970344, 1.0385063, -2.2421432, 26.235588, -0.04752721, -0.02627299]\nstd_3d = [ 0.13790289, 0.09824956, 0.42854765, 42.354717, 21.57514, 12.873396, 1.6905682, 1.7750752]\nAw = 123.62374/2 # 69.16813\nAh = 113.182/2 # 51.076797]\n\n# trans_mean = [-0.00378265, -0.00182043, -0.00622482, 0.016801083, -0.03962014, 26.235588, -0.04752721, -0.02627299]\n# trans_std = [0.08565227, 0.06028508, 0.11255758, 0.6852198, 0.38124686, 12.873396, 1.6905682, 1.7750752]\ntrans_mean = [-0.00378265, -0.00182043, -0.00622482, 0, 0, 26.235588, -0.04752721, -0.02627299]\ntrans_std = [0.08565227, 0.06028508, 0.11255758, 1, 1, 12.873396, 1.6905682, 1.7750752]\n\ndef read_kitti_cal(calfile):\n \"\"\"\n Reads the kitti calibration projection matrix (p2) file from disc.\n Args:\n calfile (str): path to single calibration file\n \"\"\"\n\n text_file = open(calfile, 'r')\n\n p2pat = re.compile(('(P2:)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)' +\n '\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s*\\n').replace('fpat', '[-+]?[\\d]+\\.?[\\d]*[Ee](?:[-+]?[\\d]+)?'))\n\n for line in text_file:\n\n parsed = p2pat.fullmatch(line)\n\n # bbGt annotation in text format of:\n # cls x y w h occ x y w h ign ang\n if parsed is not None:\n p2 = np.zeros([4, 4], dtype=float)\n p2[0, 0] = parsed.group(2)\n p2[0, 1] = parsed.group(3)\n p2[0, 2] = parsed.group(4)\n p2[0, 3] = parsed.group(5)\n p2[1, 0] = parsed.group(6)\n p2[1, 1] = parsed.group(7)\n p2[1, 2] = parsed.group(8)\n p2[1, 3] = parsed.group(9)\n p2[2, 0] = parsed.group(10)\n p2[2, 1] = parsed.group(11)\n p2[2, 2] = parsed.group(12)\n p2[2, 3] = parsed.group(13)\n\n p2[3, 3] = 1\n\n text_file.close()\n\n return p2\n\n\ndef convertRot2Alpha(ry3d, z3d, x3d):\n\n alpha = ry3d - math.atan2(-z3d, x3d) - 0.5 * math.pi\n # alpha = ry3d - math.atan2(x3d, z3d) # equivalent\n\n while alpha > math.pi: alpha -= math.pi * 2\n while alpha < (-math.pi): alpha += math.pi * 2\n\n return alpha\n\n\ndef project_3d(p2, x3d, y3d, z3d, w3d, h3d, l3d, ry3d, return_3d=False):\n \"\"\"\n Projects a 3D box into 2D vertices\n Args:\n p2 (nparray): projection matrix of size 4x3\n x3d: x-coordinate of center of object\n y3d: y-coordinate of center of object\n z3d: z-cordinate of center of object\n w3d: width of object\n h3d: height of object\n l3d: length of object\n ry3d: rotation w.r.t y-axis\n \"\"\"\n\n # compute rotational matrix around yaw axis\n R = np.array([[+math.cos(ry3d), 0, +math.sin(ry3d)],\n [0, 1, 0],\n [-math.sin(ry3d), 0, +math.cos(ry3d)]])\n\n # 3D bounding box corners\n x_corners = np.array([0, l3d, l3d, l3d, l3d, 0, 0, 0])\n y_corners = np.array([0, 0, h3d, h3d, 0, 0, h3d, h3d])\n z_corners = np.array([0, 0, 0, w3d, w3d, w3d, w3d, 0])\n\n x_corners += -l3d / 2\n y_corners += -h3d / 2\n z_corners += -w3d / 2\n\n # bounding box in object co-ordinate\n corners_3d = np.array([x_corners, y_corners, z_corners])\n\n # rotate\n corners_3d = R.dot(corners_3d)\n\n # translate object coordinate to camera coordinate\n corners_3d += np.array([x3d, y3d, z3d]).reshape((3, 1))\n\n corners_3D_1 = np.vstack((corners_3d, np.ones((corners_3d.shape[-1]))))\n corners_2D = p2.dot(corners_3D_1)\n corners_2D = corners_2D / corners_2D[2] # normalize dim 3 -> 2, image coordinate\n\n bb3d_lines_verts_idx = [0, 1, 2, 3, 4, 5, 6, 7]\n\n verts3d = (corners_2D[:, bb3d_lines_verts_idx][:2]).astype(float).T\n\n if return_3d:\n return verts3d, corners_3d # 2d corners in image coordinate and 3d corners in camera coordinate\n else:\n return verts3d\n\n\ndef read_kitti_label(file, calib, dataset):\n \"\"\"\n Reads the kitti label file from disc.\n Args:\n file (str): path to single label file for an image\n p2 (ndarray): projection matrix for the given image\n \"\"\"\n\n gts = []\n calib = calib.astype(np.float32)\n\n text_file = open(file, 'r')\n\n '''\n Values Name Description\n ----------------------------------------------------------------------------\n 1 type Describes the type of object: 'Car', 'Van', 'Truck',\n 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram',\n 'Misc' or 'DontCare'\n 1 truncated Float from 0 (non-truncated) to 1 (truncated), where\n truncated refers to the object leaving image boundaries\n 1 occluded Integer (0,1,2,3) indicating occlusion state:\n 0 = fully visible, 1 = partly occluded\n 2 = largely occluded, 3 = unknown\n 1 alpha Observation angle of object, ranging [-pi..pi]\n 4 bbox 2D bounding box of object in the image (0-based index):\n contains left, top, right, bottom pixel coordinates\n 3 dimensions 3D object dimensions: height, width, length (in meters)\n 3 location 3D object location x,y,z in camera coordinates (in meters)\n 1 rotation_y Rotation ry around Y-axis in camera coordinates [-pi..pi]\n 1 score Only for results: Float, indicating confidence in\n detection, needed for p/r curves, higher is better.\n '''\n\n pattern = re.compile(('([a-zA-Z\\-\\?\\_]+)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+'\n + '(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s+(fpat)\\s*((fpat)?)\\n')\n .replace('fpat', '[-+]?\\d*\\.\\d+|[-+]?\\d+'))\n\n bboxes = []\n bboxes_ignore = []\n bboxes_3d = []\n bboxes_3d_ignore = []\n labels = []\n labels_ignore = []\n\n TYPE2LABEL = dict(\n Background=0,\n Car=1,\n Cyclist=2,\n Pedestrian=3,\n # Van=4,\n # Person_sitting=5\n # Truck = 6\n # Tram = 7\n # Misc = 8\n )\n\n for line in text_file:\n\n parsed = pattern.fullmatch(line)\n\n # bbGt annotation in text format of:\n # cls x y w h occ x y w h ign ang\n if parsed is not None:\n\n obj = edict()\n\n ign = False\n\n label_type = parsed.group(1) # type\n trunc = float(parsed.group(2))\n occ = float(parsed.group(3))\n alpha = float(parsed.group(4))\n\n x = float(parsed.group(5)) # left\n y = float(parsed.group(6)) # top\n x2 = float(parsed.group(7)) # right\n y2 = float(parsed.group(8)) # bottom\n\n width = x2 - x + 1\n height = y2 - y + 1\n\n h3d = float(parsed.group(9))\n w3d = float(parsed.group(10))\n l3d = float(parsed.group(11))\n\n cx3d = float(parsed.group(12)) # center of car in 3d\n cy3d = float(parsed.group(13)) # bottom of car in 3d\n cz3d = float(parsed.group(14)) # center of car in 3d\n rotY = float(parsed.group(15))\n\n cy3d -= (h3d / 2)\n\n ign = 0\n verts3d, corners_3d = project_3d(calib, cx3d, cy3d, cz3d, w3d, h3d, l3d, rotY, return_3d=True)\n\n if np.any(corners_3d[2, :] <= 0):\n ign = True\n else: # 3d for 2d\n x = min(verts3d[:, 0])\n y = min(verts3d[:, 1])\n x2 = max(verts3d[:, 0])\n y2 = max(verts3d[:, 1])\n\n width = x2 - x + 1\n height = y2 - y + 1\n\n # rotY_1 = 0\n # if rotY < 0:\n # rotY = rotY + math.pi\n # rotY_1 = 1\n\n x_p, y_p, z_p, _ = calib.dot(np.array([cx3d, cy3d, cz3d, 1]))\n x_p /= z_p\n y_p /= z_p\n\n alpha = convertRot2Alpha(rotY, cz3d, cx3d)\n obj.bbox_3d = [h3d, w3d, l3d, x_p, y_p, z_p, rotY, alpha]\n\n # for i in range(8):\n # obj.bbox_3d[i] = (obj.bbox_3d[i] - mean_3d[i]) / std_3d[i]\n\n for i in range(3):\n obj.bbox_3d[i] = np.log(obj.bbox_3d[i]/mean_3d[i])\n\n for i in range(8):\n obj.bbox_3d[i] = (obj.bbox_3d[i] - trans_mean[i]) / trans_std[i]\n\n obj.bbox_2d = [x, y, x2, y2]\n obj.label = label_type\n\n # gts.append(obj)\n\n if label_type in TYPE2LABEL and occ <= 1 and not ign and height >= 23 and height <= 280:\n # print(obj.bbox_3d)\n bboxes.append(obj.bbox_2d)\n bboxes_3d.append(obj.bbox_3d)\n labels.append(TYPE2LABEL[label_type])\n # if obj.bbox_3d[3] > x2 or obj.bbox_3d[3] < x:\n # print(obj.bbox_2d, obj.bbox_3d)\n if label_type in TYPE2LABEL and occ <= 1 and ign: # or occ >= 2: # label_type == 'DontCare' or\n bboxes_ignore.append(obj.bbox_2d)\n bboxes_3d_ignore.append(obj.bbox_3d)\n labels_ignore.append(0)\n\n if dataset == 'train':\n if bboxes_ignore:\n ann = dict(\n bboxes=np.array(bboxes, dtype=np.float32),\n bboxes_3d=np.array(bboxes_3d, dtype=np.float32),\n calib=calib,\n labels=np.array(labels, dtype=np.int64),\n bboxes_ignore=np.zeros((0, 4), dtype=np.float32),\n bboxes_3d_ignore=np.zeros((0, 8), dtype=np.float32)\n # bboxes_ignore=np.array(bboxes_ignore, dtype=np.float32),\n # bboxes_3d_ignore=np.array(bboxes_3d_ignore, dtype=np.float32),\n )\n else:\n ann = dict(\n bboxes=np.array(bboxes, dtype=np.float32),\n bboxes_3d=np.array(bboxes_3d, dtype=np.float32),\n calib=calib,\n labels=np.array(labels, dtype=np.int64),\n bboxes_ignore=np.zeros((0, 4), dtype=np.float32),\n bboxes_3d_ignore=np.zeros((0, 8), dtype=np.float32),\n )\n else:\n ann = dict(\n bboxes=np.array(bboxes, dtype=np.float32),\n labels=np.array(labels, dtype=np.int64),\n bboxes_3d=np.array(bboxes_3d, dtype=np.float32),\n calib=calib,\n )\n\n return ann\n\n\n\nkitti_raw = dict()\nkitti_raw['base'] = os.path.join(os.getcwd(), 'data', 'kitti')\nkitti_raw['calib'] = os.path.join(kitti_raw['base'], 'training', 'calib')\nkitti_raw['img'] = os.path.join(kitti_raw['base'], 'training', 'image_2')\nkitti_raw['label'] = os.path.join(kitti_raw['base'], 'training', 'label_2')\nkitti_raw['pre'] = os.path.join(kitti_raw['base'], 'training', 'prev_2')\n\ntrain_file = 'kitti_tools/split1/train.txt'\nval_file = 'kitti_tools/split1/val.txt'\ntrain_list = []\nval_list = []\n\n# stats = np.zeros((0, 8), np.float32)\n\nfor item in ['train', 'val']:\n if item == 'train':\n text_file = open(train_file, 'r')\n else:\n text_file = open(val_file, 'r')\n\n for index, line in enumerate(text_file):\n if index % 20 == 0:\n print(index)\n # if index >= 200:\n # break\n parsed = re.search('(\\d+)', line)\n if parsed is not None:\n id = str(parsed[0])\n # print(id)\n\n file_info = dict()\n file_info['filename'] = os.path.join(kitti_raw['img'], id + '.png')\n file_info['calibname'] = os.path.join(kitti_raw['calib'], id + '.txt')\n file_info['labelname'] = os.path.join(kitti_raw['label'], id + '.txt')\n\n file_shape = cv2.imread(file_info['filename']).shape[:2][::-1]\n file_info['width'] = file_shape[0]\n file_info['height'] = file_shape[1]\n\n file_info['calib'] = read_kitti_cal(file_info['calibname'])\n file_info['ann'] = read_kitti_label(file_info['labelname'], file_info['calib'], item)\n # stats = np.concatenate((stats, file_info['ann']['bboxes_3d']), axis=0)\n # print(stats.mean(0), stats.std(0))\n if item == 'train':\n train_list.append(file_info)\n else:\n val_list.append(file_info)\n# output = open(os.path.join(os.getcwd(), 'train.pkl'), 'wb')\n# pickle.dump(train_list, output)\n# print(stats.mean(0),stats.std(0))\nmmcv.dump(train_list, os.path.join(os.getcwd(), os.path.join(os.getcwd(), 'kitti_tools', 'split1', 'train_3d.pkl')))\nmmcv.dump(val_list, os.path.join(os.getcwd(), os.path.join(os.getcwd(), 'kitti_tools', 'split1', 'val_3d.pkl')))","sub_path":"kitti_tools/split1/convert_datasets/kitti_3d.py","file_name":"kitti_3d.py","file_ext":"py","file_size_in_byte":13787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644428300","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\") # another bogus warning, see https://github.com/numpy/numpy/pull/432\nimport numpy as np\nimport pandas as pd\nimport sys\nfrom collections import defaultdict\nfrom pprint import pformat\nfrom collections import deque\nimport math\nfrom functools import reduce\n\nimport pandas as pd\nfrom copy import copy\nimport numpy as np\n\nfrom pyqstrat.pq_utils import *\nfrom pyqstrat.marketdata import *\nfrom pyqstrat.orders import *\nfrom pyqstrat.plot import *\nfrom pyqstrat.evaluator import *\n\n\n# In[3]:\n\n\ndef _calc_pnl(open_trades, new_trades, ending_close, multiplier):\n '''\n >>> from collections import deque\n >>> trades = deque([Trade('IBM', np.datetime64('2018-01-01 10:15:00'), 3, 51.),\n ... Trade('IBM', np.datetime64('2018-01-01 10:20:00'), 10, 50.),\n ... Trade('IBM', np.datetime64('2018-01-02 11:20:00'), -5, 45.)])\n >>> print(_calc_pnl(open_trades = deque(), new_trades = trades, ending_close = 54, multiplier = 100))\n (deque([IBM 2018-01-01 10:20 qty: 8 prc: 50.0 order: None]), 3200.0, -2800.0)\n >>> trades = deque([Trade('IBM', np.datetime64('2018-01-01 10:15:00'), -8, 10.),\n ... Trade('IBM', np.datetime64('2018-01-01 10:20:00'), 9, 11.),\n ... Trade('IBM', np.datetime64('2018-01-02 11:20:00'), -4, 6.)])\n >>> print(_calc_pnl(open_trades = deque(), new_trades = trades, ending_close = 5.8, multiplier = 100))\n (deque([IBM 2018-01-02 11:20 qty: -3 prc: 6.0 order: None]), 60.00000000000006, -1300.0)\n '''\n \n realized = 0.\n unrealized = 0.\n \n trades = copy(new_trades)\n \n while (len(trades)):\n trade = trades[0]\n if not len(open_trades) or (np.sign(open_trades[-1].qty) == np.sign(trade.qty)):\n open_trades.append(copy(trade))\n trades.popleft()\n continue\n \n if abs(trade.qty) > abs(open_trades[0].qty):\n open_trade = open_trades.popleft()\n realized += open_trade.qty * multiplier * (trade.price - open_trade.price)\n trade.qty += open_trade.qty\n else:\n open_trade = open_trades[0]\n realized += trade.qty * multiplier * (open_trades[-1].price - trade.price)\n trades.popleft()\n open_trade.qty += trade.qty\n \n unrealized = sum([open_trade.qty * (ending_close - open_trade.price) for open_trade in open_trades]) * multiplier\n\n return open_trades, unrealized, realized\n\nclass Trade:\n def __init__(self, symbol, date, qty, price, fee = 0., commission = 0., order = None):\n '''Args:\n symbol: a string\n date: Trade execution datetime\n qty: Number of contracts or shares filled\n price: Trade price\n fee: Fees paid to brokers or others. Default 0\n commision: Commission paid to brokers or others. Default 0\n order: A reference to the order that created this trade. Default None\n '''\n assert(isinstance(symbol, str) and len(symbol) > 0)\n assert(np.isfinite(qty))\n assert(np.isfinite(price))\n assert(np.isfinite(fee))\n assert(np.isfinite(commission))\n \n self.symbol = symbol\n self.date = date\n self.qty = qty\n self.price = price\n self.fee = fee\n self.commission = commission\n self.order = order\n \n def __repr__(self):\n return '{} {:%Y-%m-%d %H:%M} qty: {} prc: {}{}{} order: {}'.format(self.symbol, pd.Timestamp(self.date).to_pydatetime(), \n self.qty, self.price, \n ' ' + str(self.fee) if self.fee != 0 else '', \n ' ' + str(self.commission) if self.commission != 0 else '', \n self.order)\n\n\nclass Portfolio:\n '''A portfolio contains one or more strategies that run concurrently so you can test running strategies that are uncorrelated together.'''\n def __init__(self, name = 'main'):\n '''Args:\n name: String used for displaying this portfolio\n '''\n self.name = name\n self.strategies = {}\n \n def add_strategy(self, name, strategy):\n '''\n Args:\n name: Name of the strategy\n strategy: Strategy object\n '''\n self.strategies[name] = strategy\n strategy.portfolio = self\n strategy.name = name\n \n def run_indicators(self, strategy_names = None):\n '''Compute indicators for the strategies specified\n \n Args:\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n '''\n if strategy_names is None: strategy_names = list(self.strategies.keys())\n if len(strategy_names) == 0: raise Exception('a portofolio must have at least one strategy')\n for name in strategy_names: self.strategies[name].run_indicators()\n \n def run_signals(self, strategy_names = None):\n '''Compute signals for the strategies specified. Must be called after run_indicators\n \n Args:\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n '''\n if strategy_names is None: strategy_names = list(self.strategies.keys())\n if len(strategy_names) == 0: raise Exception('a portofolio must have at least one strategy')\n for name in strategy_names: self.strategies[name].run_signals()\n \n def run_rules(self, strategy_names = None, start_date = None, end_date = None, run_first = False, run_last = True):\n '''Run rules for the strategies specified. Must be called after run_indicators and run_signals. \n See run function for argument descriptions\n '''\n start_date, end_date = str2date(start_date), str2date(end_date)\n if strategy_names is None: strategy_names = list(self.strategies.keys())\n if len(strategy_names) == 0: raise Exception('a portofolio must have at least one strategy')\n\n strategies = [self.strategies[key] for key in strategy_names]\n \n min_date = min([strategy.dates[0] for strategy in strategies])\n if start_date: min_date = max(min_date, start_date)\n max_date = max([strategy.dates[-1] for strategy in strategies])\n if end_date: max_date = min(max_date, end_date)\n \n iter_list = []\n \n for strategy in strategies:\n dates, iterations = strategy._get_iteration_indices(start_date = start_date, end_date = end_date, run_first = run_first, run_last = run_last)\n iter_list.append((strategy, dates, iterations))\n \n dates_list = [tup[1] for tup in iter_list]\n \n #for v in self.rebalance_rules.values():\n # _, freq = v\n # rebalance_dates = pd.date_range(min_date, max_date, freq = freq).values\n # dates_list.append(rebalance_dates)\n \n all_dates = np.array(reduce(np.union1d, dates_list))\n\n iterations = [[] for x in range(len(all_dates))]\n\n for tup in iter_list: # per strategy\n strategy = tup[0]\n dates = tup[1]\n iter_tup = tup[2] # vector with list of (rule, symbol, iter_params dict)\n for i, date in enumerate(dates):\n idx = np.searchsorted(all_dates, date)\n iterations[idx].append((Strategy._iterate, (strategy, i, iter_tup[i])))\n \n #for name, tup in self.rebalance_rules.items():\n # rule, freq = tup\n # rebalance_dates = pd.date_range(all_dates[0], all_dates[-1], freq = freq).values\n # rebalance_indices = np.where(np.in1d(all_dates, rebalance_dates))[0]\n # iterations[idx].append(lambda : Portfolio.rebalance(rule), idx)\n \n self.iterations = iterations # For debugging\n \n for iter_idx, tup_list in enumerate(iterations):\n for tup in tup_list:\n func = tup[0]\n args = tup[1]\n func(*args)\n \n def run(self, strategy_names = None, start_date = None, end_date = None, run_first = False, run_last = True):\n '''\n Run indicators, signals and rules.\n \n Args:\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n start_date: Run rules starting from this date. \n Sometimes we have a few strategies in a portfolio that need different lead times before they are ready to trade\n so you can set this so they are all ready by this date. Default None\n end_date: Don't run rules after this date. Default None\n run_first: Force running rules on the first bar even if signals do not require this. Default False\n run_last: Force running rules on penultimate bar even if signals do not require this. \n '''\n start_date, end_date = str2date(start_date), str2date(end_date)\n self.run_indicators()\n self.run_signals()\n return self.run_rules(strategy_names, start_date, end_date, run_first, run_last)\n \n def df_returns(self, sampling_frequency = 'D', strategy_names = None):\n '''\n Return dataframe containing equity and returns with a date index. Equity and returns are combined from all strategies passed in.\n \n Args:\n sampling_frequency: Date frequency for rows. Default 'D' for daily so we will have one row per day\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n '''\n if strategy_names is None: strategy_names = list(self.strategies.keys())\n if len(strategy_names) == 0: raise Exception('portfolio must have at least one strategy')\n equity_list = []\n for name in strategy_names:\n equity = self.strategies[name].df_returns(sampling_frequency = sampling_frequency)[['equity']]\n equity.columns = [name]\n equity_list.append(equity)\n df = pd.concat(equity_list, axis = 1)\n df['equity'] = df.sum(axis = 1)\n df['ret'] = df.equity.pct_change()\n return df\n \n def evaluate_returns(self, sampling_frequency = 'D', strategy_names = None, plot = True, float_precision = 4):\n '''Returns a dictionary of common return metrics.\n \n Args:\n sampling_frequency: Date frequency. Default 'D' for daily so we downsample to daily returns before computing metrics\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n plot: If set to True, display plots of equity, drawdowns and returns. Default False\n float_precision: Number of significant figures to show in returns. Default 4\n '''\n returns = self.df_returns(sampling_freq, strategy_names)\n ev = compute_return_metrics(returns.index.values, returns.ret.values, returns.equity.values[0])\n display_return_metrics(ev.metrics(), float_precision = float_precision)\n if plot: plot_return_metrics(ev.metrics())\n return ev.metrics()\n \n def plot(self, sampling_frequency = 'D', strategy_names = None):\n '''Display plots of equity, drawdowns and returns\n \n Args:\n sampling_frequency: Date frequency. Default 'D' for daily so we downsample to daily returns before computing metrics\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n '''\n returns = self.df_returns(sampling_frequency, strategy_names)\n ev = compute_return_metrics(returns.index.values, returns.ret.values, returns.equity.values[0])\n plot_return_metrics(ev.metrics())\n \n def __repr__(self):\n return f'{self.name} {self.strategies.keys()}'\n \n \nclass ContractPNL:\n '''Computes pnl for a single contract over time given trades and market data'''\n def __init__(self, contract):\n self.symbol = contract.symbol\n self.multiplier = contract.multiplier\n self.marketdata = contract.marketdata\n self.dates = self.marketdata.dates\n self.unrealized = np.empty(len(self.dates), dtype = np.float) * np.nan; self.unrealized[0] = 0\n self.realized = np.empty(len(self.dates), dtype = np.float) * np.nan; self.realized[0] = 0\n \n #TODO: Add commission and fee from trades\n self.commission = np.empty(len(self.dates), dtype = np.float) * 0; self.commission[0] = 0\n self.fee = np.empty(len(self.dates), dtype = np.float) * 0; self.fee[0] = 0\n \n self.net_pnl = np.empty(len(self.dates), dtype = np.float) * np.nan; self.net_pnl[0] = 0\n self.position = np.empty(len(self.dates), dtype = np.float) * np.nan; self.position[0] = 0\n self.close = self.marketdata.c\n self._trades = []\n self.open_trades = deque()\n \n def add_trades(self, trades):\n '''Args:\n trades: A list of Trade objects\n '''\n self._trades += trades\n \n def calc(self, prev_i, i):\n '''Compute pnl and store it internally\n \n Args:\n prev_i: Start index to compute pnl from\n i: End index to compute pnl to\n '''\n calc_trades = deque([trade for trade in self._trades if trade.date > self.dates[prev_i] and trade.date <= self.dates[i]])\n \n if not np.isfinite(self.close[i]):\n unrealized = self.unrealized[prev_i]\n realized = 0. \n else:\n open_trades, unrealized, realized = _calc_pnl(self.open_trades, calc_trades, self.close[i], self.multiplier)\n self.open_trades = open_trades\n \n self.unrealized[i] = unrealized\n self.realized[i] = self.realized[prev_i] + realized\n trade_qty = sum([trade.qty for trade in calc_trades])\n self.position[i] = self.position[prev_i] + trade_qty\n self.net_pnl[i] = self.realized[i] + self.unrealized[i] - self.commission[i] - self.fee[i]\n \n def trades(self, start_date = None, end_date = None):\n '''Get a list of trades\n \n Args:\n start_date: A string or numpy datetime64. Trades with trade dates >= start_date will be returned. Default None\n end_date: A string or numpy datetime64. Trades with trade dates <= end_date will be returned. Default None\n '''\n start_date, end_date = str2date(start_date), str2date(end_date)\n trades = [trade for trade in self._trades if (start_date is None or trade.date >= start_date) and (end_date is None or trade.date <= end_date)]\n return trades\n \n def df(self):\n '''Returns a pandas dataframe with pnl data, indexed by date'''\n df = pd.DataFrame({'date' : self.dates, 'unrealized' : self.unrealized, 'realized' : self.realized, \n 'fee' : self.fee, 'net_pnl' : self.net_pnl, 'position' : self.position})\n df.dropna(subset = ['unrealized', 'realized'], inplace = True)\n df['symbol'] = self.symbol\n return df[['symbol', 'date', 'unrealized', 'realized', 'fee', 'net_pnl', 'position']].set_index('date')\n \nclass Contract:\n '''A Contract can be a real or virtual instrument. For example, for futures you may wish to create a single continous contract instead of\n a contract for each future series\n '''\n def __init__(self, symbol, marketdata, multiplier = 1.):\n '''\n Args:\n symbol: A unique string reprenting this contract. e.g IBM or WTI_FUTURE\n multiplier: If you have to multiply price to get price per contract, set that multiplier there.\n marketdata: A MarketData object containing prices for this contract.\n '''\n assert(isinstance(symbol, str) and len(symbol) > 0)\n assert(multiplier > 0)\n self.symbol = symbol\n self.multiplier = multiplier\n self.marketdata = marketdata\n\nclass Account:\n '''An Account calculates pnl for a set of contracts'''\n def __init__(self, contracts, starting_equity = 1.0e6, calc_frequency = 'D'):\n '''\n Args:\n contracts: A list of Contract objects\n starting_equity: Starting equity in account currency. Default 1.e6\n calc_frequency: Account will calculate pnl at this frequency. Default 'D' for daily\n '''\n if calc_frequency != 'D': raise Exception('unknown calc frequency: {}'.format(calc_frequency))\n self.calc_freq = calc_frequency\n self.contract_pnls = defaultdict()\n self.current_calc_index = 0\n self.marketdata = {}\n self.all_dates = None\n self.starting_equity = starting_equity\n if len(contracts) == 0:\n raise Exception('must add at least one contract')\n for contract in contracts: \n self.add_contract(contract)\n \n def _set_dates(self, dates):\n if self.all_dates is not None and not np.array_equal(dates, all_dates):\n raise Exception('all symbols in a strategy must have the same dates')\n self.all_dates = dates\n calc_dates = dates.astype('M8[D]')\n self.calc_dates = np.unique(calc_dates)\n self.calc_indices = np.searchsorted(dates, self.calc_dates, side='left') - 1\n if self.calc_indices[0] == -1: self.calc_indices[0] = 0\n self._equity = np.empty(len(dates), np.float) * np.nan; \n self._equity[0] = self.starting_equity\n \n def symbols(self):\n return list(self.contract_pnls.keys())\n \n def add_contract(self, contract):\n if self.all_dates is None: self._set_dates(contract.marketdata.dates)\n self.contract_pnls[contract.symbol] = ContractPNL(contract)\n self.marketdata[contract.symbol] = contract.marketdata\n \n def _add_trades(self, symbol, trades):\n self.contract_pnls[symbol].add_trades(trades)\n \n def calc(self, i):\n '''\n Computes P&L and stores it internally for all contracts.\n \n Args:\n i: Index to compute P&L at. Account remembers the last index it computed P&L up to and will compute P&L between these two indices\n '''\n calc_indices = self.calc_indices[:]\n if self.current_calc_index == i: return\n intermediate_calc_indices = np.ravel(np.where(np.logical_and(calc_indices > self.current_calc_index, calc_indices <= i)))\n\n if not len(intermediate_calc_indices) or calc_indices[intermediate_calc_indices[-1]] != i: \n calc_indices = np.append(calc_indices, i)\n intermediate_calc_indices = np.append(intermediate_calc_indices, len(calc_indices) - 1)\n \n for symbol, symbol_pnl in self.contract_pnls.items():\n prev_calc_index = self.current_calc_index\n for idx in intermediate_calc_indices:\n calc_index = calc_indices[idx]\n symbol_pnl.calc(prev_calc_index, calc_index)\n self._equity[calc_index] = self._equity[prev_calc_index] + symbol_pnl.net_pnl[calc_index] - symbol_pnl.net_pnl[prev_calc_index]\n #print(f'prev_calc_index: {prev_calc_index} calc_index: {calc_index} prev_equity: {self._equity[prev_calc_index]} net_pnl: {symbol_pnl.net_pnl[calc_index]} prev_net_pnl: {symbol_pnl.net_pnl[prev_calc_index]}')\n prev_calc_index = calc_index\n \n self.current_calc_index = i\n \n def position(self, symbol, date):\n '''Returns position for a symbol at a given date in number of contracts or shares. Will cause calculation if Account has not previously calculated\n up to this date'''\n i = self.find_index_before(date)\n self.calc(i)\n return self.contract_pnls[symbol].position[i]\n \n def equity(self, date):\n '''Returns equity in this account in Account currency. Will cause calculation if Account has not previously calculated up to this date'''\n i = self.find_index_before(date)\n self.calc(i)\n return self._equity[i]\n \n def trades(self, symbol = None, start_date = None, end_date = None):\n '''Returns a list of trades with the given symbol and with trade date between (and including) start date and end date if they are specified.\n If symbol is None trades for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n if symbol is None:\n trades = []\n for symbol, sym_pnl in self.contract_pnls.items():\n trades += sym_pnl.trades(start_date, end_date)\n return trades\n else:\n return self.contract_pnls[symbol].trades(start_date, end_date)\n \n def find_index_before(self, date):\n '''Returns the market data index before or at date'''\n return np.searchsorted(self.all_dates, date)\n \n def transfer_cash(self, date, amount):\n '''Move cash from one portfolio to another'''\n i = self.find_index_before(date)\n curr_equity = self.equity(date)\n if (amount > curr_equity): amount = curr_equity # Cannot make equity negative\n self._equity[i] -= amount\n return amount\n\n def df_pnl(self, symbol = None):\n '''Returns a dataframe with P&L columns. If symbol is set to None (default), sums up P&L across symbols'''\n if symbol:\n ret = self.contract_pnls[symbol].df()\n else:\n dfs = []\n for symbol, symbol_pnl in self.contract_pnls.items():\n df = symbol_pnl.df()\n dfs.append(df)\n ret = pd.concat(dfs)\n ret = ret.reset_index().groupby('date').sum()\n df_equity = pd.DataFrame({'equity' : self._equity}, index = self.all_dates).dropna()\n ret = pd.merge(ret, df_equity, left_index = True, right_index = True, how = 'outer')\n ret.index.name = 'date'\n return ret\n \n def df_trades(self, symbol = None, start_date = None, end_date = None):\n '''Returns a dataframe with data from trades with the given symbol and with trade date between (and including) start date and end date\n if they are specified. If symbol is None, trades for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n if symbol:\n trades = self.contract_pnls[symbol].trades(start_date, end_date)\n else:\n trades = [v.trades(start_date, end_date) for v in self.contract_pnls.values()]\n trades = [trade for sublist in trades for trade in sublist] # flatten list\n df = pd.DataFrame.from_records([(trade.symbol, trade.date, trade.qty, trade.price, trade.fee, trade.commission, trade.order.date, trade.order.qty, trade.order.params()) for trade in trades],\n columns = ['symbol', 'date', 'qty', 'price', 'fee', 'commission', 'order_date', 'order_qty', 'order_params'])\n return df\n \nclass Strategy:\n def __init__(self, contracts, starting_equity = 1.0e6, calc_frequency = 'D'):\n '''\n Args:\n contracts: A list of contract objects\n starting_equity: Starting equity in Strategy currency. Default 1.e6\n calc_frequency: How often P&L is calculated. Default is 'D' for daily\n '''\n self.name = None\n self.account = Account(contracts, starting_equity, calc_frequency)\n self.symbols = [contract.symbol for contract in contracts]\n self.indicators = {}\n self.indicator_values = defaultdict(dict)\n self.signals = {}\n self.signal_values = defaultdict(dict)\n self.rules = {}\n self.rule_signals = {}\n self.market_sims = {}\n self._trades = defaultdict(list)\n self._orders = []\n self.dates = self.account.all_dates\n \n def add_indicator(self, name, indicator_function):\n '''\n Args:\n name: Name of the indicator\n indicator_function: A function taking a MarketData object and returning a numpy array\n containing indicator values. The return array must have the same length as the MarketData object\n '''\n self.indicators[name] = indicator_function\n \n def add_signal(self, name, signal_function):\n '''\n Args:\n name: Name of the signal\n signal_function: A function taking a MarketData object and a dictionary of indicator value arrays as input and returning a numpy array\n containing signal values. The return array must have the same length as the MarketData object\n '''\n self.signals[name] = signal_function\n \n def add_rule(self, name, rule_function, signal_name, sig_true_values):\n '''Add a trading rule\n \n Args:\n name: Name of the trading rule\n rule_function: A trading rule function that returns a list of Orders\n signal_name: The strategy will call the trading rule function when the signal with this name matches sig_true_values\n sig_true_values: A numpy array of values. If the signal value at a bar is equal to one of these, the Strategy will call the trading rule function\n '''\n self.rule_signals[name] = (signal_name, sig_true_values)\n self.rules[name] = rule_function\n \n def add_market_sim(self, market_sim_function, symbols = None):\n '''Add a market simulator. A market simulator takes a list of Orders as input and returns a list of Trade objects.\n \n Args:\n market_sim_function: A function that takes a list of Orders and MarketData as input and returns a list of Trade objects\n symbols: A list of the symbols that this market_sim_function applies to. If None (default) it will apply to all symbols\n '''\n if symbols is None: symbols = self.symbols\n for symbol in symbols: self.market_sims[symbol] = market_sim_function\n \n def run_indicators(self, indicator_names = None, symbols = None):\n '''Calculate values of the indicators specified and store them.\n \n Args:\n indicator_names: List of indicator names. If None (default) run all indicators\n symbols: List of symbols to run these indicators for. If None (default) use all symbols\n '''\n if indicator_names is None: indicator_names = self.indicators.keys()\n if symbols is None: symbols = self.symbols\n \n for indicator_name in indicator_names:\n indicator_function = self.indicators[indicator_name]\n for symbol in symbols:\n marketdata = self.account.marketdata[symbol]\n self.indicator_values[symbol][indicator_name] = series_to_array(indicator_function(marketdata))\n \n def run_signals(self, signal_names = None, symbols = None):\n '''Calculate values of the signals specified and store them.\n \n Args:\n signal_names: List of signal names. If None (default) run all signals\n symbols: List of symbols to run these signals for. If None (default) use all symbols\n '''\n if signal_names is None: signal_names = self.signals.keys()\n if symbols is None: symbols = self.symbols\n \n for signal_name in signal_names:\n signal_function = self.signals[signal_name]\n for symbol in symbols:\n marketdata = self.account.marketdata[symbol]\n self.signal_values[symbol][signal_name] = series_to_array(signal_function(marketdata, self.indicator_values[symbol]))\n \n def run_rules(self, rule_names = None, symbols = None, start_date = None, end_date = None, run_first = False, run_last = True):\n '''Run trading rules.\n \n Args:\n rule_names: List of rule names. If None (default) run all rules\n symbols: List of symbols to run these signals for. If None (default) use all symbols\n start_date: Run rules starting from this date. Default None \n end_date: Don't run rules after this date. Default None\n run_first: Force running rules on the first bar even if signals do not require this. Default False\n run_last: Force running rules on penultimate bar even if signals do not require this. \n '''\n start_date, end_date = str2date(start_date), str2date(end_date)\n dates, iterations = self._get_iteration_indices(rule_names, symbols, start_date, end_date, run_first, run_last)\n # Now we know which rules, symbols need to be applied for each iteration, go through each iteration and apply them\n # in the same order they were added to the strategy\n for i, tup_list in enumerate(iterations):\n self._iterate(i, tup_list)\n \n def _get_iteration_indices(self, rule_names = None, symbols = None, start_date = None, end_date = None, \n run_first = False, run_last = True):\n start_date, end_date = str2date(start_date), str2date(end_date)\n if rule_names is None: rule_names = self.rules.keys()\n if symbols is None: symbols = self.symbols\n \n dates = self.dates\n num_dates = len(dates)\n \n iterations = [[] for x in range(num_dates)]\n self.orders_iter = [[] for x in range(num_dates)]\n \n for rule_name in rule_names:\n rule_function = self.rules[rule_name]\n for symbol in symbols:\n marketdata = self.account.marketdata[symbol]\n market_sim = self.market_sims[symbol]\n signal_name = self.rule_signals[rule_name][0]\n sig_true_values = self.rule_signals[rule_name][1]\n sig_values = self.signal_values[symbol][signal_name]\n dates = marketdata.dates\n null_value = False if sig_values.dtype == np.dtype('bool') else np.nan\n if start_date: sig_values[0:np.searchsorted(dates, start_date)] = null_value\n if end_date: sig_values[np.searchsorted(dates, end_date):] = null_value\n indices = np.nonzero(np.isin(sig_values, sig_true_values))[0]\n if indices[-1] == len(sig_values) -1: indices = indices[:-1] # Don't run rules on last index since we cannot fill any orders\n if run_first and indices[0] != 0: indices = np.insert(indices, 0, 0)\n if run_last and indices[-1] != len(sig_values) - 2: indices = np.append(indices, len(sig_values) - 2)\n indicator_values = self.indicator_values[symbol]\n iteration_params = {'market_sim' : market_sim, 'indicator_values' : indicator_values, 'signal_values' : sig_values, 'marketdata' : marketdata}\n for idx in indices: iterations[idx].append((rule_function, symbol, iteration_params))\n \n self.iterations = iterations # For debugging\n \n return self.dates, iterations\n \n def _iterate(self, i, tup_list):\n for tup in self.orders_iter[i]:\n try:\n open_orders, symbol, params = tup\n open_orders = self._sim_market(i, open_orders, symbol, params)\n if len(open_orders): self.orders_iter[i + 1].append((open_orders, symbol, params))\n except Exception as e:\n raise type(e)(f'Exception: {str(e)} at rule: {type(tup[0])} symbol: {tup[1]} index: {i}').with_traceback(sys.exc_info()[2])\n \n for tup in tup_list:\n try:\n rule_function, symbol, params = tup\n open_orders = self._get_orders(i, rule_function, symbol, params)\n self._orders += open_orders\n if len(open_orders): self.orders_iter[i + 1].append((open_orders, symbol, params))\n except Exception as e:\n raise type(e)(f'Exception: {str(e)} at rule: {type(tup[0])} symbol: {tup[1]} index: {i}').with_traceback(sys.exc_info()[2])\n \n def _get_orders(self, idx, rule_function, symbol, params):\n indicator_values, signal_values, marketdata = (params['indicator_values'], params['signal_values'], params['marketdata'])\n open_orders = rule_function(self, symbol, idx, self.dates[idx], marketdata, indicator_values, signal_values, self.account)\n return open_orders\n \n def _sim_market(self, idx, open_orders, symbol, params):\n '''\n Keep iterating while we have open orders since they may get filled\n TODO: For limit orders and trigger orders we can be smarter here and reduce indices like quantstrat does\n '''\n market_sim_function = params['market_sim']\n trades = market_sim_function(self, open_orders, idx, self.dates[idx], self.account.marketdata[symbol])\n if len(trades) == 0: return []\n self._trades[symbol] += trades\n self.account._add_trades(symbol, trades)\n self.account.calc(idx)\n open_orders = [order for order in open_orders if order.status == 'open']\n return open_orders\n \n def df_data(self, symbols = None, add_pnl = True, start_date = None, end_date = None):\n '''\n Add indicators and signals to end of market data and return as a pandas dataframe.\n \n Args:\n symbols: list of symbols to include. All if set to None (default)\n add_pnl: If True (default), include P&L columns in dataframe\n start_date: string or numpy datetime64. Default None\n end_date: string or numpy datetime64: Default None\n '''\n start_date, end_date = str2date(start_date), str2date(end_date)\n if symbols is None: symbols = self.symbols\n if not isinstance(symbols, list): symbols = [symbols]\n \n mds = []\n \n for symbol in symbols:\n md = self.account.marketdata[symbol].df(start_date, end_date)\n \n md.insert(0, 'symbol', symbol)\n if add_pnl: \n df_pnl = self.account.df_pnl(symbol)\n del df_pnl['symbol']\n\n indicator_values = self.indicator_values[symbol]\n\n for k in sorted(indicator_values.keys()):\n name = k\n if name in md.columns: name = name + '.ind' # if we have a market data column with the same name as the indicator\n md.insert(len(md.columns), name, indicator_values[k])\n\n signal_values = self.signal_values[symbol]\n\n for k in sorted(signal_values.keys()):\n name = k\n if name in md.columns: name = name + '.sig'\n md.insert(len(md.columns), name, signal_values[k])\n \n if add_pnl: md = pd.merge(md, df_pnl, left_index = True, right_index = True, how = 'left')\n # Add counter column for debugging\n md.insert(len(md.columns), 'i', np.arange(len(md)))\n \n mds.append(md)\n \n return pd.concat(mds)\n \n def marketdata(self, symbol):\n '''Return MarketData object for this symbol'''\n return self.account.marketdata[symbol]\n \n def trades(self, symbol = None, start_date = None, end_date = None):\n '''Returns a list of trades with the given symbol and with trade date between (and including) start date and end date if they are specified.\n If symbol is None trades for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n return self.account.trades(symbol, start_date, end_date)\n \n def df_trades(self, symbol = None, start_date = None, end_date = None):\n '''Returns a dataframe with data from trades with the given symbol and with trade date between (and including) start date and end date\n if they are specified. If symbol is None, trades for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n return self.account.df_trades(symbol, start_date, end_date)\n \n def orders(self, symbol = None, start_date = None, end_date = None):\n '''Returns a list of orders with the given symbol and with order date between (and including) start date and end date if they are specified.\n If symbol is None orders for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n return [order for order in self._orders if (symbol is None or order.symbol == symbol) and (\n start_date is None or order.date >= start_date) and (end_date is None or order.date <= end_date)]\n \n def df_orders(self, symbol = None, start_date = None, end_date = None):\n '''Returns a dataframe with data from orders with the given symbol and with order date between (and including) start date and end date\n if they are specified. If symbol is None, orders for all symbols are returned'''\n start_date, end_date = str2date(start_date), str2date(end_date)\n orders = self.orders(symbol, start_date, end_date)\n df_orders = pd.DataFrame.from_records([(order.symbol, type(order).__name__, order.date, order.qty, order.params()) \n for order in orders], columns = ['symbol', 'type', 'date', 'qty', 'params'])\n return df_orders\n \n def df_pnl(self, symbol = None):\n '''Returns a dataframe with P&L columns. If symbol is set to None (default), sums up P&L across symbols'''\n return self.account.df_pnl(symbol)\n \n def df_returns(self, symbol = None, sampling_frequency = 'D'):\n '''Return a dataframe of returns and equity indexed by date.\n \n Args:\n symbol: The symbol to get returns for. If set to None (default), this returns the sum of PNL for all symbols\n sampling_frequency: Downsampling frequency. Default is None. See pandas frequency strings for possible values\n '''\n pnl = self.df_pnl(symbol)[['equity']]\n pnl.equity = pnl.equity.ffill()\n pnl = pnl.resample(sampling_frequency).last()\n pnl['ret'] = pnl.equity.pct_change()\n return pnl\n \n def plot(self, symbols = None, md_columns = 'c', pnl_columns = 'equity', title = None, figsize = (20, 15), date_range = None, \n date_format = None, sampling_frequency = None, trade_marker_properties = None, hspace = 0.15):\n \n '''Plot indicators, signals, trades, position, pnl\n \n Args:\n symbols: List of symbols or None (default) for all symbols\n md_columns: List of columns of market data to plot. Default is 'c' for close price. You can set this to 'ohlcv' if you want to plot\n a candlestick of OHLCV data\n pnl_columns: List of P&L columns to plot. Default is 'equity'\n title: Title of plot (None)\n figsize: Figure size. Default is (20, 15)\n date_range: Tuple of strings or datetime64, e.g. (\"2018-01-01\", \"2018-04-18 15:00\") to restrict the graph. Default None\n date_format: Date format for tick labels on x axis. If set to None (default), will be selected based on date range. See matplotlib date format strings\n sampling_frequency: Downsampling frequency. Default is None. The graph may get too busy if you have too many bars of data, in which case you may want to \n downsample before plotting. See pandas frequency strings for possible values\n trade_marker_properties: A dictionary of order reason code -> marker shape, marker size, marker color for plotting trades with different reason codes.\n Default is None in which case the dictionary from the ReasonCode class is used\n hspace: Height (vertical) space between subplots. Default is 0.15\n '''\n date_range = strtup2date(date_range)\n if symbols is None: symbols = self.symbols\n if not isinstance(symbols, list): symbols = [symbols]\n if not isinstance(md_columns, list): md_columns = [md_columns]\n if not isinstance(pnl_columns, list): pnl_columns = [pnl_columns]\n for symbol in symbols:\n md = self.marketdata(symbol)\n md_dates = md.dates\n if md_columns == ['ohlcv']:\n md_list = [OHLC('price', dates = md_dates, o = md.o, h = md.h, l = md.l, c = md.c, v = md.v)]\n else:\n md_list = [TimeSeries(md_column, dates = md_dates, values = getattr(md, md_column)) for md_column in md_columns]\n indicator_list = [TimeSeries(indicator_name, dates = md_dates, values = self.indicator_values[symbol][indicator_name], line_type = '--'\n ) for indicator_name in self.indicators.keys() if indicator_name in self.indicator_values[symbol]]\n signal_list = [TimeSeries(signal_name, dates = md_dates, values = self.signal_values[symbol][signal_name]\n ) for signal_name in self.signals.keys() if signal_name in self.signal_values[symbol]]\n df_pnl_ = self.df_pnl(symbol)\n pnl_list = [TimeSeries(pnl_column, dates = df_pnl_.index.values, values = df_pnl_[pnl_column].values) for pnl_column in pnl_columns]\n if trade_marker_properties:\n trade_sets = trade_sets_by_reason_code(self._trades[symbol], trade_marker_properties)\n else:\n trade_sets = trade_sets_by_reason_code(self._trades[symbol])\n main_subplot = Subplot(indicator_list + md_list + trade_sets, height_ratio = 0.5, ylabel = 'Indicators')\n signal_subplot = Subplot(signal_list, ylabel = 'Signals', height_ratio = 0.167)\n pnl_subplot = Subplot(pnl_list, ylabel = 'Equity', height_ratio = 0.167, log_y = True, y_tick_format = '${x:,.0f}')\n position = df_pnl_.position.values\n pos_subplot = Subplot([TimeSeries('position', dates = df_pnl_.index.values, values = position, plot_type = 'filled_line')], \n ylabel = 'Position', height_ratio = 0.167)\n plot = Plot([main_subplot, signal_subplot, pos_subplot, pnl_subplot], figsize = figsize,\n date_range = date_range, date_format = date_format, sampling_frequency = sampling_frequency, title = title, hspace = hspace)\n plot.draw()\n \n def evaluate_returns(self, symbol = None, plot = True, float_precision = 4):\n '''Returns a dictionary of common return metrics.\n \n Args:\n sampling_frequency: Date frequency. Default 'D' for daily so we downsample to daily returns before computing metrics\n strategy_names: A list of strategy names. By default this is set to None and we use all strategies.\n plot: If set to True, display plots of equity, drawdowns and returns. Default False\n float_precision: Number of significant figures to show in returns. Default 4\n '''\n returns = self.df_returns(symbol)\n ev = compute_return_metrics(returns.index.values, returns.ret.values, self.account.starting_equity)\n display_return_metrics(ev.metrics(), float_precision = float_precision)\n if plot: plot_return_metrics(ev.metrics())\n return ev.metrics()\n \n def plot_returns(self, symbol = None):\n '''Display plots of equity, drawdowns and returns for the given symbol or for all symbols if symbol is None (default)'''\n if symbol is None:\n symbols = self.symbols()\n else:\n symbols = [symbol]\n \n df_list = []\n \n for symbol in symbols:\n df_list.append(self.df_returns(symbol))\n \n df = pd.concat(df_list, axis = 1)\n \n ev = compute_return_metrics(returns.index.values, returns.ret.values, self.account.starting_equity)\n plot_return_metrics(ev.metrics())\n \n def __repr__(self):\n return f'{pformat(self.indicators)} {pformat(self.rules)} {pformat(self.account)}'\n\ndef test_strategy(): \n from datetime import datetime, timedelta\n \n set_defaults()\n\n def sim_order(order, i, date, md):\n symbol = order.symbol\n trade_price = np.nan\n skid_fraction = 0.5\n \n if not md.valid_row(i): return None\n \n if isinstance(order, MarketOrder):\n if order.qty > 0:\n trade_price = 0.5 * (md.c[i] + md.h[i])\n else:\n trade_price = 0.5 * (md.c[i] + md.l[i])\n elif order.qty > 0 and md.h[i] > order.trigger_price:\n trade_price = skid_fraction * max(md.o[i], order.trigger_price, md.l[i]) + (1 - skid_fraction) * md.h[i]\n elif order.qty < 0 and md.l[i] < order.trigger_price:\n trade_price = skid_fraction * min(md.o[i], order.trigger_price, md.h[i]) + (1 - skid_fraction) * md.l[i]\n else:\n return None\n sim_trade = Trade(symbol, date, order.qty, trade_price, order = order)\n return sim_trade\n \n def market_simulator(strategy, orders, i, date, marketdata):\n trades = []\n for order in orders:\n sim_trade = sim_order(order, i, date, marketdata)\n if sim_trade is None: continue\n if math.isclose(sim_trade.qty, order.qty): order.status = 'filled'\n\n trades.append(sim_trade)\n return trades\n \n def trade_rule(strategy, symbol, i, date, marketdata, indicator_values, signal_values, account):\n heat = 0.05\n reason_code = None\n \n if not marketdata.valid_row(i): return []\n \n curr_pos = account.position(symbol, date)\n \n if i == len(marketdata.dates) - 2: # Last date so get out of position\n if not math.isclose(curr_pos, 0): \n return [MarketOrder(symbol, date, -curr_pos, reason_code = ReasonCode.BACKTEST_END)]\n else:\n return []\n \n trend = signal_values[i]\n fast_resistance, fast_support, slow_resistance, slow_support = (indicator_values['fast_resistance'][i], \n indicator_values['fast_support'][i], indicator_values['slow_resistance'][i], indicator_values['slow_support'][i])\n \n if trend == 1:\n entry_limit = fast_resistance\n stop_limit = fast_support\n elif trend == -1:\n entry_limit = fast_support\n stop_limit = fast_resistance\n else:\n return []\n\n if math.isclose(curr_pos, 0): # We got a trade in the previous bar so put in a stop limit order\n if math.isclose(entry_limit, stop_limit): return []\n curr_equity = account.equity(date)\n order_qty = curr_equity * heat / (entry_limit - stop_limit)\n trigger_price = entry_limit\n reason_code = ReasonCode.ENTER_LONG if order_qty > 0 else ReasonCode.ENTER_SHORT\n else:\n order_qty = -curr_pos\n trigger_price = stop_limit\n reason_code = ReasonCode.EXIT_LONG if order_qty < 0 else ReasonCode.EXIT_SHORT\n \n order_qty = round(order_qty)\n \n if np.isnan(order_qty):\n raise Exception(f'Got nan order qty date: {date} i: {i} curr_pos: {curr_pos} curr_equity: {curr_equity} entry_limit: {entry_limit} stop_limit: {stop_limit}')\n \n if math.isclose(order_qty, 0): return []\n \n order = StopLimitOrder(symbol, date, order_qty, trigger_price, reason_code = reason_code)\n \n return [order]\n \n def get_support(lows, n): return pd.Series(lows).rolling(window = n, min_periods = 1).min().values\n\n def get_resistance(highs, n): return pd.Series(highs).rolling(window = n, min_periods = 1).max().values\n \n def get_trend(md, ind):\n trend = pd.Series(np.where(pd.Series(md.h) > shift_np(ind['slow_resistance'], 1), 1, \n np.where(pd.Series(md.l) < shift_np(ind['slow_support'], 1), -1, \n np.nan)))\n trend.fillna(method = 'ffill', inplace = True)\n return trend.values\n \n def build_strategy(contract, fast_interval, slow_interval):\n strategy = Strategy([contract])\n strategy.add_indicator('slow_resistance', lambda md : get_resistance(md.h, slow_interval))\n strategy.add_indicator('slow_support', lambda md : get_support(md.l, slow_interval))\n strategy.add_indicator('fast_resistance', lambda md : get_resistance(md.h, fast_interval))\n strategy.add_indicator('fast_support', lambda md : get_support(md.l, fast_interval))\n strategy.add_signal('trend', get_trend)\n strategy.add_market_sim(market_simulator)\n strategy.add_rule('trade_rule', trade_rule, 'trend', np.array([-1, 1]))\n return strategy\n \n np.random.seed(0)\n dates = np.arange(datetime(2018, 1, 1, 9, 0, 0), datetime(2018, 3, 1, 16, 0, 0), timedelta(minutes = 5))\n dates = np.array([dt for dt in dates.astype(object) if dt.hour >= 9 and dt.hour <= 16]).astype('M8[m]')\n rets = np.random.normal(size = len(dates)) / 1000\n c_0 = 100\n c = np.round(c_0 * np.cumprod(1 + rets), 2)\n l = np.round(c * (1. - np.abs(np.random.random(size = len(dates)) / 1000.)), 2)\n h = np.round(c * (1. + np.abs(np.random.random(size = len(dates)) / 1000.)), 2)\n o = np.round(l + (h - l) * np.random.random(size = len(dates)), 2)\n v = np.round(np.random.normal(size = len(dates)) * 100)\n \n portfolio = Portfolio()\n \n slow_interval = 0\n \n for days in [0.5, 1, 2]:\n # 1 day from 9 - 4 pm has 7 hours which translate to 7 x 12 = 84 5 minute periods\n fast_interval = round(days * 84) \n slow_interval = round(5 * fast_interval)\n contract = Contract('IBM', MarketData(dates, c, o, h, l, v))\n portfolio.add_strategy(f'strat_{days}', build_strategy(contract, fast_interval, slow_interval))\n \n # Start at max slow days so all strategies start at the same time\n print('running')\n portfolio.run(start_date = dates[slow_interval])\n print('done')\n \n strat1 = portfolio.strategies['strat_0.5']\n portfolio.plot();\n strat1.plot();\n \nif __name__ == \"__main__\":\n test_strategy()\n\n","sub_path":"pyqstrat/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":50531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"510322732","text":"import itertools\nimport os\nimport shutil\nimport tarfile\nfrom urllib import request\nimport zipfile\n\n\nREG = 'Regression'\nBINARY_CLF = 'Binary'\nMULTI_CLF = 'Multiclass'\nMO_BINARY_CLF = 'Multi-output binary'\n\ndef get_data_home(data_home: str = None):\n \"\"\"Return the path of the creme data directory.\n\n By default this will expand the relative path '~/creme_data'.\n\n \"\"\"\n\n if data_home is None:\n data_home = os.environ.get('CREME_DATA', os.path.join('~', 'creme_data'))\n data_home = os.path.expanduser(data_home)\n if not os.path.exists(data_home):\n os.makedirs(data_home)\n return data_home\n\n\ndef download_dataset(url: str, data_home: str, uncompress=True, verbose=True) -> str:\n \"\"\"Downloads/decompresses a dataset locally if does not exist.\n\n Parameters:\n url: From where to download the dataset.\n data_home: The directory where you wish to store the data.\n uncompress: Whether to uncompress the file or not.\n verbose: Whether to indicate download progress or not.\n\n Returns:\n data_dir_path: The dataset's storage location?\n\n \"\"\"\n\n def _print(msg):\n if verbose:\n print(msg)\n\n name = os.path.basename(url)\n extension = '.'.join(name.split('.')[1:])\n data_home = get_data_home(data_home=data_home)\n path = os.path.join(data_home, f'{name}')\n archive_path = path\n if extension:\n path = path[:-(len(extension) + 1)] # e.g. path/to/file.tar.gz becomes path/to/file\n\n # Download if necessary\n if not (os.path.exists(path) or os.path.exists(archive_path)):\n\n _print(f'Downloading {url}')\n with request.urlopen(url) as r, open(archive_path, 'wb') as f:\n shutil.copyfileobj(r, f)\n\n # If no uncompression is required then we're done\n if not uncompress:\n return archive_path\n\n # Uncompress if necessary\n if not os.path.exists(path):\n\n _print(f'Uncompressing into {path}')\n\n if extension.endswith('zip'):\n with zipfile.ZipFile(archive_path, 'r') as zf:\n zf.extractall(path)\n\n elif extension.endswith(('gz', 'tar')):\n mode = 'r:' if extension.endswith('tar') else 'r:gz'\n tar = tarfile.open(archive_path, mode)\n tar.extractall(path)\n tar.close()\n\n else:\n raise RuntimeError(f'Unhandled extension type: {extension}')\n\n # Delete the archive file now that the dataset is available\n os.remove(archive_path)\n\n return path\n\n\nclass Dataset:\n\n def __init__(self, n_features, category):\n self.n_features = n_features\n self.category = category\n\n def __iter__(self):\n raise NotImplementedError\n\n def take(self, k: int):\n \"\"\"Yields the k first (`x`, `y`) pairs.\"\"\"\n return itertools.islice(self, k)\n\n\nclass FileDataset(Dataset):\n\n def __init__(self, n_samples, n_features, category, **dl_params):\n super().__init__(n_features=n_features, category=category)\n self.n_samples = n_samples\n self.dl_params = dl_params\n\n def _stream_X_y(self, dir):\n raise NotImplementedError\n\n @property\n def _remote(self):\n \"\"\"Whether or not the dataset needs downloading or not.\"\"\"\n return 'url' in self.dl_params\n\n @property\n def _ready(self):\n \"\"\"Whether or not the dataset is ready to be read.\"\"\"\n if self._remote:\n return os.path.isdir(os.path.join(\n get_data_home(self.dl_params['data_home']),\n self.dl_params['name']\n ))\n return True\n\n def __iter__(self):\n if self._remote:\n data_dir_path = download_dataset(**self.dl_params)\n else:\n data_dir_path = os.path.dirname(__file__)\n yield from self._stream_X_y(data_dir_path)\n","sub_path":"creme/datasets/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"509578989","text":"\n# python 3 basic logging tutorial: https://docs.python.org/3/howto/logging.html\n\nimport logging\nimport os\n\nos.system(\"echo '' > test_logging.log\")\n\nlogging.basicConfig(filename='test_logging.log',level=logging.DEBUG)\n\nlogging.debug('this is a debug level message')\nlogger = logging.getLogger()\nlogger.debug('this is debug msg from logger')\nlogger.setLevel(logging.INFO)\nlogger.debug('this is debug msg from logger') # won't print since DEBUG < INFO level\nlogger.info('this is info msg from logger')\n\n\n# load logging config from file, which is more common for application coding\n\nfrom logging.config import fileConfig\n\nfileConfig('test_logging_config.ini')\nlogger = logging.getLogger()\nlogger.debug('hard to see through %s is', 'the future')\n","sub_path":"test_logging.py","file_name":"test_logging.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305570978","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 5 13:48:56 2021\n\n@author: janeyalex\n\"\"\"\nimport pandas as pd\nimport collections\n\n\nf = open(\"ulysses.txt\",'r')\nl1=[]\nl2=[]\nfor line in f:\n lineword=line.split(':')\n #if not lineword[0].isdigit():\n l1.append(lineword[0])\n l2.append(int(lineword[1])) \nf.close()\n\ndf = pd.DataFrame({'word': l1,'count':l2})\n\n# 5a\ntotalNumWords = df['count'].sum()\nuniqueWords =len(l2)\nfrac = uniqueWords/totalNumWords\n\nfreq= collections.Counter(l2)\n\n# 5b\nn1=freq[1]/sum(freq.values())\nn2=freq[2]/sum(freq.values())\nn3=freq[3]/sum(freq.values())","sub_path":"HW6q5.py","file_name":"HW6q5.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"55925178","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación,\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\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 withthis program. If not, see .\n *\n * Contribuciones:\n *\n * Dario Correal - Version inicial\n \"\"\"\n\n\nfrom DISClib.DataStructures.singlelinkedlist import addLast\nimport config as cf\nfrom DISClib.ADT import list as lt\nfrom DISClib.ADT.graph import gr\nfrom DISClib.ADT import map as mp\nfrom DISClib.DataStructures import mapentry as me\nfrom DISClib.Algorithms.Graphs import scc\nfrom DISClib.ADT import orderedmap as om\nfrom DISClib.Algorithms.Graphs import dijsktra as djk\nassert cf\n\n\"\"\"\nSe define la estructura de un catálogo de videos. El catálogo tendrá dos listas, una para los videos, otra para las categorias de\nlos mismos.\n\"\"\"\n\n# Construccion de modelos\ndef newAnalyzer():\n \"\"\" Inicializa el analizador\n\n landing: Tabla de hash para guardar los vertices del grafo\n connections: Grafo para representar las rutas entre landing points\n components: Almacena la informacion de los componentes conectados\n paths: Estructura que almancena los caminos de costo minimo desde un\n vertice determinado a todos los otros vértices del grafo\n \"\"\"\n analyzer = {\n 'landing': None,\n 'cableconections': None,\n 'countries': None,\n 'ids': None,\n 'countriesinfo': None,\n 'capitales': None,\n 'components': None,\n 'paths': None\n }\n\n analyzer['landing'] = mp.newMap(numelements=14000,\n maptype='PROBING')\n\n analyzer['countries'] = mp.newMap(numelements=14000,\n maptype='PROBING')\n\n analyzer['capitales'] = mp.newMap(numelements=14000,\n maptype='PROBING')\n \n analyzer['countriesinfo'] = mp.newMap(numelements=14000,\n maptype='PROBING')\n\n analyzer['ids'] = mp.newMap(numelements=14000,\n maptype='PROBING')\n\n analyzer['cableconections'] = gr.newGraph(datastructure='ADJ_LIST',\n directed=True,\n size=14000,\n comparefunction=compareVertex)\n return analyzer\n\n# Funciones para agregar informacion al catalogo\ndef addLandingPoint(analyzer, service):\n \"\"\"\n Adiciona los landing points al grafo como vertices y arcos entre los\n landing points adyacentes.\n\n Los vertices tienen por nombre el origen y destino\n seguido de el id del cable. Por ejemplo:\n\n 3316-2africa\n\n Si es un cable con una ruta diferente seria: 3316-africa-coast-to-europe-ace\n \"\"\"\n\n origin = \"<\" + service['\\ufefforigin'] + \"-\" + service['cable_id'] + \">\"\n destination = \"<\" + service['destination'] + \"-\" + service['cable_id'] + \">\"\n length = service['cable_length']\n if service['\\ufefforigin'] == service['destination']:\n length = '0.100 km'\n addGraph(analyzer, origin, destination, length)\n addCapital(analyzer, origin, destination, length)\n return analyzer\n\ndef addGraph(analyzer, origen, destino, length):\n if not gr.containsVertex(analyzer['cableconections'],origen):\n gr.insertVertex(analyzer['cableconections'],origen)\n if not gr.containsVertex(analyzer['cableconections'],destino):\n gr.insertVertex(analyzer['cableconections'],destino)\n edge = gr.getEdge(analyzer['cableconections'], origen, destino)\n if edge is None:\n gr.addEdge(analyzer['cableconections'],origen, destino, length)\n return analyzer\n\ndef addCapital(analyzer, origen, destino, length):\n if mp.get(analyzer['landing'], origen) is not None and mp.get(analyzer['landing'], destino) is not None:\n pais_origen = mp.get(analyzer['landing'], origen)['value']['pais']\n print(pais_origen)\n pais_destino= mp.get(analyzer['landing'], destino)['value']['pais']\n info_origen = {'pais': pais_origen,\n 'origen':lt.newList(),\n 'peso': length}\n info_destino = {'pais': pais_destino,\n 'origen':lt.newList(),\n 'peso': length}\n capital_origen = mp.get(analyzer['countriesinfo'], pais_origen)['value']['CapitalName'].lower().strip()\n capital_destino = mp.get(analyzer['countriesinfo'], pais_destino)['value']['CapitalName'].lower().strip()\n entry = mp.get(analyzer['capitales'], capital_origen)\n if entry is None:\n info_origen = {'pais': pais_origen,\n 'origen':lt.newList(),\n 'peso': length}\n mp.put(analyzer['capitales'], capital_origen, info_origen)\n lt.addLast(entry['value']['origen'], origen)\n if entry['value']['peso'] < length:\n entry['value']['peso'] = length\n \n entrada = mp.get(analyzer['capitales'], capital_destino)\n if entrada is None:\n info_destino = {'pais': pais_destino,\n 'origen':lt.newList(),\n 'peso': length}\n mp.put(analyzer['capitales'], capital_destino, info_destino)\n lt.addLast(entrada['value']['origen'], destino)\n if entrada['value']['peso'] < length:\n entrada['value']['peso'] = length\n\ndef conectarCapitales(analyzer):\n llaves = mp.keySet(analyzer['capitales'])\n for key in llaves:\n if mp.get(analyzer['capitales'], key) is not None:\n entry = mp.get(analyzer['capitales'], key)['value']\n for point in entry['origen']:\n if not gr.containsVertex(analyzer['cableconections'],key):\n gr.insertVertex(analyzer['cableconections'],key)\n edge = gr.getEdge(analyzer['cableconections'], key, point)\n if edge is None:\n gr.addEdge(analyzer['cableconections'],key, point, entry['peso'])\n edge1 = gr.getEdge(analyzer['cableconections'], point, key)\n if edge1 is None:\n gr.addEdge(analyzer['cableconections'],point, key, entry['peso'])\n\n #en otro mapa guardar los ids como llaves y como valor el string service[\"origin\"] y service[\"service[cable id\"]\n\n\ndef loadlandings(analyzer, landing):\n entry = mp.get(analyzer['landing'], landing['landing_point_id'])\n pais= landing['name'].split(\",\")\n if len(pais) == 1:\n info = pais[0].strip()\n else:\n info = pais[1].strip()\n idlanding = landing[\"landing_point_id\"]\n if entry is None:\n addinformacion = {'pais':info,\n 'informacion': landing}\n mp.put(analyzer['landing'], landing['landing_point_id'], addinformacion)\n addCountry(analyzer, info , idlanding)\n \ndef addCountry(analyzer, country, idlanding):\n paises = analyzer['countries']\n entry = mp.get(paises, country)\n if entry is None:\n lista = lt.newList()\n lt.addLast(lista, idlanding)\n mp.put(paises, country, lista)\n else:\n lt.addLast(entry['value'], idlanding)\n #para asegurarme que solo este agregando\n #lo cambie a un order map \n\ndef loadCountries(analyzer, country):\n entry = mp.get(analyzer['countriesinfo'], country['CountryName'].lower().strip())\n if entry is None:\n mp.put(analyzer['countriesinfo'], country['CountryName'].lower().strip(), country)\n return analyzer\n\n\n# Funciones para creacion de datos\n\n# Funciones de consulta\n\ndef connected(analyzer):\n \"\"\"\n Calcula los componentes conectados del grafo\n Se utiliza el algoritmo de Kosaraju\n \"\"\"\n analyzer['vertex'] = scc.KosarajuSCC(analyzer['cableconections'])\n return scc.connectedComponents(analyzer['vertex'])\n\ndef landingPoints(analyzer):\n \"\"\"\n Retorna el total de landing points (vertices) del grafo\n \"\"\"\n \n return gr.numVertices(analyzer['cableconections'])\n\n\n\n\ndef totalConnections(analyzer):\n \"\"\"\n Retorna el total arcos del grafo\n \"\"\"\n return gr.numEdges(analyzer['cableconections'])\n\ndef totalCountries(analyzer):\n return mp.size(analyzer['countries'])\n\ndef informacionLanding(analyzer):\n primero = mp.get(analyzer['landing'], '3316')\n informacion = primero['value']['informacion']\n return informacion\n\ndef informacionCountries(analyzer):\n primero = mp.get(analyzer['countriesinfo'], 'chuuk')\n informacion = primero['value']\n return informacion\n\ndef connectedComponents(analyzer):\n \"\"\"\n Calcula los componentes conectados del grafo\n Se utiliza el algoritmo de Kosaraju\n \"\"\"\n analyzer['components'] = scc.KosarajuSCC(analyzer['cableconections'])\n return scc.connectedComponents(analyzer['components'])\n\ndef sameCluster(analyzer, origen, destino):\n adyacentes = gr.adjacents(analyzer['cableconections'],origen)\n relacion = False\n if lt.isPresent(adyacentes, destino):\n relacion = True\n return relacion\n\ndef minimumCostPaths(analyzer, initialStation):\n \"\"\"\n Calcula los caminos de costo mínimo desde la estacion initialStation\n a todos los demas vertices del grafo\n \"\"\"\n analyzer['paths'] = djk.Dijkstra(analyzer['cableconections'], initialStation)\n return analyzer\n\ndef minimumPath(analyzer, origin, destination):\n \"\"\"\n Retorna el camino de costo minimo entre la estacion de inicio\n y la estacion destino\n Se debe ejecutar primero la funcion minimumCostPaths\n \"\"\"\n\n c1 = me.getValue(mp.get(analyzer['countriesinfo'], origin.lower()))['CapitalName']\n c2 = me.getValue(mp.get(analyzer['countriesinfo'], destination.lower()))['CapitalName']\n\n minimumCostPaths(analyzer, c1.lower().strip())\n path = djk.pathTo(analyzer['paths'], c2.lower().strip())\n return path\n\n\n\"\"\"\ndef sameCluster(analyzer, origen, destino):\n vertice1 = gr.containsVertex(analyzer['cableconections'], origen)\n vertice2 = gr.containsVertex(analyzer['cableconections'], destino)\n if vertice1 is False and vertice2 is False:\n return \"0\"\n elif vertice1 is False:\n return \"1\"\n elif vertice2 is False:\n return \"2\"\n else:\n return scc.stronglyConnected(analyzer['cableconections'], origen, destino)\n\"\"\"\n\n# Funciones utilizadas para comparar elementos dentro de una lista\ndef compareVertex(trip1,trip2):\n if (trip1 == trip2['key']):\n return 0\n elif (trip1 > trip2['key']):\n return 1\n else:\n return -1\n #compara las llaves\ndef compareCountries(c1,c2):\n if (c1 == c2):\n return 0\n elif (c1 > c2):\n return 1\n else:\n return -1\n\n# Funciones de ordenamiento\n","sub_path":"App/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"193604128","text":"\"\"\" CSS Style for the Div components\r\n@author: Olivier Nogues\r\n\r\n\"\"\"\r\n\r\nimport CssBase\r\n\r\nclass CssDivNoBorder(CssBase.CssCls):\r\n \"\"\" \"\"\"\r\n __style = [\r\n {'attr': 'margin', 'value': '0'},\r\n {'attr': 'padding', 'value': '0'},\r\n {'attr': 'border', 'value': '0'},\r\n {'attr': 'outline', 'value': 'none'},\r\n ]\r\n\r\n\r\nclass CsssDivBoxMargin(CssBase.CssCls):\r\n \"\"\" CSS Style for Div element with a 5 pixel margin \"\"\"\r\n __style = [\r\n {'attr': 'margin', 'value': '5px'},\r\n ]\r\n\r\n\r\nclass CsssDivWhitePage(CssBase.CssCls):\r\n \"\"\" CSS Style for Div element with a 5 pixel margin \"\"\"\r\n __style = [\r\n {'attr': 'border', 'value': '1px solid black'},\r\n {'attr': 'height', 'value': '80%'},\r\n {'attr': 'min-height', 'value': '600px'},\r\n {'attr': 'width', 'value': '400px'},\r\n {'attr': 'box-shadow', 'value': '10px 10px 8px 10px #888888'},\r\n ]\r\n\r\n\r\nclass CssDivBoxCenter(CssBase.CssCls):\r\n \"\"\" CSS Style for a standard Div item \"\"\"\r\n __style = [{'attr': 'width', 'value': '100%'},\r\n {'attr': 'text-align', 'value': 'center'}]\r\n\r\n\r\nclass CssDivBoxWithDotBorder(CssBase.CssCls):\r\n \"\"\" CSS Style for a Div item with a border with dots\"\"\"\r\n __style = [{'attr': 'margin', 'value': '5px'},\r\n {'attr': 'border', 'value': '1px dashed black;'}]\r\n\r\n\r\nclass CssDivBubble(CssBase.CssCls):\r\n \"\"\" \"\"\"\r\n __style = [\r\n {'attr': 'width', 'value': '100px'},\r\n {'attr': 'margin-left', 'value': 'auto'},\r\n {'attr': 'margin-right', 'value': 'auto'},\r\n {'attr': 'height', 'value': '100px'},\r\n {'attr': 'border-radius', 'value': '50%'},\r\n {'attr': 'padding-top', 'value': '30px'},\r\n {'attr': 'text-align', 'value': 'center'}\r\n ]\r\n\r\n\r\nclass CssDivBox(CssBase.CssCls):\r\n \"\"\" CSS Style for a standard Div item \"\"\"\r\n __style = [{'attr': 'width', 'value': '100%'},\r\n {'attr': 'overflow-x', 'value': 'auto'}]\r\n\r\n\r\nclass CssDivLeft(CssBase.CssCls):\r\n \"\"\" CSS Style for a box located on the left \"\"\"\r\n __style = [{'attr': 'float', 'value': 'left'},\r\n {'attr': 'width', 'value': '20%'}]\r\n\r\n\r\nclass CssDivRight(CssBase.CssCls):\r\n \"\"\" CSS Style for a box located on the right \"\"\"\r\n __style = [{'attr': 'float', 'value': 'right'},\r\n {'attr': 'width', 'value': '80%'}]\r\n\r\n\r\nclass CssDivBorder(CssBase.CssCls):\r\n \"\"\" CSS Style for a div element with a black border \"\"\"\r\n __style = [{'attr': 'border', 'value': '1px solid black'}]\r\n\r\n\r\nclass CssDivShadow(CssBase.CssCls):\r\n \"\"\" CSS Style for a div element with a black border \"\"\"\r\n __style = [{'attr': 'box-shadow', 'value': '10px 10px 8px 10px #888888'}]\r\n\r\n\r\nclass CssDivWhitePage(CssBase.CssCls):\r\n \"\"\" CSS Style for a div white page \"\"\"\r\n reqCss = [CssDivShadow, CssDivBorder]\r\n __style = [{'attr': 'height', 'value': '80%'},\r\n {'attr': 'min-height', 'value': '600px'},\r\n {'attr': 'width', 'value': '400px'},\r\n {'attr': 'background-color', 'value': 'white'}\r\n ]\r\n\r\n\r\nclass CssDivBanner(CssBase.CssCls):\r\n \"\"\" CSS Style for the Index Banner \"\"\"\r\n __style = [{'attr': 'height', 'value': '400px'},\r\n {'attr': 'width', 'value': '100%'},\r\n {'attr': 'margin', 'value': '0'},\r\n {'attr': 'overflow-y', 'value': 'auto'},\r\n {'attr': 'margin-top', 'value': '50px'},\r\n {'attr': 'background', 'value': 'linear-gradient(#292B2C, #29b229)'},\r\n {'attr': 'padding', 'value': '10px'},\r\n {'attr': 'color', 'value': 'white'}]\r\n\r\n\r\nclass CssDivSubBanner(CssBase.CssCls):\r\n \"\"\" CSS Style for the Index Banner \"\"\"\r\n __style = [{'attr': 'height', 'value': '400px'},\r\n {'attr': 'width', 'value': '100%'},\r\n {'attr': 'margin', 'value': '0'},\r\n {'attr': 'overflow-y', 'value': 'auto'},\r\n {'attr': 'margin-top', 'value': '50px'},\r\n {'attr': 'background', 'value': 'white'}, ##a4dba4\r\n {'attr': 'padding', 'value': '0'},\r\n {'attr': 'color', 'value': 'black'}]\r\n\r\n\r\nclass CssDivLabelPoint(CssBase.CssCls):\r\n \"\"\" \"\"\"\r\n __style = [\r\n {'attr': 'background', 'value': '#292B2C'},\r\n {'attr': 'padding', 'value': '10px'},\r\n {'attr': 'margin-left', 'value': '5px'},\r\n {'attr': 'border-radius', 'value': '50%'},\r\n {'attr': 'cursor', 'value': 'pointer'},\r\n {'attr': 'display', 'value': 'inline-block'},\r\n ]\r\n chidrenTag = 'label'\r\n\r\n\r\nclass CssDivBox(CssBase.CssCls):\r\n \"\"\" \"\"\"\r\n __style = [\r\n {'attr': 'background', 'value': 'white'},\r\n {'attr': 'margin', 'value': '5px 0 5px 5px'},\r\n {'attr': 'border', 'value': '1px solid green'},\r\n ]\r\n\r\n\r\nclass CssDivCommBubble(CssBase.CssCls):\r\n \"\"\" \"\"\"\r\n\r\n __style = [\r\n {'attr': 'width', 'value': '100%'},\r\n {'attr': 'vertical-align', 'value': 'top'},\r\n\r\n {'attr': 'top', 'value': '0'},\r\n {'attr': 'height', 'value': '100px'},\r\n {'attr': 'margin-bottom', 'value': '20px'},\r\n {'attr': 'margin-left', 'value': '20px'},\r\n {'attr': 'min-height', 'value': '20px'},\r\n {'attr': 'color', 'value': 'white'},\r\n {'attr': 'display', 'value': 'inline-block'},\r\n ]\r\n\r\n before = [\r\n {'attr': 'content', 'value': \"''\"},\r\n {'attr': 'width', 'value': '0'},\r\n {'attr': 'height', 'value': '0'},\r\n {'attr': 'display', 'value': 'inline-block'},\r\n {'attr': 'border', 'value': '15px solid transparent'},\r\n {'attr': 'border-right-color', 'value': '#398438'},\r\n #{'attr': 'border-left-color', 'value': 'red'},\r\n {'attr': 'margin-left', 'value': '-30px'},\r\n #{'attr': 'margin-top', 'value': '5px'}\r\n ]\r\n","sub_path":"ares/Lib/css/CssDiv.py","file_name":"CssDiv.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"190526","text":"'''DropBox's logs configuration.\n'''\n\n__author__ = 'Miguel Ojeda'\n__copyright__ = 'Copyright 2012, CERN CMS'\n__credits__ = ['Giacomo Govi', 'Salvatore Di Guida', 'Miguel Ojeda', 'Andreas Pfeiffer']\n__license__ = 'Unknown'\n__maintainer__ = 'Miguel Ojeda'\n__email__ = 'mojedasa@cern.ch'\n\n\nimport service\n\n\n# For integration and production, we use the (reader) production dropBox database\nif service.settings['productionLevel'] in set(['int', 'pro']):\n connectionDictionary = service.secrets['dropBoxConnections']['pro']\n\n# For development, we use the prep dropBox database\nelif service.settings['productionLevel'] in set(['dev']):\n connectionDictionary = service.secrets['dropBoxConnections']['dev']\n\n# In private instances, we take connections from netrc\nelif service.settings['productionLevel'] in set(['private']):\n connectionDictionary = service.getConnectionDictionaryFromNetrc('dropBoxDatabase')\n\nelse:\n raise Exception('Unknown production level.')\n\n\ndef getBackendOldThreshold(backend):\n\n backendsOldThreshold = {\n # Online and offline backends run every 30 seconds, so 60 seconds should note a problem\n 'online': 60,\n 'offline': 60,\n\n # Tier0 backend runs at 10-min boundaries, so 20 minutes should note a problem\n 'tier0': 20 * 60,\n\n # Private instances run every 10 seconds, so 20 seconds should note a problem\n 'private': 20,\n }\n\n if backend in backendsOldThreshold:\n return backendsOldThreshold[backend]\n\n return backendsOldThreshold['private']\n\n","sub_path":"logs/dropBox/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"184319450","text":"import tqdm\nimport sys\nimport torch\nfrom losses import gaussian_log_likelihood\nfrom utils import iterate_minibatches\n\n\ndef custom_pbar(iterable, total):\n for i, item in enumerate(iterable):\n sys.stdout.write('%d/%d \\r' % (i, total))\n if i < total:\n yield item\n else:\n sys.stdout.write('\\n')\n break\n\n\ndef train_regressor(model, iters=2000, batchsize=100,\n resample=False, optimizer=None,\n log_likelihood=gaussian_log_likelihood):\n X = (model.X - model.mx)*model.iSx\n Y = (model.Y - model.my)*model.iSy\n N = X.shape[0]\n M = batchsize\n\n if optimizer is None:\n params = filter(lambda p: p.requires_grad, model.parameters())\n optimizer = torch.optim.Adam(params, 1e-3)\n\n pbar = tqdm.tqdm(enumerate(iterate_minibatches(X, Y, M)), total=iters)\n\n for i, batch in pbar:\n x, y = batch\n model.zero_grad()\n outs = model(x, normalize=False, resample=resample)\n Enlml = -log_likelihood(y, *outs).mean()\n loss = Enlml + model.regularization_loss()/N\n loss.backward()\n optimizer.step()\n pbar.set_description('log-likelihood of data: %f' % (-Enlml))\n if i == iters:\n pbar.close()\n break\n","sub_path":"prob_mbrl/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"510820376","text":"from sqlalchemy import *\nfrom migrate import *\n\n\nfrom migrate.changeset import schema\npre_meta = MetaData()\npost_meta = MetaData()\nconstraints = Table('constraints', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('constraint1_flt', Float(precision=20)),\n Column('constraint2_bool', Boolean),\n Column('constraint3_str', String(length=80)),\n Column('constraint4_sel', String(length=80)),\n Column('constraint5_selmult', String(length=80)),\n Column('constraint6_txtarea', String(length=200)),\n Column('constraint7_decimal', Float),\n Column('createddate', DateTime),\n)\n\n\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind\n # migrate_engine to your metadata\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['constraints'].create()\n\n\ndef downgrade(migrate_engine):\n # Operations to reverse the above upgrade go here.\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['constraints'].drop()\n","sub_path":"FlaskTest/db_repository/versions/002_migration.py","file_name":"002_migration.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"632575709","text":"from pydantic import BaseSettings, EmailStr\n\n\nclass Settings(BaseSettings):\n ENV: str = \"dev\"\n SENTRY_DSN: str = None\n API_KEY: str = \"you-will-want-something-safe-here\"\n DEFAULT_EMAIL_ADDRESS: EmailStr = \"default@email.com\"\n SENDGRID_API_KEY: str = \"get_your_api_key_from_sendgrid_dashboard\"\n MAILJET_API_KEY: str = \"get_your_api_key_from_mailjet_dashboard\"\n MAILJET_API_SECRET: str = \"get_your_api_secret_from_mailjet_dashboard\"\n\n class Config:\n env_file = \".env\"\n case_sensitive = True\n\n\nsettings = Settings()\n","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"139191599","text":"import sys\nimport command\nfrom util_usr import receive_msg, get_pos_param\nfrom param_id_list import param_dic as dic\ndef get_param(mavfile):\n while not command.end_entered():\n option = raw_input('Choose an option (1. parameter by ID, 2. parameter by name, 3. all GPS parameters): ')\n if option == 'end':\n sys.exit()\n else:\n try:\n option = int(option)\n except:\n print('Input has to be an integer from the option list')\n pass\n if option == 1:\n param_id = int(raw_input('Type in ID: '))\n name, value, data = receive_msg(mavfile, 'PARAM_VALUE', True, param_id = param_id)\n print('----------\\n' + value[0] + ': ' + str(value[1]) + '\\n' + '----------')\n elif option == 2 or option == '':\n param_name = raw_input('Type in parameter name: ')\n inv_dic = {v: k for k, v in dic.items()}\n if '_' not in param_name:\n param_name_splitted = param_name.split()\n param_name = ''\n for word in param_name_splitted:\n param_name += word.upper()+'_'\n param_name = param_name[:-1] #removing the last _ from the string \n print('Changed input to: ' + param_name)\n else:\n pass\n param_id = int(inv_dic[param_name])\n name, value, data = receive_msg(mavfile, 'PARAM_VALUE', True, param_id = param_id)\n print('----------\\n' + value[0] + ': ' + str(value[1]) + '\\n' + '----------')\n elif option == 3:\n get_pos_param(mavfile, 'print')\n\n else: \n print('Option not defined')\n\n\n\ncmd_get_param = command.cmd('get_param', get_param)\ncmd_get_param.execute_cmd()\n","sub_path":"pyscripts/modules/cmd_get_param.py","file_name":"cmd_get_param.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"562300601","text":"from proteus import *\nfrom proteus.default_n import *\nfrom wigley import *\nfrom twp_navier_stokes_p import *\n\ntimeIntegration = BackwardEuler_cfl\nstepController = FixedStep\n \nfemSpaces = {0:C0_AffineLinearOnSimplexWithNodalBasis,\n 1:C0_AffineLinearOnSimplexWithNodalBasis,\n 2:C0_AffineLinearOnSimplexWithNodalBasis,\n 3:C0_AffineLinearOnSimplexWithNodalBasis}\n\nelementQuadrature = SimplexGaussQuadrature(nd,quad_order)\nelementBoundaryQuadrature = SimplexGaussQuadrature(nd-1,quad_order)\n\nsubgridError = NavierStokesASGS_velocity_pressure_opt(coefficients,nd,lag=False,delayLagSteps=1,hFactor=1.0)\n\nnumericalFluxType = NavierStokes_Advection_DiagonalUpwind_Diffusion_SIPG_exterior #need weak for parallel and global conservation\n\nmassLumping = False\n\nshockCapturing = NavierStokes_SC_opt(coefficients,nd,ns_shockCapturingFactor,lag=False)\n\n\nmultilevelNonlinearSolver = NewtonNS\nlevelNonlinearSolver = NewtonNS\n\nmaxNonlinearIts = 10\nmaxLineSearches = 0\n\nnonlinearSmoother = None\n\nfullNewtonFlag = True\n\ntolFac = 1e-3\n\nnl_atol_res = 0.0\n\nmatrix = SparseMatrix\n\nmultilevelLinearSolver = PETSc\nlevelLinearSolver = PETSc\nlinear_solver_options_prefix = 'rans2p_'\nlinearSmoother=None\n\nnonlinearSolverConvergenceTest = 'rits'\nlevelNonlinearSolverConvergenceTest = 'rits'\n\nlinTolFac = 0.001\n\n","sub_path":"cases/wigleyRBLES/twp_navier_stokes_n.py","file_name":"twp_navier_stokes_n.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"74254414","text":"# from torch.utils.data import Dataset\nfrom base.base_data_loader import BaseDataLoader\nimport numpy as np\nimport torch\nimport os\nfrom random import randint\nfrom utils.util import prepare_dataset, pol2cart\nfrom scipy.signal import stft, resample\nfrom matplotlib import pyplot as plt\n\nNOISE_SAMPLES = 100\n\n\nclass SeismicDatasetLoader(BaseDataLoader):\n def __init__(self, root_dir, signal_dir, noise_dir, transform=None):\n self.root_dir = root_dir\n self.signal_dir = signal_dir\n self.noise_dir = noise_dir\n self.transform = transform\n\n assert os.path.exists(os.path.join(self.root_dir, self.signal_dir)), 'Path to signal images cannot be found'\n assert os.path.exists(os.path.join(self.root_dir, self.noise_dir)), 'Path to noise images cannot be found'\n\n self.signal = sorted([os.path.join(self.root_dir, signal_dir, file) for file in\n os.listdir(os.path.join(self.root_dir, self.signal_dir))\n if file.endswith('.npz')]) # and np.isin(int(file[0:4]), self.idx_list)])\n self.noise = sorted([os.path.join(self.root_dir, noise_dir, file) for file in\n os.listdir(os.path.join(self.root_dir, self.noise_dir))\n if file.endswith('.npz')]) # and np.isin(int(file[0:4]), self.idx_list)])\n\n def __len__(self):\n return len(self.signal)\n\n def __getitem__(self, item):\n if torch.is_tensor(item):\n item = item.tolist()\n\n signal = np.load(self.signal[item], allow_pickle=True)['arr_0']\n noise = np.load(self.noise[randint(0, item)], allow_pickle=True)['arr_0']\n\n signal = resample(signal, 25500)\n processed = prepare_dataset(noise, signal)\n processed = resample(processed, len(signal))\n noise = resample(noise, len(signal))\n\n sample = {'signal': signal, 'noise': noise, 'processed': processed}\n\n f, t, Zxx_processed = stft(processed)\n _, _, Zxx_signal = stft(signal)\n _, _, Zxx_noise = stft(noise)\n\n Zxx_processed = pol2cart(np.abs(Zxx_processed), np.angle(Zxx_processed))\n Zxx_signal = pol2cart(np.abs(Zxx_signal), np.angle(Zxx_signal))\n Zxx_noise = pol2cart(np.abs(Zxx_noise), np.angle(Zxx_noise))\n\n Zxx_signal[0] += 1e-10\n Zxx_signal[1] += 1e-10\n\n Zxx_processed = resample(Zxx_processed, 31, axis=1)\n Zxx_signal = resample(Zxx_signal, 31, axis=1)\n Zxx_noise = resample(Zxx_noise, 31, axis=1)\n f = resample(f, 31)\n\n # Ms\n signal_mask = 1 / (1 + np.abs(np.sqrt(Zxx_noise[0] ** 2 + Zxx_noise[1] ** 2)) / np.abs(\n np.sqrt(Zxx_signal[0] ** 2 + Zxx_signal[1] ** 2)))\n\n # Mn\n noise_mask = (np.abs(np.sqrt(Zxx_noise[0] ** 2 + Zxx_noise[1] ** 2)) / np.abs(\n np.sqrt(Zxx_signal[0] ** 2 + Zxx_signal[1] ** 2))) / (\n 1 + np.abs(np.sqrt(Zxx_noise[0] ** 2 + Zxx_noise[1] ** 2)) / np.abs(\n np.sqrt(Zxx_signal[0] ** 2 + Zxx_signal[1] ** 2)))\n\n stft_dict = {'f': f, 't': t, 'Zxx_signal': Zxx_signal, 'Zxx_processed': Zxx_processed}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample, stft_dict, noise_mask, signal_mask\n","sub_path":"SeismicSignalDenoising/data_loader/data_loaders.py","file_name":"data_loaders.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"55967252","text":"# dataframe\nimport numpy\nimport pandas\nmyarray = numpy.array([[1, 2, 3], [4, 5, 6]])\nrownames = ['a', 'b']\ncolnames = ['one', 'two', 'three']\nmydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames)\n#print(mydataframe)\n\n# Load CSV using Pandas from URL\nfrom pandas import read_csv\nurl = \"https://goo.gl/vhm1eU\"\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(url, names=names)\nprint(data.shape)\n\ndescription = data.describe()\nprint(description)\n","sub_path":"OLD/MlTest1/test1a.py","file_name":"test1a.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"315545792","text":"\n\n\n\n\"\"\"\n\nTrees\n\nBST\n\"\"\"\n\n\nclass Node:\n def __init__(self, value):\n self.left = None\n self.data = value\n self.right = None\n self.parent = None\n self.height = 0\n\n#self balancing binary search tree\nclass BinarySearchTree:\n\n def __init__(self, value):\n self.root = Node(value)\n\n def insert(self, value, root:Node):\n #this has to be a recursive function\n\n #we might be adding the first value for this subtree - so root will be null\n #so we just have to add a new node here - this is also used for adding a new left child or right child\n if root == None:\n return Node(value)\n #value can be greater than given root\n #recursive call on right child - that will return whatever the balanced subtree right child is\n if value > root.data:\n root.right = self.insert(value, root.right)\n root.right.parent = root\n else:\n root.left = self.insert(value, root.left)\n root.left.parent = root\n #value can be smaller than given root\n #recursive call on left child - that will return whatever the balanced subtree left child is\n\n #so at this point we should have the root, the left.child and the right.child and our parent is expecting the 'root' to be returned\n\n #we just added a child to the current 'root' - so recalculate it's height\n\n #call height\n root.height = self.height(root)\n\n #check balance for this node\n balance = self.height(root.left) - self.height(root.right)\n #height of left child\n #height of right child\n #get difference\n\n #4 cases\n #imbalance can be in\n #right subtree of right child\n #left subtree of right child\n #right subtree of left child\n #left subtree of left child\n\n #left child and if value is > leftchild.value - then right subtree of left child - leftRight rotate\n #if we have a new root - return that to teh recursive parent waiting for the 'root'\n if balance > 1 and value < root.left.data:\n return self.rightRotate(root)\n\n if balance > 1 and value > root.left.data:\n root.left = self.leftRotate(root.left)\n return self.rightRotate(root)\n\n if balance < -1 and value > root.right.data:\n return self.leftRotate(root)\n\n if balance < -1 and value < root.right.data:\n root.right = self.rightRotate(root.right)\n return self.leftRotate(root)\n #similarly we have other cases\n\n #this function has to return the root because the root of the tree/subtree can change\n return root\n\n\n def leftRotate(self, node:Node):\n print(\"leftrotate\")\n temp = node.right\n node.right = temp.left\n if temp.left != None:\n temp.left.parent = node\n temp.left = node\n temp.parent = node.parent\n node.parent = temp\n node.height =self.height(node)\n temp.height = self.height(temp)\n return temp\n\n def rightRotate(self, node:Node):\n print(\"rightRotate\")\n temp = node.left\n node.left = temp.right\n temp.parent = node.parent\n temp.right = node\n node.parent = temp\n node.height = self.height(node)\n temp.height = self.height(temp)\n return temp\n\n def height(self, node: Node):\n if node == None:\n return -1\n else:\n height = 0\n if node.left == None and node.right == None:\n node.height = 0\n return 0\n else:\n if node.left != None:\n height = node.left.height\n\n if node.right != None:\n if node.right.height > height:\n height = node.right.height\n return height + 1\n\n def contain(self,value,node:Node):\n\n print(\"Current node is \", node.data)\n if node.data == value:\n print(\"Value found!\")\n return\n\n if value < node.data:\n if node.left != None:\n self.contain(value, node.left)\n else:\n print(\"Value not found !\")\n return\n else:\n if node.right != None:\n self.contain(value, node.right)\n else:\n print(\"Value not found !\")\n return\n\n return\n\n\n def inOrderTraverse(self, node: Node):\n #first process left node\n if node.left != None:\n self.inOrderTraverse(node.left)\n\n #then process root node\n print(node.data, \"(\", node.height, \")\", end=\" - \")\n\n #then process right node\n if node.right != None:\n self.inOrderTraverse(node.right)\n\n return\n\n def postOrderTraverse(self, root: Node):\n #left - right - root\n\n if root == None:\n return\n\n self.postOrderTraverse(root.left)\n\n self.postOrderTraverse(root.right)\n\n print(root.data, \"(\", root.height, \")\", end=\" - \")\n\n return\n\n\n def preOrderTraverse(self, root: Node):\n #root - left - right\n\n if root == None:\n return\n\n print(root.data, \"(\", root.height, \")\", end=\" - \")\n\n self.preOrderTraverse(root.left)\n\n self.preOrderTraverse(root.right)\n\n return\n\ninput_array = [53, 47, 89, 71, 32, 18, 22, 51]\nnewtree = BinarySearchTree(15)\nfor x in input_array:\n print(\"\")\n print(\"Adding\", x)\n newtree.root = newtree.insert(x, newtree.root)\n\nnewtree.contain(71, newtree.root)\nnewtree.contain(32, newtree.root)\nnewtree.contain(99, newtree.root)\nprint(\"inOrderTraverse\")\nnewtree.inOrderTraverse(newtree.root)\nprint(\"\\npostOrderTraverse\")\nnewtree.postOrderTraverse(newtree.root)\nprint(\"\\npreOrderTraverse\")\nnewtree.preOrderTraverse(newtree.root)\n\n","sub_path":"practice_8.py","file_name":"practice_8.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578617885","text":"\"\"\"\nDjango settings for liwi project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport sys\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '69)jz9t9^kvci2_8^j732h%a*8yz4h-(kehld1@e2jcw_d9wkn'\n\nAWS_ACCESS_KEY_ID = 'AKIAJEYC7OVXICWHIFMA'\nAWS_SECRET_ACCESS_KEY = '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'\nAWS_SES_REGION_NAME = 'us-west-2'\nAWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com'\n\nTESTING = 'test' in sys.argv\n\nDEBUG = True\nTEMPLATE_DEBUG = True\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'south',\n 'registration',\n 'authentication',\n 'home',\n 'user_profile',\n 'art',\n 'artists',\n 'cart',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n)\n\nROOT_URLCONF = 'liwi.urls'\n\nWSGI_APPLICATION = 'liwi.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'liwi',\n 'USER': 'kshafer',\n 'PASSWORD': 'Rubygem14',\n 'HOST': 'liwi-development.c2mw5t19dwbx.us-west-2.rds.amazonaws.com',\n 'PORT': '5432',\n },\n 'liwi_test': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'liwi_test',\n 'USER': 'kshafer',\n 'PASSWORD': 'Rubygem14',\n 'HOST': 'liwi-development.c2mw5t19dwbx.us-west-2.rds.amazonaws.com',\n 'PORT': '5432',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n)\n\nTEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]\n\nAUTH_USER_MODEL = 'registration.User'\n\nLOGIN_URL = '/login'\n\nSITE_ROOT = '/home/ubuntu/liwi-site'\n\nif TESTING:\n MEDIA_ROOT = '/home/ubuntu/liwi-site/test_photos/'\n MEDIA_URL = '/test_photos/'\nelse:\n MEDIA_ROOT = '/home/ubuntu/liwi-site/photos/'\n MEDIA_URL = '/photos/'\n\n#if testing, send messages with a file based backend\n#NOTE: the run_tests script will create and tear down the mail directory\nif TESTING:\n EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'\n EMAIL_FILE_PATH = 'mail/' \nelse:\n EMAIL_BACKEND = 'django_ses.SESBackend'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'standard': {\n 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n },\n 'handlers': {\n 'null': {\n 'level':'DEBUG',\n 'class':'django.utils.log.NullHandler',\n },\n 'logfile': {\n 'level':'DEBUG',\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': SITE_ROOT + \"/logfile.txt\",\n 'maxBytes': 50000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n 'console':{\n 'level':'INFO',\n 'class':'logging.StreamHandler',\n 'formatter': 'standard'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers':['console'],\n 'propagate': True,\n 'level':'WARN',\n },\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'liwi': {\n 'handlers': ['console', 'logfile'],\n 'level': 'DEBUG',\n },\n }\n}\n","sub_path":"settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"452725530","text":"import pexpect, os\n\nfrom cli_toolkit.vivado.cmdResult import VivadoCmdResult\nfrom cli_toolkit.vivado.config import VivadoConfig\nfrom cli_toolkit.vivado.tcl import VivadoTCL\n\n\ndef mkPackageIp(verdor, user, name, version):\n return ':'.join([verdor, user, name, version])\n\n\n \nclass VivadoCntrl():\n def __init__(self, execFile=VivadoConfig.getExec(), deleteLogsOnExit=True, timeout=6 * 60 * 60, logComunication=False):\n self.execFile = execFile\n self.proc = None\n self.jurnalFile = \"vivado.jou\"\n self.logFile = 'vivado.log'\n self.verbose = True\n self.timeout = timeout\n self.guiOpened = False\n self.logComunication = logComunication\n self.encoding = 'ASCII'\n \n def __enter__(self):\n cmd = [\"-mode\", 'tcl' , \"-notrace\"]\n if self.verbose:\n cmd.append('-verbose')\n self.proc = pexpect.spawn(self.execFile, cmd)\n self.firstCmd = True\n return self\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n p = self.proc\n if p.isalive():\n p.sendline(VivadoTCL.exit())\n p.expect(\"exit\", timeout=self.timeout) # block while cmd ends\n if p.isalive():\n p.terminate()\n \n def openGui(self):\n \"\"\"\n @attention: this method disconnects controller and opens gui\n \"\"\" \n list(self.process([VivadoTCL.start_gui()])) # list to execute because process() is generator\n if self.proc.isalive():\n self.proc.wait()\n \n \n def _process(self, cmds):\n p = self.proc\n for cmd in cmds:\n if self.firstCmd:\n p.expect(\"Vivado%\", timeout=self.timeout) # block while command line init\n self.firstCmd = False\n if self.guiOpened:\n raise Exception(\"Controller have no acces to Vivado because gui is opened\")\n \n p.sendline(cmd)\n # @attention: there is timing issue in reading from tty next command returns corrupted line \n p.readline() # read cmd from tty\n # p.expect(cmd, timeout=self.timeout) \n if cmd == VivadoTCL.start_gui():\n self.guiOpened = True\n try:\n p.expect(\"Vivado%\", timeout=self.timeout) # block while cmd ends\n except pexpect.EOF:\n pass\n t = p.before.decode(self.encoding)\n if self.logComunication:\n print(cmd)\n print(t)\n res = VivadoCmdResult.fromStdoutStr(cmd, t)\n res.raiseOnErrors()\n yield res\n def process(self, cmds, iterator=False):\n \"\"\"\n @attention: if iterator == True you must iterate trough it to execute commands, \n this is how python generator works\n @param iterator: return iterator over cmd results \n \"\"\"\n results = self._process(cmds)\n if iterator:\n return results\n else:\n return list(results)\n def rmLogs(self):\n if os.path.exists(self.logFile):\n os.remove(self.logFile)\n if os.path.exists(self.jurnalFile):\n os.remove(self.jurnalFile) \n \nif __name__ == \"__main__\":\n import os\n with VivadoCntrl() as v: \n _op, _pwd, _dir = v.process(['open_project /home/nic30/Documents/vivado/Sprobe10_board_test/Sprobe10_board_test.xpr', 'pwd', 'dir'])\n print(_op.resultText)\n ls = os.listdir(_pwd.resultText)\n vivadoLs = _dir.resultText.split()\n ls.sort()\n vivadoLs.sort()\n print(ls)\n print(vivadoLs)\n v.openGui()\n print('finished')\n","sub_path":"cli_toolkit/vivado/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"621445995","text":"import logging\nimport numpy as np\nfrom PyQt5 import QtWidgets\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom .Logger import log_timing\n__all__ = ('VPICCanvas',)\n\nclass VPICCanvas(FigureCanvas):\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n\n # Logging\n self.logger = logging.getLogger('vpic.canvas')\n\n # Figure\n self.fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = self.fig.subplots(2, 3,\n gridspec_kw={'width_ratios': [1, 16, 4],\n 'height_ratios': [4, 1],\n 'wspace': 0.05,\n 'hspace': 0.05,\n 'left': 0.12,\n 'right': 0.9,\n 'bottom': 0.1,\n 'top': 0.93})\n\n # Delete un-needed axes.\n self.axes[1, 0].remove()\n self.axes[1, 2].remove()\n\n # Share axes.\n self.axes[0, 1].get_shared_x_axes().join(self.axes[0, 1],\n self.axes[1, 1])\n self.axes[0, 1].get_shared_y_axes().join(self.axes[0, 1],\n self.axes[0, 2])\n\n FigureCanvas.__init__(self, self.fig)\n self.setParent(parent)\n FigureCanvas.setSizePolicy(self,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n self.dataset = np.empty([0, 0, 0, 0])\n self.title = 'null'\n self.grid = [np.zeros(1)]*4\n self.slicer = [slice(0, 1)]*4\n self.xaxis = 0\n self.yaxis = 1\n self.vline = None\n self.hline = None\n self.image = None\n self.data = np.empty([0, 0, 0, 0])\n self.data_stale = True\n self.cbar = None\n\n @log_timing\n def read_data(self):\n \"\"\"Read and cache the 2D slice. By caching, we speed up lineouts.\"\"\"\n if self.dataset.size > 0:\n slicer_xy = self.slicer.copy()\n slicer_xy[self.xaxis] = slice(None)\n slicer_xy[self.yaxis] = slice(None)\n self.data = self.dataset[tuple(slicer_xy)]\n else:\n self.data = np.empty([0, 0, 0, 0])\n self.data_stale = True\n\n def set_slice(self, axis, index):\n \"\"\"Set the slice indicies for the line-outs.\"\"\"\n # Data coordinate.\n if isinstance(index, float):\n index = np.searchsorted(self.grid[axis], index)\n index = max(0, index-1)\n\n # Exact index.\n self.slicer[axis] = slice(index, index+1)\n\n def clear(self):\n \"\"\"Clear existing plots.\"\"\"\n self.axes[0, 0].cla()\n self.axes[0, 1].cla()\n self.axes[1, 1].cla()\n self.axes[0, 2].cla()\n\n def draw_2d(self, extent):\n \"\"\"Main 2D plotting. We only need to redraw this if the underlying\n data has changed.\"\"\"\n\n # Grab the data.\n squeeze_axis = [0, 1, 2, 3]\n squeeze_axis.remove(self.xaxis)\n squeeze_axis.remove(self.yaxis)\n if self.data.size > 0:\n data_xy = np.squeeze(self.data, axis=tuple(squeeze_axis))\n if self.xaxis < self.yaxis:\n data_xy = data_xy.T\n else:\n data_xy = np.zeros((1, 1))\n\n if self.image is not None:\n # Just update the underlying data. We do this because if users\n # update preferences (colormap, interpolation, etc.) through the\n # GUI it will be perserved across updates.\n self.image.set_data(data_xy)\n self.image.set_extent(extent)\n self.image.autoscale()\n\n else:\n # Draw the initial plot.\n self.image = self.axes[0, 1].imshow(data_xy,\n origin='lower',\n aspect='auto',\n extent=extent)\n\n # Colobar construction\n self.cbar = self.fig.colorbar(self.image, cax=self.axes[0, 0])\n\n if self.cbar is not None:\n self.cbar.ax.tick_params(axis='y',\n right=False, labelright=False,\n left=True, labelleft=True)\n\n # Set tickparams.\n self.axes[0, 1].tick_params(axis='both',\n right=False, labelright=False,\n left=False, labelleft=False,\n bottom=False, labelbottom=False,\n top=False, labeltop=False)\n\n @log_timing\n def draw_plots(self, rescale=False):\n \"\"\"Draw plots for the dataset and slices.\"\"\"\n if self.dataset.size > 0:\n\n xgrid = self.grid[self.xaxis]\n ygrid = self.grid[self.yaxis]\n xslice = xgrid[self.slicer[self.xaxis]][0]\n yslice = ygrid[self.slicer[self.yaxis]][0]\n\n slicer_x = [slice(None)]*4\n slicer_x[self.yaxis] = self.slicer[self.yaxis]\n\n slicer_y = [slice(None)]*4\n slicer_y[self.xaxis] = self.slicer[self.xaxis]\n\n # Assumes these should be 1D, but is better than squeeze due\n # to implementation inconsistency in squeezing memmaps.\n data_x = self.data[tuple(slicer_x)].flatten()\n data_y = self.data[tuple(slicer_y)].flatten()\n\n else:\n data_x = np.zeros(2)\n data_y = np.zeros(2)\n xgrid = np.atleast_1d([0, 1])\n ygrid = np.atleast_1d([0, 1])\n xslice = 0\n yslice = 0\n\n\n # Save the current limits.\n if rescale:\n xlim = xgrid[[0, -1]]\n ylim = ygrid[[0, -1]]\n else:\n xlim = self.axes[0, 1].get_xlim()\n ylim = self.axes[0, 1].get_ylim()\n\n # If stale, redraw the image.\n if self.data_stale:\n self.draw_2d([xgrid[0], xgrid[-1], ygrid[0], ygrid[-1]])\n self.data_stale = False\n\n # Construct or move the cursors.\n if self.vline is None:\n self.vline = self.axes[0, 1].axvline(xslice, c='0.2')\n else:\n self.vline.set_data([xslice, xslice], [0, 1])\n\n if self.hline is None:\n self.hline = self.axes[0, 1].axhline(yslice, c='0.2')\n else:\n self.hline.set_data([0, 1], [yslice, yslice])\n\n # Plot the lineouts.\n self.axes[0, 2].cla()\n self.axes[1, 1].cla()\n self.axes[0, 2].plot(data_y, ygrid, c='0.2', scaley=False)\n self.axes[1, 1].plot(xgrid, data_x, c='0.2', scalex=False)\n\n # Set limits\n self.axes[0, 1].set_xlim(*xlim)\n self.axes[0, 1].set_ylim(*ylim)\n\n # Set labels\n labels = ['t', 'z', 'y', 'x']\n self.axes[0, 2].set_ylabel(rf'${labels[self.yaxis]}$', fontsize='x-large')\n self.axes[0, 2].yaxis.set_label_position('right')\n self.axes[0, 2].yaxis.label.set_rotation(0)\n self.axes[0, 2].yaxis.labelpad = 10\n self.axes[1, 1].set_xlabel(rf'${labels[self.xaxis]}$', fontsize='x-large')\n\n # Set title\n indices = list(range(4))\n indices.remove(self.xaxis)\n indices.remove(self.yaxis)\n\n slice_labels = [rf'${labels[i]} = {self.grid[i][self.slicer[i]][0]:.4g}$'\n for i in indices]\n title = self.title + ': ' + ', '.join(slice_labels)\n self.axes[0, 1].set_title(title, size='large')\n\n # Set tickparams\n self.axes[0, 2].tick_params(axis='both',\n right=True, labelright=True,\n left=False, labelleft=False,\n bottom=False, labelbottom=False,\n top=True, labeltop=True)\n\n self.axes[1, 1].tick_params(axis='both',\n right=False, labelright=False,\n left=True, labelleft=True,\n bottom=True, labelbottom=True,\n top=False, labeltop=False)\n\n self.draw()\n","sub_path":"pyvpic/viewer/Canvas.py","file_name":"Canvas.py","file_ext":"py","file_size_in_byte":8443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"566379553","text":"import math\n\ndef fibonacci():\n x, y = 0, 1\n while True:\n x, y = y, x + y\n yield x\n return\n\ndef run():\n i = 1\n fib = fibonacci()\n while True:\n v = next(fib)\n if math.floor(math.log10(v)+1) >= 1000:\n break\n i += 1\n return i\n","sub_path":"src/python/p025.py","file_name":"p025.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"194008732","text":"'''\r\ntf.matmul(a, b, name) #矩阵或者tensor乘法\r\na: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`,\r\nb: `Tensor` with same type and rank as `a`.(也就是说a ,b的维度和类型必须一致)\r\n1.输入a ,b必须是矩阵或者维度大于2的tensor\r\n2.这个函数是专门矩阵或者tensor乘法,而不是矩阵元素对应元素相乘。这点要注意\r\n'''\r\nimport tensorflow as tf\r\nb1 = tf.Variable(tf.random_normal([2]), name='bias1')\r\nCL = tf.constant([1., 2., 3., 4., 5., 6.], shape=[2, 3])\r\nprint(tf.Session().run(CL))\r\n# W1 = tf.constant([7., 8., 9., 10., 11., 12.], shape=[3, 2])#偏置与W1最后维度一样\r\n# c = tf.matmul(CL, W1) #[array([[ 39., 54., 69.],\r\n# # [ 49., 68., 87.],\r\n# #[ 59., 82., 105.]], dtype=float32)]\r\n# print(c.shape)\r\n# FCNL1 = tf.nn.relu(tf.matmul(CL, W1) + b1)\r\n# FCNL1 = tf.nn.dropout(FCNL1, keep_prob=0.5)\r\n# print(FCNL1.shape)\r\n# with tf.Session() as sess:\r\n# print(sess.run([CL]))\r\n'''[array([[1, 2, 3],\r\n [4, 5, 6]]), \r\n array([[ 7, 8],\r\n [ 9, 10],\r\n [11, 12]]), \r\n array([[ 58, 64],\r\n [139, 154]])]'''","sub_path":"tf.matmul.py","file_name":"tf.matmul.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"524054966","text":"from flask.views import View\nfrom laserpony.models.project import Project\n\n\nclass BaseView(View):\n context = {}\n\n def prepare(self, *args, **kwargs):\n #Any processing that needs to happen before each request is handled\n #gets taken care of here\n projects = Project.objects\n self.context['navigation'] = {\n 'projects' : projects\n }\n self.context['extends_with']= \"nav.html\"\n\n def handle_request(self):\n \"\"\"Subclasses have to override this method to implement the\n actual view function code. This method is called with all\n the arguments from the URL rule.\n \"\"\"\n raise NotImplementedError()\n\n def dispatch_request(self, *args, **kwargs):\n self.context = dict()\n self.prepare(self, *args, **kwargs)\n return self.handle_request(*args, **kwargs)\n\n\n","sub_path":"laserpony/views/scaffold.py","file_name":"scaffold.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"27351523","text":"# -*- coding:utf-8 -*-\n#!/usr/bin/python\n# Python: 3.4.3\n# Platform: Windows\n# Author: Mr.Yuan\tfusu1435@163.com\n# Program: KNN-Algorithm demo ,dating test & handwriting classify\n# History: 2015.8.31 v1.0.0\n\nfrom numpy import *\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport operator\nimport os\n\ndef createDataset():\n\tgroup = array([[1.0,1.1],[1.0,1.0],[0.0,0],[0,0.1]])\n\tlabels = ['A','A','B','B']\n\treturn group,labels\n\ndef KNNclassify(inV,dataSet,labels,kCount):\n\tdatasetSize = dataSet.shape[0]\n\tdiffMat = tile(inV,(datasetSize,1)) - dataSet\n\tsqDiffMat = diffMat**2\n\tsqDist = sqDiffMat.sum(axis=1)\n\tdist = sqDist ** 0.5\n\tsortedDistIndicies = dist.argsort()\n\tclassCount = {}\n\tfor i in range(kCount):\n\t\tvoteLabel = labels[sortedDistIndicies[i]]\n\t\tclassCount[voteLabel] = classCount.get(voteLabel,0) + 1\n\n\tsortedClassCout = sorted(classCount.items(),\\\n\t\t\t\tkey = operator.itemgetter(1),reverse = True)\n\treturn sortedClassCout[0][0]\n\ndef file2matrix(filename):\n\tfReader = open(filename)\n\tarrayOfLines = fReader.readlines()\n\tnumOfLines = len(arrayOfLines)\n\tretMat = zeros((numOfLines,3))\n\tclassLabelVec = []\n\tindex = 0\n\tfor line in arrayOfLines:\n\t\tline = line.strip()\n\t\tlistFromLine = line.split('\\t')\n\t\tretMat[index,:] = listFromLine[0:3]\n\t\tclassLabelVec.append(int(listFromLine[-1]))\n\t\tindex += 1\n\treturn retMat,classLabelVec\n\ndef autoNorm(dataSet):\n\tminVal = dataSet.min(0)\n\tmaxVal = dataSet.max(0)\n\tranges = maxVal - minVal\n\tnormDataset = zeros(shape(dataSet))\n\tm = dataSet.shape[0]\n\tnormDataset = dataSet - tile(minVal,(m,1))\n\tnormDataset = normDataset/tile(ranges,(m,1))\n\t\n\treturn normDataset,ranges,minVal\n\ndef dateClassTest():\n\thRatio = 0.5\n\tdateMat,dateLabel = file2matrix('datingTest.txt')\n\t#plotData(dateMat)\n\tnormMat,ranges,minVal = autoNorm(dateMat)\n\tm = normMat.shape[0]\n\tnumTestVecs = int(m*hRatio)\n\terrCount = 0.0\n\tfor i in range(numTestVecs):\n\t\tclassifierRes = KNNclassify(normMat[i,:],normMat[numTestVecs:m,:],\\\n\tdateLabel[numTestVecs:m],3)\n\t\tprint (\"the classifier came back with: %d,the real answer is : %d\"\\\n\t\t% (classifierRes,dateLabel[i]))\n\tif (classifierRes != dateLabel[i]):\n\t\terrCount += 1.0\n\tprint (\"the total error rate is : %f\" % (errCount/float(numTestVecs)))\n\ndef plotData(dataSet):\n\tfig = plt.figure()\n\tax = fig.add_subplot(111)\n\tax.scatter(dataSet[:,1],dataSet[:2])\n\tplt.show()\n\n# conver img to vector\ndef img2vector(filename):\n\tretVec = zeros((1,1024))\n\tfReader = open(filename)\n\tfor i in range(32):\n\t\tlineStr = fReader.readline()\n\t\tfor j in range(32):\n\t\t\tretVec[0,32*i+j] = int(lineStr[j])\n\t\n\treturn retVec\n\t\t\t\ndef file2mat(fileDir):\n\tdataLabels = []\n\tfileList = os.listdir(fileDir)\n\tnumFile = len(fileList)\n\tprint('numFile = %d' % numFile)\n\tdataMat = zeros((numFile,1024))\n\tfor i in range(numFile):\n\t\tfileNameStr = fileList[i]\n\t\tfileStr = fileNameStr.split('.')[0]\n\t\tclassNumStr = int(fileStr.split('_')[0])\n\t\tdataLabels.append(classNumStr)\n\t\tdataMat[i,:] = img2vector('%s/%s' % (fileDir,fileNameStr))\n\t \n\treturn dataMat,dataLabels\n\ndef loadDataset():\n\t# Get training data\n\tprint('Get training data:')\n\ttrainingMat,trainingLabels = file2mat('trainingDigits')\n\t# Get test data\n\tprint('Get test data:')\n\ttestMat,testLabels = file2mat('testDigits')\n\t\n\treturn trainingMat,trainingLabels,testMat,testLabels\ndef loadDataset1():\n\t# Get training data\n\ttrainingLabels = []\n\ttrainingFileList = listdir('trainingDigits')\n\tnumTraining= len(trainingFileList)\n\ttrainingMat = zeros(numTraining,1024)\n\tfor i in range(numTraining):\n\t\tfileNameStr = trainingFileList[i]\n\t\tfileStr = fileNameStr.split('.')[0]\n\t\tclassNumStr = int(fileStr.split('_')[0])\n\t\ttrainingLabels.append(classNumStr)\n\t\ttrainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)\n\t\n\t# Get test data\n\ttestLabels = []\n\ttestFileList = listdir('testDigits')\n\tnumTest = len(testFileList)\n\ttestMat = zeros(numTest,1024)\n\tfor i in range(mTest):\n\t\tfileNameStr = testFileList[i]\n\t\tfileStr = fileNameStr.split('.')[0]\n\t\tclassNumStr = int(fileStr.split('_')[0])\n\t\ttestLabels.append(classNumStr)\n\t\ttestMat[i,:] = img2vector('testDigits/%s' % fileNameStr)\n\n\treturn trainingMat,trainingLabels,testMat,testLabels\n# test hand writing class\ndef handwritingClassTest():\n\t# step 1 : load data\n\tprint ('step 1 : load data')\n\ttrainingMat,trainingLabels,testMat,testLabels = loadDataset()\n\t# step 2 : train data\n\tprint ('step 2 : train data')\n\tpass\n\t# step 3 : test data\n\terrCount = 0.0\n\tnumTest = testMat.shape[0]\n\tprint ('step 3 : test data')\n\tfor i in range(numTest):\n\t\tclassifierRes = KNNclassify(testMat,trainingMat,trainingLabels,3)\n\t\tprint (\"the classifier cama back with : %d,the real answer is : %d\" %(classifierRes,testLabels[i]))\n\t\tif (classifierRes != testLabels[i]):\n\t\t\terrCount += 1.0\n\tprint (\"\\nthe total number of errors is : %d\" % errCount)\n\tprint (\"\\nthe total error rate is : %f\" % (errCount/float(numTest)))\n\nif __name__ == '__main__':\n#\tdataSet,labels = createDataset()\n#\tprint(KNNclassfy([0.4,0.6],dataSet,labels,3))\n#\tplotData(dataSet)\n\tdateClassTest()\n#\thandwritingClassTest()","sub_path":"KNN/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239306733","text":"# Nicholas Allan, 2015-11-10\n# \n\n#import libraries\nimport pandas as pd \nimport sys\nimport matplotlib.pyplot as plt\n\ndef main():\n \n #output variables\n\toutput_file = sys.argv[2]\n\t#input variables \n\t#action = sys.argv[1]\n\tinput_file = sys.argv[1]\n\n\t\t#load the data\n\tdata = pd.read_csv(input_file, delimiter = ',')\n \n\t\t#print data\n\tplot(data, output_file)\n\n\ndef plot(plot_data, savename):\n #plot data\n\tplt.plot(plot_data)\n #save the plot\n\tplt.savefig(savename)\n \nmain()\n","sub_path":"make_it_happen.py","file_name":"make_it_happen.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225779705","text":"\"\"\"\n Tests and examples for getting ark info\n\"\"\"\n\n__author__ = 'Matt Gidney'\n__version__ = '1.0'\n__date__ = '2013/01/10'\n\n\nclass ARKManager(object):\n \"\"\"\n This class is used to defer as long as possible the load of ARK modules\n \"\"\"\n def __init__(self, job, tool):\n self.job = job\n self.tool = tool\n \n self._ark = None\n self._arkdao = None\n self._arkutils = None\n self._versionservice = None\n \n @property \n def version_service(self):\n if self._versionservice is None:\n from AL.utils.arkdao.hessianservices.version import VersionService\n self._versionservice = VersionService()\n return self._versionservice\n \n @property \n def arkdao(self):\n if self._arkdao is None:\n import arklib\n from AL.utils.arkdao import arklibdao\n self._ark = arklib.Ark(self.job, self.tool)\n self._arkdao = arklibdao.ArkLibDAO(self.job,self._ark )\n return self._arkdao\n\n @property \n def arkutils(self):\n if self._arkutils is None:\n from AL.utils import arkutils\n self._arkutils = arkutils\n return self._arkutils\n \n \nclass Asset(object): \n def __init__(self,job,title):\n self.job=job\n self.title=title\n self.ark_manager = ARKManager(self.job, self.title)\n \n \nA=Asset(\"kragle\",\"mattg\")\n\n\n \n \n \n \n \n \n \n \n ","sub_path":"python/Binocular/_test_scripts_local/arkdao_tester.py","file_name":"arkdao_tester.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"493444837","text":"#!/usr/bin/python2\nimport serial\nfrom serial import SerialException\n\n\nclass SwitchSpeaker:\n\n def __init__(self, logger):\n self.logger = logger\n try:\n self.ser = serial.Serial(\n port='/dev/ttyUSB0',\n baudrate=9600\n )\n\n if not self.ser.isOpen():\n self.logger.info(\"Serialport /dev/ttyUSB0 cannot be opened.\")\n except SerialException:\n self.logger.info(\"Serialport /dev/ttyUSB0 already opened.\")\n\n def internal(self):\n close_1 = \"\\xff\\x03\\x01\"\n close_2 = \"\\xff\\x04\\x01\"\n self.ser.write(close_1)\n self.ser.write(close_2)\n self.ser.close()\n self.logger.info(\"switched to internal speaker\")\n\n def external(self):\n open_1 = \"\\xff\\x03\\x00\"\n open_2 = \"\\xff\\x04\\x00\"\n self.ser.write(open_1)\n self.ser.write(open_2)\n self.ser.close()\n self.logger.info(\"switched to external speaker\")\n","sub_path":"bin/Speaker/SwitchSpeaker.py","file_name":"SwitchSpeaker.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"599331053","text":"from server.portal_work import get_weekly_birthdays, get_todays_birthdays\nfrom models import Subscriber\n\n\ndef format_date(str_date):\n try:\n date = str_date.split('-')\n return '{}.{}'.format(date[2], date[1])\n except:\n return 'unknown'\n\n\ndef generate_message(birthday_people, add_date):\n if len(birthday_people) < 1:\n return \"Дни рождения не обнаружены :)\"\n result = \"\"\n try:\n for man in birthday_people:\n result += man['first_name'] + \" \"\n result += man['last_name'] + \" \"\n if add_date:\n result += \"({}) \\n\".format(format_date(man['birth_date']))\n return result\n except:\n return 'Произошла ошибка. Зайди на Портал и посмотри.'\n\n\ndef start_handler(bot, update):\n bot.sendMessage(update.message.chat_id, text='Привет! Используй /help чтобы посмотреть список команд.')\n\n\ndef weekly_birthdays_handler(bot, update):\n birthday_people = get_weekly_birthdays()\n bot.sendMessage(update.message.chat_id, text=generate_message(birthday_people, True))\n\n\ndef today_birthdays_handler(bot, update):\n birthday_people = get_todays_birthdays()\n bot.sendMessage(update.message.chat_id, text=generate_message(birthday_people, False))\n\n\ndef unknown_command_handler(bot, update):\n bot.sendMessage(update.message.chat_id, text=\"Что? Попробуй /help .\")\n\n\ndef add_subscriber_handler(bot, update):\n sub, created = Subscriber.get_or_create(channel=update.message.chat_id)\n if created:\n bot.sendMessage(update.message.chat_id, text=\"Спасибо! Теперь вы подписаны на оповещения.\")\n else:\n bot.sendMessage(update.message.chat_id, text=\"Вы уже подписаны на оповещения.\")\n\n\ndef remove_subscriber_handler(bot, update):\n try:\n sub = Subscriber.get(channel=update.message.chat_id)\n sub.delete_instance()\n bot.sendMessage(update.message.chat_id, text=\"Вы отписались от оповещений.\")\n except:\n bot.sendMessage(update.message.chat_id, text=\"Вы не подписаны на оповещения.\")\n\n","sub_path":"server/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555639972","text":"# -*- coding cp949 -*-\n\nimport math\n\ndef Add(a) :\n \"더하기\"\n num = 0\n for i in a :\n num += i\n return num\n\ndef Sub(a) :\n \"빼기\"\n num = a[0]\n for i in range(1, len(a)) :\n num -= a[i]\n return num\n\ndef Mul(a) :\n \"곱하기\"\n num = 1\n for i in a :\n num *= i\n return num\n\ndef Div(a) :\n \"나누기\"\n num = a[0]\n for i in range(1, len(a)) :\n num /= a[i]\n return num\n\ndef TriangleArea(width, height) :\n \"삼각형 넓이\"\n return width * height / 2\n\ndef RectangleArea(width, height) :\n \"사각형 넓이\"\n return width * height\n\ndef CircleArea(radius) :\n \"원의 넓이\"\n return pow(radius, 2) * math.pi\n\n\n\nprint(\"Run Arith Module\")\n\n# 모듈내에서 직접 실행할때\nif __name__ == '__main__' :\n print(\"모듈 직접 실행하였습니다.\")\n print(\"Test Add {0}\".format(Add((10, 20))))\n# 다른 파일에서 import후에 사용할 때\nelse :\n print(\"Import arith Moudle\")","sub_path":"Python/Lecture/2017_06_07_Lecture/01_Inheritance/Arith.py","file_name":"Arith.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388817663","text":"\n# Emulating 4 inputs to 3 neurons\n# so every neuron will have its own weight set and also their own different biases\n\n\ninputs = [1, 2, 3, 2.5]\nweight1 = [0.2, 0.8, -0.5, 1.0]\nweight2 = [0.5, -0.91, 0.26, -0.5]\nweight3 = [-0.26, 0.27, 0.17, 0.87]\n\nbias1 = 2\nbias2 = 3\nbias3 = 0.5\n\noutput = [inputs[0]*weight1[0] + inputs[1]*weight1[1] + inputs[2]*weight1[2] + inputs[3]*weight1[3] + bias1,inputs[0]*weight2[0] + inputs[1]*weight2[1] + inputs[2]*weight2[2] + inputs[3]*weight2[3] + bias2, inputs[0]*weight3[0] + inputs[1]*weight3[1] + inputs[2]*weight3[2] + inputs[3]*weight3[3] + bias3]\nprint(output)","sub_path":"n2(4insto3layers).py","file_name":"n2(4insto3layers).py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"341811165","text":"def ficha(n='', g=0):\n\n print(f'O jogador {n} fez {g} gol(s) no campeonato.')\n\n\n\n\nnome = str(input('Nome do jogador: '))\ngols = str(input('Numero do Gols: '))\n\nif gols.isnumeric():\n gols = int(gols)\nelse:\n gols = 0\n\nif nome.strip() == '':\n ficha(g=gols)\nelse:\n ficha(n=nome, g=gols)\n\n\n","sub_path":"exercicios/ex103-Ficha jogador.py","file_name":"ex103-Ficha jogador.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"457615581","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 23 14:22:52 2019\n\n@author: gabic\n\"\"\"\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\nfrom matplotlib.pyplot import figure\n\n#coefiientes do U \ndef a (i,h,k):\n return -2*((1/(h**2))+(1/((i*h*k)**2)))\n\ndef b (i,h,k):\n return (1/((k*i*h)**2))\n\ndef c (i,h):\n return (1/h**2)-(1/(2*(i*h)**2))\n\ndef d(i,h): \n return (1.0/h**2) + (1.0 / (2.0 * i * h**2)) \n##\n\ndef imprimeMatriz(matriz):\n ordem = len(matriz[0])\n just_space = 5\n for i in range(ordem):\n for j in range(ordem):\n sys.stdout.write(\"{0:.1f}\".format(matriz[i][j]).ljust(just_space))\n #sys.stdout.write(\"| \" + repr(vetor_solucao[i]).ljust(just_space))\n sys.stdout.flush()\n print(\"\")\n print(\"--------------------------\")\n \ndef fatoraLU(A):\n U = np.copy(A) \n n = np.shape(U)[0] \n L = np.eye(n) \n for j in np.arange(n-1): \n for i in np.arange(j+1,n): \n L[i,j] = U[i,j]/U[j,j] \n for k in np.arange(j+1,n): \n U[i,k] = U[i,k] - L[i,j]*U[j,k] \n U[i,j] = 0 \n# print(\"L:\",L)\n# print(\"U\",U)\n return L, U\ndef triangularSuperior(U,b,n):\n x = np.zeros((len(b),1),dtype = np.float64)\n x[n-1] = b[n-1]/U[n-1][n-1]\n for i in range (n-1, -1,-1):\n s = b[i]\n for j in range(i+1, n):\n s = s-U[i][j]*x[j]\n x[i] = s/U[i][i]\n return x\ndef Gauss(a,b,n):\n for k in range(0,n):\n for i in range(k+1,n):\n m = a[i][k]/a[k][k] \n for j in range(k,n):\n a[i][j]=a[i][j]-m*a[k][j]\n b[i] = b[i] - m*b[k]\n x = triangularSuperior(a,b,n)\n return x\n ############################################################################################## \nN=3\n# g=0\nr=1.0\ni=0\ntheta=np.pi*2\nh=(r/N)\nk=theta*h\n\n\n#criando matriz original\nmatriz_original=np.zeros((N**2,N**2), np.float64)\n\n\n#vetores da matriz principal N X N \n\nvetor_dP=np.ones((N**2), np.float64)*a(i+1, h,k)#diagonal principal\nvetor_d1=np.ones(((N**2)-1), np.float64)* b(i+1, h,k)#diagonal parte de cima\nvetor_d2=np.ones(((N**2)-1), np.float64)* b(i+1, h,k)#diagonal parte de baixo\n\n#vetor da matriz_baixo N X N\nvetor_dP2= np.ones((N**2)-3, np.float64)*c(i+1,h)\n\n#vetor da matriz_cima N X N, irei multiplicar de acordo com o tamanho original\nvetor_dP3=np.ones((N**2)-3, np.float64)*d(i+1,h)\n\n#juntando todas as diagonais\nmatriz_original=np.diagflat(vetor_dP, 0)+np.diagflat(vetor_d1,1)+np.diagflat(vetor_d2, -1)+ np.diagflat(vetor_dP3, 3)+np.diagflat(vetor_dP2, -3) \n#agora, irei multiplicar os valores com os seus respectivos valores de i\nvetor_multiplicador=np.array([[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],[2.0,2.0,0.0,4.0,4.0,4.0,2.0,2.0,2.0],[2.0,2.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0],[2.0,2.0,2.0,4.0,4.0,4.0,2.0,2.0,2.0],[0.0,0.0,0.0,3.0,3.0,0.0,9.0,9.0,9.0],[0.0,0.0,0.0,3.0,3.0,3.0,9.0,9.0,9.0],[0.0,0.0,0.0,3.0,3.0,3.0,9.0,9.0,9.0]]) \n#multiplicando pela matriz original\nmatriz_original=matriz_original*vetor_multiplicador\nprint(\"Matriz original já com os valores de i:\")\nimprimeMatriz(matriz_original) \n\n####################################################################################################\n####################### RESOLUÇÃO COM LU #######################################\n####################################################################################################\nF=np.ones((N**2), np.float64)*20 #função f\nL,U = fatoraLU(matriz_original)\nY = Gauss(L,F,len(F))\nx = triangularSuperior(U,Y,len(Y))\nprint(\"Resultado da discretização utilizando coordenadas polares:\",x)","sub_path":"coordenadas_polares.py","file_name":"coordenadas_polares.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"203656340","text":"import time\n\nimport asyncio\nfrom venom.rpc.comms.grpc import create_server\nfrom venom.rpc.method import rpc\nfrom hello import HelloRequest, HelloResponse\nfrom venom.rpc import Service, Venom\n\n\nclass HelloService(Service):\n @rpc\n async def say_hello(self, request: HelloRequest) -> HelloResponse:\n await asyncio.sleep(1)\n return HelloResponse(message=f\"Hello, {request.name}!\")\n\n\napp = Venom()\napp.add(HelloService)\n\nserver = create_server(app)\n\nif __name__ == '__main__':\n server.add_insecure_port('[::]:50053')\n server.start()\n try:\n while True:\n time.sleep(24 * 60 * 60)\n except KeyboardInterrupt:\n server.stop(0)\n","sub_path":"examples/grpc/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"648667349","text":"#print('Hola, esta es mi primera calculadora: ')\n#x = int(input('Ingresa el primer numero que quieres sumar: '))\n#xx = str(x)\n#print('Ya tengo el primer numero, Ahora necesito otro para sumar:')\n#y = int(input('¿Cual es el otro numero que quieres sumar: '))\n#yy = str(y)\n#suma = x+y\n#print('¡Listo, la suma de los numeros : ' + xx + ' Y el numero: ' + yy + ' es: ', suma)\n\n#print('Hola, esta es mi primera calculadora: ')\n#x = int(input('Enter the frist number: '))\n#xx = str(x)\n#y = int(input('Enter the secod number: '))\n#yy = str(y)\n#suma = x+y\n#print(xx, '+', yy, '=', suma)\n\n\nprint('Hola, esta es mi primera calculadora: ')\nx = int(input('Enter the frist number: '))\ny = int(input('Enter the secod number: '))\nsuma = x+y\nprint(str(x) + '+' + str(y) + '=' + str(suma))\n\n\n","sub_path":"Estudio_Python/calculadora.py","file_name":"calculadora.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"37354234","text":"\"\"\" Collection of syllogistic helper functions.\n\n\"\"\"\n\n#: List of syllogistic task identifiers.\nSYLLOGISMS = []\nfor _prem1 in ['A', 'I', 'E', 'O']:\n for _prem2 in ['A', 'I', 'E', 'O']:\n for _fig in ['1', '2', '3', '4']:\n SYLLOGISMS.append(_prem1 + _prem2 + _fig)\n\n#: List of syllogistic responses.\nRESPONSES = []\nfor _quant in ['A', 'I', 'E', 'O']:\n for _direction in ['ac', 'ca']:\n RESPONSES.append(_quant + _direction)\nRESPONSES.append('NVC')\n\ndef encode_task(task_tuple):\n \"\"\" Encodes a syllogistic task by transforming a task tuple string into\n its corresponding identifier.\n\n Parameters\n ----------\n task_tuple : list(list(str))\n Task tuple in list representation (e.g.,\n [['Some', 'models', 'managers'], ['All', 'models', 'clerks']])\n\n Returns\n -------\n str\n Syllogistic task identifier (e.g., 'AI1'). Figures are defined in\n accordance to Khemlani et al. (2012).\n\n \"\"\"\n\n prem_1, prem_2 = task_tuple\n\n quant1 = prem_1[0].replace('All', 'A').replace(\n 'Some not', 'O').replace('Some', 'I').replace('No', 'E')\n quant2 = prem_2[0].replace('All', 'A').replace(\n 'Some not', 'O').replace('Some', 'I').replace('No', 'E')\n figure = 1\n\n if prem_1[1] == prem_2[1]:\n figure = 4\n elif prem_1[2] == prem_2[1]:\n figure = 1\n elif prem_1[2] == prem_2[2]:\n figure = 3\n elif prem_1[1] == prem_2[2]:\n figure = 2\n else:\n raise ValueError('Could not determine figure of:', task_tuple)\n\n return quant1 + quant2 + str(figure)\n\ndef encode_response(response, task):\n \"\"\" Encodes a syllogistic response by transforming the tuple containing the\n response string and the task tuple into its string representation.\n\n Parameters\n ----------\n response : list(list(str))\n Response encodings.\n\n task : list(list(str))\n Task tuple representation.\n\n Returns\n -------\n str\n Encoded response (e.g., 'Iac').\n\n \"\"\"\n\n if not isinstance(response[0], list):\n response = [response]\n\n if response[0] == 'NVC':\n return 'NVC'\n\n if response[0][0] == 'NVC':\n return 'NVC'\n\n object_sets = [set(x[1:]) for x in task]\n midterm = object_sets[0].intersection(object_sets[1])\n obj_a = object_sets[0] - midterm\n\n quant = response[0][0].replace('All', 'A').replace(\n 'Some not', 'O').replace('Some', 'I').replace('No', 'E')\n\n return quant + ('ac' if response[0][1] == list(obj_a)[0] else 'ca')\n\ndef decode_response(enc_response, task):\n \"\"\" Decodes an encoded syllogistic response by transforming it to the\n corresponding tuple representation and inserting the appropriate terms.\n\n Parameters\n ----------\n enc_response : str\n Encoded syllogistic response (e.g., 'Aac').\n\n task : list(str)\n Syllogistic task in the tuple list representation (e.g.,\n [['Some', 'models', 'managers'], ['All', 'models', 'clerks']]).\n\n Returns\n -------\n list\n List representation of the response to decode.\n\n \"\"\"\n\n if enc_response == 'NVC':\n return [['NVC']]\n if enc_response == ['NVC']:\n return [enc_response]\n if enc_response == [['NVC']]:\n return enc_response\n\n obj_a = set(task[0][1:]) - set(task[1][1:])\n obj_c = set(task[1][1:]) - set(task[0][1:])\n\n quant = enc_response[0].replace('A', 'All').replace(\n 'I', 'Some').replace('O', 'Some not').replace('E', 'No')\n if enc_response[1:] == 'ac':\n return [[quant, list(obj_a)[0], list(obj_c)[0]]]\n\n return [[quant, list(obj_c)[0], list(obj_a)[0]]]\n","sub_path":"ccobra/syllogistic/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"425943278","text":"# define global constants for other scripts\nfrom datetime import datetime\n\nGLOBAL_CAP_CONST = 1\n\n# Customize the backtesting start time\nSTART_TRADING_TIME = {\n 'USDTWD': datetime(2008, 1, 1), \n 'USDSGD': datetime(2000, 1, 1), \n 'USDRUB': datetime(2008, 1, 1), \n 'USDCOP': datetime(2000, 1, 1), \n 'USDTRY': datetime(2004, 1, 1)\n}\n","sub_path":"trading/global_constant.py","file_name":"global_constant.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"525794538","text":"from rest_framework import views, status\nfrom rest_framework.response import Response\nimport requests\nimport ujson as json\nimport os\nfrom trello import TrelloClient, Member\nfrom card.models import Card\nfrom task.models import Task\nfrom user.models import User\n\n\nclass FetchView(views.APIView):\n\n def post(self, request, *args, **kwargs):\n\n d3_board = self.get_d3_board()\n lists = d3_board.open_lists()\n cards = lists[0].list_cards()\n\n for c in cards:\n card = self.extract_card_data(c)\n self.save_user(card.get('user'))\n self.save_card(\n card.get('id'),\n card.get('description'),\n card.get('user').get('id'))\n self.save_tasks(card)\n\n return Response({\n 'Response': 'Sucesso'},\n status=status.HTTP_200_OK)\n\n def save_user(self, userToSave):\n\n userID = userToSave.get('id')\n userName = userToSave.get('name')\n\n user = User.objects.filter(idUser=userID).first()\n\n if user:\n return\n\n newUser = User()\n newUser.idUser = userID\n newUser.nome = userName\n newUser.save()\n\n return\n\n def save_card(self, cardID, cardDescr, cardUserID):\n\n card = Card.objects.filter(idCard=cardID).first()\n user = User.objects.filter(idUser=cardUserID).first()\n\n if card:\n return\n\n newCard = Card()\n newCard.idCard = cardID\n newCard.description = cardDescr\n newCard.user = user\n newCard.save()\n\n return\n\n def save_tasks(self, card):\n tasks = card.get('tasks')\n card = Card.objects.filter(idCard=card.get('id')).first()\n\n for t in tasks:\n task = Task()\n task.idTask = t.get('id')\n task.description = t.get('description')[:250]\n task.card = card\n task.save()\n\n def is_d3_board(self, board):\n \"\"\"\n Check if the board is the 'D3 Board' by checking it's id\n \"\"\"\n\n if board is None:\n return False\n elif board.id == os.environ.get('D3_BOARD', None):\n return True\n else:\n return False\n\n def get_d3_board(self):\n client = TrelloClient(\n api_key=os.environ.get('TRELLO_API_KEY', None),\n token=os.environ.get('TRELLO_TOKEN', None),\n )\n\n all_boards = client.list_boards()\n d3_board = None\n for board in all_boards:\n if (self.is_d3_board(board)):\n d3_board = board\n break\n return d3_board\n\n def extract_card_data(self, card):\n \"\"\"\n extract info from trello's card\n\n return an object:\n {\n id,\n description,\n tasks,\n user,\n }\n \"\"\"\n if card is None:\n return None\n\n member = self.get_card_first_member(card)\n\n tasks = self.get_card_tasks(card)\n\n return {\n 'id': card.id,\n 'description': card.desc,\n 'tasks': tasks,\n 'user': member,\n }\n\n def get_card_tasks(self, card):\n \"\"\"\n return an array of objects:\n [{\n id,\n description,\n checked,\n }]\n \"\"\"\n check_lists = card.fetch_checklists()\n tasks = []\n for check_list in check_lists:\n # check_list.name = 'Segunda' | 'Terça' | ...\n tasks.extend(self.format_check_list_tasks(check_list))\n\n return tasks\n\n def format_check_list_tasks(self, check_list):\n \"\"\"\n return an array of objects:\n [{\n id,\n description,\n checked,\n }]\n \"\"\"\n if check_list is None:\n return None\n\n tasks = []\n for task in check_list.items:\n tasks.append({\n 'id': task['id'],\n 'description': task['name'],\n 'checked': task['checked'],\n })\n\n return tasks\n\n def get_card_first_member(self, card):\n \"\"\"\n return an object:\n {\n id,\n name,\n }\n \"\"\"\n memberId = card.idMembers[0]\n trelloMember = Member(card.client, memberId)\n member = trelloMember.fetch()\n\n return {\n 'id': member.id,\n 'name': member.full_name,\n }\n","sub_path":"user/fetch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"322979893","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\n分词模块\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport json\nimport re\n\nimport data_preprocess\n\nindex_data = 0\n\nfile_name = \"../data/mixCorpus_test.txt\"\nword_id, label_id = data_preprocess.data2id(file_name)\n\n\ndef get_batch(batch_size, time_step, word_id, label_id, label_size):\n \"\"\"\n 产生批量训练��据\n :param batch_size: \n :param time_step: \n :param word_id: \n :param label_id: \n :param label_size: \n :return: train_word_id 维度 [batch_size][time_step]\n train_label_id [batch_size][time_step][label_size]\n \"\"\"\n\n global index_data\n train_word_id = np.zeros(shape=[batch_size, time_step])\n train_label_id = np.zeros(shape=[batch_size, time_step, label_size])\n index = index_data\n for i in range(batch_size):\n index = index % len(word_id)\n while len(word_id[index]) > time_step:\n index = (index + 1) % len(word_id)\n for j in range(len(word_id[index])):\n train_word_id[i, j] = word_id[index][j]\n train_label_id[i, j, label_id[index][j]] = 1\n for j in range(len(word_id[index]), time_step):\n train_label_id[i, j, 0] = 1\n # 下一个句子\n index = index + 1\n index_data = index\n print('*'*30)\n print(index_data)\n print('*' * 30)\n # index_data = index_data + 1\n return train_word_id, train_label_id\n\n\ndef data_tranform(time_step, word_id):\n \"\"\"\n 产生批量训练数据\n :param time_step: \n :param word_id: \n :return: train_word_id 维度 [batch_size][time_step] \n \"\"\"\n train_word_id = np.zeros(shape=[len(word_id), time_step])\n for i in range(len(word_id)):\n for j in range(len(word_id[i])):\n if j < time_step:\n train_word_id[i, j] = word_id[i][j]\n return train_word_id\n\n\nclass ConfigArgs(object):\n \"\"\"分词参数配置\"\"\"\n label_size = 5 # 类别数\n init_scale = 0.01 # 相关参数的初始值为随机均匀分布,范围是[-init_scale,+init_scale]\n learning_rate = 1e-3 # 学习速率,在文本循环次数超过max_epoch以后会逐渐降低\n max_grad_norm = 10 # 用于控制梯度膨胀,如果梯度向量的L2模超过max_grad_norm,则等比例缩小\n num_layers = 1 # lstm层数\n num_steps = 20 # 单个数据中,序列的长度。\n hidden_size = 512 # 隐藏层中单元数目\n keep_prob = 0.5 # 用于dropout.每批数据输入时神经网络中的每个单元会以1-keep_prob的概率不工作,可以防止过拟合\n batch_size = 8 # 每批数据的规模,每批有10个。\n max_loop = 2000 # 运行次数\n charNum = 10000 # 词典大小\n char_dim = 512 # 每个字符嵌入的维度\n# hide_dim = 200 # 隐层维度\n\n\nclass WordSegment(object):\n \"\"\"\n 分词\n \"\"\"\n\n def __init__(self, config, is_training, embedding_char=None):\n \"\"\"\n 初始化函数\n :param config: 模型的配置参数 \n :param emdeding_word: 训练好的词向量\n \"\"\"\n self.config = config\n self.is_training = is_training\n self.embedding_char = embedding_char\n\n # 初始化\n self.sess = None\n self.graph = None\n self.init = None\n self.losses = None\n self._train_op = None\n self.saver = None\n # 构建图,初始化\n self.build_graph()\n self.init_op()\n\n def init_op(self):\n \"\"\"\n 分词初始化\n :return: 无\n \"\"\"\n self.sess = tf.Session(graph=self.graph)\n self.sess.run(self.init)\n\n def build_graph(self):\n \"\"\"\n 模型构建\n \"\"\"\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n # 维度 [batch][char_id]\n self.char_id = tf.placeholder(tf.int32, shape=[None, self.config.num_steps])\n # 维度 [batch][char_id][label_size]\n self.labels = tf.placeholder(tf.float32, shape=[None, self.config.num_steps, self.config.label_size])\n\n def lstm_cell():\n return tf.contrib.rnn.GRUCell(self.config.hidden_size)\n\n attn_cell = lstm_cell\n if self.is_training and self.config.keep_prob < 1: # dropout 防止过拟合\n def attn_cell():\n return tf.contrib.rnn.DropoutWrapper(\n lstm_cell(), output_keep_prob=self.config.keep_prob)\n\n cell_1_forward = tf.contrib.rnn.MultiRNNCell( # 多层lstm\n [attn_cell() for _ in range(self.config.num_layers)], state_is_tuple=True)\n cell_1_backward = tf.contrib.rnn.MultiRNNCell( # 多层lstm\n [attn_cell() for _ in range(self.config.num_layers)], state_is_tuple=True)\n\n cell_2_forward = tf.contrib.rnn.MultiRNNCell( # 多层lstm\n [attn_cell() for _ in range(self.config.num_layers)], state_is_tuple=True)\n cell_2_backward = tf.contrib.rnn.MultiRNNCell( # 多层lstm\n [attn_cell() for _ in range(self.config.num_layers)], state_is_tuple=True)\n\n # 嵌入向量\n with tf.device(\"/cpu:0\"):\n # 获取词嵌入\n if self.embedding_char is not None:\n embedding_char = tf.Variable(self.embedding_char,\n trainable=True, name=\"embedding_char\", dtype=tf.float32)\n else:\n embedding_char = tf.Variable(\n tf.truncated_normal([self.config.charNum, self.config.char_dim], stddev=0.1),\n trainable=True, name=\"embedding_char\", dtype=tf.float32)\n inputs_char = tf.nn.embedding_lookup(embedding_char, self.char_id)\n\n # BiLSTM\n outputs_1, _, _ = tf.contrib.rnn.static_bidirectional_rnn(\n cell_1_forward, cell_1_backward, tf.unstack(inputs_char, self.config.num_steps, 1),\n dtype=tf.float32, scope='bidirectional_rnn_0')\n # dropout\n if self.is_training and self.config.keep_prob < 1:\n outputs_1 = tf.nn.dropout(outputs_1, self.config.keep_prob) # 维度 [step][None][feature*2]\n\n # BiLSTM\n outputs_2, _, _ = tf.contrib.rnn.static_bidirectional_rnn(\n cell_2_forward, cell_2_backward, tf.unstack(outputs_1, self.config.num_steps, 0),\n dtype=tf.float32, scope='bidirectional_rnn_1')\n\n # dropout\n if self.is_training and self.config.keep_prob < 1:\n outputs_2 = tf.nn.dropout(outputs_2, self.config.keep_prob) # 维度 [step][None][feature*2]\n else:\n outputs_2 = tf.stack(outputs_2)\n\n weight = tf.Variable(tf.random_uniform([self.config.hidden_size*2, self.config.label_size], -0.1, 0.1))\n bias = tf.Variable(tf.zeros([self.config.label_size]))\n\n # 预测结果保存\n y_pre_sum = []\n for t_s in range(self.config.num_steps):\n y_pre = tf.nn.softmax(\n tf.matmul(outputs_2[t_s, :, :], weight) + bias\n )\n y_pre_sum.append(y_pre) # 维度 [step][batch_size][labels]\n cross_entropy = -tf.reduce_sum(self.labels[:, t_s, :] * tf.log(y_pre + 1e-10))\n tf.add_to_collection('losses', cross_entropy)\n\n # 结果 [step][batch_size]\n self.correct_prediction = tf.argmax(tf.stack(y_pre_sum), 2)\n\n # 模型评估\n for each_ in range(len(y_pre_sum)):\n correct_prediction = tf.equal(tf.argmax(y_pre_sum[each_], 1),\n tf.argmax(self.labels[:, each_, :], 1))\n tf.add_to_collection('evaluate', tf.reduce_mean(tf.cast(correct_prediction, \"float\")))\n self.evaluate = tf.add_n(tf.get_collection('evaluate'), name=\"evaluate_loss\")/self.config.num_steps\n\n # 优化损失函数\n self.losses = tf.add_n(tf.get_collection('losses'), name=\"total_loss\")\n\n self.train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(self.losses)\n '''\n # 自适应学习率调准\n self.AdaDelta_train_op = tf.train.AdadeltaOptimizer(1e-3).minimize(self.losses)\n self.Adam_train_op = tf.train.AdamOptimizer(1e-3).minimize(self.losses)\n '''\n # 梯度限制, 防止梯度爆炸\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.losses, tvars),\n self.config.max_grad_norm)\n optimizer = tf.train.AdamOptimizer(self.config.learning_rate)\n self._train_op = optimizer.apply_gradients(\n zip(grads, tvars),\n global_step=tf.contrib.framework.get_or_create_global_step())\n\n # init 和 saver\n self.init = tf.global_variables_initializer()\n self.saver = tf.train.Saver()\n\n def train_model(self):\n \"\"\"\n 模型的训练\n :return: 无 \n \"\"\"\n # 训练模型\n for i in range(self.config.max_loop):\n train_word_id, train_label_id = get_batch(self.config.batch_size, self.config.num_steps,\n word_id, label_id, self.config.label_size)\n feed_dict = {\n self.char_id: train_word_id,\n self.labels: train_label_id\n }\n loss, _, evaluate = self.sess.run([self.losses, self._train_op, self.evaluate], feed_dict=feed_dict)\n if i % 10 == 0:\n print(\"迭代次数:\", i,\" 损失:\", loss, ' 准确率:', evaluate)\n\n def predict(self, train_word_id):\n \"\"\"\n 预测\n :param train_word_id: 预测字符的id \n :return: # 维度 [step][batch_size]\n \"\"\"\n feed_dict = {\n self.char_id: train_word_id,\n }\n # 结果 [step][batch_size]\n correct_prediction = self.sess.run(self.correct_prediction, feed_dict=feed_dict)\n return correct_prediction\n\n def predict_char(self, word, words_dict):\n \"\"\"\n 标注句子,分词\n :param word: 需分词的句子\n :param words_dict: 字符字典\n :return: 返回每个字符的 label id\n 维度 [step][batch_size]\n \"\"\"\n char_id = data_preprocess.char2id(word, words_dict)\n char_id = data_tranform(self.config.num_steps, char_id)\n label_id = self.predict(char_id)\n return label_id\n\n def id2label(self, word, label_id, labels_rdict):\n \"\"\"\n 将分词的标注转为 对应的标签\n :param word: 需标注的文本\n :param label_id: 标注的文本对应的标签 # 维度 [step][batch_size]\n :param labels_dict: 标签对应的字典\n :return: \n \"\"\"\n labels = []\n for i in range(len(word)):\n label = []\n for j in range(len(word[i])):\n if j < self.config.num_steps and label_id[j][i] in labels_rdict.keys():\n label.append(labels_rdict[label_id[j][i]])\n else:\n label.append('o')\n labels.append(label)\n return labels\n\n def save_model(self, save_path):\n \"\"\"\n 模型的保存\n :param save_path: 保存的路径 \n :return: 返回模型路径\n \"\"\"\n if os.path.isfile(save_path):\n raise RuntimeError('the save path should be a dir')\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n # 记录tf模型\n tf_path = os.path.join(save_path, 'tf_vars')\n if os.path.exists(tf_path):\n os.remove(tf_path)\n self.saver.save(self.sess, tf_path)\n print(\"模型保存到: %s\" % save_path)\n return save_path\n\n def restore(self, path):\n \"\"\"\n 模型的加载\n :param path: 模型加载路径\n :return: 无\n \"\"\"\n with self.graph.as_default():\n self.saver.restore(self.sess, path + '/tf_vars')\n\n\ndef load_data(path, name, reverse):\n \"\"\"\n 加载数据\n :param path: 路径 \n :param name: 文件名\n :param reverse: 是否是逆向字典\n :return: 返回对应字典的类型\n \"\"\"\n if reverse is False:\n dictionary = json.load(open(os.path.join(path, name), 'rb'))\n else:\n reverse_dictionary = json.load(open(os.path.join(path, name), 'rb'))\n dictionary = {int(key): val for key, val in reverse_dictionary.items()}\n return dictionary\n\n\ndef load_model_data():\n \"\"\"\n 加载模型需要的数据\n :return: 模型需要的数据 字典\n \"\"\"\n path = './dictionary'\n model_dict = load_data(path, 'model_dict.json', False)\n model_rdict = load_data(path, 'model_rdict.json', True)\n label_dict = load_data(path, 'label_dict.json', False)\n label_rdict = load_data(path, 'label_rdict.json', True)\n return model_dict, model_rdict, label_dict, label_rdict\n\n\ndef load_model(model_path=\"./model_data\"):\n \"\"\"\n 加载模型\n :param model_path: \n :return: 返回模型 \n \"\"\"\n ws = WordSegment(ConfigArgs, False, None)\n ws.restore(model_path)\n return ws\n\n\ndef save_model(model_path=\"./model_data\"):\n ws = WordSegment(ConfigArgs, True, None)\n ws.train_model()\n # 保存模型\n ws.save_model(save_path=model_path)\n\n\ndef predict(ws, sentence):\n char_list = word2list(sentence)\n model_dict, model_rdict, label_dict, label_rdict = load_model_data()\n label_id = ws.predict_char(char_list, model_dict)\n labels = ws.id2label(char_list, label_id, label_rdict)\n return list2json(char_list, labels)\n\n\ndef word2list(sentence):\n \"\"\"\n 把句子转化为相应的字符数组\n :param sentence: 句子\n :return: 字符数组\n \"\"\"\n regular_expression = u'[,.!?,。!?]'\n sentence = unicode(sentence, \"utf-8\")\n sen = re.split(regular_expression, sentence)\n char_list = []\n for i in range(len(sen)):\n words = [w for w in sen[i]]\n char_list.append(words)\n return char_list\n\n\ndef list2json(sentence, char_list):\n result = []\n for i in range(len(char_list)):\n word = []\n w = ''\n k = 0\n for j in range(len(char_list[i])):\n if char_list[i][j] in ['s', 'o']:\n if w.strip() != '':\n temp = dict()\n temp['id'] = k\n temp['cont'] = w\n k = k + 1\n word.append(temp)\n temp = dict()\n temp['id'] = k\n temp['cont'] = sentence[i][j]\n word.append(temp)\n k = k + 1\n w = ''\n if char_list[i][j] in ['b', 'm', 'e']:\n w = w + sentence[i][j]\n if char_list[i][j] == 'e':\n temp = dict()\n temp['id'] = k\n temp['cont'] = w\n word.append(temp)\n k = k + 1\n w = ''\n if j == len(char_list[i])-1 and w.strip() != '':\n temp = dict()\n temp['id'] = k\n temp['cont'] = w\n word.append(temp)\n word.append(w)\n result.append(word)\n return json.dumps(result)\n\n\nif __name__ == '__main__':\n save_model()\n ws = load_model()\n # sentence = ['我是中国人', '结婚的和没结婚的']\n sentence = '我是中国人。结婚的和没结婚的'\n labels = predict(ws, sentence)\n print(labels)\n\n","sub_path":"word_seg/model/wordseg.py","file_name":"wordseg.py","file_ext":"py","file_size_in_byte":15749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"483943088","text":"#Imports to get django setup\nimport os\nimport sys\nimport django\n\nsys.path.append(\"/code\")\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"core.settings\")\ndjango.setup()\n\n#Rest of the imports\nimport logging\nimport boto3\nimport datetime\nimport requests\nimport pytz\n\nfrom django.conf import settings\nfrom archive.models import Collection, Picture\nfrom django.db import connection,transaction\n\nFORBIDDEN_NAMES = [\"documents\", \"cache\"]\n\nlogger = logging.getLogger('date')\n\nlogger.info(\"STARTING IMAGE UPLOADER\")\n\ndef s3_config():\n return boto3.client('s3',\n endpoint_url=settings.AWS_S3_ENDPOINT_URL,\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)\n\nclient = s3_config()\n\nquery_list = []\ncollection_list = []\nyear_list = []\n\n\nresponse = client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=settings.PRIVATE_MEDIA_LOCATION + \"/\", Delimiter=\"/\")\n\n# Gets a list of years\nfor obj in response.get('CommonPrefixes'):\n year = obj.get('Prefix').replace(settings.PRIVATE_MEDIA_LOCATION,\"\").replace(\"/\",\"\")\n if year not in FORBIDDEN_NAMES:\n year_list.append(year)\n\nfor year in year_list:\n response = client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=settings.PRIVATE_MEDIA_LOCATION + f\"/{year}/\", Delimiter=\"/\")\n album_year = int(year)\n # For every year, list containing albums\n for obj in response.get('CommonPrefixes'):\n album_name = obj.get('Prefix').replace(settings.PRIVATE_MEDIA_LOCATION + f\"/{year}\",\"\").replace(\"/\",\"\")\n exists_check = Collection.objects.filter(title=album_name, pub_date__year=album_year).count()\n # check if album name not exists\n if exists_check == 0:\n logger.info(\"Album does not exist\")\n # Create a collection from album name\n collection = Collection(title=album_name, type=\"Pictures\", pub_date=datetime.datetime(album_year,1,1,10,10,tzinfo=pytz.timezone('Europe/Helsinki')))\n # If an album with same name in a specific year does not exist, save the collection\n collection.save()\n response = client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=settings.PRIVATE_MEDIA_LOCATION + f\"/{year}/{album_name}\")\n contents = response.get('Contents')\n # For every album, list its contents\n for data in contents:\n path = data[\"Key\"].replace(settings.PRIVATE_MEDIA_LOCATION + \"/\", \"\")\n logger.info(path)\n picture_data = (path, False, collection.id)\n query_list.append(picture_data)\n\n\n# Creates a connection to the database and inserts the query list to the correct table\ncursor = connection.cursor()\n\nquery = ''' INSERT INTO archive_picture \n (image, favorite, collection_id) \n VALUES (%s,%s,%s) '''\n\ncursor.executemany(query, query_list)\ntransaction.commit()\n\nlogger.info(\"IMAGE UPLOADER COMPLETE\")\n","sub_path":"archive/s3_populate_db.py","file_name":"s3_populate_db.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"428346681","text":"from tkinter import *\nimport math\nfrom tkinter.scrolledtext import *\n#15/05/21\n#Caitlin Naylor \n#Job Cost/Charge Calulator\n\nclass Job:\n def __init__(self, job_num, name, distance, minutes, wof_and_tune, charge):\n self.job_num = job_num\n self.name = name\n self.distance = distance\n self.minutes = minutes\n self.wof_and_tune = wof_and_tune\n self.charge = charge\n\nclass JobCostGUI:\n def __init__(self, parent):\n self.jobs = []\n self.BG_COLOUR = \"#cceeff\"\n self.BTN_COLOUR = \"white\"\n self.FONT = \"Sans Serif\"\n #Add Jobs Frame\n self.add_job_frame = Frame(parent)\n self.add_job_frame.configure(pady = 10, padx = 10, bg = self.BG_COLOUR)\n self.add_job_frame.grid(row = 0, column = 0)\n\n #Company Logo\n #Suzy has supplied and given permission for this logo to be used in this program\n\n self.logo = PhotoImage(file = \"logo.gif\")\n self.logo_label = Label(self.add_job_frame, image = self.logo, bg = self.BG_COLOUR)\n self.logo_label.grid(row = 0, column = 0, columnspan = 4)\n \n #Add a Job Label\n self.add_job_label = Label(self.add_job_frame, text = \"Add a Job\",\n font = (self.FONT, 17), bg = self.BG_COLOUR)\n self.add_job_label.grid(row = 1, column = 0, sticky = NW, pady = 5)\n\n #Job Number Label\n self.job_num_label = Label(self.add_job_frame, text = \"Job Number\",\n font = (self.FONT, 11), bg = self.BG_COLOUR)\n self.job_num_label.grid(row = 2, column = 0, sticky = NW)\n\n #Job Number Input\n self.job_num_var = StringVar() #StringVar so that the text box is blank upon opening\n self.job_num_var.set(\"\")\n self.job_num_box = Entry(self.add_job_frame, font = (self.FONT, 10),\n textvariable = self.job_num_var, width = 30)\n self.job_num_box.grid(row = 2, column = 1, columnspan = 3, sticky = NW)\n\n #Name Label\n self.name_label = Label(self.add_job_frame, text = \"Customer Name\",\n font = (self.FONT, 11), bg = self.BG_COLOUR)\n self.name_label.grid(row = 3, column = 0, sticky = NW)\n\n #First Name Input\n self.first_name_var = StringVar()\n self.first_name_var.set(\"\")\n self.first_name_box = Entry(self.add_job_frame, font = (self.FONT, 10),\n width = 30, textvariable = self.first_name_var)\n self.first_name_box.grid(row = 4, column = 0, sticky = NW)\n\n #Last Name Input\n self.last_name_var = StringVar()\n self.last_name_var.set(\"\")\n self.last_name_box = Entry(self.add_job_frame, font = (self.FONT, 10),\n width = 30, textvariable = self.last_name_var)\n self.last_name_box.grid(row = 4, column = 1, columnspan = 3, sticky = NW)\n\n #First Name Label\n self.first_name_label = Label(self.add_job_frame, text = \"First Name\",\n font = (self.FONT, 8), bg = self.BG_COLOUR)\n self.first_name_label.grid(row = 5, column = 0, sticky = NW)\n\n #Last Name Label\n self.last_name_label = Label(self.add_job_frame, text = \"Last Name\",\n font = (self.FONT, 8), bg = self.BG_COLOUR)\n self.last_name_label.grid(row = 5, column = 1, sticky = NW)\n\n #Distance Travelled Label\n self.distance_label = Label(self.add_job_frame,\n text = \"Distance Travelled to Client (km)\",\n font = (self.FONT, 11), bg = self.BG_COLOUR)\n self.distance_label.grid(row = 6, column = 0, sticky = NW)\n\n #Distance Input\n self.distance_var = StringVar() #String not Int as IntVar automatically rounds down\n self.distance_var.set(\"\")\n self.distance_box = Entry(self.add_job_frame, font = (self.FONT, 10),\n width = 30, textvariable = self.distance_var)\n self.distance_box.grid(row = 6, column = 1, columnspan = 3, sticky = NW)\n\n #Minutes Spent on Virus Protection Label\n self.minutes_label = Label(self.add_job_frame,\n text = \"Minutes Spent on Virus Protection\",\n font = (self.FONT, 11), bg = self.BG_COLOUR)\n self.minutes_label.grid(row = 7, column = 0, sticky = NW)\n\n #Minutes Input\n self.minutes_var = StringVar() #StringVar so that the text box is blank upon opening\n self.minutes_var.set(\"\") \n self.minutes_box = Entry(self.add_job_frame, font = (self.FONT, 10),\n width = 30, textvariable = self.minutes_var)\n self.minutes_box.grid(row = 7, column = 1, columnspan = 3, sticky = NW)\n\n #Wof and tune Label\n wof_and_tune_label = Label(self.add_job_frame, text = \"Was a WOF and Tune Required?\",\n font = (self.FONT, 11), bg = self.BG_COLOUR)\n wof_and_tune_label.grid(row = 8, column = 0, sticky = NW)\n\n #Wof and tune radiobuttons\n self.wof_tune_var = StringVar()\n self.wof_tune_var.set(0)\n self.WOF_TUNE_RBS_NAMES = [\"Yes\", \"No\"]\n self.wof_tune_rbs = []\n \n for i in range(len(self.WOF_TUNE_RBS_NAMES)):\n self.wof_tune_rbs.append(Radiobutton(self.add_job_frame,\n text = self.WOF_TUNE_RBS_NAMES[i],\n value = self.WOF_TUNE_RBS_NAMES[i],\n variable = self.wof_tune_var,\n font = (self.FONT, 11), bg = self.BG_COLOUR))\n self.wof_tune_rbs[i].grid(row = 8, column = i +1, sticky = NW)\n\n #Enter Button to add a job\n #lambda code from\n #https://www.reddit.com/r/learnpython/comments/cdfmn5/tkinter_help_command_running_before_clicked/\n self.enter_job_btn = Button(self.add_job_frame, text = \"Enter\",\n font = (self.FONT, 11),width = 8, bg = self.BTN_COLOUR, \n command = lambda:self.store_input(Job)) \n self.enter_job_btn.grid(row = 9, column = 2, pady = 5, sticky = NE)\n\n #Reminder jobs a final label\n self.reminder_label = Label(self.add_job_frame,\n text = \"\"\"Note: All job entries are final so please\ndouble check before pressing enter\"\"\", \n font = (self.FONT, 7), bg = self.BG_COLOUR)\n self.reminder_label.grid(row = 10, column = 2, columnspan = 2)\n \n\n #Show Jobs Buttons\n self.show_jobs_btn = Button(self.add_job_frame, text = \"Show Jobs\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR, \n command = lambda:self.get_to_job_cards())\n self.show_jobs_btn.grid(row = 9, column = 3, padx = 5, pady = 5, sticky = NE)\n\n #Creation of other frames\n self.job_cards_frame = Frame(parent)\n\n self.error_message_frame = Frame(parent)\n\n self.summary_frame = Frame(parent)\n\n #Error message label creation\n self.error_label = Label(self.error_message_frame, font = (self.FONT, 9))\n\n def store_input(self, Job):\n self.error_label.configure(text = \"\") #Removing any previous error messages\n self.error_message_frame.grid_remove()\n\n #All input places need to be filled in \n if self.minutes_var.get() == \"\" or self.wof_tune_var.get() == \"0\" or \\\n self.first_name_var.get() == \"\" or self.last_name_var.get() == \"\" or \\\n self.job_num_var.get() == \"\" or self.distance_var.get() == \"\":\n self.add_job_frame.update_idletasks()\n self.error_label.configure(text = \"Please fill in all the entry areas before pressing enter.\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n else:\n #If letters or decimals are entered in a field that does not take that type \n while True:\n try:\n self.error_label.configure(text = \"\") #Removing any previous error messages\n self.error_message_frame.grid_remove()\n self.add_job_frame.update_idletasks() \n self.minutes = float(self.minutes_var.get())\n self.wof_and_tune = self.wof_tune_var.get()\n #WOF and tune cannot be No if minutes is zero as then no task has been done \n if self.minutes == 0 and self.wof_and_tune == \"No\":\n self.add_job_frame.update_idletasks()\n self.error_label.configure(text = \"\"\"There is no task chosen.\nPlease increase minutes spent on virus protection or change WOF and Tune to 'Yes'\"\"\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n break\n\n else:\n self.distance = float(self. distance_var.get())\n self.job_num = int(self.job_num_var.get())\n \n #If numbers below boundary are entered\n #Placed after storage as for calculation variables must be int/float\n if self.minutes < 0 or self.distance < 0 or self.job_num < 1:\n self.add_job_frame.update_idletasks()\n self.error_label.configure(text = \"\"\"That is not a valid entry. Please note that\njob number cannot be below 1, and minutes and distance cannot be below 0.\"\"\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n break\n else:\n self.name = self.first_name_var.get().strip().capitalize() + \" \" + \\\n self.last_name_var.get().strip().capitalize()\n\n\n #job number must be unique\n if len(self.jobs)>0:\n self.add_job_frame.update_idletasks()\n for i in range(len(self.jobs)):\n if self.job_num == self.jobs[i].job_num: #comparing with other job numbers\n self.add_job_frame.update_idletasks() \n self.error_label.configure(text = \"\"\"Please change the job number.\nThe entered job number belongs to another job.\"\"\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n self.job_num = 0 #this allows this entry to be easily identified as a repeat\n\n #Round Distance\n if self.distance % 1 >=0.5:\n self.distance = math.ceil(self.distance)\n else:\n self.distance = math.floor(self.distance)\n \n\n self.calc_charge()\n\n #Indivual Job Objects\n self.job = Job(self.job_num, self.name, self.distance, self.minutes,\n self.wof_and_tune, self.charge)\n \n #Collection of the Objects \n self.jobs.append(self.job)\n \n #If job number has been repeated, remove the entry that was saved\n if self.jobs[-1].job_num == 0:\n self.jobs.pop(-1)\n \n\n #Reset Input Areas\n if self.job_num !=0:\n self.job_num_var.set(\"\")\n self.first_name_var.set(\"\")\n self.last_name_var.set(\"\")\n self.distance_var.set(\"\")\n self.minutes_var.set(\"\")\n self.wof_tune_var.set(0)\n\n break\n \n \n except:\n self.add_job_frame.update_idletasks() \n self.error_label.configure(text = \"\"\"That is not a valid entry. Please note that job number, minutes,\nand distance must be numbers and that job number must be a whole number.\"\"\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n break\n \n\n def calc_charge(self):\n self.charge = 0\n FLAT_RATE = 10\n if self.distance <= 5:\n self.charge += FLAT_RATE\n else:\n self.charge += FLAT_RATE + ((self.distance - 5)*0.5)\n\n if self.wof_and_tune == self.WOF_TUNE_RBS_NAMES[0]: #yes\n self.charge += 100\n\n if self.minutes >0:\n self.charge += 0.80 *self.minutes\n\n #making charge 2dp as common for money\n #code inspired by:\n #https://www.kite.com/python/answers/how-to-print-a-float-with-two-decimal-places-in-python#:~:\n #text=Use%20str.,number%20with%20two%20decimal%20places.\n self.charge = \"{:.2f}\".format(self.charge) \n\n\n def get_to_job_cards(self):\n self.error_label.configure(text = \"\")\n self.error_message_frame.grid_remove() #removing any previous error messages\n if len(self.jobs)>0:\n self.add_job_frame.grid_remove()\n self.summary_frame.grid_remove()\n self.job_cards_frame.grid(row = 0, column = 0)\n self.job_cards_frame.configure(pady = 10, padx = 13, bg = self.BG_COLOUR)\n self.index = 0 #which job the cards are on\n self.job_cards_frame.update_idletasks()\n #Company Logo\n #Suzy has supplied and given permission for this logo to be used in this program\n\n self.logo_label = Label(self.job_cards_frame, image = self.logo, bg = self.BG_COLOUR)\n self.logo_label.grid(row = 0, column = 0, columnspan = 4)\n\n #Jobs Heading Label\n self.jobs_label = Label(self.job_cards_frame, text = \"Jobs\",\n font = (self.FONT, 17), pady = 5, bg = self.BG_COLOUR)\n self.jobs_label.grid(row = 1, column = 0, sticky = NW, pady = 5)\n\n #Text Box of Job Info\n self.job_info = Text(self.job_cards_frame, width = 48, height = 3,\n font = (self.FONT, 13), pady = 8, padx = 8)\n self.job_info.grid(row = 2, column = 0, columnspan = 4)\n\n\n self.job_info.insert(END,\"Job Number: \"+ str(self.jobs[self.index].job_num) + \"\\n\" +\n \"Customer Name: \" + self.jobs[self.index].name + \"\\n\" +\n \"Total Charge: $\" + str(self.jobs[self.index].charge))\n\n self.job_info.configure(state = 'disabled') #Disabling so the box is not typable in\n\n #Next and Prev Buttons\n self.next_card_btn = Button(self.job_cards_frame, text = \"Next Job\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR,\n command = self.next_job)\n self.next_card_btn.grid(row = 3, column = 2, sticky = NW, pady = 5)\n\n self.prev_card_btn = Button(self.job_cards_frame, text = \"Prev Job\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR,\n command = self.prev_job)\n self.prev_card_btn.grid(row = 3, column = 1, sticky = NE, pady = 5, padx = 5)\n\n #Getting to Add a Job Frame Button\n self.add_job_btn = Button(self.job_cards_frame, text = \"Add a Job\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR, \n command = self.get_to_add_jobs)\n self.add_job_btn.grid(row = 4, column = 3, sticky = NE, pady = 5)\n\n #Getting to Summary Frame Button\n #Icon from flaticon, free licensed for use,\n self.icon = PhotoImage(file = \"info-button.png\")\n self.summary_btn = Button(self.job_cards_frame, image = self.icon,\n font = (self.FONT, 11), width = 30, height = 30,\n bg = self.BTN_COLOUR, command = self.get_to_summary)\n self.summary_btn.grid(row = 1, column = 3, sticky = NE, pady = 5)\n \n else:\n self.add_job_frame.update_idletasks()\n self.error_label.configure(text = \"There are no jobs stored\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n\n \n def next_job(self):\n if len(self.jobs) > 1:\n if self.index != (len(self.jobs)-1): #if at end of list, go back to start\n self.index+=1\n else:\n self.index = 0\n\n self.job_info.configure(state = \"normal\") #undisabling box so content can change\n #updating text box to info for next job\n self.job_info.delete(1.0, END)\n self.job_info.insert(END,\"Job Number: \"+ str(self.jobs[self.index].job_num) + \"\\n\" +\n \"Customer Name: \" + self.jobs[self.index].name + \"\\n\" +\n \"Total Charge: $\" + str(self.jobs[self.index].charge))\n self.job_info.configure(state = \"disabled\")\n else:\n self.error_label.configure(text = \"There is only one job stored\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N) \n\n def prev_job(self):\n if len(self.jobs) > 0:\n if self.index !=0:\n self.index-=1\n else:\n self.index = (len(self.jobs)-1)\n\n self.job_info.configure(state = \"normal\")\n self.job_info.delete(1.0, END)\n self.job_info.insert(END,\"Job Number: \"+ str(self.jobs[self.index].job_num) + \"\\n\" +\n \"Customer Name: \" + self.jobs[self.index].name + \"\\n\" +\n \"Total Charge: $\" + str(self.jobs[self.index].charge))\n self.job_info.configure(state = \"disabled\")\n else:\n self.error_label.configure(text = \"There is only one job stored\")\n self.error_label.grid(row = 0, column = 1 )\n self.error_message_frame.grid(row = 0, column = 0, sticky = N)\n\n def get_to_add_jobs(self):\n self.error_label.configure(text = \"\")\n self.error_message_frame.grid_remove() #removing any previous error messages\n self.job_cards_frame.grid_remove()\n self.summary_frame.grid_remove()\n self.add_job_frame.grid(row = 0, column = 0)\n self.add_job_frame.update_idletasks()\n\n def get_to_summary(self):\n self.job_cards_frame.grid_remove()\n self.summary_frame.grid(row = 0, column = 0)\n self.summary_frame.update_idletasks()\n self.summary_frame.configure(pady = 10, padx = 13, bg = self.BG_COLOUR)\n\n #Company Logo\n #Suzy has supplied and given permission for this logo to be used in this programme\n\n self.logo_label = Label(self.summary_frame, image = self.logo, bg = self.BG_COLOUR)\n self.logo_label.grid(row = 0, column = 0, columnspan = 2)\n\n #Summary Heading Label\n self.summary_label = Label(self.summary_frame, text = \"Summary of Jobs\",\n font = (self.FONT, 17), pady = 5, bg = self.BG_COLOUR)\n self.summary_label.grid(row = 1, column = 0, sticky = NW, pady = 5)\n\n #Scrolled Text box of Job Information\n self.job_summary_box = ScrolledText(self.summary_frame, font = (self.FONT, 13),\n pady = 8, padx = 8, height = 8, width = 46,\n wrap = 'word')\n self.job_summary_box.grid(row = 2, column = 0, columnspan = 2)\n\n for i in range(len(self.jobs)):\n self.job_summary_box.insert(END,\"Job Number: \"+ str(self.jobs[i].job_num) + \"\\n\" +\n \"Customer Name: \" + self.jobs[i].name + \"\\n\" +\n \"Distance Travelled to Client (km): \"\n + str(self.jobs[i].distance) +\n \"\\n\" + \"Minutes spent on Virus Protection: \"\n + str(self.jobs[i].minutes) +\n \"\\n\" + \"Was WOF and Tune Required? \"\n + self.jobs[i].wof_and_tune + \"\\n\"\n + \"Total Charge: $\" + str(self.jobs[i].charge)\n + \"\\n\" + \"_____________________________\" + \"\\n\")\n\n self.job_summary_box.configure(state = 'disabled') #Disabling so the box is not typable in\n\n #Getting to Add job frame button\n self.add_a_job_btn = Button(self.summary_frame, text = \"Add a Job\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR, \n command = self.get_to_add_jobs)\n self.add_a_job_btn.grid(row = 3, column = 1, sticky = NE, pady = 10)\n\n #Back to Job Cards frame button\n self.back_to_job_cards_btn = Button(self.summary_frame, text = \"Back\",\n font = (self.FONT, 11), width = 8, bg = self.BTN_COLOUR, \n command = self.get_to_job_cards)\n self.back_to_job_cards_btn.grid(row = 1, column = 1, pady = 5, sticky = NE)\n \n \n\n#Main Routine\nif __name__==\"__main__\":\n root= Tk()\n ratings = JobCostGUI(root)\n root.title(\"Job Cost/Charge Calculator\")\n root.mainloop()\n\n","sub_path":"job_cost_charge_calculator.py","file_name":"job_cost_charge_calculator.py","file_ext":"py","file_size_in_byte":22784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"539069234","text":"##################################\n# FOR GETTING ANOMALIES\n\ndef version_1(dx): # constant stddev threshold across time\n anomalies = dx\\\n .where(dx.iloc[:, [0]] > dx.iloc[:, [0]].std())\\\n .dropna()\n return anomalies\n\ndef version_2(dx, lookback=10):\n anomalies = dx \\\n .assign(std_dev = dx.rolling(lookback).std())# \\\n anomalies = anomalies \\\n .assign(Interest = anomalies.Interest / anomalies.std_dev)# \\\n anomalies = anomalies \\\n .where(anomalies.Interest > 1.0) \\\n .dropna()\n return anomalies\n\ndef get_anomalies(data, fun, **kwargs):\n # dx = np.asarray(data.Blockchain[1:]) - np.asarray(data.Blockchain[:-1])\n dx = data.diff()\n if fun == version_1:\n anomalies = fun(dx)\n elif fun == version_2:\n anomalies = fun(dx, **kwargs)\n num_anomalies = len(anomalies)\n if num_anomalies >= 11: # more than ten anomalies\n anomalies = anomalies.sort_values(by='Interest', ascending=False)\\\n .head(10)\n return num_anomalies, anomalies.index","sub_path":"client/anomalies.py","file_name":"anomalies.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"133038259","text":"BENCHMARKS = [\n { 'bench': 'BunnymarkV2', 'lang': 'gd', },\n { 'bench': 'BunnymarkV2', 'lang': 'js', },\n { 'bench': 'BunnymarkV1Sprites', 'lang': 'gd', },\n { 'bench': 'BunnymarkV1Sprites', 'lang': 'js', },\n { 'bench': 'BunnymarkV1DrawTexture', 'lang': 'gd', },\n { 'bench': 'BunnymarkV1DrawTexture', 'lang': 'js', },\n { 'bench': 'fib', 'lang': 'gd', },\n { 'bench': 'fib', 'lang': 'js', },\n]\nimport os\nfor b in BENCHMARKS:\n commands = ' --bench=' + b['bench'] + ' --lang=' + b['lang']\n os.system('~/Documents/Workspace/Develop/Godot/godot/bin/godot.x11.opt.64 --path . ' + commands)","sub_path":"run_benchmarks.py","file_name":"run_benchmarks.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"317590146","text":"from validator import Required, Equals, validate\nfrom ficheros.codigo import Generador\ngenerador = Generador()\nclass HeaderController:\n def validar_header(self,header):\n rules = {\n \"Authorization\": [Required],\n \"Content-Type\": [Required,Equals('application/json')]\n }\n respuesta=validate(rules, header)\n if respuesta[0]:\n return True,''\n else:\n codigo = generador.validarGuardarInformacionError(\"000\",\"validar header- no se enviaron todo los parametros- header_controller\",\"post\",'') \n return False ,codigo\n ","sub_path":"mype/controller/header_controller.py","file_name":"header_controller.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"268681133","text":"from StatFunctions.StatObj import *\nimport numpy as np\nfrom StatFunctions.PDF import *\nimport math\nimport matplotlib.pyplot as plt \n\ndef EStep(data,cluster,Stat):\n ''' Calculates probability of each data for each cluster\n '''\n rValue = np.zeros((len(data),cluster)) \n for x,mean,var,pi in zip(range(cluster),Stat.mean,Stat.variance,Stat.pi):\n rValue[:,x] = pi* pdf(data,mean,var)\n for i in range(len(rValue)):\n rValue[i] = rValue[i]/(np.sum(Stat.pi)*np.sum(rValue,axis=1)[i])\n return rValue\n\ndef MStep(data,cluster,Stat,rValue):\n ''' \n Calculate fraction point for each cluster\n Update all paramaters accordingly - Using M Step Formulas\n '''\n fractPnt = []\n for x in range(len(rValue[0])):\n fractPnt.append(np.sum(rValue[:,x]))\n for k in range(len(fractPnt)):\n Stat.pi[k] = (fractPnt[k]/np.sum(fractPnt))\n Stat.mean = np.sum(data.reshape(len(data),1)*rValue,axis=0)/fractPnt\n var_c = []\n for x in range(len(rValue[0])):\n var_c.append((1/fractPnt[x])*np.dot(((np.array(rValue[:,x]).reshape(len(data),1))*(data.reshape(len(data),1)-Stat.mean[x])).T,(data.reshape(len(data),1)-Stat.mean[x])))\n #for x in range(len(var_c)):\n # Stat.variance[x] = (len(data)-1 /len(data))* var_c[x][0][0]\n return Stat\n\n\ndef LogLikelyHood(data,Stat: Stat):\n ''' \n Find Likelihood for the given data and stat paramaters\n '''\n logLik = 0\n for x in range(len(Stat.mean)):\n varS = Stat.variance[x] * Stat.variance[x]\n term1 = ((len(data)) * math.log(2 * math.pi))/(-1*2)\n term2 = ((len(data)) * math.log(varS))/(-1*2)\n term3 = np.sum((np.power(np.subtract(data,Stat.mean[x]),2))/(-1*2*varS),axis=0)\n logLik += term1+term2+term3\n return logLik\n\ndef FindOptimalClusters(dataArr):\n '''\n Finds Optimal Clusters for the given Data Set\n 1) Run for each cluster starting from 2 to 9\n 2) Execute EStep and Mstep for 10 times\n 3) Record Log likelihood for each iterations\n 4) If the log likelihood values are monotonically increasing, it is the optimal cluster\n 5) Else continue with next cluster\n '''\n optCluster = 0\n for cluster in range(2,10):\n logs=[]\n print('Checking feasibility of Cluster:' + str(cluster))\n data= np.empty(len(dataArr))\n np.copyto(data,dataArr)\n stat = Stat()\n stat.SetInitialValues(cluster,data)\n for x in range(10):\n rValue = EStep(data,cluster,stat)\n stat = MStep(data,cluster,stat,rValue)\n logLikely = LogLikelyHood(data,stat)\n logs.append(logLikely)\n if all(x Null values replaced by zero, we can replace it with any other value depending on circumstances\n 0 1 2\n0 0.0 1.0 2\n1 2.0 3.0 4\n2 3.0 0.0 5\n\"\"\"\n\"\"\"\nOther method:\n Forward fill --> to propagate the previous value forward : df.fillna(method='ffill')\n Back fill --> to propagate the next values backward : df.fillna(method='bfill')\n \n\"\"\"\n","sub_path":"Handling missing values in Pandas.py","file_name":"Handling missing values in Pandas.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"418783067","text":"import cv2\nfrom recognize_server.face_recognizer import FaceRecognizer\nfrom management_server.user_server import UserServer, User\nimport os\nimport numpy as np\n\nuser_server = UserServer()\n\nrecognizer = FaceRecognizer(recognize_flag=False)\n\n\ndef cv2_imread(filePath):\n cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)\n\n return cv_img\n\n\ndef sign_up():\n src_dir = 'xdemo_src_img'\n dirs = os.listdir(src_dir)\n\n for name in dirs:\n user = User()\n\n user.name = name\n user.title = \"學生\"\n user.college = \"工學院\"\n user.department = \"資工系(日)\"\n\n img_dir = src_dir + '/' + name\n for img_name in os.listdir(img_dir):\n img = cv2_imread(img_dir + '/' + img_name)\n frame, face_embs = recognizer.embedding(img)\n user.face_imgs.append(frame)\n user.face_embs.append(face_embs[0])\n\n ok = user_server.new_user(user)\n\n if ok:\n print(\"'{}' sign up success !!\".format(user.name))\n\n else:\n print(\"'{}' is exist !!\".format(user.name))\n\n\nif __name__ == '__main__':\n sign_up()\n","sub_path":"xdemo/demo_signup.py","file_name":"demo_signup.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"72584366","text":"\"\"\"\nTo use the python script in Command Prompt:\nWrite 'python your_file_name.py'\n\"\"\"\n\n# Four different arrays\nnumbers = [5, 10, 50, 75, 250]\nmoreNumbers = [540, 41, 78, 91, 2]\nonlyTwoNumbers = [0, 1]\nonlyOneNumber = [5]\n\n# Function that finds the minimum and maximum numbers from an array\ndef FindMinMax(arrayOfNumbers):\n # Uses the built-in function min() to find the lowest number\n minimumNumber = min(arrayOfNumbers)\n # Uses the built-in function max() to find the largest number\n maximumNumber = max(arrayOfNumbers)\n # Prints a message with a normal string\n print(\"From the list specified:\")\n # Prints the minimum and maximum number using a formatted (f) string\n print(f\"Minimum is {minimumNumber}\")\n print(f\"Maximum is {maximumNumber}\\n\")\n\n# Calls the functions with arguments\nFindMinMax(numbers)\nFindMinMax(moreNumbers)\nFindMinMax(onlyTwoNumbers)\nFindMinMax(onlyOneNumber)","sub_path":"challenge101/challenge101.py","file_name":"challenge101.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"5750657","text":"import sys\nimport itertools\nimport re\nfrom Bio import SeqIO\n\n# For a fixed positive integer k, order all possible k-mers taken from an underlying alphabet lexicographically.\n#\n# Then the k-mer composition of a string s can be represented by an array A for which A[m] denotes the number of\n# times that the mth k-mer (with respect to the lexicographic order) appears in s.\n#\n# Given: A DNA string s in FASTA format (having length at most 100 kbp).\n#\n# Return: The 4-mer composition of s.\n\nfile_path = sys.argv[1]\nsequence = \"\"\n# read input file into sequence\nwith open(file_path,'r') as handle:\n for record in SeqIO.parse(handle,\"fasta\"):\n sequence = str(record.seq)\n\n# helper function to generate all permutations of a certain alphabet\n# Lexicographical order is automatically achieved through this\ndef generate_permutations(letters):\n return [''.join(i) for i in itertools.product(letters,repeat = 4)]\n\nall_permutations = generate_permutations(\"ACGT\")\nall_counts = []\n# search for all occurences of every permutation in the sequence and count the number of occurences\nfor permutation in all_permutations:\n pattern = re.compile(r'(?=(' + permutation + '))')\n permutation_count = 0\n for occurence in re.findall(pattern,sequence):\n permutation_count += 1\n all_counts.append(permutation_count)\nprint(*all_counts,sep=' ')\n\n\n\n\n\n\n","sub_path":"Bioinformatics_Stronghold/k-Mer_Composition.py","file_name":"k-Mer_Composition.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"332234746","text":"import os\r\nimport os.path\r\nimport re\r\nimport glob\r\nimport errno\r\nimport io\r\n\r\n#DESCRICAO\r\n# Clean the stamps from CORPO in the text\r\n\r\n\r\npath=[]\r\ncorpo_ident=r'([\\s\\S]*?)<\\/CORPO>'\r\nre_space=r'(\\A\\s*?([\\s\\S]*?)<\\/CORPO>',(''+str(corpo_depois[0][0])+''),text)\r\n\t\t\t\t\t\tf=open(path_clean_total,\"r+\",encoding='utf-8')\r\n\t\t\t\t\t\tf.write(text_cleaned)\r\n\t\t\t\t\t\tf.read()\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tcopyfile(name,path_clean_total)\r\n\t\t\t\t\tfile.close()\r\n\t\t\t\t\t\r\n\t\t\t\telse:\r\n\t\t\t\t\tcopyfile(name,path_clean_total)\r\n\t\t\t\t\tprint(name + \" dont have CORPO.\")\r\n\t\t\t\t\tnotcorpo+=1'''\r\n\r\n\t\texcept IOError as exc: \r\n\t\t\tif exc.errno != errno.EISDIR:\r\n\t\t\t\traise\r\n\r\nif __name__== \"__main__\":\r\n\tmain()","sub_path":"Python/Auxiliar/clean_cabecalho.py","file_name":"clean_cabecalho.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578470581","text":"# coding: utf-8\n\nfrom hashlib import md5\n\nfrom django.test import TestCase\n\nfrom core import utils as u\n\n\nclass UploadToTestCase(TestCase):\n\n def setUp(self):\n self.filename = 'image.jpg'\n self.hash = md5(self.filename.encode('utf-8')).hexdigest()\n self.upload_path = '/'.join(\n [self.hash[:2], self.hash[2:4], self.hash + '.jpg'])\n\n def test_upload_to_directory(self):\n uploader = u.upload_to('dir')\n expected_dir = 'dir/' + self.upload_path\n assert uploader(instance=None, filename=self.filename) == expected_dir\n\n def test_upload_to_empty_directory(self):\n uploader = u.upload_to()\n assert uploader(instance=None, filename=self.filename) == self.upload_path\n","sub_path":"src/core/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"583616000","text":"import pandas as pd\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom preprocessing import transform_and_extract_train, transform_and_extract_test\nfrom plot_result import plot_all_results\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom sklearn.metrics import accuracy_score,classification_report,roc_auc_score,roc_curve,auc,precision_recall_curve,confusion_matrix\n\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.models import Sequential,Model\nfrom keras.layers import Dense, Dropout, LeakyReLU\nfrom keras import backend as K\nfrom keras import regularizers\nfrom keras.optimizers import sgd\n\nurl1 = './data/training_set.csv'\ndf = pd.read_csv(url1)\nX_train, y_train = transform_and_extract_train(df)\n\nurl2 = './data/test_set_sample.csv'\ndf_test = pd.read_csv(url2)\nX_test, y_test = transform_and_extract_test(df_test)\n\nru = RandomUnderSampler('majority')\nX_resampled, y_resampled = ru.fit_sample(X_train, y_train)\n\nK.clear_session()\nK.set_learning_phase(1)\n\ndef prediction_model():\n optimizer = sgd(lr=0.001,momentum=0.001)\n model = Sequential()\n model.add(Dense(X_train.shape[1], input_dim=X_train.shape[1], kernel_initializer='normal', activation='relu'))\n model.add(Dropout(0.1))\n model.add(Dense(int(X_train.shape[1]/2),kernel_initializer='normal', activation='relu'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.1))\n model.add(Dense(int(X_train.shape[1]/4),kernel_initializer='normal', activation='tanh'))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.1))\n model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))\n model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])\n return model\n\nestimator = KerasClassifier(build_fn=prediction_model, epochs=1000, batch_size=50, verbose=1)\nestimator.fit(X_resampled, y_resampled , validation_split=0.1)\n\nresults = estimator.predict(X_test)\n\noutput = pd.DataFrame(results)\noutput.to_csv('./data/output/test_set_sample_predictions.csv',index=None, header= False, columns= None)\n\nif len(y_test)>1: #metrics visualization will only be outputed if 'went_on_backorder' column is present in testing set\n print('===========================')\n print('Accuracy Score: ',accuracy_score(results,y_test))\n print('\\n')\n\n print('===========================')\n print('ROC AUC Score: ',roc_auc_score(results,y_test))\n print('\\n')\n\n print('===========================')\n print('Confusion Matrix')\n print(pd.DataFrame(confusion_matrix(results, y_test),columns=[-1,1],index=[-1,1]))\n print('\\n')\n\n print('===========================')\n print('Classification Report')\n print(classification_report(results,y_test))\n print('\\n')\n\n probs = estimator.predict_proba(X_test)\n plot_all_results(results, probs, y_test)\n\nprint('Finished. Please check data folder for output')\n","sub_path":"final/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"597563624","text":"'''\nCreated on Mar 9, 2018\n\n@author: lorenzo\n'''\nfrom it.ds4biz.annotator.SimpleAnnotator import SimpleAnnotator\nfrom it.ds4biz.builder.TrainBuilders import FilterWindowsTrainBuilder\nfrom it.ds4biz.feature.FeatureExtractor import WindowsTextFeatureExtractor\nfrom it.ds4biz.util.WordTokenizer import word_tokenizer\n\nclass ManualAnnotatorBuilder:\n '''\n crea un dataset con le annotazioni manuali\n '''\n\n\n def __init__(self, train_builder ,num_pred_word = -8,num_post_word = 8):\n '''\n Constructor\n '''\n self.num_pred_word = num_pred_word\n self.num_post_word = num_post_word\n self.annotator = SimpleAnnotator()\n self.train_builder = train_builder\n self.traindata = []\n \n def add_manual_annotation(self, text, target_tokens):\n \n annotext = self.annotator.annotate(text, target_tokens)\n print(list(annotext.all_annotation()))\n new_dataset_part = self.train_builder.build(annotext)\n self.traindata.extend(new_dataset_part)\n \n def all_dataset(self):\n for elment in self.traindata:\n yield elment\n \nif __name__ == '__main__':\n text = \"Buongiorno sono il Dottor. Zingler grande amico del Dott. Giorgio\"\n text = word_tokenizer(text)\n target_tokens = [\"Zingler\", \"Giorgio\"]\n print(text,target_tokens)\n gen=FilterWindowsTrainBuilder(WindowsTextFeatureExtractor(),-100,100)\n\n annbuild = ManualAnnotatorBuilder(gen)\n annbuild.add_manual_annotation(text, target_tokens)\n for a in annbuild.all_dataset():\n print(a)\n \n \n \n ","sub_path":"ds4biz/ds4biz/it/ds4biz/builder/ManualAnnotator.py","file_name":"ManualAnnotator.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"253669302","text":"import player\nimport stations\nimport gpio\nfrom time import sleep\n\n# load stations\nstations = stations.load(\"stations.txt\")\n\n# checking gpio status and execute whatever stuff\nradio = player.Player()\ngpios = gpio.GPIO()\nurls = []\nbutton_old = 666\nplay_old = 666\nwhile True:\n button, play = gpios.status()\n if (button != button_old) or (play != play_old):\n\n if (button != button_old):\n if button == 0:\n urls = stations[0]\n elif button == 1:\n urls = stations[1]\n elif button == 2:\n urls = stations[2]\n elif button == 3:\n urls = stations[3]\n\n if (play != play_old):\n if play:\n if radio.getIsOn():\n radio.transition(0)\n radio.stop()\n radio.start(urls)\n sleep(1)\n radio.transition(1)\n else:\n radio.stop()\n if (play != play_old):\n if play:\n radio.start(urls)\n sleep(1)\n radio.transition(1)\n else:\n radio.stop()\n\n button_old = button\n play_old = play\n\n sleep(0.05)","sub_path":"sternradio.py","file_name":"sternradio.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"551013314","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom torch.utils.data import Dataset, DataLoader\nimport math\nimport json\nimport itertools\nimport torch\nfrom tqdm import tqdm\n\ndef correct_batch(batch):\n while len(batch)<4000:\n batch = np.append(batch,0)\n return batch\n\nclass parkinsonsData(Dataset):\n \n def __init__(self, df, col):\n file_df = pd.read_csv(\"../../../data3/mPower/52461358.csv\")\n # if col==14:\n # files = file_df[\"deviceMotion_walking_rest.json.items\"].tolist()\n # elif col==8:\n # files = file_df[\"deviceMotion_walking_outbound.json.items\"].tolist()\n # else:\n # files = file_df[\"deviceMotion_walking_return.json.items\"].tolist()\n\n self.users = pd.read_csv(\"../../../data3/mPower/users.csv\")\n self.col = col\n self.dataset = []\n\n for z in tqdm(file_df.iterrows()):\n healthcode = z[1][3]\n try:\n label = self.users.loc[self.users['healthCode'] == healthcode][\"professional-diagnosis\"]\n \n if label.values[0]:\n label=1\n else:\n label=0\n if(os.path.exists(\"../../../data3/mPower/data/\"+str(int(z[1][col]))+\".json\")):\n f = open(\"../../../data3/mPower/data/\"+str(int(z[1][col]))+\".json\")\n data = json.load(f)\n if data != None:\n \n x=[]\n x.append([])\n x.append([])\n x.append([])\n \n for i in range(0,len(data),2):\n rot = data[i].get(\"rotationRate\")\n x[0].append(rot[\"x\"])\n x[1].append(rot[\"y\"])\n x[2].append(rot[\"z\"])\n \n stdev = np.std(np.asarray(x))\n mean = np.mean(np.asarray(x))\n x = ((np.asarray(x)-mean)/stdev).tolist()\n \n x[0] = correct_batch(x[0])\n x[1] = correct_batch(x[1])\n x[2] = correct_batch(x[2])\n \n # stdev = np.std(np.asarray(x))\n # mean = np.mean(np.asarray(x))\n # x = ((np.asarray(x)-mean)/stdev)\n \n self.dataset.append([np.asarray(x),label])\n except:\n continue\n \n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, idx):\n print(self.dataset[idx][0])\n return self.dataset[idx][0], self.dataset[idx][1] \n\n","sub_path":"parkinsons_dataset.py","file_name":"parkinsons_dataset.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"154356381","text":"import json\nimport hashlib\n\n# function to parse DID from public key\ndef didFromPK(pubKey):\n did = \"did:vtn:trustid:\" + str(hashlib.sha256(pubKey).hexdigest())\n return did\n\ndef didFromWallet(did_wallet_path):\n with open(did_wallet_path) as did_file:\n data = json.load(did_file)\n temp_did = data['dids']\n did = temp_did[0]['did']\n return did","sub_path":"app/modbus-sync-server/hfbssisdk/src/hfbssi/didFromPK.py","file_name":"didFromPK.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477912852","text":"import nltk\nimport random\n\ndef randomize(x):\n\tnew_seq = []\n\trand_list = []\n\twords = nltk.word_tokenize(x)\n\tfor i in words:\n\t\tif len(i) >= 5:\n\t\t\trand_list.append(i)\n\t\t\t#secure_random = random.SystemRandom()\n\t\t\t#selected_word = secure_random.choice(rand_list)\n\t\t\ti = i[:-1]\n\t\t\tprint(i)\n\t\t\tnew_seq.append(i)\n\t\telse:\n\t\t\tnew_seq.append(i)\n\tadversarial = ' '.join(new_seq)\n\treturn(adversarial)\n\nadversarial = randomize(\"This movie is terrible but it has some good effects.\")\nprint(adversarial)\n","sub_path":"code_0.3/randomize_sentence.py","file_name":"randomize_sentence.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"621652078","text":"from lettuce import *\nfrom should_dsl import *\n\nfrom player import Player\nfrom buraco import *\n\n@step(r'I have the players (.*)')\ndef given_i_have_the_players(step, names):\n names = names.split(', ')\n world.players = []\n for name in names:\n world.players.append(Player(name))\n\n@step(r'I initialize the game')\ndef when_i_initialize_the_game(step):\n try:\n world.buraco = Buraco(world.players)\n except InvalidNumberOfPlayers as e:\n world.msg = e.msg\n\n@step(r'each player has 11 cards')\ndef then_each_player_has_11_cards(step):\n for player in world.players:\n len(player.hand) |should| equal_to(11)\n\n@step(r'the game cannot be started')\ndef the_game_cannot_be_started(step):\n world.msg |should_be.equal_to| \"The number of players must be 2, 3 or 4\"\n\n@step(r'the game has 2 pots with 11 cards each')\ndef the_game_has_2_pots_with_11_cards_each(step):\n for pots in world.buraco.pots:\n len(pots) |should| equal_to(11)\n\n@step(r'the game has the stock with (\\d+)')\ndef the_game_has_the_stock_with(step, ramaining_cards):\n ramaining_cards = int(ramaining_cards)\n len(world.buraco.stock) |should| equal_to(ramaining_cards)\n\n","sub_path":"features/steps_definition/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"228619713","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# vim: tabstop=4 shiftwidth=4 expandtab\n\nimport os\nimport sys\nimport optparse\nfrom repomanager.rpm.repo import RPMRepManager\n\ndef main():\n parser = RPMRepManager.MakeNeededOptions()\n (options, args) = parser.parse_args()\n if not options.base:\n parser.error('No base given')\n if not options.version:\n parser.error('No version given')\n if not options.arch:\n parser.error('No arch given')\n\n rep = RPMRepManager(options)\n rpmlist = []\n for arch in [options.arch, 'noarch']:\n rpmlist += rep.list_rpms([options.base + '/' + options.version + '/' + arch])\n signed, unsigned = rep.sort_signed(rpmlist)\n for u in unsigned:\n sys.stdout.write(u.get(\"fname\") + '\\n')\n sys.stdout.flush()\n\nif __name__ == '__main__':\n main()\n","sub_path":"findunsigned.py","file_name":"findunsigned.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555180618","text":"#!/usr/bin/python\n\nimport sys, getopt, csv\nfrom datetime import datetime, timedelta\n\n\ndef main(argv):\n inputfile = None\n outputfile = None\n try:\n opts, args = getopt.getopt(argv, \"hf:o:\", [\"ifile=\", \"ofile=\"])\n except getopt.GetoptError:\n print('test.py -f -o ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('test.py -f -o ')\n sys.exit()\n elif opt in (\"-f\", \"--ifile\"):\n inputfile = arg\n elif opt in (\"-o\", \"--ofile\"):\n outputfile = arg\n\n print('Input file is ', inputfile)\n print('Output file is ', outputfile)\n\n transform(inputfile, outputfile)\n\ndef transform(inputfile, outputfile):\n print('transforming')\n header = ['ts_name', 'time', 'unit', 'value', 'class']\n read_header = ['stn', 'time', 'tso005s0']\n with open(inputfile, 'r') as file_input, open(outputfile, 'w') as file_output:\n reader = csv.reader(file_input, delimiter=';')\n next(reader, None) # skip the headers\n writer = csv.writer(file_output, delimiter=';')\n writer.writerow(header)\n\n for row in reader:\n row = [row[0], row[1], 'Celsius', row[2], 0]\n writer.writerow(row)\n\n print('transforming done')\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"misc/tools/idaweb.py","file_name":"idaweb.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"48339331","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport codecs\nimport shutil\nimport re\n\nclass JSONSchema2RST:\n def __init__(self):\n self.data = {'type': 'root', 'children': {}}\n self.source = None\n self.target = None\n self.toctrees = []\n\n def travel(self, source='./schemas', target='./source'):\n self.source = source\n self.index_target = target\n self.target = os.path.join(target, 'apis')\n self.blob_template = os.path.join(self.source, '_template/blob.rst')\n self.toc_template = os.path.join(self.source, '_template/toc.rst')\n self.index_template = os.path.join(self.source, '_template/index.rst')\n\n for root, subdirs, files in os.walk(source):\n for f in files:\n if os.path.basename(f) == 'config.json':\n config_path = os.path.join(root, os.path.basename(f))\n config_data = self.parse_config(os.path.abspath(config_path))\n config_type = config_data.get('type', 'toc')\n\n uri = self.get_uri(root)\n config_data.update({\n 'uri': uri\n })\n\n if config_type == 'toc':\n config_data.update({\n 'children': {}\n })\n elif config_type == 'blob':\n request_blob_path = os.path.join(root, 'request.json')\n response_blob_path = os.path.join(root, 'response.json')\n config_data.update({\n 'request': self.parse_config(request_blob_path),\n 'response': self.parse_config(response_blob_path)\n })\n\n self.update_uri_config(root, config_data)\n\n self.export_doc(self.data)\n\n toctrees = ''\n index_target_path = os.path.join(self.index_target,'index.rst')\n index_rst = self.parse_raw(self.index_template)\n\n for toc in self.toctrees:\n toctrees += ' '\n toctrees += os.path.join('.', 'apis', toc, 'doc')\n toctrees += '\\n'\n\n index_rst = re.sub('\\{\\{toctrees\\}\\}', toctrees, index_rst)\n\n index_file = codecs.open(index_target_path, encoding='utf-8', mode='w')\n index_file.write(index_rst)\n index_file.close()\n\n\n def get_uri(self, source):\n return os.path.relpath(os.path.abspath(source), os.path.abspath(self.source))\n\n def update_uri_config(self, source, data):\n keys_str = self.get_uri(source)\n keys_list = keys_str.split('/')\n d = self.data\n\n for key in keys_list:\n if 'children' in d and key not in d['children']:\n d['children'].update({key: data})\n d = d['children'][key]\n\n def export_doc(self, data):\n # print json.dumps(self.data, sort_keys=False, indent=4, separators=(',', ': '))\n for k, v in data['children'].iteritems():\n doc_type = v.get('type', 'toc')\n uri = v.get('uri')\n\n target_path = os.path.join(self.target, uri)\n\n if not os.path.isdir(target_path) or not os.path.exists(target_path):\n shutil.rmtree(target_path, ignore_errors=True)\n os.makedirs(target_path)\n\n target_path = os.path.join(self.target, uri, 'doc.rst')\n rst_raw = self.parse_blob(v) if doc_type == 'blob' else self.parse_toc(v)\n doc = codecs.open(target_path, encoding='utf-8', mode='w')\n doc.write(rst_raw)\n doc.close()\n\n if doc_type == 'toc':\n if 'children' in v:\n self.export_doc(v)\n elif doc_type == 'blob':\n if uri not in self.toctrees:\n self.toctrees.append(uri)\n\n example_source_path = os.path.join(self.source, uri, 'example.json')\n example_target_path = os.path.join(self.target, uri, 'example.json')\n if os.path.exists(example_source_path) and os.path.isfile(example_source_path):\n shutil.copy2(example_source_path, example_target_path)\n else:\n eg = codecs.open(example_target_path, encoding='utf-8', mode='w')\n eg.write('empty')\n eg.close()\n\n @staticmethod\n def parse_config(source):\n if os.path.exists(source):\n x = codecs.open(source, encoding='utf-8')\n data = json.loads(x.read())\n x.close()\n return data\n else:\n return {}\n\n @staticmethod\n def parse_raw(source):\n if os.path.exists(source):\n x = codecs.open(source, encoding='utf-8')\n data = x.read()\n x.close()\n return data\n else:\n return 'null'\n\n def parse_toc(self, toc):\n rst = self.parse_raw(self.toc_template)\n\n rst = re.sub('\\{\\{title\\}\\}', toc.get('title'), rst)\n\n return rst\n\n def parse_blob(self, blob):\n rst = self.parse_raw(self.blob_template)\n\n rst = re.sub('\\{\\{title\\}\\}', blob.get('title'), rst)\n rst = re.sub('\\{\\{uri\\}\\}', blob.get('uri'), rst)\n rst = re.sub('\\{\\{authors\\}\\}', blob.get('authors'), rst)\n rst = re.sub('\\{\\{version\\}\\}', blob.get('version'), rst)\n rst = re.sub('\\{\\{method\\}\\}', blob.get('method'), rst)\n\n request_raw = ''\n if 'request' in blob:\n if not not blob.get('request'):\n request_raw = self.parse_schema(blob.get('request'))\n\n rst = re.sub('\\{\\{request\\}\\}', request_raw, rst)\n\n\n response_raw = ''\n if 'response' in blob:\n if not not blob.get('response'):\n response_raw = self.parse_schema(blob.get('response').get('properties').get('data'))\n\n rst = re.sub('\\{\\{response\\}\\}', response_raw, rst)\n\n return rst\n\n @staticmethod\n def parse_schema(schema):\n\n rst = u'''\n \n \n \n | 键名 | \n 类型 | \n 描述 | \n
\n
\n \n ''' \n items = []\n if 'properties' in schema:\n items = schema['properties']\n elif 'items' in schema:\n items = schema['items'][\"properties\"]\n\n if len(items) > 0:\n i = 0\n for k,v in items.iteritems():\n schema_type = v.get('type', 'string')\n rst += '' if i/2 == 0 else '
'\n\n rst += '| ' + k + ' | ' + schema_type + ' | '\n if schema_type == 'object' or schema_type == 'array':\n rst += '' + v.get('description', '-') + ''\n rst += JSONSchema2RST.parse_schema(v)\n rst += ' | '\n else:\n rst += '' + v.get('description', '-') + ' | '\n\n rst += '
'\n\n i += 1\n else:\n rst += ''\n rst += u'| 未配置 | '\n rst += '
'\n\n rst += '''\n \n
\n '''\n return rst\n\n\nif __name__ == \"__main__\":\n jsonschema2rst = JSONSchema2RST()\n jsonschema2rst.travel()\n","sub_path":"jsonschema2rst.py","file_name":"jsonschema2rst.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"71942457","text":"#!/usr/bin/python\r\n\r\nimport sys\r\nimport socket\r\nimport threading\r\nimport Node\r\nimport Edge\r\nimport re\r\nimport heapq\r\n\r\ndef linkCheck():\r\n global linkBool\r\n linkBool = True\r\n\r\ndef graphCheck():\r\n global graphBool\r\n graphBool = True\r\n\r\ndef sendPacket():\r\n copyAliveMsgs = dict(numAliveMsgs)\r\n for neighbour in copyAliveMsgs.keys():\r\n\r\n #if a message has not been sent by the neighbour of this node\r\n if copyAliveMsgs[neighbour] == 0:\r\n\r\n #increment the number of missed messages by that neighbour\r\n numMissedMsgs[neighbour] += 1\r\n\r\n else:\r\n #a message has been sent by the neighbour of this node\r\n\r\n #reset numAliveMsgs to 0 to detect whether future messages have been sent or not\r\n numAliveMsgs[neighbour] = 0\r\n\r\n #reset the number of missed messages to 0\r\n numMissedMsgs[neighbour] = 0\r\n\r\n\r\n if numMissedMsgs[neighbour] == 3:\r\n #if a neighbour has failed to send a message 3 times in a row\r\n\r\n #get the regex of the link and delete the neighbour from the message\r\n regex = neighbour + \"=[0-9\\.]+\"\r\n global message\r\n message = re.sub(regex, '', message)\r\n\r\n #delete the neighbour from numAliveMsgs and numMissedMsgs, not needed anymore\r\n del numAliveMsgs[neighbour]\r\n del numMissedMsgs[neighbour]\r\n\r\n #delete the neighbour from the graph if it already hasn't been deleted\r\n if neighbour in graph.keys():\r\n del graph[neighbour]\r\n\r\n #for each node in the graph\r\n for node in graph.values():\r\n copyEdges = list(node.neighbours)\r\n for edge in copyEdges:\r\n\r\n #if the end node is equal to the dead neighbour then remove the edge from the list\r\n if edge.endNode == neighbour:\r\n node.neighbours.remove(edge)\r\n\r\n #generate a node failure message to send to remaining neighbours and flood network\r\n nodeToDelete = \"%s:DEAD\" % neighbour\r\n for port in portList:\r\n messageSocket.sendto(nodeToDelete, (\"127.0.0.1\", port))\r\n\r\n #send the original message/linkStatePacket\r\n for port in portList:\r\n messageSocket.sendto(message, (\"127.0.0.1\", port))\r\n\r\ndef shortestPath():\r\n\r\n #distance and previous dicts returned from dijkstra's\r\n D, P = dijkstra(graph, startNode)\r\n\r\n #for each node in the graph except this programs node\r\n for node in graph.values():\r\n if node.name == startNode.name:\r\n continue\r\n\r\n #the node that we are printing the shortest path to\r\n string = node.name\r\n\r\n #the previous neighbour to the above node\r\n previous = P[node.name]\r\n\r\n #keep working backwards adding each previous neighbour till we hit the start node\r\n while previous != startNode.name:\r\n string = previous + string\r\n previous = P[previous]\r\n string = startNode.name + string\r\n\r\n print(\"least-cost path to node %s: %s and the cost is %.1f\" % (node.name, string, D[node.name]))\r\n\r\ndef dijkstra(graph, startNode):\r\n\r\n #this is dijkstras algorithm using a priority queue\r\n\r\n dist = {}\r\n prev = {}\r\n queue = []\r\n\r\n #distance to reach the start node is 0 obviously\r\n dist[startNode.name] = 0\r\n\r\n #for each node in the graph\r\n for node in graph.values():\r\n\r\n #if the node isn't the start node\r\n if node.name != startNode.name:\r\n\r\n #initialise distance to that node = infinity and previous neighbour of that node = None\r\n dist[node.name] = float('inf')\r\n prev[node.name] = None\r\n\r\n #push the node onto the queue\r\n heapq.heappush(queue, (dist[node.name], node.name))\r\n\r\n while len(queue) != 0:\r\n\r\n #pop the vertex from the queue\r\n vertex = heapq.heappop(queue)\r\n\r\n #for every neighbour in the vertex's neighbours\r\n for neighbour in graph[vertex[1]].neighbours:\r\n\r\n #length = the distance to get to vertex + the distance to get to the neighbour of the vertex\r\n length = dist[vertex[1]] + neighbour.travelCost\r\n\r\n #if the length less dist[neighbour.endNode], found a path with lower cost\r\n if length < dist[neighbour.endNode]:\r\n\r\n #old node to be removed from queue\r\n old = (dist[neighbour.endNode], neighbour.endNode)\r\n queue.remove(old)\r\n\r\n #the distance to reach that neighbour is updated and the previous node is the vertex\r\n dist[neighbour.endNode] = length\r\n prev[neighbour.endNode] = vertex[1]\r\n\r\n #push the updated node onto the queue\r\n heapq.heappush(queue, (length, neighbour.endNode))\r\n\r\n return dist, prev\r\n\r\n#################### initial stage ####################\r\n\r\ngraph = {}\r\nportList = []\r\npacketList = []\r\nnumAliveMsgs = {}\r\nnumMissedMsgs = {}\r\nlinkBool = False\r\ngraphBool = False\r\n\r\nnodeID = str(sys.argv[1])\r\nnodePort = int(sys.argv[2])\r\nfile = str(sys.argv[3])\r\nf = open(file, 'r')\r\n\r\nUPDATE_INTERVAL = 1\r\nROUTE_UPDATE_INTERVAL = 30\r\n\r\nstartNode = Node.Node(nodeID)\r\n\r\n#link state packet - initially\r\nmessage = \"%s: \" % nodeID\r\n\r\nfirstLineCheck = 0\r\nfor line in f:\r\n if firstLineCheck == 0:\r\n firstLineCheck = 1\r\n continue\r\n\r\n strings = line.split()\r\n\r\n #create a new node from the split line\r\n newNode = Node.Node(strings[0])\r\n portList.append(int(strings[2]))\r\n\r\n #initialise statuses to check for dead neighbours later on\r\n numAliveMsgs[strings[0]] = 0\r\n numMissedMsgs[strings[0]] = 0\r\n\r\n #create edges for both nodes\r\n startNodeEdge = Edge.Edge(nodeID, strings[0], strings[1])\r\n newNodeEdge = Edge.Edge(strings[0], nodeID, strings[1])\r\n\r\n #add edges to neighbours list on both nodes\r\n startNode.neighbours.append(startNodeEdge)\r\n newNode.neighbours.append(newNodeEdge)\r\n\r\n #add the newNode to the graph\r\n graph[newNode.name] = newNode\r\n\r\n #add the edge to the link state message\r\n message += \"%s=%s \" % (strings[0], strings[1])\r\n\r\n#add the start node to the graph\r\ngraph[startNode.name] = startNode\r\n\r\n#add the message to the packetList\r\npacketList.append(message)\r\n\r\n#################### moving onto the continuous loop stage ####################\r\n\r\nmessageSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\nmessageSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\nmessageSocket.setblocking(0)\r\nmessageSocket.bind(('', nodePort))\r\n\r\n#timer which updates a boolean every second\r\nlinkTimer = threading.Timer(UPDATE_INTERVAL, linkCheck)\r\nlinkTimer.start()\r\n\r\n#time which updates a boolean every thirty seconds\r\ngraphTimer = threading.Timer(ROUTE_UPDATE_INTERVAL, graphCheck)\r\ngraphTimer.start()\r\n\r\ndupCheck = False\r\n\r\nwhile True:\r\n\r\n #if a second has passed\r\n if linkBool == True:\r\n\r\n #execute the sendPacket function, reset the boolean, reset the timer\r\n sendPacket()\r\n linkBool = False\r\n linkTimer.cancel()\r\n linkTimer = threading.Timer(UPDATE_INTERVAL, linkCheck)\r\n linkTimer.start()\r\n\r\n #if thirty seconds have passed\r\n if graphBool == True:\r\n\r\n #execute the shortestPath function, reset the boolean, reset the timer\r\n shortestPath()\r\n graphBool = False\r\n graphTimer.cancel()\r\n graphTimer = threading.Timer(ROUTE_UPDATE_INTERVAL, graphCheck)\r\n graphTimer.start()\r\n\r\n try:\r\n\r\n #receive link state packets from other nodes\r\n linkStatePacket, address = messageSocket.recvfrom(2048)\r\n\r\n #the first character of the packet is the node name\r\n nodeName = linkStatePacket[0]\r\n\r\n #if the link state packet is from one of this nodes neighbours\r\n if nodeName in numAliveMsgs.keys():\r\n numAliveMsgs[nodeName] += 1\r\n\r\n #if the link state packet has already been received then do not forward it\r\n for packet in packetList:\r\n if linkStatePacket == packet:\r\n dupCheck = True\r\n break\r\n\r\n if dupCheck == True:\r\n dupCheck = False\r\n continue\r\n\r\n #append the packet to the list\r\n packetList.append(linkStatePacket)\r\n\r\n #if we have received a failed node message\r\n if linkStatePacket == nodeName + \":DEAD\":\r\n\r\n #delete the node from the graph\r\n del graph[nodeName]\r\n\r\n for node in graph.values():\r\n copyEdges = list(node.neighbours)\r\n for edge in copyEdges:\r\n #delete all edges in the graph which contain the dead node\r\n if edge.endNode == nodeName:\r\n node.neighbours.remove(edge)\r\n\r\n #forward the failed node message to other neighbours to flood the network\r\n for port in portList:\r\n if port == address[1]:\r\n continue\r\n messageSocket.sendto(linkStatePacket, (\"127.0.0.1\", port))\r\n continue\r\n\r\n #else it's just a regular link state packet, but still forward it to other neighbours to flood network\r\n for port in portList:\r\n if port == address[1]:\r\n continue\r\n messageSocket.sendto(linkStatePacket, (\"127.0.0.1\", port))\r\n\r\n #if the graph already has the node in it\r\n if graph.has_key(nodeName):\r\n\r\n #regex to extract all the links to the nodeName\r\n links = re.findall(\"[A-Za-z]=[0-9\\.]+\", linkStatePacket)\r\n\r\n for link in links:\r\n edgeCheck = False\r\n\r\n #create a new edge\r\n newEdge = Edge.Edge(nodeName, link[0], link[2:])\r\n\r\n #if the edge is already in the nodes neighbours\r\n for edge in graph[nodeName].neighbours:\r\n if (edge.startNode == newEdge.startNode and edge.endNode == newEdge.endNode):\r\n edgeCheck = True\r\n\r\n #if the edge isn't in the nodes neighbours\r\n if (edgeCheck == False):\r\n\r\n #append the edge to the node's neighbour list\r\n graph[nodeName].neighbours.append(newEdge)\r\n\r\n #create a neighbour node and an edge going in the opposite direction\r\n neighbourNode = Node.Node(link[0])\r\n neighbourEdge = Edge.Edge(link[0], nodeName, link[2:])\r\n\r\n #if the neighbour node is already in the graph then just append the edge\r\n if neighbourNode.name in graph.keys():\r\n graph[neighbourNode.name].neighbours.append(neighbourEdge)\r\n\r\n else:\r\n #else append the edge to the node and then add the node to the graph\r\n neighbourNode.neighbours.append(neighbourEdge)\r\n graph[link[0]] = neighbourNode\r\n else:\r\n #the graph does not contain the node, so create the new node\r\n newNode = Node.Node(nodeName)\r\n\r\n #extract all links from the link state packet\r\n links = re.findall(\"[A-Za-z]=[0-9\\.]+\", linkStatePacket)\r\n\r\n #add all edges to the new node\r\n for link in links:\r\n newEdge = Edge.Edge(nodeName, link[0], link[2:])\r\n newNode.neighbours.append(newEdge)\r\n\r\n #add the node into the graph\r\n graph[newNode.name] = newNode\r\n\r\n #loop through all the links once more\r\n for link in links:\r\n\r\n #if the neighbour is already in the graph then\r\n if (link[0] in graph.keys()):\r\n\r\n #create an edge going in the opposite direction, add it to the node already in the graph\r\n neighbourEdge = Edge.Edge(link[0], nodeName, link[2:])\r\n graph[link[0]].neighbours.append(neighbourEdge)\r\n\r\n else:\r\n #else we have to create the neighbour node as well\r\n neighbourNode = Node.Node(link[0])\r\n\r\n #create the edge going in the opposite direction\r\n neighbourEdge = Edge.Edge(link[0], nodeName, link[2:])\r\n\r\n #add the edge to the node and then add the node to the graph\r\n neighbourNode.neighbours.append(neighbourEdge)\r\n graph[link[0]] = neighbourNode\r\n\r\n except:\r\n pass\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"assignment2/Lsr.py","file_name":"Lsr.py","file_ext":"py","file_size_in_byte":12567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"118223759","text":"import multiprocessing\n\ndef consumer(input_q):\n while True:\n item = input_q.get()\n #\n print(item)\n #\n input_q.task_done()\n\ndef producer(sequence, output_q):\n for item in sequence:\n #\n output_q.put(item)\n\n\n# setting\nif __name__ == '__main__':\n q = multiprocessing.JoinableQueue()\n # start consumer process\n cons_p = multiprocessing.Process(target=consumer,args=(q,))\n cons_p.daemon=True\n cons_p.start()\n\n # create sequences\n sequence = [1,2,3,4]\n producer(sequence,q)\n \n q.join()\n\n","sub_path":"multiprocess_practice.py","file_name":"multiprocess_practice.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"311978607","text":"import logging\nfrom pyAitu import executor, Bot, Dispatcher\nfrom pyAitu.models import Message, Options, FormClosed, FormSubmitted, CustomContainer, Indent, \\\n FlexOptions, Image, FileMetadata, Text, Divider, FormAction\nfrom pyAitu.models.constants.alignment import RIGHT\nfrom pyAitu.models.constants.text_size import H3, H4\nfrom pyAitu.models.constants.text_style import BOLD\nfrom pyAitu.utils.strings import UPLOADED_FILES\n\n\nAPI_TOKEN = 'YOUR_API_TOKEN'\n\nbot = Bot(token=API_TOKEN)\ndispatcher = Dispatcher(bot)\n\nlogging.basicConfig(level=logging.INFO)\n\n\n@dispatcher.message_handler()\nasync def handle(message: Message):\n \"\"\"\n Layers of containers:\n Main Container <- Parent Container <- Child Container\n \"\"\"\n\n # Child Component\n child_contact_number_text = Text(\n content_id=\"text_id\",\n title=\"+7 (727) 332-77-22\",\n options=Options(\n text_size=H3,\n text_style=BOLD,\n indent_outer=Indent(left=12, top=4, right=12, bottom=12),\n text_color=\"#A9ADB1\"\n )\n )\n\n # Child Component\n child_contact_title_text = Text(\n content_id=\"text_id\",\n title=\"Контактный телефон:\",\n options=Options(\n text_size=H4,\n indent_outer=Indent(left=12, top=2, right=12),\n text_color=\"#A9ADB1\"\n )\n )\n\n # Child Component\n child_divider = Divider(\n content_id=\"divider_id\",\n options=Options(\n indent_outer=Indent(left=12, top=14, right=12)\n )\n )\n\n # Child Component\n child_subtitle_text = Text(\n content_id=\"text_id\",\n title=\"eubank.kz\",\n options=Options(\n text_size=H4,\n alignment=RIGHT,\n indent_outer=Indent(left=12, top=2, right=12),\n text_color=\"#0075EB\"\n ),\n form_action=FormAction(action=\"open_url\",\n data_template=\"https://eubank.kz\")\n )\n\n # Child Component\n child_title_text = Text(\n content_id=\"text_cat_id\",\n title=\"Евразийский банк\",\n options=Options(\n text_size=H3,\n text_style=BOLD,\n indent_outer=Indent(left=12, top=12, right=12),\n )\n )\n\n # Child Component\n file = await bot.upload_file(\"images/cat.jpg\")\n child_image = Image(\n content_id=\"image_id\",\n options=Options(width=37, height=6,\n flex_options=FlexOptions(align_self=\"center\")),\n file_metadata=FileMetadata(\n file_id=file.get(UPLOADED_FILES)[0][\"fileId\"],\n file_type=\"image\",\n file_name=file.get(UPLOADED_FILES)[0][\"fileName\"]\n )\n )\n\n # Child Container\n child_custom_container = CustomContainer(\n content_id=\"child_id_1\",\n options=Options(width=62, height=16,\n flex_options=FlexOptions(flex_direction=\"column\", align_items=\"center\"),\n background_color=\"#2B296D\"),\n content=[child_image]\n )\n\n # Parent Container\n parent_custom_container = CustomContainer(\n content_id=\"parent_id\",\n options=Options(width=62, flex_options=FlexOptions(flex_direction=\"column\", align_items=\"start\")),\n content=[child_custom_container, child_title_text, child_subtitle_text, child_divider, child_contact_title_text,\n child_contact_number_text]\n )\n\n # Main Container\n main_custom_container = CustomContainer(\n content_id=\"main_id\",\n options=Options(indent_outer=Indent(left=16, right=16, top=8, bottom=8), background=\"card\"),\n content=[parent_custom_container]\n )\n\n content = [main_custom_container, main_custom_container, main_custom_container]\n\n await bot.send_container_message(message.chat.id, content=content)\n\n\n@dispatcher.form_submitted_handler()\nasync def handle_submission(submitted_form: FormSubmitted):\n await bot.send_message(\n submitted_form.chat.id,\n f\"Oh, it seems I have received text from you, look:\\n\\\"{submitted_form.metadata}\\\"\"\n )\n\n\n@dispatcher.form_closed_handler()\nasync def handle_form_closing(closed_form: FormClosed):\n await bot.send_message(closed_form.chat.id, \"Form is closed\")\n\n\nif __name__ == '__main__':\n executor.start_polling(dispatcher)\n","sub_path":"examples/send_container_message_bot.py","file_name":"send_container_message_bot.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"267059428","text":"\"\"\"\nThis module represents a device.\n\nComputer Systems Architecture Course\nAssignment 1\nMarch 2018\n\"\"\"\n\nfrom threading import Event, Thread, Lock, Condition\n\n\nclass ReusableBarrierCond(object):\n \"\"\"\n Class that represents a reusable barrier\n and is imported from the third lab.\n \"\"\"\n def __init__(self, num_threads):\n \"\"\"\n Constructor.\n\n @type num_threads: Integer\n @param num_threads: The number of threads for barrier\n\n @type count_threads: Integer\n @param count_threads: A variable that counts how\n many threads have arrieved at barrier\n\n @type cond: Condition\n @param cond: Does the synchronization\n \"\"\"\n self.num_threads = num_threads\n self.count_threads = self.num_threads\n self.cond = Condition()\n\n def wait(self):\n \"\"\"\n Wait method.\n \"\"\"\n self.cond.acquire()\n self.count_threads -= 1\n if self.count_threads == 0:\n self.cond.notify_all()\n self.count_threads = self.num_threads\n else:\n self.cond.wait()\n self.cond.release()\n\nclass Device(object):\n \"\"\"\n Class that represents a device.\n \"\"\"\n\n def __init__(self, device_id, sensor_data, supervisor):\n \"\"\"\n Constructor.\n\n @type device_id: Integer\n @param device_id: the unique id of this node; between 0 and N-1\n\n @type sensor_data: List of (Integer, Float)\n @param sensor_data: a list containing (location, data) as measured by this device\n\n @type supervisor: Supervisor\n @param supervisor: the testing infrastructure's control and validation component\n\n @type scripts: List of (script, Integer)\n @param scripts: a list containing (script, location)\n\n @type timepoint_done: Event\n @param timepoint_done: an event that let me know when it\n comes to another timepoint\n\n @type thread: DeviceThread\n @param thread: a thread which manage the work of MyThreads\n\n @type location_lock: Dictionary {Integer : Lock}\n @param location_lock: a dictionary which contains a lock foreach location\n\n @type barrier: ReusableBarrierCond\n @param barrier: a barrier which help me to synchronize the devices\n \"\"\"\n\n self.device_id = device_id\n self.sensor_data = sensor_data\n self.supervisor = supervisor\n self.scripts = []\n self.timepoint_done = Event()\n self.thread = None\n self.location_lock = {}\n self.barrier = None\n\n def __str__(self):\n \"\"\"\n Pretty prints this device.\n\n @rtype: String\n @return: a string containing the id of this device\n \"\"\"\n\n return \"Device %d\" % self.device_id\n\n def setup_devices(self, devices):\n \"\"\"\n Setup the devices before simulation begins.\n\n @type devices: List of Device\n @param devices: list containing all devices\n \"\"\"\n # Create a list with all device_id.\n id_list = []\n for device in devices:\n id_list.append(device.device_id)\n # Find the smallest device_id.\n id_leader = min(id_list)\n\n # Only device with the smallest id will execute the following sequence.\n if self.device_id == id_leader:\n # Create a reusable barrier for synchronize devices.\n barrier = ReusableBarrierCond(len(devices))\n # Each device will share the same barrier.\n # Each device will have a DeviceThread which\n # will start more MyThread.\n for device in devices:\n device.barrier = barrier\n device.thread = DeviceThread(device)\n device.thread.start()\n # Create the dictionary {location:lock}.\n location_list = []\n location_dict = {}\n for device in devices:\n for location in device.sensor_data:\n if location not in location_list:\n location_list.append(location)\n for location in location_list:\n lock = Lock()\n location_dict[location] = lock\n # Each device will share the same dictionary.\n for device in devices:\n device.location_lock = location_dict\n\n def assign_script(self, script, location):\n \"\"\"\n Provide a script for the device to execute.\n\n @type script: Script\n @param script: the script to execute from now on at each timepoint; None if the\n current timepoint has ended\n\n @type location: Integer\n @param location: the location for which the script is interested in\n \"\"\"\n if script is not None:\n self.scripts.append((script, location))\n else:\n self.timepoint_done.set()\n\n def get_data(self, location):\n \"\"\"\n Returns the pollution value this device has for the given location.\n\n @type location: Integer\n @param location: a location for which obtain the data\n\n @rtype: Float\n @return: the pollution value\n \"\"\"\n\n return self.sensor_data[location] if location in self.sensor_data else None\n\n def set_data(self, location, data):\n \"\"\"\n Sets the pollution value stored by this device for the given location.\n\n @type location: Integer\n @param location: a location for which to set the data\n\n @type data: Float\n @param data: the pollution value\n \"\"\"\n\n if location in self.sensor_data:\n self.sensor_data[location] = data\n\n def shutdown(self):\n \"\"\"\n Instructs the device to shutdown (terminate all threads). This method\n is invoked by the tester. This method must block until all the threads\n started by this device terminate.\n \"\"\"\n self.thread.join()\n\n\nclass DeviceThread(Thread):\n \"\"\"\n Class that implements the device's Master thread.\n \"\"\"\n\n def __init__(self, device):\n \"\"\"\n Constructor.\n\n @type device: Device\n @param device: the device which owns this Marster Thread\n \"\"\"\n Thread.__init__(self, name=\"Device Thread %d\" % device.device_id)\n self.device = device\n\n def run(self):\n\n while True:\n # Get the current neighbourhood.\n neighbours = self.device.supervisor.get_neighbours()\n\n if neighbours is None:\n break\n # Wait until device receive a None script.\n self.device.timepoint_done.wait()\n self.device.timepoint_done.clear()\n\n # Create a list of 8 Worker Threads(MyThread).\n threads = []\n for i in range(8):\n scripts_list = {}\n aux = i\n # Create a dictionary of {location : scripts} for each\n # Worker Thread.\n while aux < len(self.device.scripts):\n (script, location) = self.device.scripts[aux]\n scripts_list[location] = script\n aux += 8\n thread = MyThread(self.device, scripts_list, neighbours)\n threads.append(thread)\n # Stats and wait the threads.\n for i in range(8):\n threads[i].start()\n for i in range(8):\n threads[i].join()\n # Wait until all device will arrieve here.\n self.device.barrier.wait()\n\n\nclass MyThread(Thread):\n \"\"\"\n Class that implements the device's Worker thread.\n \"\"\"\n\n def __init__(self, device, scripts_list, neighbours):\n \"\"\"\n Constructor.\n\n @type device: Device\n @param device: the device which owns this Worker thread\n\n @type scripts_list: dictionary {Integer: script}\n @param scripts_list: a disctionary {location:script} which represents\n all scripts that worker thread must to resolve\n\n @type neighbours: List of Device\n @param neighbours: a list of all device in the neighbourhood\n \"\"\"\n Thread.__init__(self, name=\"Device Thread %d\" % device.device_id)\n self.device = device\n self.scripts_list = scripts_list\n self.neighbours = neighbours\n\n def run(self):\n # For each location from dictionary\n for location in self.scripts_list:\n script_data = []\n # Collect data from current neighbours\n # Make acquire for that location.\n self.device.location_lock[location].acquire()\n for dev in self.neighbours:\n data = dev.get_data(location)\n if data is not None:\n script_data.append(data)\n # Add our data, if any.\n data = self.device.get_data(location)\n if data is not None:\n script_data.append(data)\n\n if script_data != []:\n # Run script on data.\n result = self.scripts_list[location].run(script_data)\n\n # Update data of neighbours.\n for dev in self.neighbours:\n dev.set_data(location, result)\n # Update our data.\n self.device.set_data(location, result)\n # Make release for that location.\n self.device.location_lock[location].release()\n","sub_path":"Third Year/Computer Architecture/Homework 1/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"247837526","text":"from toontown.coghq.SpecImports import *\nimport random\nGlobalEntities = {1000: {'type': 'levelMgr',\n 'name': 'LevelMgr',\n 'comment': '',\n 'parentEntId': 0,\n 'cogLevel': 0,\n 'farPlaneDistance': 1500,\n 'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone22a',\n 'wantDoors': 1},\n 1001: {'type': 'editMgr',\n 'name': 'EditMgr',\n 'parentEntId': 0,\n 'insertEntity': None,\n 'removeEntity': None,\n 'requestNewEntity': None,\n 'requestSave': None},\n 0: {'type': 'zone',\n 'name': 'UberZone',\n 'comment': '',\n 'parentEntId': 0,\n 'scale': 1,\n 'description': '',\n 'visibility': []},\n 100030: {'type': 'battleBlocker',\n 'name': '',\n 'comment': '',\n 'parentEntId': 0,\n 'pos': Point3(-0.124318, -27.1644, 0),\n 'hpr': Vec3(0, 0, 0),\n 'scale': Vec3(1, 1, 1),\n 'cellId': 0,\n 'radius': 25.0},\n 100000: {'type': 'elevatorMarker',\n 'name': '',\n 'comment': '',\n 'parentEntId': 0,\n 'pos': Point3(0.199988, -31.3479, 0),\n 'hpr': Vec3(180, 0, 0),\n 'scale': Point3(1, 1, 1),\n 'modelPath': 0},\n 100001: {'type': 'model',\n 'name': '',\n 'comment': '',\n 'parentEntId': 0,\n 'pos': Point3(0, -30.3883, 13.5561),\n 'hpr': Vec3(180, 0, 0),\n 'scale': Vec3(2.6262, 2.6262, 2.6262),\n 'collisionsOnly': 0,\n 'flattenType': 'light',\n 'loadType': 'loadModelCopy',\n 'modelPath': 'phase_11/models/lawbotHQ/LB_bookshelfB'},\n 10000: {'type': 'nodepath',\n 'name': 'cogs',\n 'comment': '',\n 'parentEntId': 0,\n 'pos': Point3(0, 0, 0),\n 'hpr': Vec3(180, 0, 0),\n 'scale': 1}}\nScenario0 = {}\nlevelSpec = {'globalEntities': GlobalEntities,\n 'scenarios': [Scenario0],\n 'titleString': 'MemTag: LawbotOfficeOilRoom_Battle00 %s' % random.random()}\n","sub_path":"toontown/coghq/LawbotOfficeOilRoom_Battle00.py","file_name":"LawbotOfficeOilRoom_Battle00.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"631579921","text":"from django.test import TestCase\nfrom random import randint\nfrom faker import Factory\nfrom .models import Bookmarklet, Category, Vote, User, Comment\nimport methods\nimport templatetags.decoder\n\n\nclass TestVotes(TestCase):\n def setUp(self):\n self.user = create_user('t', 'ah')\n self.user.save()\n c = Category.objects.create(\n name='c'\n )\n self.b = Bookmarklet.objects.create(\n name='test',\n source='http://dfg',\n content='adfgd',\n user=self.user,\n description='desc',\n )\n self.b.categories.add(c)\n self.b.save()\n\n def test_vote(self):\n u1 = create_user('a', 'b')\n u2 = create_user('f', 'b')\n u3 = create_user('g', 'b')\n u4 = create_user('c', 'b')\n Vote.objects.create(user=u1, bookmarklet=self.b, rating=4)\n Vote.objects.create(user=u2, bookmarklet=self.b, rating=2)\n Vote.objects.create(user=u3, bookmarklet=self.b, rating=1)\n Vote.objects.create(user=u4, bookmarklet=self.b, rating=4)\n self.assertEqual(methods.get_review_avg(1), 2.75)\n\n def test_lot_votes(self):\n self.create_lot_votes(2000)\n\n def create_lot_votes(self, qty):\n # need to profile avg method..\n faker = Factory.create()\n\n for i in range(qty):\n username = faker.user_name() + str(randint(0, qty))\n user = create_user(name=username, passwd='p')\n Vote.objects.create(user=user, bookmarklet=self.b, rating=randint(0, 5))\n self.b.avg_rating = methods.get_review_avg(1)\n self.b.save()\n self.assertGreater(self.b.avg_rating, 0)\n\n\nclass TestCategories(TestCase):\n def test_two_categories(self):\n self.user = create_user('t', 'ah')\n self.user.save()\n c = Category.objects.create(name='c')\n c1 = Category.objects.create(name='c1')\n self.b = Bookmarklet.objects.create(\n name='test',\n source='http://dfg',\n content='adfgd',\n user=self.user,\n description='desc',\n )\n self.b.categories.add(c)\n self.b.categories.add(c1)\n self.b.save()\n self.assertEqual(c, self.b.categories.get(pk=1))\n self.assertEqual(c1, self.b.categories.get(pk=2))\n\n\nclass TestComments(TestCase):\n def setUp(self):\n self.user = create_user('t', 'ah')\n self.user.save()\n c = Category(\n name='c'\n )\n c.save()\n self.b = Bookmarklet.objects.create(\n name='test',\n source='http://dfg',\n content='adfgd',\n user=self.user,\n description='desc',\n )\n self.b.categories.add(c)\n self.b.save()\n\n def test_comment(self):\n comm = Comment.objects.create(\n text=\"my comment!\",\n user=self.user,\n bookmarklet=self.b\n )\n self.assertEqual(comm.text,self.b.comment_set.get(pk=1).text)\n\n\n def test_top_bookmarklets(self):\n for i in range(0, 12):\n self.create_bookmarklet()\n allb = Bookmarklet.objects.all()\n self.assertEqual(13, len(allb))\n qs = Bookmarklet.objects.order_by('avg_rating')[:10]\n self.assertEqual(10, len(qs))\n\n def create_bookmarklet(self):\n faker = Factory.create()\n return Bookmarklet.objects.create(\n name=faker.name(),\n source='http://www.test.com',\n content='not used',\n user=self.user,\n description='desc',\n avg_rating=randint(1, 5),\n )\n\n\ndef create_user(name, passwd):\n return User.objects.create(username=name, password=passwd)\n\n\nclass TestDecoder(TestCase):\n def test_with_js(self):\n value = 'data:text/html,%20